diff --git a/.gitattributes b/.gitattributes deleted file mode 100644 index 6eb3a078e..000000000 --- a/.gitattributes +++ /dev/null @@ -1,4 +0,0 @@ -# Set the default behavior, in case people don't have core.autocrlf set. -* text=auto - -*.go eol=lf diff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.md index 8b5d6a1c9..89aaf8097 100644 --- a/.github/CONTRIBUTING.md +++ b/.github/CONTRIBUTING.md @@ -37,6 +37,7 @@ The current list of HashiCorp Providers is as follows: * `aws` * `azurerm` * `google` + * `opc` Our testing standards are the same for both HashiCorp and Community providers, and HashiCorp runs full acceptance test suites for every provider nightly to @@ -201,6 +202,9 @@ Implementing a new resource is a good way to learn more about how Terraform interacts with upstream APIs. There are plenty of examples to draw from in the existing resources, but you still get to implement something completely new. + - [ ] __Minimal LOC__: It can be inefficient for both the reviewer + and author to go through long feedback cycles on a big PR with many + resources. We therefore encourage you to only submit **1 resource at a time**. - [ ] __Acceptance tests__: New resources should include acceptance tests covering their behavior. See [Writing Acceptance Tests](#writing-acceptance-tests) below for a detailed guide on how to @@ -223,6 +227,11 @@ Implementing a new provider gives Terraform the ability to manage resources in a whole new API. It's a larger undertaking, but brings major new functionality into Terraform. + - [ ] __Minimal initial LOC__: Some providers may be big and it can be + inefficient for both reviewer & author to go through long feedback cycles + on a big PR with many resources. We encourage you to only submit + the necessary minimum in a single PR, ideally **just the first resource** + of the provider. - [ ] __Acceptance tests__: Each provider should include an acceptance test suite with tests for each resource should include acceptance tests covering its behavior. See [Writing Acceptance Tests](#writing-acceptance-tests) below diff --git a/.travis.yml b/.travis.yml index 04cc6f309..411407aa9 100644 --- a/.travis.yml +++ b/.travis.yml @@ -2,7 +2,7 @@ dist: trusty sudo: false language: go go: -- 1.8 +- 1.8.1 # add TF_CONSUL_TEST=1 to run consul tests # they were causing timouts in travis @@ -39,4 +39,4 @@ notifications: matrix: fast_finish: true allow_failures: - - go: tip + - go: tip \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index fb7432532..8fb2e3152 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,13 +1,402 @@ -## 0.9.3 (unreleased) +## 0.9.6 (Unreleased) + +BACKWARDS INCOMPATIBILITIES / NOTES: + +* provider/google: Users of `google_compute_health_check` who were not setting a value for the `host` property of `http_health_check` or `https_health_check` previously had a faulty default value. This has been fixed and will show as a change in terraform plan/apply. [GH-14441] + +FEATURES: + +* **New Provider:** `OVH` [GH-12669] +* **New Resource:** `aws_default_subnet` [GH-14476] +* **New Resource:** `aws_default_vpc_dhcp_options` [GH-14475] +* **New Resource:** `aws_devicefarm_project` [GH-14288] +* **New Resource:** `aws_wafregion_ipset` [GH-13705] +* **New Resource:** `aws_wafregion_byte_match_set` [GH-13705] +* **New Resource:** `azurerm_express_route_circuit` [GH-14265] +* **New Data Source:** `aws_db_snapshot` [GH-10291] IMPROVEMENTS: - - * provider/aws: Add support to set iam_role_arn on cloudformation Stack [GH-12547] +* core/provider-split: Split out the Oracle OPC provider to new structure [GH-14362] +* provider/aws: Show state reason when EC2 instance fails to launch [GH-14479] +* provider/aws: Show last scaling activity when ASG creation/update fails [GH-14480] +* provider/aws: Add `tags` (list of maps) for `aws_autoscaling_group` [GH-13574] +* provider/azurerm: Virtual Machine Scale Sets with managed disk support [GH-13717] +* provider/azurerm: Virtual Machine Scale Sets with single placement option support [GH-14510] +* provider/datadog: Add last aggregator to datadog_timeboard resource [GH-14391] +* provider/datadog: Added new evaluation_delay parameter [GH-14433] +* provider/docker: Allow Windows Docker containers to map volumes [GH-13584] +* provider/google: Add a `url` attribute to `google_storage_bucket` [GH-14393] +* provider/google: Make google resource storage bucket importable [GH-14455] +* provider/heroku: Add import ability for `heroku_pipeline` resource [GH-14486] +* provider/openstack: Add support for all protocols in Security Group Rules [GH-14307] +* provider/rundeck: adds `description` to `command` schema in `rundeck_job` resource [GH-14352] +* provider/scaleway: allow public_ip to be set on server resource [GH-14515] + +BUG FIXES: + +* core: When using `-target`, any outputs that include attributes of the targeted resources are now updated [GH-14186] +* core: Fixed 0.9.5 regression with the conditional operator `.. ? .. : ..` failing to type check with unknown/computed values [GH-14454] +* core: Fixed 0.9 regression causing issues during refresh when adding new data resource instances using `count` [GH-14098] +* core: Fixed crasher when populating a "splat variable" from an empty (nil) module state. [GH-14526] +* provider/aws: Increase EIP update timeout [GH-14381] +* provider/aws: Increase timeout for creating security group [GH-14380] +* provider/aws: Increase timeout for (dis)associating IPv6 addr to subnet [GH-14401] +* provider/aws: Using the new time schema helper for RDS Instance lifecycle mgmt [GH-14369] +* provider/aws: Using the timeout schema helper to make alb timeout cofigurable [GH-14375] +* provider/aws: Refresh from state when CodePipeline Not Found [GH-14431] +* provider/aws: Override spot_instance_requests volume_tags schema [GH-14481] +* provider/aws: Allow Internet Gateway IPv6 routes [GH-14484] +* provider/aws: ForceNew aws_launch_config when root_block_device changes [GH-14507] +* provider/aws: Pass IAM Roles to codepipeline actions [GH-14263] +* provider/aws: Create rule(s) for prefix-list-only AWS security group permissions on 'terraform import' [GH-14528] +* provider/aws: Set aws_subnet ipv6_cidr_block to computed [GH-14542] +* provider/cloudstack: `cloudstack_firewall` panicked when used with older (< v4.6) CloudStack versions [GH-14044] +* provider/datadog: Allowed method on aggregator is `avg` ! `average` [GH-14414] +* provider/digitalocean: Fix parsing of digitalocean dns records [GH-14215] +* provider/github: Log HTTP requests and responses in DEBUG mode [GH-14363] +* provider/google: Fix health check http/https defaults [GH-14441] +* provider/heroku: Fix issue with setting correct CName in heroku_domain [GH-14443] +* provider/opc: Correctly export `ip_address` in IP Addr Reservation [GH-14543] +* provider/openstack: Handle Deleted Resources in Floating IP Association [GH-14533] +* provider/vault: Prevent panic when no secret found [GH-14435] + +## 0.9.5 (May 11, 2017) + +BACKWARDS INCOMPATIBILITIES / NOTES: + +* provider/aws: Users of aws_cloudfront_distributions with custom_origins have been broken due to changes in the AWS API requiring `OriginReadTimeout` being set for updates. This has been fixed and will show as a change in terraform plan / apply. ([#13367](https://github.com/hashicorp/terraform/issues/13367)) +* provider/aws: Users of China and Gov clouds, cannot use the new tagging of volumes created as part of aws_instances ([#14055](https://github.com/hashicorp/terraform/issues/14055)) +* provider/aws: Skip tag operations on cloudwatch logs in govcloud partition. Currently not supported by Amazon. ([#12414](https://github.com/hashicorp/terraform/issues/12414)) +* provider/aws: More consistent (un)quoting of long TXT/SPF `aws_route53_record`s. + Previously we were trimming first 2 quotes and now we're (correctly) trimming first and last one. + Depending on the use of quotes in your TXT/SPF records this may result in extra diff in plan/apply ([#14170](https://github.com/hashicorp/terraform/issues/14170)) + +FEATURES: + +* **New Provider:** `gitlab` ([#13898](https://github.com/hashicorp/terraform/issues/13898)) +* **New Resource:** `aws_emr_security_configuration` ([#14080](https://github.com/hashicorp/terraform/issues/14080)) +* **New Resource:** `aws_ssm_maintenance_window` ([#14087](https://github.com/hashicorp/terraform/issues/14087)) +* **New Resource:** `aws_ssm_maintenance_window_target` ([#14087](https://github.com/hashicorp/terraform/issues/14087)) +* **New Resource:** `aws_ssm_maintenance_window_task` ([#14087](https://github.com/hashicorp/terraform/issues/14087)) +* **New Resource:** `azurerm_sql_elasticpool` ([#14099](https://github.com/hashicorp/terraform/issues/14099)) +* **New Resource:** `google_bigquery_table` ([#13743](https://github.com/hashicorp/terraform/issues/13743)) +* **New Resource:** `google_compute_backend_bucket` ([#14015](https://github.com/hashicorp/terraform/issues/14015)) +* **New Resource:** `google_compute_snapshot` ([#12482](https://github.com/hashicorp/terraform/issues/12482)) +* **New Resource:** `heroku_app_feature` ([#14035](https://github.com/hashicorp/terraform/issues/14035)) +* **New Resource:** `heroku_pipeline` ([#14078](https://github.com/hashicorp/terraform/issues/14078)) +* **New Resource:** `heroku_pipeline_coupling` ([#14078](https://github.com/hashicorp/terraform/issues/14078)) +* **New Resource:** `kubernetes_limit_range` ([#14285](https://github.com/hashicorp/terraform/issues/14285)) +* **New Resource:** `kubernetes_resource_quota` ([#13914](https://github.com/hashicorp/terraform/issues/13914)) +* **New Resource:** `vault_auth_backend` ([#10988](https://github.com/hashicorp/terraform/issues/10988)) +* **New Data Source:** `aws_efs_file_system` ([#14041](https://github.com/hashicorp/terraform/issues/14041)) +* **New Data Source:** `http`, for retrieving text data from generic HTTP servers ([#14270](https://github.com/hashicorp/terraform/issues/14270)) +* **New Data Source:** `google_container_engine_versions`, for retrieving valid versions for clusters ([#14280](https://github.com/hashicorp/terraform/issues/14280)) +* **New Interpolation Function:** `log`, for computing logarithms ([#12872](https://github.com/hashicorp/terraform/issues/12872)) + +IMPROVEMENTS: + +* core: `sha512` and `base64sha512` interpolation functions, similar to their `sha256` equivalents. ([#14100](https://github.com/hashicorp/terraform/issues/14100)) +* core: It's now possible to use the index operator `[ ]` to select a known value out of a partially-known list, such as using "splat syntax" and increasing the `count`. ([#14135](https://github.com/hashicorp/terraform/issues/14135)) +* provider/aws: Add support for CustomOrigin timeouts to aws_cloudfront_distribution ([#13367](https://github.com/hashicorp/terraform/issues/13367)) +* provider/aws: Add support for IAMDatabaseAuthenticationEnabled ([#14092](https://github.com/hashicorp/terraform/issues/14092)) +* provider/aws: aws_dynamodb_table Add support for TimeToLive ([#14104](https://github.com/hashicorp/terraform/issues/14104)) +* provider/aws: Add `security_configuration` support to `aws_emr_cluster` ([#14133](https://github.com/hashicorp/terraform/issues/14133)) +* provider/aws: Add support for the tenancy placement option in `aws_spot_fleet_request` ([#14163](https://github.com/hashicorp/terraform/issues/14163)) +* provider/aws: `aws_db_option_group` normalizes name to lowercase ([#14192](https://github.com/hashicorp/terraform/issues/14192), [#14366](https://github.com/hashicorp/terraform/issues/14366)) +* provider/aws: Add support description to aws_iam_role ([#14208](https://github.com/hashicorp/terraform/issues/14208)) +* provider/aws: Add support for SSM Documents to aws_cloudwatch_event_target ([#14067](https://github.com/hashicorp/terraform/issues/14067)) +* provider/aws: add additional custom service endpoint options for CloudFormation, KMS, RDS, SNS & SQS ([#14097](https://github.com/hashicorp/terraform/issues/14097)) +* provider/aws: Add ARN to security group data source ([#14245](https://github.com/hashicorp/terraform/issues/14245)) +* provider/aws: Improve the wording of DynamoDB Validation error message ([#14256](https://github.com/hashicorp/terraform/issues/14256)) +* provider/aws: Add support for importing Kinesis Streams ([#14278](https://github.com/hashicorp/terraform/issues/14278)) +* provider/aws: Add `arn` attribute to `aws_ses_domain_identity` resource ([#14306](https://github.com/hashicorp/terraform/issues/14306)) +* provider/aws: Add support for targets to aws_ssm_association ([#14246](https://github.com/hashicorp/terraform/issues/14246)) +* provider/aws: native redis clustering support for elasticache ([#14317](https://github.com/hashicorp/terraform/issues/14317)) +* provider/aws: Support updating `aws_waf_rule` predicates ([#14089](https://github.com/hashicorp/terraform/issues/14089)) +* provider/azurerm: `azurerm_template_deployment` now supports String/Int/Boolean outputs ([#13670](https://github.com/hashicorp/terraform/issues/13670)) +* provider/azurerm: Expose the Private IP Address for a Load Balancer, if available ([#13965](https://github.com/hashicorp/terraform/issues/13965)) +* provider/dns: Fix data dns txt record set ([#14271](https://github.com/hashicorp/terraform/issues/14271)) +* provider/dnsimple: Add support for import for dnsimple_records ([#9130](https://github.com/hashicorp/terraform/issues/9130)) +* provider/dyn: Add verbose Dyn provider logs ([#14076](https://github.com/hashicorp/terraform/issues/14076)) +* provider/google: Add support for networkIP in compute instance templates ([#13515](https://github.com/hashicorp/terraform/issues/13515)) +* provider/google: google_dns_managed_zone is now importable ([#13824](https://github.com/hashicorp/terraform/issues/13824)) +* provider/google: Add support for `compute_route` ([#14065](https://github.com/hashicorp/terraform/issues/14065)) +* provider/google: Add `path` to `google_pubsub_subscription` ([#14238](https://github.com/hashicorp/terraform/issues/14238)) +* provider/google: Improve Service Account by offering to recreate if missing ([#14282](https://github.com/hashicorp/terraform/issues/14282)) +* provider/google: Log HTTP requests and responses in DEBUG mode ([#14281](https://github.com/hashicorp/terraform/issues/14281)) +* provider/google: Add additional properties for google resource storage bucket object ([#14259](https://github.com/hashicorp/terraform/issues/14259)) +* provider/google: Handle all 404 checks in read functions via the new function ([#14335](https://github.com/hashicorp/terraform/issues/14335)) +* provider/heroku: import heroku_app resource ([#14248](https://github.com/hashicorp/terraform/issues/14248)) +* provider/nomad: Add TLS options ([#13956](https://github.com/hashicorp/terraform/issues/13956)) +* provider/triton: Add support for reading provider configuration from `TRITON_*` environment variables in addition to `SDC_*`([#14000](https://github.com/hashicorp/terraform/issues/14000)) +* provider/triton: Add `cloud_config` argument to `triton_machine` resources for Linux containers ([#12840](https://github.com/hashicorp/terraform/issues/12840)) +* provider/triton: Add `insecure_skip_tls_verify` ([#14077](https://github.com/hashicorp/terraform/issues/14077)) + +BUG FIXES: + +* core: `module` blocks without names are now caught in validation, along with various other block types ([#14162](https://github.com/hashicorp/terraform/issues/14162)) +* core: no longer will errors and normal log output get garbled together on Windows ([#14194](https://github.com/hashicorp/terraform/issues/14194)) +* core: Avoid crash on empty TypeSet blocks ([#14305](https://github.com/hashicorp/terraform/issues/14305)) +* provider/aws: Update aws_ebs_volume when attached ([#14005](https://github.com/hashicorp/terraform/issues/14005)) +* provider/aws: Set aws_instance volume_tags to be Computed ([#14007](https://github.com/hashicorp/terraform/issues/14007)) +* provider/aws: Fix issue getting partition for federated users ([#13992](https://github.com/hashicorp/terraform/issues/13992)) +* provider/aws: aws_spot_instance_request not forcenew on volume_tags ([#14046](https://github.com/hashicorp/terraform/issues/14046)) +* provider/aws: Exclude aws_instance volume tagging for China and Gov Clouds ([#14055](https://github.com/hashicorp/terraform/issues/14055)) +* provider/aws: Fix source_dest_check with network_interface ([#14079](https://github.com/hashicorp/terraform/issues/14079)) +* provider/aws: Fixes the bug where SNS delivery policy get always recreated ([#14064](https://github.com/hashicorp/terraform/issues/14064)) +* provider/aws: Increase timeouts for Route Table retries ([#14345](https://github.com/hashicorp/terraform/issues/14345)) +* provider/aws: Prevent Crash when importing aws_route53_record ([#14218](https://github.com/hashicorp/terraform/issues/14218)) +* provider/aws: More consistent (un)quoting of long TXT/SPF `aws_route53_record`s ([#14170](https://github.com/hashicorp/terraform/issues/14170)) +* provider/aws: Retry deletion of AWSConfig Rule on ResourceInUseException ([#14269](https://github.com/hashicorp/terraform/issues/14269)) +* provider/aws: Refresh ssm document from state on 404 ([#14279](https://github.com/hashicorp/terraform/issues/14279)) +* provider/aws: Allow zero-value ELB and ALB names ([#14304](https://github.com/hashicorp/terraform/issues/14304)) +* provider/aws: Update the ignoring of AWS specific tags ([#14321](https://github.com/hashicorp/terraform/issues/14321)) +* provider/aws: Adding IPv6 address to instance causes perpetual diff ([#14355](https://github.com/hashicorp/terraform/issues/14355)) +* provider/aws: Fix SG update on instance with multiple network interfaces ([#14299](https://github.com/hashicorp/terraform/issues/14299)) +* provider/azurerm: Fixing a bug in `azurerm_network_interface` ([#14365](https://github.com/hashicorp/terraform/issues/14365)) +* provider/digitalocean: Prevent diffs when using IDs of images instead of slugs ([#13879](https://github.com/hashicorp/terraform/issues/13879)) +* provider/fastly: Changes setting conditionals to optional ([#14103](https://github.com/hashicorp/terraform/issues/14103)) +* provider/google: Ignore certain project services that can't be enabled directly via the api ([#13730](https://github.com/hashicorp/terraform/issues/13730)) +* provider/google: Ability to add more than 25 project services ([#13758](https://github.com/hashicorp/terraform/issues/13758)) +* provider/google: Fix compute instance panic with bad disk config ([#14169](https://github.com/hashicorp/terraform/issues/14169)) +* provider/google: Handle `google_storage_bucket_object` not being found ([#14203](https://github.com/hashicorp/terraform/issues/14203)) +* provider/google: Handle `google_compute_instance_group_manager` not being found ([#14190](https://github.com/hashicorp/terraform/issues/14190)) +* provider/google: better visibility for compute_region_backend_service ([#14301](https://github.com/hashicorp/terraform/issues/14301)) +* provider/heroku: Configure buildpacks correctly for both Org Apps and non-org Apps ([#13990](https://github.com/hashicorp/terraform/issues/13990)) +* provider/heroku: Fix `heroku_cert` update of ssl cert ([#14240](https://github.com/hashicorp/terraform/issues/14240)) +* provider/openstack: Handle disassociating deleted FloatingIP's from a server ([#14210](https://github.com/hashicorp/terraform/issues/14210)) +* provider/postgres grant role when creating database ([#11452](https://github.com/hashicorp/terraform/issues/11452)) +* provider/triton: Make triton machine deletes synchronous. ([#14368](https://github.com/hashicorp/terraform/issues/14368)) +* provisioner/remote-exec: Fix panic from remote_exec provisioner ([#14134](https://github.com/hashicorp/terraform/issues/14134)) + +## 0.9.4 (26th April 2017) + +BACKWARDS INCOMPATIBILITIES / NOTES: + + * provider/template: Fix invalid MIME formatting in `template_cloudinit_config`. + While the change itself is not breaking the data source it may be referenced + e.g. in `aws_launch_configuration` and similar resources which are immutable + and the formatting change will therefore trigger recreation ([#13752](https://github.com/hashicorp/terraform/issues/13752)) + +FEATURES: + +* **New Provider:** `opc` - Oracle Public Cloud ([#13468](https://github.com/hashicorp/terraform/issues/13468)) +* **New Provider:** `oneandone` ([#13633](https://github.com/hashicorp/terraform/issues/13633)) +* **New Data Source:** `aws_ami_ids` ([#13844](https://github.com/hashicorp/terraform/issues/13844)] [[#13866](https://github.com/hashicorp/terraform/issues/13866)) +* **New Data Source:** `aws_ebs_snapshot_ids` ([#13844](https://github.com/hashicorp/terraform/issues/13844)] [[#13866](https://github.com/hashicorp/terraform/issues/13866)) +* **New Data Source:** `aws_kms_alias` ([#13669](https://github.com/hashicorp/terraform/issues/13669)) +* **New Data Source:** `aws_kinesis_stream` ([#13562](https://github.com/hashicorp/terraform/issues/13562)) +* **New Data Source:** `digitalocean_image` ([#13787](https://github.com/hashicorp/terraform/issues/13787)) +* **New Data Source:** `google_compute_network` ([#12442](https://github.com/hashicorp/terraform/issues/12442)) +* **New Data Source:** `google_compute_subnetwork` ([#12442](https://github.com/hashicorp/terraform/issues/12442)) +* **New Resource:** `local_file` for creating local files (please see the docs for caveats) ([#12757](https://github.com/hashicorp/terraform/issues/12757)) +* **New Resource:** `alicloud_ess_scalinggroup` ([#13731](https://github.com/hashicorp/terraform/issues/13731)) +* **New Resource:** `alicloud_ess_scalingconfiguration` ([#13731](https://github.com/hashicorp/terraform/issues/13731)) +* **New Resource:** `alicloud_ess_scalingrule` ([#13731](https://github.com/hashicorp/terraform/issues/13731)) +* **New Resource:** `alicloud_ess_schedule` ([#13731](https://github.com/hashicorp/terraform/issues/13731)) +* **New Resource:** `alicloud_snat_entry` ([#13731](https://github.com/hashicorp/terraform/issues/13731)) +* **New Resource:** `alicloud_forward_entry` ([#13731](https://github.com/hashicorp/terraform/issues/13731)) +* **New Resource:** `aws_cognito_identity_pool` ([#13783](https://github.com/hashicorp/terraform/issues/13783)) +* **New Resource:**  `aws_network_interface_attachment` ([#13861](https://github.com/hashicorp/terraform/issues/13861)) +* **New Resource:** `github_branch_protection` ([#10476](https://github.com/hashicorp/terraform/issues/10476)) +* **New Resource:** `google_bigquery_dataset` ([#13436](https://github.com/hashicorp/terraform/issues/13436)) +* **New Resource:** `heroku_space` ([#13921](https://github.com/hashicorp/terraform/issues/13921)) +* **New Resource:** `template_dir` for producing a directory from templates ([#13652](https://github.com/hashicorp/terraform/issues/13652)) +* **New Interpolation Function:** `coalescelist()` ([#12537](https://github.com/hashicorp/terraform/issues/12537)) + + +IMPROVEMENTS: + + * core: Add a `-reconfigure` flag to the `init` command, to configure a backend while ignoring any saved configuration ([#13825](https://github.com/hashicorp/terraform/issues/13825)) + * helper/schema: Disallow validation+diff suppression on computed fields ([#13878](https://github.com/hashicorp/terraform/issues/13878)) + * config: The interpolation function `cidrhost` now accepts a negative host number to count backwards from the end of the range ([#13765](https://github.com/hashicorp/terraform/issues/13765)) + * config: New interpolation function `matchkeys` for using values from one list to filter corresponding values from another list using a matching set. ([#13847](https://github.com/hashicorp/terraform/issues/13847)) + * state/remote/swift: Support Openstack request logging ([#13583](https://github.com/hashicorp/terraform/issues/13583)) + * provider/aws: Add an option to skip getting the supported EC2 platforms ([#13672](https://github.com/hashicorp/terraform/issues/13672)) + * provider/aws: Add `name_prefix` support to `aws_cloudwatch_log_group` ([#13273](https://github.com/hashicorp/terraform/issues/13273)) + * provider/aws: Add `bucket_prefix` to `aws_s3_bucket` ([#13274](https://github.com/hashicorp/terraform/issues/13274)) + * provider/aws: Add replica_source_db to the aws_db_instance datasource ([#13842](https://github.com/hashicorp/terraform/issues/13842)) + * provider/aws: Add IPv6 outputs to aws_subnet datasource ([#13841](https://github.com/hashicorp/terraform/issues/13841)) + * provider/aws: Exercise SecondaryPrivateIpAddressCount for network interface ([#10590](https://github.com/hashicorp/terraform/issues/10590)) + * provider/aws: Expose execution ARN + invoke URL for APIG deployment ([#13889](https://github.com/hashicorp/terraform/issues/13889)) + * provider/aws: Expose invoke ARN from Lambda function (for API Gateway) ([#13890](https://github.com/hashicorp/terraform/issues/13890)) + * provider/aws: Add tagging support to the 'aws_lambda_function' resource ([#13873](https://github.com/hashicorp/terraform/issues/13873)) + * provider/aws: Validate WAF metric names ([#13885](https://github.com/hashicorp/terraform/issues/13885)) + * provider/aws: Allow AWS Subnet to change IPv6 CIDR Block without ForceNew ([#13909](https://github.com/hashicorp/terraform/issues/13909)) + * provider/aws: Allow filtering of aws_subnet_ids by tags ([#13937](https://github.com/hashicorp/terraform/issues/13937)) + * provider/aws: Support aws_instance and volume tagging on creation ([#13945](https://github.com/hashicorp/terraform/issues/13945)) + * provider/aws: Add network_interface to aws_instance ([#12933](https://github.com/hashicorp/terraform/issues/12933)) + * provider/azurerm: VM Scale Sets - import support ([#13464](https://github.com/hashicorp/terraform/issues/13464)) + * provider/azurerm: Allow Azure China region support ([#13767](https://github.com/hashicorp/terraform/issues/13767)) + * provider/digitalocean: Export droplet prices ([#13720](https://github.com/hashicorp/terraform/issues/13720)) + * provider/fastly: Add support for GCS logging ([#13553](https://github.com/hashicorp/terraform/issues/13553)) + * provider/google: `google_compute_address` and `google_compute_global_address` are now importable ([#13270](https://github.com/hashicorp/terraform/issues/13270)) + * provider/google: `google_compute_network` is now importable ([#13834](https://github.com/hashicorp/terraform/issues/13834)) + * provider/google: add attached_disk field to google_compute_instance ([#13443](https://github.com/hashicorp/terraform/issues/13443)) + * provider/heroku: Set App buildpacks from config ([#13910](https://github.com/hashicorp/terraform/issues/13910)) + * provider/heroku: Create Heroku app in a private space ([#13862](https://github.com/hashicorp/terraform/issues/13862)) + * provider/vault: `vault_generic_secret` resource can now optionally detect drift if it has appropriate access ([#11776](https://github.com/hashicorp/terraform/issues/11776)) + +BUG FIXES: + + * core: Prevent resource.Retry from adding untracked resources after the timeout: ([#13778](https://github.com/hashicorp/terraform/issues/13778)) + * core: Allow a schema.TypeList to be ForceNew and computed ([#13863](https://github.com/hashicorp/terraform/issues/13863)) + * core: Fix crash when refresh or apply build an invalid graph ([#13665](https://github.com/hashicorp/terraform/issues/13665)) + * core: Add the close provider/provisioner transformers back ([#13102](https://github.com/hashicorp/terraform/issues/13102)) + * core: Fix a crash condition by improving the flatmap.Expand() logic ([#13541](https://github.com/hashicorp/terraform/issues/13541)) + * provider/alicloud: Fix create PrePaid instance ([#13662](https://github.com/hashicorp/terraform/issues/13662)) + * provider/alicloud: Fix allocate public ip error ([#13268](https://github.com/hashicorp/terraform/issues/13268)) + * provider/alicloud: alicloud_security_group_rule: check ptr before use it [[#13731](https://github.com/hashicorp/terraform/issues/13731)) + * provider/alicloud: alicloud_instance: fix ecs internet_max_bandwidth_out cannot set zero bug ([#13731](https://github.com/hashicorp/terraform/issues/13731)) + * provider/aws: Allow force-destroying `aws_route53_zone` which has trailing dot ([#12421](https://github.com/hashicorp/terraform/issues/12421)) + * provider/aws: Allow GovCloud KMS ARNs to pass validation in `kms_key_id` attributes ([#13699](https://github.com/hashicorp/terraform/issues/13699)) + * provider/aws: Changing aws_opsworks_instance should ForceNew ([#13839](https://github.com/hashicorp/terraform/issues/13839)) + * provider/aws: Fix DB Parameter Group Name ([#13279](https://github.com/hashicorp/terraform/issues/13279)) + * provider/aws: Fix issue importing some Security Groups and Rules based on rule structure ([#13630](https://github.com/hashicorp/terraform/issues/13630)) + * provider/aws: Fix issue for cross account IAM role with `aws_lambda_permission` ([#13865](https://github.com/hashicorp/terraform/issues/13865)) + * provider/aws: Fix WAF IPSet descriptors removal on update ([#13766](https://github.com/hashicorp/terraform/issues/13766)) + * provider/aws: Increase default number of retries from 11 to 25 ([#13673](https://github.com/hashicorp/terraform/issues/13673)) + * provider/aws: Remove aws_vpc_dhcp_options if not found ([#13610](https://github.com/hashicorp/terraform/issues/13610)) + * provider/aws: Remove aws_network_acl_rule if not found ([#13608](https://github.com/hashicorp/terraform/issues/13608)) + * provider/aws: Use mutex & retry for WAF change operations ([#13656](https://github.com/hashicorp/terraform/issues/13656)) + * provider/aws: Adding support for ipv6 to aws_subnets needs migration ([#13876](https://github.com/hashicorp/terraform/issues/13876)) + * provider/aws: Fix validation of the `name_prefix` parameter of the `aws_alb` resource ([#13441](https://github.com/hashicorp/terraform/issues/13441)) + * provider/azurerm: azurerm_redis_cache resource missing hostname ([#13650](https://github.com/hashicorp/terraform/issues/13650)) + * provider/azurerm: Locking around Network Security Group / Subnets ([#13637](https://github.com/hashicorp/terraform/issues/13637)) + * provider/azurerm: Locking route table on subnet create/delete ([#13791](https://github.com/hashicorp/terraform/issues/13791)) + * provider/azurerm: VM's - fixes a bug where ssh_keys could contain a null entry ([#13755](https://github.com/hashicorp/terraform/issues/13755)) + * provider/azurerm: VM's - ignoring the case on the `create_option` field during Diff's ([#13933](https://github.com/hashicorp/terraform/issues/13933)) + * provider/azurerm: fixing a bug refreshing the `azurerm_redis_cache` ([#13899](https://github.com/hashicorp/terraform/issues/13899)) + * provider/fastly: Fix issue with using 0 for `default_ttl` ([#13648](https://github.com/hashicorp/terraform/issues/13648)) + * provider/google: Fix panic in GKE provisioning with addons ([#13954](https://github.com/hashicorp/terraform/issues/13954)) + * provider/fastly: Add ability to associate a healthcheck to a backend ([#13539](https://github.com/hashicorp/terraform/issues/13539)) + * provider/google: Stop setting the id when project creation fails ([#13644](https://github.com/hashicorp/terraform/issues/13644)) + * provider/google: Make ports in resource_compute_forwarding_rule ForceNew ([#13833](https://github.com/hashicorp/terraform/issues/13833)) + * provider/google: Validation fixes for forwarding rules ([#13952](https://github.com/hashicorp/terraform/issues/13952)) + * provider/ignition: Internal cache moved to global, instead per provider instance ([#13919](https://github.com/hashicorp/terraform/issues/13919)) + * provider/logentries: Refresh from state when resources not found ([#13810](https://github.com/hashicorp/terraform/issues/13810)) + * provider/newrelic: newrelic_alert_condition - `condition_scope` must be `application` or `instance` ([#12972](https://github.com/hashicorp/terraform/issues/12972)) + * provider/opc: fixed issue with unqualifying nats ([#13826](https://github.com/hashicorp/terraform/issues/13826)) + * provider/opc: Fix instance label if unset ([#13846](https://github.com/hashicorp/terraform/issues/13846)) + * provider/openstack: Fix updating Ports ([#13604](https://github.com/hashicorp/terraform/issues/13604)) + * provider/rabbitmq: Allow users without tags ([#13798](https://github.com/hashicorp/terraform/issues/13798)) + +## 0.9.3 (April 12, 2017) + +BACKWARDS INCOMPATIBILITIES / NOTES: + * provider/aws: Fix a critical bug in `aws_emr_cluster` in order to preserve the ordering + of any arguments in `bootstrap_action`. Terraform will now enforce the ordering + from the configuration. As a result, `aws_emr_cluster` resources may need to be + recreated, as there is no API to update them in-place ([#13580](https://github.com/hashicorp/terraform/issues/13580)) + +FEATURES: + + * **New Resource:** `aws_api_gateway_method_settings` ([#13542](https://github.com/hashicorp/terraform/issues/13542)) + * **New Resource:** `aws_api_gateway_stage` ([#13540](https://github.com/hashicorp/terraform/issues/13540)) + * **New Resource:** `aws_iam_openid_connect_provider` ([#13456](https://github.com/hashicorp/terraform/issues/13456)) + * **New Resource:** `aws_lightsail_static_ip` ([#13175](https://github.com/hashicorp/terraform/issues/13175)) + * **New Resource:** `aws_lightsail_static_ip_attachment` ([#13207](https://github.com/hashicorp/terraform/issues/13207)) + * **New Resource:** `aws_ses_domain_identity` ([#13098](https://github.com/hashicorp/terraform/issues/13098)) + * **New Resource:** `azurerm_managed_disk` ([#12455](https://github.com/hashicorp/terraform/issues/12455)) + * **New Resource:** `kubernetes_persistent_volume` ([#13277](https://github.com/hashicorp/terraform/issues/13277)) + * **New Resource:** `kubernetes_persistent_volume_claim` ([#13527](https://github.com/hashicorp/terraform/issues/13527)) + * **New Resource:** `kubernetes_secret` ([#12960](https://github.com/hashicorp/terraform/issues/12960)) + * **New Data Source:** `aws_iam_role` ([#13213](https://github.com/hashicorp/terraform/issues/13213)) + +IMPROVEMENTS: + + * core: add `-lock-timeout` option, which will block and retry locks for the given duration ([#13262](https://github.com/hashicorp/terraform/issues/13262)) + * core: new `chomp` interpolation function which returns the given string with any trailing newline characters removed ([#13419](https://github.com/hashicorp/terraform/issues/13419)) + * backend/remote-state: Add support for assume role extensions to s3 backend ([#13236](https://github.com/hashicorp/terraform/issues/13236)) + * backend/remote-state: Filter extra entries from s3 environment listings ([#13596](https://github.com/hashicorp/terraform/issues/13596)) + * config: New interpolation functions `basename` and `dirname`, for file path manipulation ([#13080](https://github.com/hashicorp/terraform/issues/13080)) + * helper/resource: Allow unknown "pending" states ([#13099](https://github.com/hashicorp/terraform/issues/13099)) + * command/hook_ui: Increase max length of state IDs from 20 to 80 ([#13317](https://github.com/hashicorp/terraform/issues/13317)) + * provider/aws: Add support to set iam_role_arn on cloudformation Stack ([#12547](https://github.com/hashicorp/terraform/issues/12547)) + * provider/aws: Support priority and listener_arn update of alb_listener_rule ([#13125](https://github.com/hashicorp/terraform/issues/13125)) + * provider/aws: Deprecate roles in favour of role in iam_instance_profile ([#13130](https://github.com/hashicorp/terraform/issues/13130)) + * provider/aws: Make alb_target_group_attachment port optional ([#13139](https://github.com/hashicorp/terraform/issues/13139)) + * provider/aws: `aws_api_gateway_domain_name` `certificate_private_key` field marked as sensitive ([#13147](https://github.com/hashicorp/terraform/issues/13147)) + * provider/aws: `aws_directory_service_directory` `password` field marked as sensitive ([#13147](https://github.com/hashicorp/terraform/issues/13147)) + * provider/aws: `aws_kinesis_firehose_delivery_stream` `password` field marked as sensitive ([#13147](https://github.com/hashicorp/terraform/issues/13147)) + * provider/aws: `aws_opsworks_application` `app_source.0.password` & `ssl_configuration.0.private_key` fields marked as sensitive ([#13147](https://github.com/hashicorp/terraform/issues/13147)) + * provider/aws: `aws_opsworks_stack` `custom_cookbooks_source.0.password` field marked as sensitive ([#13147](https://github.com/hashicorp/terraform/issues/13147)) + * provider/aws: Support the ability to enable / disable ipv6 support in VPC ([#12527](https://github.com/hashicorp/terraform/issues/12527)) + * provider/aws: Added API Gateway integration update ([#13249](https://github.com/hashicorp/terraform/issues/13249)) + * provider/aws: Add `identifier` | `name_prefix` to RDS resources ([#13232](https://github.com/hashicorp/terraform/issues/13232)) + * provider/aws: Validate `aws_ecs_task_definition.container_definitions` ([#12161](https://github.com/hashicorp/terraform/issues/12161)) + * provider/aws: Update caller_identity data source ([#13092](https://github.com/hashicorp/terraform/issues/13092)) + * provider/aws: `aws_subnet_ids` data source for getting a list of subnet ids matching certain criteria ([#13188](https://github.com/hashicorp/terraform/issues/13188)) + * provider/aws: Support ip_address_type for aws_alb ([#13227](https://github.com/hashicorp/terraform/issues/13227)) + * provider/aws: Migrate `aws_dms_*` resources away from AWS waiters ([#13291](https://github.com/hashicorp/terraform/issues/13291)) + * provider/aws: Add support for treat_missing_data to cloudwatch_metric_alarm ([#13358](https://github.com/hashicorp/terraform/issues/13358)) + * provider/aws: Add support for evaluate_low_sample_count_percentiles to cloudwatch_metric_alarm ([#13371](https://github.com/hashicorp/terraform/issues/13371)) + * provider/aws: Add `name_prefix` to `aws_alb_target_group` ([#13442](https://github.com/hashicorp/terraform/issues/13442)) + * provider/aws: Add support for EMR clusters to aws_appautoscaling_target ([#13368](https://github.com/hashicorp/terraform/issues/13368)) + * provider/aws: Add import capabilities to codecommit_repository ([#13577](https://github.com/hashicorp/terraform/issues/13577)) + * provider/bitbucket: Improved error handling ([#13390](https://github.com/hashicorp/terraform/issues/13390)) + * provider/cloudstack: Do not force a new resource when updating `cloudstack_loadbalancer_rule` members ([#11786](https://github.com/hashicorp/terraform/issues/11786)) + * provider/fastly: Add support for Sumologic logging ([#12541](https://github.com/hashicorp/terraform/issues/12541)) + * provider/github: Handle the case when issue labels already exist ([#13182](https://github.com/hashicorp/terraform/issues/13182)) + * provider/google: Mark `google_container_cluster`'s `client_key` & `password` inside `master_auth` as sensitive ([#13148](https://github.com/hashicorp/terraform/issues/13148)) + * provider/google: Add node_pool field in resource_container_cluster ([#13402](https://github.com/hashicorp/terraform/issues/13402)) + * provider/kubernetes: Allow defining custom config context ([#12958](https://github.com/hashicorp/terraform/issues/12958)) + * provider/openstack: Add support for 'value_specs' options to `openstack_compute_servergroup_v2` ([#13380](https://github.com/hashicorp/terraform/issues/13380)) + * provider/statuscake: Add support for StatusCake TriggerRate field ([#13340](https://github.com/hashicorp/terraform/issues/13340)) + * provider/triton: Move to joyent/triton-go ([#13225](https://github.com/hashicorp/terraform/issues/13225)) + * provisioner/chef: Make sure we add new Chef-Vault clients as clients ([#13525](https://github.com/hashicorp/terraform/issues/13525)) + +BUG FIXES: + + * core: Escaped interpolation-like sequences (like `$${foo}`) now permitted in variable defaults ([#13137](https://github.com/hashicorp/terraform/issues/13137)) + * core: Fix strange issues with computed values in provider configuration that were worked around with `-input=false` ([#11264](https://github.com/hashicorp/terraform/issues/11264)], [[#13264](https://github.com/hashicorp/terraform/issues/13264)) + * core: Fix crash when providing nested maps as variable values in a `module` block ([#13343](https://github.com/hashicorp/terraform/issues/13343)) + * core: `connection` block attributes are now subject to basic validation of attribute names during validate walk ([#13400](https://github.com/hashicorp/terraform/issues/13400)) + * provider/aws: Add Support for maintenance_window and back_window to rds_cluster_instance ([#13134](https://github.com/hashicorp/terraform/issues/13134)) + * provider/aws: Increase timeout for AMI registration ([#13159](https://github.com/hashicorp/terraform/issues/13159)) + * provider/aws: Increase timeouts for ELB ([#13161](https://github.com/hashicorp/terraform/issues/13161)) + * provider/aws: `volume_type` of `aws_elasticsearch_domain.0.ebs_options` marked as `Computed` which prevents spurious diffs ([#13160](https://github.com/hashicorp/terraform/issues/13160)) + * provider/aws: Don't set DBName on `aws_db_instance` from snapshot ([#13140](https://github.com/hashicorp/terraform/issues/13140)) + * provider/aws: Add DiffSuppression to aws_ecs_service placement_strategies ([#13220](https://github.com/hashicorp/terraform/issues/13220)) + * provider/aws: Refresh aws_alb_target_group stickiness on manual updates ([#13199](https://github.com/hashicorp/terraform/issues/13199)) + * provider/aws: Preserve default retain_on_delete in cloudfront import ([#13209](https://github.com/hashicorp/terraform/issues/13209)) + * provider/aws: Refresh aws_alb_target_group tags ([#13200](https://github.com/hashicorp/terraform/issues/13200)) + * provider/aws: Set aws_vpn_connection to recreate when in deleted state ([#13204](https://github.com/hashicorp/terraform/issues/13204)) + * provider/aws: Wait for aws_opsworks_instance to be running when it's specified ([#13218](https://github.com/hashicorp/terraform/issues/13218)) + * provider/aws: Handle `aws_lambda_function` missing s3 key error ([#10960](https://github.com/hashicorp/terraform/issues/10960)) + * provider/aws: Set stickiness to computed in alb_target_group ([#13278](https://github.com/hashicorp/terraform/issues/13278)) + * provider/aws: Increase timeout for deploying `cloudfront_distribution` from 40 to 70 mins ([#13319](https://github.com/hashicorp/terraform/issues/13319)) + * provider/aws: Increase AMI retry timeouts ([#13324](https://github.com/hashicorp/terraform/issues/13324)) + * provider/aws: Increase subnet deletion timeout ([#13356](https://github.com/hashicorp/terraform/issues/13356)) + * provider/aws: Increase launch_configuration creation timeout ([#13357](https://github.com/hashicorp/terraform/issues/13357)) + * provider/aws: Increase Beanstalk env 'ready' timeout ([#13359](https://github.com/hashicorp/terraform/issues/13359)) + * provider/aws: Raise timeout for deleting APIG REST API ([#13414](https://github.com/hashicorp/terraform/issues/13414)) + * provider/aws: Raise timeout for attaching/detaching VPN Gateway ([#13457](https://github.com/hashicorp/terraform/issues/13457)) + * provider/aws: Recreate opsworks_stack on change of service_role_arn ([#13325](https://github.com/hashicorp/terraform/issues/13325)) + * provider/aws: Fix KMS Key reading with Exists method ([#13348](https://github.com/hashicorp/terraform/issues/13348)) + * provider/aws: Fix DynamoDB issues about GSIs indexes ([#13256](https://github.com/hashicorp/terraform/issues/13256)) + * provider/aws: Fix `aws_s3_bucket` drift detection of logging options ([#13281](https://github.com/hashicorp/terraform/issues/13281)) + * provider/aws: Update ElasticTranscoderPreset to have default for MaxFrameRate ([#13422](https://github.com/hashicorp/terraform/issues/13422)) + * provider/aws: Fix aws_ami_launch_permission refresh when AMI disappears ([#13469](https://github.com/hashicorp/terraform/issues/13469)) + * provider/aws: Add support for updating SSM documents ([#13491](https://github.com/hashicorp/terraform/issues/13491)) + * provider/aws: Fix panic on nil route configs ([#13548](https://github.com/hashicorp/terraform/issues/13548)) + * provider/azurerm: Network Security Group - ignoring protocol casing at Import time ([#13153](https://github.com/hashicorp/terraform/issues/13153)) + * provider/azurerm: Fix crash when importing Local Network Gateways ([#13261](https://github.com/hashicorp/terraform/issues/13261)) + * provider/azurerm: Defaulting the value of `duplicate_detection_history_time_window` for `azurerm_servicebus_topic` ([#13223](https://github.com/hashicorp/terraform/issues/13223)) + * provider/azurerm: Event Hubs making the Location field idempotent ([#13570](https://github.com/hashicorp/terraform/issues/13570)) + * provider/bitbucket: Fixed issue where provider would fail with an "EOF" error on some operations ([#13390](https://github.com/hashicorp/terraform/issues/13390)) + * provider/dnsimple: Handle 404 on DNSimple records ([#13131](https://github.com/hashicorp/terraform/issues/13131)) + * provider/kubernetes: Use PATCH to update namespace ([#13114](https://github.com/hashicorp/terraform/issues/13114)) + * provider/ns1: No splitting answer on SPF records. ([#13260](https://github.com/hashicorp/terraform/issues/13260)) + * provider/openstack: Refresh volume_attachment from state if NotFound ([#13342](https://github.com/hashicorp/terraform/issues/13342)) + * provider/openstack: Add SOFT_DELETED to delete status ([#13444](https://github.com/hashicorp/terraform/issues/13444)) + * provider/profitbricks: Changed output type of ips variable of ip_block ProfitBricks resource ([#13290](https://github.com/hashicorp/terraform/issues/13290)) + * provider/template: Fix panic in cloudinit config ([#13581](https://github.com/hashicorp/terraform/issues/13581)) ## 0.9.2 (March 28, 2017) -BACKWARDS IMCOMPATIBILITIES / NOTES: +BACKWARDS INCOMPATIBILITIES / NOTES: * provider/openstack: Port Fixed IPs are able to be read again using the original numerical notation. However, Fixed IP configurations which are obtaining addresses via DHCP must now use the `all_fixed_ips` attribute to reference the returned IP address. * Environment names must be safe to use as a URL path segment without escaping, and is enforced by the CLI. @@ -58,8 +447,8 @@ IMPROVEMENTS: * provider/pagerduty: Validate credentials ([#12854](https://github.com/hashicorp/terraform/issues/12854)) * provider/openstack: Adding all_metadata attribute ([#13061](https://github.com/hashicorp/terraform/issues/13061)) * provider/profitbricks: Handling missing resources ([#13053](https://github.com/hashicorp/terraform/issues/13053)) - -BUG FIXES: + +BUG FIXES: * core: Remove legacy remote state configuration on state migration. This fixes errors when saving plans. ([#12888](https://github.com/hashicorp/terraform/issues/12888)) * provider/arukas: Default timeout for launching container increased to 15mins (was 10mins) ([#12849](https://github.com/hashicorp/terraform/issues/12849)) @@ -88,7 +477,7 @@ BUG FIXES: ## 0.9.1 (March 17, 2017) -BACKWARDS IMCOMPATIBILITIES / NOTES: +BACKWARDS INCOMPATIBILITIES / NOTES: * provider/pagerduty: the deprecated `name_regex` field has been removed from vendor data source ([#12396](https://github.com/hashicorp/terraform/issues/12396)) @@ -125,7 +514,7 @@ BUG FIXES: * provider/aws: Stop setting weight property on route53_record read ([#12756](https://github.com/hashicorp/terraform/issues/12756)) * provider/google: Fix the Google provider asking for account_file input on every run ([#12729](https://github.com/hashicorp/terraform/issues/12729)) * provider/profitbricks: Prevent panic on profitbricks volume ([#12819](https://github.com/hashicorp/terraform/issues/12819)) - + ## 0.9.0 (March 15, 2017) @@ -273,7 +662,7 @@ BUG FIXES: * provider/google: Correct the incorrect instance group manager URL returned from GKE ([#4336](https://github.com/hashicorp/terraform/issues/4336)) * provider/google: Fix a plan/apply cycle in IAM policies ([#12387](https://github.com/hashicorp/terraform/issues/12387)) * provider/google: Fix a plan/apply cycle in forwarding rules when only a single port is specified ([#12662](https://github.com/hashicorp/terraform/issues/12662)) - + ## 0.9.0-beta2 (March 2, 2017) BACKWARDS INCOMPATIBILITIES / NOTES: @@ -477,7 +866,7 @@ Bug FIXES: * core: module sources ended in archive extensions without a "." won't be treated as archives ([#11438](https://github.com/hashicorp/terraform/issues/11438)) * core: destroy ordering of resources within modules is correct ([#11765](https://github.com/hashicorp/terraform/issues/11765)) * core: Fix crash if count interpolates into a non-int ([#11864](https://github.com/hashicorp/terraform/issues/11864)) - * core: Targeting a module will properly exclude untargeted module outputs ([#11291](https://github.com/hashicorp/terraform/issues/11291)) + * core: Targeting a module will properly exclude untargeted module outputs ([#11921](https://github.com/hashicorp/terraform/issues/11921)) * state/remote/s3: Fix Bug with Assume Role for Federated IAM Account ([#10067](https://github.com/hashicorp/terraform/issues/10067)) * provider/aws: Fix security_group_rule resource timeout errors ([#11809](https://github.com/hashicorp/terraform/issues/11809)) * provider/aws: Fix diff suppress function for aws_db_instance ([#11909](https://github.com/hashicorp/terraform/issues/11909)) diff --git a/Makefile b/Makefile index 277b3c273..3adc57f1a 100644 --- a/Makefile +++ b/Makefile @@ -79,8 +79,8 @@ cover: # vet runs the Go source code static analysis tool `vet` to find # any common errors. vet: - @echo "go vet ." - @go vet $$(go list ./... | grep -v vendor/) ; if [ $$? -eq 1 ]; then \ + @echo 'go vet $$(go list ./... | grep -v /terraform/vendor/)' + @go vet $$(go list ./... | grep -v /terraform/vendor/) ; if [ $$? -eq 1 ]; then \ echo ""; \ echo "Vet found suspicious constructs. Please check the reported constructs"; \ echo "and fix them if necessary before submitting the code for review."; \ diff --git a/README.md b/README.md index f4b36b564..351cf0e8a 100644 --- a/README.md +++ b/README.md @@ -5,7 +5,7 @@ Terraform - [![Gitter chat](https://badges.gitter.im/hashicorp-terraform/Lobby.png)](https://gitter.im/hashicorp-terraform/Lobby) - Mailing list: [Google Groups](http://groups.google.com/group/terraform-tool) -![Terraform](https://raw.githubusercontent.com/hashicorp/terraform/master/website/source/assets/images/readme.png) +![Terraform](https://rawgithub.com/hashicorp/terraform/master/website/source/assets/images/logo-hashicorp.svg) Terraform is a tool for building, changing, and versioning infrastructure safely and efficiently. Terraform can manage existing and popular service providers as well as custom in-house solutions. diff --git a/Vagrantfile b/Vagrantfile index f59618e3b..368331868 100644 --- a/Vagrantfile +++ b/Vagrantfile @@ -5,7 +5,7 @@ VAGRANTFILE_API_VERSION = "2" # Software version variables -GOVERSION = "1.8" +GOVERSION = "1.8.1" UBUNTUVERSION = "16.04" # CPU and RAM can be adjusted depending on your system diff --git a/backend/backend.go b/backend/backend.go index f6c567c71..09a16fbaa 100644 --- a/backend/backend.go +++ b/backend/backend.go @@ -7,6 +7,7 @@ package backend import ( "context" "errors" + "time" "github.com/hashicorp/terraform/config/module" "github.com/hashicorp/terraform/state" @@ -132,6 +133,9 @@ type Operation struct { // state.Lockers for its duration, and Unlock when complete. LockState bool + // The duration to retry obtaining a State lock. + StateLockTimeout time.Duration + // Environment is the named state that should be loaded from the Backend. Environment string } diff --git a/backend/local/backend.go b/backend/local/backend.go index 063766b1e..7c715d67a 100644 --- a/backend/local/backend.go +++ b/backend/local/backend.go @@ -170,9 +170,30 @@ func (b *Local) DeleteState(name string) error { } func (b *Local) State(name string) (state.State, error) { + statePath, stateOutPath, backupPath := b.StatePaths(name) + // If we have a backend handling state, defer to that. if b.Backend != nil { - return b.Backend.State(name) + s, err := b.Backend.State(name) + if err != nil { + return nil, err + } + + // make sure we always have a backup state, unless it disabled + if backupPath == "" { + return s, nil + } + + // see if the delegated backend returned a BackupState of its own + if s, ok := s.(*state.BackupState); ok { + return s, nil + } + + s = &state.BackupState{ + Real: s, + Path: backupPath, + } + return s, nil } if s, ok := b.states[name]; ok { @@ -183,8 +204,6 @@ func (b *Local) State(name string) (state.State, error) { return nil, err } - statePath, stateOutPath, backupPath := b.StatePaths(name) - // Otherwise, we need to load the state. var s state.State = &state.LocalState{ Path: statePath, diff --git a/backend/local/backend_apply.go b/backend/local/backend_apply.go index 6b80aac34..9bc41f487 100644 --- a/backend/local/backend_apply.go +++ b/backend/local/backend_apply.go @@ -9,7 +9,7 @@ import ( "github.com/hashicorp/errwrap" "github.com/hashicorp/go-multierror" "github.com/hashicorp/terraform/backend" - clistate "github.com/hashicorp/terraform/command/state" + "github.com/hashicorp/terraform/command/clistate" "github.com/hashicorp/terraform/config/module" "github.com/hashicorp/terraform/state" "github.com/hashicorp/terraform/terraform" @@ -52,9 +52,12 @@ func (b *Local) opApply( } if op.LockState { + lockCtx, cancel := context.WithTimeout(ctx, op.StateLockTimeout) + defer cancel() + lockInfo := state.NewLockInfo() lockInfo.Operation = op.Type.String() - lockID, err := clistate.Lock(opState, lockInfo, b.CLI, b.Colorize()) + lockID, err := clistate.Lock(lockCtx, opState, lockInfo, b.CLI, b.Colorize()) if err != nil { runningOp.Err = errwrap.Wrapf("Error locking state: {{err}}", err) return @@ -99,7 +102,9 @@ func (b *Local) opApply( doneCh := make(chan struct{}) go func() { defer close(doneCh) - applyState, applyErr = tfCtx.Apply() + _, applyErr = tfCtx.Apply() + // we always want the state, even if apply failed + applyState = tfCtx.State() /* // Record any shadow errors for later @@ -116,7 +121,7 @@ func (b *Local) opApply( select { case <-ctx.Done(): if b.CLI != nil { - b.CLI.Output("Interrupt received. Gracefully shutting down...") + b.CLI.Output("stopping apply operation...") } // Stop execution diff --git a/backend/local/backend_plan.go b/backend/local/backend_plan.go index f63735873..42a56eb29 100644 --- a/backend/local/backend_plan.go +++ b/backend/local/backend_plan.go @@ -10,8 +10,8 @@ import ( "github.com/hashicorp/errwrap" "github.com/hashicorp/go-multierror" "github.com/hashicorp/terraform/backend" + "github.com/hashicorp/terraform/command/clistate" "github.com/hashicorp/terraform/command/format" - clistate "github.com/hashicorp/terraform/command/state" "github.com/hashicorp/terraform/config/module" "github.com/hashicorp/terraform/state" "github.com/hashicorp/terraform/terraform" @@ -61,9 +61,12 @@ func (b *Local) opPlan( } if op.LockState { + lockCtx, cancel := context.WithTimeout(ctx, op.StateLockTimeout) + defer cancel() + lockInfo := state.NewLockInfo() lockInfo.Operation = op.Type.String() - lockID, err := clistate.Lock(opState, lockInfo, b.CLI, b.Colorize()) + lockID, err := clistate.Lock(lockCtx, opState, lockInfo, b.CLI, b.Colorize()) if err != nil { runningOp.Err = errwrap.Wrapf("Error locking state: {{err}}", err) return diff --git a/backend/local/backend_refresh.go b/backend/local/backend_refresh.go index c8b23bd32..282e63045 100644 --- a/backend/local/backend_refresh.go +++ b/backend/local/backend_refresh.go @@ -9,7 +9,7 @@ import ( "github.com/hashicorp/errwrap" "github.com/hashicorp/go-multierror" "github.com/hashicorp/terraform/backend" - clistate "github.com/hashicorp/terraform/command/state" + "github.com/hashicorp/terraform/command/clistate" "github.com/hashicorp/terraform/config/module" "github.com/hashicorp/terraform/state" ) @@ -51,9 +51,12 @@ func (b *Local) opRefresh( } if op.LockState { + lockCtx, cancel := context.WithTimeout(ctx, op.StateLockTimeout) + defer cancel() + lockInfo := state.NewLockInfo() lockInfo.Operation = op.Type.String() - lockID, err := clistate.Lock(opState, lockInfo, b.CLI, b.Colorize()) + lockID, err := clistate.Lock(lockCtx, opState, lockInfo, b.CLI, b.Colorize()) if err != nil { runningOp.Err = errwrap.Wrapf("Error locking state: {{err}}", err) return diff --git a/backend/local/backend_test.go b/backend/local/backend_test.go index 3b5f1f9bd..a32cbc7d7 100644 --- a/backend/local/backend_test.go +++ b/backend/local/backend_test.go @@ -169,6 +169,11 @@ func TestLocal_addAndRemoveStates(t *testing.T) { // verify it's being called. type testDelegateBackend struct { *Local + + // return a sentinel error on these calls + stateErr bool + statesErr bool + deleteErr bool } var errTestDelegateState = errors.New("State called") @@ -176,22 +181,39 @@ var errTestDelegateStates = errors.New("States called") var errTestDelegateDeleteState = errors.New("Delete called") func (b *testDelegateBackend) State(name string) (state.State, error) { - return nil, errTestDelegateState + if b.stateErr { + return nil, errTestDelegateState + } + s := &state.LocalState{ + Path: "terraform.tfstate", + PathOut: "terraform.tfstate", + } + return s, nil } func (b *testDelegateBackend) States() ([]string, error) { - return nil, errTestDelegateStates + if b.statesErr { + return nil, errTestDelegateStates + } + return []string{"default"}, nil } func (b *testDelegateBackend) DeleteState(name string) error { - return errTestDelegateDeleteState + if b.deleteErr { + return errTestDelegateDeleteState + } + return nil } // verify that the MultiState methods are dispatched to the correct Backend. func TestLocal_multiStateBackend(t *testing.T) { // assign a separate backend where we can read the state b := &Local{ - Backend: &testDelegateBackend{}, + Backend: &testDelegateBackend{ + stateErr: true, + statesErr: true, + deleteErr: true, + }, } if _, err := b.State("test"); err != errTestDelegateState { @@ -205,7 +227,43 @@ func TestLocal_multiStateBackend(t *testing.T) { if err := b.DeleteState("test"); err != errTestDelegateDeleteState { t.Fatal("expected errTestDelegateDeleteState, got:", err) } +} +// verify that a remote state backend is always wrapped in a BackupState +func TestLocal_remoteStateBackup(t *testing.T) { + // assign a separate backend to mock a remote state backend + b := &Local{ + Backend: &testDelegateBackend{}, + } + + s, err := b.State("default") + if err != nil { + t.Fatal(err) + } + + bs, ok := s.(*state.BackupState) + if !ok { + t.Fatal("remote state is not backed up") + } + + if bs.Path != DefaultStateFilename+DefaultBackupExtension { + t.Fatal("bad backup location:", bs.Path) + } + + // do the same with a named state, which should use the local env directories + s, err = b.State("test") + if err != nil { + t.Fatal(err) + } + + bs, ok = s.(*state.BackupState) + if !ok { + t.Fatal("remote state is not backed up") + } + + if bs.Path != filepath.Join(DefaultEnvDir, "test", DefaultStateFilename+DefaultBackupExtension) { + t.Fatal("bad backup location:", bs.Path) + } } // change into a tmp dir and return a deferable func to change back and cleanup diff --git a/backend/local/counthookaction_string.go b/backend/local/counthookaction_string.go index 574a8c6cb..92b2624a5 100644 --- a/backend/local/counthookaction_string.go +++ b/backend/local/counthookaction_string.go @@ -1,4 +1,4 @@ -// Code generated by "stringer -type=countHookAction hook_count_action.go"; DO NOT EDIT +// Code generated by "stringer -type=countHookAction hook_count_action.go"; DO NOT EDIT. package local diff --git a/backend/operationtype_string.go b/backend/operationtype_string.go index 6edadb919..15fbba6ec 100644 --- a/backend/operationtype_string.go +++ b/backend/operationtype_string.go @@ -1,4 +1,4 @@ -// Code generated by "stringer -type=OperationType operation_type.go"; DO NOT EDIT +// Code generated by "stringer -type=OperationType operation_type.go"; DO NOT EDIT. package backend diff --git a/backend/remote-state/consul/backend_state.go b/backend/remote-state/consul/backend_state.go index 74f30c842..9a8fd080f 100644 --- a/backend/remote-state/consul/backend_state.go +++ b/backend/remote-state/consul/backend_state.go @@ -102,22 +102,19 @@ func (b *Backend) State(name string) (state.State, error) { stateMgr = &state.LockDisabled{Inner: stateMgr} } - // Get the locker, which we know always exists - stateMgrLocker := stateMgr.(state.Locker) - // Grab a lock, we use this to write an empty state if one doesn't // exist already. We have to write an empty state as a sentinel value // so States() knows it exists. lockInfo := state.NewLockInfo() lockInfo.Operation = "init" - lockId, err := stateMgrLocker.Lock(lockInfo) + lockId, err := stateMgr.Lock(lockInfo) if err != nil { return nil, fmt.Errorf("failed to lock state in Consul: %s", err) } // Local helper function so we can call it multiple places lockUnlock := func(parent error) error { - if err := stateMgrLocker.Unlock(lockId); err != nil { + if err := stateMgr.Unlock(lockId); err != nil { return fmt.Errorf(strings.TrimSpace(errStateUnlock), lockId, err) } diff --git a/backend/remote-state/consul/client.go b/backend/remote-state/consul/client.go index cd5971163..b11f31ba1 100644 --- a/backend/remote-state/consul/client.go +++ b/backend/remote-state/consul/client.go @@ -121,16 +121,15 @@ func (c *RemoteClient) Lock(info *state.LockInfo) (string, error) { default: if c.lockCh != nil { // we have an active lock already - return "", nil + return "", fmt.Errorf("state %q already locked", c.Path) } } if c.consulLock == nil { opts := &consulapi.LockOptions{ Key: c.Path + lockSuffix, - // We currently don't procide any options to block terraform and - // retry lock acquisition, but we can wait briefly in case the - // lock is about to be freed. + // only wait briefly, so terraform has the choice to fail fast or + // retry as needed. LockWaitTime: time.Second, LockTryOnce: true, } @@ -191,6 +190,10 @@ func (c *RemoteClient) Unlock(id string) error { err := c.consulLock.Unlock() c.lockCh = nil + // This is only cleanup, and will fail if the lock was immediately taken by + // another client, so we don't report an error to the user here. + c.consulLock.Destroy() + kv := c.Client.KV() _, delErr := kv.Delete(c.Path+lockInfoSuffix, nil) if delErr != nil { diff --git a/backend/remote-state/consul/client_test.go b/backend/remote-state/consul/client_test.go index 57b7c452e..dc7988135 100644 --- a/backend/remote-state/consul/client_test.go +++ b/backend/remote-state/consul/client_test.go @@ -6,6 +6,7 @@ import ( "time" "github.com/hashicorp/terraform/backend" + "github.com/hashicorp/terraform/state" "github.com/hashicorp/terraform/state/remote" ) @@ -98,3 +99,43 @@ func TestConsul_stateLock(t *testing.T) { remote.TestRemoteLocks(t, sA.(*remote.State).Client, sB.(*remote.State).Client) } + +func TestConsul_destroyLock(t *testing.T) { + srv := newConsulTestServer(t) + defer srv.Stop() + + // Get the backend + b := backend.TestBackendConfig(t, New(), map[string]interface{}{ + "address": srv.HTTPAddr, + "path": fmt.Sprintf("tf-unit/%s", time.Now().String()), + }) + + // Grab the client + s, err := b.State(backend.DefaultStateName) + if err != nil { + t.Fatalf("err: %s", err) + } + + c := s.(*remote.State).Client.(*RemoteClient) + + info := state.NewLockInfo() + id, err := c.Lock(info) + if err != nil { + t.Fatal(err) + } + + lockPath := c.Path + lockSuffix + + if err := c.Unlock(id); err != nil { + t.Fatal(err) + } + + // get the lock val + pair, _, err := c.Client.KV().Get(lockPath, nil) + if err != nil { + t.Fatal(err) + } + if pair != nil { + t.Fatalf("lock key not cleaned up at: %s", pair.Key) + } +} diff --git a/backend/remote-state/s3/backend.go b/backend/remote-state/s3/backend.go index 8265d7f25..846746b98 100644 --- a/backend/remote-state/s3/backend.go +++ b/backend/remote-state/s3/backend.go @@ -2,15 +2,9 @@ package s3 import ( "context" - "fmt" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/dynamodb" "github.com/aws/aws-sdk-go/service/s3" - cleanhttp "github.com/hashicorp/go-cleanhttp" - multierror "github.com/hashicorp/go-multierror" "github.com/hashicorp/terraform/backend" "github.com/hashicorp/terraform/helper/schema" @@ -21,101 +15,122 @@ import ( func New() backend.Backend { s := &schema.Backend{ Schema: map[string]*schema.Schema{ - "bucket": &schema.Schema{ + "bucket": { Type: schema.TypeString, Required: true, Description: "The name of the S3 bucket", }, - "key": &schema.Schema{ + "key": { Type: schema.TypeString, Required: true, Description: "The path to the state file inside the bucket", }, - "region": &schema.Schema{ + "region": { Type: schema.TypeString, Required: true, Description: "The region of the S3 bucket.", DefaultFunc: schema.EnvDefaultFunc("AWS_DEFAULT_REGION", nil), }, - "endpoint": &schema.Schema{ + "endpoint": { Type: schema.TypeString, Optional: true, Description: "A custom endpoint for the S3 API", DefaultFunc: schema.EnvDefaultFunc("AWS_S3_ENDPOINT", ""), }, - "encrypt": &schema.Schema{ + "encrypt": { Type: schema.TypeBool, Optional: true, Description: "Whether to enable server side encryption of the state file", Default: false, }, - "acl": &schema.Schema{ + "acl": { Type: schema.TypeString, Optional: true, Description: "Canned ACL to be applied to the state file", Default: "", }, - "access_key": &schema.Schema{ + "access_key": { Type: schema.TypeString, Optional: true, Description: "AWS access key", Default: "", }, - "secret_key": &schema.Schema{ + "secret_key": { Type: schema.TypeString, Optional: true, Description: "AWS secret key", Default: "", }, - "kms_key_id": &schema.Schema{ + "kms_key_id": { Type: schema.TypeString, Optional: true, Description: "The ARN of a KMS Key to use for encrypting the state", Default: "", }, - "lock_table": &schema.Schema{ + "lock_table": { Type: schema.TypeString, Optional: true, Description: "DynamoDB table for state locking", Default: "", }, - "profile": &schema.Schema{ + "profile": { Type: schema.TypeString, Optional: true, Description: "AWS profile name", Default: "", }, - "shared_credentials_file": &schema.Schema{ + "shared_credentials_file": { Type: schema.TypeString, Optional: true, Description: "Path to a shared credentials file", Default: "", }, - "token": &schema.Schema{ + "token": { Type: schema.TypeString, Optional: true, Description: "MFA token", Default: "", }, - "role_arn": &schema.Schema{ + "role_arn": { Type: schema.TypeString, Optional: true, Description: "The role to be assumed", Default: "", }, + + "session_name": { + Type: schema.TypeString, + Optional: true, + Description: "The session name to use when assuming the role.", + Default: "", + }, + + "external_id": { + Type: schema.TypeString, + Optional: true, + Description: "The external ID to use when assuming the role", + Default: "", + }, + + "assume_role_policy": { + Type: schema.TypeString, + Optional: true, + Description: "The permissions applied when assuming a role.", + Default: "", + }, }, } @@ -154,45 +169,27 @@ func (b *Backend) configure(ctx context.Context) error { b.kmsKeyID = data.Get("kms_key_id").(string) b.lockTable = data.Get("lock_table").(string) - var errs []error - creds, err := terraformAWS.GetCredentials(&terraformAWS.Config{ - AccessKey: data.Get("access_key").(string), - SecretKey: data.Get("secret_key").(string), - Token: data.Get("token").(string), - Profile: data.Get("profile").(string), - CredsFilename: data.Get("shared_credentials_file").(string), - AssumeRoleARN: data.Get("role_arn").(string), - }) + cfg := &terraformAWS.Config{ + AccessKey: data.Get("access_key").(string), + AssumeRoleARN: data.Get("role_arn").(string), + AssumeRoleExternalID: data.Get("external_id").(string), + AssumeRolePolicy: data.Get("assume_role_policy").(string), + AssumeRoleSessionName: data.Get("session_name").(string), + CredsFilename: data.Get("shared_credentials_file").(string), + Profile: data.Get("profile").(string), + Region: data.Get("region").(string), + S3Endpoint: data.Get("endpoint").(string), + SecretKey: data.Get("secret_key").(string), + Token: data.Get("token").(string), + } + + client, err := cfg.Client() if err != nil { return err } - // Call Get to check for credential provider. If nothing found, we'll get an - // error, and we can present it nicely to the user - _, err = creds.Get() - if err != nil { - if awsErr, ok := err.(awserr.Error); ok && awsErr.Code() == "NoCredentialProviders" { - errs = append(errs, fmt.Errorf(`No valid credential sources found for AWS S3 remote. -Please see https://www.terraform.io/docs/state/remote/s3.html for more information on -providing credentials for the AWS S3 remote`)) - } else { - errs = append(errs, fmt.Errorf("Error loading credentials for AWS S3 remote: %s", err)) - } - return &multierror.Error{Errors: errs} - } - - endpoint := data.Get("endpoint").(string) - region := data.Get("region").(string) - - awsConfig := &aws.Config{ - Credentials: creds, - Endpoint: aws.String(endpoint), - Region: aws.String(region), - HTTPClient: cleanhttp.DefaultClient(), - } - sess := session.New(awsConfig) - b.s3Client = s3.New(sess) - b.dynClient = dynamodb.New(sess) + b.s3Client = client.(*terraformAWS.AWSClient).S3() + b.dynClient = client.(*terraformAWS.AWSClient).DynamoDB() return nil } diff --git a/backend/remote-state/s3/backend_state.go b/backend/remote-state/s3/backend_state.go index 2d745156e..f7a4d337d 100644 --- a/backend/remote-state/s3/backend_state.go +++ b/backend/remote-state/s3/backend_state.go @@ -1,6 +1,7 @@ package s3 import ( + "errors" "fmt" "sort" "strings" @@ -30,29 +31,34 @@ func (b *Backend) States() ([]string, error) { return nil, err } - var envs []string + envs := []string{backend.DefaultStateName} for _, obj := range resp.Contents { - env := keyEnv(*obj.Key) + env := b.keyEnv(*obj.Key) if env != "" { envs = append(envs, env) } } - sort.Strings(envs) - envs = append([]string{backend.DefaultStateName}, envs...) + sort.Strings(envs[1:]) return envs, nil } // extract the env name from the S3 key -func keyEnv(key string) string { - parts := strings.Split(key, "/") +func (b *Backend) keyEnv(key string) string { + // we have 3 parts, the prefix, the env name, and the key name + parts := strings.SplitN(key, "/", 3) if len(parts) < 3 { // no env here return "" } + // shouldn't happen since we listed by prefix if parts[0] != keyEnvPrefix { - // not our key, so ignore + return "" + } + + // not our key, so don't include it in our listing + if parts[2] != b.keyName { return "" } @@ -78,6 +84,10 @@ func (b *Backend) DeleteState(name string) error { } func (b *Backend) State(name string) (state.State, error) { + if name == "" { + return nil, errors.New("missing state name") + } + client := &RemoteClient{ s3Client: b.s3Client, dynClient: b.dynClient, diff --git a/backend/remote-state/s3/backend_test.go b/backend/remote-state/s3/backend_test.go index f8b664b80..d90c76a6c 100644 --- a/backend/remote-state/s3/backend_test.go +++ b/backend/remote-state/s3/backend_test.go @@ -3,6 +3,7 @@ package s3 import ( "fmt" "os" + "reflect" "testing" "time" @@ -10,6 +11,8 @@ import ( "github.com/aws/aws-sdk-go/service/dynamodb" "github.com/aws/aws-sdk-go/service/s3" "github.com/hashicorp/terraform/backend" + "github.com/hashicorp/terraform/state/remote" + "github.com/hashicorp/terraform/terraform" ) // verify that we are doing ACC tests or the S3 tests specifically @@ -29,16 +32,12 @@ func TestBackend_impl(t *testing.T) { } func TestBackendConfig(t *testing.T) { - // This test just instantiates the client. Shouldn't make any actual - // requests nor incur any costs. - + testACC(t) config := map[string]interface{}{ "region": "us-west-1", "bucket": "tf-test", "key": "state", "encrypt": true, - "access_key": "ACCESS_KEY", - "secret_key": "SECRET_KEY", "lock_table": "dynamoTable", } @@ -58,11 +57,11 @@ func TestBackendConfig(t *testing.T) { if err != nil { t.Fatalf("Error when requesting credentials") } - if credentials.AccessKeyID != "ACCESS_KEY" { - t.Fatalf("Incorrect Access Key Id was populated") + if credentials.AccessKeyID == "" { + t.Fatalf("No Access Key Id was populated") } - if credentials.SecretAccessKey != "SECRET_KEY" { - t.Fatalf("Incorrect Secret Access Key was populated") + if credentials.SecretAccessKey == "" { + t.Fatalf("No Secret Access Key was populated") } } @@ -88,7 +87,7 @@ func TestBackendLocked(t *testing.T) { testACC(t) bucketName := fmt.Sprintf("terraform-remote-s3-test-%x", time.Now().Unix()) - keyName := "testState" + keyName := "test/state" b1 := backend.TestBackendConfig(t, New(), map[string]interface{}{ "bucket": bucketName, @@ -112,6 +111,133 @@ func TestBackendLocked(t *testing.T) { backend.TestBackend(t, b1, b2) } +// add some extra junk in S3 to try and confuse the env listing. +func TestBackendExtraPaths(t *testing.T) { + testACC(t) + bucketName := fmt.Sprintf("terraform-remote-s3-test-%x", time.Now().Unix()) + keyName := "test/state/tfstate" + + b := backend.TestBackendConfig(t, New(), map[string]interface{}{ + "bucket": bucketName, + "key": keyName, + "encrypt": true, + }).(*Backend) + + createS3Bucket(t, b.s3Client, bucketName) + defer deleteS3Bucket(t, b.s3Client, bucketName) + + // put multiple states in old env paths. + s1 := terraform.NewState() + s2 := terraform.NewState() + + // RemoteClient to Put things in various paths + client := &RemoteClient{ + s3Client: b.s3Client, + dynClient: b.dynClient, + bucketName: b.bucketName, + path: b.path("s1"), + serverSideEncryption: b.serverSideEncryption, + acl: b.acl, + kmsKeyID: b.kmsKeyID, + lockTable: b.lockTable, + } + + stateMgr := &remote.State{Client: client} + stateMgr.WriteState(s1) + if err := stateMgr.PersistState(); err != nil { + t.Fatal(err) + } + + client.path = b.path("s2") + stateMgr.WriteState(s2) + if err := stateMgr.PersistState(); err != nil { + t.Fatal(err) + } + + if err := checkStateList(b, []string{"default", "s1", "s2"}); err != nil { + t.Fatal(err) + } + + // put a state in an env directory name + client.path = keyEnvPrefix + "/error" + stateMgr.WriteState(terraform.NewState()) + if err := stateMgr.PersistState(); err != nil { + t.Fatal(err) + } + if err := checkStateList(b, []string{"default", "s1", "s2"}); err != nil { + t.Fatal(err) + } + + // add state with the wrong key for an existing env + client.path = keyEnvPrefix + "/s2/notTestState" + stateMgr.WriteState(terraform.NewState()) + if err := stateMgr.PersistState(); err != nil { + t.Fatal(err) + } + if err := checkStateList(b, []string{"default", "s1", "s2"}); err != nil { + t.Fatal(err) + } + + // remove the state with extra subkey + if err := b.DeleteState("s2"); err != nil { + t.Fatal(err) + } + + if err := checkStateList(b, []string{"default", "s1"}); err != nil { + t.Fatal(err) + } + + // fetch that state again, which should produce a new lineage + s2Mgr, err := b.State("s2") + if err != nil { + t.Fatal(err) + } + if err := s2Mgr.RefreshState(); err != nil { + t.Fatal(err) + } + + if s2Mgr.State().Lineage == s2.Lineage { + t.Fatal("state s2 was not deleted") + } + s2 = s2Mgr.State() + + // add a state with a key that matches an existing environment dir name + client.path = keyEnvPrefix + "/s2/" + stateMgr.WriteState(terraform.NewState()) + if err := stateMgr.PersistState(); err != nil { + t.Fatal(err) + } + + // make sure s2 is OK + s2Mgr, err = b.State("s2") + if err != nil { + t.Fatal(err) + } + if err := s2Mgr.RefreshState(); err != nil { + t.Fatal(err) + } + + if s2Mgr.State().Lineage != s2.Lineage { + t.Fatal("we got the wrong state for s2") + } + + if err := checkStateList(b, []string{"default", "s1", "s2"}); err != nil { + t.Fatal(err) + } +} + +func checkStateList(b backend.Backend, expected []string) error { + states, err := b.States() + if err != nil { + return err + } + + if !reflect.DeepEqual(states, expected) { + return fmt.Errorf("incorrect states listed: %q", states) + } + return nil +} + func createS3Bucket(t *testing.T, s3Client *s3.S3, bucketName string) { createBucketReq := &s3.CreateBucketInput{ Bucket: &bucketName, diff --git a/backend/remote-state/s3/client.go b/backend/remote-state/s3/client.go index 735180ba9..d7603e4bf 100644 --- a/backend/remote-state/s3/client.go +++ b/backend/remote-state/s3/client.go @@ -113,8 +113,7 @@ func (c *RemoteClient) Lock(info *state.LockInfo) (string, error) { return "", nil } - stateName := fmt.Sprintf("%s/%s", c.bucketName, c.path) - info.Path = stateName + info.Path = c.lockPath() if info.ID == "" { lockID, err := uuid.GenerateUUID() @@ -127,7 +126,7 @@ func (c *RemoteClient) Lock(info *state.LockInfo) (string, error) { putParams := &dynamodb.PutItemInput{ Item: map[string]*dynamodb.AttributeValue{ - "LockID": {S: aws.String(stateName)}, + "LockID": {S: aws.String(c.lockPath())}, "Info": {S: aws.String(string(info.Marshal()))}, }, TableName: aws.String(c.lockTable), @@ -153,7 +152,7 @@ func (c *RemoteClient) Lock(info *state.LockInfo) (string, error) { func (c *RemoteClient) getLockInfo() (*state.LockInfo, error) { getParams := &dynamodb.GetItemInput{ Key: map[string]*dynamodb.AttributeValue{ - "LockID": {S: aws.String(fmt.Sprintf("%s/%s", c.bucketName, c.path))}, + "LockID": {S: aws.String(c.lockPath())}, }, ProjectionExpression: aws.String("LockID, Info"), TableName: aws.String(c.lockTable), @@ -202,7 +201,7 @@ func (c *RemoteClient) Unlock(id string) error { params := &dynamodb.DeleteItemInput{ Key: map[string]*dynamodb.AttributeValue{ - "LockID": {S: aws.String(fmt.Sprintf("%s/%s", c.bucketName, c.path))}, + "LockID": {S: aws.String(c.lockPath())}, }, TableName: aws.String(c.lockTable), } @@ -214,3 +213,7 @@ func (c *RemoteClient) Unlock(id string) error { } return nil } + +func (c *RemoteClient) lockPath() string { + return fmt.Sprintf("%s/%s", c.bucketName, c.path) +} diff --git a/builtin/bins/provider-gitlab/main.go b/builtin/bins/provider-gitlab/main.go new file mode 100644 index 000000000..acb94705d --- /dev/null +++ b/builtin/bins/provider-gitlab/main.go @@ -0,0 +1,12 @@ +package main + +import ( + "github.com/hashicorp/terraform/builtin/providers/gitlab" + "github.com/hashicorp/terraform/plugin" +) + +func main() { + plugin.Serve(&plugin.ServeOpts{ + ProviderFunc: gitlab.Provider, + }) +} diff --git a/builtin/bins/provider-localfile/main.go b/builtin/bins/provider-localfile/main.go new file mode 100644 index 000000000..70494016f --- /dev/null +++ b/builtin/bins/provider-localfile/main.go @@ -0,0 +1,12 @@ +package main + +import ( + "github.com/hashicorp/terraform/builtin/providers/local" + "github.com/hashicorp/terraform/plugin" +) + +func main() { + plugin.Serve(&plugin.ServeOpts{ + ProviderFunc: local.Provider, + }) +} diff --git a/builtin/bins/provider-ovh/main.go b/builtin/bins/provider-ovh/main.go new file mode 100644 index 000000000..90d4ec923 --- /dev/null +++ b/builtin/bins/provider-ovh/main.go @@ -0,0 +1,12 @@ +package main + +import ( + "github.com/hashicorp/terraform/builtin/providers/ovh" + "github.com/hashicorp/terraform/plugin" +) + +func main() { + plugin.Serve(&plugin.ServeOpts{ + ProviderFunc: ovh.Provider, + }) +} diff --git a/builtin/providers/alicloud/common.go b/builtin/providers/alicloud/common.go index c2af2a683..e9bb1a9f8 100644 --- a/builtin/providers/alicloud/common.go +++ b/builtin/providers/alicloud/common.go @@ -17,38 +17,39 @@ const ( const defaultTimeout = 120 // timeout for long time progerss product, rds e.g. -const defaultLongTimeout = 800 +const defaultLongTimeout = 1000 func getRegion(d *schema.ResourceData, meta interface{}) common.Region { return meta.(*AliyunClient).Region } func notFoundError(err error) bool { - if e, ok := err.(*common.Error); ok && (e.StatusCode == 404 || e.ErrorResponse.Message == "Not found") { + if e, ok := err.(*common.Error); ok && + (e.StatusCode == 404 || e.ErrorResponse.Message == "Not found" || e.Code == InstanceNotfound) { return true } return false } -// Protocal represents network protocal -type Protocal string +// Protocol represents network protocol +type Protocol string -// Constants of protocal definition +// Constants of protocol definition const ( - Http = Protocal("http") - Https = Protocal("https") - Tcp = Protocal("tcp") - Udp = Protocal("udp") + Http = Protocol("http") + Https = Protocol("https") + Tcp = Protocol("tcp") + Udp = Protocol("udp") ) -// ValidProtocals network protocal list -var ValidProtocals = []Protocal{Http, Https, Tcp, Udp} +// ValidProtocols network protocol list +var ValidProtocols = []Protocol{Http, Https, Tcp, Udp} // simple array value check method, support string type only -func isProtocalValid(value string) bool { +func isProtocolValid(value string) bool { res := false - for _, v := range ValidProtocals { + for _, v := range ValidProtocols { if string(v) == value { res = true } @@ -77,4 +78,16 @@ const DB_DEFAULT_CONNECT_PORT = "3306" const COMMA_SEPARATED = "," +const COLON_SEPARATED = ":" + const LOCAL_HOST_IP = "127.0.0.1" + +// Takes the result of flatmap.Expand for an array of strings +// and returns a []string +func expandStringList(configured []interface{}) []string { + vs := make([]string, 0, len(configured)) + for _, v := range configured { + vs = append(vs, v.(string)) + } + return vs +} diff --git a/builtin/providers/alicloud/config.go b/builtin/providers/alicloud/config.go index e17003bb2..f84c7e02a 100644 --- a/builtin/providers/alicloud/config.go +++ b/builtin/providers/alicloud/config.go @@ -5,6 +5,7 @@ import ( "github.com/denverdino/aliyungo/common" "github.com/denverdino/aliyungo/ecs" + "github.com/denverdino/aliyungo/ess" "github.com/denverdino/aliyungo/rds" "github.com/denverdino/aliyungo/slb" ) @@ -20,6 +21,7 @@ type Config struct { type AliyunClient struct { Region common.Region ecsconn *ecs.Client + essconn *ess.Client rdsconn *rds.Client // use new version ecsNewconn *ecs.Client @@ -60,6 +62,11 @@ func (c *Config) Client() (*AliyunClient, error) { return nil, err } + essconn, err := c.essConn() + if err != nil { + return nil, err + } + return &AliyunClient{ Region: c.Region, ecsconn: ecsconn, @@ -67,6 +74,7 @@ func (c *Config) Client() (*AliyunClient, error) { vpcconn: vpcconn, slbconn: slbconn, rdsconn: rdsconn, + essconn: essconn, }, nil } @@ -123,3 +131,8 @@ func (c *Config) vpcConn() (*ecs.Client, error) { return client, nil } +func (c *Config) essConn() (*ess.Client, error) { + client := ess.NewESSClient(c.AccessKey, c.SecretKey, c.Region) + client.SetBusinessInfo(BusinessInfoKey) + return client, nil +} diff --git a/builtin/providers/alicloud/errors.go b/builtin/providers/alicloud/errors.go index 338525330..06d29642b 100644 --- a/builtin/providers/alicloud/errors.go +++ b/builtin/providers/alicloud/errors.go @@ -1,5 +1,7 @@ package alicloud +import "github.com/denverdino/aliyungo/common" + const ( // common Notfound = "Not found" @@ -25,7 +27,23 @@ const ( //Nat gateway NatGatewayInvalidRegionId = "Invalid.RegionId" DependencyViolationBandwidthPackages = "DependencyViolation.BandwidthPackages" + NotFindSnatEntryBySnatId = "NotFindSnatEntryBySnatId" + NotFindForwardEntryByForwardId = "NotFindForwardEntryByForwardId" // vswitch VswitcInvalidRegionId = "InvalidRegionId.NotFound" + + // ess + InvalidScalingGroupIdNotFound = "InvalidScalingGroupId.NotFound" + IncorrectScalingConfigurationLifecycleState = "IncorrectScalingConfigurationLifecycleState" ) + +func GetNotFoundErrorFromString(str string) error { + return &common.Error{ + ErrorResponse: common.ErrorResponse{ + Code: InstanceNotfound, + Message: str, + }, + StatusCode: -1, + } +} diff --git a/builtin/providers/alicloud/provider.go b/builtin/providers/alicloud/provider.go index 677c1c70d..fe3613014 100644 --- a/builtin/providers/alicloud/provider.go +++ b/builtin/providers/alicloud/provider.go @@ -38,18 +38,24 @@ func Provider() terraform.ResourceProvider { "alicloud_instance_types": dataSourceAlicloudInstanceTypes(), }, ResourcesMap: map[string]*schema.Resource{ - "alicloud_instance": resourceAliyunInstance(), - "alicloud_disk": resourceAliyunDisk(), - "alicloud_disk_attachment": resourceAliyunDiskAttachment(), - "alicloud_security_group": resourceAliyunSecurityGroup(), - "alicloud_security_group_rule": resourceAliyunSecurityGroupRule(), - "alicloud_db_instance": resourceAlicloudDBInstance(), - "alicloud_vpc": resourceAliyunVpc(), - "alicloud_nat_gateway": resourceAliyunNatGateway(), + "alicloud_instance": resourceAliyunInstance(), + "alicloud_disk": resourceAliyunDisk(), + "alicloud_disk_attachment": resourceAliyunDiskAttachment(), + "alicloud_security_group": resourceAliyunSecurityGroup(), + "alicloud_security_group_rule": resourceAliyunSecurityGroupRule(), + "alicloud_db_instance": resourceAlicloudDBInstance(), + "alicloud_ess_scaling_group": resourceAlicloudEssScalingGroup(), + "alicloud_ess_scaling_configuration": resourceAlicloudEssScalingConfiguration(), + "alicloud_ess_scaling_rule": resourceAlicloudEssScalingRule(), + "alicloud_ess_schedule": resourceAlicloudEssSchedule(), + "alicloud_vpc": resourceAliyunVpc(), + "alicloud_nat_gateway": resourceAliyunNatGateway(), //both subnet and vswith exists,cause compatible old version, and compatible aws habit. "alicloud_subnet": resourceAliyunSubnet(), "alicloud_vswitch": resourceAliyunSubnet(), "alicloud_route_entry": resourceAliyunRouteEntry(), + "alicloud_snat_entry": resourceAliyunSnatEntry(), + "alicloud_forward_entry": resourceAliyunForwardEntry(), "alicloud_eip": resourceAliyunEip(), "alicloud_eip_association": resourceAliyunEipAssociation(), "alicloud_slb": resourceAliyunSlb(), diff --git a/builtin/providers/alicloud/resource_alicloud_db_instance.go b/builtin/providers/alicloud/resource_alicloud_db_instance.go index c19aef165..062b5d0e1 100644 --- a/builtin/providers/alicloud/resource_alicloud_db_instance.go +++ b/builtin/providers/alicloud/resource_alicloud_db_instance.go @@ -218,7 +218,7 @@ func resourceAlicloudDBInstanceCreate(d *schema.ResourceData, meta interface{}) // wait instance status change from Creating to running if err := conn.WaitForInstance(d.Id(), rds.Running, defaultLongTimeout); err != nil { - log.Printf("[DEBUG] WaitForInstance %s got error: %#v", rds.Running, err) + return fmt.Errorf("WaitForInstance %s got error: %#v", rds.Running, err) } if err := modifySecurityIps(d.Id(), d.Get("security_ips"), meta); err != nil { @@ -386,6 +386,11 @@ func resourceAlicloudDBInstanceRead(d *schema.ResourceData, meta interface{}) er if err != nil { return err } + if resp.Databases.Database == nil { + d.SetId("") + return nil + } + d.Set("db_mappings", flattenDatabaseMappings(resp.Databases.Database)) argn := rds.DescribeDBInstanceNetInfoArgs{ diff --git a/builtin/providers/alicloud/resource_alicloud_db_instance_test.go b/builtin/providers/alicloud/resource_alicloud_db_instance_test.go index 8348e5089..498cc3ae1 100644 --- a/builtin/providers/alicloud/resource_alicloud_db_instance_test.go +++ b/builtin/providers/alicloud/resource_alicloud_db_instance_test.go @@ -535,7 +535,7 @@ func testAccCheckDBInstanceDestroy(s *terraform.State) error { client := testAccProvider.Meta().(*AliyunClient) for _, rs := range s.RootModule().Resources { - if rs.Type != "alicloud_db_instance.foo" { + if rs.Type != "alicloud_db_instance" { continue } diff --git a/builtin/providers/alicloud/resource_alicloud_eip.go b/builtin/providers/alicloud/resource_alicloud_eip.go index 8a0329eb8..f1c9621a8 100644 --- a/builtin/providers/alicloud/resource_alicloud_eip.go +++ b/builtin/providers/alicloud/resource_alicloud_eip.go @@ -78,7 +78,14 @@ func resourceAliyunEipRead(d *schema.ResourceData, meta interface{}) error { d.SetId("") return nil } - return err + return fmt.Errorf("Error Describe Eip Attribute: %#v", err) + } + + if eip.InstanceId != "" { + d.Set("instance", eip.InstanceId) + } else { + d.Set("instance", "") + return nil } bandwidth, _ := strconv.Atoi(eip.Bandwidth) @@ -87,12 +94,6 @@ func resourceAliyunEipRead(d *schema.ResourceData, meta interface{}) error { d.Set("ip_address", eip.IpAddress) d.Set("status", eip.Status) - if eip.InstanceId != "" { - d.Set("instance", eip.InstanceId) - } else { - d.Set("instance", "") - } - return nil } diff --git a/builtin/providers/alicloud/resource_alicloud_eip_association.go b/builtin/providers/alicloud/resource_alicloud_eip_association.go index a9d419ce1..5f492b40b 100644 --- a/builtin/providers/alicloud/resource_alicloud_eip_association.go +++ b/builtin/providers/alicloud/resource_alicloud_eip_association.go @@ -66,7 +66,7 @@ func resourceAliyunEipAssociationRead(d *schema.ResourceData, meta interface{}) d.SetId("") return nil } - return err + return fmt.Errorf("Error Describe Eip Attribute: %#v", err) } if eip.InstanceId != instanceId { diff --git a/builtin/providers/alicloud/resource_alicloud_ess_scalingconfiguration.go b/builtin/providers/alicloud/resource_alicloud_ess_scalingconfiguration.go new file mode 100644 index 000000000..3a8d94380 --- /dev/null +++ b/builtin/providers/alicloud/resource_alicloud_ess_scalingconfiguration.go @@ -0,0 +1,320 @@ +package alicloud + +import ( + "fmt" + "github.com/denverdino/aliyungo/common" + "github.com/denverdino/aliyungo/ecs" + "github.com/denverdino/aliyungo/ess" + "github.com/hashicorp/terraform/helper/resource" + "github.com/hashicorp/terraform/helper/schema" + "strings" + "time" +) + +func resourceAlicloudEssScalingConfiguration() *schema.Resource { + return &schema.Resource{ + Create: resourceAliyunEssScalingConfigurationCreate, + Read: resourceAliyunEssScalingConfigurationRead, + Update: resourceAliyunEssScalingConfigurationUpdate, + Delete: resourceAliyunEssScalingConfigurationDelete, + + Schema: map[string]*schema.Schema{ + "active": &schema.Schema{ + Type: schema.TypeBool, + Optional: true, + Computed: true, + }, + "enable": &schema.Schema{ + Type: schema.TypeBool, + Optional: true, + }, + "scaling_group_id": &schema.Schema{ + Type: schema.TypeString, + ForceNew: true, + Required: true, + }, + "image_id": &schema.Schema{ + Type: schema.TypeString, + ForceNew: true, + Required: true, + }, + "instance_type": &schema.Schema{ + Type: schema.TypeString, + ForceNew: true, + Required: true, + }, + "io_optimized": &schema.Schema{ + Type: schema.TypeString, + Required: true, + ForceNew: true, + ValidateFunc: validateIoOptimized, + }, + "security_group_id": &schema.Schema{ + Type: schema.TypeString, + ForceNew: true, + Required: true, + }, + "scaling_configuration_name": &schema.Schema{ + Type: schema.TypeString, + Optional: true, + Computed: true, + }, + "internet_charge_type": &schema.Schema{ + Type: schema.TypeString, + ForceNew: true, + Optional: true, + Computed: true, + ValidateFunc: validateInternetChargeType, + }, + "internet_max_bandwidth_in": &schema.Schema{ + Type: schema.TypeInt, + Optional: true, + ForceNew: true, + Computed: true, + }, + "internet_max_bandwidth_out": &schema.Schema{ + Type: schema.TypeInt, + Optional: true, + ForceNew: true, + ValidateFunc: validateInternetMaxBandWidthOut, + }, + "system_disk_category": &schema.Schema{ + Type: schema.TypeString, + Optional: true, + ForceNew: true, + Computed: true, + ValidateFunc: validateAllowedStringValue([]string{ + string(ecs.DiskCategoryCloud), + string(ecs.DiskCategoryCloudSSD), + string(ecs.DiskCategoryCloudEfficiency), + string(ecs.DiskCategoryEphemeralSSD), + }), + }, + "data_disk": &schema.Schema{ + Optional: true, + ForceNew: true, + Type: schema.TypeList, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "size": &schema.Schema{ + Type: schema.TypeInt, + Optional: true, + }, + "category": &schema.Schema{ + Type: schema.TypeString, + Optional: true, + }, + "snapshot_id": &schema.Schema{ + Type: schema.TypeString, + Optional: true, + }, + "device": &schema.Schema{ + Type: schema.TypeString, + Optional: true, + }, + }, + }, + }, + "instance_ids": &schema.Schema{ + Type: schema.TypeList, + Elem: &schema.Schema{Type: schema.TypeString}, + Optional: true, + MaxItems: 20, + }, + }, + } +} + +func resourceAliyunEssScalingConfigurationCreate(d *schema.ResourceData, meta interface{}) error { + + args, err := buildAlicloudEssScalingConfigurationArgs(d, meta) + if err != nil { + return err + } + + essconn := meta.(*AliyunClient).essconn + + scaling, err := essconn.CreateScalingConfiguration(args) + if err != nil { + return err + } + + d.SetId(d.Get("scaling_group_id").(string) + COLON_SEPARATED + scaling.ScalingConfigurationId) + + return resourceAliyunEssScalingConfigurationUpdate(d, meta) +} + +func resourceAliyunEssScalingConfigurationUpdate(d *schema.ResourceData, meta interface{}) error { + client := meta.(*AliyunClient) + if d.HasChange("active") { + active := d.Get("active").(bool) + if !active { + return fmt.Errorf("Please active the scaling configuration directly.") + } + ids := strings.Split(d.Id(), COLON_SEPARATED) + err := client.ActiveScalingConfigurationById(ids[0], ids[1]) + + if err != nil { + return fmt.Errorf("Active scaling configuration %s err: %#v", ids[1], err) + } + } + + if err := enableEssScalingConfiguration(d, meta); err != nil { + return err + } + + return resourceAliyunEssScalingConfigurationRead(d, meta) +} + +func enableEssScalingConfiguration(d *schema.ResourceData, meta interface{}) error { + client := meta.(*AliyunClient) + ids := strings.Split(d.Id(), COLON_SEPARATED) + + if d.HasChange("enable") { + d.SetPartial("enable") + enable := d.Get("enable").(bool) + if !enable { + err := client.DisableScalingConfigurationById(ids[0]) + + if err != nil { + return fmt.Errorf("Disable scaling group %s err: %#v", ids[0], err) + } + } + + instance_ids := []string{} + if d.HasChange("instance_ids") { + d.SetPartial("instance_ids") + instances := d.Get("instance_ids").([]interface{}) + instance_ids = expandStringList(instances) + } + err := client.EnableScalingConfigurationById(ids[0], ids[1], instance_ids) + + if err != nil { + return fmt.Errorf("Enable scaling configuration %s err: %#v", ids[1], err) + } + } + return nil +} + +func resourceAliyunEssScalingConfigurationRead(d *schema.ResourceData, meta interface{}) error { + + client := meta.(*AliyunClient) + ids := strings.Split(d.Id(), COLON_SEPARATED) + c, err := client.DescribeScalingConfigurationById(ids[0], ids[1]) + if err != nil { + if e, ok := err.(*common.Error); ok && e.Code == InstanceNotfound { + d.SetId("") + return nil + } + return fmt.Errorf("Error Describe ESS scaling configuration Attribute: %#v", err) + } + + d.Set("scaling_group_id", c.ScalingGroupId) + d.Set("active", c.LifecycleState == ess.Active) + d.Set("image_id", c.ImageId) + d.Set("instance_type", c.InstanceType) + d.Set("io_optimized", c.IoOptimized) + d.Set("security_group_id", c.SecurityGroupId) + d.Set("scaling_configuration_name", c.ScalingConfigurationName) + d.Set("internet_charge_type", c.InternetChargeType) + d.Set("internet_max_bandwidth_in", c.InternetMaxBandwidthIn) + d.Set("internet_max_bandwidth_out", c.InternetMaxBandwidthOut) + d.Set("system_disk_category", c.SystemDiskCategory) + d.Set("data_disk", flattenDataDiskMappings(c.DataDisks.DataDisk)) + + return nil +} + +func resourceAliyunEssScalingConfigurationDelete(d *schema.ResourceData, meta interface{}) error { + client := meta.(*AliyunClient) + + return resource.Retry(5*time.Minute, func() *resource.RetryError { + ids := strings.Split(d.Id(), COLON_SEPARATED) + err := client.DeleteScalingConfigurationById(ids[0], ids[1]) + + if err != nil { + e, _ := err.(*common.Error) + if e.ErrorResponse.Code == IncorrectScalingConfigurationLifecycleState { + return resource.NonRetryableError( + fmt.Errorf("Scaling configuration is active - please active another one and trying again.")) + } + if e.ErrorResponse.Code != InvalidScalingGroupIdNotFound { + return resource.RetryableError( + fmt.Errorf("Scaling configuration in use - trying again while it is deleted.")) + } + } + + _, err = client.DescribeScalingConfigurationById(ids[0], ids[1]) + if err != nil { + if notFoundError(err) { + return nil + } + return resource.NonRetryableError(err) + } + + return resource.RetryableError( + fmt.Errorf("Scaling configuration in use - trying again while it is deleted.")) + }) +} + +func buildAlicloudEssScalingConfigurationArgs(d *schema.ResourceData, meta interface{}) (*ess.CreateScalingConfigurationArgs, error) { + args := &ess.CreateScalingConfigurationArgs{ + ScalingGroupId: d.Get("scaling_group_id").(string), + ImageId: d.Get("image_id").(string), + InstanceType: d.Get("instance_type").(string), + IoOptimized: ecs.IoOptimized(d.Get("io_optimized").(string)), + SecurityGroupId: d.Get("security_group_id").(string), + } + + if v := d.Get("scaling_configuration_name").(string); v != "" { + args.ScalingConfigurationName = v + } + + if v := d.Get("internet_charge_type").(string); v != "" { + args.InternetChargeType = common.InternetChargeType(v) + } + + if v := d.Get("internet_max_bandwidth_in").(int); v != 0 { + args.InternetMaxBandwidthIn = v + } + + if v := d.Get("internet_max_bandwidth_out").(int); v != 0 { + args.InternetMaxBandwidthOut = v + } + + if v := d.Get("system_disk_category").(string); v != "" { + args.SystemDisk_Category = common.UnderlineString(v) + } + + dds, ok := d.GetOk("data_disk") + if ok { + disks := dds.([]interface{}) + diskTypes := []ess.DataDiskType{} + + for _, e := range disks { + pack := e.(map[string]interface{}) + disk := ess.DataDiskType{ + Size: pack["size"].(int), + Category: pack["category"].(string), + SnapshotId: pack["snapshot_id"].(string), + Device: pack["device"].(string), + } + if v := pack["size"].(int); v != 0 { + disk.Size = v + } + if v := pack["category"].(string); v != "" { + disk.Category = v + } + if v := pack["snapshot_id"].(string); v != "" { + disk.SnapshotId = v + } + if v := pack["device"].(string); v != "" { + disk.Device = v + } + diskTypes = append(diskTypes, disk) + } + args.DataDisk = diskTypes + } + + return args, nil +} diff --git a/builtin/providers/alicloud/resource_alicloud_ess_scalingconfiguration_test.go b/builtin/providers/alicloud/resource_alicloud_ess_scalingconfiguration_test.go new file mode 100644 index 000000000..4a2269b38 --- /dev/null +++ b/builtin/providers/alicloud/resource_alicloud_ess_scalingconfiguration_test.go @@ -0,0 +1,495 @@ +package alicloud + +import ( + "fmt" + "github.com/denverdino/aliyungo/common" + "github.com/denverdino/aliyungo/ess" + "github.com/hashicorp/terraform/helper/resource" + "github.com/hashicorp/terraform/terraform" + "log" + "regexp" + "strings" + "testing" +) + +func TestAccAlicloudEssScalingConfiguration_basic(t *testing.T) { + var sc ess.ScalingConfigurationItemType + + resource.Test(t, resource.TestCase{ + PreCheck: func() { + testAccPreCheck(t) + }, + + // module name + IDRefreshName: "alicloud_ess_scaling_configuration.foo", + + Providers: testAccProviders, + CheckDestroy: testAccCheckEssScalingConfigurationDestroy, + Steps: []resource.TestStep{ + resource.TestStep{ + Config: testAccEssScalingConfigurationConfig, + Check: resource.ComposeTestCheckFunc( + testAccCheckEssScalingConfigurationExists( + "alicloud_ess_scaling_configuration.foo", &sc), + resource.TestCheckResourceAttr( + "alicloud_ess_scaling_configuration.foo", + "instance_type", + "ecs.s2.large"), + resource.TestMatchResourceAttr( + "alicloud_ess_scaling_configuration.foo", + "image_id", + regexp.MustCompile("^centos_6")), + ), + }, + }, + }) +} + +func TestAccAlicloudEssScalingConfiguration_multiConfig(t *testing.T) { + var sc ess.ScalingConfigurationItemType + + resource.Test(t, resource.TestCase{ + PreCheck: func() { + testAccPreCheck(t) + }, + + // module name + IDRefreshName: "alicloud_ess_scaling_configuration.bar", + + Providers: testAccProviders, + CheckDestroy: testAccCheckEssScalingConfigurationDestroy, + Steps: []resource.TestStep{ + resource.TestStep{ + Config: testAccEssScalingConfiguration_multiConfig, + Check: resource.ComposeTestCheckFunc( + testAccCheckEssScalingConfigurationExists( + "alicloud_ess_scaling_configuration.bar", &sc), + resource.TestCheckResourceAttr( + "alicloud_ess_scaling_configuration.bar", + "active", + "false"), + resource.TestCheckResourceAttr( + "alicloud_ess_scaling_configuration.bar", + "instance_type", + "ecs.s2.large"), + resource.TestMatchResourceAttr( + "alicloud_ess_scaling_configuration.bar", + "image_id", + regexp.MustCompile("^centos_6")), + ), + }, + }, + }) +} + +func SkipTestAccAlicloudEssScalingConfiguration_active(t *testing.T) { + var sc ess.ScalingConfigurationItemType + + resource.Test(t, resource.TestCase{ + PreCheck: func() { + testAccPreCheck(t) + }, + + // module name + IDRefreshName: "alicloud_ess_scaling_configuration.bar", + + Providers: testAccProviders, + CheckDestroy: testAccCheckEssScalingConfigurationDestroy, + Steps: []resource.TestStep{ + resource.TestStep{ + Config: testAccEssScalingConfiguration_active, + Check: resource.ComposeTestCheckFunc( + testAccCheckEssScalingConfigurationExists( + "alicloud_ess_scaling_configuration.bar", &sc), + resource.TestCheckResourceAttr( + "alicloud_ess_scaling_configuration.bar", + "active", + "true"), + resource.TestCheckResourceAttr( + "alicloud_ess_scaling_configuration.bar", + "instance_type", + "ecs.s2.large"), + resource.TestMatchResourceAttr( + "alicloud_ess_scaling_configuration.bar", + "image_id", + regexp.MustCompile("^centos_6")), + ), + }, + + resource.TestStep{ + Config: testAccEssScalingConfiguration_inActive, + Check: resource.ComposeTestCheckFunc( + testAccCheckEssScalingConfigurationExists( + "alicloud_ess_scaling_configuration.bar", &sc), + resource.TestCheckResourceAttr( + "alicloud_ess_scaling_configuration.bar", + "active", + "false"), + resource.TestCheckResourceAttr( + "alicloud_ess_scaling_configuration.bar", + "instance_type", + "ecs.s2.large"), + resource.TestMatchResourceAttr( + "alicloud_ess_scaling_configuration.bar", + "image_id", + regexp.MustCompile("^centos_6")), + ), + }, + }, + }) +} + +func SkipTestAccAlicloudEssScalingConfiguration_enable(t *testing.T) { + var sc ess.ScalingConfigurationItemType + + resource.Test(t, resource.TestCase{ + PreCheck: func() { + testAccPreCheck(t) + }, + + // module name + IDRefreshName: "alicloud_ess_scaling_configuration.foo", + + Providers: testAccProviders, + CheckDestroy: testAccCheckEssScalingConfigurationDestroy, + Steps: []resource.TestStep{ + resource.TestStep{ + Config: testAccEssScalingConfiguration_enable, + Check: resource.ComposeTestCheckFunc( + testAccCheckEssScalingConfigurationExists( + "alicloud_ess_scaling_configuration.foo", &sc), + resource.TestCheckResourceAttr( + "alicloud_ess_scaling_configuration.foo", + "enable", + "true"), + resource.TestCheckResourceAttr( + "alicloud_ess_scaling_configuration.foo", + "instance_type", + "ecs.s2.large"), + resource.TestMatchResourceAttr( + "alicloud_ess_scaling_configuration.foo", + "image_id", + regexp.MustCompile("^centos_6")), + ), + }, + + resource.TestStep{ + Config: testAccEssScalingConfiguration_disable, + Check: resource.ComposeTestCheckFunc( + testAccCheckEssScalingConfigurationExists( + "alicloud_ess_scaling_configuration.foo", &sc), + resource.TestCheckResourceAttr( + "alicloud_ess_scaling_configuration.foo", + "enable", + "false"), + resource.TestCheckResourceAttr( + "alicloud_ess_scaling_configuration.foo", + "instance_type", + "ecs.s2.large"), + resource.TestMatchResourceAttr( + "alicloud_ess_scaling_configuration.foo", + "image_id", + regexp.MustCompile("^centos_6")), + ), + }, + }, + }) +} + +func testAccCheckEssScalingConfigurationExists(n string, d *ess.ScalingConfigurationItemType) resource.TestCheckFunc { + return func(s *terraform.State) error { + rs, ok := s.RootModule().Resources[n] + if !ok { + return fmt.Errorf("Not found: %s", n) + } + + if rs.Primary.ID == "" { + return fmt.Errorf("No ESS Scaling Configuration ID is set") + } + + client := testAccProvider.Meta().(*AliyunClient) + ids := strings.Split(rs.Primary.ID, COLON_SEPARATED) + attr, err := client.DescribeScalingConfigurationById(ids[0], ids[1]) + log.Printf("[DEBUG] check scaling configuration %s attribute %#v", rs.Primary.ID, attr) + + if err != nil { + return err + } + + if attr == nil { + return fmt.Errorf("Scaling Configuration not found") + } + + *d = *attr + return nil + } +} + +func testAccCheckEssScalingConfigurationDestroy(s *terraform.State) error { + client := testAccProvider.Meta().(*AliyunClient) + + for _, rs := range s.RootModule().Resources { + if rs.Type != "alicloud_ess_scaling_configuration" { + continue + } + ids := strings.Split(rs.Primary.ID, COLON_SEPARATED) + ins, err := client.DescribeScalingConfigurationById(ids[0], ids[1]) + + if ins != nil { + return fmt.Errorf("Error ESS scaling configuration still exist") + } + + // Verify the error is what we want + if err != nil { + // Verify the error is what we want + e, _ := err.(*common.Error) + if e.ErrorResponse.Code == InstanceNotfound { + continue + } + return err + } + } + + return nil +} + +const testAccEssScalingConfigurationConfig = ` +data "alicloud_images" "ecs_image" { + most_recent = true + name_regex = "^centos_6\\w{1,5}[64].*" +} + +resource "alicloud_security_group" "tf_test_foo" { + description = "foo" +} + +resource "alicloud_security_group_rule" "ssh-in" { + type = "ingress" + ip_protocol = "tcp" + nic_type = "internet" + policy = "accept" + port_range = "22/22" + priority = 1 + security_group_id = "${alicloud_security_group.tf_test_foo.id}" + cidr_ip = "0.0.0.0/0" +} + +resource "alicloud_ess_scaling_group" "foo" { + min_size = 1 + max_size = 1 + scaling_group_name = "foo" + removal_policies = ["OldestInstance", "NewestInstance"] +} + +resource "alicloud_ess_scaling_configuration" "foo" { + scaling_group_id = "${alicloud_ess_scaling_group.foo.id}" + + image_id = "${data.alicloud_images.ecs_image.images.0.id}" + instance_type = "ecs.s2.large" + io_optimized = "optimized" + security_group_id = "${alicloud_security_group.tf_test_foo.id}" +} +` + +const testAccEssScalingConfiguration_multiConfig = ` +data "alicloud_images" "ecs_image" { + most_recent = true + name_regex = "^centos_6\\w{1,5}[64].*" +} + +resource "alicloud_security_group" "tf_test_foo" { + description = "foo" +} + +resource "alicloud_security_group_rule" "ssh-in" { + type = "ingress" + ip_protocol = "tcp" + nic_type = "internet" + policy = "accept" + port_range = "22/22" + priority = 1 + security_group_id = "${alicloud_security_group.tf_test_foo.id}" + cidr_ip = "0.0.0.0/0" +} + +resource "alicloud_ess_scaling_group" "foo" { + min_size = 1 + max_size = 1 + scaling_group_name = "foo" + removal_policies = ["OldestInstance", "NewestInstance"] +} + +resource "alicloud_ess_scaling_configuration" "foo" { + scaling_group_id = "${alicloud_ess_scaling_group.foo.id}" + + image_id = "${data.alicloud_images.ecs_image.images.0.id}" + instance_type = "ecs.s2.large" + io_optimized = "optimized" + security_group_id = "${alicloud_security_group.tf_test_foo.id}" +} + +resource "alicloud_ess_scaling_configuration" "bar" { + scaling_group_id = "${alicloud_ess_scaling_group.foo.id}" + + image_id = "${data.alicloud_images.ecs_image.images.0.id}" + instance_type = "ecs.s2.large" + io_optimized = "optimized" + security_group_id = "${alicloud_security_group.tf_test_foo.id}" +} +` + +const testAccEssScalingConfiguration_active = ` +data "alicloud_images" "ecs_image" { + most_recent = true + name_regex = "^centos_6\\w{1,5}[64].*" +} + +resource "alicloud_security_group" "tf_test_foo" { + description = "foo" +} + +resource "alicloud_security_group_rule" "ssh-in" { + type = "ingress" + ip_protocol = "tcp" + nic_type = "internet" + policy = "accept" + port_range = "22/22" + priority = 1 + security_group_id = "${alicloud_security_group.tf_test_foo.id}" + cidr_ip = "0.0.0.0/0" +} + +resource "alicloud_ess_scaling_group" "foo" { + min_size = 1 + max_size = 1 + scaling_group_name = "foo" + removal_policies = ["OldestInstance", "NewestInstance"] +} + +resource "alicloud_ess_scaling_configuration" "foo" { + scaling_group_id = "${alicloud_ess_scaling_group.foo.id}" + active = true + + image_id = "${data.alicloud_images.ecs_image.images.0.id}" + instance_type = "ecs.s2.large" + io_optimized = "optimized" + security_group_id = "${alicloud_security_group.tf_test_foo.id}" +} +` + +const testAccEssScalingConfiguration_inActive = ` +data "alicloud_images" "ecs_image" { + most_recent = true + name_regex = "^centos_6\\w{1,5}[64].*" +} + +resource "alicloud_security_group" "tf_test_foo" { + description = "foo" +} + +resource "alicloud_security_group_rule" "ssh-in" { + type = "ingress" + ip_protocol = "tcp" + nic_type = "internet" + policy = "accept" + port_range = "22/22" + priority = 1 + security_group_id = "${alicloud_security_group.tf_test_foo.id}" + cidr_ip = "0.0.0.0/0" +} + +resource "alicloud_ess_scaling_group" "foo" { + min_size = 1 + max_size = 1 + scaling_group_name = "foo" + removal_policies = ["OldestInstance", "NewestInstance"] +} + +resource "alicloud_ess_scaling_configuration" "foo" { + scaling_group_id = "${alicloud_ess_scaling_group.foo.id}" + active = false + + image_id = "${data.alicloud_images.ecs_image.images.0.id}" + instance_type = "ecs.s2.large" + io_optimized = "optimized" + security_group_id = "${alicloud_security_group.tf_test_foo.id}" +} +` + +const testAccEssScalingConfiguration_enable = ` +data "alicloud_images" "ecs_image" { + most_recent = true + name_regex = "^centos_6\\w{1,5}[64].*" +} + +resource "alicloud_security_group" "tf_test_foo" { + description = "foo" +} + +resource "alicloud_security_group_rule" "ssh-in" { + type = "ingress" + ip_protocol = "tcp" + nic_type = "internet" + policy = "accept" + port_range = "22/22" + priority = 1 + security_group_id = "${alicloud_security_group.tf_test_foo.id}" + cidr_ip = "0.0.0.0/0" +} + +resource "alicloud_ess_scaling_group" "foo" { + min_size = 1 + max_size = 1 + scaling_group_name = "foo" + removal_policies = ["OldestInstance", "NewestInstance"] +} + +resource "alicloud_ess_scaling_configuration" "foo" { + scaling_group_id = "${alicloud_ess_scaling_group.foo.id}" + enable = true + + image_id = "${data.alicloud_images.ecs_image.images.0.id}" + instance_type = "ecs.s2.large" + io_optimized = "optimized" + security_group_id = "${alicloud_security_group.tf_test_foo.id}" +} +` + +const testAccEssScalingConfiguration_disable = ` +data "alicloud_images" "ecs_image" { + most_recent = true + name_regex = "^centos_6\\w{1,5}[64].*" +} + +resource "alicloud_security_group" "tf_test_foo" { + description = "foo" +} + +resource "alicloud_security_group_rule" "ssh-in" { + type = "ingress" + ip_protocol = "tcp" + nic_type = "internet" + policy = "accept" + port_range = "22/22" + priority = 1 + security_group_id = "${alicloud_security_group.tf_test_foo.id}" + cidr_ip = "0.0.0.0/0" +} + +resource "alicloud_ess_scaling_group" "foo" { + min_size = 1 + max_size = 1 + scaling_group_name = "foo" + removal_policies = ["OldestInstance", "NewestInstance"] +} + +resource "alicloud_ess_scaling_configuration" "foo" { + scaling_group_id = "${alicloud_ess_scaling_group.foo.id}" + enable = false + + image_id = "${data.alicloud_images.ecs_image.images.0.id}" + instance_type = "ecs.s2.large" + io_optimized = "optimized" + security_group_id = "${alicloud_security_group.tf_test_foo.id}" +} +` diff --git a/builtin/providers/alicloud/resource_alicloud_ess_scalinggroup.go b/builtin/providers/alicloud/resource_alicloud_ess_scalinggroup.go new file mode 100644 index 000000000..89f4154db --- /dev/null +++ b/builtin/providers/alicloud/resource_alicloud_ess_scalinggroup.go @@ -0,0 +1,209 @@ +package alicloud + +import ( + "fmt" + "github.com/denverdino/aliyungo/common" + "github.com/denverdino/aliyungo/ess" + "github.com/hashicorp/terraform/helper/resource" + "github.com/hashicorp/terraform/helper/schema" + "strings" + "time" +) + +func resourceAlicloudEssScalingGroup() *schema.Resource { + return &schema.Resource{ + Create: resourceAliyunEssScalingGroupCreate, + Read: resourceAliyunEssScalingGroupRead, + Update: resourceAliyunEssScalingGroupUpdate, + Delete: resourceAliyunEssScalingGroupDelete, + + Schema: map[string]*schema.Schema{ + "min_size": &schema.Schema{ + Type: schema.TypeInt, + Required: true, + ValidateFunc: validateIntegerInRange(0, 100), + }, + "max_size": &schema.Schema{ + Type: schema.TypeInt, + Required: true, + ValidateFunc: validateIntegerInRange(0, 100), + }, + "scaling_group_name": &schema.Schema{ + Type: schema.TypeString, + Optional: true, + }, + "default_cooldown": &schema.Schema{ + Type: schema.TypeInt, + Default: 300, + Optional: true, + ValidateFunc: validateIntegerInRange(0, 86400), + }, + "vswitch_id": &schema.Schema{ + Type: schema.TypeString, + Optional: true, + }, + "removal_policies": &schema.Schema{ + Type: schema.TypeList, + Elem: &schema.Schema{Type: schema.TypeString}, + Optional: true, + MaxItems: 2, + }, + "db_instance_ids": &schema.Schema{ + Type: schema.TypeList, + Elem: &schema.Schema{Type: schema.TypeString}, + Optional: true, + MaxItems: 3, + }, + "loadbalancer_ids": &schema.Schema{ + Type: schema.TypeList, + Elem: &schema.Schema{Type: schema.TypeString}, + Optional: true, + }, + }, + } +} + +func resourceAliyunEssScalingGroupCreate(d *schema.ResourceData, meta interface{}) error { + + args, err := buildAlicloudEssScalingGroupArgs(d, meta) + if err != nil { + return err + } + + essconn := meta.(*AliyunClient).essconn + + scaling, err := essconn.CreateScalingGroup(args) + if err != nil { + return err + } + + d.SetId(scaling.ScalingGroupId) + + return resourceAliyunEssScalingGroupUpdate(d, meta) +} + +func resourceAliyunEssScalingGroupRead(d *schema.ResourceData, meta interface{}) error { + + client := meta.(*AliyunClient) + + scaling, err := client.DescribeScalingGroupById(d.Id()) + if err != nil { + if e, ok := err.(*common.Error); ok && e.Code == InstanceNotfound { + d.SetId("") + return nil + } + return fmt.Errorf("Error Describe ESS scaling group Attribute: %#v", err) + } + + d.Set("min_size", scaling.MinSize) + d.Set("max_size", scaling.MaxSize) + d.Set("scaling_group_name", scaling.ScalingGroupName) + d.Set("default_cooldown", scaling.DefaultCooldown) + d.Set("removal_policies", scaling.RemovalPolicies) + d.Set("db_instance_ids", scaling.DBInstanceIds) + d.Set("loadbalancer_ids", scaling.LoadBalancerId) + + return nil +} + +func resourceAliyunEssScalingGroupUpdate(d *schema.ResourceData, meta interface{}) error { + + conn := meta.(*AliyunClient).essconn + args := &ess.ModifyScalingGroupArgs{ + ScalingGroupId: d.Id(), + } + + if d.HasChange("scaling_group_name") { + args.ScalingGroupName = d.Get("scaling_group_name").(string) + } + + if d.HasChange("min_size") { + args.MinSize = d.Get("min_size").(int) + } + + if d.HasChange("max_size") { + args.MaxSize = d.Get("max_size").(int) + } + + if d.HasChange("default_cooldown") { + args.DefaultCooldown = d.Get("default_cooldown").(int) + } + + if d.HasChange("removal_policies") { + policyStrings := d.Get("removal_policies").([]interface{}) + args.RemovalPolicy = expandStringList(policyStrings) + } + + if _, err := conn.ModifyScalingGroup(args); err != nil { + return err + } + + return resourceAliyunEssScalingGroupRead(d, meta) +} + +func resourceAliyunEssScalingGroupDelete(d *schema.ResourceData, meta interface{}) error { + client := meta.(*AliyunClient) + + return resource.Retry(2*time.Minute, func() *resource.RetryError { + err := client.DeleteScalingGroupById(d.Id()) + + if err != nil { + e, _ := err.(*common.Error) + if e.ErrorResponse.Code != InvalidScalingGroupIdNotFound { + return resource.RetryableError(fmt.Errorf("Scaling group in use - trying again while it is deleted.")) + } + } + + _, err = client.DescribeScalingGroupById(d.Id()) + if err != nil { + if notFoundError(err) { + return nil + } + return resource.NonRetryableError(err) + } + + return resource.RetryableError(fmt.Errorf("Scaling group in use - trying again while it is deleted.")) + }) +} + +func buildAlicloudEssScalingGroupArgs(d *schema.ResourceData, meta interface{}) (*ess.CreateScalingGroupArgs, error) { + client := meta.(*AliyunClient) + args := &ess.CreateScalingGroupArgs{ + RegionId: getRegion(d, meta), + MinSize: d.Get("min_size").(int), + MaxSize: d.Get("max_size").(int), + DefaultCooldown: d.Get("default_cooldown").(int), + } + + if v := d.Get("scaling_group_name").(string); v != "" { + args.ScalingGroupName = v + } + + if v := d.Get("vswitch_id").(string); v != "" { + args.VSwitchId = v + + // get vpcId + vpcId, err := client.GetVpcIdByVSwitchId(v) + + if err != nil { + return nil, fmt.Errorf("VswitchId %s is not valid of current region", v) + } + // fill vpcId by vswitchId + args.VpcId = vpcId + + } + + dbs, ok := d.GetOk("db_instance_ids") + if ok { + dbsStrings := dbs.([]interface{}) + args.DBInstanceId = expandStringList(dbsStrings) + } + + lbs, ok := d.GetOk("loadbalancer_ids") + if ok { + lbsStrings := lbs.([]interface{}) + args.LoadBalancerId = strings.Join(expandStringList(lbsStrings), COMMA_SEPARATED) + } + + return args, nil +} diff --git a/builtin/providers/alicloud/resource_alicloud_ess_scalinggroup_test.go b/builtin/providers/alicloud/resource_alicloud_ess_scalinggroup_test.go new file mode 100644 index 000000000..e707035b1 --- /dev/null +++ b/builtin/providers/alicloud/resource_alicloud_ess_scalinggroup_test.go @@ -0,0 +1,297 @@ +package alicloud + +import ( + "fmt" + "github.com/denverdino/aliyungo/common" + "github.com/denverdino/aliyungo/ess" + "github.com/hashicorp/terraform/helper/resource" + "github.com/hashicorp/terraform/terraform" + "log" + "testing" +) + +func TestAccAlicloudEssScalingGroup_basic(t *testing.T) { + var sg ess.ScalingGroupItemType + + resource.Test(t, resource.TestCase{ + PreCheck: func() { + testAccPreCheck(t) + }, + + // module name + IDRefreshName: "alicloud_ess_scaling_group.foo", + + Providers: testAccProviders, + CheckDestroy: testAccCheckEssScalingGroupDestroy, + Steps: []resource.TestStep{ + resource.TestStep{ + Config: testAccEssScalingGroupConfig, + Check: resource.ComposeTestCheckFunc( + testAccCheckEssScalingGroupExists( + "alicloud_ess_scaling_group.foo", &sg), + resource.TestCheckResourceAttr( + "alicloud_ess_scaling_group.foo", + "min_size", + "1"), + resource.TestCheckResourceAttr( + "alicloud_ess_scaling_group.foo", + "max_size", + "1"), + resource.TestCheckResourceAttr( + "alicloud_ess_scaling_group.foo", + "scaling_group_name", + "foo"), + resource.TestCheckResourceAttr( + "alicloud_ess_scaling_group.foo", + "removal_policies.#", + "2", + ), + ), + }, + }, + }) + +} + +func TestAccAlicloudEssScalingGroup_update(t *testing.T) { + var sg ess.ScalingGroupItemType + + resource.Test(t, resource.TestCase{ + PreCheck: func() { + testAccPreCheck(t) + }, + + // module name + IDRefreshName: "alicloud_ess_scaling_group.foo", + + Providers: testAccProviders, + CheckDestroy: testAccCheckEssScalingGroupDestroy, + Steps: []resource.TestStep{ + resource.TestStep{ + Config: testAccEssScalingGroup, + Check: resource.ComposeTestCheckFunc( + testAccCheckEssScalingGroupExists( + "alicloud_ess_scaling_group.foo", &sg), + resource.TestCheckResourceAttr( + "alicloud_ess_scaling_group.foo", + "min_size", + "1"), + resource.TestCheckResourceAttr( + "alicloud_ess_scaling_group.foo", + "max_size", + "1"), + resource.TestCheckResourceAttr( + "alicloud_ess_scaling_group.foo", + "scaling_group_name", + "foo"), + resource.TestCheckResourceAttr( + "alicloud_ess_scaling_group.foo", + "removal_policies.#", + "2", + ), + ), + }, + + resource.TestStep{ + Config: testAccEssScalingGroup_update, + Check: resource.ComposeTestCheckFunc( + testAccCheckEssScalingGroupExists( + "alicloud_ess_scaling_group.foo", &sg), + resource.TestCheckResourceAttr( + "alicloud_ess_scaling_group.foo", + "min_size", + "2"), + resource.TestCheckResourceAttr( + "alicloud_ess_scaling_group.foo", + "max_size", + "2"), + resource.TestCheckResourceAttr( + "alicloud_ess_scaling_group.foo", + "scaling_group_name", + "update"), + resource.TestCheckResourceAttr( + "alicloud_ess_scaling_group.foo", + "removal_policies.#", + "1", + ), + ), + }, + }, + }) + +} + +func SkipTestAccAlicloudEssScalingGroup_vpc(t *testing.T) { + var sg ess.ScalingGroupItemType + + resource.Test(t, resource.TestCase{ + PreCheck: func() { + testAccPreCheck(t) + }, + + // module name + IDRefreshName: "alicloud_ess_scaling_group.foo", + + Providers: testAccProviders, + CheckDestroy: testAccCheckEssScalingGroupDestroy, + Steps: []resource.TestStep{ + resource.TestStep{ + Config: testAccEssScalingGroup_vpc, + Check: resource.ComposeTestCheckFunc( + testAccCheckEssScalingGroupExists( + "alicloud_ess_scaling_group.foo", &sg), + resource.TestCheckResourceAttr( + "alicloud_ess_scaling_group.foo", + "min_size", + "1"), + resource.TestCheckResourceAttr( + "alicloud_ess_scaling_group.foo", + "max_size", + "1"), + resource.TestCheckResourceAttr( + "alicloud_ess_scaling_group.foo", + "scaling_group_name", + "foo"), + resource.TestCheckResourceAttr( + "alicloud_ess_scaling_group.foo", + "removal_policies.#", + "2", + ), + ), + }, + }, + }) + +} + +func testAccCheckEssScalingGroupExists(n string, d *ess.ScalingGroupItemType) resource.TestCheckFunc { + return func(s *terraform.State) error { + rs, ok := s.RootModule().Resources[n] + if !ok { + return fmt.Errorf("Not found: %s", n) + } + + if rs.Primary.ID == "" { + return fmt.Errorf("No ESS Scaling Group ID is set") + } + + client := testAccProvider.Meta().(*AliyunClient) + attr, err := client.DescribeScalingGroupById(rs.Primary.ID) + log.Printf("[DEBUG] check scaling group %s attribute %#v", rs.Primary.ID, attr) + + if err != nil { + return err + } + + if attr == nil { + return fmt.Errorf("Scaling Group not found") + } + + *d = *attr + return nil + } +} + +func testAccCheckEssScalingGroupDestroy(s *terraform.State) error { + client := testAccProvider.Meta().(*AliyunClient) + + for _, rs := range s.RootModule().Resources { + if rs.Type != "alicloud_ess_scaling_group" { + continue + } + + ins, err := client.DescribeScalingGroupById(rs.Primary.ID) + + if ins != nil { + return fmt.Errorf("Error ESS scaling group still exist") + } + + // Verify the error is what we want + if err != nil { + // Verify the error is what we want + e, _ := err.(*common.Error) + if e.ErrorResponse.Code == InstanceNotfound { + continue + } + return err + } + } + + return nil +} + +const testAccEssScalingGroupConfig = ` +resource "alicloud_ess_scaling_group" "foo" { + min_size = 1 + max_size = 1 + scaling_group_name = "foo" + removal_policies = ["OldestInstance", "NewestInstance"] +} +` + +const testAccEssScalingGroup = ` +resource "alicloud_ess_scaling_group" "foo" { + min_size = 1 + max_size = 1 + scaling_group_name = "foo" + removal_policies = ["OldestInstance", "NewestInstance"] +} +` + +const testAccEssScalingGroup_update = ` +resource "alicloud_ess_scaling_group" "foo" { + min_size = 2 + max_size = 2 + scaling_group_name = "update" + removal_policies = ["OldestInstance"] +} +` +const testAccEssScalingGroup_vpc = ` +data "alicloud_images" "ecs_image" { + most_recent = true + name_regex = "^centos_6\\w{1,5}[64].*" +} + +data "alicloud_zones" "default" { + "available_disk_category"= "cloud_efficiency" + "available_resource_creation"= "VSwitch" +} + +resource "alicloud_vpc" "foo" { + name = "tf_test_foo" + cidr_block = "172.16.0.0/12" +} + +resource "alicloud_vswitch" "foo" { + vpc_id = "${alicloud_vpc.foo.id}" + cidr_block = "172.16.0.0/21" + availability_zone = "${data.alicloud_zones.default.zones.0.id}" +} + +resource "alicloud_security_group" "tf_test_foo" { + description = "foo" + vpc_id = "${alicloud_vpc.foo.id}" +} + +resource "alicloud_ess_scaling_group" "foo" { + min_size = 1 + max_size = 1 + scaling_group_name = "foo" + default_cooldown = 20 + vswitch_id = "${alicloud_vswitch.foo.id}" + removal_policies = ["OldestInstance", "NewestInstance"] +} + +resource "alicloud_ess_scaling_configuration" "foo" { + scaling_group_id = "${alicloud_ess_scaling_group.foo.id}" + enable = true + + image_id = "${data.alicloud_images.ecs_image.images.0.id}" + instance_type = "ecs.n1.medium" + io_optimized = "optimized" + system_disk_category = "cloud_efficiency" + internet_charge_type = "PayByTraffic" + internet_max_bandwidth_out = 10 + security_group_id = "${alicloud_security_group.tf_test_foo.id}" +} +` diff --git a/builtin/providers/alicloud/resource_alicloud_ess_scalingrule.go b/builtin/providers/alicloud/resource_alicloud_ess_scalingrule.go new file mode 100644 index 000000000..bfa1f904f --- /dev/null +++ b/builtin/providers/alicloud/resource_alicloud_ess_scalingrule.go @@ -0,0 +1,168 @@ +package alicloud + +import ( + "fmt" + "github.com/denverdino/aliyungo/common" + "github.com/denverdino/aliyungo/ess" + "github.com/hashicorp/terraform/helper/resource" + "github.com/hashicorp/terraform/helper/schema" + "strings" + "time" +) + +func resourceAlicloudEssScalingRule() *schema.Resource { + return &schema.Resource{ + Create: resourceAliyunEssScalingRuleCreate, + Read: resourceAliyunEssScalingRuleRead, + Update: resourceAliyunEssScalingRuleUpdate, + Delete: resourceAliyunEssScalingRuleDelete, + + Schema: map[string]*schema.Schema{ + "scaling_group_id": &schema.Schema{ + Type: schema.TypeString, + Required: true, + }, + "adjustment_type": &schema.Schema{ + Type: schema.TypeString, + Required: true, + ValidateFunc: validateAllowedStringValue([]string{string(ess.QuantityChangeInCapacity), + string(ess.PercentChangeInCapacity), string(ess.TotalCapacity)}), + }, + "adjustment_value": &schema.Schema{ + Type: schema.TypeInt, + Required: true, + }, + "scaling_rule_name": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Optional: true, + }, + "ari": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + }, + "cooldown": &schema.Schema{ + Type: schema.TypeInt, + Optional: true, + ValidateFunc: validateIntegerInRange(0, 86400), + }, + }, + } +} + +func resourceAliyunEssScalingRuleCreate(d *schema.ResourceData, meta interface{}) error { + + args, err := buildAlicloudEssScalingRuleArgs(d, meta) + if err != nil { + return err + } + + essconn := meta.(*AliyunClient).essconn + + rule, err := essconn.CreateScalingRule(args) + if err != nil { + return err + } + + d.SetId(d.Get("scaling_group_id").(string) + COLON_SEPARATED + rule.ScalingRuleId) + + return resourceAliyunEssScalingRuleUpdate(d, meta) +} + +func resourceAliyunEssScalingRuleRead(d *schema.ResourceData, meta interface{}) error { + + client := meta.(*AliyunClient) + ids := strings.Split(d.Id(), COLON_SEPARATED) + + rule, err := client.DescribeScalingRuleById(ids[0], ids[1]) + if err != nil { + if e, ok := err.(*common.Error); ok && e.Code == InstanceNotfound { + d.SetId("") + return nil + } + return fmt.Errorf("Error Describe ESS scaling rule Attribute: %#v", err) + } + + d.Set("scaling_group_id", rule.ScalingGroupId) + d.Set("ari", rule.ScalingRuleAri) + d.Set("adjustment_type", rule.AdjustmentType) + d.Set("adjustment_value", rule.AdjustmentValue) + d.Set("scaling_rule_name", rule.ScalingRuleName) + d.Set("cooldown", rule.Cooldown) + + return nil +} + +func resourceAliyunEssScalingRuleDelete(d *schema.ResourceData, meta interface{}) error { + client := meta.(*AliyunClient) + ids := strings.Split(d.Id(), COLON_SEPARATED) + + return resource.Retry(2*time.Minute, func() *resource.RetryError { + err := client.DeleteScalingRuleById(ids[1]) + + if err != nil { + return resource.RetryableError(fmt.Errorf("Scaling rule in use - trying again while it is deleted.")) + } + + _, err = client.DescribeScalingRuleById(ids[0], ids[1]) + if err != nil { + if notFoundError(err) { + return nil + } + return resource.NonRetryableError(err) + } + + return resource.RetryableError(fmt.Errorf("Scaling rule in use - trying again while it is deleted.")) + }) +} + +func resourceAliyunEssScalingRuleUpdate(d *schema.ResourceData, meta interface{}) error { + + conn := meta.(*AliyunClient).essconn + ids := strings.Split(d.Id(), COLON_SEPARATED) + + args := &ess.ModifyScalingRuleArgs{ + ScalingRuleId: ids[1], + } + + if d.HasChange("adjustment_type") { + args.AdjustmentType = ess.AdjustmentType(d.Get("adjustment_type").(string)) + } + + if d.HasChange("adjustment_value") { + args.AdjustmentValue = d.Get("adjustment_value").(int) + } + + if d.HasChange("scaling_rule_name") { + args.ScalingRuleName = d.Get("scaling_rule_name").(string) + } + + if d.HasChange("cooldown") { + args.Cooldown = d.Get("cooldown").(int) + } + + if _, err := conn.ModifyScalingRule(args); err != nil { + return err + } + + return resourceAliyunEssScalingRuleRead(d, meta) +} + +func buildAlicloudEssScalingRuleArgs(d *schema.ResourceData, meta interface{}) (*ess.CreateScalingRuleArgs, error) { + args := &ess.CreateScalingRuleArgs{ + RegionId: getRegion(d, meta), + ScalingGroupId: d.Get("scaling_group_id").(string), + AdjustmentType: ess.AdjustmentType(d.Get("adjustment_type").(string)), + AdjustmentValue: d.Get("adjustment_value").(int), + } + + if v := d.Get("scaling_rule_name").(string); v != "" { + args.ScalingRuleName = v + } + + if v := d.Get("cooldown").(int); v != 0 { + args.Cooldown = v + } + + return args, nil +} diff --git a/builtin/providers/alicloud/resource_alicloud_ess_scalingrule_test.go b/builtin/providers/alicloud/resource_alicloud_ess_scalingrule_test.go new file mode 100644 index 000000000..81020a747 --- /dev/null +++ b/builtin/providers/alicloud/resource_alicloud_ess_scalingrule_test.go @@ -0,0 +1,290 @@ +package alicloud + +import ( + "fmt" + "github.com/denverdino/aliyungo/common" + "github.com/denverdino/aliyungo/ess" + "github.com/hashicorp/terraform/helper/resource" + "github.com/hashicorp/terraform/terraform" + "log" + "strings" + "testing" +) + +func TestAccAlicloudEssScalingRule_basic(t *testing.T) { + var sc ess.ScalingRuleItemType + + resource.Test(t, resource.TestCase{ + PreCheck: func() { + testAccPreCheck(t) + }, + + // module name + IDRefreshName: "alicloud_ess_scaling_rule.foo", + + Providers: testAccProviders, + CheckDestroy: testAccCheckEssScalingRuleDestroy, + Steps: []resource.TestStep{ + resource.TestStep{ + Config: testAccEssScalingRuleConfig, + Check: resource.ComposeTestCheckFunc( + testAccCheckEssScalingRuleExists( + "alicloud_ess_scaling_rule.foo", &sc), + resource.TestCheckResourceAttr( + "alicloud_ess_scaling_rule.foo", + "adjustment_type", + "TotalCapacity"), + resource.TestCheckResourceAttr( + "alicloud_ess_scaling_rule.foo", + "adjustment_value", + "1"), + ), + }, + }, + }) +} + +func TestAccAlicloudEssScalingRule_update(t *testing.T) { + var sc ess.ScalingRuleItemType + + resource.Test(t, resource.TestCase{ + PreCheck: func() { + testAccPreCheck(t) + }, + + // module name + IDRefreshName: "alicloud_ess_scaling_rule.foo", + + Providers: testAccProviders, + CheckDestroy: testAccCheckEssScalingRuleDestroy, + Steps: []resource.TestStep{ + resource.TestStep{ + Config: testAccEssScalingRule, + Check: resource.ComposeTestCheckFunc( + testAccCheckEssScalingRuleExists( + "alicloud_ess_scaling_rule.foo", &sc), + testAccCheckEssScalingRuleExists( + "alicloud_ess_scaling_rule.foo", &sc), + resource.TestCheckResourceAttr( + "alicloud_ess_scaling_rule.foo", + "adjustment_type", + "TotalCapacity"), + resource.TestCheckResourceAttr( + "alicloud_ess_scaling_rule.foo", + "adjustment_value", + "1"), + ), + }, + + resource.TestStep{ + Config: testAccEssScalingRule_update, + Check: resource.ComposeTestCheckFunc( + testAccCheckEssScalingRuleExists( + "alicloud_ess_scaling_rule.foo", &sc), + testAccCheckEssScalingRuleExists( + "alicloud_ess_scaling_rule.foo", &sc), + resource.TestCheckResourceAttr( + "alicloud_ess_scaling_rule.foo", + "adjustment_type", + "TotalCapacity"), + resource.TestCheckResourceAttr( + "alicloud_ess_scaling_rule.foo", + "adjustment_value", + "2"), + ), + }, + }, + }) +} + +func testAccCheckEssScalingRuleExists(n string, d *ess.ScalingRuleItemType) resource.TestCheckFunc { + return func(s *terraform.State) error { + rs, ok := s.RootModule().Resources[n] + if !ok { + return fmt.Errorf("Not found: %s", n) + } + + if rs.Primary.ID == "" { + return fmt.Errorf("No ESS Scaling Rule ID is set") + } + + client := testAccProvider.Meta().(*AliyunClient) + ids := strings.Split(rs.Primary.ID, COLON_SEPARATED) + attr, err := client.DescribeScalingRuleById(ids[0], ids[1]) + log.Printf("[DEBUG] check scaling rule %s attribute %#v", rs.Primary.ID, attr) + + if err != nil { + return err + } + + if attr == nil { + return fmt.Errorf("Scaling rule not found") + } + + *d = *attr + return nil + } +} + +func testAccCheckEssScalingRuleDestroy(s *terraform.State) error { + client := testAccProvider.Meta().(*AliyunClient) + + for _, rs := range s.RootModule().Resources { + if rs.Type != "alicloud_ess_scaling_rule" { + continue + } + ids := strings.Split(rs.Primary.ID, COLON_SEPARATED) + ins, err := client.DescribeScalingRuleById(ids[0], ids[1]) + + if ins != nil { + return fmt.Errorf("Error ESS scaling rule still exist") + } + + // Verify the error is what we want + if err != nil { + // Verify the error is what we want + e, _ := err.(*common.Error) + if e.ErrorResponse.Code == InstanceNotfound { + continue + } + return err + } + } + + return nil +} + +const testAccEssScalingRuleConfig = ` +data "alicloud_images" "ecs_image" { + most_recent = true + name_regex = "^centos_6\\w{1,5}[64].*" +} + +resource "alicloud_security_group" "tf_test_foo" { + description = "foo" +} + +resource "alicloud_security_group_rule" "ssh-in" { + type = "ingress" + ip_protocol = "tcp" + nic_type = "internet" + policy = "accept" + port_range = "22/22" + priority = 1 + security_group_id = "${alicloud_security_group.tf_test_foo.id}" + cidr_ip = "0.0.0.0/0" +} + +resource "alicloud_ess_scaling_group" "bar" { + min_size = 1 + max_size = 1 + scaling_group_name = "bar" + removal_policies = ["OldestInstance", "NewestInstance"] +} + +resource "alicloud_ess_scaling_configuration" "foo" { + scaling_group_id = "${alicloud_ess_scaling_group.bar.id}" + + image_id = "${data.alicloud_images.ecs_image.images.0.id}" + instance_type = "ecs.s2.large" + io_optimized = "optimized" + security_group_id = "${alicloud_security_group.tf_test_foo.id}" +} + +resource "alicloud_ess_scaling_rule" "foo" { + scaling_group_id = "${alicloud_ess_scaling_group.bar.id}" + adjustment_type = "TotalCapacity" + adjustment_value = 1 + cooldown = 120 +} +` + +const testAccEssScalingRule = ` +data "alicloud_images" "ecs_image" { + most_recent = true + name_regex = "^centos_6\\w{1,5}[64].*" +} + +resource "alicloud_security_group" "tf_test_foo" { + description = "foo" +} + +resource "alicloud_security_group_rule" "ssh-in" { + type = "ingress" + ip_protocol = "tcp" + nic_type = "internet" + policy = "accept" + port_range = "22/22" + priority = 1 + security_group_id = "${alicloud_security_group.tf_test_foo.id}" + cidr_ip = "0.0.0.0/0" +} + +resource "alicloud_ess_scaling_group" "bar" { + min_size = 1 + max_size = 1 + scaling_group_name = "bar" + removal_policies = ["OldestInstance", "NewestInstance"] +} + +resource "alicloud_ess_scaling_configuration" "foo" { + scaling_group_id = "${alicloud_ess_scaling_group.bar.id}" + + image_id = "${data.alicloud_images.ecs_image.images.0.id}" + instance_type = "ecs.s2.large" + io_optimized = "optimized" + security_group_id = "${alicloud_security_group.tf_test_foo.id}" +} + +resource "alicloud_ess_scaling_rule" "foo" { + scaling_group_id = "${alicloud_ess_scaling_group.bar.id}" + adjustment_type = "TotalCapacity" + adjustment_value = 1 + cooldown = 120 +} +` + +const testAccEssScalingRule_update = ` +data "alicloud_images" "ecs_image" { + most_recent = true + name_regex = "^centos_6\\w{1,5}[64].*" +} + +resource "alicloud_security_group" "tf_test_foo" { + description = "foo" +} + +resource "alicloud_security_group_rule" "ssh-in" { + type = "ingress" + ip_protocol = "tcp" + nic_type = "internet" + policy = "accept" + port_range = "22/22" + priority = 1 + security_group_id = "${alicloud_security_group.tf_test_foo.id}" + cidr_ip = "0.0.0.0/0" +} + +resource "alicloud_ess_scaling_group" "bar" { + min_size = 1 + max_size = 1 + scaling_group_name = "bar" + removal_policies = ["OldestInstance", "NewestInstance"] +} + +resource "alicloud_ess_scaling_configuration" "foo" { + scaling_group_id = "${alicloud_ess_scaling_group.bar.id}" + + image_id = "${data.alicloud_images.ecs_image.images.0.id}" + instance_type = "ecs.s2.large" + io_optimized = "optimized" + security_group_id = "${alicloud_security_group.tf_test_foo.id}" +} + +resource "alicloud_ess_scaling_rule" "foo" { + scaling_group_id = "${alicloud_ess_scaling_group.bar.id}" + adjustment_type = "TotalCapacity" + adjustment_value = 2 + cooldown = 60 +} +` diff --git a/builtin/providers/alicloud/resource_alicloud_ess_schedule.go b/builtin/providers/alicloud/resource_alicloud_ess_schedule.go new file mode 100644 index 000000000..4e5660a50 --- /dev/null +++ b/builtin/providers/alicloud/resource_alicloud_ess_schedule.go @@ -0,0 +1,220 @@ +package alicloud + +import ( + "fmt" + "github.com/denverdino/aliyungo/common" + "github.com/denverdino/aliyungo/ess" + "github.com/hashicorp/terraform/helper/resource" + "github.com/hashicorp/terraform/helper/schema" + "time" +) + +func resourceAlicloudEssSchedule() *schema.Resource { + return &schema.Resource{ + Create: resourceAliyunEssScheduleCreate, + Read: resourceAliyunEssScheduleRead, + Update: resourceAliyunEssScheduleUpdate, + Delete: resourceAliyunEssScheduleDelete, + + Schema: map[string]*schema.Schema{ + "scheduled_action": &schema.Schema{ + Type: schema.TypeString, + Required: true, + }, + "launch_time": &schema.Schema{ + Type: schema.TypeString, + Required: true, + }, + "scheduled_task_name": &schema.Schema{ + Type: schema.TypeString, + Optional: true, + }, + "description": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Optional: true, + }, + "launch_expiration_time": &schema.Schema{ + Type: schema.TypeInt, + Default: 600, + Optional: true, + ValidateFunc: validateIntegerInRange(0, 21600), + }, + "recurrence_type": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Optional: true, + ValidateFunc: validateAllowedStringValue([]string{string(ess.Daily), + string(ess.Weekly), string(ess.Monthly)}), + }, + "recurrence_value": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Optional: true, + }, + "recurrence_end_time": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Optional: true, + }, + "task_enabled": &schema.Schema{ + Type: schema.TypeBool, + Default: true, + Optional: true, + }, + }, + } +} + +func resourceAliyunEssScheduleCreate(d *schema.ResourceData, meta interface{}) error { + + args, err := buildAlicloudEssScheduleArgs(d, meta) + if err != nil { + return err + } + + essconn := meta.(*AliyunClient).essconn + + rule, err := essconn.CreateScheduledTask(args) + if err != nil { + return err + } + + d.SetId(rule.ScheduledTaskId) + + return resourceAliyunEssScheduleUpdate(d, meta) +} + +func resourceAliyunEssScheduleRead(d *schema.ResourceData, meta interface{}) error { + + client := meta.(*AliyunClient) + + rule, err := client.DescribeScheduleById(d.Id()) + if err != nil { + if e, ok := err.(*common.Error); ok && e.Code == InstanceNotfound { + d.SetId("") + return nil + } + return fmt.Errorf("Error Describe ESS schedule Attribute: %#v", err) + } + + d.Set("scheduled_action", rule.ScheduledAction) + d.Set("launch_time", rule.LaunchTime) + d.Set("scheduled_task_name", rule.ScheduledTaskName) + d.Set("description", rule.Description) + d.Set("launch_expiration_time", rule.LaunchExpirationTime) + d.Set("recurrence_type", rule.RecurrenceType) + d.Set("recurrence_value", rule.RecurrenceValue) + d.Set("recurrence_end_time", rule.RecurrenceEndTime) + d.Set("task_enabled", rule.TaskEnabled) + + return nil +} + +func resourceAliyunEssScheduleUpdate(d *schema.ResourceData, meta interface{}) error { + + conn := meta.(*AliyunClient).essconn + + args := &ess.ModifyScheduledTaskArgs{ + ScheduledTaskId: d.Id(), + } + + if d.HasChange("scheduled_task_name") { + args.ScheduledTaskName = d.Get("scheduled_task_name").(string) + } + + if d.HasChange("description") { + args.Description = d.Get("description").(string) + } + + if d.HasChange("scheduled_action") { + args.ScheduledAction = d.Get("scheduled_action").(string) + } + + if d.HasChange("launch_time") { + args.LaunchTime = d.Get("launch_time").(string) + } + + if d.HasChange("launch_expiration_time") { + args.LaunchExpirationTime = d.Get("launch_expiration_time").(int) + } + + if d.HasChange("recurrence_type") { + args.RecurrenceType = ess.RecurrenceType(d.Get("recurrence_type").(string)) + } + + if d.HasChange("recurrence_value") { + args.RecurrenceValue = d.Get("recurrence_value").(string) + } + + if d.HasChange("recurrence_end_time") { + args.RecurrenceEndTime = d.Get("recurrence_end_time").(string) + } + + if d.HasChange("task_enabled") { + args.TaskEnabled = d.Get("task_enabled").(bool) + } + + if _, err := conn.ModifyScheduledTask(args); err != nil { + return err + } + + return resourceAliyunEssScheduleRead(d, meta) +} + +func resourceAliyunEssScheduleDelete(d *schema.ResourceData, meta interface{}) error { + client := meta.(*AliyunClient) + + return resource.Retry(2*time.Minute, func() *resource.RetryError { + err := client.DeleteScheduleById(d.Id()) + + if err != nil { + return resource.RetryableError(fmt.Errorf("Scaling schedule in use - trying again while it is deleted.")) + } + + _, err = client.DescribeScheduleById(d.Id()) + if err != nil { + if notFoundError(err) { + return nil + } + return resource.NonRetryableError(err) + } + + return resource.RetryableError(fmt.Errorf("Scaling schedule in use - trying again while it is deleted.")) + }) +} + +func buildAlicloudEssScheduleArgs(d *schema.ResourceData, meta interface{}) (*ess.CreateScheduledTaskArgs, error) { + args := &ess.CreateScheduledTaskArgs{ + RegionId: getRegion(d, meta), + ScheduledAction: d.Get("scheduled_action").(string), + LaunchTime: d.Get("launch_time").(string), + TaskEnabled: d.Get("task_enabled").(bool), + } + + if v := d.Get("scheduled_task_name").(string); v != "" { + args.ScheduledTaskName = v + } + + if v := d.Get("description").(string); v != "" { + args.Description = v + } + + if v := d.Get("recurrence_type").(string); v != "" { + args.RecurrenceType = ess.RecurrenceType(v) + } + + if v := d.Get("recurrence_value").(string); v != "" { + args.RecurrenceValue = v + } + + if v := d.Get("recurrence_end_time").(string); v != "" { + args.RecurrenceEndTime = v + } + + if v := d.Get("launch_expiration_time").(int); v != 0 { + args.LaunchExpirationTime = v + } + + return args, nil +} diff --git a/builtin/providers/alicloud/resource_alicloud_ess_schedule_test.go b/builtin/providers/alicloud/resource_alicloud_ess_schedule_test.go new file mode 100644 index 000000000..cb8044cc4 --- /dev/null +++ b/builtin/providers/alicloud/resource_alicloud_ess_schedule_test.go @@ -0,0 +1,151 @@ +package alicloud + +import ( + "fmt" + "github.com/denverdino/aliyungo/common" + "github.com/denverdino/aliyungo/ess" + "github.com/hashicorp/terraform/helper/resource" + "github.com/hashicorp/terraform/terraform" + "log" + "testing" +) + +func TestAccAlicloudEssSchedule_basic(t *testing.T) { + var sc ess.ScheduledTaskItemType + + resource.Test(t, resource.TestCase{ + PreCheck: func() { + testAccPreCheck(t) + }, + + // module name + IDRefreshName: "alicloud_ess_schedule.foo", + + Providers: testAccProviders, + CheckDestroy: testAccCheckEssScheduleDestroy, + Steps: []resource.TestStep{ + resource.TestStep{ + Config: testAccEssScheduleConfig, + Check: resource.ComposeTestCheckFunc( + testAccCheckEssScheduleExists( + "alicloud_ess_schedule.foo", &sc), + resource.TestCheckResourceAttr( + "alicloud_ess_schedule.foo", + "launch_time", + "2017-04-29T07:30Z"), + resource.TestCheckResourceAttr( + "alicloud_ess_schedule.foo", + "task_enabled", + "true"), + ), + }, + }, + }) +} + +func testAccCheckEssScheduleExists(n string, d *ess.ScheduledTaskItemType) resource.TestCheckFunc { + return func(s *terraform.State) error { + rs, ok := s.RootModule().Resources[n] + if !ok { + return fmt.Errorf("Not found: %s", n) + } + + if rs.Primary.ID == "" { + return fmt.Errorf("No ESS Schedule ID is set") + } + + client := testAccProvider.Meta().(*AliyunClient) + attr, err := client.DescribeScheduleById(rs.Primary.ID) + log.Printf("[DEBUG] check schedule %s attribute %#v", rs.Primary.ID, attr) + + if err != nil { + return err + } + + if attr == nil { + return fmt.Errorf("Ess schedule not found") + } + + *d = *attr + return nil + } +} + +func testAccCheckEssScheduleDestroy(s *terraform.State) error { + client := testAccProvider.Meta().(*AliyunClient) + + for _, rs := range s.RootModule().Resources { + if rs.Type != "alicloud_ess_schedule" { + continue + } + ins, err := client.DescribeScheduleById(rs.Primary.ID) + + if ins != nil { + return fmt.Errorf("Error ESS schedule still exist") + } + + // Verify the error is what we want + if err != nil { + // Verify the error is what we want + e, _ := err.(*common.Error) + if e.ErrorResponse.Code == InstanceNotfound { + continue + } + return err + } + } + + return nil +} + +const testAccEssScheduleConfig = ` +data "alicloud_images" "ecs_image" { + most_recent = true + name_regex = "^centos_6\\w{1,5}[64].*" +} + +resource "alicloud_security_group" "tf_test_foo" { + name = "tf_test_foo" + description = "foo" +} + +resource "alicloud_security_group_rule" "ssh-in" { + type = "ingress" + ip_protocol = "tcp" + nic_type = "internet" + policy = "accept" + port_range = "22/22" + priority = 1 + security_group_id = "${alicloud_security_group.tf_test_foo.id}" + cidr_ip = "0.0.0.0/0" +} + +resource "alicloud_ess_scaling_group" "bar" { + min_size = 1 + max_size = 1 + scaling_group_name = "bar" + removal_policies = ["OldestInstance", "NewestInstance"] +} + +resource "alicloud_ess_scaling_configuration" "foo" { + scaling_group_id = "${alicloud_ess_scaling_group.bar.id}" + + image_id = "${data.alicloud_images.ecs_image.images.0.id}" + instance_type = "ecs.s2.large" + io_optimized = "optimized" + security_group_id = "${alicloud_security_group.tf_test_foo.id}" +} + +resource "alicloud_ess_scaling_rule" "foo" { + scaling_group_id = "${alicloud_ess_scaling_group.bar.id}" + adjustment_type = "TotalCapacity" + adjustment_value = 2 + cooldown = 60 +} + +resource "alicloud_ess_schedule" "foo" { + scheduled_action = "${alicloud_ess_scaling_rule.foo.ari}" + launch_time = "2017-04-29T07:30Z" + scheduled_task_name = "tf-foo" +} +` diff --git a/builtin/providers/alicloud/resource_alicloud_forward.go b/builtin/providers/alicloud/resource_alicloud_forward.go new file mode 100644 index 000000000..8f75c54d0 --- /dev/null +++ b/builtin/providers/alicloud/resource_alicloud_forward.go @@ -0,0 +1,165 @@ +package alicloud + +import ( + "fmt" + "github.com/denverdino/aliyungo/ecs" + "github.com/hashicorp/terraform/helper/schema" +) + +func resourceAliyunForwardEntry() *schema.Resource { + return &schema.Resource{ + Create: resourceAliyunForwardEntryCreate, + Read: resourceAliyunForwardEntryRead, + Update: resourceAliyunForwardEntryUpdate, + Delete: resourceAliyunForwardEntryDelete, + + Schema: map[string]*schema.Schema{ + "forward_table_id": &schema.Schema{ + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + "external_ip": &schema.Schema{ + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + "external_port": &schema.Schema{ + Type: schema.TypeString, + Required: true, + ValidateFunc: validateForwardPort, + }, + "ip_protocol": &schema.Schema{ + Type: schema.TypeString, + Required: true, + ValidateFunc: validateAllowedStringValue([]string{"tcp", "udp", "any"}), + }, + "internal_ip": &schema.Schema{ + Type: schema.TypeString, + Required: true, + }, + "internal_port": &schema.Schema{ + Type: schema.TypeString, + Required: true, + ValidateFunc: validateForwardPort, + }, + }, + } +} + +func resourceAliyunForwardEntryCreate(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*AliyunClient).vpcconn + + args := &ecs.CreateForwardEntryArgs{ + RegionId: getRegion(d, meta), + ForwardTableId: d.Get("forward_table_id").(string), + ExternalIp: d.Get("external_ip").(string), + ExternalPort: d.Get("external_port").(string), + IpProtocol: d.Get("ip_protocol").(string), + InternalIp: d.Get("internal_ip").(string), + InternalPort: d.Get("internal_port").(string), + } + + resp, err := conn.CreateForwardEntry(args) + if err != nil { + return fmt.Errorf("CreateForwardEntry got error: %#v", err) + } + + d.SetId(resp.ForwardEntryId) + d.Set("forward_table_id", d.Get("forward_table_id").(string)) + + return resourceAliyunForwardEntryRead(d, meta) +} + +func resourceAliyunForwardEntryRead(d *schema.ResourceData, meta interface{}) error { + client := meta.(*AliyunClient) + + forwardEntry, err := client.DescribeForwardEntry(d.Get("forward_table_id").(string), d.Id()) + + if err != nil { + if notFoundError(err) { + return nil + } + return err + } + + d.Set("forward_table_id", forwardEntry.ForwardTableId) + d.Set("external_ip", forwardEntry.ExternalIp) + d.Set("external_port", forwardEntry.ExternalPort) + d.Set("ip_protocol", forwardEntry.IpProtocol) + d.Set("internal_ip", forwardEntry.InternalIp) + d.Set("internal_port", forwardEntry.InternalPort) + + return nil +} + +func resourceAliyunForwardEntryUpdate(d *schema.ResourceData, meta interface{}) error { + client := meta.(*AliyunClient) + conn := client.vpcconn + + forwardEntry, err := client.DescribeForwardEntry(d.Get("forward_table_id").(string), d.Id()) + if err != nil { + return err + } + + d.Partial(true) + attributeUpdate := false + args := &ecs.ModifyForwardEntryArgs{ + RegionId: getRegion(d, meta), + ForwardTableId: forwardEntry.ForwardTableId, + ForwardEntryId: forwardEntry.ForwardEntryId, + ExternalIp: forwardEntry.ExternalIp, + IpProtocol: forwardEntry.IpProtocol, + ExternalPort: forwardEntry.ExternalPort, + InternalIp: forwardEntry.InternalIp, + InternalPort: forwardEntry.InternalPort, + } + + if d.HasChange("external_port") { + d.SetPartial("external_port") + args.ExternalPort = d.Get("external_port").(string) + attributeUpdate = true + } + + if d.HasChange("ip_protocol") { + d.SetPartial("ip_protocol") + args.IpProtocol = d.Get("ip_protocol").(string) + attributeUpdate = true + } + + if d.HasChange("internal_port") { + d.SetPartial("internal_port") + args.InternalPort = d.Get("internal_port").(string) + attributeUpdate = true + } + + if attributeUpdate { + if err := conn.ModifyForwardEntry(args); err != nil { + return err + } + } + + d.Partial(false) + + return resourceAliyunForwardEntryRead(d, meta) +} + +func resourceAliyunForwardEntryDelete(d *schema.ResourceData, meta interface{}) error { + client := meta.(*AliyunClient) + conn := client.vpcconn + + forwardEntryId := d.Id() + forwardTableId := d.Get("forward_table_id").(string) + + args := &ecs.DeleteForwardEntryArgs{ + RegionId: getRegion(d, meta), + ForwardTableId: forwardTableId, + ForwardEntryId: forwardEntryId, + } + + if err := conn.DeleteForwardEntry(args); err != nil { + return err + } + + return nil +} diff --git a/builtin/providers/alicloud/resource_alicloud_forward_test.go b/builtin/providers/alicloud/resource_alicloud_forward_test.go new file mode 100644 index 000000000..60a67f322 --- /dev/null +++ b/builtin/providers/alicloud/resource_alicloud_forward_test.go @@ -0,0 +1,216 @@ +package alicloud + +import ( + "fmt" + "github.com/denverdino/aliyungo/common" + "github.com/denverdino/aliyungo/ecs" + "github.com/hashicorp/terraform/helper/resource" + "github.com/hashicorp/terraform/terraform" + "testing" +) + +func TestAccAlicloudForward_basic(t *testing.T) { + var forward ecs.ForwardTableEntrySetType + + resource.Test(t, resource.TestCase{ + PreCheck: func() { + testAccPreCheck(t) + }, + + // module name + IDRefreshName: "alicloud_forward_entry.foo", + Providers: testAccProviders, + CheckDestroy: testAccCheckForwardEntryDestroy, + Steps: []resource.TestStep{ + resource.TestStep{ + Config: testAccForwardEntryConfig, + Check: resource.ComposeTestCheckFunc( + testAccCheckForwardEntryExists( + "alicloud_forward_entry.foo", &forward), + ), + }, + + resource.TestStep{ + Config: testAccForwardEntryUpdate, + Check: resource.ComposeTestCheckFunc( + testAccCheckForwardEntryExists( + "alicloud_forward_entry.foo", &forward), + ), + }, + }, + }) + +} + +func testAccCheckForwardEntryDestroy(s *terraform.State) error { + client := testAccProvider.Meta().(*AliyunClient) + + for _, rs := range s.RootModule().Resources { + if rs.Type != "alicloud_snat_entry" { + continue + } + + // Try to find the Snat entry + instance, err := client.DescribeForwardEntry(rs.Primary.Attributes["forward_table_id"], rs.Primary.ID) + + //this special deal cause the DescribeSnatEntry can't find the records would be throw "cant find the snatTable error" + if instance.ForwardEntryId == "" { + return nil + } + + if instance.ForwardEntryId != "" { + return fmt.Errorf("Forward entry still exist") + } + + if err != nil { + // Verify the error is what we want + e, _ := err.(*common.Error) + + if !notFoundError(e) { + return err + } + } + + } + + return nil +} + +func testAccCheckForwardEntryExists(n string, snat *ecs.ForwardTableEntrySetType) resource.TestCheckFunc { + return func(s *terraform.State) error { + rs, ok := s.RootModule().Resources[n] + if !ok { + return fmt.Errorf("Not found: %s", n) + } + + if rs.Primary.ID == "" { + return fmt.Errorf("No ForwardEntry ID is set") + } + + client := testAccProvider.Meta().(*AliyunClient) + instance, err := client.DescribeForwardEntry(rs.Primary.Attributes["forward_table_id"], rs.Primary.ID) + + if err != nil { + return err + } + if instance.ForwardEntryId == "" { + return fmt.Errorf("ForwardEntry not found") + } + + *snat = instance + return nil + } +} + +const testAccForwardEntryConfig = ` +provider "alicloud"{ + region = "cn-hangzhou" +} + +data "alicloud_zones" "default" { + "available_resource_creation"= "VSwitch" +} + +resource "alicloud_vpc" "foo" { + name = "tf_test_foo" + cidr_block = "172.16.0.0/12" +} + +resource "alicloud_vswitch" "foo" { + vpc_id = "${alicloud_vpc.foo.id}" + cidr_block = "172.16.0.0/21" + availability_zone = "${data.alicloud_zones.default.zones.0.id}" +} + +resource "alicloud_nat_gateway" "foo" { + vpc_id = "${alicloud_vpc.foo.id}" + spec = "Small" + name = "test_foo" + bandwidth_packages = [{ + ip_count = 1 + bandwidth = 5 + zone = "${data.alicloud_zones.default.zones.0.id}" + },{ + ip_count = 1 + bandwidth = 6 + zone = "${data.alicloud_zones.default.zones.0.id}" + }] + depends_on = [ + "alicloud_vswitch.foo"] +} + +resource "alicloud_forward_entry" "foo"{ + forward_table_id = "${alicloud_nat_gateway.foo.forward_table_ids}" + external_ip = "${alicloud_nat_gateway.foo.bandwidth_packages.0.public_ip_addresses}" + external_port = "80" + ip_protocol = "tcp" + internal_ip = "172.16.0.3" + internal_port = "8080" +} + +resource "alicloud_forward_entry" "foo1"{ + forward_table_id = "${alicloud_nat_gateway.foo.forward_table_ids}" + external_ip = "${alicloud_nat_gateway.foo.bandwidth_packages.0.public_ip_addresses}" + external_port = "443" + ip_protocol = "udp" + internal_ip = "172.16.0.4" + internal_port = "8080" +} +` + +const testAccForwardEntryUpdate = ` +provider "alicloud"{ + region = "cn-hangzhou" +} + +data "alicloud_zones" "default" { + "available_resource_creation"= "VSwitch" +} + +resource "alicloud_vpc" "foo" { + name = "tf_test_foo" + cidr_block = "172.16.0.0/12" +} + +resource "alicloud_vswitch" "foo" { + vpc_id = "${alicloud_vpc.foo.id}" + cidr_block = "172.16.0.0/21" + availability_zone = "${data.alicloud_zones.default.zones.0.id}" +} + +resource "alicloud_nat_gateway" "foo" { + vpc_id = "${alicloud_vpc.foo.id}" + spec = "Small" + name = "test_foo" + bandwidth_packages = [{ + ip_count = 1 + bandwidth = 5 + zone = "${data.alicloud_zones.default.zones.0.id}" + },{ + ip_count = 1 + bandwidth = 6 + zone = "${data.alicloud_zones.default.zones.0.id}" + }] + depends_on = [ + "alicloud_vswitch.foo"] +} + +resource "alicloud_forward_entry" "foo"{ + forward_table_id = "${alicloud_nat_gateway.foo.forward_table_ids}" + external_ip = "${alicloud_nat_gateway.foo.bandwidth_packages.0.public_ip_addresses}" + external_port = "80" + ip_protocol = "tcp" + internal_ip = "172.16.0.3" + internal_port = "8081" +} + + +resource "alicloud_forward_entry" "foo1"{ + forward_table_id = "${alicloud_nat_gateway.foo.forward_table_ids}" + external_ip = "${alicloud_nat_gateway.foo.bandwidth_packages.0.public_ip_addresses}" + external_port = "22" + ip_protocol = "udp" + internal_ip = "172.16.0.4" + internal_port = "8080" +} +` diff --git a/builtin/providers/alicloud/resource_alicloud_instance.go b/builtin/providers/alicloud/resource_alicloud_instance.go index fe221f17b..492780917 100644 --- a/builtin/providers/alicloud/resource_alicloud_instance.go +++ b/builtin/providers/alicloud/resource_alicloud_instance.go @@ -8,8 +8,10 @@ import ( "encoding/json" "github.com/denverdino/aliyungo/common" "github.com/denverdino/aliyungo/ecs" + "github.com/hashicorp/terraform/helper/resource" "github.com/hashicorp/terraform/helper/schema" "strings" + "time" ) func resourceAliyunInstance() *schema.Resource { @@ -193,11 +195,8 @@ func resourceAliyunInstanceCreate(d *schema.ResourceData, meta interface{}) erro //d.Set("system_disk_category", d.Get("system_disk_category")) //d.Set("system_disk_size", d.Get("system_disk_size")) - if d.Get("allocate_public_ip").(bool) { - _, err := conn.AllocatePublicIpAddress(d.Id()) - if err != nil { - log.Printf("[DEBUG] AllocatePublicIpAddress for instance got error: %#v", err) - } + if err := allocateIpAndBandWidthRelative(d, meta); err != nil { + return fmt.Errorf("allocateIpAndBandWidthRelative err: %#v", err) } // after instance created, its status is pending, @@ -226,6 +225,12 @@ func resourceAliyunRunInstance(d *schema.ResourceData, meta interface{}) error { return err } + if args.IoOptimized == "optimized" { + args.IoOptimized = ecs.IoOptimized("true") + } else { + args.IoOptimized = ecs.IoOptimized("false") + } + runArgs, err := buildAliyunRunInstancesArgs(d, meta) if err != nil { return err @@ -246,14 +251,15 @@ func resourceAliyunRunInstance(d *schema.ResourceData, meta interface{}) error { d.Set("system_disk_category", d.Get("system_disk_category")) d.Set("system_disk_size", d.Get("system_disk_size")) - if d.Get("allocate_public_ip").(bool) { - _, err := conn.AllocatePublicIpAddress(d.Id()) - if err != nil { - log.Printf("[DEBUG] AllocatePublicIpAddress for instance got error: %#v", err) - } + // after instance created, its status change from pending, starting to running + if err := conn.WaitForInstanceAsyn(d.Id(), ecs.Running, defaultTimeout); err != nil { + log.Printf("[DEBUG] WaitForInstance %s got error: %#v", ecs.Running, err) + } + + if err := allocateIpAndBandWidthRelative(d, meta); err != nil { + return fmt.Errorf("allocateIpAndBandWidthRelative err: %#v", err) } - // after instance created, its status change from pending, starting to running if err := conn.WaitForInstanceAsyn(d.Id(), ecs.Running, defaultTimeout); err != nil { log.Printf("[DEBUG] WaitForInstance %s got error: %#v", ecs.Running, err) } @@ -451,30 +457,47 @@ func resourceAliyunInstanceDelete(d *schema.ResourceData, meta interface{}) erro client := meta.(*AliyunClient) conn := client.ecsconn - instance, err := client.QueryInstancesById(d.Id()) - if err != nil { - if notFoundError(err) { - return nil - } - return fmt.Errorf("Error DescribeInstanceAttribute: %#v", err) - } - - if instance.Status != ecs.Stopped { - if err := conn.StopInstance(d.Id(), true); err != nil { - return err + return resource.Retry(5*time.Minute, func() *resource.RetryError { + instance, err := client.QueryInstancesById(d.Id()) + if err != nil { + if notFoundError(err) { + return nil + } } - if err := conn.WaitForInstance(d.Id(), ecs.Stopped, defaultTimeout); err != nil { - return err + if instance.Status != ecs.Stopped { + if err := conn.StopInstance(d.Id(), true); err != nil { + return resource.RetryableError(fmt.Errorf("ECS stop error - trying again.")) + } + + if err := conn.WaitForInstance(d.Id(), ecs.Stopped, defaultTimeout); err != nil { + return resource.RetryableError(fmt.Errorf("Waiting for ecs stopped timeout - trying again.")) + } + } + + if err := conn.DeleteInstance(d.Id()); err != nil { + return resource.RetryableError(fmt.Errorf("ECS Instance in use - trying again while it is deleted.")) + } + + return nil + }) + +} + +func allocateIpAndBandWidthRelative(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*AliyunClient).ecsconn + if d.Get("allocate_public_ip").(bool) { + if d.Get("internet_max_bandwidth_out") == 0 { + return fmt.Errorf("Error: if allocate_public_ip is true than the internet_max_bandwidth_out cannot equal zero.") + } + _, err := conn.AllocatePublicIpAddress(d.Id()) + if err != nil { + return fmt.Errorf("[DEBUG] AllocatePublicIpAddress for instance got error: %#v", err) } } - - if err := conn.DeleteInstance(d.Id()); err != nil { - return err - } - return nil } + func buildAliyunRunInstancesArgs(d *schema.ResourceData, meta interface{}) (*ecs.RunInstanceArgs, error) { args := &ecs.RunInstanceArgs{ MaxAmount: DEFAULT_INSTANCE_COUNT, @@ -560,7 +583,6 @@ func buildAliyunInstanceArgs(d *schema.ResourceData, meta interface{}) (*ecs.Cre args.Description = v } - log.Printf("[DEBUG] SystemDisk is %d", systemDiskSize) if v := d.Get("internet_charge_type").(string); v != "" { args.InternetChargeType = common.InternetChargeType(v) } @@ -578,11 +600,7 @@ func buildAliyunInstanceArgs(d *schema.ResourceData, meta interface{}) (*ecs.Cre } if v := d.Get("io_optimized").(string); v != "" { - if v == "optimized" { - args.IoOptimized = ecs.IoOptimized("true") - } else { - args.IoOptimized = ecs.IoOptimized("false") - } + args.IoOptimized = ecs.IoOptimized(v) } vswitchValue := d.Get("subnet_id").(string) diff --git a/builtin/providers/alicloud/resource_alicloud_instance_test.go b/builtin/providers/alicloud/resource_alicloud_instance_test.go index 4e8f0c716..3547d4693 100644 --- a/builtin/providers/alicloud/resource_alicloud_instance_test.go +++ b/builtin/providers/alicloud/resource_alicloud_instance_test.go @@ -4,12 +4,13 @@ import ( "fmt" "testing" + "log" + "github.com/denverdino/aliyungo/common" "github.com/denverdino/aliyungo/ecs" "github.com/hashicorp/terraform/helper/resource" "github.com/hashicorp/terraform/helper/schema" "github.com/hashicorp/terraform/terraform" - "log" ) func TestAccAlicloudInstance_basic(t *testing.T) { @@ -456,6 +457,17 @@ func TestAccAlicloudInstance_associatePublicIP(t *testing.T) { } } + testCheckPublicIP := func() resource.TestCheckFunc { + return func(*terraform.State) error { + publicIP := instance.PublicIpAddress.IpAddress[0] + if publicIP == "" { + return fmt.Errorf("can't get public IP") + } + + return nil + } + } + resource.Test(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) @@ -469,6 +481,7 @@ func TestAccAlicloudInstance_associatePublicIP(t *testing.T) { Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists("alicloud_instance.foo", &instance), testCheckPrivateIP(), + testCheckPublicIP(), ), }, }, diff --git a/builtin/providers/alicloud/resource_alicloud_nat_gateway.go b/builtin/providers/alicloud/resource_alicloud_nat_gateway.go index 99e71347a..7851e661c 100644 --- a/builtin/providers/alicloud/resource_alicloud_nat_gateway.go +++ b/builtin/providers/alicloud/resource_alicloud_nat_gateway.go @@ -8,6 +8,7 @@ import ( "github.com/hashicorp/terraform/helper/resource" "github.com/hashicorp/terraform/helper/schema" "log" + "strconv" "strings" "time" ) @@ -44,6 +45,16 @@ func resourceAliyunNatGateway() *schema.Resource { Computed: true, }, + "snat_table_ids": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + }, + + "forward_table_ids": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + }, + "bandwidth_packages": &schema.Schema{ Type: schema.TypeList, Elem: &schema.Resource{ @@ -60,6 +71,10 @@ func resourceAliyunNatGateway() *schema.Resource { Type: schema.TypeString, Optional: true, }, + "public_ip_addresses": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + }, }, }, Required: true, @@ -133,8 +148,16 @@ func resourceAliyunNatGatewayRead(d *schema.ResourceData, meta interface{}) erro d.Set("name", natGateway.Name) d.Set("spec", natGateway.Spec) d.Set("bandwidth_package_ids", strings.Join(natGateway.BandwidthPackageIds.BandwidthPackageId, ",")) + d.Set("snat_table_ids", strings.Join(natGateway.SnatTableIds.SnatTableId, ",")) + d.Set("forward_table_ids", strings.Join(natGateway.ForwardTableIds.ForwardTableId, ",")) d.Set("description", natGateway.Description) d.Set("vpc_id", natGateway.VpcId) + bindWidthPackages, err := flattenBandWidthPackages(natGateway.BandwidthPackageIds.BandwidthPackageId, meta, d) + if err != nil { + log.Printf("[ERROR] bindWidthPackages flattenBandWidthPackages failed. natgateway id is %#v", d.Id()) + } else { + d.Set("bandwidth_packages", bindWidthPackages) + } return nil } @@ -254,7 +277,7 @@ func resourceAliyunNatGatewayDelete(d *schema.ResourceData, meta interface{}) er } args := &ecs.DeleteNatGatewayArgs{ - RegionId: client.Region, + RegionId: getRegion(d, meta), NatGatewayId: d.Id(), } @@ -267,7 +290,7 @@ func resourceAliyunNatGatewayDelete(d *schema.ResourceData, meta interface{}) er } describeArgs := &ecs.DescribeNatGatewaysArgs{ - RegionId: client.Region, + RegionId: getRegion(d, meta), NatGatewayId: d.Id(), } gw, _, gwErr := conn.DescribeNatGateways(describeArgs) @@ -282,3 +305,69 @@ func resourceAliyunNatGatewayDelete(d *schema.ResourceData, meta interface{}) er return resource.RetryableError(fmt.Errorf("NatGateway in use - trying again while it is deleted.")) }) } + +func flattenBandWidthPackages(bandWidthPackageIds []string, meta interface{}, d *schema.ResourceData) ([]map[string]interface{}, error) { + + packageLen := len(bandWidthPackageIds) + result := make([]map[string]interface{}, 0, packageLen) + + for i := packageLen - 1; i >= 0; i-- { + packageId := bandWidthPackageIds[i] + packages, err := getPackages(packageId, meta, d) + if err != nil { + log.Printf("[ERROR] NatGateways getPackages failed. packageId is %#v", packageId) + return result, err + } + ipAddress := flattenPackPublicIp(packages.PublicIpAddresses.PublicIpAddresse) + ipCont, ipContErr := strconv.Atoi(packages.IpCount) + bandWidth, bandWidthErr := strconv.Atoi(packages.Bandwidth) + if ipContErr != nil { + log.Printf("[ERROR] NatGateways getPackages failed: ipCont convert error. packageId is %#v", packageId) + return result, ipContErr + } + if bandWidthErr != nil { + log.Printf("[ERROR] NatGateways getPackages failed: bandWidthErr convert error. packageId is %#v", packageId) + return result, bandWidthErr + } + l := map[string]interface{}{ + "ip_count": ipCont, + "bandwidth": bandWidth, + "zone": packages.ZoneId, + "public_ip_addresses": ipAddress, + } + result = append(result, l) + } + return result, nil +} + +func getPackages(packageId string, meta interface{}, d *schema.ResourceData) (*ecs.DescribeBandwidthPackageType, error) { + client := meta.(*AliyunClient) + conn := client.vpcconn + packages, err := conn.DescribeBandwidthPackages(&ecs.DescribeBandwidthPackagesArgs{ + RegionId: getRegion(d, meta), + BandwidthPackageId: packageId, + }) + + if err != nil { + log.Printf("[ERROR] Describe bandwidth package is failed, BandwidthPackageId Id: %s", packageId) + return nil, err + } + + if len(packages) == 0 { + return nil, common.GetClientErrorFromString(InstanceNotfound) + } + + return &packages[0], nil + +} + +func flattenPackPublicIp(publicIpAddressList []ecs.PublicIpAddresseType) string { + var result []string + + for _, publicIpAddresses := range publicIpAddressList { + ipAddress := publicIpAddresses.IpAddress + result = append(result, ipAddress) + } + + return strings.Join(result, ",") +} diff --git a/builtin/providers/alicloud/resource_alicloud_nat_gateway_test.go b/builtin/providers/alicloud/resource_alicloud_nat_gateway_test.go index a928c5dc1..963be3cb1 100644 --- a/builtin/providers/alicloud/resource_alicloud_nat_gateway_test.go +++ b/builtin/providers/alicloud/resource_alicloud_nat_gateway_test.go @@ -48,6 +48,7 @@ func TestAccAlicloudNatGateway_basic(t *testing.T) { "alicloud_nat_gateway.foo", "name", "test_foo"), + testAccCheckNatgatewayIpAddress("alicloud_nat_gateway.foo", &nat), ), }, }, @@ -96,6 +97,31 @@ func TestAccAlicloudNatGateway_spec(t *testing.T) { } +func testAccCheckNatgatewayIpAddress(n string, nat *ecs.NatGatewaySetType) resource.TestCheckFunc { + return func(s *terraform.State) error { + rs, ok := s.RootModule().Resources[n] + if !ok { + return fmt.Errorf("Not found: %s", n) + } + + if rs.Primary.ID == "" { + return fmt.Errorf("No NatGateway ID is set") + } + + client := testAccProvider.Meta().(*AliyunClient) + natGateway, err := client.DescribeNatGateway(rs.Primary.ID) + + if err != nil { + return err + } + if natGateway == nil { + return fmt.Errorf("Natgateway not found") + } + + return nil + } +} + func testAccCheckNatGatewayExists(n string, nat *ecs.NatGatewaySetType) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[n] @@ -164,7 +190,7 @@ resource "alicloud_vpc" "foo" { resource "alicloud_vswitch" "foo" { vpc_id = "${alicloud_vpc.foo.id}" cidr_block = "172.16.0.0/21" - availability_zone = "${data.alicloud_zones.default.zones.0.id}" + availability_zone = "${data.alicloud_zones.default.zones.2.id}" } resource "alicloud_nat_gateway" "foo" { @@ -174,11 +200,19 @@ resource "alicloud_nat_gateway" "foo" { bandwidth_packages = [{ ip_count = 1 bandwidth = 5 - zone = "${data.alicloud_zones.default.zones.0.id}" + zone = "${data.alicloud_zones.default.zones.2.id}" }, { ip_count = 2 - bandwidth = 10 - zone = "${data.alicloud_zones.default.zones.0.id}" + bandwidth = 6 + zone = "${data.alicloud_zones.default.zones.2.id}" + }, { + ip_count = 3 + bandwidth = 7 + zone = "${data.alicloud_zones.default.zones.2.id}" + }, { + ip_count = 1 + bandwidth = 8 + zone = "${data.alicloud_zones.default.zones.2.id}" }] depends_on = [ "alicloud_vswitch.foo"] diff --git a/builtin/providers/alicloud/resource_alicloud_security_group.go b/builtin/providers/alicloud/resource_alicloud_security_group.go index 5f85bfd29..b1d60f704 100644 --- a/builtin/providers/alicloud/resource_alicloud_security_group.go +++ b/builtin/providers/alicloud/resource_alicloud_security_group.go @@ -74,6 +74,11 @@ func resourceAliyunSecurityGroupRead(d *schema.ResourceData, meta interface{}) e return fmt.Errorf("Error DescribeSecurityGroupAttribute: %#v", err) } + if sg == nil { + d.SetId("") + return nil + } + d.Set("name", sg.SecurityGroupName) d.Set("description", sg.Description) diff --git a/builtin/providers/alicloud/resource_alicloud_security_group_rule.go b/builtin/providers/alicloud/resource_alicloud_security_group_rule.go index c43db23a8..56e4de670 100644 --- a/builtin/providers/alicloud/resource_alicloud_security_group_rule.go +++ b/builtin/providers/alicloud/resource_alicloud_security_group_rule.go @@ -3,9 +3,10 @@ package alicloud import ( "fmt" "github.com/denverdino/aliyungo/ecs" + "github.com/hashicorp/terraform/helper/resource" "github.com/hashicorp/terraform/helper/schema" - "log" "strings" + "time" ) func resourceAliyunSecurityGroupRule() *schema.Resource { @@ -141,7 +142,7 @@ func resourceAliyunSecurityGroupRuleRead(d *schema.ResourceData, meta interface{ } return fmt.Errorf("Error SecurityGroup rule: %#v", err) } - log.Printf("[WARN]sg %s, type %s, protocol %s, port %s, rule %#v", sgId, direction, ip_protocol, port_range, rule) + d.Set("type", rule.Direction) d.Set("ip_protocol", strings.ToLower(string(rule.IpProtocol))) d.Set("nic_type", rule.NicType) @@ -163,7 +164,7 @@ func resourceAliyunSecurityGroupRuleRead(d *schema.ResourceData, meta interface{ return nil } -func resourceAliyunSecurityGroupRuleDelete(d *schema.ResourceData, meta interface{}) error { +func deleteSecurityGroupRule(d *schema.ResourceData, meta interface{}) error { client := meta.(*AliyunClient) ruleType := d.Get("type").(string) @@ -187,6 +188,30 @@ func resourceAliyunSecurityGroupRuleDelete(d *schema.ResourceData, meta interfac AuthorizeSecurityGroupEgressArgs: *args, } return client.RevokeSecurityGroupEgress(revokeArgs) +} + +func resourceAliyunSecurityGroupRuleDelete(d *schema.ResourceData, meta interface{}) error { + client := meta.(*AliyunClient) + parts := strings.Split(d.Id(), ":") + sgId, direction, ip_protocol, port_range, nic_type := parts[0], parts[1], parts[2], parts[3], parts[4] + + return resource.Retry(5*time.Minute, func() *resource.RetryError { + err := deleteSecurityGroupRule(d, meta) + + if err != nil { + resource.RetryableError(fmt.Errorf("Security group rule in use - trying again while it is deleted.")) + } + + _, err = client.DescribeSecurityGroupRule(sgId, direction, nic_type, ip_protocol, port_range) + if err != nil { + if notFoundError(err) { + return nil + } + return resource.NonRetryableError(err) + } + + return resource.RetryableError(fmt.Errorf("Security group rule in use - trying again while it is deleted.")) + }) } diff --git a/builtin/providers/alicloud/resource_alicloud_slb.go b/builtin/providers/alicloud/resource_alicloud_slb.go index f3d2af9d3..de8a8906d 100644 --- a/builtin/providers/alicloud/resource_alicloud_slb.go +++ b/builtin/providers/alicloud/resource_alicloud_slb.go @@ -281,6 +281,11 @@ func resourceAliyunSlbRead(d *schema.ResourceData, meta interface{}) error { return err } + if loadBalancer == nil { + d.SetId("") + return nil + } + d.Set("name", loadBalancer.LoadBalancerName) if loadBalancer.AddressType == slb.InternetAddressType { diff --git a/builtin/providers/alicloud/resource_alicloud_slb_attachment.go b/builtin/providers/alicloud/resource_alicloud_slb_attachment.go index 6a9163c07..74e13c26c 100644 --- a/builtin/providers/alicloud/resource_alicloud_slb_attachment.go +++ b/builtin/providers/alicloud/resource_alicloud_slb_attachment.go @@ -64,10 +64,14 @@ func resourceAliyunSlbAttachmentRead(d *schema.ResourceData, meta interface{}) e if err != nil { if notFoundError(err) { d.SetId("") - return fmt.Errorf("Read special SLB Id not found: %#v", err) + return nil } + return fmt.Errorf("Read special SLB Id not found: %#v", err) + } - return err + if loadBalancer == nil { + d.SetId("") + return nil } backendServerType := loadBalancer.BackendServers diff --git a/builtin/providers/alicloud/resource_alicloud_snat.go b/builtin/providers/alicloud/resource_alicloud_snat.go new file mode 100644 index 000000000..887d50388 --- /dev/null +++ b/builtin/providers/alicloud/resource_alicloud_snat.go @@ -0,0 +1,134 @@ +package alicloud + +import ( + "fmt" + "github.com/denverdino/aliyungo/ecs" + "github.com/hashicorp/terraform/helper/schema" +) + +func resourceAliyunSnatEntry() *schema.Resource { + return &schema.Resource{ + Create: resourceAliyunSnatEntryCreate, + Read: resourceAliyunSnatEntryRead, + Update: resourceAliyunSnatEntryUpdate, + Delete: resourceAliyunSnatEntryDelete, + + Schema: map[string]*schema.Schema{ + "snat_table_id": &schema.Schema{ + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + "source_vswitch_id": &schema.Schema{ + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + "snat_ip": &schema.Schema{ + Type: schema.TypeString, + Required: true, + }, + }, + } +} + +func resourceAliyunSnatEntryCreate(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*AliyunClient).vpcconn + + args := &ecs.CreateSnatEntryArgs{ + RegionId: getRegion(d, meta), + SnatTableId: d.Get("snat_table_id").(string), + SourceVSwitchId: d.Get("source_vswitch_id").(string), + SnatIp: d.Get("snat_ip").(string), + } + + resp, err := conn.CreateSnatEntry(args) + if err != nil { + return fmt.Errorf("CreateSnatEntry got error: %#v", err) + } + + d.SetId(resp.SnatEntryId) + d.Set("snat_table_id", d.Get("snat_table_id").(string)) + + return resourceAliyunSnatEntryRead(d, meta) +} + +func resourceAliyunSnatEntryRead(d *schema.ResourceData, meta interface{}) error { + client := meta.(*AliyunClient) + + snatEntry, err := client.DescribeSnatEntry(d.Get("snat_table_id").(string), d.Id()) + + if err != nil { + if notFoundError(err) { + return nil + } + return err + } + + d.Set("snat_table_id", snatEntry.SnatTableId) + d.Set("source_vswitch_id", snatEntry.SourceVSwitchId) + d.Set("snat_ip", snatEntry.SnatIp) + + return nil +} + +func resourceAliyunSnatEntryUpdate(d *schema.ResourceData, meta interface{}) error { + client := meta.(*AliyunClient) + conn := client.vpcconn + + snatEntry, err := client.DescribeSnatEntry(d.Get("snat_table_id").(string), d.Id()) + if err != nil { + return err + } + + d.Partial(true) + attributeUpdate := false + args := &ecs.ModifySnatEntryArgs{ + RegionId: getRegion(d, meta), + SnatTableId: snatEntry.SnatTableId, + SnatEntryId: snatEntry.SnatEntryId, + } + + if d.HasChange("snat_ip") { + d.SetPartial("snat_ip") + var snat_ip string + if v, ok := d.GetOk("snat_ip"); ok { + snat_ip = v.(string) + } else { + return fmt.Errorf("cann't change snap_ip to empty string") + } + args.SnatIp = snat_ip + + attributeUpdate = true + } + + if attributeUpdate { + if err := conn.ModifySnatEntry(args); err != nil { + return err + } + } + + d.Partial(false) + + return resourceAliyunSnatEntryRead(d, meta) +} + +func resourceAliyunSnatEntryDelete(d *schema.ResourceData, meta interface{}) error { + client := meta.(*AliyunClient) + conn := client.vpcconn + + snatEntryId := d.Id() + snatTableId := d.Get("snat_table_id").(string) + + args := &ecs.DeleteSnatEntryArgs{ + RegionId: getRegion(d, meta), + SnatTableId: snatTableId, + SnatEntryId: snatEntryId, + } + + if err := conn.DeleteSnatEntry(args); err != nil { + return err + } + + return nil +} diff --git a/builtin/providers/alicloud/resource_alicloud_snat_test.go b/builtin/providers/alicloud/resource_alicloud_snat_test.go new file mode 100644 index 000000000..673ff59dd --- /dev/null +++ b/builtin/providers/alicloud/resource_alicloud_snat_test.go @@ -0,0 +1,180 @@ +package alicloud + +import ( + "fmt" + "github.com/denverdino/aliyungo/common" + "github.com/denverdino/aliyungo/ecs" + "github.com/hashicorp/terraform/helper/resource" + "github.com/hashicorp/terraform/terraform" + "testing" +) + +func TestAccAlicloudSnat_basic(t *testing.T) { + var snat ecs.SnatEntrySetType + + resource.Test(t, resource.TestCase{ + PreCheck: func() { + testAccPreCheck(t) + }, + + // module name + IDRefreshName: "alicloud_snat_entry.foo", + Providers: testAccProviders, + CheckDestroy: testAccCheckSnatEntryDestroy, + Steps: []resource.TestStep{ + resource.TestStep{ + Config: testAccSnatEntryConfig, + Check: resource.ComposeTestCheckFunc( + testAccCheckSnatEntryExists( + "alicloud_snat_entry.foo", &snat), + ), + }, + resource.TestStep{ + Config: testAccSnatEntryUpdate, + Check: resource.ComposeTestCheckFunc( + testAccCheckSnatEntryExists( + "alicloud_snat_entry.foo", &snat), + ), + }, + }, + }) + +} + +func testAccCheckSnatEntryDestroy(s *terraform.State) error { + client := testAccProvider.Meta().(*AliyunClient) + + for _, rs := range s.RootModule().Resources { + if rs.Type != "alicloud_snat_entry" { + continue + } + + // Try to find the Snat entry + instance, err := client.DescribeSnatEntry(rs.Primary.Attributes["snat_table_id"], rs.Primary.ID) + + //this special deal cause the DescribeSnatEntry can't find the records would be throw "cant find the snatTable error" + if instance.SnatEntryId == "" { + return nil + } + + if instance.SnatEntryId != "" { + return fmt.Errorf("Snat entry still exist") + } + + if err != nil { + // Verify the error is what we want + e, _ := err.(*common.Error) + + if !notFoundError(e) { + return err + } + } + + } + + return nil +} + +func testAccCheckSnatEntryExists(n string, snat *ecs.SnatEntrySetType) resource.TestCheckFunc { + return func(s *terraform.State) error { + rs, ok := s.RootModule().Resources[n] + if !ok { + return fmt.Errorf("Not found: %s", n) + } + + if rs.Primary.ID == "" { + return fmt.Errorf("No SnatEntry ID is set") + } + + client := testAccProvider.Meta().(*AliyunClient) + instance, err := client.DescribeSnatEntry(rs.Primary.Attributes["snat_table_id"], rs.Primary.ID) + + if err != nil { + return err + } + if instance.SnatEntryId == "" { + return fmt.Errorf("SnatEntry not found") + } + + *snat = instance + return nil + } +} + +const testAccSnatEntryConfig = ` +data "alicloud_zones" "default" { + "available_resource_creation"= "VSwitch" +} + +resource "alicloud_vpc" "foo" { + name = "tf_test_foo" + cidr_block = "172.16.0.0/12" +} + +resource "alicloud_vswitch" "foo" { + vpc_id = "${alicloud_vpc.foo.id}" + cidr_block = "172.16.0.0/21" + availability_zone = "${data.alicloud_zones.default.zones.2.id}" +} + +resource "alicloud_nat_gateway" "foo" { + vpc_id = "${alicloud_vpc.foo.id}" + spec = "Small" + name = "test_foo" + bandwidth_packages = [{ + ip_count = 2 + bandwidth = 5 + zone = "${data.alicloud_zones.default.zones.2.id}" + },{ + ip_count = 1 + bandwidth = 6 + zone = "${data.alicloud_zones.default.zones.2.id}" + }] + depends_on = [ + "alicloud_vswitch.foo"] +} +resource "alicloud_snat_entry" "foo"{ + snat_table_id = "${alicloud_nat_gateway.foo.snat_table_ids}" + source_vswitch_id = "${alicloud_vswitch.foo.id}" + snat_ip = "${alicloud_nat_gateway.foo.bandwidth_packages.0.public_ip_addresses}" +} +` + +const testAccSnatEntryUpdate = ` +data "alicloud_zones" "default" { + "available_resource_creation"= "VSwitch" +} + +resource "alicloud_vpc" "foo" { + name = "tf_test_foo" + cidr_block = "172.16.0.0/12" +} + +resource "alicloud_vswitch" "foo" { + vpc_id = "${alicloud_vpc.foo.id}" + cidr_block = "172.16.0.0/21" + availability_zone = "${data.alicloud_zones.default.zones.2.id}" +} + +resource "alicloud_nat_gateway" "foo" { + vpc_id = "${alicloud_vpc.foo.id}" + spec = "Small" + name = "test_foo" + bandwidth_packages = [{ + ip_count = 2 + bandwidth = 5 + zone = "${data.alicloud_zones.default.zones.2.id}" + },{ + ip_count = 1 + bandwidth = 6 + zone = "${data.alicloud_zones.default.zones.2.id}" + }] + depends_on = [ + "alicloud_vswitch.foo"] +} +resource "alicloud_snat_entry" "foo"{ + snat_table_id = "${alicloud_nat_gateway.foo.snat_table_ids}" + source_vswitch_id = "${alicloud_vswitch.foo.id}" + snat_ip = "${alicloud_nat_gateway.foo.bandwidth_packages.1.public_ip_addresses}" +} +` diff --git a/builtin/providers/alicloud/resource_alicloud_vpc.go b/builtin/providers/alicloud/resource_alicloud_vpc.go index e59e3b53b..7418395fd 100644 --- a/builtin/providers/alicloud/resource_alicloud_vpc.go +++ b/builtin/providers/alicloud/resource_alicloud_vpc.go @@ -86,7 +86,7 @@ func resourceAliyunVpcCreate(d *schema.ResourceData, meta interface{}) error { return fmt.Errorf("Timeout when WaitForVpcAvailable") } - return resourceAliyunVpcRead(d, meta) + return resourceAliyunVpcUpdate(d, meta) } func resourceAliyunVpcRead(d *schema.ResourceData, meta interface{}) error { @@ -144,7 +144,7 @@ func resourceAliyunVpcUpdate(d *schema.ResourceData, meta interface{}) error { d.Partial(false) - return nil + return resourceAliyunVpcRead(d, meta) } func resourceAliyunVpcDelete(d *schema.ResourceData, meta interface{}) error { diff --git a/builtin/providers/alicloud/resource_alicloud_vswitch.go b/builtin/providers/alicloud/resource_alicloud_vswitch.go index 74d4c6a88..d4149b9ca 100644 --- a/builtin/providers/alicloud/resource_alicloud_vswitch.go +++ b/builtin/providers/alicloud/resource_alicloud_vswitch.go @@ -68,7 +68,7 @@ func resourceAliyunSwitchCreate(d *schema.ResourceData, meta interface{}) error return fmt.Errorf("WaitForVSwitchAvailable got a error: %s", err) } - return resourceAliyunSwitchRead(d, meta) + return resourceAliyunSwitchUpdate(d, meta) } func resourceAliyunSwitchRead(d *schema.ResourceData, meta interface{}) error { @@ -139,7 +139,7 @@ func resourceAliyunSwitchUpdate(d *schema.ResourceData, meta interface{}) error d.Partial(false) - return nil + return resourceAliyunSwitchRead(d, meta) } func resourceAliyunSwitchDelete(d *schema.ResourceData, meta interface{}) error { diff --git a/builtin/providers/alicloud/service_alicloud_ecs.go b/builtin/providers/alicloud/service_alicloud_ecs.go index 4ff0e5f04..79b6b07fb 100644 --- a/builtin/providers/alicloud/service_alicloud_ecs.go +++ b/builtin/providers/alicloud/service_alicloud_ecs.go @@ -131,7 +131,7 @@ func (client *AliyunClient) QueryInstancesById(id string) (instance *ecs.Instanc } if len(instances) == 0 { - return nil, common.GetClientErrorFromString(InstanceNotfound) + return nil, GetNotFoundErrorFromString(InstanceNotfound) } return &instances[0], nil @@ -244,7 +244,7 @@ func (client *AliyunClient) DescribeSecurityGroupRule(securityGroupId, direction return &p, nil } } - return nil, nil + return nil, GetNotFoundErrorFromString("Security group rule not found") } diff --git a/builtin/providers/alicloud/service_alicloud_ess.go b/builtin/providers/alicloud/service_alicloud_ess.go new file mode 100644 index 000000000..69d514ef2 --- /dev/null +++ b/builtin/providers/alicloud/service_alicloud_ess.go @@ -0,0 +1,167 @@ +package alicloud + +import ( + "github.com/denverdino/aliyungo/ess" +) + +func (client *AliyunClient) DescribeScalingGroupById(sgId string) (*ess.ScalingGroupItemType, error) { + args := ess.DescribeScalingGroupsArgs{ + RegionId: client.Region, + ScalingGroupId: []string{sgId}, + } + + sgs, _, err := client.essconn.DescribeScalingGroups(&args) + if err != nil { + return nil, err + } + + if len(sgs) == 0 { + return nil, GetNotFoundErrorFromString("Scaling group not found") + } + + return &sgs[0], nil +} + +func (client *AliyunClient) DeleteScalingGroupById(sgId string) error { + args := ess.DeleteScalingGroupArgs{ + ScalingGroupId: sgId, + ForceDelete: true, + } + + _, err := client.essconn.DeleteScalingGroup(&args) + return err +} + +func (client *AliyunClient) DescribeScalingConfigurationById(sgId, configId string) (*ess.ScalingConfigurationItemType, error) { + args := ess.DescribeScalingConfigurationsArgs{ + RegionId: client.Region, + ScalingGroupId: sgId, + ScalingConfigurationId: []string{configId}, + } + + cs, _, err := client.essconn.DescribeScalingConfigurations(&args) + if err != nil { + return nil, err + } + + if len(cs) == 0 { + return nil, GetNotFoundErrorFromString("Scaling configuration not found") + } + + return &cs[0], nil +} + +func (client *AliyunClient) ActiveScalingConfigurationById(sgId, configId string) error { + args := ess.ModifyScalingGroupArgs{ + ScalingGroupId: sgId, + ActiveScalingConfigurationId: configId, + } + + _, err := client.essconn.ModifyScalingGroup(&args) + return err +} + +func (client *AliyunClient) EnableScalingConfigurationById(sgId, configId string, ids []string) error { + args := ess.EnableScalingGroupArgs{ + ScalingGroupId: sgId, + ActiveScalingConfigurationId: configId, + } + + if len(ids) > 0 { + args.InstanceId = ids + } + + _, err := client.essconn.EnableScalingGroup(&args) + return err +} + +func (client *AliyunClient) DisableScalingConfigurationById(sgId string) error { + args := ess.DisableScalingGroupArgs{ + ScalingGroupId: sgId, + } + + _, err := client.essconn.DisableScalingGroup(&args) + return err +} + +func (client *AliyunClient) DeleteScalingConfigurationById(sgId, configId string) error { + args := ess.DeleteScalingConfigurationArgs{ + ScalingGroupId: sgId, + ScalingConfigurationId: configId, + } + + _, err := client.essconn.DeleteScalingConfiguration(&args) + return err +} + +// Flattens an array of datadisk into a []map[string]interface{} +func flattenDataDiskMappings(list []ess.DataDiskItemType) []map[string]interface{} { + result := make([]map[string]interface{}, 0, len(list)) + for _, i := range list { + l := map[string]interface{}{ + "size": i.Size, + "category": i.Category, + "snapshot_id": i.SnapshotId, + "device": i.Device, + } + result = append(result, l) + } + return result +} + +func (client *AliyunClient) DescribeScalingRuleById(sgId, ruleId string) (*ess.ScalingRuleItemType, error) { + args := ess.DescribeScalingRulesArgs{ + RegionId: client.Region, + ScalingGroupId: sgId, + ScalingRuleId: []string{ruleId}, + } + + cs, _, err := client.essconn.DescribeScalingRules(&args) + if err != nil { + return nil, err + } + + if len(cs) == 0 { + return nil, GetNotFoundErrorFromString("Scaling rule not found") + } + + return &cs[0], nil +} + +func (client *AliyunClient) DeleteScalingRuleById(ruleId string) error { + args := ess.DeleteScalingRuleArgs{ + RegionId: client.Region, + ScalingRuleId: ruleId, + } + + _, err := client.essconn.DeleteScalingRule(&args) + return err +} + +func (client *AliyunClient) DescribeScheduleById(scheduleId string) (*ess.ScheduledTaskItemType, error) { + args := ess.DescribeScheduledTasksArgs{ + RegionId: client.Region, + ScheduledTaskId: []string{scheduleId}, + } + + cs, _, err := client.essconn.DescribeScheduledTasks(&args) + if err != nil { + return nil, err + } + + if len(cs) == 0 { + return nil, GetNotFoundErrorFromString("Schedule not found") + } + + return &cs[0], nil +} + +func (client *AliyunClient) DeleteScheduleById(scheduleId string) error { + args := ess.DeleteScheduledTaskArgs{ + RegionId: client.Region, + ScheduledTaskId: scheduleId, + } + + _, err := client.essconn.DeleteScheduledTask(&args) + return err +} diff --git a/builtin/providers/alicloud/service_alicloud_rds.go b/builtin/providers/alicloud/service_alicloud_rds.go index 903374fe6..700a5d138 100644 --- a/builtin/providers/alicloud/service_alicloud_rds.go +++ b/builtin/providers/alicloud/service_alicloud_rds.go @@ -6,7 +6,20 @@ import ( "strings" ) -// when getInstance is empty, then throw InstanceNotfound error +// +// _______________ _______________ _______________ +// | | ______param______\ | | _____request_____\ | | +// | Business | | Service | | SDK/API | +// | | __________________ | | __________________ | | +// |______________| \ (obj, err) |______________| \ (status, cont) |______________| +// | | +// |A. {instance, nil} |a. {200, content} +// |B. {nil, error} |b. {200, nil} +// |c. {4xx, nil} +// +// The API return 200 for resource not found. +// When getInstance is empty, then throw InstanceNotfound error. +// That the business layer only need to check error. func (client *AliyunClient) DescribeDBInstanceById(id string) (instance *rds.DBInstanceAttribute, err error) { arrtArgs := rds.DescribeDBInstancesArgs{ DBInstanceId: id, @@ -19,7 +32,7 @@ func (client *AliyunClient) DescribeDBInstanceById(id string) (instance *rds.DBI attr := resp.Items.DBInstanceAttribute if len(attr) <= 0 { - return nil, common.GetClientErrorFromString(InstanceNotfound) + return nil, GetNotFoundErrorFromString("DB instance not found") } return &attr[0], nil @@ -164,13 +177,10 @@ func (client *AliyunClient) GetSecurityIps(instanceId string) ([]string, error) if err != nil { return nil, err } - ips := "" - for i, ip := range arr { - if i == 0 { - ips += ip.SecurityIPList - } else { - ips += COMMA_SEPARATED + ip.SecurityIPList - } + var ips, separator string + for _, ip := range arr { + ips += separator + ip.SecurityIPList + separator = COMMA_SEPARATED } return strings.Split(ips, COMMA_SEPARATED), nil } diff --git a/builtin/providers/alicloud/service_alicloud_vpc.go b/builtin/providers/alicloud/service_alicloud_vpc.go index 775fe112c..491ab034f 100644 --- a/builtin/providers/alicloud/service_alicloud_vpc.go +++ b/builtin/providers/alicloud/service_alicloud_vpc.go @@ -32,6 +32,7 @@ func (client *AliyunClient) DescribeNatGateway(natGatewayId string) (*ecs.NatGat } natGateways, _, err := client.vpcconn.DescribeNatGateways(args) + //fmt.Println("natGateways %#v", natGateways) if err != nil { return nil, err } @@ -64,6 +65,78 @@ func (client *AliyunClient) DescribeVpc(vpcId string) (*ecs.VpcSetType, error) { return &vpcs[0], nil } +func (client *AliyunClient) DescribeSnatEntry(snatTableId string, snatEntryId string) (ecs.SnatEntrySetType, error) { + + var resultSnat ecs.SnatEntrySetType + + args := &ecs.DescribeSnatTableEntriesArgs{ + RegionId: client.Region, + SnatTableId: snatTableId, + } + + snatEntries, _, err := client.vpcconn.DescribeSnatTableEntries(args) + + //this special deal cause the DescribeSnatEntry can't find the records would be throw "cant find the snatTable error" + //so judge the snatEntries length priority + if len(snatEntries) == 0 { + return resultSnat, common.GetClientErrorFromString(InstanceNotfound) + } + + if err != nil { + return resultSnat, err + } + + findSnat := false + + for _, snat := range snatEntries { + if snat.SnatEntryId == snatEntryId { + resultSnat = snat + findSnat = true + } + } + if !findSnat { + return resultSnat, common.GetClientErrorFromString(NotFindSnatEntryBySnatId) + } + + return resultSnat, nil +} + +func (client *AliyunClient) DescribeForwardEntry(forwardTableId string, forwardEntryId string) (ecs.ForwardTableEntrySetType, error) { + + var resultFoward ecs.ForwardTableEntrySetType + + args := &ecs.DescribeForwardTableEntriesArgs{ + RegionId: client.Region, + ForwardTableId: forwardTableId, + } + + forwardEntries, _, err := client.vpcconn.DescribeForwardTableEntries(args) + + //this special deal cause the DescribeSnatEntry can't find the records would be throw "cant find the snatTable error" + //so judge the snatEntries length priority + if len(forwardEntries) == 0 { + return resultFoward, common.GetClientErrorFromString(InstanceNotfound) + } + + findForward := false + + for _, forward := range forwardEntries { + if forward.ForwardEntryId == forwardEntryId { + resultFoward = forward + findForward = true + } + } + if !findForward { + return resultFoward, common.GetClientErrorFromString(NotFindForwardEntryByForwardId) + } + + if err != nil { + return resultFoward, err + } + + return resultFoward, nil +} + // describe vswitch by param filters func (client *AliyunClient) QueryVswitches(args *ecs.DescribeVSwitchesArgs) (vswitches []ecs.VSwitchSetType, err error) { vsws, _, err := client.ecsconn.DescribeVSwitches(args) @@ -130,7 +203,7 @@ func (client *AliyunClient) QueryRouteEntry(routeTableId, cidrBlock, nextHopType return &e, nil } } - return nil, nil + return nil, GetNotFoundErrorFromString("Vpc router entry not found") } func (client *AliyunClient) GetVpcIdByVSwitchId(vswitchId string) (vpcId string, err error) { diff --git a/builtin/providers/alicloud/struct_security_groups.go b/builtin/providers/alicloud/struct_security_groups.go deleted file mode 100644 index 678f68f7d..000000000 --- a/builtin/providers/alicloud/struct_security_groups.go +++ /dev/null @@ -1,11 +0,0 @@ -package alicloud - -// Takes the result of flatmap.Expand for an array of strings -// and returns a []string -func expandStringList(configured []interface{}) []string { - vs := make([]string, 0, len(configured)) - for _, v := range configured { - vs = append(vs, v.(string)) - } - return vs -} diff --git a/builtin/providers/alicloud/validators.go b/builtin/providers/alicloud/validators.go index 9687e68e8..4c3c82f3e 100644 --- a/builtin/providers/alicloud/validators.go +++ b/builtin/providers/alicloud/validators.go @@ -18,7 +18,7 @@ func validateInstancePort(v interface{}, k string) (ws []string, errors []error) value := v.(int) if value < 1 || value > 65535 { errors = append(errors, fmt.Errorf( - "%q must be a valid instance port between 1 and 65535", + "%q must be a valid port between 1 and 65535", k)) return } @@ -26,8 +26,8 @@ func validateInstancePort(v interface{}, k string) (ws []string, errors []error) } func validateInstanceProtocol(v interface{}, k string) (ws []string, errors []error) { - protocal := v.(string) - if !isProtocalValid(protocal) { + protocol := v.(string) + if !isProtocolValid(protocol) { errors = append(errors, fmt.Errorf( "%q is an invalid value. Valid values are either http, https, tcp or udp", k)) @@ -282,9 +282,9 @@ func validateInternetChargeType(v interface{}, k string) (ws []string, errors [] func validateInternetMaxBandWidthOut(v interface{}, k string) (ws []string, errors []error) { value := v.(int) - if value < 1 || value > 100 { + if value < 0 || value > 100 { errors = append(errors, fmt.Errorf( - "%q must be a valid internet bandwidth out between 1 and 1000", + "%q must be a valid internet bandwidth out between 0 and 100", k)) return } @@ -565,3 +565,14 @@ func validateRegion(v interface{}, k string) (ws []string, errors []error) { } return } + +func validateForwardPort(v interface{}, k string) (ws []string, errors []error) { + value := v.(string) + if value != "any" { + valueConv, err := strconv.Atoi(value) + if err != nil || valueConv < 1 || valueConv > 65535 { + errors = append(errors, fmt.Errorf("%q must be a valid port between 1 and 65535 or any ", k)) + } + } + return +} diff --git a/builtin/providers/alicloud/validators_test.go b/builtin/providers/alicloud/validators_test.go index 7d40de6b7..3160c496c 100644 --- a/builtin/providers/alicloud/validators_test.go +++ b/builtin/providers/alicloud/validators_test.go @@ -21,17 +21,17 @@ func TestValidateInstancePort(t *testing.T) { } func TestValidateInstanceProtocol(t *testing.T) { - validProtocals := []string{"http", "tcp", "https", "udp"} - for _, v := range validProtocals { - _, errors := validateInstanceProtocol(v, "instance_protocal") + validProtocols := []string{"http", "tcp", "https", "udp"} + for _, v := range validProtocols { + _, errors := validateInstanceProtocol(v, "instance_protocol") if len(errors) != 0 { t.Fatalf("%q should be a valid instance protocol: %q", v, errors) } } - invalidProtocals := []string{"HTTP", "abc", "ecmp", "dubbo"} - for _, v := range invalidProtocals { - _, errors := validateInstanceProtocol(v, "instance_protocal") + invalidProtocols := []string{"HTTP", "abc", "ecmp", "dubbo"} + for _, v := range invalidProtocols { + _, errors := validateInstanceProtocol(v, "instance_protocol") if len(errors) == 0 { t.Fatalf("%q should be an invalid instance protocol", v) } @@ -353,7 +353,7 @@ func TestValidateInternetMaxBandWidthOut(t *testing.T) { } } - invalidInternetMaxBandWidthOut := []int{-2, 0, 101, 123} + invalidInternetMaxBandWidthOut := []int{-2, 101, 123} for _, v := range invalidInternetMaxBandWidthOut { _, errors := validateInternetMaxBandWidthOut(v, "internet_max_bandwidth_out") if len(errors) == 0 { diff --git a/builtin/providers/aws/auth_helpers.go b/builtin/providers/aws/auth_helpers.go index 1a73c6e8b..e808d4d39 100644 --- a/builtin/providers/aws/auth_helpers.go +++ b/builtin/providers/aws/auth_helpers.go @@ -54,7 +54,7 @@ func GetAccountInfo(iamconn *iam.IAM, stsconn *sts.STS, authProviderName string) awsErr, ok := err.(awserr.Error) // AccessDenied and ValidationError can be raised // if credentials belong to federated profile, so we ignore these - if !ok || (awsErr.Code() != "AccessDenied" && awsErr.Code() != "ValidationError") { + if !ok || (awsErr.Code() != "AccessDenied" && awsErr.Code() != "ValidationError" && awsErr.Code() != "InvalidClientTokenId") { return "", "", fmt.Errorf("Failed getting account ID via 'iam:GetUser': %s", err) } log.Printf("[DEBUG] Getting account ID via iam:GetUser failed: %s", err) diff --git a/builtin/providers/aws/autoscaling_tags.go b/builtin/providers/aws/autoscaling_tags.go index e9ca8531a..5c0911505 100644 --- a/builtin/providers/aws/autoscaling_tags.go +++ b/builtin/providers/aws/autoscaling_tags.go @@ -5,6 +5,7 @@ import ( "fmt" "log" "regexp" + "strconv" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/autoscaling" @@ -12,8 +13,8 @@ import ( "github.com/hashicorp/terraform/helper/schema" ) -// tagsSchema returns the schema to use for tags. -func autoscalingTagsSchema() *schema.Schema { +// autoscalingTagSchema returns the schema to use for the tag element. +func autoscalingTagSchema() *schema.Schema { return &schema.Schema{ Type: schema.TypeSet, Optional: true, @@ -35,11 +36,11 @@ func autoscalingTagsSchema() *schema.Schema { }, }, }, - Set: autoscalingTagsToHash, + Set: autoscalingTagToHash, } } -func autoscalingTagsToHash(v interface{}) int { +func autoscalingTagToHash(v interface{}) int { var buf bytes.Buffer m := v.(map[string]interface{}) buf.WriteString(fmt.Sprintf("%s-", m["key"].(string))) @@ -52,35 +53,74 @@ func autoscalingTagsToHash(v interface{}) int { // setTags is a helper to set the tags for a resource. It expects the // tags field to be named "tag" func setAutoscalingTags(conn *autoscaling.AutoScaling, d *schema.ResourceData) error { - if d.HasChange("tag") { + resourceID := d.Get("name").(string) + var createTags, removeTags []*autoscaling.Tag + + if d.HasChange("tag") || d.HasChange("tags") { oraw, nraw := d.GetChange("tag") o := setToMapByKey(oraw.(*schema.Set), "key") n := setToMapByKey(nraw.(*schema.Set), "key") - resourceID := d.Get("name").(string) - c, r := diffAutoscalingTags( - autoscalingTagsFromMap(o, resourceID), - autoscalingTagsFromMap(n, resourceID), - resourceID) - create := autoscaling.CreateOrUpdateTagsInput{ - Tags: c, - } - remove := autoscaling.DeleteTagsInput{ - Tags: r, + old, err := autoscalingTagsFromMap(o, resourceID) + if err != nil { + return err } - // Set tags - if len(r) > 0 { - log.Printf("[DEBUG] Removing autoscaling tags: %#v", r) - if _, err := conn.DeleteTags(&remove); err != nil { - return err - } + new, err := autoscalingTagsFromMap(n, resourceID) + if err != nil { + return err } - if len(c) > 0 { - log.Printf("[DEBUG] Creating autoscaling tags: %#v", c) - if _, err := conn.CreateOrUpdateTags(&create); err != nil { - return err - } + + c, r, err := diffAutoscalingTags(old, new, resourceID) + if err != nil { + return err + } + + createTags = append(createTags, c...) + removeTags = append(removeTags, r...) + + oraw, nraw = d.GetChange("tags") + old, err = autoscalingTagsFromList(oraw.([]interface{}), resourceID) + if err != nil { + return err + } + + new, err = autoscalingTagsFromList(nraw.([]interface{}), resourceID) + if err != nil { + return err + } + + c, r, err = diffAutoscalingTags(old, new, resourceID) + if err != nil { + return err + } + + createTags = append(createTags, c...) + removeTags = append(removeTags, r...) + } + + // Set tags + if len(removeTags) > 0 { + log.Printf("[DEBUG] Removing autoscaling tags: %#v", removeTags) + + remove := autoscaling.DeleteTagsInput{ + Tags: removeTags, + } + + if _, err := conn.DeleteTags(&remove); err != nil { + return err + } + } + + if len(createTags) > 0 { + log.Printf("[DEBUG] Creating autoscaling tags: %#v", createTags) + + create := autoscaling.CreateOrUpdateTagsInput{ + Tags: createTags, + } + + if _, err := conn.CreateOrUpdateTags(&create); err != nil { + return err } } @@ -90,11 +130,12 @@ func setAutoscalingTags(conn *autoscaling.AutoScaling, d *schema.ResourceData) e // diffTags takes our tags locally and the ones remotely and returns // the set of tags that must be created, and the set of tags that must // be destroyed. -func diffAutoscalingTags(oldTags, newTags []*autoscaling.Tag, resourceID string) ([]*autoscaling.Tag, []*autoscaling.Tag) { +func diffAutoscalingTags(oldTags, newTags []*autoscaling.Tag, resourceID string) ([]*autoscaling.Tag, []*autoscaling.Tag, error) { // First, we're creating everything we have create := make(map[string]interface{}) for _, t := range newTags { tag := map[string]interface{}{ + "key": *t.Key, "value": *t.Value, "propagate_at_launch": *t.PropagateAtLaunch, } @@ -112,27 +153,99 @@ func diffAutoscalingTags(oldTags, newTags []*autoscaling.Tag, resourceID string) } } - return autoscalingTagsFromMap(create, resourceID), remove + createTags, err := autoscalingTagsFromMap(create, resourceID) + if err != nil { + return nil, nil, err + } + + return createTags, remove, nil +} + +func autoscalingTagsFromList(vs []interface{}, resourceID string) ([]*autoscaling.Tag, error) { + result := make([]*autoscaling.Tag, 0, len(vs)) + for _, tag := range vs { + attr, ok := tag.(map[string]interface{}) + if !ok { + continue + } + + t, err := autoscalingTagFromMap(attr, resourceID) + if err != nil { + return nil, err + } + + if t != nil { + result = append(result, t) + } + } + return result, nil } // tagsFromMap returns the tags for the given map of data. -func autoscalingTagsFromMap(m map[string]interface{}, resourceID string) []*autoscaling.Tag { +func autoscalingTagsFromMap(m map[string]interface{}, resourceID string) ([]*autoscaling.Tag, error) { result := make([]*autoscaling.Tag, 0, len(m)) - for k, v := range m { - attr := v.(map[string]interface{}) - t := &autoscaling.Tag{ - Key: aws.String(k), - Value: aws.String(attr["value"].(string)), - PropagateAtLaunch: aws.Bool(attr["propagate_at_launch"].(bool)), - ResourceId: aws.String(resourceID), - ResourceType: aws.String("auto-scaling-group"), + for _, v := range m { + attr, ok := v.(map[string]interface{}) + if !ok { + continue } - if !tagIgnoredAutoscaling(t) { + + t, err := autoscalingTagFromMap(attr, resourceID) + if err != nil { + return nil, err + } + + if t != nil { result = append(result, t) } } - return result + return result, nil +} + +func autoscalingTagFromMap(attr map[string]interface{}, resourceID string) (*autoscaling.Tag, error) { + if _, ok := attr["key"]; !ok { + return nil, fmt.Errorf("%s: invalid tag attributes: key missing", resourceID) + } + + if _, ok := attr["value"]; !ok { + return nil, fmt.Errorf("%s: invalid tag attributes: value missing", resourceID) + } + + if _, ok := attr["propagate_at_launch"]; !ok { + return nil, fmt.Errorf("%s: invalid tag attributes: propagate_at_launch missing", resourceID) + } + + var propagateAtLaunch bool + var err error + + if v, ok := attr["propagate_at_launch"].(bool); ok { + propagateAtLaunch = v + } + + if v, ok := attr["propagate_at_launch"].(string); ok { + if propagateAtLaunch, err = strconv.ParseBool(v); err != nil { + return nil, fmt.Errorf( + "%s: invalid tag attribute: invalid value for propagate_at_launch: %s", + resourceID, + v, + ) + } + } + + t := &autoscaling.Tag{ + Key: aws.String(attr["key"].(string)), + Value: aws.String(attr["value"].(string)), + PropagateAtLaunch: aws.Bool(propagateAtLaunch), + ResourceId: aws.String(resourceID), + ResourceType: aws.String("auto-scaling-group"), + } + + if tagIgnoredAutoscaling(t) { + return nil, nil + } + + return t, nil } // autoscalingTagsToMap turns the list of tags into a map. @@ -140,6 +253,7 @@ func autoscalingTagsToMap(ts []*autoscaling.Tag) map[string]interface{} { tags := make(map[string]interface{}) for _, t := range ts { tag := map[string]interface{}{ + "key": *t.Key, "value": *t.Value, "propagate_at_launch": *t.PropagateAtLaunch, } @@ -154,6 +268,7 @@ func autoscalingTagDescriptionsToMap(ts *[]*autoscaling.TagDescription) map[stri tags := make(map[string]map[string]interface{}) for _, t := range *ts { tag := map[string]interface{}{ + "key": *t.Key, "value": *t.Value, "propagate_at_launch": *t.PropagateAtLaunch, } @@ -190,7 +305,7 @@ func setToMapByKey(s *schema.Set, key string) map[string]interface{} { // compare a tag against a list of strings and checks if it should // be ignored or not func tagIgnoredAutoscaling(t *autoscaling.Tag) bool { - filter := []string{"^aws:*"} + filter := []string{"^aws:"} for _, v := range filter { log.Printf("[DEBUG] Matching %v with %v\n", v, *t.Key) if r, _ := regexp.MatchString(v, *t.Key); r == true { diff --git a/builtin/providers/aws/autoscaling_tags_test.go b/builtin/providers/aws/autoscaling_tags_test.go index 04d8c15cb..0107764d1 100644 --- a/builtin/providers/aws/autoscaling_tags_test.go +++ b/builtin/providers/aws/autoscaling_tags_test.go @@ -20,24 +20,28 @@ func TestDiffAutoscalingTags(t *testing.T) { { Old: map[string]interface{}{ "Name": map[string]interface{}{ + "key": "Name", "value": "bar", "propagate_at_launch": true, }, }, New: map[string]interface{}{ "DifferentTag": map[string]interface{}{ + "key": "DifferentTag", "value": "baz", "propagate_at_launch": true, }, }, Create: map[string]interface{}{ "DifferentTag": map[string]interface{}{ + "key": "DifferentTag", "value": "baz", "propagate_at_launch": true, }, }, Remove: map[string]interface{}{ "Name": map[string]interface{}{ + "key": "Name", "value": "bar", "propagate_at_launch": true, }, @@ -48,24 +52,28 @@ func TestDiffAutoscalingTags(t *testing.T) { { Old: map[string]interface{}{ "Name": map[string]interface{}{ + "key": "Name", "value": "bar", "propagate_at_launch": true, }, }, New: map[string]interface{}{ "Name": map[string]interface{}{ + "key": "Name", "value": "baz", "propagate_at_launch": false, }, }, Create: map[string]interface{}{ "Name": map[string]interface{}{ + "key": "Name", "value": "baz", "propagate_at_launch": false, }, }, Remove: map[string]interface{}{ "Name": map[string]interface{}{ + "key": "Name", "value": "bar", "propagate_at_launch": true, }, @@ -76,10 +84,20 @@ func TestDiffAutoscalingTags(t *testing.T) { var resourceID = "sample" for i, tc := range cases { - awsTagsOld := autoscalingTagsFromMap(tc.Old, resourceID) - awsTagsNew := autoscalingTagsFromMap(tc.New, resourceID) + awsTagsOld, err := autoscalingTagsFromMap(tc.Old, resourceID) + if err != nil { + t.Fatalf("%d: unexpected error convertig old tags: %v", i, err) + } - c, r := diffAutoscalingTags(awsTagsOld, awsTagsNew, resourceID) + awsTagsNew, err := autoscalingTagsFromMap(tc.New, resourceID) + if err != nil { + t.Fatalf("%d: unexpected error convertig new tags: %v", i, err) + } + + c, r, err := diffAutoscalingTags(awsTagsOld, awsTagsNew, resourceID) + if err != nil { + t.Fatalf("%d: unexpected error diff'ing tags: %v", i, err) + } cm := autoscalingTagsToMap(c) rm := autoscalingTagsToMap(r) diff --git a/builtin/providers/aws/cloudfront_distribution_configuration_structure.go b/builtin/providers/aws/cloudfront_distribution_configuration_structure.go index 489e9883c..a47217647 100644 --- a/builtin/providers/aws/cloudfront_distribution_configuration_structure.go +++ b/builtin/providers/aws/cloudfront_distribution_configuration_structure.go @@ -773,21 +773,31 @@ func originCustomHeaderHash(v interface{}) int { } func expandCustomOriginConfig(m map[string]interface{}) *cloudfront.CustomOriginConfig { - return &cloudfront.CustomOriginConfig{ - OriginProtocolPolicy: aws.String(m["origin_protocol_policy"].(string)), - HTTPPort: aws.Int64(int64(m["http_port"].(int))), - HTTPSPort: aws.Int64(int64(m["https_port"].(int))), - OriginSslProtocols: expandCustomOriginConfigSSL(m["origin_ssl_protocols"].([]interface{})), + + customOrigin := &cloudfront.CustomOriginConfig{ + OriginProtocolPolicy: aws.String(m["origin_protocol_policy"].(string)), + HTTPPort: aws.Int64(int64(m["http_port"].(int))), + HTTPSPort: aws.Int64(int64(m["https_port"].(int))), + OriginSslProtocols: expandCustomOriginConfigSSL(m["origin_ssl_protocols"].([]interface{})), + OriginReadTimeout: aws.Int64(int64(m["origin_read_timeout"].(int))), + OriginKeepaliveTimeout: aws.Int64(int64(m["origin_keepalive_timeout"].(int))), } + + return customOrigin } func flattenCustomOriginConfig(cor *cloudfront.CustomOriginConfig) map[string]interface{} { - return map[string]interface{}{ - "origin_protocol_policy": *cor.OriginProtocolPolicy, - "http_port": int(*cor.HTTPPort), - "https_port": int(*cor.HTTPSPort), - "origin_ssl_protocols": flattenCustomOriginConfigSSL(cor.OriginSslProtocols), + + customOrigin := map[string]interface{}{ + "origin_protocol_policy": *cor.OriginProtocolPolicy, + "http_port": int(*cor.HTTPPort), + "https_port": int(*cor.HTTPSPort), + "origin_ssl_protocols": flattenCustomOriginConfigSSL(cor.OriginSslProtocols), + "origin_read_timeout": int(*cor.OriginReadTimeout), + "origin_keepalive_timeout": int(*cor.OriginKeepaliveTimeout), } + + return customOrigin } // Assemble the hash for the aws_cloudfront_distribution custom_origin_config @@ -801,6 +811,9 @@ func customOriginConfigHash(v interface{}) int { for _, v := range sortInterfaceSlice(m["origin_ssl_protocols"].([]interface{})) { buf.WriteString(fmt.Sprintf("%s-", v.(string))) } + buf.WriteString(fmt.Sprintf("%d-", m["origin_keepalive_timeout"].(int))) + buf.WriteString(fmt.Sprintf("%d-", m["origin_read_timeout"].(int))) + return hashcode.String(buf.String()) } diff --git a/builtin/providers/aws/cloudfront_distribution_configuration_structure_test.go b/builtin/providers/aws/cloudfront_distribution_configuration_structure_test.go index 0092cb8d2..cb594d48e 100644 --- a/builtin/providers/aws/cloudfront_distribution_configuration_structure_test.go +++ b/builtin/providers/aws/cloudfront_distribution_configuration_structure_test.go @@ -117,10 +117,12 @@ func originCustomHeaderConf2() map[string]interface{} { func customOriginConf() map[string]interface{} { return map[string]interface{}{ - "origin_protocol_policy": "http-only", - "http_port": 80, - "https_port": 443, - "origin_ssl_protocols": customOriginSslProtocolsConf(), + "origin_protocol_policy": "http-only", + "http_port": 80, + "https_port": 443, + "origin_ssl_protocols": customOriginSslProtocolsConf(), + "origin_read_timeout": 30, + "origin_keepalive_timeout": 5, } } @@ -785,6 +787,12 @@ func TestCloudFrontStructure_expandCustomOriginConfig(t *testing.T) { if *co.HTTPSPort != 443 { t.Fatalf("Expected HTTPSPort to be 443, got %v", *co.HTTPSPort) } + if *co.OriginReadTimeout != 30 { + t.Fatalf("Expected Origin Read Timeout to be 30, got %v", *co.OriginReadTimeout) + } + if *co.OriginKeepaliveTimeout != 5 { + t.Fatalf("Expected Origin Keepalive Timeout to be 5, got %v", *co.OriginKeepaliveTimeout) + } } func TestCloudFrontStructure_flattenCustomOriginConfig(t *testing.T) { diff --git a/builtin/providers/aws/config.go b/builtin/providers/aws/config.go index 1cfda12b7..e060dbda9 100644 --- a/builtin/providers/aws/config.go +++ b/builtin/providers/aws/config.go @@ -28,8 +28,10 @@ import ( "github.com/aws/aws-sdk-go/service/codecommit" "github.com/aws/aws-sdk-go/service/codedeploy" "github.com/aws/aws-sdk-go/service/codepipeline" + "github.com/aws/aws-sdk-go/service/cognitoidentity" "github.com/aws/aws-sdk-go/service/configservice" "github.com/aws/aws-sdk-go/service/databasemigrationservice" + "github.com/aws/aws-sdk-go/service/devicefarm" "github.com/aws/aws-sdk-go/service/directoryservice" "github.com/aws/aws-sdk-go/service/dynamodb" "github.com/aws/aws-sdk-go/service/ec2" @@ -64,6 +66,7 @@ import ( "github.com/aws/aws-sdk-go/service/ssm" "github.com/aws/aws-sdk-go/service/sts" "github.com/aws/aws-sdk-go/service/waf" + "github.com/aws/aws-sdk-go/service/wafregional" "github.com/davecgh/go-spew/spew" "github.com/hashicorp/errwrap" "github.com/hashicorp/go-cleanhttp" @@ -88,15 +91,25 @@ type Config struct { AllowedAccountIds []interface{} ForbiddenAccountIds []interface{} - DynamoDBEndpoint string - KinesisEndpoint string - Ec2Endpoint string - IamEndpoint string - ElbEndpoint string - S3Endpoint string - Insecure bool + CloudFormationEndpoint string + CloudWatchEndpoint string + CloudWatchEventsEndpoint string + CloudWatchLogsEndpoint string + DynamoDBEndpoint string + DeviceFarmEndpoint string + Ec2Endpoint string + ElbEndpoint string + IamEndpoint string + KinesisEndpoint string + KmsEndpoint string + RdsEndpoint string + S3Endpoint string + SnsEndpoint string + SqsEndpoint string + Insecure bool SkipCredsValidation bool + SkipGetEC2Platforms bool SkipRegionValidation bool SkipRequestingAccountId bool SkipMetadataApiCheck bool @@ -110,7 +123,9 @@ type AWSClient struct { cloudwatchconn *cloudwatch.CloudWatch cloudwatchlogsconn *cloudwatchlogs.CloudWatchLogs cloudwatcheventsconn *cloudwatchevents.CloudWatchEvents + cognitoconn *cognitoidentity.CognitoIdentity configconn *configservice.ConfigService + devicefarmconn *devicefarm.DeviceFarm dmsconn *databasemigrationservice.DatabaseMigrationService dsconn *directoryservice.DirectoryService dynamodbconn *dynamodb.DynamoDB @@ -158,6 +173,29 @@ type AWSClient struct { sfnconn *sfn.SFN ssmconn *ssm.SSM wafconn *waf.WAF + wafregionalconn *wafregional.WAFRegional +} + +func (c *AWSClient) S3() *s3.S3 { + return c.s3conn +} + +func (c *AWSClient) DynamoDB() *dynamodb.DynamoDB { + return c.dynamodbconn +} + +func (c *AWSClient) IsGovCloud() bool { + if c.region == "us-gov-west-1" { + return true + } + return false +} + +func (c *AWSClient) IsChinaCloud() bool { + if c.region == "cn-north-1" { + return true + } + return false } // Client configures and returns a fully initialized AWSClient @@ -239,12 +277,24 @@ func (c *Config) Client() (interface{}, error) { usEast1Sess := sess.Copy(&aws.Config{Region: aws.String("us-east-1")}) // Some services have user-configurable endpoints + awsCfSess := sess.Copy(&aws.Config{Endpoint: aws.String(c.CloudFormationEndpoint)}) + awsCwSess := sess.Copy(&aws.Config{Endpoint: aws.String(c.CloudWatchEndpoint)}) + awsCweSess := sess.Copy(&aws.Config{Endpoint: aws.String(c.CloudWatchEventsEndpoint)}) + awsCwlSess := sess.Copy(&aws.Config{Endpoint: aws.String(c.CloudWatchLogsEndpoint)}) + awsDynamoSess := sess.Copy(&aws.Config{Endpoint: aws.String(c.DynamoDBEndpoint)}) awsEc2Sess := sess.Copy(&aws.Config{Endpoint: aws.String(c.Ec2Endpoint)}) awsElbSess := sess.Copy(&aws.Config{Endpoint: aws.String(c.ElbEndpoint)}) awsIamSess := sess.Copy(&aws.Config{Endpoint: aws.String(c.IamEndpoint)}) + awsKinesisSess := sess.Copy(&aws.Config{Endpoint: aws.String(c.KinesisEndpoint)}) + awsKmsSess := sess.Copy(&aws.Config{Endpoint: aws.String(c.KmsEndpoint)}) + awsRdsSess := sess.Copy(&aws.Config{Endpoint: aws.String(c.RdsEndpoint)}) awsS3Sess := sess.Copy(&aws.Config{Endpoint: aws.String(c.S3Endpoint)}) - dynamoSess := sess.Copy(&aws.Config{Endpoint: aws.String(c.DynamoDBEndpoint)}) - kinesisSess := sess.Copy(&aws.Config{Endpoint: aws.String(c.KinesisEndpoint)}) + awsSnsSess := sess.Copy(&aws.Config{Endpoint: aws.String(c.SnsEndpoint)}) + awsSqsSess := sess.Copy(&aws.Config{Endpoint: aws.String(c.SqsEndpoint)}) + awsDeviceFarmSess := sess.Copy(&aws.Config{Endpoint: aws.String(c.DeviceFarmEndpoint)}) + + log.Println("[INFO] Initializing DeviceFarm SDK connection") + client.devicefarmconn = devicefarm.New(awsDeviceFarmSess) // These two services need to be set up early so we can check on AccountID client.iamconn = iam.New(awsIamSess) @@ -272,33 +322,36 @@ func (c *Config) Client() (interface{}, error) { client.ec2conn = ec2.New(awsEc2Sess) - supportedPlatforms, err := GetSupportedEC2Platforms(client.ec2conn) - if err != nil { - // We intentionally fail *silently* because there's a chance - // user just doesn't have ec2:DescribeAccountAttributes permissions - log.Printf("[WARN] Unable to get supported EC2 platforms: %s", err) - } else { - client.supportedplatforms = supportedPlatforms + if !c.SkipGetEC2Platforms { + supportedPlatforms, err := GetSupportedEC2Platforms(client.ec2conn) + if err != nil { + // We intentionally fail *silently* because there's a chance + // user just doesn't have ec2:DescribeAccountAttributes permissions + log.Printf("[WARN] Unable to get supported EC2 platforms: %s", err) + } else { + client.supportedplatforms = supportedPlatforms + } } client.acmconn = acm.New(sess) client.apigateway = apigateway.New(sess) client.appautoscalingconn = applicationautoscaling.New(sess) client.autoscalingconn = autoscaling.New(sess) - client.cfconn = cloudformation.New(sess) + client.cfconn = cloudformation.New(awsCfSess) client.cloudfrontconn = cloudfront.New(sess) client.cloudtrailconn = cloudtrail.New(sess) - client.cloudwatchconn = cloudwatch.New(sess) - client.cloudwatcheventsconn = cloudwatchevents.New(sess) - client.cloudwatchlogsconn = cloudwatchlogs.New(sess) + client.cloudwatchconn = cloudwatch.New(awsCwSess) + client.cloudwatcheventsconn = cloudwatchevents.New(awsCweSess) + client.cloudwatchlogsconn = cloudwatchlogs.New(awsCwlSess) client.codecommitconn = codecommit.New(sess) client.codebuildconn = codebuild.New(sess) client.codedeployconn = codedeploy.New(sess) client.configconn = configservice.New(sess) + client.cognitoconn = cognitoidentity.New(sess) client.dmsconn = databasemigrationservice.New(sess) client.codepipelineconn = codepipeline.New(sess) client.dsconn = directoryservice.New(sess) - client.dynamodbconn = dynamodb.New(dynamoSess) + client.dynamodbconn = dynamodb.New(awsDynamoSess) client.ecrconn = ecr.New(sess) client.ecsconn = ecs.New(sess) client.efsconn = efs.New(sess) @@ -312,22 +365,23 @@ func (c *Config) Client() (interface{}, error) { client.firehoseconn = firehose.New(sess) client.inspectorconn = inspector.New(sess) client.glacierconn = glacier.New(sess) - client.kinesisconn = kinesis.New(kinesisSess) - client.kmsconn = kms.New(sess) + client.kinesisconn = kinesis.New(awsKinesisSess) + client.kmsconn = kms.New(awsKmsSess) client.lambdaconn = lambda.New(sess) client.lightsailconn = lightsail.New(usEast1Sess) client.opsworksconn = opsworks.New(sess) client.r53conn = route53.New(usEast1Sess) - client.rdsconn = rds.New(sess) + client.rdsconn = rds.New(awsRdsSess) client.redshiftconn = redshift.New(sess) client.simpledbconn = simpledb.New(sess) client.s3conn = s3.New(awsS3Sess) client.sesConn = ses.New(sess) client.sfnconn = sfn.New(sess) - client.snsconn = sns.New(sess) - client.sqsconn = sqs.New(sess) + client.snsconn = sns.New(awsSnsSess) + client.sqsconn = sqs.New(awsSqsSess) client.ssmconn = ssm.New(sess) client.wafconn = waf.New(sess) + client.wafregionalconn = wafregional.New(sess) return &client, nil } diff --git a/builtin/providers/aws/data_source_aws_ami.go b/builtin/providers/aws/data_source_aws_ami.go index 877069a22..3439adaef 100644 --- a/builtin/providers/aws/data_source_aws_ami.go +++ b/builtin/providers/aws/data_source_aws_ami.go @@ -5,8 +5,6 @@ import ( "fmt" "log" "regexp" - "sort" - "time" "github.com/aws/aws-sdk-go/service/ec2" "github.com/hashicorp/terraform/helper/hashcode" @@ -181,7 +179,7 @@ func dataSourceAwsAmiRead(d *schema.ResourceData, meta interface{}) error { nameRegex, nameRegexOk := d.GetOk("name_regex") owners, ownersOk := d.GetOk("owners") - if executableUsersOk == false && filtersOk == false && nameRegexOk == false && ownersOk == false { + if !executableUsersOk && !filtersOk && !nameRegexOk && !ownersOk { return fmt.Errorf("One of executable_users, filters, name_regex, or owners must be assigned") } @@ -249,21 +247,9 @@ func dataSourceAwsAmiRead(d *schema.ResourceData, meta interface{}) error { return amiDescriptionAttributes(d, image) } -type imageSort []*ec2.Image - -func (a imageSort) Len() int { return len(a) } -func (a imageSort) Swap(i, j int) { a[i], a[j] = a[j], a[i] } -func (a imageSort) Less(i, j int) bool { - itime, _ := time.Parse(time.RFC3339, *a[i].CreationDate) - jtime, _ := time.Parse(time.RFC3339, *a[j].CreationDate) - return itime.Unix() < jtime.Unix() -} - // Returns the most recent AMI out of a slice of images. func mostRecentAmi(images []*ec2.Image) *ec2.Image { - sortedImages := images - sort.Sort(imageSort(sortedImages)) - return sortedImages[len(sortedImages)-1] + return sortImages(images)[0] } // populate the numerous fields that the image description returns. diff --git a/builtin/providers/aws/data_source_aws_ami_ids.go b/builtin/providers/aws/data_source_aws_ami_ids.go new file mode 100644 index 000000000..20df34ac3 --- /dev/null +++ b/builtin/providers/aws/data_source_aws_ami_ids.go @@ -0,0 +1,111 @@ +package aws + +import ( + "fmt" + "log" + "regexp" + + "github.com/aws/aws-sdk-go/service/ec2" + "github.com/hashicorp/terraform/helper/hashcode" + "github.com/hashicorp/terraform/helper/schema" +) + +func dataSourceAwsAmiIds() *schema.Resource { + return &schema.Resource{ + Read: dataSourceAwsAmiIdsRead, + + Schema: map[string]*schema.Schema{ + "filter": dataSourceFiltersSchema(), + "executable_users": { + Type: schema.TypeList, + Optional: true, + ForceNew: true, + Elem: &schema.Schema{Type: schema.TypeString}, + }, + "name_regex": { + Type: schema.TypeString, + Optional: true, + ForceNew: true, + ValidateFunc: validateNameRegex, + }, + "owners": { + Type: schema.TypeList, + Optional: true, + ForceNew: true, + Elem: &schema.Schema{Type: schema.TypeString}, + }, + "tags": dataSourceTagsSchema(), + "ids": &schema.Schema{ + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{Type: schema.TypeString}, + }, + }, + } +} + +func dataSourceAwsAmiIdsRead(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*AWSClient).ec2conn + + executableUsers, executableUsersOk := d.GetOk("executable_users") + filters, filtersOk := d.GetOk("filter") + nameRegex, nameRegexOk := d.GetOk("name_regex") + owners, ownersOk := d.GetOk("owners") + + if executableUsersOk == false && filtersOk == false && nameRegexOk == false && ownersOk == false { + return fmt.Errorf("One of executable_users, filters, name_regex, or owners must be assigned") + } + + params := &ec2.DescribeImagesInput{} + + if executableUsersOk { + params.ExecutableUsers = expandStringList(executableUsers.([]interface{})) + } + if filtersOk { + params.Filters = buildAwsDataSourceFilters(filters.(*schema.Set)) + } + if ownersOk { + o := expandStringList(owners.([]interface{})) + + if len(o) > 0 { + params.Owners = o + } + } + + resp, err := conn.DescribeImages(params) + if err != nil { + return err + } + + var filteredImages []*ec2.Image + imageIds := make([]string, 0) + + if nameRegexOk { + r := regexp.MustCompile(nameRegex.(string)) + for _, image := range resp.Images { + // Check for a very rare case where the response would include no + // image name. No name means nothing to attempt a match against, + // therefore we are skipping such image. + if image.Name == nil || *image.Name == "" { + log.Printf("[WARN] Unable to find AMI name to match against "+ + "for image ID %q owned by %q, nothing to do.", + *image.ImageId, *image.OwnerId) + continue + } + if r.MatchString(*image.Name) { + filteredImages = append(filteredImages, image) + } + } + } else { + filteredImages = resp.Images[:] + } + + for _, image := range sortImages(filteredImages) { + imageIds = append(imageIds, *image.ImageId) + } + + d.SetId(fmt.Sprintf("%d", hashcode.String(params.String()))) + d.Set("ids", imageIds) + + return nil +} diff --git a/builtin/providers/aws/data_source_aws_ami_ids_test.go b/builtin/providers/aws/data_source_aws_ami_ids_test.go new file mode 100644 index 000000000..52582eaba --- /dev/null +++ b/builtin/providers/aws/data_source_aws_ami_ids_test.go @@ -0,0 +1,128 @@ +package aws + +import ( + "fmt" + "testing" + + "github.com/hashicorp/terraform/helper/resource" + "github.com/satori/uuid" +) + +func TestAccDataSourceAwsAmiIds_basic(t *testing.T) { + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + Steps: []resource.TestStep{ + { + Config: testAccDataSourceAwsAmiIdsConfig_basic, + Check: resource.ComposeTestCheckFunc( + testAccCheckAwsAmiDataSourceID("data.aws_ami_ids.ubuntu"), + ), + }, + }, + }) +} + +func TestAccDataSourceAwsAmiIds_sorted(t *testing.T) { + uuid := uuid.NewV4().String() + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + Steps: []resource.TestStep{ + { + Config: testAccDataSourceAwsAmiIdsConfig_sorted1(uuid), + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttrSet("aws_ami_from_instance.a", "id"), + resource.TestCheckResourceAttrSet("aws_ami_from_instance.b", "id"), + ), + }, + { + Config: testAccDataSourceAwsAmiIdsConfig_sorted2(uuid), + Check: resource.ComposeTestCheckFunc( + testAccCheckAwsEbsSnapshotDataSourceID("data.aws_ami_ids.test"), + resource.TestCheckResourceAttr("data.aws_ami_ids.test", "ids.#", "2"), + resource.TestCheckResourceAttrPair( + "data.aws_ami_ids.test", "ids.0", + "aws_ami_from_instance.b", "id"), + resource.TestCheckResourceAttrPair( + "data.aws_ami_ids.test", "ids.1", + "aws_ami_from_instance.a", "id"), + ), + }, + }, + }) +} + +func TestAccDataSourceAwsAmiIds_empty(t *testing.T) { + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + Steps: []resource.TestStep{ + { + Config: testAccDataSourceAwsAmiIdsConfig_empty, + Check: resource.ComposeTestCheckFunc( + testAccCheckAwsAmiDataSourceID("data.aws_ami_ids.empty"), + resource.TestCheckResourceAttr("data.aws_ami_ids.empty", "ids.#", "0"), + ), + }, + }, + }) +} + +const testAccDataSourceAwsAmiIdsConfig_basic = ` +data "aws_ami_ids" "ubuntu" { + owners = ["099720109477"] + + filter { + name = "name" + values = ["ubuntu/images/ubuntu-*-*-amd64-server-*"] + } +} +` + +func testAccDataSourceAwsAmiIdsConfig_sorted1(uuid string) string { + return fmt.Sprintf(` +resource "aws_instance" "test" { + ami = "ami-efd0428f" + instance_type = "m3.medium" + + count = 2 +} + +resource "aws_ami_from_instance" "a" { + name = "tf-test-%s-a" + source_instance_id = "${aws_instance.test.*.id[0]}" + snapshot_without_reboot = true +} + +resource "aws_ami_from_instance" "b" { + name = "tf-test-%s-b" + source_instance_id = "${aws_instance.test.*.id[1]}" + snapshot_without_reboot = true + + // We want to ensure that 'aws_ami_from_instance.a.creation_date' is less + // than 'aws_ami_from_instance.b.creation_date' so that we can ensure that + // the images are being sorted correctly. + depends_on = ["aws_ami_from_instance.a"] +} +`, uuid, uuid) +} + +func testAccDataSourceAwsAmiIdsConfig_sorted2(uuid string) string { + return testAccDataSourceAwsAmiIdsConfig_sorted1(uuid) + fmt.Sprintf(` +data "aws_ami_ids" "test" { + owners = ["self"] + name_regex = "^tf-test-%s-" +} +`, uuid) +} + +const testAccDataSourceAwsAmiIdsConfig_empty = ` +data "aws_ami_ids" "empty" { + filter { + name = "name" + values = [] + } +} +` diff --git a/builtin/providers/aws/data_source_aws_caller_identity.go b/builtin/providers/aws/data_source_aws_caller_identity.go index 05c03864d..a2adcef34 100644 --- a/builtin/providers/aws/data_source_aws_caller_identity.go +++ b/builtin/providers/aws/data_source_aws_caller_identity.go @@ -5,6 +5,7 @@ import ( "log" "time" + "github.com/aws/aws-sdk-go/service/sts" "github.com/hashicorp/terraform/helper/schema" ) @@ -17,24 +18,33 @@ func dataSourceAwsCallerIdentity() *schema.Resource { Type: schema.TypeString, Computed: true, }, + + "arn": { + Type: schema.TypeString, + Computed: true, + }, + + "user_id": { + Type: schema.TypeString, + Computed: true, + }, }, } } func dataSourceAwsCallerIdentityRead(d *schema.ResourceData, meta interface{}) error { - client := meta.(*AWSClient) + client := meta.(*AWSClient).stsconn - log.Printf("[DEBUG] Reading Caller Identity.") - d.SetId(time.Now().UTC().String()) - - if client.accountid == "" { - log.Println("[DEBUG] No Account ID available, failing") - return fmt.Errorf("No AWS Account ID is available to the provider. Please ensure that\n" + - "skip_requesting_account_id is not set on the AWS provider.") + res, err := client.GetCallerIdentity(&sts.GetCallerIdentityInput{}) + if err != nil { + return fmt.Errorf("Error getting Caller Identity: %v", err) } - log.Printf("[DEBUG] Setting AWS Account ID to %s.", client.accountid) - d.Set("account_id", meta.(*AWSClient).accountid) + log.Printf("[DEBUG] Received Caller Identity: %s", res) + d.SetId(time.Now().UTC().String()) + d.Set("account_id", res.Account) + d.Set("arn", res.Arn) + d.Set("user_id", res.UserId) return nil } diff --git a/builtin/providers/aws/data_source_aws_caller_identity_test.go b/builtin/providers/aws/data_source_aws_caller_identity_test.go index f874d7da9..100bb4db8 100644 --- a/builtin/providers/aws/data_source_aws_caller_identity_test.go +++ b/builtin/providers/aws/data_source_aws_caller_identity_test.go @@ -39,6 +39,14 @@ func testAccCheckAwsCallerIdentityAccountId(n string) resource.TestCheckFunc { return fmt.Errorf("Incorrect Account ID: expected %q, got %q", expected, rs.Primary.Attributes["account_id"]) } + if rs.Primary.Attributes["user_id"] == "" { + return fmt.Errorf("UserID expected to not be nil") + } + + if rs.Primary.Attributes["arn"] == "" { + return fmt.Errorf("ARN expected to not be nil") + } + return nil } } diff --git a/builtin/providers/aws/data_source_aws_db_instance.go b/builtin/providers/aws/data_source_aws_db_instance.go index 8adec4127..753319a84 100644 --- a/builtin/providers/aws/data_source_aws_db_instance.go +++ b/builtin/providers/aws/data_source_aws_db_instance.go @@ -188,6 +188,11 @@ func dataSourceAwsDbInstance() *schema.Resource { Computed: true, Elem: &schema.Schema{Type: schema.TypeString}, }, + + "replicate_source_db": { + Type: schema.TypeString, + Computed: true, + }, }, } } @@ -271,6 +276,7 @@ func dataSourceAwsDbInstanceRead(d *schema.ResourceData, meta interface{}) error d.Set("storage_encrypted", dbInstance.StorageEncrypted) d.Set("storage_type", dbInstance.StorageType) d.Set("timezone", dbInstance.Timezone) + d.Set("replicate_source_db", dbInstance.ReadReplicaSourceDBInstanceIdentifier) var vpcSecurityGroups []string for _, v := range dbInstance.VpcSecurityGroups { diff --git a/builtin/providers/aws/data_source_aws_db_snapshot.go b/builtin/providers/aws/data_source_aws_db_snapshot.go new file mode 100644 index 000000000..1f381e405 --- /dev/null +++ b/builtin/providers/aws/data_source_aws_db_snapshot.go @@ -0,0 +1,217 @@ +package aws + +import ( + "fmt" + "log" + "sort" + "time" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/service/rds" + "github.com/hashicorp/terraform/helper/schema" +) + +func dataSourceAwsDbSnapshot() *schema.Resource { + return &schema.Resource{ + Read: dataSourceAwsDbSnapshotRead, + + Schema: map[string]*schema.Schema{ + //selection criteria + "db_instance_identifier": { + Type: schema.TypeString, + Optional: true, + ForceNew: true, + }, + + "db_snapshot_identifier": { + Type: schema.TypeString, + Optional: true, + ForceNew: true, + }, + + "snapshot_type": { + Type: schema.TypeString, + Optional: true, + ForceNew: true, + }, + + "include_shared": { + Type: schema.TypeBool, + Optional: true, + ForceNew: true, + Default: false, + }, + + "include_public": { + Type: schema.TypeBool, + Optional: true, + ForceNew: true, + Default: false, + }, + "most_recent": { + Type: schema.TypeBool, + Optional: true, + Default: false, + ForceNew: true, + }, + + //Computed values returned + "allocated_storage": { + Type: schema.TypeInt, + Computed: true, + }, + "availability_zone": { + Type: schema.TypeString, + Computed: true, + }, + "db_snapshot_arn": { + Type: schema.TypeString, + Computed: true, + }, + "encrypted": { + Type: schema.TypeBool, + Computed: true, + }, + "engine": { + Type: schema.TypeString, + Computed: true, + }, + "engine_version": { + Type: schema.TypeString, + Computed: true, + }, + "iops": { + Type: schema.TypeInt, + Computed: true, + }, + "kms_key_id": { + Type: schema.TypeString, + Computed: true, + }, + "license_model": { + Type: schema.TypeString, + Computed: true, + }, + "option_group_name": { + Type: schema.TypeString, + Computed: true, + }, + "port": { + Type: schema.TypeInt, + Computed: true, + }, + "source_db_snapshot_identifier": { + Type: schema.TypeString, + Computed: true, + }, + "source_region": { + Type: schema.TypeString, + Computed: true, + }, + "snapshot_create_time": { + Type: schema.TypeString, + Computed: true, + }, + "status": { + Type: schema.TypeString, + Computed: true, + }, + "storage_type": { + Type: schema.TypeString, + Computed: true, + }, + "vpc_id": { + Type: schema.TypeString, + Computed: true, + }, + }, + } +} + +func dataSourceAwsDbSnapshotRead(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*AWSClient).rdsconn + + instanceIdentifier, instanceIdentifierOk := d.GetOk("db_instance_identifier") + snapshotIdentifier, snapshotIdentifierOk := d.GetOk("db_snapshot_identifier") + + if !instanceIdentifierOk && !snapshotIdentifierOk { + return fmt.Errorf("One of db_snapshot_indentifier or db_instance_identifier must be assigned") + } + + params := &rds.DescribeDBSnapshotsInput{ + IncludePublic: aws.Bool(d.Get("include_public").(bool)), + IncludeShared: aws.Bool(d.Get("include_shared").(bool)), + } + if v, ok := d.GetOk("snapshot_type"); ok { + params.SnapshotType = aws.String(v.(string)) + } + if instanceIdentifierOk { + params.DBInstanceIdentifier = aws.String(instanceIdentifier.(string)) + } + if snapshotIdentifierOk { + params.DBSnapshotIdentifier = aws.String(snapshotIdentifier.(string)) + } + + resp, err := conn.DescribeDBSnapshots(params) + if err != nil { + return err + } + + if len(resp.DBSnapshots) < 1 { + return fmt.Errorf("Your query returned no results. Please change your search criteria and try again.") + } + + var snapshot *rds.DBSnapshot + if len(resp.DBSnapshots) > 1 { + recent := d.Get("most_recent").(bool) + log.Printf("[DEBUG] aws_db_snapshot - multiple results found and `most_recent` is set to: %t", recent) + if recent { + snapshot = mostRecentDbSnapshot(resp.DBSnapshots) + } else { + return fmt.Errorf("Your query returned more than one result. Please try a more specific search criteria.") + } + } else { + snapshot = resp.DBSnapshots[0] + } + + return dbSnapshotDescriptionAttributes(d, snapshot) +} + +type rdsSnapshotSort []*rds.DBSnapshot + +func (a rdsSnapshotSort) Len() int { return len(a) } +func (a rdsSnapshotSort) Swap(i, j int) { a[i], a[j] = a[j], a[i] } +func (a rdsSnapshotSort) Less(i, j int) bool { + return (*a[i].SnapshotCreateTime).Before(*a[j].SnapshotCreateTime) +} + +func mostRecentDbSnapshot(snapshots []*rds.DBSnapshot) *rds.DBSnapshot { + sortedSnapshots := snapshots + sort.Sort(rdsSnapshotSort(sortedSnapshots)) + return sortedSnapshots[len(sortedSnapshots)-1] +} + +func dbSnapshotDescriptionAttributes(d *schema.ResourceData, snapshot *rds.DBSnapshot) error { + d.SetId(*snapshot.DBInstanceIdentifier) + d.Set("db_instance_identifier", snapshot.DBInstanceIdentifier) + d.Set("db_snapshot_identifier", snapshot.DBSnapshotIdentifier) + d.Set("snapshot_type", snapshot.SnapshotType) + d.Set("allocated_storage", snapshot.AllocatedStorage) + d.Set("availability_zone", snapshot.AvailabilityZone) + d.Set("db_snapshot_arn", snapshot.DBSnapshotArn) + d.Set("encrypted", snapshot.Encrypted) + d.Set("engine", snapshot.Engine) + d.Set("engine_version", snapshot.EngineVersion) + d.Set("iops", snapshot.Iops) + d.Set("kms_key_id", snapshot.KmsKeyId) + d.Set("license_model", snapshot.LicenseModel) + d.Set("option_group_name", snapshot.OptionGroupName) + d.Set("port", snapshot.Port) + d.Set("source_db_snapshot_identifier", snapshot.SourceDBSnapshotIdentifier) + d.Set("source_region", snapshot.SourceRegion) + d.Set("status", snapshot.Status) + d.Set("vpc_id", snapshot.VpcId) + d.Set("snapshot_create_time", snapshot.SnapshotCreateTime.Format(time.RFC3339)) + + return nil +} diff --git a/builtin/providers/aws/data_source_aws_db_snapshot_test.go b/builtin/providers/aws/data_source_aws_db_snapshot_test.go new file mode 100644 index 000000000..0b300b5a2 --- /dev/null +++ b/builtin/providers/aws/data_source_aws_db_snapshot_test.go @@ -0,0 +1,74 @@ +package aws + +import ( + "fmt" + "testing" + + "github.com/hashicorp/terraform/helper/acctest" + "github.com/hashicorp/terraform/helper/resource" + "github.com/hashicorp/terraform/terraform" +) + +func TestAccAWSDbSnapshotDataSource_basic(t *testing.T) { + rInt := acctest.RandInt() + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + Steps: []resource.TestStep{ + { + Config: testAccCheckAwsDbSnapshotDataSourceConfig(rInt), + Check: resource.ComposeTestCheckFunc( + testAccCheckAwsDbSnapshotDataSourceID("data.aws_db_snapshot.snapshot"), + ), + }, + }, + }) +} + +func testAccCheckAwsDbSnapshotDataSourceID(n string) resource.TestCheckFunc { + return func(s *terraform.State) error { + rs, ok := s.RootModule().Resources[n] + if !ok { + return fmt.Errorf("Can't find Volume data source: %s", n) + } + + if rs.Primary.ID == "" { + return fmt.Errorf("Snapshot data source ID not set") + } + return nil + } +} + +func testAccCheckAwsDbSnapshotDataSourceConfig(rInt int) string { + return fmt.Sprintf(` +resource "aws_db_instance" "bar" { + allocated_storage = 10 + engine = "MySQL" + engine_version = "5.6.21" + instance_class = "db.t1.micro" + name = "baz" + password = "barbarbarbar" + username = "foo" + + + # Maintenance Window is stored in lower case in the API, though not strictly + # documented. Terraform will downcase this to match (as opposed to throw a + # validation error). + maintenance_window = "Fri:09:00-Fri:09:30" + + backup_retention_period = 0 + + parameter_group_name = "default.mysql5.6" +} + +data "aws_db_snapshot" "snapshot" { + most_recent = "true" + db_snapshot_identifier = "${aws_db_snapshot.test.id}" +} + + +resource "aws_db_snapshot" "test" { + db_instance_identifier = "${aws_db_instance.bar.id}" + db_snapshot_identifier = "testsnapshot%d" +}`, rInt) +} diff --git a/builtin/providers/aws/data_source_aws_ebs_snapshot.go b/builtin/providers/aws/data_source_aws_ebs_snapshot.go index b16f61f22..c0e386643 100644 --- a/builtin/providers/aws/data_source_aws_ebs_snapshot.go +++ b/builtin/providers/aws/data_source_aws_ebs_snapshot.go @@ -3,7 +3,6 @@ package aws import ( "fmt" "log" - "sort" "github.com/aws/aws-sdk-go/service/ec2" "github.com/hashicorp/terraform/helper/schema" @@ -94,7 +93,7 @@ func dataSourceAwsEbsSnapshotRead(d *schema.ResourceData, meta interface{}) erro snapshotIds, snapshotIdsOk := d.GetOk("snapshot_ids") owners, ownersOk := d.GetOk("owners") - if restorableUsers == false && filtersOk == false && snapshotIds == false && ownersOk == false { + if !restorableUsersOk && !filtersOk && !snapshotIdsOk && !ownersOk { return fmt.Errorf("One of snapshot_ids, filters, restorable_by_user_ids, or owners must be assigned") } @@ -138,20 +137,8 @@ func dataSourceAwsEbsSnapshotRead(d *schema.ResourceData, meta interface{}) erro return snapshotDescriptionAttributes(d, snapshot) } -type snapshotSort []*ec2.Snapshot - -func (a snapshotSort) Len() int { return len(a) } -func (a snapshotSort) Swap(i, j int) { a[i], a[j] = a[j], a[i] } -func (a snapshotSort) Less(i, j int) bool { - itime := *a[i].StartTime - jtime := *a[j].StartTime - return itime.Unix() < jtime.Unix() -} - func mostRecentSnapshot(snapshots []*ec2.Snapshot) *ec2.Snapshot { - sortedSnapshots := snapshots - sort.Sort(snapshotSort(sortedSnapshots)) - return sortedSnapshots[len(sortedSnapshots)-1] + return sortSnapshots(snapshots)[0] } func snapshotDescriptionAttributes(d *schema.ResourceData, snapshot *ec2.Snapshot) error { diff --git a/builtin/providers/aws/data_source_aws_ebs_snapshot_ids.go b/builtin/providers/aws/data_source_aws_ebs_snapshot_ids.go new file mode 100644 index 000000000..bd4f2ad8b --- /dev/null +++ b/builtin/providers/aws/data_source_aws_ebs_snapshot_ids.go @@ -0,0 +1,77 @@ +package aws + +import ( + "fmt" + + "github.com/aws/aws-sdk-go/service/ec2" + "github.com/hashicorp/terraform/helper/hashcode" + "github.com/hashicorp/terraform/helper/schema" +) + +func dataSourceAwsEbsSnapshotIds() *schema.Resource { + return &schema.Resource{ + Read: dataSourceAwsEbsSnapshotIdsRead, + + Schema: map[string]*schema.Schema{ + "filter": dataSourceFiltersSchema(), + "owners": { + Type: schema.TypeList, + Optional: true, + ForceNew: true, + Elem: &schema.Schema{Type: schema.TypeString}, + }, + "restorable_by_user_ids": { + Type: schema.TypeList, + Optional: true, + ForceNew: true, + Elem: &schema.Schema{Type: schema.TypeString}, + }, + "tags": dataSourceTagsSchema(), + "ids": &schema.Schema{ + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{Type: schema.TypeString}, + }, + }, + } +} + +func dataSourceAwsEbsSnapshotIdsRead(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*AWSClient).ec2conn + + restorableUsers, restorableUsersOk := d.GetOk("restorable_by_user_ids") + filters, filtersOk := d.GetOk("filter") + owners, ownersOk := d.GetOk("owners") + + if restorableUsers == false && filtersOk == false && ownersOk == false { + return fmt.Errorf("One of filters, restorable_by_user_ids, or owners must be assigned") + } + + params := &ec2.DescribeSnapshotsInput{} + + if restorableUsersOk { + params.RestorableByUserIds = expandStringList(restorableUsers.([]interface{})) + } + if filtersOk { + params.Filters = buildAwsDataSourceFilters(filters.(*schema.Set)) + } + if ownersOk { + params.OwnerIds = expandStringList(owners.([]interface{})) + } + + resp, err := conn.DescribeSnapshots(params) + if err != nil { + return err + } + + snapshotIds := make([]string, 0) + + for _, snapshot := range sortSnapshots(resp.Snapshots) { + snapshotIds = append(snapshotIds, *snapshot.SnapshotId) + } + + d.SetId(fmt.Sprintf("%d", hashcode.String(params.String()))) + d.Set("ids", snapshotIds) + + return nil +} diff --git a/builtin/providers/aws/data_source_aws_ebs_snapshot_ids_test.go b/builtin/providers/aws/data_source_aws_ebs_snapshot_ids_test.go new file mode 100644 index 000000000..0c5f3ec4d --- /dev/null +++ b/builtin/providers/aws/data_source_aws_ebs_snapshot_ids_test.go @@ -0,0 +1,131 @@ +package aws + +import ( + "fmt" + "testing" + + "github.com/hashicorp/terraform/helper/resource" + "github.com/satori/uuid" +) + +func TestAccDataSourceAwsEbsSnapshotIds_basic(t *testing.T) { + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + Steps: []resource.TestStep{ + { + Config: testAccDataSourceAwsEbsSnapshotIdsConfig_basic, + Check: resource.ComposeTestCheckFunc( + testAccCheckAwsEbsSnapshotDataSourceID("data.aws_ebs_snapshot_ids.test"), + ), + }, + }, + }) +} + +func TestAccDataSourceAwsEbsSnapshotIds_sorted(t *testing.T) { + uuid := uuid.NewV4().String() + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + Steps: []resource.TestStep{ + { + Config: testAccDataSourceAwsEbsSnapshotIdsConfig_sorted1(uuid), + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttrSet("aws_ebs_snapshot.a", "id"), + resource.TestCheckResourceAttrSet("aws_ebs_snapshot.b", "id"), + ), + }, + { + Config: testAccDataSourceAwsEbsSnapshotIdsConfig_sorted2(uuid), + Check: resource.ComposeTestCheckFunc( + testAccCheckAwsEbsSnapshotDataSourceID("data.aws_ebs_snapshot_ids.test"), + resource.TestCheckResourceAttr("data.aws_ebs_snapshot_ids.test", "ids.#", "2"), + resource.TestCheckResourceAttrPair( + "data.aws_ebs_snapshot_ids.test", "ids.0", + "aws_ebs_snapshot.b", "id"), + resource.TestCheckResourceAttrPair( + "data.aws_ebs_snapshot_ids.test", "ids.1", + "aws_ebs_snapshot.a", "id"), + ), + }, + }, + }) +} + +func TestAccDataSourceAwsEbsSnapshotIds_empty(t *testing.T) { + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + Steps: []resource.TestStep{ + { + Config: testAccDataSourceAwsEbsSnapshotIdsConfig_empty, + Check: resource.ComposeTestCheckFunc( + testAccCheckAwsEbsSnapshotDataSourceID("data.aws_ebs_snapshot_ids.empty"), + resource.TestCheckResourceAttr("data.aws_ebs_snapshot_ids.empty", "ids.#", "0"), + ), + }, + }, + }) +} + +const testAccDataSourceAwsEbsSnapshotIdsConfig_basic = ` +resource "aws_ebs_volume" "test" { + availability_zone = "us-west-2a" + size = 1 +} + +resource "aws_ebs_snapshot" "test" { + volume_id = "${aws_ebs_volume.test.id}" +} + +data "aws_ebs_snapshot_ids" "test" { + owners = ["self"] +} +` + +func testAccDataSourceAwsEbsSnapshotIdsConfig_sorted1(uuid string) string { + return fmt.Sprintf(` +resource "aws_ebs_volume" "test" { + availability_zone = "us-west-2a" + size = 1 + + count = 2 +} + +resource "aws_ebs_snapshot" "a" { + volume_id = "${aws_ebs_volume.test.*.id[0]}" + description = "tf-test-%s" +} + +resource "aws_ebs_snapshot" "b" { + volume_id = "${aws_ebs_volume.test.*.id[1]}" + description = "tf-test-%s" + + // We want to ensure that 'aws_ebs_snapshot.a.creation_date' is less than + // 'aws_ebs_snapshot.b.creation_date'/ so that we can ensure that the + // snapshots are being sorted correctly. + depends_on = ["aws_ebs_snapshot.a"] +} +`, uuid, uuid) +} + +func testAccDataSourceAwsEbsSnapshotIdsConfig_sorted2(uuid string) string { + return testAccDataSourceAwsEbsSnapshotIdsConfig_sorted1(uuid) + fmt.Sprintf(` +data "aws_ebs_snapshot_ids" "test" { + owners = ["self"] + + filter { + name = "description" + values = ["tf-test-%s"] + } +} +`, uuid) +} + +const testAccDataSourceAwsEbsSnapshotIdsConfig_empty = ` +data "aws_ebs_snapshot_ids" "empty" { + owners = ["000000000000"] +} +` diff --git a/builtin/providers/aws/data_source_aws_ebs_snapshot_test.go b/builtin/providers/aws/data_source_aws_ebs_snapshot_test.go index 682e758cc..58a20165a 100644 --- a/builtin/providers/aws/data_source_aws_ebs_snapshot_test.go +++ b/builtin/providers/aws/data_source_aws_ebs_snapshot_test.go @@ -44,7 +44,7 @@ func testAccCheckAwsEbsSnapshotDataSourceID(n string) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[n] if !ok { - return fmt.Errorf("Can't find Volume data source: %s", n) + return fmt.Errorf("Can't find snapshot data source: %s", n) } if rs.Primary.ID == "" { diff --git a/builtin/providers/aws/data_source_aws_ecs_task_definition_test.go b/builtin/providers/aws/data_source_aws_ecs_task_definition_test.go index 545da0714..6d6ffa35a 100644 --- a/builtin/providers/aws/data_source_aws_ecs_task_definition_test.go +++ b/builtin/providers/aws/data_source_aws_ecs_task_definition_test.go @@ -15,10 +15,10 @@ func TestAccAWSEcsDataSource_ecsTaskDefinition(t *testing.T) { resource.TestStep{ Config: testAccCheckAwsEcsTaskDefinitionDataSourceConfig, Check: resource.ComposeTestCheckFunc( - resource.TestMatchResourceAttr("data.aws_ecs_task_definition.mongo", "id", regexp.MustCompile("^arn:aws:ecs:us-west-2:[0-9]{12}:task-definition/mongodb:[1-9]*[0-9]$")), + resource.TestMatchResourceAttr("data.aws_ecs_task_definition.mongo", "id", regexp.MustCompile("^arn:aws:ecs:us-west-2:[0-9]{12}:task-definition/mongodb:[1-9][0-9]*$")), resource.TestCheckResourceAttr("data.aws_ecs_task_definition.mongo", "family", "mongodb"), resource.TestCheckResourceAttr("data.aws_ecs_task_definition.mongo", "network_mode", "bridge"), - resource.TestMatchResourceAttr("data.aws_ecs_task_definition.mongo", "revision", regexp.MustCompile("^[1-9]*[0-9]$")), + resource.TestMatchResourceAttr("data.aws_ecs_task_definition.mongo", "revision", regexp.MustCompile("^[1-9][0-9]*$")), resource.TestCheckResourceAttr("data.aws_ecs_task_definition.mongo", "status", "ACTIVE"), resource.TestMatchResourceAttr("data.aws_ecs_task_definition.mongo", "task_role_arn", regexp.MustCompile("^arn:aws:iam::[0-9]{12}:role/mongo_role$")), ), diff --git a/builtin/providers/aws/data_source_aws_efs_file_system.go b/builtin/providers/aws/data_source_aws_efs_file_system.go new file mode 100644 index 000000000..014ae1353 --- /dev/null +++ b/builtin/providers/aws/data_source_aws_efs_file_system.go @@ -0,0 +1,113 @@ +package aws + +import ( + "fmt" + "log" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/service/efs" + "github.com/hashicorp/errwrap" + "github.com/hashicorp/terraform/helper/schema" +) + +func dataSourceAwsEfsFileSystem() *schema.Resource { + return &schema.Resource{ + Read: dataSourceAwsEfsFileSystemRead, + + Schema: map[string]*schema.Schema{ + "creation_token": { + Type: schema.TypeString, + Optional: true, + Computed: true, + ForceNew: true, + ValidateFunc: validateMaxLength(64), + }, + "file_system_id": { + Type: schema.TypeString, + Optional: true, + Computed: true, + ForceNew: true, + }, + "performance_mode": { + Type: schema.TypeString, + Computed: true, + }, + "tags": tagsSchemaComputed(), + }, + } +} + +func dataSourceAwsEfsFileSystemRead(d *schema.ResourceData, meta interface{}) error { + efsconn := meta.(*AWSClient).efsconn + + describeEfsOpts := &efs.DescribeFileSystemsInput{} + + if v, ok := d.GetOk("creation_token"); ok { + describeEfsOpts.CreationToken = aws.String(v.(string)) + } + + if v, ok := d.GetOk("file_system_id"); ok { + describeEfsOpts.FileSystemId = aws.String(v.(string)) + } + + describeResp, err := efsconn.DescribeFileSystems(describeEfsOpts) + if err != nil { + return errwrap.Wrapf("Error retrieving EFS: {{err}}", err) + } + if len(describeResp.FileSystems) != 1 { + return fmt.Errorf("Search returned %d results, please revise so only one is returned", len(describeResp.FileSystems)) + } + + d.SetId(*describeResp.FileSystems[0].FileSystemId) + + tags := make([]*efs.Tag, 0) + var marker string + for { + params := &efs.DescribeTagsInput{ + FileSystemId: aws.String(d.Id()), + } + if marker != "" { + params.Marker = aws.String(marker) + } + + tagsResp, err := efsconn.DescribeTags(params) + if err != nil { + return fmt.Errorf("Error retrieving EC2 tags for EFS file system (%q): %s", + d.Id(), err.Error()) + } + + for _, tag := range tagsResp.Tags { + tags = append(tags, tag) + } + + if tagsResp.NextMarker != nil { + marker = *tagsResp.NextMarker + } else { + break + } + } + + err = d.Set("tags", tagsToMapEFS(tags)) + if err != nil { + return err + } + + var fs *efs.FileSystemDescription + for _, f := range describeResp.FileSystems { + if d.Id() == *f.FileSystemId { + fs = f + break + } + } + if fs == nil { + log.Printf("[WARN] EFS (%s) not found, removing from state", d.Id()) + d.SetId("") + return nil + } + + d.Set("creation_token", fs.CreationToken) + d.Set("performance_mode", fs.PerformanceMode) + d.Set("file_system_id", fs.FileSystemId) + + return nil +} diff --git a/builtin/providers/aws/data_source_aws_efs_file_system_test.go b/builtin/providers/aws/data_source_aws_efs_file_system_test.go new file mode 100644 index 000000000..925e6afd8 --- /dev/null +++ b/builtin/providers/aws/data_source_aws_efs_file_system_test.go @@ -0,0 +1,71 @@ +package aws + +import ( + "fmt" + "testing" + + "github.com/hashicorp/terraform/helper/resource" + "github.com/hashicorp/terraform/terraform" +) + +func TestAccDataSourceAwsEfsFileSystem(t *testing.T) { + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + Steps: []resource.TestStep{ + { + Config: testAccDataSourceAwsEfsFileSystemConfig, + Check: resource.ComposeTestCheckFunc( + testAccDataSourceAwsEfsFileSystemCheck("data.aws_efs_file_system.by_creation_token"), + testAccDataSourceAwsEfsFileSystemCheck("data.aws_efs_file_system.by_id"), + ), + }, + }, + }) +} + +func testAccDataSourceAwsEfsFileSystemCheck(name string) resource.TestCheckFunc { + return func(s *terraform.State) error { + rs, ok := s.RootModule().Resources[name] + if !ok { + return fmt.Errorf("root module has no resource called %s", name) + } + + efsRs, ok := s.RootModule().Resources["aws_efs_file_system.test"] + if !ok { + return fmt.Errorf("can't find aws_efs_file_system.test in state") + } + + attr := rs.Primary.Attributes + + if attr["creation_token"] != efsRs.Primary.Attributes["creation_token"] { + return fmt.Errorf( + "creation_token is %s; want %s", + attr["creation_token"], + efsRs.Primary.Attributes["creation_token"], + ) + } + + if attr["id"] != efsRs.Primary.Attributes["id"] { + return fmt.Errorf( + "file_system_id is %s; want %s", + attr["id"], + efsRs.Primary.Attributes["id"], + ) + } + + return nil + } +} + +const testAccDataSourceAwsEfsFileSystemConfig = ` +resource "aws_efs_file_system" "test" {} + +data "aws_efs_file_system" "by_creation_token" { + creation_token = "${aws_efs_file_system.test.creation_token}" +} + +data "aws_efs_file_system" "by_id" { + file_system_id = "${aws_efs_file_system.test.id}" +} +` diff --git a/builtin/providers/aws/data_source_aws_iam_account_alias.go b/builtin/providers/aws/data_source_aws_iam_account_alias.go index c8b8378cf..f93897373 100644 --- a/builtin/providers/aws/data_source_aws_iam_account_alias.go +++ b/builtin/providers/aws/data_source_aws_iam_account_alias.go @@ -34,6 +34,7 @@ func dataSourceAwsIamAccountAliasRead(d *schema.ResourceData, meta interface{}) if err != nil { return err } + // 'AccountAliases': [] if there is no alias. if resp == nil || len(resp.AccountAliases) == 0 { return fmt.Errorf("no IAM account alias found") diff --git a/builtin/providers/aws/data_source_aws_iam_account_alias_test.go b/builtin/providers/aws/data_source_aws_iam_account_alias_test.go deleted file mode 100644 index a23a6a93e..000000000 --- a/builtin/providers/aws/data_source_aws_iam_account_alias_test.go +++ /dev/null @@ -1,43 +0,0 @@ -package aws - -import ( - "fmt" - "testing" - - "github.com/hashicorp/terraform/helper/resource" - "github.com/hashicorp/terraform/terraform" -) - -func TestAccAWSIamAccountAlias_basic(t *testing.T) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: testAccCheckAwsIamAccountAliasConfig_basic, - Check: resource.ComposeTestCheckFunc( - testAccCheckAwsIamAccountAlias("data.aws_iam_account_alias.current"), - ), - }, - }, - }) -} - -func testAccCheckAwsIamAccountAlias(n string) resource.TestCheckFunc { - return func(s *terraform.State) error { - rs, ok := s.RootModule().Resources[n] - if !ok { - return fmt.Errorf("Can't find Account Alias resource: %s", n) - } - - if rs.Primary.Attributes["account_alias"] == "" { - return fmt.Errorf("Missing Account Alias") - } - - return nil - } -} - -const testAccCheckAwsIamAccountAliasConfig_basic = ` -data "aws_iam_account_alias" "current" { } -` diff --git a/builtin/providers/aws/data_source_aws_iam_role.go b/builtin/providers/aws/data_source_aws_iam_role.go new file mode 100644 index 000000000..f681268b9 --- /dev/null +++ b/builtin/providers/aws/data_source_aws_iam_role.go @@ -0,0 +1,67 @@ +package aws + +import ( + "fmt" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/service/iam" + "github.com/hashicorp/errwrap" + "github.com/hashicorp/terraform/helper/schema" +) + +func dataSourceAwsIAMRole() *schema.Resource { + return &schema.Resource{ + Read: dataSourceAwsIAMRoleRead, + + Schema: map[string]*schema.Schema{ + "arn": { + Type: schema.TypeString, + Computed: true, + }, + "assume_role_policy_document": { + Type: schema.TypeString, + Computed: true, + }, + "path": { + Type: schema.TypeString, + Computed: true, + }, + "role_id": { + Type: schema.TypeString, + Computed: true, + }, + "role_name": { + Type: schema.TypeString, + Required: true, + }, + }, + } +} + +func dataSourceAwsIAMRoleRead(d *schema.ResourceData, meta interface{}) error { + iamconn := meta.(*AWSClient).iamconn + + roleName := d.Get("role_name").(string) + + req := &iam.GetRoleInput{ + RoleName: aws.String(roleName), + } + + resp, err := iamconn.GetRole(req) + if err != nil { + return errwrap.Wrapf("Error getting roles: {{err}}", err) + } + if resp == nil { + return fmt.Errorf("no IAM role found") + } + + role := resp.Role + + d.SetId(*role.RoleId) + d.Set("arn", role.Arn) + d.Set("assume_role_policy_document", role.AssumeRolePolicyDocument) + d.Set("path", role.Path) + d.Set("role_id", role.RoleId) + + return nil +} diff --git a/builtin/providers/aws/data_source_aws_iam_role_test.go b/builtin/providers/aws/data_source_aws_iam_role_test.go new file mode 100644 index 000000000..160e5d49b --- /dev/null +++ b/builtin/providers/aws/data_source_aws_iam_role_test.go @@ -0,0 +1,59 @@ +package aws + +import ( + "regexp" + "testing" + + "github.com/hashicorp/terraform/helper/resource" +) + +func TestAccAWSDataSourceIAMRole_basic(t *testing.T) { + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + Steps: []resource.TestStep{ + { + Config: testAccAwsIAMRoleConfig, + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttrSet("data.aws_iam_role.test", "role_id"), + resource.TestCheckResourceAttr("data.aws_iam_role.test", "assume_role_policy_document", "%7B%22Version%22%3A%222012-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"), + resource.TestCheckResourceAttr("data.aws_iam_role.test", "path", "/testpath/"), + resource.TestCheckResourceAttr("data.aws_iam_role.test", "role_name", "TestRole"), + resource.TestMatchResourceAttr("data.aws_iam_role.test", "arn", regexp.MustCompile("^arn:aws:iam::[0-9]{12}:role/testpath/TestRole$")), + ), + }, + }, + }) +} + +const testAccAwsIAMRoleConfig = ` +provider "aws" { + region = "us-east-1" +} + +resource "aws_iam_role" "test_role" { + name = "TestRole" + + assume_role_policy = < 0 { for _, pair := range perm.UserIdGroupPairs { p := &ec2.IpPermission{ - FromPort: perm.FromPort, - IpProtocol: perm.IpProtocol, - PrefixListIds: perm.PrefixListIds, - ToPort: perm.ToPort, - + FromPort: perm.FromPort, + IpProtocol: perm.IpProtocol, + PrefixListIds: perm.PrefixListIds, + ToPort: perm.ToPort, UserIdGroupPairs: []*ec2.UserIdGroupPair{pair}, } - if perm.Ipv6Ranges != nil { - p.Ipv6Ranges = perm.Ipv6Ranges - } - - if perm.IpRanges != nil { - p.IpRanges = perm.IpRanges - } - r, err := resourceAwsSecurityGroupImportStatePermPair(sg, ruleType, p) if err != nil { return nil, err @@ -87,6 +118,22 @@ func resourceAwsSecurityGroupImportStatePerm(sg *ec2.SecurityGroup, ruleType str result = append(result, r) } } + + if len(result) == 0 && len(perm.PrefixListIds) > 0 { + p := &ec2.IpPermission{ + FromPort: perm.FromPort, + IpProtocol: perm.IpProtocol, + PrefixListIds: perm.PrefixListIds, + ToPort: perm.ToPort, + } + + r, err := resourceAwsSecurityGroupImportStatePermPair(sg, ruleType, p) + if err != nil { + return nil, err + } + result = append(result, r) + } + return result, nil } diff --git a/builtin/providers/aws/import_aws_security_group_test.go b/builtin/providers/aws/import_aws_security_group_test.go index 4b0597670..a57313ae5 100644 --- a/builtin/providers/aws/import_aws_security_group_test.go +++ b/builtin/providers/aws/import_aws_security_group_test.go @@ -101,3 +101,87 @@ func TestAccAWSSecurityGroup_importSourceSecurityGroup(t *testing.T) { }, }) } + +func TestAccAWSSecurityGroup_importIPRangeAndSecurityGroupWithSameRules(t *testing.T) { + checkFn := func(s []*terraform.InstanceState) error { + // Expect 4: group, 3 rules + if len(s) != 4 { + return fmt.Errorf("expected 4 states: %#v", s) + } + + return nil + } + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSSecurityGroupDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAWSSecurityGroupConfig_importIPRangeAndSecurityGroupWithSameRules, + }, + + { + ResourceName: "aws_security_group.test_group_1", + ImportState: true, + ImportStateCheck: checkFn, + }, + }, + }) +} + +func TestAccAWSSecurityGroup_importIPRangesWithSameRules(t *testing.T) { + checkFn := func(s []*terraform.InstanceState) error { + // Expect 4: group, 2 rules + if len(s) != 3 { + return fmt.Errorf("expected 3 states: %#v", s) + } + + return nil + } + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSSecurityGroupDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAWSSecurityGroupConfig_importIPRangesWithSameRules, + }, + + { + ResourceName: "aws_security_group.test_group_1", + ImportState: true, + ImportStateCheck: checkFn, + }, + }, + }) +} + +func TestAccAWSSecurityGroup_importPrefixList(t *testing.T) { + checkFn := func(s []*terraform.InstanceState) error { + // Expect 2: group, 1 rule + if len(s) != 2 { + return fmt.Errorf("expected 2 states: %#v", s) + } + + return nil + } + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSSecurityGroupDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAWSSecurityGroupConfigPrefixListEgress, + }, + + { + ResourceName: "aws_security_group.egress", + ImportState: true, + ImportStateCheck: checkFn, + }, + }, + }) +} diff --git a/builtin/providers/aws/import_aws_spot_datafeed_subscription_test.go b/builtin/providers/aws/import_aws_spot_datafeed_subscription_test.go index 8d60f3994..24c7acc59 100644 --- a/builtin/providers/aws/import_aws_spot_datafeed_subscription_test.go +++ b/builtin/providers/aws/import_aws_spot_datafeed_subscription_test.go @@ -7,7 +7,7 @@ import ( "github.com/hashicorp/terraform/helper/resource" ) -func TestAccAWSSpotDatafeedSubscription_importBasic(t *testing.T) { +func testAccAWSSpotDatafeedSubscription_importBasic(t *testing.T) { resourceName := "aws_spot_datafeed_subscription.default" ri := acctest.RandInt() @@ -16,11 +16,11 @@ func TestAccAWSSpotDatafeedSubscription_importBasic(t *testing.T) { Providers: testAccProviders, CheckDestroy: testAccCheckAWSSpotDatafeedSubscriptionDestroy, Steps: []resource.TestStep{ - resource.TestStep{ + { Config: testAccAWSSpotDatafeedSubscription(ri), }, - resource.TestStep{ + { ResourceName: resourceName, ImportState: true, ImportStateVerify: true, diff --git a/builtin/providers/aws/import_aws_vpn_connection_test.go b/builtin/providers/aws/import_aws_vpn_connection_test.go index a9dd41b58..a7297a220 100644 --- a/builtin/providers/aws/import_aws_vpn_connection_test.go +++ b/builtin/providers/aws/import_aws_vpn_connection_test.go @@ -3,11 +3,13 @@ package aws import ( "testing" + "github.com/hashicorp/terraform/helper/acctest" "github.com/hashicorp/terraform/helper/resource" ) func TestAccAWSVpnConnection_importBasic(t *testing.T) { resourceName := "aws_vpn_connection.foo" + rBgpAsn := acctest.RandIntRange(64512, 65534) resource.Test(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, @@ -15,7 +17,7 @@ func TestAccAWSVpnConnection_importBasic(t *testing.T) { CheckDestroy: testAccAwsVpnConnectionDestroy, Steps: []resource.TestStep{ { - Config: testAccAwsVpnConnectionConfig, + Config: testAccAwsVpnConnectionConfig(rBgpAsn), }, { ResourceName: resourceName, diff --git a/builtin/providers/aws/provider.go b/builtin/providers/aws/provider.go index 744eb21ad..f486d2718 100644 --- a/builtin/providers/aws/provider.go +++ b/builtin/providers/aws/provider.go @@ -70,7 +70,7 @@ func Provider() terraform.ResourceProvider { "max_retries": { Type: schema.TypeInt, Optional: true, - Default: 11, + Default: 25, Description: descriptions["max_retries"], }, @@ -122,6 +122,13 @@ func Provider() terraform.ResourceProvider { Description: descriptions["skip_credentials_validation"], }, + "skip_get_ec2_platforms": { + Type: schema.TypeBool, + Optional: true, + Default: false, + Description: descriptions["skip_get_ec2_platforms"], + }, + "skip_region_validation": { Type: schema.TypeBool, Optional: true, @@ -156,6 +163,7 @@ func Provider() terraform.ResourceProvider { "aws_alb": dataSourceAwsAlb(), "aws_alb_listener": dataSourceAwsAlbListener(), "aws_ami": dataSourceAwsAmi(), + "aws_ami_ids": dataSourceAwsAmiIds(), "aws_autoscaling_groups": dataSourceAwsAutoscalingGroups(), "aws_availability_zone": dataSourceAwsAvailabilityZone(), "aws_availability_zones": dataSourceAwsAvailabilityZones(), @@ -164,19 +172,25 @@ func Provider() terraform.ResourceProvider { "aws_canonical_user_id": dataSourceAwsCanonicalUserId(), "aws_cloudformation_stack": dataSourceAwsCloudFormationStack(), "aws_db_instance": dataSourceAwsDbInstance(), + "aws_db_snapshot": dataSourceAwsDbSnapshot(), "aws_ebs_snapshot": dataSourceAwsEbsSnapshot(), + "aws_ebs_snapshot_ids": dataSourceAwsEbsSnapshotIds(), "aws_ebs_volume": dataSourceAwsEbsVolume(), "aws_ecs_cluster": dataSourceAwsEcsCluster(), "aws_ecs_container_definition": dataSourceAwsEcsContainerDefinition(), "aws_ecs_task_definition": dataSourceAwsEcsTaskDefinition(), + "aws_efs_file_system": dataSourceAwsEfsFileSystem(), "aws_eip": dataSourceAwsEip(), "aws_elb_hosted_zone_id": dataSourceAwsElbHostedZoneId(), "aws_elb_service_account": dataSourceAwsElbServiceAccount(), + "aws_kinesis_stream": dataSourceAwsKinesisStream(), "aws_iam_account_alias": dataSourceAwsIamAccountAlias(), "aws_iam_policy_document": dataSourceAwsIamPolicyDocument(), + "aws_iam_role": dataSourceAwsIAMRole(), "aws_iam_server_certificate": dataSourceAwsIAMServerCertificate(), "aws_instance": dataSourceAwsInstance(), "aws_ip_ranges": dataSourceAwsIPRanges(), + "aws_kms_alias": dataSourceAwsKmsAlias(), "aws_kms_secret": dataSourceAwsKmsSecret(), "aws_partition": dataSourceAwsPartition(), "aws_prefix_list": dataSourceAwsPrefixList(), @@ -187,6 +201,7 @@ func Provider() terraform.ResourceProvider { "aws_s3_bucket_object": dataSourceAwsS3BucketObject(), "aws_sns_topic": dataSourceAwsSnsTopic(), "aws_subnet": dataSourceAwsSubnet(), + "aws_subnet_ids": dataSourceAwsSubnetIDs(), "aws_security_group": dataSourceAwsSecurityGroup(), "aws_vpc": dataSourceAwsVpc(), "aws_vpc_endpoint": dataSourceAwsVpcEndpoint(), @@ -216,9 +231,11 @@ func Provider() terraform.ResourceProvider { "aws_api_gateway_integration_response": resourceAwsApiGatewayIntegrationResponse(), "aws_api_gateway_method": resourceAwsApiGatewayMethod(), "aws_api_gateway_method_response": resourceAwsApiGatewayMethodResponse(), + "aws_api_gateway_method_settings": resourceAwsApiGatewayMethodSettings(), "aws_api_gateway_model": resourceAwsApiGatewayModel(), "aws_api_gateway_resource": resourceAwsApiGatewayResource(), "aws_api_gateway_rest_api": resourceAwsApiGatewayRestApi(), + "aws_api_gateway_stage": resourceAwsApiGatewayStage(), "aws_api_gateway_usage_plan": resourceAwsApiGatewayUsagePlan(), "aws_api_gateway_usage_plan_key": resourceAwsApiGatewayUsagePlanKey(), "aws_app_cookie_stickiness_policy": resourceAwsAppCookieStickinessPolicy(), @@ -245,6 +262,7 @@ func Provider() terraform.ResourceProvider { "aws_config_configuration_recorder": resourceAwsConfigConfigurationRecorder(), "aws_config_configuration_recorder_status": resourceAwsConfigConfigurationRecorderStatus(), "aws_config_delivery_channel": resourceAwsConfigDeliveryChannel(), + "aws_cognito_identity_pool": resourceAwsCognitoIdentityPool(), "aws_autoscaling_lifecycle_hook": resourceAwsAutoscalingLifecycleHook(), "aws_cloudwatch_metric_alarm": resourceAwsCloudWatchMetricAlarm(), "aws_codedeploy_app": resourceAwsCodeDeployApp(), @@ -260,7 +278,9 @@ func Provider() terraform.ResourceProvider { "aws_db_option_group": resourceAwsDbOptionGroup(), "aws_db_parameter_group": resourceAwsDbParameterGroup(), "aws_db_security_group": resourceAwsDbSecurityGroup(), + "aws_db_snapshot": resourceAwsDbSnapshot(), "aws_db_subnet_group": resourceAwsDbSubnetGroup(), + "aws_devicefarm_project": resourceAwsDevicefarmProject(), "aws_directory_service_directory": resourceAwsDirectoryServiceDirectory(), "aws_dms_certificate": resourceAwsDmsCertificate(), "aws_dms_endpoint": resourceAwsDmsEndpoint(), @@ -297,6 +317,7 @@ func Provider() terraform.ResourceProvider { "aws_elb_attachment": resourceAwsElbAttachment(), "aws_emr_cluster": resourceAwsEMRCluster(), "aws_emr_instance_group": resourceAwsEMRInstanceGroup(), + "aws_emr_security_configuration": resourceAwsEMRSecurityConfiguration(), "aws_flow_log": resourceAwsFlowLog(), "aws_glacier_vault": resourceAwsGlacierVault(), "aws_iam_access_key": resourceAwsIamAccessKey(), @@ -307,6 +328,7 @@ func Provider() terraform.ResourceProvider { "aws_iam_group_membership": resourceAwsIamGroupMembership(), "aws_iam_group_policy_attachment": resourceAwsIamGroupPolicyAttachment(), "aws_iam_instance_profile": resourceAwsIamInstanceProfile(), + "aws_iam_openid_connect_provider": resourceAwsIamOpenIDConnectProvider(), "aws_iam_policy": resourceAwsIamPolicy(), "aws_iam_policy_attachment": resourceAwsIamPolicyAttachment(), "aws_iam_role_policy_attachment": resourceAwsIamRolePolicyAttachment(), @@ -337,6 +359,8 @@ func Provider() terraform.ResourceProvider { "aws_lightsail_domain": resourceAwsLightsailDomain(), "aws_lightsail_instance": resourceAwsLightsailInstance(), "aws_lightsail_key_pair": resourceAwsLightsailKeyPair(), + "aws_lightsail_static_ip": resourceAwsLightsailStaticIp(), + "aws_lightsail_static_ip_attachment": resourceAwsLightsailStaticIpAttachment(), "aws_lb_cookie_stickiness_policy": resourceAwsLBCookieStickinessPolicy(), "aws_load_balancer_policy": resourceAwsLoadBalancerPolicy(), "aws_load_balancer_backend_server_policy": resourceAwsLoadBalancerBackendServerPolicies(), @@ -349,6 +373,7 @@ func Provider() terraform.ResourceProvider { "aws_default_route_table": resourceAwsDefaultRouteTable(), "aws_network_acl_rule": resourceAwsNetworkAclRule(), "aws_network_interface": resourceAwsNetworkInterface(), + "aws_network_interface_attachment": resourceAwsNetworkInterfaceAttachment(), "aws_opsworks_application": resourceAwsOpsworksApplication(), "aws_opsworks_stack": resourceAwsOpsworksStack(), "aws_opsworks_java_app_layer": resourceAwsOpsworksJavaAppLayer(), @@ -383,6 +408,7 @@ func Provider() terraform.ResourceProvider { "aws_route_table": resourceAwsRouteTable(), "aws_route_table_association": resourceAwsRouteTableAssociation(), "aws_ses_active_receipt_rule_set": resourceAwsSesActiveReceiptRuleSet(), + "aws_ses_domain_identity": resourceAwsSesDomainIdentity(), "aws_ses_receipt_filter": resourceAwsSesReceiptFilter(), "aws_ses_receipt_rule": resourceAwsSesReceiptRule(), "aws_ses_receipt_rule_set": resourceAwsSesReceiptRuleSet(), @@ -399,6 +425,9 @@ func Provider() terraform.ResourceProvider { "aws_ssm_activation": resourceAwsSsmActivation(), "aws_ssm_association": resourceAwsSsmAssociation(), "aws_ssm_document": resourceAwsSsmDocument(), + "aws_ssm_maintenance_window": resourceAwsSsmMaintenanceWindow(), + "aws_ssm_maintenance_window_target": resourceAwsSsmMaintenanceWindowTarget(), + "aws_ssm_maintenance_window_task": resourceAwsSsmMaintenanceWindowTask(), "aws_spot_datafeed_subscription": resourceAwsSpotDataFeedSubscription(), "aws_spot_instance_request": resourceAwsSpotInstanceRequest(), "aws_spot_fleet_request": resourceAwsSpotFleetRequest(), @@ -410,9 +439,11 @@ func Provider() terraform.ResourceProvider { "aws_sns_topic_subscription": resourceAwsSnsTopicSubscription(), "aws_sfn_activity": resourceAwsSfnActivity(), "aws_sfn_state_machine": resourceAwsSfnStateMachine(), + "aws_default_subnet": resourceAwsDefaultSubnet(), "aws_subnet": resourceAwsSubnet(), "aws_volume_attachment": resourceAwsVolumeAttachment(), "aws_vpc_dhcp_options_association": resourceAwsVpcDhcpOptionsAssociation(), + "aws_default_vpc_dhcp_options": resourceAwsDefaultVpcDhcpOptions(), "aws_vpc_dhcp_options": resourceAwsVpcDhcpOptions(), "aws_vpc_peering_connection": resourceAwsVpcPeeringConnection(), "aws_vpc_peering_connection_accepter": resourceAwsVpcPeeringConnectionAccepter(), @@ -430,6 +461,8 @@ func Provider() terraform.ResourceProvider { "aws_waf_web_acl": resourceAwsWafWebAcl(), "aws_waf_xss_match_set": resourceAwsWafXssMatchSet(), "aws_waf_sql_injection_match_set": resourceAwsWafSqlInjectionMatchSet(), + "aws_wafregional_byte_match_set": resourceAwsWafRegionalByteMatchSet(), + "aws_wafregional_ipset": resourceAwsWafRegionalIPSet(), }, ConfigureFunc: providerConfigure, } @@ -461,26 +494,47 @@ func init() { "being executed. If the API request still fails, an error is\n" + "thrown.", + "cloudformation_endpoint": "Use this to override the default endpoint URL constructed from the `region`.\n", + + "cloudwatch_endpoint": "Use this to override the default endpoint URL constructed from the `region`.\n", + + "cloudwatchevents_endpoint": "Use this to override the default endpoint URL constructed from the `region`.\n", + + "cloudwatchlogs_endpoint": "Use this to override the default endpoint URL constructed from the `region`.\n", + + "devicefarm_endpoint": "Use this to override the default endpoint URL constructed from the `region`.\n", + "dynamodb_endpoint": "Use this to override the default endpoint URL constructed from the `region`.\n" + "It's typically used to connect to dynamodb-local.", "kinesis_endpoint": "Use this to override the default endpoint URL constructed from the `region`.\n" + "It's typically used to connect to kinesalite.", + "kms_endpoint": "Use this to override the default endpoint URL constructed from the `region`.\n", + "iam_endpoint": "Use this to override the default endpoint URL constructed from the `region`.\n", "ec2_endpoint": "Use this to override the default endpoint URL constructed from the `region`.\n", "elb_endpoint": "Use this to override the default endpoint URL constructed from the `region`.\n", + "rds_endpoint": "Use this to override the default endpoint URL constructed from the `region`.\n", + "s3_endpoint": "Use this to override the default endpoint URL constructed from the `region`.\n", + "sns_endpoint": "Use this to override the default endpoint URL constructed from the `region`.\n", + + "sqs_endpoint": "Use this to override the default endpoint URL constructed from the `region`.\n", + "insecure": "Explicitly allow the provider to perform \"insecure\" SSL requests. If omitted," + "default value is `false`", "skip_credentials_validation": "Skip the credentials validation via STS API. " + "Used for AWS API implementations that do not have STS available/implemented.", + "skip_get_ec2_platforms": "Skip getting the supported EC2 platforms. " + + "Used by users that don't have ec2:DescribeAccountAttributes permissions.", + "skip_region_validation": "Skip static validation of region name. " + "Used by users of alternative AWS-like APIs or users w/ access to regions that are not public (yet).", @@ -520,6 +574,7 @@ func providerConfigure(d *schema.ResourceData) (interface{}, error) { MaxRetries: d.Get("max_retries").(int), Insecure: d.Get("insecure").(bool), SkipCredsValidation: d.Get("skip_credentials_validation").(bool), + SkipGetEC2Platforms: d.Get("skip_get_ec2_platforms").(bool), SkipRegionValidation: d.Get("skip_region_validation").(bool), SkipRequestingAccountId: d.Get("skip_requesting_account_id").(bool), SkipMetadataApiCheck: d.Get("skip_metadata_api_check").(bool), @@ -547,12 +602,21 @@ func providerConfigure(d *schema.ResourceData) (interface{}, error) { for _, endpointsSetI := range endpointsSet.List() { endpoints := endpointsSetI.(map[string]interface{}) + config.CloudFormationEndpoint = endpoints["cloudformation"].(string) + config.CloudWatchEndpoint = endpoints["cloudwatch"].(string) + config.CloudWatchEventsEndpoint = endpoints["cloudwatchevents"].(string) + config.CloudWatchLogsEndpoint = endpoints["cloudwatchlogs"].(string) + config.DeviceFarmEndpoint = endpoints["devicefarm"].(string) config.DynamoDBEndpoint = endpoints["dynamodb"].(string) - config.IamEndpoint = endpoints["iam"].(string) config.Ec2Endpoint = endpoints["ec2"].(string) config.ElbEndpoint = endpoints["elb"].(string) + config.IamEndpoint = endpoints["iam"].(string) config.KinesisEndpoint = endpoints["kinesis"].(string) + config.KmsEndpoint = endpoints["kms"].(string) + config.RdsEndpoint = endpoints["rds"].(string) config.S3Endpoint = endpoints["s3"].(string) + config.SnsEndpoint = endpoints["sns"].(string) + config.SqsEndpoint = endpoints["sqs"].(string) } if v, ok := d.GetOk("allowed_account_ids"); ok { @@ -621,6 +685,36 @@ func endpointsSchema() *schema.Schema { Optional: true, Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ + "cloudwatch": { + Type: schema.TypeString, + Optional: true, + Default: "", + Description: descriptions["cloudwatch_endpoint"], + }, + "cloudwatchevents": { + Type: schema.TypeString, + Optional: true, + Default: "", + Description: descriptions["cloudwatchevents_endpoint"], + }, + "cloudwatchlogs": { + Type: schema.TypeString, + Optional: true, + Default: "", + Description: descriptions["cloudwatchlogs_endpoint"], + }, + "cloudformation": { + Type: schema.TypeString, + Optional: true, + Default: "", + Description: descriptions["cloudformation_endpoint"], + }, + "devicefarm": { + Type: schema.TypeString, + Optional: true, + Default: "", + Description: descriptions["devicefarm_endpoint"], + }, "dynamodb": { Type: schema.TypeString, Optional: true, @@ -653,12 +747,36 @@ func endpointsSchema() *schema.Schema { Default: "", Description: descriptions["kinesis_endpoint"], }, + "kms": { + Type: schema.TypeString, + Optional: true, + Default: "", + Description: descriptions["kms_endpoint"], + }, + "rds": { + Type: schema.TypeString, + Optional: true, + Default: "", + Description: descriptions["rds_endpoint"], + }, "s3": { Type: schema.TypeString, Optional: true, Default: "", Description: descriptions["s3_endpoint"], }, + "sns": { + Type: schema.TypeString, + Optional: true, + Default: "", + Description: descriptions["sns_endpoint"], + }, + "sqs": { + Type: schema.TypeString, + Optional: true, + Default: "", + Description: descriptions["sqs_endpoint"], + }, }, }, Set: endpointsToHash, @@ -668,12 +786,21 @@ func endpointsSchema() *schema.Schema { func endpointsToHash(v interface{}) int { var buf bytes.Buffer m := v.(map[string]interface{}) + buf.WriteString(fmt.Sprintf("%s-", m["cloudwatch"].(string))) + buf.WriteString(fmt.Sprintf("%s-", m["cloudwatchevents"].(string))) + buf.WriteString(fmt.Sprintf("%s-", m["cloudwatchlogs"].(string))) + buf.WriteString(fmt.Sprintf("%s-", m["cloudformation"].(string))) + buf.WriteString(fmt.Sprintf("%s-", m["devicefarm"].(string))) buf.WriteString(fmt.Sprintf("%s-", m["dynamodb"].(string))) buf.WriteString(fmt.Sprintf("%s-", m["iam"].(string))) buf.WriteString(fmt.Sprintf("%s-", m["ec2"].(string))) buf.WriteString(fmt.Sprintf("%s-", m["elb"].(string))) buf.WriteString(fmt.Sprintf("%s-", m["kinesis"].(string))) + buf.WriteString(fmt.Sprintf("%s-", m["kms"].(string))) + buf.WriteString(fmt.Sprintf("%s-", m["rds"].(string))) buf.WriteString(fmt.Sprintf("%s-", m["s3"].(string))) + buf.WriteString(fmt.Sprintf("%s-", m["sns"].(string))) + buf.WriteString(fmt.Sprintf("%s-", m["sqs"].(string))) return hashcode.String(buf.String()) } diff --git a/builtin/providers/aws/resource_aws_alb.go b/builtin/providers/aws/resource_aws_alb.go index 1a577e4b0..d1652c680 100644 --- a/builtin/providers/aws/resource_aws_alb.go +++ b/builtin/providers/aws/resource_aws_alb.go @@ -24,6 +24,12 @@ func resourceAwsAlb() *schema.Resource { State: schema.ImportStatePassthrough, }, + Timeouts: &schema.ResourceTimeout{ + Create: schema.DefaultTimeout(10 * time.Minute), + Update: schema.DefaultTimeout(10 * time.Minute), + Delete: schema.DefaultTimeout(10 * time.Minute), + }, + Schema: map[string]*schema.Schema{ "arn": { Type: schema.TypeString, @@ -48,7 +54,7 @@ func resourceAwsAlb() *schema.Resource { Type: schema.TypeString, Optional: true, ForceNew: true, - ValidateFunc: validateElbName, + ValidateFunc: validateElbNamePrefix, }, "internal": { @@ -108,6 +114,12 @@ func resourceAwsAlb() *schema.Resource { Default: 60, }, + "ip_address_type": { + Type: schema.TypeString, + Computed: true, + Optional: true, + }, + "vpc_id": { Type: schema.TypeString, Computed: true, @@ -158,6 +170,10 @@ func resourceAwsAlbCreate(d *schema.ResourceData, meta interface{}) error { elbOpts.Subnets = expandStringList(v.(*schema.Set).List()) } + if v, ok := d.GetOk("ip_address_type"); ok { + elbOpts.IpAddressType = aws.String(v.(string)) + } + log.Printf("[DEBUG] ALB create configuration: %#v", elbOpts) resp, err := elbconn.CreateLoadBalancer(elbOpts) @@ -174,7 +190,7 @@ func resourceAwsAlbCreate(d *schema.ResourceData, meta interface{}) error { log.Printf("[INFO] ALB ID: %s", d.Id()) stateConf := &resource.StateChangeConf{ - Pending: []string{"active", "provisioning", "failed"}, + Pending: []string{"provisioning", "failed"}, Target: []string{"active"}, Refresh: func() (interface{}, string, error) { describeResp, err := elbconn.DescribeLoadBalancers(&elbv2.DescribeLoadBalancersInput{ @@ -193,8 +209,9 @@ func resourceAwsAlbCreate(d *schema.ResourceData, meta interface{}) error { return describeResp, *dLb.State.Code, nil }, - Timeout: 5 * time.Minute, - MinTimeout: 3 * time.Second, + Timeout: d.Timeout(schema.TimeoutCreate), + MinTimeout: 10 * time.Second, + Delay: 30 * time.Second, // Wait 30 secs before starting } _, err = stateConf.WaitForState() if err != nil { @@ -325,6 +342,49 @@ func resourceAwsAlbUpdate(d *schema.ResourceData, meta interface{}) error { } } + if d.HasChange("ip_address_type") { + + params := &elbv2.SetIpAddressTypeInput{ + LoadBalancerArn: aws.String(d.Id()), + IpAddressType: aws.String(d.Get("ip_address_type").(string)), + } + + _, err := elbconn.SetIpAddressType(params) + if err != nil { + return fmt.Errorf("Failure Setting ALB IP Address Type: %s", err) + } + + } + + stateConf := &resource.StateChangeConf{ + Pending: []string{"active", "provisioning", "failed"}, + Target: []string{"active"}, + Refresh: func() (interface{}, string, error) { + describeResp, err := elbconn.DescribeLoadBalancers(&elbv2.DescribeLoadBalancersInput{ + LoadBalancerArns: []*string{aws.String(d.Id())}, + }) + if err != nil { + return nil, "", err + } + + if len(describeResp.LoadBalancers) != 1 { + return nil, "", fmt.Errorf("No load balancers returned for %s", d.Id()) + } + dLb := describeResp.LoadBalancers[0] + + log.Printf("[INFO] ALB state: %s", *dLb.State.Code) + + return describeResp, *dLb.State.Code, nil + }, + Timeout: d.Timeout(schema.TimeoutUpdate), + MinTimeout: 10 * time.Second, + Delay: 30 * time.Second, // Wait 30 secs before starting + } + _, err := stateConf.WaitForState() + if err != nil { + return err + } + return resourceAwsAlbRead(d, meta) } @@ -381,6 +441,7 @@ func flattenAwsAlbResource(d *schema.ResourceData, meta interface{}, alb *elbv2. d.Set("vpc_id", alb.VpcId) d.Set("zone_id", alb.CanonicalHostedZoneId) d.Set("dns_name", alb.DNSName) + d.Set("ip_address_type", alb.IpAddressType) respTags, err := elbconn.DescribeTags(&elbv2.DescribeTagsInput{ ResourceArns: []*string{alb.LoadBalancerArn}, diff --git a/builtin/providers/aws/resource_aws_alb_listener_rule.go b/builtin/providers/aws/resource_aws_alb_listener_rule.go index d82d7410a..21292753c 100644 --- a/builtin/providers/aws/resource_aws_alb_listener_rule.go +++ b/builtin/providers/aws/resource_aws_alb_listener_rule.go @@ -31,10 +31,12 @@ func resourceAwsAlbListenerRule() *schema.Resource { "listener_arn": { Type: schema.TypeString, Required: true, + ForceNew: true, }, "priority": { Type: schema.TypeInt, Required: true, + ForceNew: true, ValidateFunc: validateAwsAlbListenerRulePriority, }, "action": { @@ -184,42 +186,75 @@ func resourceAwsAlbListenerRuleRead(d *schema.ResourceData, meta interface{}) er func resourceAwsAlbListenerRuleUpdate(d *schema.ResourceData, meta interface{}) error { elbconn := meta.(*AWSClient).elbv2conn + d.Partial(true) + + if d.HasChange("priority") { + params := &elbv2.SetRulePrioritiesInput{ + RulePriorities: []*elbv2.RulePriorityPair{ + { + RuleArn: aws.String(d.Id()), + Priority: aws.Int64(int64(d.Get("priority").(int))), + }, + }, + } + + _, err := elbconn.SetRulePriorities(params) + if err != nil { + return err + } + + d.SetPartial("priority") + } + + requestUpdate := false params := &elbv2.ModifyRuleInput{ RuleArn: aws.String(d.Id()), } - actions := d.Get("action").([]interface{}) - params.Actions = make([]*elbv2.Action, len(actions)) - for i, action := range actions { - actionMap := action.(map[string]interface{}) - params.Actions[i] = &elbv2.Action{ - TargetGroupArn: aws.String(actionMap["target_group_arn"].(string)), - Type: aws.String(actionMap["type"].(string)), + if d.HasChange("action") { + actions := d.Get("action").([]interface{}) + params.Actions = make([]*elbv2.Action, len(actions)) + for i, action := range actions { + actionMap := action.(map[string]interface{}) + params.Actions[i] = &elbv2.Action{ + TargetGroupArn: aws.String(actionMap["target_group_arn"].(string)), + Type: aws.String(actionMap["type"].(string)), + } + } + requestUpdate = true + d.SetPartial("action") + } + + if d.HasChange("condition") { + conditions := d.Get("condition").([]interface{}) + params.Conditions = make([]*elbv2.RuleCondition, len(conditions)) + for i, condition := range conditions { + conditionMap := condition.(map[string]interface{}) + values := conditionMap["values"].([]interface{}) + params.Conditions[i] = &elbv2.RuleCondition{ + Field: aws.String(conditionMap["field"].(string)), + Values: make([]*string, len(values)), + } + for j, value := range values { + params.Conditions[i].Values[j] = aws.String(value.(string)) + } + } + requestUpdate = true + d.SetPartial("condition") + } + + if requestUpdate { + resp, err := elbconn.ModifyRule(params) + if err != nil { + return errwrap.Wrapf("Error modifying ALB Listener Rule: {{err}}", err) + } + + if len(resp.Rules) == 0 { + return errors.New("Error modifying creating ALB Listener Rule: no rules returned in response") } } - conditions := d.Get("condition").([]interface{}) - params.Conditions = make([]*elbv2.RuleCondition, len(conditions)) - for i, condition := range conditions { - conditionMap := condition.(map[string]interface{}) - values := conditionMap["values"].([]interface{}) - params.Conditions[i] = &elbv2.RuleCondition{ - Field: aws.String(conditionMap["field"].(string)), - Values: make([]*string, len(values)), - } - for j, value := range values { - params.Conditions[i].Values[j] = aws.String(value.(string)) - } - } - - resp, err := elbconn.ModifyRule(params) - if err != nil { - return errwrap.Wrapf("Error modifying ALB Listener Rule: {{err}}", err) - } - - if len(resp.Rules) == 0 { - return errors.New("Error modifying creating ALB Listener Rule: no rules returned in response") - } + d.Partial(false) return resourceAwsAlbListenerRuleRead(d, meta) } diff --git a/builtin/providers/aws/resource_aws_alb_listener_rule_test.go b/builtin/providers/aws/resource_aws_alb_listener_rule_test.go index 0407ca614..8ddc0ef9e 100644 --- a/builtin/providers/aws/resource_aws_alb_listener_rule_test.go +++ b/builtin/providers/aws/resource_aws_alb_listener_rule_test.go @@ -44,6 +44,63 @@ func TestAccAWSALBListenerRule_basic(t *testing.T) { }) } +func TestAccAWSALBListenerRule_updateRulePriority(t *testing.T) { + var rule elbv2.Rule + albName := fmt.Sprintf("testrule-basic-%s", acctest.RandStringFromCharSet(13, acctest.CharSetAlphaNum)) + targetGroupName := fmt.Sprintf("testtargetgroup-%s", acctest.RandStringFromCharSet(10, acctest.CharSetAlphaNum)) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + IDRefreshName: "aws_alb_listener_rule.static", + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSALBListenerRuleDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAWSALBListenerRuleConfig_basic(albName, targetGroupName), + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSALBListenerRuleExists("aws_alb_listener_rule.static", &rule), + resource.TestCheckResourceAttr("aws_alb_listener_rule.static", "priority", "100"), + ), + }, + { + Config: testAccAWSALBListenerRuleConfig_updateRulePriority(albName, targetGroupName), + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSALBListenerRuleExists("aws_alb_listener_rule.static", &rule), + resource.TestCheckResourceAttr("aws_alb_listener_rule.static", "priority", "101"), + ), + }, + }, + }) +} + +func TestAccAWSALBListenerRule_changeListenerRuleArnForcesNew(t *testing.T) { + var before, after elbv2.Rule + albName := fmt.Sprintf("testrule-basic-%s", acctest.RandStringFromCharSet(13, acctest.CharSetAlphaNum)) + targetGroupName := fmt.Sprintf("testtargetgroup-%s", acctest.RandStringFromCharSet(10, acctest.CharSetAlphaNum)) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + IDRefreshName: "aws_alb_listener_rule.static", + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSALBListenerRuleDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAWSALBListenerRuleConfig_basic(albName, targetGroupName), + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSALBListenerRuleExists("aws_alb_listener_rule.static", &before), + ), + }, + { + Config: testAccAWSALBListenerRuleConfig_changeRuleArn(albName, targetGroupName), + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSALBListenerRuleExists("aws_alb_listener_rule.static", &after), + testAccCheckAWSAlbListenerRuleRecreated(t, &before, &after), + ), + }, + }, + }) +} + func TestAccAWSALBListenerRule_multipleConditionThrowsError(t *testing.T) { albName := fmt.Sprintf("testrule-basic-%s", acctest.RandStringFromCharSet(13, acctest.CharSetAlphaNum)) targetGroupName := fmt.Sprintf("testtargetgroup-%s", acctest.RandStringFromCharSet(10, acctest.CharSetAlphaNum)) @@ -61,6 +118,16 @@ func TestAccAWSALBListenerRule_multipleConditionThrowsError(t *testing.T) { }) } +func testAccCheckAWSAlbListenerRuleRecreated(t *testing.T, + before, after *elbv2.Rule) resource.TestCheckFunc { + return func(s *terraform.State) error { + if *before.RuleArn == *after.RuleArn { + t.Fatalf("Expected change of Listener Rule ARNs, but both were %v", before.RuleArn) + } + return nil + } +} + func testAccCheckAWSALBListenerRuleExists(n string, res *elbv2.Rule) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[n] @@ -343,3 +410,238 @@ resource "aws_security_group" "alb_test" { } }`, albName, targetGroupName) } + +func testAccAWSALBListenerRuleConfig_updateRulePriority(albName, targetGroupName string) string { + return fmt.Sprintf(` +resource "aws_alb_listener_rule" "static" { + listener_arn = "${aws_alb_listener.front_end.arn}" + priority = 101 + + action { + type = "forward" + target_group_arn = "${aws_alb_target_group.test.arn}" + } + + condition { + field = "path-pattern" + values = ["/static/*"] + } +} + +resource "aws_alb_listener" "front_end" { + load_balancer_arn = "${aws_alb.alb_test.id}" + protocol = "HTTP" + port = "80" + + default_action { + target_group_arn = "${aws_alb_target_group.test.id}" + type = "forward" + } +} + +resource "aws_alb" "alb_test" { + name = "%s" + internal = true + security_groups = ["${aws_security_group.alb_test.id}"] + subnets = ["${aws_subnet.alb_test.*.id}"] + + idle_timeout = 30 + enable_deletion_protection = false + + tags { + TestName = "TestAccAWSALB_basic" + } +} + +resource "aws_alb_target_group" "test" { + name = "%s" + port = 8080 + protocol = "HTTP" + vpc_id = "${aws_vpc.alb_test.id}" + + health_check { + path = "/health" + interval = 60 + port = 8081 + protocol = "HTTP" + timeout = 3 + healthy_threshold = 3 + unhealthy_threshold = 3 + matcher = "200-299" + } +} + +variable "subnets" { + default = ["10.0.1.0/24", "10.0.2.0/24"] + type = "list" +} + +data "aws_availability_zones" "available" {} + +resource "aws_vpc" "alb_test" { + cidr_block = "10.0.0.0/16" + + tags { + TestName = "TestAccAWSALB_basic" + } +} + +resource "aws_subnet" "alb_test" { + count = 2 + vpc_id = "${aws_vpc.alb_test.id}" + cidr_block = "${element(var.subnets, count.index)}" + map_public_ip_on_launch = true + availability_zone = "${element(data.aws_availability_zones.available.names, count.index)}" + + tags { + TestName = "TestAccAWSALB_basic" + } +} + +resource "aws_security_group" "alb_test" { + name = "allow_all_alb_test" + description = "Used for ALB Testing" + vpc_id = "${aws_vpc.alb_test.id}" + + ingress { + from_port = 0 + to_port = 0 + protocol = "-1" + cidr_blocks = ["0.0.0.0/0"] + } + + egress { + from_port = 0 + to_port = 0 + protocol = "-1" + cidr_blocks = ["0.0.0.0/0"] + } + + tags { + TestName = "TestAccAWSALB_basic" + } +}`, albName, targetGroupName) +} + +func testAccAWSALBListenerRuleConfig_changeRuleArn(albName, targetGroupName string) string { + return fmt.Sprintf(` +resource "aws_alb_listener_rule" "static" { + listener_arn = "${aws_alb_listener.front_end_ruleupdate.arn}" + priority = 101 + + action { + type = "forward" + target_group_arn = "${aws_alb_target_group.test.arn}" + } + + condition { + field = "path-pattern" + values = ["/static/*"] + } +} + +resource "aws_alb_listener" "front_end" { + load_balancer_arn = "${aws_alb.alb_test.id}" + protocol = "HTTP" + port = "80" + + default_action { + target_group_arn = "${aws_alb_target_group.test.id}" + type = "forward" + } +} + +resource "aws_alb_listener" "front_end_ruleupdate" { + load_balancer_arn = "${aws_alb.alb_test.id}" + protocol = "HTTP" + port = "8080" + + default_action { + target_group_arn = "${aws_alb_target_group.test.id}" + type = "forward" + } +} + +resource "aws_alb" "alb_test" { + name = "%s" + internal = true + security_groups = ["${aws_security_group.alb_test.id}"] + subnets = ["${aws_subnet.alb_test.*.id}"] + + idle_timeout = 30 + enable_deletion_protection = false + + tags { + TestName = "TestAccAWSALB_basic" + } +} + +resource "aws_alb_target_group" "test" { + name = "%s" + port = 8080 + protocol = "HTTP" + vpc_id = "${aws_vpc.alb_test.id}" + + health_check { + path = "/health" + interval = 60 + port = 8081 + protocol = "HTTP" + timeout = 3 + healthy_threshold = 3 + unhealthy_threshold = 3 + matcher = "200-299" + } +} + +variable "subnets" { + default = ["10.0.1.0/24", "10.0.2.0/24"] + type = "list" +} + +data "aws_availability_zones" "available" {} + +resource "aws_vpc" "alb_test" { + cidr_block = "10.0.0.0/16" + + tags { + TestName = "TestAccAWSALB_basic" + } +} + +resource "aws_subnet" "alb_test" { + count = 2 + vpc_id = "${aws_vpc.alb_test.id}" + cidr_block = "${element(var.subnets, count.index)}" + map_public_ip_on_launch = true + availability_zone = "${element(data.aws_availability_zones.available.names, count.index)}" + + tags { + TestName = "TestAccAWSALB_basic" + } +} + +resource "aws_security_group" "alb_test" { + name = "allow_all_alb_test" + description = "Used for ALB Testing" + vpc_id = "${aws_vpc.alb_test.id}" + + ingress { + from_port = 0 + to_port = 0 + protocol = "-1" + cidr_blocks = ["0.0.0.0/0"] + } + + egress { + from_port = 0 + to_port = 0 + protocol = "-1" + cidr_blocks = ["0.0.0.0/0"] + } + + tags { + TestName = "TestAccAWSALB_basic" + } +}`, albName, targetGroupName) +} diff --git a/builtin/providers/aws/resource_aws_alb_target_group.go b/builtin/providers/aws/resource_aws_alb_target_group.go index 96ecd0d42..cd4256839 100644 --- a/builtin/providers/aws/resource_aws_alb_target_group.go +++ b/builtin/providers/aws/resource_aws_alb_target_group.go @@ -12,6 +12,7 @@ import ( "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/service/elbv2" "github.com/hashicorp/errwrap" + "github.com/hashicorp/terraform/helper/resource" "github.com/hashicorp/terraform/helper/schema" ) @@ -37,10 +38,18 @@ func resourceAwsAlbTargetGroup() *schema.Resource { }, "name": { + Type: schema.TypeString, + Optional: true, + Computed: true, + ForceNew: true, + ConflictsWith: []string{"name_prefix"}, + ValidateFunc: validateAwsAlbTargetGroupName, + }, + "name_prefix": { Type: schema.TypeString, - Required: true, + Optional: true, ForceNew: true, - ValidateFunc: validateAwsAlbTargetGroupName, + ValidateFunc: validateAwsAlbTargetGroupNamePrefix, }, "port": { @@ -73,6 +82,7 @@ func resourceAwsAlbTargetGroup() *schema.Resource { "stickiness": { Type: schema.TypeList, Optional: true, + Computed: true, MaxItems: 1, Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ @@ -171,8 +181,17 @@ func resourceAwsAlbTargetGroup() *schema.Resource { func resourceAwsAlbTargetGroupCreate(d *schema.ResourceData, meta interface{}) error { elbconn := meta.(*AWSClient).elbv2conn + var groupName string + if v, ok := d.GetOk("name"); ok { + groupName = v.(string) + } else if v, ok := d.GetOk("name_prefix"); ok { + groupName = resource.PrefixedUniqueId(v.(string)) + } else { + groupName = resource.PrefixedUniqueId("tf-") + } + params := &elbv2.CreateTargetGroupInput{ - Name: aws.String(d.Get("name").(string)), + Name: aws.String(groupName), Port: aws.Int64(int64(d.Get("port").(int))), Protocol: aws.String(d.Get("protocol").(string)), VpcId: aws.String(d.Get("vpc_id").(string)), @@ -258,11 +277,19 @@ func resourceAwsAlbTargetGroupRead(d *schema.ResourceData, meta interface{}) err for _, attr := range attrResp.Attributes { switch *attr.Key { case "stickiness.enabled": - stickinessMap["enabled"] = *attr.Value + enabled, err := strconv.ParseBool(*attr.Value) + if err != nil { + return fmt.Errorf("Error converting stickiness.enabled to bool: %s", *attr.Value) + } + stickinessMap["enabled"] = enabled case "stickiness.type": stickinessMap["type"] = *attr.Value case "stickiness.lb_cookie.duration_seconds": - stickinessMap["cookie_duration"] = *attr.Value + duration, err := strconv.Atoi(*attr.Value) + if err != nil { + return fmt.Errorf("Error converting stickiness.lb_cookie.duration_seconds to int: %s", *attr.Value) + } + stickinessMap["cookie_duration"] = duration case "deregistration_delay.timeout_seconds": timeout, err := strconv.Atoi(*attr.Value) if err != nil { @@ -271,7 +298,24 @@ func resourceAwsAlbTargetGroupRead(d *schema.ResourceData, meta interface{}) err d.Set("deregistration_delay", timeout) } } - d.Set("stickiness", []interface{}{stickinessMap}) + + if err := d.Set("stickiness", []interface{}{stickinessMap}); err != nil { + return err + } + + tagsResp, err := elbconn.DescribeTags(&elbv2.DescribeTagsInput{ + ResourceArns: []*string{aws.String(d.Id())}, + }) + if err != nil { + return errwrap.Wrapf("Error retrieving Target Group Tags: {{err}}", err) + } + for _, t := range tagsResp.TagDescriptions { + if *t.ResourceArn == d.Id() { + if err := d.Set("tags", tagsToMapELBv2(t.Tags)); err != nil { + return err + } + } + } return nil } @@ -437,14 +481,6 @@ func validateAwsAlbTargetGroupHealthCheckProtocol(v interface{}, k string) (ws [ return } -func validateAwsAlbTargetGroupName(v interface{}, k string) (ws []string, errors []error) { - name := v.(string) - if len(name) > 32 { - errors = append(errors, fmt.Errorf("%q (%q) cannot be longer than '32' characters", k, name)) - } - return -} - func validateAwsAlbTargetGroupPort(v interface{}, k string) (ws []string, errors []error) { port := v.(int) if port < 1 || port > 65536 { diff --git a/builtin/providers/aws/resource_aws_alb_target_group_attachment.go b/builtin/providers/aws/resource_aws_alb_target_group_attachment.go index e6ba35b94..55a3b7392 100644 --- a/builtin/providers/aws/resource_aws_alb_target_group_attachment.go +++ b/builtin/providers/aws/resource_aws_alb_target_group_attachment.go @@ -34,7 +34,7 @@ func resourceAwsAlbTargetGroupAttachment() *schema.Resource { "port": { Type: schema.TypeInt, ForceNew: true, - Required: true, + Optional: true, }, }, } @@ -43,18 +43,21 @@ func resourceAwsAlbTargetGroupAttachment() *schema.Resource { func resourceAwsAlbAttachmentCreate(d *schema.ResourceData, meta interface{}) error { elbconn := meta.(*AWSClient).elbv2conn - params := &elbv2.RegisterTargetsInput{ - TargetGroupArn: aws.String(d.Get("target_group_arn").(string)), - Targets: []*elbv2.TargetDescription{ - { - Id: aws.String(d.Get("target_id").(string)), - Port: aws.Int64(int64(d.Get("port").(int))), - }, - }, + target := &elbv2.TargetDescription{ + Id: aws.String(d.Get("target_id").(string)), } - log.Printf("[INFO] Registering Target %s (%d) with Target Group %s", d.Get("target_id").(string), - d.Get("port").(int), d.Get("target_group_arn").(string)) + if v, ok := d.GetOk("port"); ok { + target.Port = aws.Int64(int64(v.(int))) + } + + params := &elbv2.RegisterTargetsInput{ + TargetGroupArn: aws.String(d.Get("target_group_arn").(string)), + Targets: []*elbv2.TargetDescription{target}, + } + + log.Printf("[INFO] Registering Target %s with Target Group %s", d.Get("target_id").(string), + d.Get("target_group_arn").(string)) _, err := elbconn.RegisterTargets(params) if err != nil { @@ -69,14 +72,17 @@ func resourceAwsAlbAttachmentCreate(d *schema.ResourceData, meta interface{}) er func resourceAwsAlbAttachmentDelete(d *schema.ResourceData, meta interface{}) error { elbconn := meta.(*AWSClient).elbv2conn + target := &elbv2.TargetDescription{ + Id: aws.String(d.Get("target_id").(string)), + } + + if v, ok := d.GetOk("port"); ok { + target.Port = aws.Int64(int64(v.(int))) + } + params := &elbv2.DeregisterTargetsInput{ TargetGroupArn: aws.String(d.Get("target_group_arn").(string)), - Targets: []*elbv2.TargetDescription{ - { - Id: aws.String(d.Get("target_id").(string)), - Port: aws.Int64(int64(d.Get("port").(int))), - }, - }, + Targets: []*elbv2.TargetDescription{target}, } _, err := elbconn.DeregisterTargets(params) @@ -93,14 +99,18 @@ func resourceAwsAlbAttachmentDelete(d *schema.ResourceData, meta interface{}) er // target, so there is no work to do beyond ensuring that the target and group still exist. func resourceAwsAlbAttachmentRead(d *schema.ResourceData, meta interface{}) error { elbconn := meta.(*AWSClient).elbv2conn + + target := &elbv2.TargetDescription{ + Id: aws.String(d.Get("target_id").(string)), + } + + if v, ok := d.GetOk("port"); ok { + target.Port = aws.Int64(int64(v.(int))) + } + resp, err := elbconn.DescribeTargetHealth(&elbv2.DescribeTargetHealthInput{ TargetGroupArn: aws.String(d.Get("target_group_arn").(string)), - Targets: []*elbv2.TargetDescription{ - { - Id: aws.String(d.Get("target_id").(string)), - Port: aws.Int64(int64(d.Get("port").(int))), - }, - }, + Targets: []*elbv2.TargetDescription{target}, }) if err != nil { if isTargetGroupNotFound(err) { diff --git a/builtin/providers/aws/resource_aws_alb_target_group_attachment_test.go b/builtin/providers/aws/resource_aws_alb_target_group_attachment_test.go index bd063516d..32369d5d5 100644 --- a/builtin/providers/aws/resource_aws_alb_target_group_attachment_test.go +++ b/builtin/providers/aws/resource_aws_alb_target_group_attachment_test.go @@ -3,14 +3,15 @@ package aws import ( "errors" "fmt" + "strconv" + "testing" + "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/elbv2" "github.com/hashicorp/errwrap" "github.com/hashicorp/terraform/helper/acctest" "github.com/hashicorp/terraform/helper/resource" "github.com/hashicorp/terraform/terraform" - "strconv" - "testing" ) func TestAccAWSALBTargetGroupAttachment_basic(t *testing.T) { @@ -32,6 +33,25 @@ func TestAccAWSALBTargetGroupAttachment_basic(t *testing.T) { }) } +func TestAccAWSALBTargetGroupAttachment_withoutPort(t *testing.T) { + targetGroupName := fmt.Sprintf("test-target-group-%s", acctest.RandStringFromCharSet(10, acctest.CharSetAlphaNum)) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + IDRefreshName: "aws_alb_target_group.test", + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSALBTargetGroupAttachmentDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAWSALBTargetGroupAttachmentConfigWithoutPort(targetGroupName), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckAWSALBTargetGroupAttachmentExists("aws_alb_target_group_attachment.test"), + ), + }, + }, + }) +} + func testAccCheckAWSALBTargetGroupAttachmentExists(n string) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[n] @@ -45,15 +65,20 @@ func testAccCheckAWSALBTargetGroupAttachmentExists(n string) resource.TestCheckF conn := testAccProvider.Meta().(*AWSClient).elbv2conn - port, _ := strconv.Atoi(rs.Primary.Attributes["port"]) + _, hasPort := rs.Primary.Attributes["port"] + targetGroupArn, _ := rs.Primary.Attributes["target_group_arn"] + + target := &elbv2.TargetDescription{ + Id: aws.String(rs.Primary.Attributes["target_id"]), + } + if hasPort == true { + port, _ := strconv.Atoi(rs.Primary.Attributes["port"]) + target.Port = aws.Int64(int64(port)) + } + describe, err := conn.DescribeTargetHealth(&elbv2.DescribeTargetHealthInput{ - TargetGroupArn: aws.String(rs.Primary.Attributes["target_group_arn"]), - Targets: []*elbv2.TargetDescription{ - { - Id: aws.String(rs.Primary.Attributes["target_id"]), - Port: aws.Int64(int64(port)), - }, - }, + TargetGroupArn: aws.String(targetGroupArn), + Targets: []*elbv2.TargetDescription{target}, }) if err != nil { @@ -76,15 +101,20 @@ func testAccCheckAWSALBTargetGroupAttachmentDestroy(s *terraform.State) error { continue } - port, _ := strconv.Atoi(rs.Primary.Attributes["port"]) + _, hasPort := rs.Primary.Attributes["port"] + targetGroupArn, _ := rs.Primary.Attributes["target_group_arn"] + + target := &elbv2.TargetDescription{ + Id: aws.String(rs.Primary.Attributes["target_id"]), + } + if hasPort == true { + port, _ := strconv.Atoi(rs.Primary.Attributes["port"]) + target.Port = aws.Int64(int64(port)) + } + describe, err := conn.DescribeTargetHealth(&elbv2.DescribeTargetHealthInput{ - TargetGroupArn: aws.String(rs.Primary.Attributes["target_group_arn"]), - Targets: []*elbv2.TargetDescription{ - { - Id: aws.String(rs.Primary.Attributes["target_id"]), - Port: aws.Int64(int64(port)), - }, - }, + TargetGroupArn: aws.String(targetGroupArn), + Targets: []*elbv2.TargetDescription{target}, }) if err == nil { if len(describe.TargetHealthDescriptions) != 0 { @@ -103,6 +133,55 @@ func testAccCheckAWSALBTargetGroupAttachmentDestroy(s *terraform.State) error { return nil } +func testAccAWSALBTargetGroupAttachmentConfigWithoutPort(targetGroupName string) string { + return fmt.Sprintf(` +resource "aws_alb_target_group_attachment" "test" { + target_group_arn = "${aws_alb_target_group.test.arn}" + target_id = "${aws_instance.test.id}" +} + +resource "aws_instance" "test" { + ami = "ami-f701cb97" + instance_type = "t2.micro" + subnet_id = "${aws_subnet.subnet.id}" +} + +resource "aws_alb_target_group" "test" { + name = "%s" + port = 443 + protocol = "HTTPS" + vpc_id = "${aws_vpc.test.id}" + + deregistration_delay = 200 + + stickiness { + type = "lb_cookie" + cookie_duration = 10000 + } + + health_check { + path = "/health" + interval = 60 + port = 8081 + protocol = "HTTP" + timeout = 3 + healthy_threshold = 3 + unhealthy_threshold = 3 + matcher = "200-299" + } +} + +resource "aws_subnet" "subnet" { + cidr_block = "10.0.1.0/24" + vpc_id = "${aws_vpc.test.id}" + +} + +resource "aws_vpc" "test" { + cidr_block = "10.0.0.0/16" +}`, targetGroupName) +} + func testAccAWSALBTargetGroupAttachmentConfig_basic(targetGroupName string) string { return fmt.Sprintf(` resource "aws_alb_target_group_attachment" "test" { diff --git a/builtin/providers/aws/resource_aws_alb_target_group_test.go b/builtin/providers/aws/resource_aws_alb_target_group_test.go index 67d453e6c..2045ffeb7 100644 --- a/builtin/providers/aws/resource_aws_alb_target_group_test.go +++ b/builtin/providers/aws/resource_aws_alb_target_group_test.go @@ -3,6 +3,7 @@ package aws import ( "errors" "fmt" + "regexp" "testing" "github.com/aws/aws-sdk-go/aws" @@ -77,6 +78,47 @@ func TestAccAWSALBTargetGroup_basic(t *testing.T) { resource.TestCheckResourceAttr("aws_alb_target_group.test", "health_check.0.healthy_threshold", "3"), resource.TestCheckResourceAttr("aws_alb_target_group.test", "health_check.0.unhealthy_threshold", "3"), resource.TestCheckResourceAttr("aws_alb_target_group.test", "health_check.0.matcher", "200-299"), + resource.TestCheckResourceAttr("aws_alb_target_group.test", "tags.%", "1"), + resource.TestCheckResourceAttr("aws_alb_target_group.test", "tags.TestName", "TestAccAWSALBTargetGroup_basic"), + ), + }, + }, + }) +} + +func TestAccAWSALBTargetGroup_namePrefix(t *testing.T) { + var conf elbv2.TargetGroup + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + IDRefreshName: "aws_alb_target_group.test", + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSALBTargetGroupDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAWSALBTargetGroupConfig_namePrefix, + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSALBTargetGroupExists("aws_alb_target_group.test", &conf), + resource.TestMatchResourceAttr("aws_alb_target_group.test", "name", regexp.MustCompile("^tf-")), + ), + }, + }, + }) +} + +func TestAccAWSALBTargetGroup_generatedName(t *testing.T) { + var conf elbv2.TargetGroup + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + IDRefreshName: "aws_alb_target_group.test", + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSALBTargetGroupDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAWSALBTargetGroupConfig_generatedName, + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSALBTargetGroupExists("aws_alb_target_group.test", &conf), ), }, }, @@ -713,3 +755,28 @@ resource "aws_vpc" "test" { } }`, targetGroupName, stickinessBlock) } + +const testAccAWSALBTargetGroupConfig_namePrefix = ` +resource "aws_alb_target_group" "test" { + name_prefix = "tf-" + port = 80 + protocol = "HTTP" + vpc_id = "${aws_vpc.test.id}" +} + +resource "aws_vpc" "test" { + cidr_block = "10.0.0.0/16" +} +` + +const testAccAWSALBTargetGroupConfig_generatedName = ` +resource "aws_alb_target_group" "test" { + port = 80 + protocol = "HTTP" + vpc_id = "${aws_vpc.test.id}" +} + +resource "aws_vpc" "test" { + cidr_block = "10.0.0.0/16" +} +` diff --git a/builtin/providers/aws/resource_aws_alb_test.go b/builtin/providers/aws/resource_aws_alb_test.go index de127dfc4..5e766d74b 100644 --- a/builtin/providers/aws/resource_aws_alb_test.go +++ b/builtin/providers/aws/resource_aws_alb_test.go @@ -67,6 +67,7 @@ func TestAccAWSALB_basic(t *testing.T) { resource.TestCheckResourceAttr("aws_alb.alb_test", "tags.TestName", "TestAccAWSALB_basic"), resource.TestCheckResourceAttr("aws_alb.alb_test", "enable_deletion_protection", "false"), resource.TestCheckResourceAttr("aws_alb.alb_test", "idle_timeout", "30"), + resource.TestCheckResourceAttr("aws_alb.alb_test", "ip_address_type", "ipv4"), resource.TestCheckResourceAttrSet("aws_alb.alb_test", "vpc_id"), resource.TestCheckResourceAttrSet("aws_alb.alb_test", "zone_id"), resource.TestCheckResourceAttrSet("aws_alb.alb_test", "dns_name"), @@ -97,6 +98,26 @@ func TestAccAWSALB_generatedName(t *testing.T) { }) } +func TestAccAWSALB_generatesNameForZeroValue(t *testing.T) { + var conf elbv2.LoadBalancer + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + IDRefreshName: "aws_alb.alb_test", + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSALBDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAWSALBConfig_zeroValueName(), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckAWSALBExists("aws_alb.alb_test", &conf), + resource.TestCheckResourceAttrSet("aws_alb.alb_test", "name"), + ), + }, + }, + }) +} + func TestAccAWSALB_namePrefix(t *testing.T) { var conf elbv2.LoadBalancer @@ -112,7 +133,7 @@ func TestAccAWSALB_namePrefix(t *testing.T) { testAccCheckAWSALBExists("aws_alb.alb_test", &conf), resource.TestCheckResourceAttrSet("aws_alb.alb_test", "name"), resource.TestMatchResourceAttr("aws_alb.alb_test", "name", - regexp.MustCompile("^tf-lb")), + regexp.MustCompile("^tf-lb-")), ), }, }, @@ -208,6 +229,34 @@ func TestAccAWSALB_updatedSubnets(t *testing.T) { }) } +func TestAccAWSALB_updatedIpAddressType(t *testing.T) { + var pre, post elbv2.LoadBalancer + albName := fmt.Sprintf("testaccawsalb-basic-%s", acctest.RandStringFromCharSet(10, acctest.CharSetAlphaNum)) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + IDRefreshName: "aws_alb.alb_test", + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSALBDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAWSALBConfigWithIpAddressType(albName), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckAWSALBExists("aws_alb.alb_test", &pre), + resource.TestCheckResourceAttr("aws_alb.alb_test", "ip_address_type", "ipv4"), + ), + }, + { + Config: testAccAWSALBConfigWithIpAddressTypeUpdated(albName), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckAWSALBExists("aws_alb.alb_test", &post), + resource.TestCheckResourceAttr("aws_alb.alb_test", "ip_address_type", "dualstack"), + ), + }, + }, + }) +} + // TestAccAWSALB_noSecurityGroup regression tests the issue in #8264, // where if an ALB is created without a security group, a default one // is assigned. @@ -388,6 +437,228 @@ func testAccCheckAWSALBDestroy(s *terraform.State) error { return nil } +func testAccAWSALBConfigWithIpAddressTypeUpdated(albName string) string { + return fmt.Sprintf(`resource "aws_alb" "alb_test" { + name = "%s" + security_groups = ["${aws_security_group.alb_test.id}"] + subnets = ["${aws_subnet.alb_test_1.id}", "${aws_subnet.alb_test_2.id}"] + + ip_address_type = "dualstack" + + idle_timeout = 30 + enable_deletion_protection = false + + tags { + TestName = "TestAccAWSALB_basic" + } +} + +resource "aws_alb_listener" "test" { + load_balancer_arn = "${aws_alb.alb_test.id}" + protocol = "HTTP" + port = "80" + + default_action { + target_group_arn = "${aws_alb_target_group.test.id}" + type = "forward" + } +} + +resource "aws_alb_target_group" "test" { + name = "%s" + port = 80 + protocol = "HTTP" + vpc_id = "${aws_vpc.alb_test.id}" + + deregistration_delay = 200 + + stickiness { + type = "lb_cookie" + cookie_duration = 10000 + } + + health_check { + path = "/health2" + interval = 30 + port = 8082 + protocol = "HTTPS" + timeout = 4 + healthy_threshold = 4 + unhealthy_threshold = 4 + matcher = "200" + } +} + +resource "aws_egress_only_internet_gateway" "igw" { + vpc_id = "${aws_vpc.alb_test.id}" +} + +resource "aws_vpc" "alb_test" { + cidr_block = "10.0.0.0/16" + assign_generated_ipv6_cidr_block = true + + tags { + TestName = "TestAccAWSALB_basic" + } +} + +resource "aws_internet_gateway" "foo" { + vpc_id = "${aws_vpc.alb_test.id}" +} + +resource "aws_subnet" "alb_test_1" { + vpc_id = "${aws_vpc.alb_test.id}" + cidr_block = "10.0.1.0/24" + map_public_ip_on_launch = true + availability_zone = "us-west-2a" + ipv6_cidr_block = "${cidrsubnet(aws_vpc.alb_test.ipv6_cidr_block, 8, 1)}" + + tags { + TestName = "TestAccAWSALB_basic" + } +} + +resource "aws_subnet" "alb_test_2" { + vpc_id = "${aws_vpc.alb_test.id}" + cidr_block = "10.0.2.0/24" + map_public_ip_on_launch = true + availability_zone = "us-west-2b" + ipv6_cidr_block = "${cidrsubnet(aws_vpc.alb_test.ipv6_cidr_block, 8, 2)}" + + tags { + TestName = "TestAccAWSALB_basic" + } +} + +resource "aws_security_group" "alb_test" { + name = "allow_all_alb_test" + description = "Used for ALB Testing" + vpc_id = "${aws_vpc.alb_test.id}" + + ingress { + from_port = 0 + to_port = 0 + protocol = "-1" + cidr_blocks = ["0.0.0.0/0"] + } + + tags { + TestName = "TestAccAWSALB_basic" + } +}`, albName, albName) +} + +func testAccAWSALBConfigWithIpAddressType(albName string) string { + return fmt.Sprintf(`resource "aws_alb" "alb_test" { + name = "%s" + security_groups = ["${aws_security_group.alb_test.id}"] + subnets = ["${aws_subnet.alb_test_1.id}", "${aws_subnet.alb_test_2.id}"] + + ip_address_type = "ipv4" + + idle_timeout = 30 + enable_deletion_protection = false + + tags { + TestName = "TestAccAWSALB_basic" + } +} + +resource "aws_alb_listener" "test" { + load_balancer_arn = "${aws_alb.alb_test.id}" + protocol = "HTTP" + port = "80" + + default_action { + target_group_arn = "${aws_alb_target_group.test.id}" + type = "forward" + } +} + +resource "aws_alb_target_group" "test" { + name = "%s" + port = 80 + protocol = "HTTP" + vpc_id = "${aws_vpc.alb_test.id}" + + deregistration_delay = 200 + + stickiness { + type = "lb_cookie" + cookie_duration = 10000 + } + + health_check { + path = "/health2" + interval = 30 + port = 8082 + protocol = "HTTPS" + timeout = 4 + healthy_threshold = 4 + unhealthy_threshold = 4 + matcher = "200" + } +} + +resource "aws_egress_only_internet_gateway" "igw" { + vpc_id = "${aws_vpc.alb_test.id}" +} + +resource "aws_vpc" "alb_test" { + cidr_block = "10.0.0.0/16" + assign_generated_ipv6_cidr_block = true + + tags { + TestName = "TestAccAWSALB_basic" + } +} + +resource "aws_internet_gateway" "foo" { + vpc_id = "${aws_vpc.alb_test.id}" +} + +resource "aws_subnet" "alb_test_1" { + vpc_id = "${aws_vpc.alb_test.id}" + cidr_block = "10.0.1.0/24" + map_public_ip_on_launch = true + availability_zone = "us-west-2a" + ipv6_cidr_block = "${cidrsubnet(aws_vpc.alb_test.ipv6_cidr_block, 8, 1)}" + + tags { + TestName = "TestAccAWSALB_basic" + } +} + +resource "aws_subnet" "alb_test_2" { + vpc_id = "${aws_vpc.alb_test.id}" + cidr_block = "10.0.2.0/24" + map_public_ip_on_launch = true + availability_zone = "us-west-2b" + ipv6_cidr_block = "${cidrsubnet(aws_vpc.alb_test.ipv6_cidr_block, 8, 2)}" + + tags { + TestName = "TestAccAWSALB_basic" + } +} + +resource "aws_security_group" "alb_test" { + name = "allow_all_alb_test" + description = "Used for ALB Testing" + vpc_id = "${aws_vpc.alb_test.id}" + + ingress { + from_port = 0 + to_port = 0 + protocol = "-1" + cidr_blocks = ["0.0.0.0/0"] + } + + tags { + TestName = "TestAccAWSALB_basic" + } +}`, albName, albName) +} + func testAccAWSALBConfig_basic(albName string) string { return fmt.Sprintf(`resource "aws_alb" "alb_test" { name = "%s" @@ -597,10 +868,86 @@ resource "aws_security_group" "alb_test" { }`) } +func testAccAWSALBConfig_zeroValueName() string { + return fmt.Sprintf(` +resource "aws_alb" "alb_test" { + name = "" + internal = true + security_groups = ["${aws_security_group.alb_test.id}"] + subnets = ["${aws_subnet.alb_test.*.id}"] + + idle_timeout = 30 + enable_deletion_protection = false + + tags { + TestName = "TestAccAWSALB_basic" + } +} + +variable "subnets" { + default = ["10.0.1.0/24", "10.0.2.0/24"] + type = "list" +} + +data "aws_availability_zones" "available" {} + +resource "aws_vpc" "alb_test" { + cidr_block = "10.0.0.0/16" + + tags { + TestName = "TestAccAWSALB_basic" + } +} + +resource "aws_internet_gateway" "gw" { + vpc_id = "${aws_vpc.alb_test.id}" + + tags { + Name = "TestAccAWSALB_basic" + } +} + +resource "aws_subnet" "alb_test" { + count = 2 + vpc_id = "${aws_vpc.alb_test.id}" + cidr_block = "${element(var.subnets, count.index)}" + map_public_ip_on_launch = true + availability_zone = "${element(data.aws_availability_zones.available.names, count.index)}" + + tags { + TestName = "TestAccAWSALB_basic" + } +} + +resource "aws_security_group" "alb_test" { + name = "allow_all_alb_test" + description = "Used for ALB Testing" + vpc_id = "${aws_vpc.alb_test.id}" + + ingress { + from_port = 0 + to_port = 0 + protocol = "-1" + cidr_blocks = ["0.0.0.0/0"] + } + + egress { + from_port = 0 + to_port = 0 + protocol = "-1" + cidr_blocks = ["0.0.0.0/0"] + } + + tags { + TestName = "TestAccAWSALB_basic" + } +}`) +} + func testAccAWSALBConfig_namePrefix() string { return fmt.Sprintf(` resource "aws_alb" "alb_test" { - name_prefix = "tf-lb" + name_prefix = "tf-lb-" internal = true security_groups = ["${aws_security_group.alb_test.id}"] subnets = ["${aws_subnet.alb_test.*.id}"] diff --git a/builtin/providers/aws/resource_aws_ami.go b/builtin/providers/aws/resource_aws_ami.go index 6e4ee1522..d01c402ed 100644 --- a/builtin/providers/aws/resource_aws_ami.go +++ b/builtin/providers/aws/resource_aws_ami.go @@ -18,8 +18,8 @@ import ( ) const ( - AWSAMIRetryTimeout = 10 * time.Minute - AWSAMIDeleteRetryTimeout = 20 * time.Minute + AWSAMIRetryTimeout = 40 * time.Minute + AWSAMIDeleteRetryTimeout = 90 * time.Minute AWSAMIRetryDelay = 5 * time.Second AWSAMIRetryMinTimeout = 3 * time.Second ) diff --git a/builtin/providers/aws/resource_aws_ami_launch_permission.go b/builtin/providers/aws/resource_aws_ami_launch_permission.go index d1c738d39..278e9d9ab 100644 --- a/builtin/providers/aws/resource_aws_ami_launch_permission.go +++ b/builtin/providers/aws/resource_aws_ami_launch_permission.go @@ -2,7 +2,11 @@ package aws import ( "fmt" + "log" + "strings" + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/service/ec2" "github.com/hashicorp/terraform/helper/schema" ) @@ -92,6 +96,12 @@ func hasLaunchPermission(conn *ec2.EC2, image_id string, account_id string) (boo Attribute: aws.String("launchPermission"), }) if err != nil { + // When an AMI disappears out from under a launch permission resource, we will + // see either InvalidAMIID.NotFound or InvalidAMIID.Unavailable. + if ec2err, ok := err.(awserr.Error); ok && strings.HasPrefix(ec2err.Code(), "InvalidAMIID") { + log.Printf("[DEBUG] %s no longer exists, so we'll drop launch permission for %s from the state", image_id, account_id) + return false, nil + } return false, err } diff --git a/builtin/providers/aws/resource_aws_ami_launch_permission_test.go b/builtin/providers/aws/resource_aws_ami_launch_permission_test.go index 0affa9161..4ccb35c7c 100644 --- a/builtin/providers/aws/resource_aws_ami_launch_permission_test.go +++ b/builtin/providers/aws/resource_aws_ami_launch_permission_test.go @@ -2,15 +2,18 @@ package aws import ( "fmt" - r "github.com/hashicorp/terraform/helper/resource" - "github.com/hashicorp/terraform/terraform" "os" "testing" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/service/ec2" + r "github.com/hashicorp/terraform/helper/resource" + "github.com/hashicorp/terraform/terraform" ) func TestAccAWSAMILaunchPermission_Basic(t *testing.T) { - image_id := "" - account_id := os.Getenv("AWS_ACCOUNT_ID") + imageID := "" + accountID := os.Getenv("AWS_ACCOUNT_ID") r.Test(t, r.TestCase{ PreCheck: func() { @@ -23,19 +26,36 @@ func TestAccAWSAMILaunchPermission_Basic(t *testing.T) { Steps: []r.TestStep{ // Scaffold everything r.TestStep{ - Config: testAccAWSAMILaunchPermissionConfig(account_id, true), + Config: testAccAWSAMILaunchPermissionConfig(accountID, true), Check: r.ComposeTestCheckFunc( - testCheckResourceGetAttr("aws_ami_copy.test", "id", &image_id), - testAccAWSAMILaunchPermissionExists(account_id, &image_id), + testCheckResourceGetAttr("aws_ami_copy.test", "id", &imageID), + testAccAWSAMILaunchPermissionExists(accountID, &imageID), ), }, // Drop just launch permission to test destruction r.TestStep{ - Config: testAccAWSAMILaunchPermissionConfig(account_id, false), + Config: testAccAWSAMILaunchPermissionConfig(accountID, false), Check: r.ComposeTestCheckFunc( - testAccAWSAMILaunchPermissionDestroyed(account_id, &image_id), + testAccAWSAMILaunchPermissionDestroyed(accountID, &imageID), ), }, + // Re-add everything so we can test when AMI disappears + r.TestStep{ + Config: testAccAWSAMILaunchPermissionConfig(accountID, true), + Check: r.ComposeTestCheckFunc( + testCheckResourceGetAttr("aws_ami_copy.test", "id", &imageID), + testAccAWSAMILaunchPermissionExists(accountID, &imageID), + ), + }, + // Here we delete the AMI to verify the follow-on refresh after this step + // should not error. + r.TestStep{ + Config: testAccAWSAMILaunchPermissionConfig(accountID, true), + Check: r.ComposeTestCheckFunc( + testAccAWSAMIDisappears(&imageID), + ), + ExpectNonEmptyPlan: true, + }, }, }) } @@ -58,31 +78,53 @@ func testCheckResourceGetAttr(name, key string, value *string) r.TestCheckFunc { } } -func testAccAWSAMILaunchPermissionExists(account_id string, image_id *string) r.TestCheckFunc { +func testAccAWSAMILaunchPermissionExists(accountID string, imageID *string) r.TestCheckFunc { return func(s *terraform.State) error { conn := testAccProvider.Meta().(*AWSClient).ec2conn - if has, err := hasLaunchPermission(conn, *image_id, account_id); err != nil { + if has, err := hasLaunchPermission(conn, *imageID, accountID); err != nil { return err } else if !has { - return fmt.Errorf("launch permission does not exist for '%s' on '%s'", account_id, *image_id) + return fmt.Errorf("launch permission does not exist for '%s' on '%s'", accountID, *imageID) } return nil } } -func testAccAWSAMILaunchPermissionDestroyed(account_id string, image_id *string) r.TestCheckFunc { +func testAccAWSAMILaunchPermissionDestroyed(accountID string, imageID *string) r.TestCheckFunc { return func(s *terraform.State) error { conn := testAccProvider.Meta().(*AWSClient).ec2conn - if has, err := hasLaunchPermission(conn, *image_id, account_id); err != nil { + if has, err := hasLaunchPermission(conn, *imageID, accountID); err != nil { return err } else if has { - return fmt.Errorf("launch permission still exists for '%s' on '%s'", account_id, *image_id) + return fmt.Errorf("launch permission still exists for '%s' on '%s'", accountID, *imageID) } return nil } } -func testAccAWSAMILaunchPermissionConfig(account_id string, includeLaunchPermission bool) string { +// testAccAWSAMIDisappears is technically a "test check function" but really it +// exists to perform a side effect of deleting an AMI out from under a resource +// so we can test that Terraform will react properly +func testAccAWSAMIDisappears(imageID *string) r.TestCheckFunc { + return func(s *terraform.State) error { + conn := testAccProvider.Meta().(*AWSClient).ec2conn + req := &ec2.DeregisterImageInput{ + ImageId: aws.String(*imageID), + } + + _, err := conn.DeregisterImage(req) + if err != nil { + return err + } + + if err := resourceAwsAmiWaitForDestroy(*imageID, conn); err != nil { + return err + } + return nil + } +} + +func testAccAWSAMILaunchPermissionConfig(accountID string, includeLaunchPermission bool) string { base := ` resource "aws_ami_copy" "test" { name = "launch-permission-test" @@ -101,5 +143,5 @@ resource "aws_ami_launch_permission" "self-test" { image_id = "${aws_ami_copy.test.id}" account_id = "%s" } -`, account_id) +`, accountID) } diff --git a/builtin/providers/aws/resource_aws_ami_test.go b/builtin/providers/aws/resource_aws_ami_test.go index cf34187f1..2f2e481a4 100644 --- a/builtin/providers/aws/resource_aws_ami_test.go +++ b/builtin/providers/aws/resource_aws_ami_test.go @@ -82,6 +82,10 @@ func testAccCheckAmiDestroy(s *terraform.State) error { } resp, err := conn.DescribeImages(DescribeAmiOpts) if err != nil { + if isAWSErr(err, "InvalidAMIID", "NotFound") { + log.Printf("[DEBUG] AMI not found, passing") + return nil + } return err } @@ -183,7 +187,7 @@ resource "aws_ebs_volume" "foo" { availability_zone = "us-west-2a" size = 8 tags { - Name = "tf-acc-test" + Name = "testAccAmiConfig_basic" } } @@ -209,7 +213,7 @@ resource "aws_ebs_volume" "foo" { availability_zone = "us-west-2a" size = 20 tags { - Name = "tf-acc-test" + Name = "testAccAmiConfig_snapshotSize" } } diff --git a/builtin/providers/aws/resource_aws_api_gateway_deployment.go b/builtin/providers/aws/resource_aws_api_gateway_deployment.go index 494776288..f4c1daf20 100644 --- a/builtin/providers/aws/resource_aws_api_gateway_deployment.go +++ b/builtin/providers/aws/resource_aws_api_gateway_deployment.go @@ -54,6 +54,16 @@ func resourceAwsApiGatewayDeployment() *schema.Resource { Type: schema.TypeString, Computed: true, }, + + "invoke_url": { + Type: schema.TypeString, + Computed: true, + }, + + "execution_arn": { + Type: schema.TypeString, + Computed: true, + }, }, } } @@ -90,8 +100,9 @@ func resourceAwsApiGatewayDeploymentRead(d *schema.ResourceData, meta interface{ conn := meta.(*AWSClient).apigateway log.Printf("[DEBUG] Reading API Gateway Deployment %s", d.Id()) + restApiId := d.Get("rest_api_id").(string) out, err := conn.GetDeployment(&apigateway.GetDeploymentInput{ - RestApiId: aws.String(d.Get("rest_api_id").(string)), + RestApiId: aws.String(restApiId), DeploymentId: aws.String(d.Id()), }) if err != nil { @@ -104,6 +115,18 @@ func resourceAwsApiGatewayDeploymentRead(d *schema.ResourceData, meta interface{ log.Printf("[DEBUG] Received API Gateway Deployment: %s", out) d.Set("description", out.Description) + region := meta.(*AWSClient).region + stageName := d.Get("stage_name").(string) + + d.Set("invoke_url", buildApiGatewayInvokeURL(restApiId, region, stageName)) + + accountId := meta.(*AWSClient).accountid + arn, err := buildApiGatewayExecutionARN(restApiId, region, accountId) + if err != nil { + return err + } + d.Set("execution_arn", arn+"/"+stageName) + if err := d.Set("created_date", out.CreatedDate.Format(time.RFC3339)); err != nil { log.Printf("[DEBUG] Error setting created_date: %s", err) } diff --git a/builtin/providers/aws/resource_aws_api_gateway_domain_name.go b/builtin/providers/aws/resource_aws_api_gateway_domain_name.go index 103f7bed4..be90c40ec 100644 --- a/builtin/providers/aws/resource_aws_api_gateway_domain_name.go +++ b/builtin/providers/aws/resource_aws_api_gateway_domain_name.go @@ -48,6 +48,7 @@ func resourceAwsApiGatewayDomainName() *schema.Resource { Type: schema.TypeString, ForceNew: true, Optional: true, + Sensitive: true, ConflictsWith: []string{"certificate_arn"}, }, diff --git a/builtin/providers/aws/resource_aws_api_gateway_integration.go b/builtin/providers/aws/resource_aws_api_gateway_integration.go index b06982880..f782e11ea 100644 --- a/builtin/providers/aws/resource_aws_api_gateway_integration.go +++ b/builtin/providers/aws/resource_aws_api_gateway_integration.go @@ -11,87 +11,94 @@ import ( "github.com/aws/aws-sdk-go/service/apigateway" "github.com/hashicorp/terraform/helper/resource" "github.com/hashicorp/terraform/helper/schema" + "strings" ) func resourceAwsApiGatewayIntegration() *schema.Resource { return &schema.Resource{ Create: resourceAwsApiGatewayIntegrationCreate, Read: resourceAwsApiGatewayIntegrationRead, - Update: resourceAwsApiGatewayIntegrationCreate, + Update: resourceAwsApiGatewayIntegrationUpdate, Delete: resourceAwsApiGatewayIntegrationDelete, Schema: map[string]*schema.Schema{ - "rest_api_id": &schema.Schema{ + "rest_api_id": { Type: schema.TypeString, Required: true, ForceNew: true, }, - "resource_id": &schema.Schema{ + "resource_id": { Type: schema.TypeString, Required: true, ForceNew: true, }, - "http_method": &schema.Schema{ + "http_method": { Type: schema.TypeString, Required: true, ForceNew: true, ValidateFunc: validateHTTPMethod, }, - "type": &schema.Schema{ + "type": { Type: schema.TypeString, Required: true, + ForceNew: true, ValidateFunc: validateApiGatewayIntegrationType, }, - "uri": &schema.Schema{ + "uri": { Type: schema.TypeString, Optional: true, + ForceNew: true, }, - "credentials": &schema.Schema{ + "credentials": { Type: schema.TypeString, Optional: true, + ForceNew: true, }, - "integration_http_method": &schema.Schema{ + "integration_http_method": { Type: schema.TypeString, Optional: true, + ForceNew: true, ValidateFunc: validateHTTPMethod, }, - "request_templates": &schema.Schema{ + "request_templates": { Type: schema.TypeMap, Optional: true, Elem: schema.TypeString, }, - "request_parameters": &schema.Schema{ + "request_parameters": { Type: schema.TypeMap, Elem: schema.TypeString, Optional: true, ConflictsWith: []string{"request_parameters_in_json"}, }, - "request_parameters_in_json": &schema.Schema{ + "request_parameters_in_json": { Type: schema.TypeString, Optional: true, ConflictsWith: []string{"request_parameters"}, Deprecated: "Use field request_parameters instead", }, - "content_handling": &schema.Schema{ + "content_handling": { Type: schema.TypeString, Optional: true, + ForceNew: true, ValidateFunc: validateApiGatewayIntegrationContentHandling, }, - "passthrough_behavior": &schema.Schema{ + "passthrough_behavior": { Type: schema.TypeString, Optional: true, Computed: true, + ForceNew: true, ValidateFunc: validateApiGatewayIntegrationPassthroughBehavior, }, }, @@ -101,6 +108,7 @@ func resourceAwsApiGatewayIntegration() *schema.Resource { func resourceAwsApiGatewayIntegrationCreate(d *schema.ResourceData, meta interface{}) error { conn := meta.(*AWSClient).apigateway + log.Print("[DEBUG] Creating API Gateway Integration") var integrationHttpMethod *string if v, ok := d.GetOk("integration_http_method"); ok { integrationHttpMethod = aws.String(v.(string)) @@ -163,13 +171,13 @@ func resourceAwsApiGatewayIntegrationCreate(d *schema.ResourceData, meta interfa d.SetId(fmt.Sprintf("agi-%s-%s-%s", d.Get("rest_api_id").(string), d.Get("resource_id").(string), d.Get("http_method").(string))) - return nil + return resourceAwsApiGatewayIntegrationRead(d, meta) } func resourceAwsApiGatewayIntegrationRead(d *schema.ResourceData, meta interface{}) error { conn := meta.(*AWSClient).apigateway - log.Printf("[DEBUG] Reading API Gateway Integration %s", d.Id()) + log.Printf("[DEBUG] Reading API Gateway Integration: %s", d.Id()) integration, err := conn.GetIntegration(&apigateway.GetIntegrationInput{ HttpMethod: aws.String(d.Get("http_method").(string)), ResourceId: aws.String(d.Get("resource_id").(string)), @@ -191,17 +199,127 @@ func resourceAwsApiGatewayIntegrationRead(d *schema.ResourceData, meta interface } d.Set("request_templates", aws.StringValueMap(integration.RequestTemplates)) - d.Set("credentials", integration.Credentials) d.Set("type", integration.Type) - d.Set("uri", integration.Uri) d.Set("request_parameters", aws.StringValueMap(integration.RequestParameters)) d.Set("request_parameters_in_json", aws.StringValueMap(integration.RequestParameters)) d.Set("passthrough_behavior", integration.PassthroughBehavior) - d.Set("content_handling", integration.ContentHandling) + + if integration.Uri != nil { + d.Set("uri", integration.Uri) + } + + if integration.Credentials != nil { + d.Set("credentials", integration.Credentials) + } + + if integration.ContentHandling != nil { + d.Set("content_handling", integration.ContentHandling) + } return nil } +func resourceAwsApiGatewayIntegrationUpdate(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*AWSClient).apigateway + + log.Printf("[DEBUG] Updating API Gateway Integration: %s", d.Id()) + operations := make([]*apigateway.PatchOperation, 0) + + // https://docs.aws.amazon.com/apigateway/api-reference/link-relation/integration-update/#remarks + // According to the above documentation, only a few parts are addable / removable. + if d.HasChange("request_templates") { + o, n := d.GetChange("request_templates") + prefix := "requestTemplates" + + os := o.(map[string]interface{}) + ns := n.(map[string]interface{}) + + // Handle Removal + for k := range os { + if _, ok := ns[k]; !ok { + operations = append(operations, &apigateway.PatchOperation{ + Op: aws.String("remove"), + Path: aws.String(fmt.Sprintf("/%s/%s", prefix, strings.Replace(k, "/", "~1", -1))), + }) + } + } + + for k, v := range ns { + // Handle replaces + if _, ok := os[k]; ok { + operations = append(operations, &apigateway.PatchOperation{ + Op: aws.String("replace"), + Path: aws.String(fmt.Sprintf("/%s/%s", prefix, strings.Replace(k, "/", "~1", -1))), + Value: aws.String(v.(string)), + }) + } + + // Handle additions + if _, ok := os[k]; !ok { + operations = append(operations, &apigateway.PatchOperation{ + Op: aws.String("add"), + Path: aws.String(fmt.Sprintf("/%s/%s", prefix, strings.Replace(k, "/", "~1", -1))), + Value: aws.String(v.(string)), + }) + } + } + } + + if d.HasChange("request_parameters") { + o, n := d.GetChange("request_parameters") + prefix := "requestParameters" + + os := o.(map[string]interface{}) + ns := n.(map[string]interface{}) + + // Handle Removal + for k := range os { + if _, ok := ns[k]; !ok { + operations = append(operations, &apigateway.PatchOperation{ + Op: aws.String("remove"), + Path: aws.String(fmt.Sprintf("/%s/%s", prefix, strings.Replace(k, "/", "~1", -1))), + }) + } + } + + for k, v := range ns { + // Handle replaces + if _, ok := os[k]; ok { + operations = append(operations, &apigateway.PatchOperation{ + Op: aws.String("replace"), + Path: aws.String(fmt.Sprintf("/%s/%s", prefix, strings.Replace(k, "/", "~1", -1))), + Value: aws.String(v.(string)), + }) + } + + // Handle additions + if _, ok := os[k]; !ok { + operations = append(operations, &apigateway.PatchOperation{ + Op: aws.String("add"), + Path: aws.String(fmt.Sprintf("/%s/%s", prefix, strings.Replace(k, "/", "~1", -1))), + Value: aws.String(v.(string)), + }) + } + } + } + + params := &apigateway.UpdateIntegrationInput{ + HttpMethod: aws.String(d.Get("http_method").(string)), + ResourceId: aws.String(d.Get("resource_id").(string)), + RestApiId: aws.String(d.Get("rest_api_id").(string)), + PatchOperations: operations, + } + + _, err := conn.UpdateIntegration(params) + if err != nil { + return fmt.Errorf("Error updating API Gateway Integration: %s", err) + } + + d.SetId(fmt.Sprintf("agi-%s-%s-%s", d.Get("rest_api_id").(string), d.Get("resource_id").(string), d.Get("http_method").(string))) + + return resourceAwsApiGatewayIntegrationRead(d, meta) +} + func resourceAwsApiGatewayIntegrationDelete(d *schema.ResourceData, meta interface{}) error { conn := meta.(*AWSClient).apigateway log.Printf("[DEBUG] Deleting API Gateway Integration: %s", d.Id()) diff --git a/builtin/providers/aws/resource_aws_api_gateway_integration_test.go b/builtin/providers/aws/resource_aws_api_gateway_integration_test.go index 153ed13b4..ff9c23387 100644 --- a/builtin/providers/aws/resource_aws_api_gateway_integration_test.go +++ b/builtin/providers/aws/resource_aws_api_gateway_integration_test.go @@ -19,88 +19,80 @@ func TestAccAWSAPIGatewayIntegration_basic(t *testing.T) { Providers: testAccProviders, CheckDestroy: testAccCheckAWSAPIGatewayIntegrationDestroy, Steps: []resource.TestStep{ - resource.TestStep{ + { Config: testAccAWSAPIGatewayIntegrationConfig, Check: resource.ComposeTestCheckFunc( testAccCheckAWSAPIGatewayIntegrationExists("aws_api_gateway_integration.test", &conf), - testAccCheckAWSAPIGatewayIntegrationAttributes(&conf), - resource.TestCheckResourceAttr( - "aws_api_gateway_integration.test", "type", "HTTP"), - resource.TestCheckResourceAttr( - "aws_api_gateway_integration.test", "integration_http_method", "GET"), - resource.TestCheckResourceAttr( - "aws_api_gateway_integration.test", "uri", "https://www.google.de"), - resource.TestCheckResourceAttr( - "aws_api_gateway_integration.test", "request_templates.application/json", ""), - resource.TestCheckResourceAttr( - "aws_api_gateway_integration.test", "request_templates.application/xml", "#set($inputRoot = $input.path('$'))\n{ }"), - resource.TestCheckResourceAttr( - "aws_api_gateway_integration.test", "passthrough_behavior", "WHEN_NO_MATCH"), - resource.TestCheckNoResourceAttr( - "aws_api_gateway_integration.test", "content_handling"), + resource.TestCheckResourceAttr("aws_api_gateway_integration.test", "type", "HTTP"), + resource.TestCheckResourceAttr("aws_api_gateway_integration.test", "integration_http_method", "GET"), + resource.TestCheckResourceAttr("aws_api_gateway_integration.test", "uri", "https://www.google.de"), + resource.TestCheckResourceAttr("aws_api_gateway_integration.test", "passthrough_behavior", "WHEN_NO_MATCH"), + resource.TestCheckResourceAttr("aws_api_gateway_integration.test", "content_handling", "CONVERT_TO_TEXT"), + resource.TestCheckNoResourceAttr("aws_api_gateway_integration.test", "credentials"), + resource.TestCheckResourceAttr("aws_api_gateway_integration.test", "request_parameters.%", "2"), + resource.TestCheckResourceAttr("aws_api_gateway_integration.test", "request_parameters.integration.request.header.X-Authorization", "'static'"), + resource.TestCheckResourceAttr("aws_api_gateway_integration.test", "request_parameters.integration.request.header.X-Foo", "'Bar'"), + resource.TestCheckResourceAttr("aws_api_gateway_integration.test", "request_templates.%", "2"), + resource.TestCheckResourceAttr("aws_api_gateway_integration.test", "request_templates.application/json", ""), + resource.TestCheckResourceAttr("aws_api_gateway_integration.test", "request_templates.application/xml", "#set($inputRoot = $input.path('$'))\n{ }"), ), }, - resource.TestStep{ + { Config: testAccAWSAPIGatewayIntegrationConfigUpdate, Check: resource.ComposeTestCheckFunc( testAccCheckAWSAPIGatewayIntegrationExists("aws_api_gateway_integration.test", &conf), - testAccCheckAWSAPIGatewayMockIntegrationAttributes(&conf), - resource.TestCheckResourceAttr( - "aws_api_gateway_integration.test", "type", "MOCK"), - resource.TestCheckResourceAttr( - "aws_api_gateway_integration.test", "integration_http_method", ""), - resource.TestCheckResourceAttr( - "aws_api_gateway_integration.test", "uri", ""), - resource.TestCheckResourceAttr( - "aws_api_gateway_integration.test", "passthrough_behavior", "NEVER"), - resource.TestCheckResourceAttr( - "aws_api_gateway_integration.test", "content_handling", "CONVERT_TO_BINARY"), + resource.TestCheckResourceAttr("aws_api_gateway_integration.test", "type", "HTTP"), + resource.TestCheckResourceAttr("aws_api_gateway_integration.test", "integration_http_method", "GET"), + resource.TestCheckResourceAttr("aws_api_gateway_integration.test", "uri", "https://www.google.de"), + resource.TestCheckResourceAttr("aws_api_gateway_integration.test", "passthrough_behavior", "WHEN_NO_MATCH"), + resource.TestCheckResourceAttr("aws_api_gateway_integration.test", "content_handling", "CONVERT_TO_TEXT"), + resource.TestCheckNoResourceAttr("aws_api_gateway_integration.test", "credentials"), + resource.TestCheckResourceAttr("aws_api_gateway_integration.test", "request_parameters.%", "2"), + resource.TestCheckResourceAttr("aws_api_gateway_integration.test", "request_parameters.integration.request.header.X-Authorization", "'updated'"), + resource.TestCheckResourceAttr("aws_api_gateway_integration.test", "request_parameters.integration.request.header.X-FooBar", "'Baz'"), + resource.TestCheckResourceAttr("aws_api_gateway_integration.test", "request_templates.%", "2"), + resource.TestCheckResourceAttr("aws_api_gateway_integration.test", "request_templates.application/json", "{'foobar': 'bar}"), + resource.TestCheckResourceAttr("aws_api_gateway_integration.test", "request_templates.text/html", "Foo"), + ), + }, + + { + Config: testAccAWSAPIGatewayIntegrationConfigUpdateNoTemplates, + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSAPIGatewayIntegrationExists("aws_api_gateway_integration.test", &conf), + resource.TestCheckResourceAttr("aws_api_gateway_integration.test", "type", "HTTP"), + resource.TestCheckResourceAttr("aws_api_gateway_integration.test", "integration_http_method", "GET"), + resource.TestCheckResourceAttr("aws_api_gateway_integration.test", "uri", "https://www.google.de"), + resource.TestCheckResourceAttr("aws_api_gateway_integration.test", "passthrough_behavior", "WHEN_NO_MATCH"), + resource.TestCheckResourceAttr("aws_api_gateway_integration.test", "content_handling", "CONVERT_TO_TEXT"), + resource.TestCheckNoResourceAttr("aws_api_gateway_integration.test", "credentials"), + resource.TestCheckResourceAttr("aws_api_gateway_integration.test", "request_parameters.%", "0"), + resource.TestCheckResourceAttr("aws_api_gateway_integration.test", "request_templates.%", "0"), + ), + }, + + { + Config: testAccAWSAPIGatewayIntegrationConfig, + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSAPIGatewayIntegrationExists("aws_api_gateway_integration.test", &conf), + resource.TestCheckResourceAttr("aws_api_gateway_integration.test", "type", "HTTP"), + resource.TestCheckResourceAttr("aws_api_gateway_integration.test", "integration_http_method", "GET"), + resource.TestCheckResourceAttr("aws_api_gateway_integration.test", "uri", "https://www.google.de"), + resource.TestCheckResourceAttr("aws_api_gateway_integration.test", "passthrough_behavior", "WHEN_NO_MATCH"), + resource.TestCheckResourceAttr("aws_api_gateway_integration.test", "content_handling", "CONVERT_TO_TEXT"), + resource.TestCheckNoResourceAttr("aws_api_gateway_integration.test", "credentials"), + resource.TestCheckResourceAttr("aws_api_gateway_integration.test", "request_parameters.%", "2"), + resource.TestCheckResourceAttr("aws_api_gateway_integration.test", "request_parameters.integration.request.header.X-Authorization", "'static'"), + resource.TestCheckResourceAttr("aws_api_gateway_integration.test", "request_templates.%", "2"), + resource.TestCheckResourceAttr("aws_api_gateway_integration.test", "request_templates.application/json", ""), + resource.TestCheckResourceAttr("aws_api_gateway_integration.test", "request_templates.application/xml", "#set($inputRoot = $input.path('$'))\n{ }"), ), }, }, }) } -func testAccCheckAWSAPIGatewayMockIntegrationAttributes(conf *apigateway.Integration) resource.TestCheckFunc { - return func(s *terraform.State) error { - if *conf.Type != "MOCK" { - return fmt.Errorf("Wrong Type: %q", *conf.Type) - } - if *conf.RequestParameters["integration.request.header.X-Authorization"] != "'updated'" { - return fmt.Errorf("wrong updated RequestParameters for header.X-Authorization") - } - if *conf.ContentHandling != "CONVERT_TO_BINARY" { - return fmt.Errorf("wrong ContentHandling: %q", *conf.ContentHandling) - } - return nil - } -} - -func testAccCheckAWSAPIGatewayIntegrationAttributes(conf *apigateway.Integration) resource.TestCheckFunc { - return func(s *terraform.State) error { - if *conf.HttpMethod == "" { - return fmt.Errorf("empty HttpMethod") - } - if *conf.Uri != "https://www.google.de" { - return fmt.Errorf("wrong Uri") - } - if *conf.Type != "HTTP" { - return fmt.Errorf("wrong Type") - } - if conf.RequestTemplates["application/json"] != nil { - return fmt.Errorf("wrong RequestTemplate for application/json") - } - if *conf.RequestTemplates["application/xml"] != "#set($inputRoot = $input.path('$'))\n{ }" { - return fmt.Errorf("wrong RequestTemplate for application/xml") - } - if *conf.RequestParameters["integration.request.header.X-Authorization"] != "'static'" { - return fmt.Errorf("wrong RequestParameters for header.X-Authorization") - } - return nil - } -} - func testAccCheckAWSAPIGatewayIntegrationExists(n string, res *apigateway.Integration) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[n] @@ -196,13 +188,15 @@ resource "aws_api_gateway_integration" "test" { } request_parameters = { - "integration.request.header.X-Authorization" = "'static'" + "integration.request.header.X-Authorization" = "'static'" + "integration.request.header.X-Foo" = "'Bar'" } type = "HTTP" uri = "https://www.google.de" integration_http_method = "GET" passthrough_behavior = "WHEN_NO_MATCH" + content_handling = "CONVERT_TO_TEXT" } ` @@ -233,13 +227,55 @@ resource "aws_api_gateway_integration" "test" { resource_id = "${aws_api_gateway_resource.test.id}" http_method = "${aws_api_gateway_method.test.http_method}" - request_parameters = { - "integration.request.header.X-Authorization" = "'updated'" + request_templates = { + "application/json" = "{'foobar': 'bar}" + "text/html" = "Foo" } - type = "MOCK" - passthrough_behavior = "NEVER" - content_handling = "CONVERT_TO_BINARY" + request_parameters = { + "integration.request.header.X-Authorization" = "'updated'" + "integration.request.header.X-FooBar" = "'Baz'" + } + type = "HTTP" + uri = "https://www.google.de" + integration_http_method = "GET" + passthrough_behavior = "WHEN_NO_MATCH" + content_handling = "CONVERT_TO_TEXT" +} +` + +const testAccAWSAPIGatewayIntegrationConfigUpdateNoTemplates = ` +resource "aws_api_gateway_rest_api" "test" { + name = "test" +} + +resource "aws_api_gateway_resource" "test" { + rest_api_id = "${aws_api_gateway_rest_api.test.id}" + parent_id = "${aws_api_gateway_rest_api.test.root_resource_id}" + path_part = "test" +} + +resource "aws_api_gateway_method" "test" { + rest_api_id = "${aws_api_gateway_rest_api.test.id}" + resource_id = "${aws_api_gateway_resource.test.id}" + http_method = "GET" + authorization = "NONE" + + request_models = { + "application/json" = "Error" + } +} + +resource "aws_api_gateway_integration" "test" { + rest_api_id = "${aws_api_gateway_rest_api.test.id}" + resource_id = "${aws_api_gateway_resource.test.id}" + http_method = "${aws_api_gateway_method.test.http_method}" + + type = "HTTP" + uri = "https://www.google.de" + integration_http_method = "GET" + passthrough_behavior = "WHEN_NO_MATCH" + content_handling = "CONVERT_TO_TEXT" } ` diff --git a/builtin/providers/aws/resource_aws_api_gateway_method_settings.go b/builtin/providers/aws/resource_aws_api_gateway_method_settings.go new file mode 100644 index 000000000..06d5efd01 --- /dev/null +++ b/builtin/providers/aws/resource_aws_api_gateway_method_settings.go @@ -0,0 +1,248 @@ +package aws + +import ( + "fmt" + "log" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/awserr" + "github.com/aws/aws-sdk-go/service/apigateway" + "github.com/hashicorp/terraform/helper/schema" +) + +func resourceAwsApiGatewayMethodSettings() *schema.Resource { + return &schema.Resource{ + Create: resourceAwsApiGatewayMethodSettingsUpdate, + Read: resourceAwsApiGatewayMethodSettingsRead, + Update: resourceAwsApiGatewayMethodSettingsUpdate, + Delete: resourceAwsApiGatewayMethodSettingsDelete, + + Schema: map[string]*schema.Schema{ + "rest_api_id": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + "stage_name": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + "method_path": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + "settings": { + Type: schema.TypeList, + Required: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "metrics_enabled": { + Type: schema.TypeBool, + Optional: true, + }, + "logging_level": { + Type: schema.TypeString, + Optional: true, + }, + "data_trace_enabled": { + Type: schema.TypeBool, + Optional: true, + }, + "throttling_burst_limit": { + Type: schema.TypeInt, + Optional: true, + }, + "throttling_rate_limit": { + Type: schema.TypeFloat, + Optional: true, + }, + "caching_enabled": { + Type: schema.TypeBool, + Optional: true, + }, + "cache_ttl_in_seconds": { + Type: schema.TypeInt, + Optional: true, + }, + "cache_data_encrypted": { + Type: schema.TypeBool, + Optional: true, + }, + "require_authorization_for_cache_control": { + Type: schema.TypeBool, + Optional: true, + }, + "unauthorized_cache_control_header_strategy": { + Type: schema.TypeString, + Optional: true, + }, + }, + }, + }, + }, + } +} + +func resourceAwsApiGatewayMethodSettingsRead(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*AWSClient).apigateway + + log.Printf("[DEBUG] Reading API Gateway Method Settings %s", d.Id()) + input := apigateway.GetStageInput{ + RestApiId: aws.String(d.Get("rest_api_id").(string)), + StageName: aws.String(d.Get("stage_name").(string)), + } + stage, err := conn.GetStage(&input) + if err != nil { + if awsErr, ok := err.(awserr.Error); ok && awsErr.Code() == "NotFoundException" { + log.Printf("[WARN] API Gateway Stage %s not found, removing method settings", d.Id()) + d.SetId("") + return nil + } + return err + } + log.Printf("[DEBUG] Received API Gateway Stage: %s", stage) + + methodPath := d.Get("method_path").(string) + settings, ok := stage.MethodSettings[methodPath] + if !ok { + log.Printf("[WARN] API Gateway Method Settings for %q not found, removing", methodPath) + d.SetId("") + return nil + } + + d.Set("settings.0.metrics_enabled", settings.MetricsEnabled) + d.Set("settings.0.logging_level", settings.LoggingLevel) + d.Set("settings.0.data_trace_enabled", settings.DataTraceEnabled) + d.Set("settings.0.throttling_burst_limit", settings.ThrottlingBurstLimit) + d.Set("settings.0.throttling_rate_limit", settings.ThrottlingRateLimit) + d.Set("settings.0.caching_enabled", settings.CachingEnabled) + d.Set("settings.0.cache_ttl_in_seconds", settings.CacheTtlInSeconds) + d.Set("settings.0.cache_data_encrypted", settings.CacheDataEncrypted) + d.Set("settings.0.require_authorization_for_cache_control", settings.RequireAuthorizationForCacheControl) + d.Set("settings.0.unauthorized_cache_control_header_strategy", settings.UnauthorizedCacheControlHeaderStrategy) + + return nil +} + +func resourceAwsApiGatewayMethodSettingsUpdate(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*AWSClient).apigateway + + methodPath := d.Get("method_path").(string) + prefix := fmt.Sprintf("/%s/", methodPath) + + ops := make([]*apigateway.PatchOperation, 0) + if d.HasChange("settings.0.metrics_enabled") { + ops = append(ops, &apigateway.PatchOperation{ + Op: aws.String("replace"), + Path: aws.String(prefix + "metrics/enabled"), + Value: aws.String(fmt.Sprintf("%t", d.Get("settings.0.metrics_enabled").(bool))), + }) + } + if d.HasChange("settings.0.logging_level") { + ops = append(ops, &apigateway.PatchOperation{ + Op: aws.String("replace"), + Path: aws.String(prefix + "logging/loglevel"), + Value: aws.String(d.Get("settings.0.logging_level").(string)), + }) + } + if d.HasChange("settings.0.data_trace_enabled") { + ops = append(ops, &apigateway.PatchOperation{ + Op: aws.String("replace"), + Path: aws.String(prefix + "logging/dataTrace"), + Value: aws.String(fmt.Sprintf("%t", d.Get("settings.0.data_trace_enabled").(bool))), + }) + } + + if d.HasChange("settings.0.throttling_burst_limit") { + ops = append(ops, &apigateway.PatchOperation{ + Op: aws.String("replace"), + Path: aws.String(prefix + "throttling/burstLimit"), + Value: aws.String(fmt.Sprintf("%d", d.Get("settings.0.throttling_burst_limit").(int))), + }) + } + if d.HasChange("settings.0.throttling_rate_limit") { + ops = append(ops, &apigateway.PatchOperation{ + Op: aws.String("replace"), + Path: aws.String(prefix + "throttling/rateLimit"), + Value: aws.String(fmt.Sprintf("%f", d.Get("settings.0.throttling_rate_limit").(float64))), + }) + } + if d.HasChange("settings.0.caching_enabled") { + ops = append(ops, &apigateway.PatchOperation{ + Op: aws.String("replace"), + Path: aws.String(prefix + "caching/enabled"), + Value: aws.String(fmt.Sprintf("%t", d.Get("settings.0.caching_enabled").(bool))), + }) + } + if d.HasChange("settings.0.cache_ttl_in_seconds") { + ops = append(ops, &apigateway.PatchOperation{ + Op: aws.String("replace"), + Path: aws.String(prefix + "caching/ttlInSeconds"), + Value: aws.String(fmt.Sprintf("%d", d.Get("settings.0.cache_ttl_in_seconds").(int))), + }) + } + if d.HasChange("settings.0.cache_data_encrypted") { + ops = append(ops, &apigateway.PatchOperation{ + Op: aws.String("replace"), + Path: aws.String(prefix + "caching/dataEncrypted"), + Value: aws.String(fmt.Sprintf("%d", d.Get("settings.0.cache_data_encrypted").(int))), + }) + } + if d.HasChange("settings.0.require_authorization_for_cache_control") { + ops = append(ops, &apigateway.PatchOperation{ + Op: aws.String("replace"), + Path: aws.String(prefix + "caching/requireAuthorizationForCacheControl"), + Value: aws.String(fmt.Sprintf("%t", d.Get("settings.0.require_authorization_for_cache_control").(bool))), + }) + } + if d.HasChange("settings.0.unauthorized_cache_control_header_strategy") { + ops = append(ops, &apigateway.PatchOperation{ + Op: aws.String("replace"), + Path: aws.String(prefix + "caching/unauthorizedCacheControlHeaderStrategy"), + Value: aws.String(d.Get("settings.0.unauthorized_cache_control_header_strategy").(string)), + }) + } + + restApiId := d.Get("rest_api_id").(string) + stageName := d.Get("stage_name").(string) + input := apigateway.UpdateStageInput{ + RestApiId: aws.String(restApiId), + StageName: aws.String(stageName), + PatchOperations: ops, + } + log.Printf("[DEBUG] Updating API Gateway Stage: %s", input) + _, err := conn.UpdateStage(&input) + if err != nil { + return fmt.Errorf("Updating API Gateway Stage failed: %s", err) + } + + d.SetId(restApiId + "-" + stageName + "-" + methodPath) + + return resourceAwsApiGatewayMethodSettingsRead(d, meta) +} + +func resourceAwsApiGatewayMethodSettingsDelete(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*AWSClient).apigateway + log.Printf("[DEBUG] Deleting API Gateway Method Settings: %s", d.Id()) + + input := apigateway.UpdateStageInput{ + RestApiId: aws.String(d.Get("rest_api_id").(string)), + StageName: aws.String(d.Get("stage_name").(string)), + PatchOperations: []*apigateway.PatchOperation{ + { + Op: aws.String("remove"), + Path: aws.String(fmt.Sprintf("/%s", d.Get("method_path").(string))), + }, + }, + } + log.Printf("[DEBUG] Updating API Gateway Stage: %s", input) + _, err := conn.UpdateStage(&input) + if err != nil { + return fmt.Errorf("Updating API Gateway Stage failed: %s", err) + } + + return nil +} diff --git a/builtin/providers/aws/resource_aws_api_gateway_method_settings_test.go b/builtin/providers/aws/resource_aws_api_gateway_method_settings_test.go new file mode 100644 index 000000000..9372a6748 --- /dev/null +++ b/builtin/providers/aws/resource_aws_api_gateway_method_settings_test.go @@ -0,0 +1,265 @@ +package aws + +import ( + "fmt" + "testing" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/awserr" + "github.com/aws/aws-sdk-go/service/apigateway" + "github.com/hashicorp/terraform/helper/acctest" + "github.com/hashicorp/terraform/helper/resource" + "github.com/hashicorp/terraform/terraform" +) + +func TestAccAWSAPIGatewayMethodSettings_basic(t *testing.T) { + var stage apigateway.Stage + rInt := acctest.RandInt() + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSAPIGatewayMethodSettingsDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAWSAPIGatewayMethodSettingsConfig(rInt), + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSAPIGatewayMethodSettingsExists("aws_api_gateway_method_settings.test", &stage), + testAccCheckAWSAPIGatewayMethodSettings_metricsEnabled(&stage, "test/GET", true), + testAccCheckAWSAPIGatewayMethodSettings_loggingLevel(&stage, "test/GET", "INFO"), + resource.TestCheckResourceAttr("aws_api_gateway_method_settings.test", "settings.#", "1"), + resource.TestCheckResourceAttr("aws_api_gateway_method_settings.test", "settings.0.metrics_enabled", "true"), + resource.TestCheckResourceAttr("aws_api_gateway_method_settings.test", "settings.0.logging_level", "INFO"), + ), + }, + + { + Config: testAccAWSAPIGatewayMethodSettingsConfigUpdate(rInt), + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSAPIGatewayMethodSettingsExists("aws_api_gateway_method_settings.test", &stage), + testAccCheckAWSAPIGatewayMethodSettings_metricsEnabled(&stage, "test/GET", false), + testAccCheckAWSAPIGatewayMethodSettings_loggingLevel(&stage, "test/GET", "OFF"), + resource.TestCheckResourceAttr("aws_api_gateway_method_settings.test", "settings.#", "1"), + resource.TestCheckResourceAttr("aws_api_gateway_method_settings.test", "settings.0.metrics_enabled", "false"), + resource.TestCheckResourceAttr("aws_api_gateway_method_settings.test", "settings.0.logging_level", "OFF"), + ), + }, + }, + }) +} + +func testAccCheckAWSAPIGatewayMethodSettings_metricsEnabled(conf *apigateway.Stage, path string, expected bool) resource.TestCheckFunc { + return func(s *terraform.State) error { + settings, ok := conf.MethodSettings[path] + if !ok { + return fmt.Errorf("Expected to find method settings for %q", path) + } + + if expected && *settings.MetricsEnabled != expected { + return fmt.Errorf("Expected metrics to be enabled, got %t", *settings.MetricsEnabled) + } + if !expected && *settings.MetricsEnabled != expected { + return fmt.Errorf("Expected metrics to be disabled, got %t", *settings.MetricsEnabled) + } + + return nil + } +} + +func testAccCheckAWSAPIGatewayMethodSettings_loggingLevel(conf *apigateway.Stage, path string, expectedLevel string) resource.TestCheckFunc { + return func(s *terraform.State) error { + settings, ok := conf.MethodSettings[path] + if !ok { + return fmt.Errorf("Expected to find method settings for %q", path) + } + + if *settings.LoggingLevel != expectedLevel { + return fmt.Errorf("Expected logging level to match %q, got %q", expectedLevel, *settings.LoggingLevel) + } + + return nil + } +} + +func testAccCheckAWSAPIGatewayMethodSettingsExists(n string, res *apigateway.Stage) resource.TestCheckFunc { + return func(s *terraform.State) error { + rs, ok := s.RootModule().Resources[n] + if !ok { + return fmt.Errorf("Not found: %s", n) + } + + if rs.Primary.ID == "" { + return fmt.Errorf("No API Gateway Stage ID is set") + } + + conn := testAccProvider.Meta().(*AWSClient).apigateway + + req := &apigateway.GetStageInput{ + StageName: aws.String(s.RootModule().Resources["aws_api_gateway_deployment.test"].Primary.Attributes["stage_name"]), + RestApiId: aws.String(s.RootModule().Resources["aws_api_gateway_rest_api.test"].Primary.ID), + } + out, err := conn.GetStage(req) + if err != nil { + return err + } + + *res = *out + + return nil + } +} + +func testAccCheckAWSAPIGatewayMethodSettingsDestroy(s *terraform.State) error { + conn := testAccProvider.Meta().(*AWSClient).apigateway + + for _, rs := range s.RootModule().Resources { + if rs.Type != "aws_api_gateway_method_settings" { + continue + } + + req := &apigateway.GetStageInput{ + StageName: aws.String(s.RootModule().Resources["aws_api_gateway_deployment.test"].Primary.Attributes["stage_name"]), + RestApiId: aws.String(s.RootModule().Resources["aws_api_gateway_rest_api.test"].Primary.ID), + } + out, err := conn.GetStage(req) + if err == nil { + return fmt.Errorf("API Gateway Stage still exists: %s", out) + } + + awsErr, ok := err.(awserr.Error) + if !ok { + return err + } + if awsErr.Code() != "NotFoundException" { + return err + } + + return nil + } + + return nil +} + +func testAccAWSAPIGatewayMethodSettingsConfig(rInt int) string { + return fmt.Sprintf(` +resource "aws_api_gateway_rest_api" "test" { + name = "tf-acc-test-apig-method-%d" +} + +resource "aws_api_gateway_resource" "test" { + rest_api_id = "${aws_api_gateway_rest_api.test.id}" + parent_id = "${aws_api_gateway_rest_api.test.root_resource_id}" + path_part = "test" +} + +resource "aws_api_gateway_method" "test" { + rest_api_id = "${aws_api_gateway_rest_api.test.id}" + resource_id = "${aws_api_gateway_resource.test.id}" + http_method = "GET" + authorization = "NONE" + + request_models = { + "application/json" = "Error" + } + + request_parameters = { + "method.request.header.Content-Type" = false, + "method.request.querystring.page" = true + } +} + +resource "aws_api_gateway_integration" "test" { + rest_api_id = "${aws_api_gateway_rest_api.test.id}" + resource_id = "${aws_api_gateway_resource.test.id}" + http_method = "${aws_api_gateway_method.test.http_method}" + type = "MOCK" + + request_templates { + "application/xml" = < 0 { + recentStatus = fmt.Sprintf("%s", resp.Activities[0]) + } else { + recentStatus = "(0 activities found)" + } + } else { + recentStatus = fmt.Sprintf("(Failed to describe scaling activities: %s)", aErr) + } + + msg := fmt.Sprintf("{{err}}. Most recent activity: %s", recentStatus) + return errwrap.Wrapf(msg, err) } type capacitySatisfiedFunc func(*schema.ResourceData, int, int) (bool, string) diff --git a/builtin/providers/aws/resource_aws_autoscaling_lifecycle_hook_test.go b/builtin/providers/aws/resource_aws_autoscaling_lifecycle_hook_test.go index 7fece49a2..580c2ed55 100644 --- a/builtin/providers/aws/resource_aws_autoscaling_lifecycle_hook_test.go +++ b/builtin/providers/aws/resource_aws_autoscaling_lifecycle_hook_test.go @@ -202,7 +202,7 @@ resource "aws_launch_configuration" "foobar" { } resource "aws_sqs_queue" "foobar" { - name = "foobar" + name = "foobar-%d" delay_seconds = 90 max_message_size = 2048 message_retention_seconds = 86400 @@ -225,7 +225,7 @@ EOF } resource "aws_iam_role_policy" "foobar" { - name = "foobar" + name = "foobar-%d" role = "${aws_iam_role.foobar.id}" policy = < 0 { action.RunOrder = aws.Int64(int64(ro)) @@ -372,6 +378,10 @@ func flattenAwsCodePipelineStageActions(actions []*codepipeline.ActionDeclaratio values["input_artifacts"] = flattenAwsCodePipelineActionsInputArtifacts(action.InputArtifacts) } + if action.RoleArn != nil { + values["role_arn"] = *action.RoleArn + } + if action.RunOrder != nil { values["run_order"] = int(*action.RunOrder) } @@ -441,6 +451,12 @@ func resourceAwsCodePipelineRead(d *schema.ResourceData, meta interface{}) error }) if err != nil { + pipelineerr, ok := err.(awserr.Error) + if ok && pipelineerr.Code() == "PipelineNotFoundException" { + log.Printf("[INFO] Codepipeline %q not found", d.Id()) + d.SetId("") + return nil + } return fmt.Errorf("[ERROR] Error retreiving Pipeline: %q", err) } pipeline := resp.Pipeline diff --git a/builtin/providers/aws/resource_aws_codepipeline_test.go b/builtin/providers/aws/resource_aws_codepipeline_test.go index e9b068435..a377f5ac7 100644 --- a/builtin/providers/aws/resource_aws_codepipeline_test.go +++ b/builtin/providers/aws/resource_aws_codepipeline_test.go @@ -3,6 +3,7 @@ package aws import ( "fmt" "os" + "regexp" "testing" "github.com/aws/aws-sdk-go/aws" @@ -46,6 +47,33 @@ func TestAccAWSCodePipeline_basic(t *testing.T) { }) } +func TestAccAWSCodePipeline_deployWithServiceRole(t *testing.T) { + if os.Getenv("GITHUB_TOKEN") == "" { + t.Skip("Environment variable GITHUB_TOKEN is not set") + } + + name := acctest.RandString(10) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSCodePipelineDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAWSCodePipelineConfig_deployWithServiceRole(name), + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSCodePipelineExists("aws_codepipeline.bar"), + resource.TestCheckResourceAttr("aws_codepipeline.bar", "stage.2.name", "Deploy"), + resource.TestCheckResourceAttr("aws_codepipeline.bar", "stage.2.action.0.category", "Deploy"), + resource.TestMatchResourceAttr( + "aws_codepipeline.bar", "stage.2.action.0.role_arn", + regexp.MustCompile("^arn:aws:iam::[0-9]{12}:role/codepipeline-action-role.*")), + ), + }, + }, + }) +} + func testAccCheckAWSCodePipelineExists(n string) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[n] @@ -314,3 +342,189 @@ resource "aws_codepipeline" "bar" { } `, rName, rName, rName) } + +func testAccAWSCodePipelineConfig_deployWithServiceRole(rName string) string { + return fmt.Sprintf(` +resource "aws_s3_bucket" "foo" { + bucket = "tf-test-pipeline-%s" + acl = "private" +} + +resource "aws_iam_role" "codepipeline_role" { + name = "codepipeline-role-%s" + + assume_role_policy = < 255 { - errors = append(errors, fmt.Errorf( - "%q cannot be greater than 255 characters", k)) - } - return -} diff --git a/builtin/providers/aws/resource_aws_db_option_group_test.go b/builtin/providers/aws/resource_aws_db_option_group_test.go index 5a3215b04..8e9b22e1b 100644 --- a/builtin/providers/aws/resource_aws_db_option_group_test.go +++ b/builtin/providers/aws/resource_aws_db_option_group_test.go @@ -2,6 +2,7 @@ package aws import ( "fmt" + "regexp" "testing" "github.com/aws/aws-sdk-go/aws" @@ -34,6 +35,66 @@ func TestAccAWSDBOptionGroup_basic(t *testing.T) { }) } +func TestAccAWSDBOptionGroup_namePrefix(t *testing.T) { + var v rds.OptionGroup + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSDBOptionGroupDestroy, + Steps: []resource.TestStep{ + resource.TestStep{ + Config: testAccAWSDBOptionGroup_namePrefix, + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSDBOptionGroupExists("aws_db_option_group.test", &v), + testAccCheckAWSDBOptionGroupAttributes(&v), + resource.TestMatchResourceAttr( + "aws_db_option_group.test", "name", regexp.MustCompile("^tf-test-")), + ), + }, + }, + }) +} + +func TestAccAWSDBOptionGroup_generatedName(t *testing.T) { + var v rds.OptionGroup + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSDBOptionGroupDestroy, + Steps: []resource.TestStep{ + resource.TestStep{ + Config: testAccAWSDBOptionGroup_generatedName, + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSDBOptionGroupExists("aws_db_option_group.test", &v), + testAccCheckAWSDBOptionGroupAttributes(&v), + ), + }, + }, + }) +} + +func TestAccAWSDBOptionGroup_defaultDescription(t *testing.T) { + var v rds.OptionGroup + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSDBOptionGroupDestroy, + Steps: []resource.TestStep{ + resource.TestStep{ + Config: testAccAWSDBOptionGroup_defaultDescription(acctest.RandInt()), + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSDBOptionGroupExists("aws_db_option_group.test", &v), + resource.TestCheckResourceAttr( + "aws_db_option_group.test", "option_group_description", "Managed by Terraform"), + ), + }, + }, + }) +} + func TestAccAWSDBOptionGroup_basicDestroyWithInstance(t *testing.T) { rName := fmt.Sprintf("option-group-test-terraform-%s", acctest.RandString(5)) @@ -160,42 +221,6 @@ func testAccCheckAWSDBOptionGroupAttributes(v *rds.OptionGroup) resource.TestChe } } -func TestResourceAWSDBOptionGroupName_validation(t *testing.T) { - cases := []struct { - Value string - ErrCount int - }{ - { - Value: "testing123!", - ErrCount: 1, - }, - { - Value: "1testing123", - ErrCount: 1, - }, - { - Value: "testing--123", - ErrCount: 1, - }, - { - Value: "testing123-", - ErrCount: 1, - }, - { - Value: randomString(256), - ErrCount: 1, - }, - } - - for _, tc := range cases { - _, errors := validateDbOptionGroupName(tc.Value, "aws_db_option_group_name") - - if len(errors) != tc.ErrCount { - t.Fatalf("Expected the DB Option Group Name to trigger a validation error") - } - } -} - func testAccCheckAWSDBOptionGroupExists(n string, v *rds.OptionGroup) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[n] @@ -292,6 +317,7 @@ resource "aws_db_instance" "bar" { maintenance_window = "Fri:09:00-Fri:09:30" backup_retention_period = 0 + skip_final_snapshot = true option_group_name = "${aws_db_option_group.bar.name}" } @@ -387,3 +413,30 @@ resource "aws_db_option_group" "bar" { } `, r) } + +const testAccAWSDBOptionGroup_namePrefix = ` +resource "aws_db_option_group" "test" { + name_prefix = "tf-test-" + option_group_description = "Test option group for terraform" + engine_name = "mysql" + major_engine_version = "5.6" +} +` + +const testAccAWSDBOptionGroup_generatedName = ` +resource "aws_db_option_group" "test" { + option_group_description = "Test option group for terraform" + engine_name = "mysql" + major_engine_version = "5.6" +} +` + +func testAccAWSDBOptionGroup_defaultDescription(n int) string { + return fmt.Sprintf(` +resource "aws_db_option_group" "test" { + name = "tf-test-%d" + engine_name = "mysql" + major_engine_version = "5.6" +} +`, n) +} diff --git a/builtin/providers/aws/resource_aws_db_parameter_group.go b/builtin/providers/aws/resource_aws_db_parameter_group.go index b18282712..4e2611ff7 100644 --- a/builtin/providers/aws/resource_aws_db_parameter_group.go +++ b/builtin/providers/aws/resource_aws_db_parameter_group.go @@ -32,10 +32,19 @@ func resourceAwsDbParameterGroup() *schema.Resource { Computed: true, }, "name": &schema.Schema{ + Type: schema.TypeString, + Optional: true, + Computed: true, + ForceNew: true, + ConflictsWith: []string{"name_prefix"}, + ValidateFunc: validateDbParamGroupName, + }, + "name_prefix": &schema.Schema{ Type: schema.TypeString, + Optional: true, + Computed: true, ForceNew: true, - Required: true, - ValidateFunc: validateDbParamGroupName, + ValidateFunc: validateDbParamGroupNamePrefix, }, "family": &schema.Schema{ Type: schema.TypeString, @@ -81,8 +90,18 @@ func resourceAwsDbParameterGroupCreate(d *schema.ResourceData, meta interface{}) rdsconn := meta.(*AWSClient).rdsconn tags := tagsFromMapRDS(d.Get("tags").(map[string]interface{})) + var groupName string + if v, ok := d.GetOk("name"); ok { + groupName = v.(string) + } else if v, ok := d.GetOk("name_prefix"); ok { + groupName = resource.PrefixedUniqueId(v.(string)) + } else { + groupName = resource.UniqueId() + } + d.Set("name", groupName) + createOpts := rds.CreateDBParameterGroupInput{ - DBParameterGroupName: aws.String(d.Get("name").(string)), + DBParameterGroupName: aws.String(groupName), DBParameterGroupFamily: aws.String(d.Get("family").(string)), Description: aws.String(d.Get("description").(string)), Tags: tags, diff --git a/builtin/providers/aws/resource_aws_db_parameter_group_test.go b/builtin/providers/aws/resource_aws_db_parameter_group_test.go index 75db4f77d..1d330bfc7 100644 --- a/builtin/providers/aws/resource_aws_db_parameter_group_test.go +++ b/builtin/providers/aws/resource_aws_db_parameter_group_test.go @@ -3,6 +3,7 @@ package aws import ( "fmt" "math/rand" + "regexp" "testing" "time" @@ -290,6 +291,44 @@ func TestAccAWSDBParameterGroup_basic(t *testing.T) { }) } +func TestAccAWSDBParameterGroup_namePrefix(t *testing.T) { + var v rds.DBParameterGroup + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSDBParameterGroupDestroy, + Steps: []resource.TestStep{ + resource.TestStep{ + Config: testAccDBParameterGroupConfig_namePrefix, + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSDBParameterGroupExists("aws_db_parameter_group.test", &v), + resource.TestMatchResourceAttr( + "aws_db_parameter_group.test", "name", regexp.MustCompile("^tf-test-")), + ), + }, + }, + }) +} + +func TestAccAWSDBParameterGroup_generatedName(t *testing.T) { + var v rds.DBParameterGroup + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSDBParameterGroupDestroy, + Steps: []resource.TestStep{ + resource.TestStep{ + Config: testAccDBParameterGroupConfig_generatedName, + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSDBParameterGroupExists("aws_db_parameter_group.test", &v), + ), + }, + }, + }) +} + func TestAccAWSDBParameterGroup_withApplyMethod(t *testing.T) { var v rds.DBParameterGroup @@ -671,3 +710,26 @@ resource "aws_db_parameter_group" "large" { parameter { name = "tx_isolation" value = "REPEATABLE-READ" } }`, n) } + +const testAccDBParameterGroupConfig_namePrefix = ` +resource "aws_db_parameter_group" "test" { + name_prefix = "tf-test-" + family = "mysql5.6" + + parameter { + name = "sync_binlog" + value = 0 + } +} +` + +const testAccDBParameterGroupConfig_generatedName = ` +resource "aws_db_parameter_group" "test" { + family = "mysql5.6" + + parameter { + name = "sync_binlog" + value = 0 + } +} +` diff --git a/builtin/providers/aws/resource_aws_db_snapshot.go b/builtin/providers/aws/resource_aws_db_snapshot.go new file mode 100644 index 000000000..f2ab24c4a --- /dev/null +++ b/builtin/providers/aws/resource_aws_db_snapshot.go @@ -0,0 +1,216 @@ +package aws + +import ( + "fmt" + "log" + "time" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/awserr" + "github.com/aws/aws-sdk-go/service/rds" + "github.com/hashicorp/terraform/helper/resource" + "github.com/hashicorp/terraform/helper/schema" +) + +func resourceAwsDbSnapshot() *schema.Resource { + return &schema.Resource{ + Create: resourceAwsDbSnapshotCreate, + Read: resourceAwsDbSnapshotRead, + Delete: resourceAwsDbSnapshotDelete, + + Timeouts: &schema.ResourceTimeout{ + Read: schema.DefaultTimeout(10 * time.Minute), + }, + + Schema: map[string]*schema.Schema{ + "db_snapshot_identifier": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + "db_instance_identifier": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + + "allocated_storage": { + Type: schema.TypeInt, + Computed: true, + }, + "availability_zone": { + Type: schema.TypeString, + Computed: true, + }, + "db_snapshot_arn": { + Type: schema.TypeString, + Computed: true, + }, + "encrypted": { + Type: schema.TypeBool, + Computed: true, + }, + "engine": { + Type: schema.TypeString, + Computed: true, + }, + "engine_version": { + Type: schema.TypeString, + Computed: true, + }, + "iops": { + Type: schema.TypeInt, + Computed: true, + }, + "kms_key_id": { + Type: schema.TypeString, + Computed: true, + }, + "license_model": { + Type: schema.TypeString, + Computed: true, + }, + "option_group_name": { + Type: schema.TypeString, + Computed: true, + }, + "port": { + Type: schema.TypeInt, + Computed: true, + }, + "source_db_snapshot_identifier": { + Type: schema.TypeString, + Computed: true, + }, + "source_region": { + Type: schema.TypeString, + Computed: true, + }, + "snapshot_type": { + Type: schema.TypeString, + Computed: true, + }, + "status": { + Type: schema.TypeString, + Computed: true, + }, + "storage_type": { + Type: schema.TypeString, + Computed: true, + }, + "vpc_id": { + Type: schema.TypeString, + Computed: true, + }, + }, + } +} + +func resourceAwsDbSnapshotCreate(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*AWSClient).rdsconn + + params := &rds.CreateDBSnapshotInput{ + DBInstanceIdentifier: aws.String(d.Get("db_instance_identifier").(string)), + DBSnapshotIdentifier: aws.String(d.Get("db_snapshot_identifier").(string)), + } + + _, err := conn.CreateDBSnapshot(params) + if err != nil { + return err + } + d.SetId(d.Get("db_snapshot_identifier").(string)) + + stateConf := &resource.StateChangeConf{ + Pending: []string{"creating"}, + Target: []string{"available"}, + Refresh: resourceAwsDbSnapshotStateRefreshFunc(d, meta), + Timeout: d.Timeout(schema.TimeoutRead), + MinTimeout: 10 * time.Second, + Delay: 30 * time.Second, // Wait 30 secs before starting + } + + // Wait, catching any errors + _, err = stateConf.WaitForState() + if err != nil { + return err + } + + return resourceAwsDbSnapshotRead(d, meta) +} + +func resourceAwsDbSnapshotRead(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*AWSClient).rdsconn + + params := &rds.DescribeDBSnapshotsInput{ + DBSnapshotIdentifier: aws.String(d.Id()), + } + resp, err := conn.DescribeDBSnapshots(params) + if err != nil { + return err + } + + snapshot := resp.DBSnapshots[0] + + d.Set("allocated_storage", snapshot.AllocatedStorage) + d.Set("availability_zone", snapshot.AvailabilityZone) + d.Set("db_snapshot_arn", snapshot.DBSnapshotArn) + d.Set("encrypted", snapshot.Encrypted) + d.Set("engine", snapshot.Engine) + d.Set("engine_version", snapshot.EngineVersion) + d.Set("iops", snapshot.Iops) + d.Set("kms_key_id", snapshot.KmsKeyId) + d.Set("license_model", snapshot.LicenseModel) + d.Set("option_group_name", snapshot.OptionGroupName) + d.Set("port", snapshot.Port) + d.Set("source_db_snapshot_identifier", snapshot.SourceDBSnapshotIdentifier) + d.Set("source_region", snapshot.SourceRegion) + d.Set("snapshot_type", snapshot.SnapshotType) + d.Set("status", snapshot.Status) + d.Set("vpc_id", snapshot.VpcId) + + return nil +} + +func resourceAwsDbSnapshotDelete(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*AWSClient).rdsconn + + params := &rds.DeleteDBSnapshotInput{ + DBSnapshotIdentifier: aws.String(d.Id()), + } + _, err := conn.DeleteDBSnapshot(params) + if err != nil { + return err + } + + return nil +} + +func resourceAwsDbSnapshotStateRefreshFunc( + d *schema.ResourceData, meta interface{}) resource.StateRefreshFunc { + return func() (interface{}, string, error) { + conn := meta.(*AWSClient).rdsconn + + opts := &rds.DescribeDBSnapshotsInput{ + DBSnapshotIdentifier: aws.String(d.Id()), + } + + log.Printf("[DEBUG] DB Snapshot describe configuration: %#v", opts) + + resp, err := conn.DescribeDBSnapshots(opts) + if err != nil { + snapshoterr, ok := err.(awserr.Error) + if ok && snapshoterr.Code() == "DBSnapshotNotFound" { + return nil, "", nil + } + return nil, "", fmt.Errorf("Error retrieving DB Snapshots: %s", err) + } + + if len(resp.DBSnapshots) != 1 { + return nil, "", fmt.Errorf("No snapshots returned for %s", d.Id()) + } + + snapshot := resp.DBSnapshots[0] + + return resp, *snapshot.Status, nil + } +} diff --git a/builtin/providers/aws/resource_aws_db_snapshot_test.go b/builtin/providers/aws/resource_aws_db_snapshot_test.go new file mode 100644 index 000000000..2b33a2389 --- /dev/null +++ b/builtin/providers/aws/resource_aws_db_snapshot_test.go @@ -0,0 +1,83 @@ +package aws + +import ( + "fmt" + "testing" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/service/rds" + "github.com/hashicorp/terraform/helper/acctest" + "github.com/hashicorp/terraform/helper/resource" + "github.com/hashicorp/terraform/terraform" +) + +func TestAccAWSDBSnapshot_basic(t *testing.T) { + var v rds.DBSnapshot + rInt := acctest.RandInt() + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + Steps: []resource.TestStep{ + { + Config: testAccAwsDbSnapshotConfig(rInt), + Check: resource.ComposeTestCheckFunc( + testAccCheckDbSnapshotExists("aws_db_snapshot.test", &v), + ), + }, + }, + }) +} + +func testAccCheckDbSnapshotExists(n string, v *rds.DBSnapshot) resource.TestCheckFunc { + return func(s *terraform.State) error { + rs, ok := s.RootModule().Resources[n] + if !ok { + return fmt.Errorf("Not found: %s", n) + } + + if rs.Primary.ID == "" { + return fmt.Errorf("No ID is set") + } + + conn := testAccProvider.Meta().(*AWSClient).rdsconn + + request := &rds.DescribeDBSnapshotsInput{ + DBSnapshotIdentifier: aws.String(rs.Primary.ID), + } + + response, err := conn.DescribeDBSnapshots(request) + if err == nil { + if response.DBSnapshots != nil && len(response.DBSnapshots) > 0 { + *v = *response.DBSnapshots[0] + return nil + } + } + return fmt.Errorf("Error finding RDS DB Snapshot %s", rs.Primary.ID) + } +} + +func testAccAwsDbSnapshotConfig(rInt int) string { + return fmt.Sprintf(` +resource "aws_db_instance" "bar" { + allocated_storage = 10 + engine = "MySQL" + engine_version = "5.6.21" + instance_class = "db.t1.micro" + name = "baz" + password = "barbarbarbar" + username = "foo" + + maintenance_window = "Fri:09:00-Fri:09:30" + + backup_retention_period = 0 + + parameter_group_name = "default.mysql5.6" + + skip_final_snapshot = true +} + +resource "aws_db_snapshot" "test" { + db_instance_identifier = "${aws_db_instance.bar.id}" + db_snapshot_identifier = "testsnapshot%d" +}`, rInt) +} diff --git a/builtin/providers/aws/resource_aws_db_subnet_group.go b/builtin/providers/aws/resource_aws_db_subnet_group.go index 9c1c56199..c4e437bee 100644 --- a/builtin/providers/aws/resource_aws_db_subnet_group.go +++ b/builtin/providers/aws/resource_aws_db_subnet_group.go @@ -3,7 +3,6 @@ package aws import ( "fmt" "log" - "regexp" "strings" "time" @@ -31,10 +30,19 @@ func resourceAwsDbSubnetGroup() *schema.Resource { }, "name": &schema.Schema{ + Type: schema.TypeString, + Optional: true, + Computed: true, + ForceNew: true, + ConflictsWith: []string{"name_prefix"}, + ValidateFunc: validateDbSubnetGroupName, + }, + "name_prefix": &schema.Schema{ Type: schema.TypeString, + Optional: true, + Computed: true, ForceNew: true, - Required: true, - ValidateFunc: validateSubnetGroupName, + ValidateFunc: validateDbSubnetGroupNamePrefix, }, "description": &schema.Schema{ @@ -65,8 +73,17 @@ func resourceAwsDbSubnetGroupCreate(d *schema.ResourceData, meta interface{}) er subnetIds[i] = aws.String(subnetId.(string)) } + var groupName string + if v, ok := d.GetOk("name"); ok { + groupName = v.(string) + } else if v, ok := d.GetOk("name_prefix"); ok { + groupName = resource.PrefixedUniqueId(v.(string)) + } else { + groupName = resource.UniqueId() + } + createOpts := rds.CreateDBSubnetGroupInput{ - DBSubnetGroupName: aws.String(d.Get("name").(string)), + DBSubnetGroupName: aws.String(groupName), DBSubnetGroupDescription: aws.String(d.Get("description").(string)), SubnetIds: subnetIds, Tags: tags, @@ -238,20 +255,3 @@ func buildRDSsubgrpARN(identifier, partition, accountid, region string) (string, return arn, nil } - -func validateSubnetGroupName(v interface{}, k string) (ws []string, errors []error) { - value := v.(string) - if !regexp.MustCompile(`^[ .0-9a-z-_]+$`).MatchString(value) { - errors = append(errors, fmt.Errorf( - "only lowercase alphanumeric characters, hyphens, underscores, periods, and spaces allowed in %q", k)) - } - if len(value) > 255 { - errors = append(errors, fmt.Errorf( - "%q cannot be longer than 255 characters", k)) - } - if regexp.MustCompile(`(?i)^default$`).MatchString(value) { - errors = append(errors, fmt.Errorf( - "%q is not allowed as %q", "Default", k)) - } - return -} diff --git a/builtin/providers/aws/resource_aws_db_subnet_group_test.go b/builtin/providers/aws/resource_aws_db_subnet_group_test.go index 434ae1728..70d27c5db 100644 --- a/builtin/providers/aws/resource_aws_db_subnet_group_test.go +++ b/builtin/providers/aws/resource_aws_db_subnet_group_test.go @@ -2,6 +2,7 @@ package aws import ( "fmt" + "regexp" "testing" "github.com/hashicorp/terraform/helper/acctest" @@ -43,6 +44,46 @@ func TestAccAWSDBSubnetGroup_basic(t *testing.T) { }) } +func TestAccAWSDBSubnetGroup_namePrefix(t *testing.T) { + var v rds.DBSubnetGroup + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckDBSubnetGroupDestroy, + Steps: []resource.TestStep{ + resource.TestStep{ + Config: testAccDBSubnetGroupConfig_namePrefix, + Check: resource.ComposeTestCheckFunc( + testAccCheckDBSubnetGroupExists( + "aws_db_subnet_group.test", &v), + resource.TestMatchResourceAttr( + "aws_db_subnet_group.test", "name", regexp.MustCompile("^tf_test-")), + ), + }, + }, + }) +} + +func TestAccAWSDBSubnetGroup_generatedName(t *testing.T) { + var v rds.DBSubnetGroup + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckDBSubnetGroupDestroy, + Steps: []resource.TestStep{ + resource.TestStep{ + Config: testAccDBSubnetGroupConfig_generatedName, + Check: resource.ComposeTestCheckFunc( + testAccCheckDBSubnetGroupExists( + "aws_db_subnet_group.test", &v), + ), + }, + }, + }) +} + // Regression test for https://github.com/hashicorp/terraform/issues/2603 and // https://github.com/hashicorp/terraform/issues/2664 func TestAccAWSDBSubnetGroup_withUndocumentedCharacters(t *testing.T) { @@ -105,38 +146,6 @@ func TestAccAWSDBSubnetGroup_updateDescription(t *testing.T) { }) } -func TestResourceAWSDBSubnetGroupNameValidation(t *testing.T) { - cases := []struct { - Value string - ErrCount int - }{ - { - Value: "tEsting", - ErrCount: 1, - }, - { - Value: "testing?", - ErrCount: 1, - }, - { - Value: "default", - ErrCount: 1, - }, - { - Value: randomString(300), - ErrCount: 1, - }, - } - - for _, tc := range cases { - _, errors := validateSubnetGroupName(tc.Value, "aws_db_subnet_group") - - if len(errors) != tc.ErrCount { - t.Fatalf("Expected the DB Subnet Group name to trigger a validation error") - } - } -} - func testAccCheckDBSubnetGroupDestroy(s *terraform.State) error { conn := testAccProvider.Meta().(*AWSClient).rdsconn @@ -263,6 +272,49 @@ resource "aws_db_subnet_group" "foo" { }`, rName) } +const testAccDBSubnetGroupConfig_namePrefix = ` +resource "aws_vpc" "test" { + cidr_block = "10.1.0.0/16" +} + +resource "aws_subnet" "a" { + vpc_id = "${aws_vpc.test.id}" + cidr_block = "10.1.1.0/24" + availability_zone = "us-west-2a" +} + +resource "aws_subnet" "b" { + vpc_id = "${aws_vpc.test.id}" + cidr_block = "10.1.2.0/24" + availability_zone = "us-west-2b" +} + +resource "aws_db_subnet_group" "test" { + name_prefix = "tf_test-" + subnet_ids = ["${aws_subnet.a.id}", "${aws_subnet.b.id}"] +}` + +const testAccDBSubnetGroupConfig_generatedName = ` +resource "aws_vpc" "test" { + cidr_block = "10.1.0.0/16" +} + +resource "aws_subnet" "a" { + vpc_id = "${aws_vpc.test.id}" + cidr_block = "10.1.1.0/24" + availability_zone = "us-west-2a" +} + +resource "aws_subnet" "b" { + vpc_id = "${aws_vpc.test.id}" + cidr_block = "10.1.2.0/24" + availability_zone = "us-west-2b" +} + +resource "aws_db_subnet_group" "test" { + subnet_ids = ["${aws_subnet.a.id}", "${aws_subnet.b.id}"] +}` + const testAccDBSubnetGroupConfig_withUnderscoresAndPeriodsAndSpaces = ` resource "aws_vpc" "main" { cidr_block = "192.168.0.0/16" diff --git a/builtin/providers/aws/resource_aws_default_subnet.go b/builtin/providers/aws/resource_aws_default_subnet.go new file mode 100644 index 000000000..fc10723db --- /dev/null +++ b/builtin/providers/aws/resource_aws_default_subnet.go @@ -0,0 +1,85 @@ +package aws + +import ( + "fmt" + "log" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/service/ec2" + "github.com/hashicorp/terraform/helper/schema" +) + +func resourceAwsDefaultSubnet() *schema.Resource { + // reuse aws_subnet schema, and methods for READ, UPDATE + dsubnet := resourceAwsSubnet() + dsubnet.Create = resourceAwsDefaultSubnetCreate + dsubnet.Delete = resourceAwsDefaultSubnetDelete + + // vpc_id is a required value for Default Subnets + dsubnet.Schema["availability_zone"] = &schema.Schema{ + Type: schema.TypeString, + Required: true, + } + // vpc_id is a computed value for Default Subnets + dsubnet.Schema["vpc_id"] = &schema.Schema{ + Type: schema.TypeString, + Computed: true, + } + // cidr_block is a computed value for Default Subnets + dsubnet.Schema["cidr_block"] = &schema.Schema{ + Type: schema.TypeString, + Computed: true, + } + // ipv6_cidr_block is a computed value for Default Subnets + dsubnet.Schema["ipv6_cidr_block"] = &schema.Schema{ + Type: schema.TypeString, + Computed: true, + } + // map_public_ip_on_launch is a computed value for Default Subnets + dsubnet.Schema["map_public_ip_on_launch"] = &schema.Schema{ + Type: schema.TypeBool, + Computed: true, + } + // assign_ipv6_address_on_creation is a computed value for Default Subnets + dsubnet.Schema["assign_ipv6_address_on_creation"] = &schema.Schema{ + Type: schema.TypeBool, + Computed: true, + } + + return dsubnet +} + +func resourceAwsDefaultSubnetCreate(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*AWSClient).ec2conn + req := &ec2.DescribeSubnetsInput{ + Filters: []*ec2.Filter{ + &ec2.Filter{ + Name: aws.String("availabilityZone"), + Values: aws.StringSlice([]string{d.Get("availability_zone").(string)}), + }, + &ec2.Filter{ + Name: aws.String("defaultForAz"), + Values: aws.StringSlice([]string{"true"}), + }, + }, + } + + resp, err := conn.DescribeSubnets(req) + if err != nil { + return err + } + + if len(resp.Subnets) != 1 || resp.Subnets[0] == nil { + return fmt.Errorf("Default subnet not found") + } + + d.SetId(aws.StringValue(resp.Subnets[0].SubnetId)) + + return resourceAwsSubnetUpdate(d, meta) +} + +func resourceAwsDefaultSubnetDelete(d *schema.ResourceData, meta interface{}) error { + log.Printf("[WARN] Cannot destroy Default Subnet. Terraform will remove this resource from the state file, however resources may remain.") + d.SetId("") + return nil +} diff --git a/builtin/providers/aws/resource_aws_default_subnet_test.go b/builtin/providers/aws/resource_aws_default_subnet_test.go new file mode 100644 index 000000000..0c12b6b94 --- /dev/null +++ b/builtin/providers/aws/resource_aws_default_subnet_test.go @@ -0,0 +1,56 @@ +// make testacc TEST=./builtin/providers/aws/ TESTARGS='-run=TestAccAWSDefaultVpc_' +package aws + +import ( + "testing" + + "github.com/aws/aws-sdk-go/service/ec2" + "github.com/hashicorp/terraform/helper/resource" + "github.com/hashicorp/terraform/terraform" +) + +func TestAccAWSDefaultSubnet_basic(t *testing.T) { + var v ec2.Subnet + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSDefaultSubnetDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAWSDefaultSubnetConfigBasic, + Check: resource.ComposeTestCheckFunc( + testAccCheckSubnetExists("aws_default_subnet.foo", &v), + resource.TestCheckResourceAttr( + "aws_default_subnet.foo", "availability_zone", "us-west-2a"), + resource.TestCheckResourceAttr( + "aws_default_subnet.foo", "map_public_ip_on_launch", "true"), + resource.TestCheckResourceAttr( + "aws_default_subnet.foo", "assign_ipv6_address_on_creation", "false"), + resource.TestCheckResourceAttr( + "aws_default_subnet.foo", "tags.%", "1"), + resource.TestCheckResourceAttr( + "aws_default_subnet.foo", "tags.Name", "Default subnet for us-west-2a"), + ), + }, + }, + }) +} + +func testAccCheckAWSDefaultSubnetDestroy(s *terraform.State) error { + // We expect subnet to still exist + return nil +} + +const testAccAWSDefaultSubnetConfigBasic = ` +provider "aws" { + region = "us-west-2" +} + +resource "aws_default_subnet" "foo" { + availability_zone = "us-west-2a" + tags { + Name = "Default subnet for us-west-2a" + } +} +` diff --git a/builtin/providers/aws/resource_aws_default_vpc_dhcp_options.go b/builtin/providers/aws/resource_aws_default_vpc_dhcp_options.go new file mode 100644 index 000000000..cb433ff4b --- /dev/null +++ b/builtin/providers/aws/resource_aws_default_vpc_dhcp_options.go @@ -0,0 +1,90 @@ +package aws + +import ( + "fmt" + "log" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/service/ec2" + "github.com/hashicorp/terraform/helper/schema" +) + +func resourceAwsDefaultVpcDhcpOptions() *schema.Resource { + // reuse aws_vpc_dhcp_options schema, and methods for READ, UPDATE + dvpc := resourceAwsVpcDhcpOptions() + dvpc.Create = resourceAwsDefaultVpcDhcpOptionsCreate + dvpc.Delete = resourceAwsDefaultVpcDhcpOptionsDelete + + // domain_name is a computed value for Default Default DHCP Options Sets + dvpc.Schema["domain_name"] = &schema.Schema{ + Type: schema.TypeString, + Computed: true, + } + // domain_name_servers is a computed value for Default Default DHCP Options Sets + dvpc.Schema["domain_name_servers"] = &schema.Schema{ + Type: schema.TypeString, + Computed: true, + } + // ntp_servers is a computed value for Default Default DHCP Options Sets + dvpc.Schema["ntp_servers"] = &schema.Schema{ + Type: schema.TypeString, + Computed: true, + } + + return dvpc +} + +func resourceAwsDefaultVpcDhcpOptionsCreate(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*AWSClient).ec2conn + + var domainName string + awsRegion := meta.(*AWSClient).region + if awsRegion == "us-east-1" { + domainName = "ec2.internal" + } else { + domainName = awsRegion + ".compute.internal" + } + req := &ec2.DescribeDhcpOptionsInput{ + Filters: []*ec2.Filter{ + &ec2.Filter{ + Name: aws.String("key"), + Values: aws.StringSlice([]string{"domain-name"}), + }, + &ec2.Filter{ + Name: aws.String("value"), + Values: aws.StringSlice([]string{domainName}), + }, + &ec2.Filter{ + Name: aws.String("key"), + Values: aws.StringSlice([]string{"domain-name-servers"}), + }, + &ec2.Filter{ + Name: aws.String("value"), + Values: aws.StringSlice([]string{"AmazonProvidedDNS"}), + }, + }, + } + + resp, err := conn.DescribeDhcpOptions(req) + if err != nil { + return err + } + + if len(resp.DhcpOptions) != 1 || resp.DhcpOptions[0] == nil { + return fmt.Errorf("Default DHCP Options Set not found") + } + + d.SetId(aws.StringValue(resp.DhcpOptions[0].DhcpOptionsId)) + + if err := resourceAwsVpcDhcpOptionsUpdate(d, meta); err != nil { + return err + } + + return resourceAwsVpcDhcpOptionsRead(d, meta) +} + +func resourceAwsDefaultVpcDhcpOptionsDelete(d *schema.ResourceData, meta interface{}) error { + log.Printf("[WARN] Cannot destroy Default DHCP Options Set. Terraform will remove this resource from the state file, however resources may remain.") + d.SetId("") + return nil +} diff --git a/builtin/providers/aws/resource_aws_default_vpc_dhcp_options_test.go b/builtin/providers/aws/resource_aws_default_vpc_dhcp_options_test.go new file mode 100644 index 000000000..8149d245f --- /dev/null +++ b/builtin/providers/aws/resource_aws_default_vpc_dhcp_options_test.go @@ -0,0 +1,53 @@ +// make testacc TEST=./builtin/providers/aws/ TESTARGS='-run=TestAccAWSDefaultVpc_' +package aws + +import ( + "testing" + + "github.com/aws/aws-sdk-go/service/ec2" + "github.com/hashicorp/terraform/helper/resource" + "github.com/hashicorp/terraform/terraform" +) + +func TestAccAWSDefaultVpcDhcpOptions_basic(t *testing.T) { + var d ec2.DhcpOptions + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSDefaultVpcDhcpOptionsDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAWSDefaultVpcDhcpOptionsConfigBasic, + Check: resource.ComposeTestCheckFunc( + testAccCheckDHCPOptionsExists("aws_default_vpc_dhcp_options.foo", &d), + resource.TestCheckResourceAttr( + "aws_default_vpc_dhcp_options.foo", "domain_name", "us-west-2.compute.internal"), + resource.TestCheckResourceAttr( + "aws_default_vpc_dhcp_options.foo", "domain_name_servers", "AmazonProvidedDNS"), + resource.TestCheckResourceAttr( + "aws_default_vpc_dhcp_options.foo", "tags.%", "1"), + resource.TestCheckResourceAttr( + "aws_default_vpc_dhcp_options.foo", "tags.Name", "Default DHCP Option Set"), + ), + }, + }, + }) +} + +func testAccCheckAWSDefaultVpcDhcpOptionsDestroy(s *terraform.State) error { + // We expect DHCP Options Set to still exist + return nil +} + +const testAccAWSDefaultVpcDhcpOptionsConfigBasic = ` +provider "aws" { + region = "us-west-2" +} + +resource "aws_default_vpc_dhcp_options" "foo" { + tags { + Name = "Default DHCP Option Set" + } +} +` diff --git a/builtin/providers/aws/resource_aws_devicefarm_project.go b/builtin/providers/aws/resource_aws_devicefarm_project.go new file mode 100644 index 000000000..e7e377eaf --- /dev/null +++ b/builtin/providers/aws/resource_aws_devicefarm_project.go @@ -0,0 +1,112 @@ +package aws + +import ( + "fmt" + "log" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/service/devicefarm" + "github.com/hashicorp/terraform/helper/schema" +) + +func resourceAwsDevicefarmProject() *schema.Resource { + return &schema.Resource{ + Create: resourceAwsDevicefarmProjectCreate, + Read: resourceAwsDevicefarmProjectRead, + Update: resourceAwsDevicefarmProjectUpdate, + Delete: resourceAwsDevicefarmProjectDelete, + + Schema: map[string]*schema.Schema{ + "arn": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + }, + + "name": &schema.Schema{ + Type: schema.TypeString, + Required: true, + }, + }, + } +} + +func resourceAwsDevicefarmProjectCreate(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*AWSClient).devicefarmconn + region := meta.(*AWSClient).region + + // We need to ensure that DeviceFarm is only being run against us-west-2 + // As this is the only place that AWS currently supports it + if region != "us-west-2" { + return fmt.Errorf("DeviceFarm can only be used with us-west-2. You are trying to use it on %s", region) + } + + input := &devicefarm.CreateProjectInput{ + Name: aws.String(d.Get("name").(string)), + } + + log.Printf("[DEBUG] Creating DeviceFarm Project: %s", d.Get("name").(string)) + out, err := conn.CreateProject(input) + if err != nil { + return fmt.Errorf("Error creating DeviceFarm Project: %s", err) + } + + log.Printf("[DEBUG] Successsfully Created DeviceFarm Project: %s", *out.Project.Arn) + d.SetId(*out.Project.Arn) + + return resourceAwsDevicefarmProjectRead(d, meta) +} + +func resourceAwsDevicefarmProjectRead(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*AWSClient).devicefarmconn + + input := &devicefarm.GetProjectInput{ + Arn: aws.String(d.Id()), + } + + log.Printf("[DEBUG] Reading DeviceFarm Project: %s", d.Id()) + out, err := conn.GetProject(input) + if err != nil { + return fmt.Errorf("Error reading DeviceFarm Project: %s", err) + } + + d.Set("name", out.Project.Name) + d.Set("arn", out.Project.Arn) + + return nil +} + +func resourceAwsDevicefarmProjectUpdate(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*AWSClient).devicefarmconn + + if d.HasChange("name") { + input := &devicefarm.UpdateProjectInput{ + Arn: aws.String(d.Id()), + Name: aws.String(d.Get("name").(string)), + } + + log.Printf("[DEBUG] Updating DeviceFarm Project: %s", d.Id()) + _, err := conn.UpdateProject(input) + if err != nil { + return fmt.Errorf("Error Updating DeviceFarm Project: %s", err) + } + + } + + return resourceAwsDevicefarmProjectRead(d, meta) +} + +func resourceAwsDevicefarmProjectDelete(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*AWSClient).devicefarmconn + + input := &devicefarm.DeleteProjectInput{ + Arn: aws.String(d.Id()), + } + + log.Printf("[DEBUG] Deleting DeviceFarm Project: %s", d.Id()) + _, err := conn.DeleteProject(input) + if err != nil { + return fmt.Errorf("Error deleting DeviceFarm Project: %s", err) + } + + return nil +} diff --git a/builtin/providers/aws/resource_aws_devicefarm_project_test.go b/builtin/providers/aws/resource_aws_devicefarm_project_test.go new file mode 100644 index 000000000..dc3a92c04 --- /dev/null +++ b/builtin/providers/aws/resource_aws_devicefarm_project_test.go @@ -0,0 +1,119 @@ +package aws + +import ( + "fmt" + "testing" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/awserr" + "github.com/aws/aws-sdk-go/service/devicefarm" + "github.com/hashicorp/terraform/helper/acctest" + "github.com/hashicorp/terraform/helper/resource" + "github.com/hashicorp/terraform/terraform" +) + +func TestAccAWSDeviceFarmProject_basic(t *testing.T) { + var afterCreate, afterUpdate devicefarm.Project + beforeInt := acctest.RandInt() + afterInt := acctest.RandInt() + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckDeviceFarmProjectDestroy, + Steps: []resource.TestStep{ + { + Config: testAccDeviceFarmProjectConfig(beforeInt), + Check: resource.ComposeTestCheckFunc( + testAccCheckDeviceFarmProjectExists( + "aws_devicefarm_project.foo", &afterCreate), + resource.TestCheckResourceAttr( + "aws_devicefarm_project.foo", "name", fmt.Sprintf("tf-testproject-%d", beforeInt)), + ), + }, + + { + Config: testAccDeviceFarmProjectConfig(afterInt), + Check: resource.ComposeTestCheckFunc( + testAccCheckDeviceFarmProjectExists( + "aws_devicefarm_project.foo", &afterUpdate), + resource.TestCheckResourceAttr( + "aws_devicefarm_project.foo", "name", fmt.Sprintf("tf-testproject-%d", afterInt)), + testAccCheckDeviceFarmProjectNotRecreated( + t, &afterCreate, &afterUpdate), + ), + }, + }, + }) +} + +func testAccCheckDeviceFarmProjectNotRecreated(t *testing.T, + before, after *devicefarm.Project) resource.TestCheckFunc { + return func(s *terraform.State) error { + if *before.Arn != *after.Arn { + t.Fatalf("Expected DeviceFarm Project ARNs to be the same. But they were: %v, %v", *before.Arn, *after.Arn) + } + return nil + } +} + +func testAccCheckDeviceFarmProjectExists(n string, v *devicefarm.Project) resource.TestCheckFunc { + return func(s *terraform.State) error { + rs, ok := s.RootModule().Resources[n] + if !ok { + return fmt.Errorf("Not found: %s", n) + } + + if rs.Primary.ID == "" { + return fmt.Errorf("No ID is set") + } + + conn := testAccProvider.Meta().(*AWSClient).devicefarmconn + resp, err := conn.GetProject( + &devicefarm.GetProjectInput{Arn: aws.String(rs.Primary.ID)}) + if err != nil { + return err + } + if resp.Project == nil { + return fmt.Errorf("DeviceFarmProject not found") + } + + *v = *resp.Project + + return nil + } +} + +func testAccCheckDeviceFarmProjectDestroy(s *terraform.State) error { + conn := testAccProvider.Meta().(*AWSClient).devicefarmconn + + for _, rs := range s.RootModule().Resources { + if rs.Type != "aws_devicefarm_project" { + continue + } + + // Try to find the resource + resp, err := conn.GetProject( + &devicefarm.GetProjectInput{Arn: aws.String(rs.Primary.ID)}) + if err == nil { + if resp.Project != nil { + return fmt.Errorf("still exist.") + } + + return nil + } + + if dferr, ok := err.(awserr.Error); ok && dferr.Code() == "DeviceFarmProjectNotFoundFault" { + return nil + } + } + + return nil +} + +func testAccDeviceFarmProjectConfig(rInt int) string { + return fmt.Sprintf(` +resource "aws_devicefarm_project" "foo" { + name = "tf-testproject-%d" +}`, rInt) +} diff --git a/builtin/providers/aws/resource_aws_directory_service_directory.go b/builtin/providers/aws/resource_aws_directory_service_directory.go index 773a5afd8..a9bd952dd 100644 --- a/builtin/providers/aws/resource_aws_directory_service_directory.go +++ b/builtin/providers/aws/resource_aws_directory_service_directory.go @@ -33,9 +33,10 @@ func resourceAwsDirectoryServiceDirectory() *schema.Resource { ForceNew: true, }, "password": &schema.Schema{ - Type: schema.TypeString, - Required: true, - ForceNew: true, + Type: schema.TypeString, + Required: true, + ForceNew: true, + Sensitive: true, }, "size": &schema.Schema{ Type: schema.TypeString, diff --git a/builtin/providers/aws/resource_aws_dms_endpoint.go b/builtin/providers/aws/resource_aws_dms_endpoint.go index 07cd7a272..586ed9f7c 100644 --- a/builtin/providers/aws/resource_aws_dms_endpoint.go +++ b/builtin/providers/aws/resource_aws_dms_endpoint.go @@ -6,7 +6,6 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/private/waiter" dms "github.com/aws/aws-sdk-go/service/databasemigrationservice" "github.com/hashicorp/terraform/helper/schema" "github.com/hashicorp/terraform/helper/validation" @@ -168,6 +167,7 @@ func resourceAwsDmsEndpointRead(d *schema.ResourceData, meta interface{}) error }) if err != nil { if dmserr, ok := err.(awserr.Error); ok && dmserr.Code() == "ResourceNotFoundFault" { + log.Printf("[DEBUG] DMS Replication Endpoint %q Not Found", d.Id()) d.SetId("") return nil } @@ -283,11 +283,6 @@ func resourceAwsDmsEndpointDelete(d *schema.ResourceData, meta interface{}) erro return err } - waitErr := waitForEndpointDelete(conn, d.Get("endpoint_id").(string), 30, 20) - if waitErr != nil { - return waitErr - } - return nil } @@ -310,36 +305,3 @@ func resourceAwsDmsEndpointSetState(d *schema.ResourceData, endpoint *dms.Endpoi return nil } - -func waitForEndpointDelete(client *dms.DatabaseMigrationService, endpointId string, delay int, maxAttempts int) error { - input := &dms.DescribeEndpointsInput{ - Filters: []*dms.Filter{ - { - Name: aws.String("endpoint-id"), - Values: []*string{aws.String(endpointId)}, - }, - }, - } - - config := waiter.Config{ - Operation: "DescribeEndpoints", - Delay: delay, - MaxAttempts: maxAttempts, - Acceptors: []waiter.WaitAcceptor{ - { - State: "success", - Matcher: "path", - Argument: "length(Endpoints[]) > `0`", - Expected: false, - }, - }, - } - - w := waiter.Waiter{ - Client: client, - Input: input, - Config: config, - } - - return w.Wait() -} diff --git a/builtin/providers/aws/resource_aws_dms_endpoint_test.go b/builtin/providers/aws/resource_aws_dms_endpoint_test.go index 6f8662283..59c3d87c7 100644 --- a/builtin/providers/aws/resource_aws_dms_endpoint_test.go +++ b/builtin/providers/aws/resource_aws_dms_endpoint_test.go @@ -8,7 +8,6 @@ import ( dms "github.com/aws/aws-sdk-go/service/databasemigrationservice" "github.com/hashicorp/terraform/helper/acctest" "github.com/hashicorp/terraform/helper/resource" - "github.com/hashicorp/terraform/helper/schema" "github.com/hashicorp/terraform/terraform" ) @@ -67,11 +66,6 @@ func dmsEndpointDestroy(s *terraform.State) error { } func checkDmsEndpointExists(n string) resource.TestCheckFunc { - providers := []*schema.Provider{testAccProvider} - return checkDmsEndpointExistsWithProviders(n, &providers) -} - -func checkDmsEndpointExistsWithProviders(n string, providers *[]*schema.Provider) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[n] if !ok { @@ -81,29 +75,26 @@ func checkDmsEndpointExistsWithProviders(n string, providers *[]*schema.Provider if rs.Primary.ID == "" { return fmt.Errorf("No ID is set") } - for _, provider := range *providers { - // Ignore if Meta is empty, this can happen for validation providers - if provider.Meta() == nil { - continue - } - conn := provider.Meta().(*AWSClient).dmsconn - _, err := conn.DescribeEndpoints(&dms.DescribeEndpointsInput{ - Filters: []*dms.Filter{ - { - Name: aws.String("endpoint-id"), - Values: []*string{aws.String(rs.Primary.ID)}, - }, + conn := testAccProvider.Meta().(*AWSClient).dmsconn + resp, err := conn.DescribeEndpoints(&dms.DescribeEndpointsInput{ + Filters: []*dms.Filter{ + { + Name: aws.String("endpoint-id"), + Values: []*string{aws.String(rs.Primary.ID)}, }, - }) + }, + }) - if err != nil { - return fmt.Errorf("DMS endpoint error: %v", err) - } - return nil + if err != nil { + return fmt.Errorf("DMS endpoint error: %v", err) } - return fmt.Errorf("DMS endpoint not found") + if resp.Endpoints == nil { + return fmt.Errorf("DMS endpoint not found") + } + + return nil } } diff --git a/builtin/providers/aws/resource_aws_dms_replication_instance.go b/builtin/providers/aws/resource_aws_dms_replication_instance.go index 63552d28e..2b6948936 100644 --- a/builtin/providers/aws/resource_aws_dms_replication_instance.go +++ b/builtin/providers/aws/resource_aws_dms_replication_instance.go @@ -3,11 +3,12 @@ package aws import ( "fmt" "log" + "time" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/private/waiter" dms "github.com/aws/aws-sdk-go/service/databasemigrationservice" + "github.com/hashicorp/terraform/helper/resource" "github.com/hashicorp/terraform/helper/schema" ) @@ -174,12 +175,23 @@ func resourceAwsDmsReplicationInstanceCreate(d *schema.ResourceData, meta interf return err } - err = waitForInstanceCreated(conn, d.Get("replication_instance_id").(string), 30, 20) + d.SetId(d.Get("replication_instance_id").(string)) + + stateConf := &resource.StateChangeConf{ + Pending: []string{"creating"}, + Target: []string{"available"}, + Refresh: resourceAwsDmsReplicationInstanceStateRefreshFunc(d, meta), + Timeout: d.Timeout(schema.TimeoutCreate), + MinTimeout: 10 * time.Second, + Delay: 30 * time.Second, // Wait 30 secs before starting + } + + // Wait, catching any errors + _, err = stateConf.WaitForState() if err != nil { return err } - d.SetId(d.Get("replication_instance_id").(string)) return resourceAwsDmsReplicationInstanceRead(d, meta) } @@ -196,6 +208,7 @@ func resourceAwsDmsReplicationInstanceRead(d *schema.ResourceData, meta interfac }) if err != nil { if dmserr, ok := err.(awserr.Error); ok && dmserr.Code() == "ResourceNotFoundFault" { + log.Printf("[DEBUG] DMS Replication Instance %q Not Found", d.Id()) d.SetId("") return nil } @@ -287,6 +300,21 @@ func resourceAwsDmsReplicationInstanceUpdate(d *schema.ResourceData, meta interf return err } + stateConf := &resource.StateChangeConf{ + Pending: []string{"modifying"}, + Target: []string{"available"}, + Refresh: resourceAwsDmsReplicationInstanceStateRefreshFunc(d, meta), + Timeout: d.Timeout(schema.TimeoutCreate), + MinTimeout: 10 * time.Second, + Delay: 30 * time.Second, // Wait 30 secs before starting + } + + // Wait, catching any errors + _, err = stateConf.WaitForState() + if err != nil { + return err + } + return resourceAwsDmsReplicationInstanceRead(d, meta) } @@ -307,9 +335,19 @@ func resourceAwsDmsReplicationInstanceDelete(d *schema.ResourceData, meta interf return err } - waitErr := waitForInstanceDeleted(conn, d.Get("replication_instance_id").(string), 30, 20) - if waitErr != nil { - return waitErr + stateConf := &resource.StateChangeConf{ + Pending: []string{"deleting"}, + Target: []string{}, + Refresh: resourceAwsDmsReplicationInstanceStateRefreshFunc(d, meta), + Timeout: d.Timeout(schema.TimeoutCreate), + MinTimeout: 10 * time.Second, + Delay: 30 * time.Second, // Wait 30 secs before starting + } + + // Wait, catching any errors + _, err = stateConf.WaitForState() + if err != nil { + return err } return nil @@ -355,68 +393,35 @@ func resourceAwsDmsReplicationInstanceSetState(d *schema.ResourceData, instance return nil } -func waitForInstanceCreated(client *dms.DatabaseMigrationService, id string, delay int, maxAttempts int) error { - input := &dms.DescribeReplicationInstancesInput{ - Filters: []*dms.Filter{ - { - Name: aws.String("replication-instance-id"), - Values: []*string{aws.String(id)}, +func resourceAwsDmsReplicationInstanceStateRefreshFunc( + d *schema.ResourceData, meta interface{}) resource.StateRefreshFunc { + return func() (interface{}, string, error) { + conn := meta.(*AWSClient).dmsconn + + v, err := conn.DescribeReplicationInstances(&dms.DescribeReplicationInstancesInput{ + Filters: []*dms.Filter{ + { + Name: aws.String("replication-instance-id"), + Values: []*string{aws.String(d.Id())}, // Must use d.Id() to work with import. + }, }, - }, - } + }) + if err != nil { + if dmserr, ok := err.(awserr.Error); ok && dmserr.Code() == "ResourceNotFoundFault" { + return nil, "", nil + } + log.Printf("Error on retrieving DMS Replication Instance when waiting: %s", err) + return nil, "", err + } - config := waiter.Config{ - Operation: "DescribeReplicationInstances", - Delay: delay, - MaxAttempts: maxAttempts, - Acceptors: []waiter.WaitAcceptor{ - { - State: "success", - Matcher: "pathAll", - Argument: "ReplicationInstances[].ReplicationInstanceStatus", - Expected: "available", - }, - }, - } + if v == nil { + return nil, "", nil + } - w := waiter.Waiter{ - Client: client, - Input: input, - Config: config, - } + if v.ReplicationInstances == nil { + return nil, "", fmt.Errorf("Error on retrieving DMS Replication Instance when waiting for State") + } - return w.Wait() -} - -func waitForInstanceDeleted(client *dms.DatabaseMigrationService, id string, delay int, maxAttempts int) error { - input := &dms.DescribeReplicationInstancesInput{ - Filters: []*dms.Filter{ - { - Name: aws.String("replication-instance-id"), - Values: []*string{aws.String(id)}, - }, - }, - } - - config := waiter.Config{ - Operation: "DescribeReplicationInstances", - Delay: delay, - MaxAttempts: maxAttempts, - Acceptors: []waiter.WaitAcceptor{ - { - State: "success", - Matcher: "path", - Argument: "length(ReplicationInstances[]) > `0`", - Expected: false, - }, - }, - } - - w := waiter.Waiter{ - Client: client, - Input: input, - Config: config, - } - - return w.Wait() + return v, *v.ReplicationInstances[0].ReplicationInstanceStatus, nil + } } diff --git a/builtin/providers/aws/resource_aws_dms_replication_instance_test.go b/builtin/providers/aws/resource_aws_dms_replication_instance_test.go index 17e7f85c8..0cb8a37d5 100644 --- a/builtin/providers/aws/resource_aws_dms_replication_instance_test.go +++ b/builtin/providers/aws/resource_aws_dms_replication_instance_test.go @@ -8,7 +8,6 @@ import ( dms "github.com/aws/aws-sdk-go/service/databasemigrationservice" "github.com/hashicorp/terraform/helper/acctest" "github.com/hashicorp/terraform/helper/resource" - "github.com/hashicorp/terraform/helper/schema" "github.com/hashicorp/terraform/terraform" ) @@ -47,11 +46,6 @@ func TestAccAwsDmsReplicationInstanceBasic(t *testing.T) { } func checkDmsReplicationInstanceExists(n string) resource.TestCheckFunc { - providers := []*schema.Provider{testAccProvider} - return checkDmsReplicationInstanceExistsWithProviders(n, &providers) -} - -func checkDmsReplicationInstanceExistsWithProviders(n string, providers *[]*schema.Provider) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[n] if !ok { @@ -61,29 +55,24 @@ func checkDmsReplicationInstanceExistsWithProviders(n string, providers *[]*sche if rs.Primary.ID == "" { return fmt.Errorf("No ID is set") } - for _, provider := range *providers { - // Ignore if Meta is empty, this can happen for validation providers - if provider.Meta() == nil { - continue - } - - conn := provider.Meta().(*AWSClient).dmsconn - _, err := conn.DescribeReplicationInstances(&dms.DescribeReplicationInstancesInput{ - Filters: []*dms.Filter{ - { - Name: aws.String("replication-instance-id"), - Values: []*string{aws.String(rs.Primary.ID)}, - }, + conn := testAccProvider.Meta().(*AWSClient).dmsconn + resp, err := conn.DescribeReplicationInstances(&dms.DescribeReplicationInstancesInput{ + Filters: []*dms.Filter{ + { + Name: aws.String("replication-instance-id"), + Values: []*string{aws.String(rs.Primary.ID)}, }, - }) + }, + }) - if err != nil { - return fmt.Errorf("DMS replication instance error: %v", err) - } - return nil + if err != nil { + return fmt.Errorf("DMS replication instance error: %v", err) + } + if resp.ReplicationInstances == nil { + return fmt.Errorf("DMS replication instance not found") } - return fmt.Errorf("DMS replication instance not found") + return nil } } @@ -104,22 +93,11 @@ func dmsReplicationInstanceDestroy(s *terraform.State) error { func dmsReplicationInstanceConfig(randId string) string { return fmt.Sprintf(` -resource "aws_iam_role" "dms_iam_role" { - name = "dms-vpc-role" - assume_role_policy = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Sid\":\"\",\"Effect\":\"Allow\",\"Principal\":{\"Service\":\"dms.amazonaws.com\"},\"Action\":\"sts:AssumeRole\"}]}" -} - -resource "aws_iam_role_policy_attachment" "dms_iam_role_policy" { - role = "${aws_iam_role.dms_iam_role.name}" - policy_arn = "arn:aws:iam::aws:policy/service-role/AmazonDMSVPCManagementRole" -} - resource "aws_vpc" "dms_vpc" { cidr_block = "10.1.0.0/16" tags { Name = "tf-test-dms-vpc-%[1]s" } - depends_on = ["aws_iam_role_policy_attachment.dms_iam_role_policy"] } resource "aws_subnet" "dms_subnet_1" { @@ -146,7 +124,6 @@ resource "aws_dms_replication_subnet_group" "dms_replication_subnet_group" { replication_subnet_group_id = "tf-test-dms-replication-subnet-group-%[1]s" replication_subnet_group_description = "terraform test for replication subnet group" subnet_ids = ["${aws_subnet.dms_subnet_1.id}", "${aws_subnet.dms_subnet_2.id}"] - depends_on = ["aws_iam_role_policy_attachment.dms_iam_role_policy"] } resource "aws_dms_replication_instance" "dms_replication_instance" { @@ -168,22 +145,11 @@ resource "aws_dms_replication_instance" "dms_replication_instance" { func dmsReplicationInstanceConfigUpdate(randId string) string { return fmt.Sprintf(` -resource "aws_iam_role" "dms_iam_role" { - name = "dms-vpc-role" - assume_role_policy = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Sid\":\"\",\"Effect\":\"Allow\",\"Principal\":{\"Service\":\"dms.amazonaws.com\"},\"Action\":\"sts:AssumeRole\"}]}" -} - -resource "aws_iam_role_policy_attachment" "dms_iam_role_policy" { - role = "${aws_iam_role.dms_iam_role.name}" - policy_arn = "arn:aws:iam::aws:policy/service-role/AmazonDMSVPCManagementRole" -} - resource "aws_vpc" "dms_vpc" { cidr_block = "10.1.0.0/16" tags { Name = "tf-test-dms-vpc-%[1]s" } - depends_on = ["aws_iam_role_policy_attachment.dms_iam_role_policy"] } resource "aws_subnet" "dms_subnet_1" { @@ -210,7 +176,6 @@ resource "aws_dms_replication_subnet_group" "dms_replication_subnet_group" { replication_subnet_group_id = "tf-test-dms-replication-subnet-group-%[1]s" replication_subnet_group_description = "terraform test for replication subnet group" subnet_ids = ["${aws_subnet.dms_subnet_1.id}", "${aws_subnet.dms_subnet_2.id}"] - depends_on = ["aws_iam_role_policy_attachment.dms_iam_role_policy"] } resource "aws_dms_replication_instance" "dms_replication_instance" { diff --git a/builtin/providers/aws/resource_aws_dms_replication_subnet_group_test.go b/builtin/providers/aws/resource_aws_dms_replication_subnet_group_test.go index 574745f9e..608382ccc 100644 --- a/builtin/providers/aws/resource_aws_dms_replication_subnet_group_test.go +++ b/builtin/providers/aws/resource_aws_dms_replication_subnet_group_test.go @@ -101,22 +101,11 @@ func dmsReplicationSubnetGroupDestroy(s *terraform.State) error { func dmsReplicationSubnetGroupConfig(randId string) string { return fmt.Sprintf(` -resource "aws_iam_role" "dms_iam_role" { - name = "dms-vpc-role" - assume_role_policy = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Sid\":\"\",\"Effect\":\"Allow\",\"Principal\":{\"Service\":\"dms.amazonaws.com\"},\"Action\":\"sts:AssumeRole\"}]}" -} - -resource "aws_iam_role_policy_attachment" "dms_iam_role_policy" { - role = "${aws_iam_role.dms_iam_role.name}" - policy_arn = "arn:aws:iam::aws:policy/service-role/AmazonDMSVPCManagementRole" -} - resource "aws_vpc" "dms_vpc" { cidr_block = "10.1.0.0/16" tags { Name = "tf-test-dms-vpc-%[1]s" } - depends_on = ["aws_iam_role_policy_attachment.dms_iam_role_policy"] } resource "aws_subnet" "dms_subnet_1" { @@ -164,22 +153,11 @@ resource "aws_dms_replication_subnet_group" "dms_replication_subnet_group" { func dmsReplicationSubnetGroupConfigUpdate(randId string) string { return fmt.Sprintf(` -resource "aws_iam_role" "dms_iam_role" { - name = "dms-vpc-role" - assume_role_policy = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Sid\":\"\",\"Effect\":\"Allow\",\"Principal\":{\"Service\":\"dms.amazonaws.com\"},\"Action\":\"sts:AssumeRole\"}]}" -} - -resource "aws_iam_role_policy_attachment" "dms_iam_role_policy" { - role = "${aws_iam_role.dms_iam_role.name}" - policy_arn = "arn:aws:iam::aws:policy/service-role/AmazonDMSVPCManagementRole" -} - resource "aws_vpc" "dms_vpc" { cidr_block = "10.1.0.0/16" tags { Name = "tf-test-dms-vpc-%[1]s" } - depends_on = ["aws_iam_role_policy_attachment.dms_iam_role_policy"] } resource "aws_subnet" "dms_subnet_1" { diff --git a/builtin/providers/aws/resource_aws_dms_replication_task.go b/builtin/providers/aws/resource_aws_dms_replication_task.go index a9ab72ce4..ab10eedbc 100644 --- a/builtin/providers/aws/resource_aws_dms_replication_task.go +++ b/builtin/providers/aws/resource_aws_dms_replication_task.go @@ -8,8 +8,8 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/private/waiter" dms "github.com/aws/aws-sdk-go/service/databasemigrationservice" + "github.com/hashicorp/terraform/helper/resource" "github.com/hashicorp/terraform/helper/schema" "github.com/hashicorp/terraform/helper/validation" ) @@ -121,13 +121,23 @@ func resourceAwsDmsReplicationTaskCreate(d *schema.ResourceData, meta interface{ } taskId := d.Get("replication_task_id").(string) + d.SetId(taskId) - err = waitForTaskCreated(conn, taskId, 30, 10) + stateConf := &resource.StateChangeConf{ + Pending: []string{"creating"}, + Target: []string{"ready"}, + Refresh: resourceAwsDmsReplicationTaskStateRefreshFunc(d, meta), + Timeout: d.Timeout(schema.TimeoutCreate), + MinTimeout: 10 * time.Second, + Delay: 30 * time.Second, // Wait 30 secs before starting + } + + // Wait, catching any errors + _, err = stateConf.WaitForState() if err != nil { return err } - d.SetId(taskId) return resourceAwsDmsReplicationTaskRead(d, meta) } @@ -144,6 +154,7 @@ func resourceAwsDmsReplicationTaskRead(d *schema.ResourceData, meta interface{}) }) if err != nil { if dmserr, ok := err.(awserr.Error); ok && dmserr.Code() == "ResourceNotFoundFault" { + log.Printf("[DEBUG] DMS Replication Task %q Not Found", d.Id()) d.SetId("") return nil } @@ -213,7 +224,17 @@ func resourceAwsDmsReplicationTaskUpdate(d *schema.ResourceData, meta interface{ return err } - err = waitForTaskUpdated(conn, d.Get("replication_task_id").(string), 30, 10) + stateConf := &resource.StateChangeConf{ + Pending: []string{"modifying"}, + Target: []string{"ready", "stopped", "failed"}, + Refresh: resourceAwsDmsReplicationTaskStateRefreshFunc(d, meta), + Timeout: d.Timeout(schema.TimeoutCreate), + MinTimeout: 10 * time.Second, + Delay: 30 * time.Second, // Wait 30 secs before starting + } + + // Wait, catching any errors + _, err = stateConf.WaitForState() if err != nil { return err } @@ -235,12 +256,27 @@ func resourceAwsDmsReplicationTaskDelete(d *schema.ResourceData, meta interface{ _, err := conn.DeleteReplicationTask(request) if err != nil { + if dmserr, ok := err.(awserr.Error); ok && dmserr.Code() == "ResourceNotFoundFault" { + log.Printf("[DEBUG] DMS Replication Task %q Not Found", d.Id()) + d.SetId("") + return nil + } return err } - waitErr := waitForTaskDeleted(conn, d.Get("replication_task_id").(string), 30, 10) - if waitErr != nil { - return waitErr + stateConf := &resource.StateChangeConf{ + Pending: []string{"deleting"}, + Target: []string{}, + Refresh: resourceAwsDmsReplicationTaskStateRefreshFunc(d, meta), + Timeout: d.Timeout(schema.TimeoutCreate), + MinTimeout: 10 * time.Second, + Delay: 30 * time.Second, // Wait 30 secs before starting + } + + // Wait, catching any errors + _, err = stateConf.WaitForState() + if err != nil { + return err } return nil @@ -261,119 +297,35 @@ func resourceAwsDmsReplicationTaskSetState(d *schema.ResourceData, task *dms.Rep return nil } -func waitForTaskCreated(client *dms.DatabaseMigrationService, id string, delay int, maxAttempts int) error { - input := &dms.DescribeReplicationTasksInput{ - Filters: []*dms.Filter{ - { - Name: aws.String("replication-task-id"), - Values: []*string{aws.String(id)}, - }, - }, - } +func resourceAwsDmsReplicationTaskStateRefreshFunc( + d *schema.ResourceData, meta interface{}) resource.StateRefreshFunc { + return func() (interface{}, string, error) { + conn := meta.(*AWSClient).dmsconn - config := waiter.Config{ - Operation: "DescribeReplicationTasks", - Delay: delay, - MaxAttempts: maxAttempts, - Acceptors: []waiter.WaitAcceptor{ - { - State: "retry", - Matcher: "pathAll", - Argument: "ReplicationTasks[].Status", - Expected: "creating", + v, err := conn.DescribeReplicationTasks(&dms.DescribeReplicationTasksInput{ + Filters: []*dms.Filter{ + { + Name: aws.String("replication-task-id"), + Values: []*string{aws.String(d.Id())}, // Must use d.Id() to work with import. + }, }, - { - State: "success", - Matcher: "pathAll", - Argument: "ReplicationTasks[].Status", - Expected: "ready", - }, - }, - } + }) + if err != nil { + if dmserr, ok := err.(awserr.Error); ok && dmserr.Code() == "ResourceNotFoundFault" { + return nil, "", nil + } + log.Printf("Error on retrieving DMS Replication Task when waiting: %s", err) + return nil, "", err + } - w := waiter.Waiter{ - Client: client, - Input: input, - Config: config, - } + if v == nil { + return nil, "", nil + } - return w.Wait() -} - -func waitForTaskUpdated(client *dms.DatabaseMigrationService, id string, delay int, maxAttempts int) error { - input := &dms.DescribeReplicationTasksInput{ - Filters: []*dms.Filter{ - { - Name: aws.String("replication-task-id"), - Values: []*string{aws.String(id)}, - }, - }, - } - - config := waiter.Config{ - Operation: "DescribeReplicationTasks", - Delay: delay, - MaxAttempts: maxAttempts, - Acceptors: []waiter.WaitAcceptor{ - { - State: "retry", - Matcher: "pathAll", - Argument: "ReplicationTasks[].Status", - Expected: "modifying", - }, - { - State: "success", - Matcher: "pathAll", - Argument: "ReplicationTasks[].Status", - Expected: "ready", - }, - }, - } - - w := waiter.Waiter{ - Client: client, - Input: input, - Config: config, - } - - return w.Wait() -} - -func waitForTaskDeleted(client *dms.DatabaseMigrationService, id string, delay int, maxAttempts int) error { - input := &dms.DescribeReplicationTasksInput{ - Filters: []*dms.Filter{ - { - Name: aws.String("replication-task-id"), - Values: []*string{aws.String(id)}, - }, - }, - } - - config := waiter.Config{ - Operation: "DescribeReplicationTasks", - Delay: delay, - MaxAttempts: maxAttempts, - Acceptors: []waiter.WaitAcceptor{ - { - State: "retry", - Matcher: "pathAll", - Argument: "ReplicationTasks[].Status", - Expected: "deleting", - }, - { - State: "success", - Matcher: "path", - Argument: "length(ReplicationTasks[]) > `0`", - Expected: false, - }, - }, - } - - w := waiter.Waiter{ - Client: client, - Input: input, - Config: config, - } - - return w.Wait() + if v.ReplicationTasks != nil { + log.Printf("[DEBUG] DMS Replication Task status for instance %s: %s", d.Id(), *v.ReplicationTasks[0].Status) + } + + return v, *v.ReplicationTasks[0].Status, nil + } } diff --git a/builtin/providers/aws/resource_aws_dms_replication_task_test.go b/builtin/providers/aws/resource_aws_dms_replication_task_test.go index 07ac7f58f..9105a3109 100644 --- a/builtin/providers/aws/resource_aws_dms_replication_task_test.go +++ b/builtin/providers/aws/resource_aws_dms_replication_task_test.go @@ -8,7 +8,6 @@ import ( dms "github.com/aws/aws-sdk-go/service/databasemigrationservice" "github.com/hashicorp/terraform/helper/acctest" "github.com/hashicorp/terraform/helper/resource" - "github.com/hashicorp/terraform/helper/schema" "github.com/hashicorp/terraform/terraform" ) @@ -44,11 +43,6 @@ func TestAccAwsDmsReplicationTaskBasic(t *testing.T) { } func checkDmsReplicationTaskExists(n string) resource.TestCheckFunc { - providers := []*schema.Provider{testAccProvider} - return checkDmsReplicationTaskExistsWithProviders(n, &providers) -} - -func checkDmsReplicationTaskExistsWithProviders(n string, providers *[]*schema.Provider) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[n] if !ok { @@ -58,29 +52,25 @@ func checkDmsReplicationTaskExistsWithProviders(n string, providers *[]*schema.P if rs.Primary.ID == "" { return fmt.Errorf("No ID is set") } - for _, provider := range *providers { - // Ignore if Meta is empty, this can happen for validation providers - if provider.Meta() == nil { - continue - } - conn := provider.Meta().(*AWSClient).dmsconn - _, err := conn.DescribeReplicationTasks(&dms.DescribeReplicationTasksInput{ - Filters: []*dms.Filter{ - { - Name: aws.String("replication-task-id"), - Values: []*string{aws.String(rs.Primary.ID)}, - }, + conn := testAccProvider.Meta().(*AWSClient).dmsconn + resp, err := conn.DescribeReplicationTasks(&dms.DescribeReplicationTasksInput{ + Filters: []*dms.Filter{ + { + Name: aws.String("replication-task-id"), + Values: []*string{aws.String(rs.Primary.ID)}, }, - }) + }, + }) - if err != nil { - return fmt.Errorf("DMS replication subnet group error: %v", err) - } - return nil + if err != nil { + return err } - return fmt.Errorf("DMS replication subnet group not found") + if resp.ReplicationTasks == nil { + return fmt.Errorf("DMS replication task error: %v", err) + } + return nil } } @@ -90,9 +80,22 @@ func dmsReplicationTaskDestroy(s *terraform.State) error { continue } - err := checkDmsReplicationTaskExists(rs.Primary.ID) - if err == nil { - return fmt.Errorf("Found replication subnet group that was not destroyed: %s", rs.Primary.ID) + conn := testAccProvider.Meta().(*AWSClient).dmsconn + resp, err := conn.DescribeReplicationTasks(&dms.DescribeReplicationTasksInput{ + Filters: []*dms.Filter{ + { + Name: aws.String("replication-task-id"), + Values: []*string{aws.String(rs.Primary.ID)}, + }, + }, + }) + + if err != nil { + return nil + } + + if resp != nil && len(resp.ReplicationTasks) > 0 { + return fmt.Errorf("DMS replication task still exists: %v", err) } } @@ -101,22 +104,11 @@ func dmsReplicationTaskDestroy(s *terraform.State) error { func dmsReplicationTaskConfig(randId string) string { return fmt.Sprintf(` -resource "aws_iam_role" "dms_iam_role" { - name = "dms-vpc-role" - assume_role_policy = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Sid\":\"\",\"Effect\":\"Allow\",\"Principal\":{\"Service\":\"dms.amazonaws.com\"},\"Action\":\"sts:AssumeRole\"}]}" -} - -resource "aws_iam_role_policy_attachment" "dms_iam_role_policy" { - role = "${aws_iam_role.dms_iam_role.name}" - policy_arn = "arn:aws:iam::aws:policy/service-role/AmazonDMSVPCManagementRole" -} - resource "aws_vpc" "dms_vpc" { cidr_block = "10.1.0.0/16" tags { Name = "tf-test-dms-vpc-%[1]s" } - depends_on = ["aws_iam_role_policy_attachment.dms_iam_role_policy"] } resource "aws_subnet" "dms_subnet_1" { @@ -148,7 +140,6 @@ resource "aws_dms_endpoint" "dms_endpoint_source" { port = 3306 username = "tftest" password = "tftest" - depends_on = ["aws_iam_role_policy_attachment.dms_iam_role_policy"] } resource "aws_dms_endpoint" "dms_endpoint_target" { @@ -160,14 +151,12 @@ resource "aws_dms_endpoint" "dms_endpoint_target" { port = 3306 username = "tftest" password = "tftest" - depends_on = ["aws_iam_role_policy_attachment.dms_iam_role_policy"] } resource "aws_dms_replication_subnet_group" "dms_replication_subnet_group" { replication_subnet_group_id = "tf-test-dms-replication-subnet-group-%[1]s" replication_subnet_group_description = "terraform test for replication subnet group" subnet_ids = ["${aws_subnet.dms_subnet_1.id}", "${aws_subnet.dms_subnet_2.id}"] - depends_on = ["aws_iam_role_policy_attachment.dms_iam_role_policy"] } resource "aws_dms_replication_instance" "dms_replication_instance" { @@ -199,22 +188,11 @@ resource "aws_dms_replication_task" "dms_replication_task" { func dmsReplicationTaskConfigUpdate(randId string) string { return fmt.Sprintf(` -resource "aws_iam_role" "dms_iam_role" { - name = "dms-vpc-role" - assume_role_policy = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Sid\":\"\",\"Effect\":\"Allow\",\"Principal\":{\"Service\":\"dms.amazonaws.com\"},\"Action\":\"sts:AssumeRole\"}]}" -} - -resource "aws_iam_role_policy_attachment" "dms_iam_role_policy" { - role = "${aws_iam_role.dms_iam_role.name}" - policy_arn = "arn:aws:iam::aws:policy/service-role/AmazonDMSVPCManagementRole" -} - resource "aws_vpc" "dms_vpc" { cidr_block = "10.1.0.0/16" tags { Name = "tf-test-dms-vpc-%[1]s" } - depends_on = ["aws_iam_role_policy_attachment.dms_iam_role_policy"] } resource "aws_subnet" "dms_subnet_1" { @@ -246,7 +224,6 @@ resource "aws_dms_endpoint" "dms_endpoint_source" { port = 3306 username = "tftest" password = "tftest" - depends_on = ["aws_iam_role_policy_attachment.dms_iam_role_policy"] } resource "aws_dms_endpoint" "dms_endpoint_target" { @@ -258,14 +235,12 @@ resource "aws_dms_endpoint" "dms_endpoint_target" { port = 3306 username = "tftest" password = "tftest" - depends_on = ["aws_iam_role_policy_attachment.dms_iam_role_policy"] } resource "aws_dms_replication_subnet_group" "dms_replication_subnet_group" { replication_subnet_group_id = "tf-test-dms-replication-subnet-group-%[1]s" replication_subnet_group_description = "terraform test for replication subnet group" subnet_ids = ["${aws_subnet.dms_subnet_1.id}", "${aws_subnet.dms_subnet_2.id}"] - depends_on = ["aws_iam_role_policy_attachment.dms_iam_role_policy"] } resource "aws_dms_replication_instance" "dms_replication_instance" { diff --git a/builtin/providers/aws/resource_aws_dynamodb_table.go b/builtin/providers/aws/resource_aws_dynamodb_table.go index e0c63760d..155da08f9 100644 --- a/builtin/providers/aws/resource_aws_dynamodb_table.go +++ b/builtin/providers/aws/resource_aws_dynamodb_table.go @@ -39,6 +39,9 @@ func resourceAwsDynamoDbTable() *schema.Resource { State: schema.ImportStatePassthrough, }, + SchemaVersion: 1, + MigrateState: resourceAwsDynamoDbTableMigrateState, + Schema: map[string]*schema.Schema{ "arn": { Type: schema.TypeString, @@ -89,6 +92,23 @@ func resourceAwsDynamoDbTable() *schema.Resource { return hashcode.String(buf.String()) }, }, + "ttl": { + Type: schema.TypeSet, + Optional: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "attribute_name": { + Type: schema.TypeString, + Required: true, + }, + "enabled": { + Type: schema.TypeBool, + Required: true, + }, + }, + }, + }, "local_secondary_index": { Type: schema.TypeSet, Optional: true, @@ -157,15 +177,6 @@ func resourceAwsDynamoDbTable() *schema.Resource { }, }, }, - // GSI names are the uniqueness constraint - Set: func(v interface{}) int { - var buf bytes.Buffer - m := v.(map[string]interface{}) - buf.WriteString(fmt.Sprintf("%s-", m["name"].(string))) - buf.WriteString(fmt.Sprintf("%d-", m["write_capacity"].(int))) - buf.WriteString(fmt.Sprintf("%d-", m["read_capacity"].(int))) - return hashcode.String(buf.String()) - }, }, "stream_enabled": { Type: schema.TypeBool, @@ -302,6 +313,7 @@ func resourceAwsDynamoDbTableCreate(d *schema.ResourceData, meta interface{}) er log.Printf("[DEBUG] Adding StreamSpecifications to the table") } + _, timeToLiveOk := d.GetOk("ttl") _, tagsOk := d.GetOk("tags") attemptCount := 1 @@ -332,12 +344,28 @@ func resourceAwsDynamoDbTableCreate(d *schema.ResourceData, meta interface{}) er if err := d.Set("arn", tableArn); err != nil { return err } + + // Wait, till table is active before imitating any TimeToLive changes + if err := waitForTableToBeActive(d.Id(), meta); err != nil { + log.Printf("[DEBUG] Error waiting for table to be active: %s", err) + return err + } + + log.Printf("[DEBUG] Setting DynamoDB TimeToLive on arn: %s", tableArn) + if timeToLiveOk { + if err := updateTimeToLive(d, meta); err != nil { + log.Printf("[DEBUG] Error updating table TimeToLive: %s", err) + return err + } + } + if tagsOk { log.Printf("[DEBUG] Setting DynamoDB Tags on arn: %s", tableArn) if err := createTableTags(d, meta); err != nil { return err } } + return resourceAwsDynamoDbTableRead(d, meta) } } @@ -533,9 +561,8 @@ func resourceAwsDynamoDbTableUpdate(d *schema.ResourceData, meta interface{}) er table := tableDescription.Table - updates := []*dynamodb.GlobalSecondaryIndexUpdate{} - for _, updatedgsidata := range gsiSet.List() { + updates := []*dynamodb.GlobalSecondaryIndexUpdate{} gsidata := updatedgsidata.(map[string]interface{}) gsiName := gsidata["name"].(string) gsiWriteCapacity := gsidata["write_capacity"].(int) @@ -584,12 +611,23 @@ func resourceAwsDynamoDbTableUpdate(d *schema.ResourceData, meta interface{}) er log.Printf("[DEBUG] Error updating table: %s", err) return err } + + if err := waitForGSIToBeActive(d.Id(), gsiName, meta); err != nil { + return errwrap.Wrapf("Error waiting for Dynamo DB GSI to be active: {{err}}", err) + } } } } } + if d.HasChange("ttl") { + if err := updateTimeToLive(d, meta); err != nil { + log.Printf("[DEBUG] Error updating table TimeToLive: %s", err) + return err + } + } + // Update tags if err := setTagsDynamoDb(dynamodbconn, d); err != nil { return err @@ -598,6 +636,46 @@ func resourceAwsDynamoDbTableUpdate(d *schema.ResourceData, meta interface{}) er return resourceAwsDynamoDbTableRead(d, meta) } +func updateTimeToLive(d *schema.ResourceData, meta interface{}) error { + dynamodbconn := meta.(*AWSClient).dynamodbconn + + if ttl, ok := d.GetOk("ttl"); ok { + + timeToLiveSet := ttl.(*schema.Set) + + spec := &dynamodb.TimeToLiveSpecification{} + + timeToLive := timeToLiveSet.List()[0].(map[string]interface{}) + spec.AttributeName = aws.String(timeToLive["attribute_name"].(string)) + spec.Enabled = aws.Bool(timeToLive["enabled"].(bool)) + + req := &dynamodb.UpdateTimeToLiveInput{ + TableName: aws.String(d.Id()), + TimeToLiveSpecification: spec, + } + + _, err := dynamodbconn.UpdateTimeToLive(req) + + if err != nil { + // If ttl was not set within the .tf file before and has now been added we still run this command to update + // But there has been no change so lets continue + if awsErr, ok := err.(awserr.Error); ok && awsErr.Code() == "ValidationException" && awsErr.Message() == "TimeToLive is already disabled" { + return nil + } + log.Printf("[DEBUG] Error updating TimeToLive on table: %s", err) + return err + } + + log.Printf("[DEBUG] Updated TimeToLive on table") + + if err := waitForTimeToLiveUpdateToBeCompleted(d.Id(), timeToLive["enabled"].(bool), meta); err != nil { + return errwrap.Wrapf("Error waiting for Dynamo DB TimeToLive to be updated: {{err}}", err) + } + } + + return nil +} + func resourceAwsDynamoDbTableRead(d *schema.ResourceData, meta interface{}) error { dynamodbconn := meta.(*AWSClient).dynamodbconn log.Printf("[DEBUG] Loading data for DynamoDB table '%s'", d.Id()) @@ -714,6 +792,23 @@ func resourceAwsDynamoDbTableRead(d *schema.ResourceData, meta interface{}) erro d.Set("arn", table.TableArn) + timeToLiveReq := &dynamodb.DescribeTimeToLiveInput{ + TableName: aws.String(d.Id()), + } + timeToLiveOutput, err := dynamodbconn.DescribeTimeToLive(timeToLiveReq) + if err != nil { + return err + } + timeToLive := []interface{}{} + attribute := map[string]*string{ + "name": timeToLiveOutput.TimeToLiveDescription.AttributeName, + "type": timeToLiveOutput.TimeToLiveDescription.TimeToLiveStatus, + } + timeToLive = append(timeToLive, attribute) + d.Set("timeToLive", timeToLive) + + log.Printf("[DEBUG] Loaded TimeToLive data for DynamoDB table '%s'", d.Id()) + tags, err := readTableTags(d, meta) if err != nil { return err @@ -913,6 +1008,39 @@ func waitForTableToBeActive(tableName string, meta interface{}) error { } +func waitForTimeToLiveUpdateToBeCompleted(tableName string, enabled bool, meta interface{}) error { + dynamodbconn := meta.(*AWSClient).dynamodbconn + req := &dynamodb.DescribeTimeToLiveInput{ + TableName: aws.String(tableName), + } + + stateMatched := false + for stateMatched == false { + result, err := dynamodbconn.DescribeTimeToLive(req) + + if err != nil { + return err + } + + if enabled { + stateMatched = *result.TimeToLiveDescription.TimeToLiveStatus == dynamodb.TimeToLiveStatusEnabled + } else { + stateMatched = *result.TimeToLiveDescription.TimeToLiveStatus == dynamodb.TimeToLiveStatusDisabled + } + + // Wait for a few seconds, this may take a long time... + if !stateMatched { + log.Printf("[DEBUG] Sleeping for 5 seconds before checking TimeToLive state again") + time.Sleep(5 * time.Second) + } + } + + log.Printf("[DEBUG] TimeToLive update complete") + + return nil + +} + func createTableTags(d *schema.ResourceData, meta interface{}) error { // DynamoDB Table has to be in the ACTIVE state in order to tag the resource if err := waitForTableToBeActive(d.Id(), meta); err != nil { diff --git a/builtin/providers/aws/resource_aws_dynamodb_table_migrate.go b/builtin/providers/aws/resource_aws_dynamodb_table_migrate.go new file mode 100644 index 000000000..59865effc --- /dev/null +++ b/builtin/providers/aws/resource_aws_dynamodb_table_migrate.go @@ -0,0 +1,70 @@ +package aws + +import ( + "fmt" + "log" + + "github.com/hashicorp/terraform/helper/schema" + "github.com/hashicorp/terraform/terraform" + "strings" +) + +func resourceAwsDynamoDbTableMigrateState( + v int, is *terraform.InstanceState, meta interface{}) (*terraform.InstanceState, error) { + switch v { + case 0: + log.Println("[INFO] Found AWS DynamoDB Table State v0; migrating to v1") + return migrateDynamoDBStateV0toV1(is) + default: + return is, fmt.Errorf("Unexpected schema version: %d", v) + } +} + +func migrateDynamoDBStateV0toV1(is *terraform.InstanceState) (*terraform.InstanceState, error) { + if is.Empty() { + log.Println("[DEBUG] Empty InstanceState; nothing to migrate.") + return is, nil + } + + log.Printf("[DEBUG] DynamoDB Table Attributes before Migration: %#v", is.Attributes) + + prefix := "global_secondary_index" + entity := resourceAwsDynamoDbTable() + + // Read old keys + reader := &schema.MapFieldReader{ + Schema: entity.Schema, + Map: schema.BasicMapReader(is.Attributes), + } + result, err := reader.ReadField([]string{prefix}) + if err != nil { + return nil, err + } + + oldKeys, ok := result.Value.(*schema.Set) + if !ok { + return nil, fmt.Errorf("Got unexpected value from state: %#v", result.Value) + } + + // Delete old keys + for k := range is.Attributes { + if strings.HasPrefix(k, fmt.Sprintf("%s.", prefix)) { + delete(is.Attributes, k) + } + } + + // Write new keys + writer := schema.MapFieldWriter{ + Schema: entity.Schema, + } + if err := writer.WriteField([]string{prefix}, oldKeys); err != nil { + return is, err + } + for k, v := range writer.Map() { + is.Attributes[k] = v + } + + log.Printf("[DEBUG] DynamoDB Table Attributes after State Migration: %#v", is.Attributes) + + return is, nil +} diff --git a/builtin/providers/aws/resource_aws_dynamodb_table_test.go b/builtin/providers/aws/resource_aws_dynamodb_table_test.go index 4d5437f17..59cebc4a1 100644 --- a/builtin/providers/aws/resource_aws_dynamodb_table_test.go +++ b/builtin/providers/aws/resource_aws_dynamodb_table_test.go @@ -14,19 +14,24 @@ import ( ) func TestAccAWSDynamoDbTable_basic(t *testing.T) { + var conf dynamodb.DescribeTableOutput + + rName := acctest.RandomWithPrefix("TerraformTestTable-") + resource.Test(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, CheckDestroy: testAccCheckAWSDynamoDbTableDestroy, Steps: []resource.TestStep{ { - Config: testAccAWSDynamoDbConfigInitialState(), + Config: testAccAWSDynamoDbConfigInitialState(rName), Check: resource.ComposeTestCheckFunc( - testAccCheckInitialAWSDynamoDbTableExists("aws_dynamodb_table.basic-dynamodb-table"), + testAccCheckInitialAWSDynamoDbTableExists("aws_dynamodb_table.basic-dynamodb-table", &conf), + testAccCheckInitialAWSDynamoDbTableConf("aws_dynamodb_table.basic-dynamodb-table"), ), }, { - Config: testAccAWSDynamoDbConfigAddSecondaryGSI, + Config: testAccAWSDynamoDbConfigAddSecondaryGSI(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDynamoDbTableWasUpdated("aws_dynamodb_table.basic-dynamodb-table"), ), @@ -36,6 +41,8 @@ func TestAccAWSDynamoDbTable_basic(t *testing.T) { } func TestAccAWSDynamoDbTable_streamSpecification(t *testing.T) { + var conf dynamodb.DescribeTableOutput + resource.Test(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, @@ -44,7 +51,8 @@ func TestAccAWSDynamoDbTable_streamSpecification(t *testing.T) { { Config: testAccAWSDynamoDbConfigStreamSpecification(), Check: resource.ComposeTestCheckFunc( - testAccCheckInitialAWSDynamoDbTableExists("aws_dynamodb_table.basic-dynamodb-table"), + testAccCheckInitialAWSDynamoDbTableExists("aws_dynamodb_table.basic-dynamodb-table", &conf), + testAccCheckInitialAWSDynamoDbTableConf("aws_dynamodb_table.basic-dynamodb-table"), resource.TestCheckResourceAttr( "aws_dynamodb_table.basic-dynamodb-table", "stream_enabled", "true"), resource.TestCheckResourceAttr( @@ -56,6 +64,8 @@ func TestAccAWSDynamoDbTable_streamSpecification(t *testing.T) { } func TestAccAWSDynamoDbTable_tags(t *testing.T) { + var conf dynamodb.DescribeTableOutput + resource.Test(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, @@ -64,7 +74,8 @@ func TestAccAWSDynamoDbTable_tags(t *testing.T) { { Config: testAccAWSDynamoDbConfigTags(), Check: resource.ComposeTestCheckFunc( - testAccCheckInitialAWSDynamoDbTableExists("aws_dynamodb_table.basic-dynamodb-table"), + testAccCheckInitialAWSDynamoDbTableExists("aws_dynamodb_table.basic-dynamodb-table", &conf), + testAccCheckInitialAWSDynamoDbTableConf("aws_dynamodb_table.basic-dynamodb-table"), resource.TestCheckResourceAttr( "aws_dynamodb_table.basic-dynamodb-table", "tags.%", "3"), ), @@ -73,6 +84,97 @@ func TestAccAWSDynamoDbTable_tags(t *testing.T) { }) } +// https://github.com/hashicorp/terraform/issues/13243 +func TestAccAWSDynamoDbTable_gsiUpdate(t *testing.T) { + var conf dynamodb.DescribeTableOutput + name := acctest.RandString(10) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSDynamoDbTableDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAWSDynamoDbConfigGsiUpdate(name), + Check: resource.ComposeTestCheckFunc( + testAccCheckInitialAWSDynamoDbTableExists("aws_dynamodb_table.test", &conf), + ), + }, + { + Config: testAccAWSDynamoDbConfigGsiUpdated(name), + Check: resource.ComposeTestCheckFunc( + testAccCheckInitialAWSDynamoDbTableExists("aws_dynamodb_table.test", &conf), + ), + }, + }, + }) +} + +func TestAccAWSDynamoDbTable_ttl(t *testing.T) { + var conf dynamodb.DescribeTableOutput + + rName := acctest.RandomWithPrefix("TerraformTestTable-") + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSDynamoDbTableDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAWSDynamoDbConfigInitialState(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckInitialAWSDynamoDbTableExists("aws_dynamodb_table.basic-dynamodb-table", &conf), + ), + }, + { + Config: testAccAWSDynamoDbConfigAddTimeToLive(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckDynamoDbTableTimeToLiveWasUpdated("aws_dynamodb_table.basic-dynamodb-table"), + ), + }, + }, + }) +} +func testAccCheckDynamoDbTableTimeToLiveWasUpdated(n string) resource.TestCheckFunc { + return func(s *terraform.State) error { + log.Printf("[DEBUG] Trying to create initial table state!") + rs, ok := s.RootModule().Resources[n] + if !ok { + return fmt.Errorf("Not found: %s", n) + } + + if rs.Primary.ID == "" { + return fmt.Errorf("No DynamoDB table name specified!") + } + + conn := testAccProvider.Meta().(*AWSClient).dynamodbconn + + params := &dynamodb.DescribeTimeToLiveInput{ + TableName: aws.String(rs.Primary.ID), + } + + resp, err := conn.DescribeTimeToLive(params) + + if err != nil { + return fmt.Errorf("[ERROR] Problem describing time to live for table '%s': %s", rs.Primary.ID, err) + } + + ttlDescription := resp.TimeToLiveDescription + + log.Printf("[DEBUG] Checking on table %s", rs.Primary.ID) + + if *ttlDescription.TimeToLiveStatus != dynamodb.TimeToLiveStatusEnabled { + return fmt.Errorf("TimeToLiveStatus %s, not ENABLED!", *ttlDescription.TimeToLiveStatus) + } + + if *ttlDescription.AttributeName != "TestTTL" { + return fmt.Errorf("AttributeName was %s, not TestTTL!", *ttlDescription.AttributeName) + } + + return nil + } +} + func TestResourceAWSDynamoDbTableStreamViewType_validation(t *testing.T) { cases := []struct { Value string @@ -143,7 +245,37 @@ func testAccCheckAWSDynamoDbTableDestroy(s *terraform.State) error { return nil } -func testAccCheckInitialAWSDynamoDbTableExists(n string) resource.TestCheckFunc { +func testAccCheckInitialAWSDynamoDbTableExists(n string, table *dynamodb.DescribeTableOutput) resource.TestCheckFunc { + return func(s *terraform.State) error { + log.Printf("[DEBUG] Trying to create initial table state!") + rs, ok := s.RootModule().Resources[n] + if !ok { + return fmt.Errorf("Not found: %s", n) + } + + if rs.Primary.ID == "" { + return fmt.Errorf("No DynamoDB table name specified!") + } + + conn := testAccProvider.Meta().(*AWSClient).dynamodbconn + + params := &dynamodb.DescribeTableInput{ + TableName: aws.String(rs.Primary.ID), + } + + resp, err := conn.DescribeTable(params) + + if err != nil { + return fmt.Errorf("[ERROR] Problem describing table '%s': %s", rs.Primary.ID, err) + } + + *table = *resp + + return nil + } +} + +func testAccCheckInitialAWSDynamoDbTableConf(n string) resource.TestCheckFunc { return func(s *terraform.State) error { log.Printf("[DEBUG] Trying to create initial table state!") rs, ok := s.RootModule().Resources[n] @@ -298,126 +430,145 @@ func dynamoDbAttributesToMap(attributes *[]*dynamodb.AttributeDefinition) map[st return attrmap } -func testAccAWSDynamoDbConfigInitialState() string { +func testAccAWSDynamoDbConfigInitialState(rName string) string { return fmt.Sprintf(` resource "aws_dynamodb_table" "basic-dynamodb-table" { - name = "TerraformTestTable-%d" - read_capacity = 10 - write_capacity = 20 - hash_key = "TestTableHashKey" - range_key = "TestTableRangeKey" - attribute { - name = "TestTableHashKey" - type = "S" - } - attribute { - name = "TestTableRangeKey" - type = "S" - } - attribute { - name = "TestLSIRangeKey" - type = "N" - } - attribute { - name = "TestGSIRangeKey" - type = "S" - } - local_secondary_index { - name = "TestTableLSI" - range_key = "TestLSIRangeKey" - projection_type = "ALL" - } - global_secondary_index { - name = "InitialTestTableGSI" - hash_key = "TestTableHashKey" - range_key = "TestGSIRangeKey" - write_capacity = 10 - read_capacity = 10 - projection_type = "KEYS_ONLY" - } + name = "%s" + read_capacity = 10 + write_capacity = 20 + hash_key = "TestTableHashKey" + range_key = "TestTableRangeKey" + + attribute { + name = "TestTableHashKey" + type = "S" + } + + attribute { + name = "TestTableRangeKey" + type = "S" + } + + attribute { + name = "TestLSIRangeKey" + type = "N" + } + + attribute { + name = "TestGSIRangeKey" + type = "S" + } + + local_secondary_index { + name = "TestTableLSI" + range_key = "TestLSIRangeKey" + projection_type = "ALL" + } + + global_secondary_index { + name = "InitialTestTableGSI" + hash_key = "TestTableHashKey" + range_key = "TestGSIRangeKey" + write_capacity = 10 + read_capacity = 10 + projection_type = "KEYS_ONLY" + } } -`, acctest.RandInt()) +`, rName) } -const testAccAWSDynamoDbConfigAddSecondaryGSI = ` +func testAccAWSDynamoDbConfigAddSecondaryGSI(rName string) string { + return fmt.Sprintf(` resource "aws_dynamodb_table" "basic-dynamodb-table" { - name = "TerraformTestTable" - read_capacity = 20 - write_capacity = 20 - hash_key = "TestTableHashKey" - range_key = "TestTableRangeKey" - attribute { - name = "TestTableHashKey" - type = "S" - } - attribute { - name = "TestTableRangeKey" - type = "S" - } - attribute { - name = "TestLSIRangeKey" - type = "N" - } - attribute { - name = "ReplacementGSIRangeKey" - type = "N" - } - local_secondary_index { - name = "TestTableLSI" - range_key = "TestLSIRangeKey" - projection_type = "ALL" - } - global_secondary_index { - name = "ReplacementTestTableGSI" - hash_key = "TestTableHashKey" - range_key = "ReplacementGSIRangeKey" - write_capacity = 5 - read_capacity = 5 - projection_type = "INCLUDE" - non_key_attributes = ["TestNonKeyAttribute"] - } + name = "%s" + read_capacity = 20 + write_capacity = 20 + hash_key = "TestTableHashKey" + range_key = "TestTableRangeKey" + + attribute { + name = "TestTableHashKey" + type = "S" + } + + attribute { + name = "TestTableRangeKey" + type = "S" + } + + attribute { + name = "TestLSIRangeKey" + type = "N" + } + + attribute { + name = "ReplacementGSIRangeKey" + type = "N" + } + + local_secondary_index { + name = "TestTableLSI" + range_key = "TestLSIRangeKey" + projection_type = "ALL" + } + + global_secondary_index { + name = "ReplacementTestTableGSI" + hash_key = "TestTableHashKey" + range_key = "ReplacementGSIRangeKey" + write_capacity = 5 + read_capacity = 5 + projection_type = "INCLUDE" + non_key_attributes = ["TestNonKeyAttribute"] + } +}`, rName) } -` func testAccAWSDynamoDbConfigStreamSpecification() string { return fmt.Sprintf(` resource "aws_dynamodb_table" "basic-dynamodb-table" { - name = "TerraformTestStreamTable-%d" - read_capacity = 10 - write_capacity = 20 - hash_key = "TestTableHashKey" - range_key = "TestTableRangeKey" - attribute { - name = "TestTableHashKey" - type = "S" - } - attribute { - name = "TestTableRangeKey" - type = "S" - } - attribute { - name = "TestLSIRangeKey" - type = "N" - } - attribute { - name = "TestGSIRangeKey" - type = "S" - } - local_secondary_index { - name = "TestTableLSI" - range_key = "TestLSIRangeKey" - projection_type = "ALL" - } - global_secondary_index { - name = "InitialTestTableGSI" - hash_key = "TestTableHashKey" - range_key = "TestGSIRangeKey" - write_capacity = 10 - read_capacity = 10 - projection_type = "KEYS_ONLY" - } - stream_enabled = true - stream_view_type = "KEYS_ONLY" + name = "TerraformTestStreamTable-%d" + read_capacity = 10 + write_capacity = 20 + hash_key = "TestTableHashKey" + range_key = "TestTableRangeKey" + + attribute { + name = "TestTableHashKey" + type = "S" + } + + attribute { + name = "TestTableRangeKey" + type = "S" + } + + attribute { + name = "TestLSIRangeKey" + type = "N" + } + + attribute { + name = "TestGSIRangeKey" + type = "S" + } + + local_secondary_index { + name = "TestTableLSI" + range_key = "TestLSIRangeKey" + projection_type = "ALL" + } + + global_secondary_index { + name = "InitialTestTableGSI" + hash_key = "TestTableHashKey" + range_key = "TestGSIRangeKey" + write_capacity = 10 + read_capacity = 10 + projection_type = "KEYS_ONLY" + } + stream_enabled = true + stream_view_type = "KEYS_ONLY" } `, acctest.RandInt()) } @@ -425,45 +576,222 @@ resource "aws_dynamodb_table" "basic-dynamodb-table" { func testAccAWSDynamoDbConfigTags() string { return fmt.Sprintf(` resource "aws_dynamodb_table" "basic-dynamodb-table" { - name = "TerraformTestTable-%d" - read_capacity = 10 - write_capacity = 20 - hash_key = "TestTableHashKey" - range_key = "TestTableRangeKey" - attribute { - name = "TestTableHashKey" - type = "S" - } - attribute { - name = "TestTableRangeKey" - type = "S" - } - attribute { - name = "TestLSIRangeKey" - type = "N" - } - attribute { - name = "TestGSIRangeKey" - type = "S" - } - local_secondary_index { - name = "TestTableLSI" - range_key = "TestLSIRangeKey" - projection_type = "ALL" - } - global_secondary_index { - name = "InitialTestTableGSI" - hash_key = "TestTableHashKey" - range_key = "TestGSIRangeKey" - write_capacity = 10 - read_capacity = 10 - projection_type = "KEYS_ONLY" - } - tags { - Name = "terraform-test-table-%d" - AccTest = "yes" - Testing = "absolutely" - } + name = "TerraformTestTable-%d" + read_capacity = 10 + write_capacity = 20 + hash_key = "TestTableHashKey" + range_key = "TestTableRangeKey" + + attribute { + name = "TestTableHashKey" + type = "S" + } + + attribute { + name = "TestTableRangeKey" + type = "S" + } + + attribute { + name = "TestLSIRangeKey" + type = "N" + } + + attribute { + name = "TestGSIRangeKey" + type = "S" + } + + local_secondary_index { + name = "TestTableLSI" + range_key = "TestLSIRangeKey" + projection_type = "ALL" + } + + global_secondary_index { + name = "InitialTestTableGSI" + hash_key = "TestTableHashKey" + range_key = "TestGSIRangeKey" + write_capacity = 10 + read_capacity = 10 + projection_type = "KEYS_ONLY" + } + + tags { + Name = "terraform-test-table-%d" + AccTest = "yes" + Testing = "absolutely" + } } `, acctest.RandInt(), acctest.RandInt()) } + +func testAccAWSDynamoDbConfigGsiUpdate(name string) string { + return fmt.Sprintf(` +variable "capacity" { + default = 10 +} + +resource "aws_dynamodb_table" "test" { + name = "tf-acc-test-%s" + read_capacity = "${var.capacity}" + write_capacity = "${var.capacity}" + hash_key = "id" + + attribute { + name = "id" + type = "S" + } + + attribute { + name = "att1" + type = "S" + } + + attribute { + name = "att2" + type = "S" + } + + attribute { + name = "att3" + type = "S" + } + + global_secondary_index { + name = "att1-index" + hash_key = "att1" + write_capacity = "${var.capacity}" + read_capacity = "${var.capacity}" + projection_type = "ALL" + } + + global_secondary_index { + name = "att2-index" + hash_key = "att2" + write_capacity = "${var.capacity}" + read_capacity = "${var.capacity}" + projection_type = "ALL" + } + + global_secondary_index { + name = "att3-index" + hash_key = "att3" + write_capacity = "${var.capacity}" + read_capacity = "${var.capacity}" + projection_type = "ALL" + } +} +`, name) +} + +func testAccAWSDynamoDbConfigGsiUpdated(name string) string { + return fmt.Sprintf(` +variable "capacity" { + default = 20 +} + +resource "aws_dynamodb_table" "test" { + name = "tf-acc-test-%s" + read_capacity = "${var.capacity}" + write_capacity = "${var.capacity}" + hash_key = "id" + + attribute { + name = "id" + type = "S" + } + + attribute { + name = "att1" + type = "S" + } + + attribute { + name = "att2" + type = "S" + } + + attribute { + name = "att3" + type = "S" + } + + global_secondary_index { + name = "att1-index" + hash_key = "att1" + write_capacity = "${var.capacity}" + read_capacity = "${var.capacity}" + projection_type = "ALL" + } + + global_secondary_index { + name = "att2-index" + hash_key = "att2" + write_capacity = "${var.capacity}" + read_capacity = "${var.capacity}" + projection_type = "ALL" + } + + global_secondary_index { + name = "att3-index" + hash_key = "att3" + write_capacity = "${var.capacity}" + read_capacity = "${var.capacity}" + projection_type = "ALL" + } +} +`, name) +} + +func testAccAWSDynamoDbConfigAddTimeToLive(rName string) string { + return fmt.Sprintf(` +resource "aws_dynamodb_table" "basic-dynamodb-table" { + name = "%s" + read_capacity = 10 + write_capacity = 20 + hash_key = "TestTableHashKey" + range_key = "TestTableRangeKey" + + attribute { + name = "TestTableHashKey" + type = "S" + } + + attribute { + name = "TestTableRangeKey" + type = "S" + } + + attribute { + name = "TestLSIRangeKey" + type = "N" + } + + attribute { + name = "TestGSIRangeKey" + type = "S" + } + + local_secondary_index { + name = "TestTableLSI" + range_key = "TestLSIRangeKey" + projection_type = "ALL" + } + + ttl { + attribute_name = "TestTTL" + enabled = true + } + + global_secondary_index { + name = "InitialTestTableGSI" + hash_key = "TestTableHashKey" + range_key = "TestGSIRangeKey" + write_capacity = 10 + read_capacity = 10 + projection_type = "KEYS_ONLY" + } +} +`, rName) +} diff --git a/builtin/providers/aws/resource_aws_ebs_volume.go b/builtin/providers/aws/resource_aws_ebs_volume.go index 49d5281a1..1beda135e 100644 --- a/builtin/providers/aws/resource_aws_ebs_volume.go +++ b/builtin/providers/aws/resource_aws_ebs_volume.go @@ -179,7 +179,7 @@ func resourceAWSEbsVolumeUpdate(d *schema.ResourceData, meta interface{}) error stateConf := &resource.StateChangeConf{ Pending: []string{"creating", "modifying"}, - Target: []string{"available"}, + Target: []string{"available", "in-use"}, Refresh: volumeStateRefreshFunc(conn, *result.VolumeModification.VolumeId), Timeout: 5 * time.Minute, Delay: 10 * time.Second, diff --git a/builtin/providers/aws/resource_aws_ebs_volume_test.go b/builtin/providers/aws/resource_aws_ebs_volume_test.go index bb98265a2..1c62247ed 100644 --- a/builtin/providers/aws/resource_aws_ebs_volume_test.go +++ b/builtin/providers/aws/resource_aws_ebs_volume_test.go @@ -30,6 +30,31 @@ func TestAccAWSEBSVolume_basic(t *testing.T) { }) } +func TestAccAWSEBSVolume_updateAttachedEbsVolume(t *testing.T) { + var v ec2.Volume + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + IDRefreshName: "aws_ebs_volume.test", + Providers: testAccProviders, + Steps: []resource.TestStep{ + { + Config: testAccAwsEbsAttachedVolumeConfig, + Check: resource.ComposeTestCheckFunc( + testAccCheckVolumeExists("aws_ebs_volume.test", &v), + resource.TestCheckResourceAttr("aws_ebs_volume.test", "size", "10"), + ), + }, + { + Config: testAccAwsEbsAttachedVolumeConfigUpdateSize, + Check: resource.ComposeTestCheckFunc( + testAccCheckVolumeExists("aws_ebs_volume.test", &v), + resource.TestCheckResourceAttr("aws_ebs_volume.test", "size", "20"), + ), + }, + }, + }) +} + func TestAccAWSEBSVolume_updateSize(t *testing.T) { var v ec2.Volume resource.Test(t, resource.TestCase{ @@ -200,6 +225,124 @@ resource "aws_ebs_volume" "test" { } ` +const testAccAwsEbsAttachedVolumeConfig = ` +data "aws_ami" "debian_jessie_latest" { + most_recent = true + + filter { + name = "name" + values = ["debian-jessie-*"] + } + + filter { + name = "virtualization-type" + values = ["hvm"] + } + + filter { + name = "architecture" + values = ["x86_64"] + } + + filter { + name = "root-device-type" + values = ["ebs"] + } + + owners = ["379101102735"] # Debian +} + +resource "aws_instance" "test" { + ami = "${data.aws_ami.debian_jessie_latest.id}" + associate_public_ip_address = true + count = 1 + instance_type = "t2.medium" + + root_block_device { + volume_size = "10" + volume_type = "standard" + delete_on_termination = true + } + + tags { + Name = "test-terraform" + } +} + +resource "aws_ebs_volume" "test" { + depends_on = ["aws_instance.test"] + availability_zone = "${aws_instance.test.availability_zone}" + type = "gp2" + size = "10" +} + +resource "aws_volume_attachment" "test" { + depends_on = ["aws_ebs_volume.test"] + device_name = "/dev/xvdg" + volume_id = "${aws_ebs_volume.test.id}" + instance_id = "${aws_instance.test.id}" +} +` + +const testAccAwsEbsAttachedVolumeConfigUpdateSize = ` +data "aws_ami" "debian_jessie_latest" { + most_recent = true + + filter { + name = "name" + values = ["debian-jessie-*"] + } + + filter { + name = "virtualization-type" + values = ["hvm"] + } + + filter { + name = "architecture" + values = ["x86_64"] + } + + filter { + name = "root-device-type" + values = ["ebs"] + } + + owners = ["379101102735"] # Debian +} + +resource "aws_instance" "test" { + ami = "${data.aws_ami.debian_jessie_latest.id}" + associate_public_ip_address = true + count = 1 + instance_type = "t2.medium" + + root_block_device { + volume_size = "10" + volume_type = "standard" + delete_on_termination = true + } + + tags { + Name = "test-terraform" + } +} + +resource "aws_ebs_volume" "test" { + depends_on = ["aws_instance.test"] + availability_zone = "${aws_instance.test.availability_zone}" + type = "gp2" + size = "20" +} + +resource "aws_volume_attachment" "test" { + depends_on = ["aws_ebs_volume.test"] + device_name = "/dev/xvdg" + volume_id = "${aws_ebs_volume.test.id}" + instance_id = "${aws_instance.test.id}" +} +` + const testAccAwsEbsVolumeConfigUpdateSize = ` resource "aws_ebs_volume" "test" { availability_zone = "us-west-2a" diff --git a/builtin/providers/aws/resource_aws_ecs_service.go b/builtin/providers/aws/resource_aws_ecs_service.go index f763b08a9..9874effd5 100644 --- a/builtin/providers/aws/resource_aws_ecs_service.go +++ b/builtin/providers/aws/resource_aws_ecs_service.go @@ -118,6 +118,12 @@ func resourceAwsEcsService() *schema.Resource { Type: schema.TypeString, ForceNew: true, Optional: true, + DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool { + if strings.ToLower(old) == strings.ToLower(new) { + return true + } + return false + }, }, }, }, @@ -504,10 +510,15 @@ func resourceAwsEcsServiceDelete(d *schema.ResourceData, meta interface{}) error func resourceAwsEcsLoadBalancerHash(v interface{}) int { var buf bytes.Buffer m := v.(map[string]interface{}) + buf.WriteString(fmt.Sprintf("%s-", m["elb_name"].(string))) buf.WriteString(fmt.Sprintf("%s-", m["container_name"].(string))) buf.WriteString(fmt.Sprintf("%d-", m["container_port"].(int))) + if s := m["target_group_arn"].(string); s != "" { + buf.WriteString(fmt.Sprintf("%s-", s)) + } + return hashcode.String(buf.String()) } diff --git a/builtin/providers/aws/resource_aws_ecs_service_test.go b/builtin/providers/aws/resource_aws_ecs_service_test.go index dab45018a..c3a603547 100644 --- a/builtin/providers/aws/resource_aws_ecs_service_test.go +++ b/builtin/providers/aws/resource_aws_ecs_service_test.go @@ -7,6 +7,7 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/ecs" + "github.com/hashicorp/terraform/helper/acctest" "github.com/hashicorp/terraform/helper/resource" "github.com/hashicorp/terraform/terraform" ) @@ -84,20 +85,21 @@ func TestParseTaskDefinition(t *testing.T) { } func TestAccAWSEcsServiceWithARN(t *testing.T) { + rInt := acctest.RandInt() resource.Test(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, CheckDestroy: testAccCheckAWSEcsServiceDestroy, Steps: []resource.TestStep{ { - Config: testAccAWSEcsService, + Config: testAccAWSEcsService(rInt), Check: resource.ComposeTestCheckFunc( testAccCheckAWSEcsServiceExists("aws_ecs_service.mongo"), ), }, { - Config: testAccAWSEcsServiceModified, + Config: testAccAWSEcsServiceModified(rInt), Check: resource.ComposeTestCheckFunc( testAccCheckAWSEcsServiceExists("aws_ecs_service.mongo"), ), @@ -107,20 +109,21 @@ func TestAccAWSEcsServiceWithARN(t *testing.T) { } func TestAccAWSEcsServiceWithFamilyAndRevision(t *testing.T) { + rName := acctest.RandomWithPrefix("tf-test") resource.Test(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, CheckDestroy: testAccCheckAWSEcsServiceDestroy, Steps: []resource.TestStep{ { - Config: testAccAWSEcsServiceWithFamilyAndRevision, + Config: testAccAWSEcsServiceWithFamilyAndRevision(rName), Check: resource.ComposeTestCheckFunc( testAccCheckAWSEcsServiceExists("aws_ecs_service.jenkins"), ), }, { - Config: testAccAWSEcsServiceWithFamilyAndRevisionModified, + Config: testAccAWSEcsServiceWithFamilyAndRevisionModified(rName), Check: resource.ComposeTestCheckFunc( testAccCheckAWSEcsServiceExists("aws_ecs_service.jenkins"), ), @@ -179,13 +182,14 @@ func TestAccAWSEcsService_withIamRole(t *testing.T) { } func TestAccAWSEcsService_withDeploymentValues(t *testing.T) { + rInt := acctest.RandInt() resource.Test(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, CheckDestroy: testAccCheckAWSEcsServiceDestroy, Steps: []resource.TestStep{ { - Config: testAccAWSEcsServiceWithDeploymentValues, + Config: testAccAWSEcsServiceWithDeploymentValues(rInt), Check: resource.ComposeTestCheckFunc( testAccCheckAWSEcsServiceExists("aws_ecs_service.mongo"), resource.TestCheckResourceAttr( @@ -242,13 +246,15 @@ func TestAccAWSEcsService_withEcsClusterName(t *testing.T) { } func TestAccAWSEcsService_withAlb(t *testing.T) { + rName := acctest.RandomWithPrefix("tf-acc") + resource.Test(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, CheckDestroy: testAccCheckAWSEcsServiceDestroy, Steps: []resource.TestStep{ { - Config: testAccAWSEcsServiceWithAlb, + Config: testAccAWSEcsServiceWithAlb(rName), Check: resource.ComposeTestCheckFunc( testAccCheckAWSEcsServiceExists("aws_ecs_service.with_alb"), ), @@ -258,20 +264,21 @@ func TestAccAWSEcsService_withAlb(t *testing.T) { } func TestAccAWSEcsServiceWithPlacementStrategy(t *testing.T) { + rInt := acctest.RandInt() resource.Test(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, CheckDestroy: testAccCheckAWSEcsServiceDestroy, Steps: []resource.TestStep{ { - Config: testAccAWSEcsService, + Config: testAccAWSEcsService(rInt), Check: resource.ComposeTestCheckFunc( testAccCheckAWSEcsServiceExists("aws_ecs_service.mongo"), resource.TestCheckResourceAttr("aws_ecs_service.mongo", "placement_strategy.#", "0"), ), }, { - Config: testAccAWSEcsServiceWithPlacementStrategy, + Config: testAccAWSEcsServiceWithPlacementStrategy(rInt), Check: resource.ComposeTestCheckFunc( testAccCheckAWSEcsServiceExists("aws_ecs_service.mongo"), resource.TestCheckResourceAttr("aws_ecs_service.mongo", "placement_strategy.#", "1"), @@ -282,13 +289,14 @@ func TestAccAWSEcsServiceWithPlacementStrategy(t *testing.T) { } func TestAccAWSEcsServiceWithPlacementConstraints(t *testing.T) { + rInt := acctest.RandInt() resource.Test(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, CheckDestroy: testAccCheckAWSEcsServiceDestroy, Steps: []resource.TestStep{ { - Config: testAccAWSEcsServiceWithPlacementConstraint, + Config: testAccAWSEcsServiceWithPlacementConstraint(rInt), Check: resource.ComposeTestCheckFunc( testAccCheckAWSEcsServiceExists("aws_ecs_service.mongo"), resource.TestCheckResourceAttr("aws_ecs_service.mongo", "placement_constraints.#", "1"), @@ -299,13 +307,14 @@ func TestAccAWSEcsServiceWithPlacementConstraints(t *testing.T) { } func TestAccAWSEcsServiceWithPlacementConstraints_emptyExpression(t *testing.T) { + rInt := acctest.RandInt() resource.Test(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, CheckDestroy: testAccCheckAWSEcsServiceDestroy, Steps: []resource.TestStep{ { - Config: testAccAWSEcsServiceWithPlacementConstraintEmptyExpression, + Config: testAccAWSEcsServiceWithPlacementConstraintEmptyExpression(rInt), Check: resource.ComposeTestCheckFunc( testAccCheckAWSEcsServiceExists("aws_ecs_service.mongo"), resource.TestCheckResourceAttr("aws_ecs_service.mongo", "placement_constraints.#", "1"), @@ -362,9 +371,10 @@ func testAccCheckAWSEcsServiceExists(name string) resource.TestCheckFunc { } } -var testAccAWSEcsService = ` +func testAccAWSEcsService(rInt int) string { + return fmt.Sprintf(` resource "aws_ecs_cluster" "default" { - name = "terraformecstest1" + name = "terraformecstest%d" } resource "aws_ecs_task_definition" "mongo" { @@ -383,16 +393,18 @@ DEFINITION } resource "aws_ecs_service" "mongo" { - name = "mongodb" + name = "mongodb-%d" cluster = "${aws_ecs_cluster.default.id}" task_definition = "${aws_ecs_task_definition.mongo.arn}" desired_count = 1 } -` +`, rInt, rInt) +} -var testAccAWSEcsServiceModified = ` +func testAccAWSEcsServiceModified(rInt int) string { + return fmt.Sprintf(` resource "aws_ecs_cluster" "default" { - name = "terraformecstest1" + name = "terraformecstest%d" } resource "aws_ecs_task_definition" "mongo" { @@ -411,16 +423,18 @@ DEFINITION } resource "aws_ecs_service" "mongo" { - name = "mongodb" + name = "mongodb-%d" cluster = "${aws_ecs_cluster.default.id}" task_definition = "${aws_ecs_task_definition.mongo.arn}" desired_count = 2 } -` +`, rInt, rInt) +} -var testAccAWSEcsServiceWithPlacementStrategy = ` +func testAccAWSEcsServiceWithPlacementStrategy(rInt int) string { + return fmt.Sprintf(` resource "aws_ecs_cluster" "default" { - name = "terraformecstest1" + name = "terraformecstest%d" } resource "aws_ecs_task_definition" "mongo" { @@ -439,7 +453,7 @@ DEFINITION } resource "aws_ecs_service" "mongo" { - name = "mongodb" + name = "mongodb-%d" cluster = "${aws_ecs_cluster.default.id}" task_definition = "${aws_ecs_task_definition.mongo.arn}" desired_count = 1 @@ -448,43 +462,47 @@ resource "aws_ecs_service" "mongo" { field = "memory" } } -` +`, rInt, rInt) +} -var testAccAWSEcsServiceWithPlacementConstraint = ` +func testAccAWSEcsServiceWithPlacementConstraint(rInt int) string { + return fmt.Sprintf(` + resource "aws_ecs_cluster" "default" { + name = "terraformecstest%d" + } + + resource "aws_ecs_task_definition" "mongo" { + family = "mongodb" + container_definitions = < 10280 { + errors = append(errors, fmt.Errorf( + "%q cannot be longer than 10280 characters", k)) + } + return + }, + }, + "name_prefix": &schema.Schema{ + Type: schema.TypeString, + Optional: true, + ForceNew: true, + ValidateFunc: func(v interface{}, k string) (ws []string, errors []error) { + value := v.(string) + if len(value) > 10000 { + errors = append(errors, fmt.Errorf( + "%q cannot be longer than 10000 characters, name is limited to 10280", k)) + } + return + }, + }, + + "configuration": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + ValidateFunc: validateJsonString, + }, + + "creation_date": { + Type: schema.TypeString, + Computed: true, + }, + }, + } +} + +func resourceAwsEmrSecurityConfigurationCreate(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*AWSClient).emrconn + + var emrSCName string + if v, ok := d.GetOk("name"); ok { + emrSCName = v.(string) + } else { + if v, ok := d.GetOk("name_prefix"); ok { + emrSCName = resource.PrefixedUniqueId(v.(string)) + } else { + emrSCName = resource.PrefixedUniqueId("tf-emr-sc-") + } + } + + resp, err := conn.CreateSecurityConfiguration(&emr.CreateSecurityConfigurationInput{ + Name: aws.String(emrSCName), + SecurityConfiguration: aws.String(d.Get("configuration").(string)), + }) + + if err != nil { + return err + } + + d.SetId(*resp.Name) + return resourceAwsEmrSecurityConfigurationRead(d, meta) +} + +func resourceAwsEmrSecurityConfigurationRead(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*AWSClient).emrconn + + resp, err := conn.DescribeSecurityConfiguration(&emr.DescribeSecurityConfigurationInput{ + Name: aws.String(d.Id()), + }) + if err != nil { + if isAWSErr(err, "InvalidRequestException", "does not exist") { + log.Printf("[WARN] EMR Security Configuraiton (%s) not found, removing from state", d.Id()) + d.SetId("") + return nil + } + return err + } + + d.Set("creation_date", resp.CreationDateTime) + d.Set("name", resp.Name) + d.Set("configuration", resp.SecurityConfiguration) + + return nil +} + +func resourceAwsEmrSecurityConfigurationDelete(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*AWSClient).emrconn + + _, err := conn.DeleteSecurityConfiguration(&emr.DeleteSecurityConfigurationInput{ + Name: aws.String(d.Id()), + }) + if err != nil { + if isAWSErr(err, "InvalidRequestException", "does not exist") { + d.SetId("") + return nil + } + return err + } + d.SetId("") + + return nil +} diff --git a/builtin/providers/aws/resource_aws_emr_security_configuration_test.go b/builtin/providers/aws/resource_aws_emr_security_configuration_test.go new file mode 100644 index 000000000..c17fb806f --- /dev/null +++ b/builtin/providers/aws/resource_aws_emr_security_configuration_test.go @@ -0,0 +1,111 @@ +package aws + +import ( + "fmt" + "testing" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/service/emr" + "github.com/hashicorp/terraform/helper/resource" + "github.com/hashicorp/terraform/terraform" +) + +func TestAccAWSEmrSecurityConfiguration_basic(t *testing.T) { + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckEmrSecurityConfigurationDestroy, + Steps: []resource.TestStep{ + { + Config: testAccEmrSecurityConfigurationConfig, + Check: resource.ComposeTestCheckFunc( + testAccCheckEmrSecurityConfigurationExists("aws_emr_security_configuration.foo"), + ), + }, + }, + }) +} + +func testAccCheckEmrSecurityConfigurationDestroy(s *terraform.State) error { + conn := testAccProvider.Meta().(*AWSClient).emrconn + for _, rs := range s.RootModule().Resources { + if rs.Type != "aws_emr_security_configuration" { + continue + } + + // Try to find the Security Configuration + resp, err := conn.DescribeSecurityConfiguration(&emr.DescribeSecurityConfigurationInput{ + Name: aws.String(rs.Primary.ID), + }) + if err == nil { + if resp.Name != nil && *resp.Name == rs.Primary.ID { + // assume this means the resource still exists + return fmt.Errorf("Error: EMR Security Configuration still exists: %s", *resp.Name) + } + return nil + } + + // Verify the error is what we want + if err != nil { + if isAWSErr(err, "InvalidRequestException", "does not exist") { + return nil + } + return err + } + } + + return nil +} + +func testAccCheckEmrSecurityConfigurationExists(n string) resource.TestCheckFunc { + return func(s *terraform.State) error { + rs, ok := s.RootModule().Resources[n] + if !ok { + return fmt.Errorf("Not found: %s", n) + } + + if rs.Primary.ID == "" { + return fmt.Errorf("No EMR Security Configuration ID is set") + } + + conn := testAccProvider.Meta().(*AWSClient).emrconn + resp, err := conn.DescribeSecurityConfiguration(&emr.DescribeSecurityConfigurationInput{ + Name: aws.String(rs.Primary.ID), + }) + if err != nil { + return err + } + + if resp.Name == nil { + return fmt.Errorf("EMR Security Configuration had nil name which shouldn't happen") + } + + if *resp.Name != rs.Primary.ID { + return fmt.Errorf("EMR Security Configuration name mismatch, got (%s), expected (%s)", *resp.Name, rs.Primary.ID) + } + + return nil + } +} + +const testAccEmrSecurityConfigurationConfig = ` +resource "aws_emr_security_configuration" "foo" { + configuration = < 0 { + d.Set("role", result.Roles[0].RoleName) //there will only be 1 role returned + } + roles := &schema.Set{F: schema.HashString} for _, role := range result.Roles { roles.Add(*role.RoleName) diff --git a/builtin/providers/aws/resource_aws_iam_instance_profile_test.go b/builtin/providers/aws/resource_aws_iam_instance_profile_test.go index 0bd3d5ffb..f60c4584f 100644 --- a/builtin/providers/aws/resource_aws_iam_instance_profile_test.go +++ b/builtin/providers/aws/resource_aws_iam_instance_profile_test.go @@ -2,6 +2,7 @@ package aws import ( "fmt" + "regexp" "strings" "testing" @@ -37,6 +38,8 @@ func TestAccAWSIAMInstanceProfile_importBasic(t *testing.T) { } func TestAccAWSIAMInstanceProfile_basic(t *testing.T) { + var conf iam.GetInstanceProfileOutput + rName := acctest.RandString(5) resource.Test(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, @@ -44,6 +47,41 @@ func TestAccAWSIAMInstanceProfile_basic(t *testing.T) { Steps: []resource.TestStep{ { Config: testAccAwsIamInstanceProfileConfig(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSInstanceProfileExists("aws_iam_instance_profile.test", &conf), + ), + }, + }, + }) +} + +func TestAccAWSIAMInstanceProfile_withRoleNotRoles(t *testing.T) { + var conf iam.GetInstanceProfileOutput + + rName := acctest.RandString(5) + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + Steps: []resource.TestStep{ + { + Config: testAccAWSInstanceProfileWithRoleSpecified(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSInstanceProfileExists("aws_iam_instance_profile.test", &conf), + ), + }, + }, + }) +} + +func TestAccAWSIAMInstanceProfile_missingRoleThrowsError(t *testing.T) { + rName := acctest.RandString(5) + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + Steps: []resource.TestStep{ + { + Config: testAccAwsIamInstanceProfileConfigMissingRole(rName), + ExpectError: regexp.MustCompile(regexp.QuoteMeta("Either `role` or `roles` (deprecated) must be specified when creating an IAM Instance Profile")), }, }, }) @@ -157,6 +195,13 @@ resource "aws_iam_instance_profile" "test" { }`, rName) } +func testAccAwsIamInstanceProfileConfigMissingRole(rName string) string { + return fmt.Sprintf(` +resource "aws_iam_instance_profile" "test" { + name = "test-%s" +}`, rName) +} + func testAccAWSInstanceProfilePrefixNameConfig(rName string) string { return fmt.Sprintf(` resource "aws_iam_role" "test" { @@ -169,3 +214,16 @@ resource "aws_iam_instance_profile" "test" { roles = ["${aws_iam_role.test.name}"] }`, rName) } + +func testAccAWSInstanceProfileWithRoleSpecified(rName string) string { + return fmt.Sprintf(` +resource "aws_iam_role" "test" { + name = "test-%s" + assume_role_policy = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Principal\":{\"Service\":[\"ec2.amazonaws.com\"]},\"Action\":[\"sts:AssumeRole\"]}]}" +} + +resource "aws_iam_instance_profile" "test" { + name_prefix = "test-" + role = "${aws_iam_role.test.name}" +}`, rName) +} diff --git a/builtin/providers/aws/resource_aws_iam_openid_connect_provider.go b/builtin/providers/aws/resource_aws_iam_openid_connect_provider.go new file mode 100644 index 000000000..1791da4ec --- /dev/null +++ b/builtin/providers/aws/resource_aws_iam_openid_connect_provider.go @@ -0,0 +1,141 @@ +package aws + +import ( + "fmt" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/awserr" + "github.com/aws/aws-sdk-go/service/iam" + + "github.com/hashicorp/terraform/helper/schema" +) + +func resourceAwsIamOpenIDConnectProvider() *schema.Resource { + return &schema.Resource{ + Create: resourceAwsIamOpenIDConnectProviderCreate, + Read: resourceAwsIamOpenIDConnectProviderRead, + Update: resourceAwsIamOpenIDConnectProviderUpdate, + Delete: resourceAwsIamOpenIDConnectProviderDelete, + Exists: resourceAwsIamOpenIDConnectProviderExists, + Importer: &schema.ResourceImporter{ + State: schema.ImportStatePassthrough, + }, + + Schema: map[string]*schema.Schema{ + "arn": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + }, + "url": &schema.Schema{ + Type: schema.TypeString, + Computed: false, + Required: true, + ForceNew: true, + ValidateFunc: validateOpenIdURL, + DiffSuppressFunc: suppressOpenIdURL, + }, + "client_id_list": &schema.Schema{ + Elem: &schema.Schema{Type: schema.TypeString}, + Type: schema.TypeList, + Required: true, + ForceNew: true, + }, + "thumbprint_list": &schema.Schema{ + Elem: &schema.Schema{Type: schema.TypeString}, + Type: schema.TypeList, + Required: true, + }, + }, + } +} + +func resourceAwsIamOpenIDConnectProviderCreate(d *schema.ResourceData, meta interface{}) error { + iamconn := meta.(*AWSClient).iamconn + + input := &iam.CreateOpenIDConnectProviderInput{ + Url: aws.String(d.Get("url").(string)), + ClientIDList: expandStringList(d.Get("client_id_list").([]interface{})), + ThumbprintList: expandStringList(d.Get("thumbprint_list").([]interface{})), + } + + out, err := iamconn.CreateOpenIDConnectProvider(input) + if err != nil { + return err + } + + d.SetId(*out.OpenIDConnectProviderArn) + + return resourceAwsIamOpenIDConnectProviderRead(d, meta) +} + +func resourceAwsIamOpenIDConnectProviderRead(d *schema.ResourceData, meta interface{}) error { + iamconn := meta.(*AWSClient).iamconn + + input := &iam.GetOpenIDConnectProviderInput{ + OpenIDConnectProviderArn: aws.String(d.Id()), + } + out, err := iamconn.GetOpenIDConnectProvider(input) + if err != nil { + return err + } + + d.Set("arn", d.Id()) + d.Set("url", out.Url) + d.Set("client_id_list", flattenStringList(out.ClientIDList)) + d.Set("thumbprint_list", flattenStringList(out.ThumbprintList)) + + return nil +} + +func resourceAwsIamOpenIDConnectProviderUpdate(d *schema.ResourceData, meta interface{}) error { + iamconn := meta.(*AWSClient).iamconn + + if d.HasChange("thumbprint_list") { + input := &iam.UpdateOpenIDConnectProviderThumbprintInput{ + OpenIDConnectProviderArn: aws.String(d.Id()), + ThumbprintList: expandStringList(d.Get("thumbprint_list").([]interface{})), + } + + _, err := iamconn.UpdateOpenIDConnectProviderThumbprint(input) + if err != nil { + return err + } + } + + return resourceAwsIamOpenIDConnectProviderRead(d, meta) +} + +func resourceAwsIamOpenIDConnectProviderDelete(d *schema.ResourceData, meta interface{}) error { + iamconn := meta.(*AWSClient).iamconn + + input := &iam.DeleteOpenIDConnectProviderInput{ + OpenIDConnectProviderArn: aws.String(d.Id()), + } + _, err := iamconn.DeleteOpenIDConnectProvider(input) + + if err != nil { + if err, ok := err.(awserr.Error); ok && err.Code() == "NoSuchEntity" { + return nil + } + return fmt.Errorf("Error deleting platform application %s", err) + } + + return nil +} + +func resourceAwsIamOpenIDConnectProviderExists(d *schema.ResourceData, meta interface{}) (bool, error) { + iamconn := meta.(*AWSClient).iamconn + + input := &iam.GetOpenIDConnectProviderInput{ + OpenIDConnectProviderArn: aws.String(d.Id()), + } + _, err := iamconn.GetOpenIDConnectProvider(input) + if err != nil { + if err, ok := err.(awserr.Error); ok && err.Code() == "NoSuchEntity" { + return false, nil + } + return true, err + } + + return true, nil +} diff --git a/builtin/providers/aws/resource_aws_iam_openid_connect_provider_test.go b/builtin/providers/aws/resource_aws_iam_openid_connect_provider_test.go new file mode 100644 index 000000000..6cf10d8b8 --- /dev/null +++ b/builtin/providers/aws/resource_aws_iam_openid_connect_provider_test.go @@ -0,0 +1,187 @@ +package aws + +import ( + "fmt" + "testing" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/awserr" + "github.com/aws/aws-sdk-go/service/iam" + "github.com/hashicorp/terraform/helper/acctest" + "github.com/hashicorp/terraform/helper/resource" + "github.com/hashicorp/terraform/terraform" +) + +func TestAccAWSIAMOpenIDConnectProvider_basic(t *testing.T) { + rString := acctest.RandString(5) + url := "accounts.google.com/" + rString + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckIAMOpenIDConnectProviderDestroy, + Steps: []resource.TestStep{ + resource.TestStep{ + Config: testAccIAMOpenIDConnectProviderConfig(rString), + Check: resource.ComposeTestCheckFunc( + testAccCheckIAMOpenIDConnectProvider("aws_iam_openid_connect_provider.goog"), + resource.TestCheckResourceAttr("aws_iam_openid_connect_provider.goog", "url", url), + resource.TestCheckResourceAttr("aws_iam_openid_connect_provider.goog", "client_id_list.#", "1"), + resource.TestCheckResourceAttr("aws_iam_openid_connect_provider.goog", "client_id_list.0", + "266362248691-re108qaeld573ia0l6clj2i5ac7r7291.apps.googleusercontent.com"), + resource.TestCheckResourceAttr("aws_iam_openid_connect_provider.goog", "thumbprint_list.#", "0"), + ), + }, + resource.TestStep{ + Config: testAccIAMOpenIDConnectProviderConfig_modified(rString), + Check: resource.ComposeTestCheckFunc( + testAccCheckIAMOpenIDConnectProvider("aws_iam_openid_connect_provider.goog"), + resource.TestCheckResourceAttr("aws_iam_openid_connect_provider.goog", "url", url), + resource.TestCheckResourceAttr("aws_iam_openid_connect_provider.goog", "client_id_list.#", "1"), + resource.TestCheckResourceAttr("aws_iam_openid_connect_provider.goog", "client_id_list.0", + "266362248691-re108qaeld573ia0l6clj2i5ac7r7291.apps.googleusercontent.com"), + resource.TestCheckResourceAttr("aws_iam_openid_connect_provider.goog", "thumbprint_list.#", "2"), + resource.TestCheckResourceAttr("aws_iam_openid_connect_provider.goog", "thumbprint_list.0", "cf23df2207d99a74fbe169e3eba035e633b65d94"), + resource.TestCheckResourceAttr("aws_iam_openid_connect_provider.goog", "thumbprint_list.1", "c784713d6f9cb67b55dd84f4e4af7832d42b8f55"), + ), + }, + }, + }) +} + +func TestAccAWSIAMOpenIDConnectProvider_importBasic(t *testing.T) { + resourceName := "aws_iam_openid_connect_provider.goog" + rString := acctest.RandString(5) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckIAMOpenIDConnectProviderDestroy, + Steps: []resource.TestStep{ + resource.TestStep{ + Config: testAccIAMOpenIDConnectProviderConfig_modified(rString), + }, + + resource.TestStep{ + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func TestAccAWSIAMOpenIDConnectProvider_disappears(t *testing.T) { + rString := acctest.RandString(5) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckIAMOpenIDConnectProviderDestroy, + Steps: []resource.TestStep{ + resource.TestStep{ + Config: testAccIAMOpenIDConnectProviderConfig(rString), + Check: resource.ComposeTestCheckFunc( + testAccCheckIAMOpenIDConnectProvider("aws_iam_openid_connect_provider.goog"), + testAccCheckIAMOpenIDConnectProviderDisappears("aws_iam_openid_connect_provider.goog"), + ), + ExpectNonEmptyPlan: true, + }, + }, + }) +} + +func testAccCheckIAMOpenIDConnectProviderDestroy(s *terraform.State) error { + iamconn := testAccProvider.Meta().(*AWSClient).iamconn + + for _, rs := range s.RootModule().Resources { + if rs.Type != "aws_iam_openid_connect_provider" { + continue + } + + input := &iam.GetOpenIDConnectProviderInput{ + OpenIDConnectProviderArn: aws.String(rs.Primary.ID), + } + out, err := iamconn.GetOpenIDConnectProvider(input) + if err != nil { + if iamerr, ok := err.(awserr.Error); ok && iamerr.Code() == "NoSuchEntity" { + // none found, that's good + return nil + } + return fmt.Errorf("Error reading IAM OpenID Connect Provider, out: %s, err: %s", out, err) + } + + if out != nil { + return fmt.Errorf("Found IAM OpenID Connect Provider, expected none: %s", out) + } + } + + return nil +} + +func testAccCheckIAMOpenIDConnectProviderDisappears(id string) resource.TestCheckFunc { + return func(s *terraform.State) error { + rs, ok := s.RootModule().Resources[id] + if !ok { + return fmt.Errorf("Not Found: %s", id) + } + + if rs.Primary.ID == "" { + return fmt.Errorf("No ID is set") + } + + iamconn := testAccProvider.Meta().(*AWSClient).iamconn + _, err := iamconn.DeleteOpenIDConnectProvider(&iam.DeleteOpenIDConnectProviderInput{ + OpenIDConnectProviderArn: aws.String(rs.Primary.ID), + }) + return err + } +} + +func testAccCheckIAMOpenIDConnectProvider(id string) resource.TestCheckFunc { + return func(s *terraform.State) error { + rs, ok := s.RootModule().Resources[id] + if !ok { + return fmt.Errorf("Not Found: %s", id) + } + + if rs.Primary.ID == "" { + return fmt.Errorf("No ID is set") + } + + iamconn := testAccProvider.Meta().(*AWSClient).iamconn + _, err := iamconn.GetOpenIDConnectProvider(&iam.GetOpenIDConnectProviderInput{ + OpenIDConnectProviderArn: aws.String(rs.Primary.ID), + }) + + if err != nil { + return err + } + + return nil + } +} + +func testAccIAMOpenIDConnectProviderConfig(rString string) string { + return fmt.Sprintf(` +resource "aws_iam_openid_connect_provider" "goog" { + url="https://accounts.google.com/%s" + client_id_list = [ + "266362248691-re108qaeld573ia0l6clj2i5ac7r7291.apps.googleusercontent.com" + ] + thumbprint_list = [] +} +`, rString) +} + +func testAccIAMOpenIDConnectProviderConfig_modified(rString string) string { + return fmt.Sprintf(` +resource "aws_iam_openid_connect_provider" "goog" { + url="https://accounts.google.com/%s" + client_id_list = [ + "266362248691-re108qaeld573ia0l6clj2i5ac7r7291.apps.googleusercontent.com" + ] + thumbprint_list = ["cf23df2207d99a74fbe169e3eba035e633b65d94", "c784713d6f9cb67b55dd84f4e4af7832d42b8f55"] +} +`, rString) +} diff --git a/builtin/providers/aws/resource_aws_iam_policy_attachment_test.go b/builtin/providers/aws/resource_aws_iam_policy_attachment_test.go index 58738f4bd..6ae57b1d5 100644 --- a/builtin/providers/aws/resource_aws_iam_policy_attachment_test.go +++ b/builtin/providers/aws/resource_aws_iam_policy_attachment_test.go @@ -43,6 +43,7 @@ func TestAccAWSPolicyAttachment_basic(t *testing.T) { func TestAccAWSPolicyAttachment_paginatedEntities(t *testing.T) { var out iam.ListEntitiesForPolicyOutput + rInt := acctest.RandInt() resource.Test(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, @@ -50,7 +51,7 @@ func TestAccAWSPolicyAttachment_paginatedEntities(t *testing.T) { CheckDestroy: testAccCheckAWSPolicyAttachmentDestroy, Steps: []resource.TestStep{ resource.TestStep{ - Config: testAccAWSPolicyPaginatedAttachConfig, + Config: testAccAWSPolicyPaginatedAttachConfig(rInt), Check: resource.ComposeTestCheckFunc( testAccCheckAWSPolicyAttachmentExists("aws_iam_policy_attachment.test-paginated-attach", 101, &out), ), @@ -302,34 +303,33 @@ resource "aws_iam_policy_attachment" "test-attach" { }`, u1, u2, u3) } -const testAccAWSPolicyPaginatedAttachConfig = ` +func testAccAWSPolicyPaginatedAttachConfig(rInt int) string { + return fmt.Sprintf(` resource "aws_iam_user" "user" { - count = 101 - name = "${format("paged-test-user-%d", count.index + 1)}" + count = 101 + name = "${format("paged-test-user-%d-%%d", count.index + 1)}" } - resource "aws_iam_policy" "policy" { - name = "test-policy" - description = "A test policy" - policy = <:") + err = fmt.Errorf("role_policy id must be of the form :") return } diff --git a/builtin/providers/aws/resource_aws_iam_role_test.go b/builtin/providers/aws/resource_aws_iam_role_test.go index 22ffa8ec3..4bc5b844a 100644 --- a/builtin/providers/aws/resource_aws_iam_role_test.go +++ b/builtin/providers/aws/resource_aws_iam_role_test.go @@ -10,12 +10,14 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/service/iam" + "github.com/hashicorp/terraform/helper/acctest" "github.com/hashicorp/terraform/helper/resource" "github.com/hashicorp/terraform/terraform" ) func TestAccAWSRole_basic(t *testing.T) { var conf iam.GetRoleOutput + rName := acctest.RandString(10) resource.Test(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, @@ -23,13 +25,48 @@ func TestAccAWSRole_basic(t *testing.T) { CheckDestroy: testAccCheckAWSRoleDestroy, Steps: []resource.TestStep{ { - Config: testAccAWSRoleConfig, + Config: testAccAWSRoleConfig(rName), Check: resource.ComposeTestCheckFunc( testAccCheckAWSRoleExists("aws_iam_role.role", &conf), - testAccCheckAWSRoleAttributes(&conf), - resource.TestCheckResourceAttrSet( - "aws_iam_role.role", "create_date", - ), + resource.TestCheckResourceAttr("aws_iam_role.role", "path", "/"), + resource.TestCheckResourceAttrSet("aws_iam_role.role", "create_date"), + ), + }, + }, + }) +} + +func TestAccAWSRole_basicWithDescription(t *testing.T) { + var conf iam.GetRoleOutput + rName := acctest.RandString(10) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSRoleDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAWSRoleConfigWithDescription(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSRoleExists("aws_iam_role.role", &conf), + resource.TestCheckResourceAttr("aws_iam_role.role", "path", "/"), + resource.TestCheckResourceAttr("aws_iam_role.role", "description", "This 1s a D3scr!pti0n with weird content: &@90ë“‘{«¡Çø}"), + ), + }, + { + Config: testAccAWSRoleConfigWithUpdatedDescription(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSRoleExists("aws_iam_role.role", &conf), + resource.TestCheckResourceAttr("aws_iam_role.role", "path", "/"), + resource.TestCheckResourceAttr("aws_iam_role.role", "description", "This 1s an Upd@ted D3scr!pti0n with weird content: &90ë“‘{«¡Çø}"), + ), + }, + { + Config: testAccAWSRoleConfig(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSRoleExists("aws_iam_role.role", &conf), + resource.TestCheckResourceAttrSet("aws_iam_role.role", "create_date"), + resource.TestCheckResourceAttr("aws_iam_role.role", "description", ""), ), }, }, @@ -38,6 +75,7 @@ func TestAccAWSRole_basic(t *testing.T) { func TestAccAWSRole_namePrefix(t *testing.T) { var conf iam.GetRoleOutput + rName := acctest.RandString(10) resource.Test(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, @@ -47,7 +85,7 @@ func TestAccAWSRole_namePrefix(t *testing.T) { CheckDestroy: testAccCheckAWSRoleDestroy, Steps: []resource.TestStep{ { - Config: testAccAWSRolePrefixNameConfig, + Config: testAccAWSRolePrefixNameConfig(rName), Check: resource.ComposeTestCheckFunc( testAccCheckAWSRoleExists("aws_iam_role.role", &conf), testAccCheckAWSRoleGeneratedNamePrefix( @@ -60,6 +98,7 @@ func TestAccAWSRole_namePrefix(t *testing.T) { func TestAccAWSRole_testNameChange(t *testing.T) { var conf iam.GetRoleOutput + rName := acctest.RandString(10) resource.Test(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, @@ -67,14 +106,14 @@ func TestAccAWSRole_testNameChange(t *testing.T) { CheckDestroy: testAccCheckAWSRoleDestroy, Steps: []resource.TestStep{ { - Config: testAccAWSRolePre, + Config: testAccAWSRolePre(rName), Check: resource.ComposeTestCheckFunc( testAccCheckAWSRoleExists("aws_iam_role.role_update_test", &conf), ), }, { - Config: testAccAWSRolePost, + Config: testAccAWSRolePost(rName), Check: resource.ComposeTestCheckFunc( testAccCheckAWSRoleExists("aws_iam_role.role_update_test", &conf), ), @@ -84,13 +123,15 @@ func TestAccAWSRole_testNameChange(t *testing.T) { } func TestAccAWSRole_badJSON(t *testing.T) { + rName := acctest.RandString(10) + resource.Test(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, CheckDestroy: testAccCheckAWSRoleDestroy, Steps: []resource.TestStep{ { - Config: testAccAWSRoleConfig_badJson, + Config: testAccAWSRoleConfig_badJson(rName), ExpectError: regexp.MustCompile(`.*contains an invalid JSON:.*`), }, }, @@ -169,38 +210,52 @@ func testAccCheckAWSRoleGeneratedNamePrefix(resource, prefix string) resource.Te } } -func testAccCheckAWSRoleAttributes(role *iam.GetRoleOutput) resource.TestCheckFunc { - return func(s *terraform.State) error { - if *role.Role.RoleName != "test-role" { - return fmt.Errorf("Bad name: %s", *role.Role.RoleName) - } - - if *role.Role.Path != "/" { - return fmt.Errorf("Bad path: %s", *role.Role.Path) - } - return nil - } -} - -const testAccAWSRoleConfig = ` +func testAccAWSRoleConfig(rName string) string { + return fmt.Sprintf(` resource "aws_iam_role" "role" { - name = "test-role" + name = "test-role-%s" path = "/" assume_role_policy = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Principal\":{\"Service\":[\"ec2.amazonaws.com\"]},\"Action\":[\"sts:AssumeRole\"]}]}" } -` +`, rName) +} -const testAccAWSRolePrefixNameConfig = ` +func testAccAWSRoleConfigWithDescription(rName string) string { + return fmt.Sprintf(` resource "aws_iam_role" "role" { - name_prefix = "test-role-" + name = "test-role-%s" + description = "This 1s a D3scr!pti0n with weird content: &@90ë“‘{«¡Çø}" path = "/" assume_role_policy = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Principal\":{\"Service\":[\"ec2.amazonaws.com\"]},\"Action\":[\"sts:AssumeRole\"]}]}" } -` +`, rName) +} -const testAccAWSRolePre = ` +func testAccAWSRoleConfigWithUpdatedDescription(rName string) string { + return fmt.Sprintf(` +resource "aws_iam_role" "role" { + name = "test-role-%s" + description = "This 1s an Upd@ted D3scr!pti0n with weird content: &90ë“‘{«¡Çø}" + path = "/" + assume_role_policy = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Principal\":{\"Service\":[\"ec2.amazonaws.com\"]},\"Action\":[\"sts:AssumeRole\"]}]}" +} +`, rName) +} + +func testAccAWSRolePrefixNameConfig(rName string) string { + return fmt.Sprintf(` +resource "aws_iam_role" "role" { + name_prefix = "test-role-%s" + path = "/" + assume_role_policy = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Principal\":{\"Service\":[\"ec2.amazonaws.com\"]},\"Action\":[\"sts:AssumeRole\"]}]}" +} +`, rName) +} + +func testAccAWSRolePre(rName string) string { + return fmt.Sprintf(` resource "aws_iam_role" "role_update_test" { - name = "tf_old_name" + name = "tf_old_name_%s" path = "/test/" assume_role_policy = < 0 { + runOpts.TagSpecifications = tagsSpec + } + } + // Create the instance log.Printf("[DEBUG] Run configuration: %s", runOpts) @@ -444,7 +523,7 @@ func resourceAwsInstanceCreate(d *schema.ResourceData, meta interface{}) error { stateConf := &resource.StateChangeConf{ Pending: []string{"pending"}, Target: []string{"running"}, - Refresh: InstanceStateRefreshFunc(conn, *instance.InstanceId), + Refresh: InstanceStateRefreshFunc(conn, *instance.InstanceId, "terminated"), Timeout: 10 * time.Minute, Delay: 10 * time.Second, MinTimeout: 3 * time.Second, @@ -528,23 +607,63 @@ func resourceAwsInstanceRead(d *schema.ResourceData, meta interface{}) error { d.Set("private_ip", instance.PrivateIpAddress) d.Set("iam_instance_profile", iamInstanceProfileArnToName(instance.IamInstanceProfile)) + // Set configured Network Interface Device Index Slice + // We only want to read, and populate state for the configured network_interface attachments. Otherwise, other + // resources have the potential to attach network interfaces to the instance, and cause a perpetual create/destroy + // diff. We should only read on changes configured for this specific resource because of this. + var configuredDeviceIndexes []int + if v, ok := d.GetOk("network_interface"); ok { + vL := v.(*schema.Set).List() + for _, vi := range vL { + mVi := vi.(map[string]interface{}) + configuredDeviceIndexes = append(configuredDeviceIndexes, mVi["device_index"].(int)) + } + } + var ipv6Addresses []string if len(instance.NetworkInterfaces) > 0 { - for _, ni := range instance.NetworkInterfaces { - if *ni.Attachment.DeviceIndex == 0 { - d.Set("subnet_id", ni.SubnetId) - d.Set("network_interface_id", ni.NetworkInterfaceId) - d.Set("associate_public_ip_address", ni.Association != nil) - d.Set("ipv6_address_count", len(ni.Ipv6Addresses)) - - for _, address := range ni.Ipv6Addresses { - ipv6Addresses = append(ipv6Addresses, *address.Ipv6Address) + var primaryNetworkInterface ec2.InstanceNetworkInterface + var networkInterfaces []map[string]interface{} + for _, iNi := range instance.NetworkInterfaces { + ni := make(map[string]interface{}) + if *iNi.Attachment.DeviceIndex == 0 { + primaryNetworkInterface = *iNi + } + // If the attached network device is inside our configuration, refresh state with values found. + // Otherwise, assume the network device was attached via an outside resource. + for _, index := range configuredDeviceIndexes { + if index == int(*iNi.Attachment.DeviceIndex) { + ni["device_index"] = *iNi.Attachment.DeviceIndex + ni["network_interface_id"] = *iNi.NetworkInterfaceId + ni["delete_on_termination"] = *iNi.Attachment.DeleteOnTermination } } + // Don't add empty network interfaces to schema + if len(ni) == 0 { + continue + } + networkInterfaces = append(networkInterfaces, ni) } + if err := d.Set("network_interface", networkInterfaces); err != nil { + return fmt.Errorf("Error setting network_interfaces: %v", err) + } + + // Set primary network interface details + d.Set("subnet_id", primaryNetworkInterface.SubnetId) + d.Set("network_interface_id", primaryNetworkInterface.NetworkInterfaceId) // TODO: Deprecate me v0.10.0 + d.Set("primary_network_interface_id", primaryNetworkInterface.NetworkInterfaceId) + d.Set("associate_public_ip_address", primaryNetworkInterface.Association != nil) + d.Set("ipv6_address_count", len(primaryNetworkInterface.Ipv6Addresses)) + d.Set("source_dest_check", *primaryNetworkInterface.SourceDestCheck) + + for _, address := range primaryNetworkInterface.Ipv6Addresses { + ipv6Addresses = append(ipv6Addresses, *address.Ipv6Address) + } + } else { d.Set("subnet_id", instance.SubnetId) - d.Set("network_interface_id", "") + d.Set("network_interface_id", "") // TODO: Deprecate me v0.10.0 + d.Set("primary_network_interface_id", "") } if err := d.Set("ipv6_addresses", ipv6Addresses); err != nil { @@ -563,6 +682,10 @@ func resourceAwsInstanceRead(d *schema.ResourceData, meta interface{}) error { d.Set("tags", tagsToMap(instance.Tags)) + if err := readVolumeTags(conn, d); err != nil { + return err + } + if err := readSecurityGroups(d, instance); err != nil { return err } @@ -605,16 +728,32 @@ func resourceAwsInstanceUpdate(d *schema.ResourceData, meta interface{}) error { conn := meta.(*AWSClient).ec2conn d.Partial(true) - if err := setTags(conn, d); err != nil { - return err - } else { - d.SetPartial("tags") + + restricted := meta.(*AWSClient).IsGovCloud() || meta.(*AWSClient).IsChinaCloud() + + if d.HasChange("tags") { + if !d.IsNewResource() || !restricted { + if err := setTags(conn, d); err != nil { + return err + } else { + d.SetPartial("tags") + } + } + } + if d.HasChange("volume_tags") { + if !d.IsNewResource() || !restricted { + if err := setVolumeTags(conn, d); err != nil { + return err + } else { + d.SetPartial("volume_tags") + } + } } if d.HasChange("iam_instance_profile") && !d.IsNewResource() { request := &ec2.DescribeIamInstanceProfileAssociationsInput{ Filters: []*ec2.Filter{ - &ec2.Filter{ + { Name: aws.String("instance-id"), Values: []*string{aws.String(d.Id())}, }, @@ -671,24 +810,28 @@ func resourceAwsInstanceUpdate(d *schema.ResourceData, meta interface{}) error { } } - if d.HasChange("source_dest_check") || d.IsNewResource() { - // SourceDestCheck can only be set on VPC instances // AWS will return an error of InvalidParameterCombination if we attempt - // to modify the source_dest_check of an instance in EC2 Classic - log.Printf("[INFO] Modifying `source_dest_check` on Instance %s", d.Id()) - _, err := conn.ModifyInstanceAttribute(&ec2.ModifyInstanceAttributeInput{ - InstanceId: aws.String(d.Id()), - SourceDestCheck: &ec2.AttributeBooleanValue{ - Value: aws.Bool(d.Get("source_dest_check").(bool)), - }, - }) - if err != nil { - if ec2err, ok := err.(awserr.Error); ok { - // Toloerate InvalidParameterCombination error in Classic, otherwise - // return the error - if "InvalidParameterCombination" != ec2err.Code() { - return err + // SourceDestCheck can only be modified on an instance without manually specified network interfaces. + // SourceDestCheck, in that case, is configured at the network interface level + if _, ok := d.GetOk("network_interface"); !ok { + if d.HasChange("source_dest_check") || d.IsNewResource() { + // SourceDestCheck can only be set on VPC instances // AWS will return an error of InvalidParameterCombination if we attempt + // to modify the source_dest_check of an instance in EC2 Classic + log.Printf("[INFO] Modifying `source_dest_check` on Instance %s", d.Id()) + _, err := conn.ModifyInstanceAttribute(&ec2.ModifyInstanceAttributeInput{ + InstanceId: aws.String(d.Id()), + SourceDestCheck: &ec2.AttributeBooleanValue{ + Value: aws.Bool(d.Get("source_dest_check").(bool)), + }, + }) + if err != nil { + if ec2err, ok := err.(awserr.Error); ok { + // Tolerate InvalidParameterCombination error in Classic, otherwise + // return the error + if "InvalidParameterCombination" != ec2err.Code() { + return err + } + log.Printf("[WARN] Attempted to modify SourceDestCheck on non VPC instance: %s", ec2err.Message()) } - log.Printf("[WARN] Attempted to modify SourceDestCheck on non VPC instance: %s", ec2err.Message()) } } } @@ -700,13 +843,39 @@ func resourceAwsInstanceUpdate(d *schema.ResourceData, meta interface{}) error { groups = append(groups, aws.String(v.(string))) } } - _, err := conn.ModifyInstanceAttribute(&ec2.ModifyInstanceAttributeInput{ - InstanceId: aws.String(d.Id()), - Groups: groups, + // If a user has multiple network interface attachments on the target EC2 instance, simply modifying the + // instance attributes via a `ModifyInstanceAttributes()` request would fail with the following error message: + // "There are multiple interfaces attached to instance 'i-XX'. Please specify an interface ID for the operation instead." + // Thus, we need to actually modify the primary network interface for the new security groups, as the primary + // network interface is where we modify/create security group assignments during Create. + log.Printf("[INFO] Modifying `vpc_security_group_ids` on Instance %q", d.Id()) + instances, err := conn.DescribeInstances(&ec2.DescribeInstancesInput{ + InstanceIds: []*string{aws.String(d.Id())}, }) if err != nil { return err } + instance := instances.Reservations[0].Instances[0] + var primaryInterface ec2.InstanceNetworkInterface + for _, ni := range instance.NetworkInterfaces { + if *ni.Attachment.DeviceIndex == 0 { + primaryInterface = *ni + } + } + + if primaryInterface.NetworkInterfaceId == nil { + log.Print("[Error] Attempted to set vpc_security_group_ids on an instance without a primary network interface") + return fmt.Errorf( + "Failed to update vpc_security_group_ids on %q, which does not contain a primary network interface", + d.Id()) + } + + if _, err := conn.ModifyNetworkInterfaceAttribute(&ec2.ModifyNetworkInterfaceAttributeInput{ + NetworkInterfaceId: primaryInterface.NetworkInterfaceId, + Groups: groups, + }); err != nil { + return err + } } if d.HasChange("instance_type") && !d.IsNewResource() { @@ -718,7 +887,7 @@ func resourceAwsInstanceUpdate(d *schema.ResourceData, meta interface{}) error { stateConf := &resource.StateChangeConf{ Pending: []string{"pending", "running", "shutting-down", "stopped", "stopping"}, Target: []string{"stopped"}, - Refresh: InstanceStateRefreshFunc(conn, d.Id()), + Refresh: InstanceStateRefreshFunc(conn, d.Id(), ""), Timeout: 10 * time.Minute, Delay: 10 * time.Second, MinTimeout: 3 * time.Second, @@ -749,7 +918,7 @@ func resourceAwsInstanceUpdate(d *schema.ResourceData, meta interface{}) error { stateConf = &resource.StateChangeConf{ Pending: []string{"pending", "stopped"}, Target: []string{"running"}, - Refresh: InstanceStateRefreshFunc(conn, d.Id()), + Refresh: InstanceStateRefreshFunc(conn, d.Id(), "terminated"), Timeout: 10 * time.Minute, Delay: 10 * time.Second, MinTimeout: 3 * time.Second, @@ -827,7 +996,7 @@ func resourceAwsInstanceDelete(d *schema.ResourceData, meta interface{}) error { // InstanceStateRefreshFunc returns a resource.StateRefreshFunc that is used to watch // an EC2 instance. -func InstanceStateRefreshFunc(conn *ec2.EC2, instanceID string) resource.StateRefreshFunc { +func InstanceStateRefreshFunc(conn *ec2.EC2, instanceID, failState string) resource.StateRefreshFunc { return func() (interface{}, string, error) { resp, err := conn.DescribeInstances(&ec2.DescribeInstancesInput{ InstanceIds: []*string{aws.String(instanceID)}, @@ -849,10 +1018,29 @@ func InstanceStateRefreshFunc(conn *ec2.EC2, instanceID string) resource.StateRe } i := resp.Reservations[0].Instances[0] - return i, *i.State.Name, nil + state := *i.State.Name + + if state == failState { + return i, state, fmt.Errorf("Failed to reach target state. Reason: %s", + stringifyStateReason(i.StateReason)) + + } + + return i, state, nil } } +func stringifyStateReason(sr *ec2.StateReason) string { + if sr.Message != nil { + return *sr.Message + } + if sr.Code != nil { + return *sr.Code + } + + return sr.String() +} + func readBlockDevices(d *schema.ResourceData, instance *ec2.Instance, conn *ec2.EC2) error { ibds, err := readBlockDevicesFromInstance(instance, conn) if err != nil { @@ -1008,6 +1196,55 @@ func fetchRootDeviceName(ami string, conn *ec2.EC2) (*string, error) { return rootDeviceName, nil } +func buildNetworkInterfaceOpts(d *schema.ResourceData, groups []*string, nInterfaces interface{}) []*ec2.InstanceNetworkInterfaceSpecification { + networkInterfaces := []*ec2.InstanceNetworkInterfaceSpecification{} + // Get necessary items + associatePublicIPAddress := d.Get("associate_public_ip_address").(bool) + subnet, hasSubnet := d.GetOk("subnet_id") + + if hasSubnet && associatePublicIPAddress { + // If we have a non-default VPC / Subnet specified, we can flag + // AssociatePublicIpAddress to get a Public IP assigned. By default these are not provided. + // You cannot specify both SubnetId and the NetworkInterface.0.* parameters though, otherwise + // you get: Network interfaces and an instance-level subnet ID may not be specified on the same request + // You also need to attach Security Groups to the NetworkInterface instead of the instance, + // to avoid: Network interfaces and an instance-level security groups may not be specified on + // the same request + ni := &ec2.InstanceNetworkInterfaceSpecification{ + AssociatePublicIpAddress: aws.Bool(associatePublicIPAddress), + DeviceIndex: aws.Int64(int64(0)), + SubnetId: aws.String(subnet.(string)), + Groups: groups, + } + + if v, ok := d.GetOk("private_ip"); ok { + ni.PrivateIpAddress = aws.String(v.(string)) + } + + if v := d.Get("vpc_security_group_ids").(*schema.Set); v.Len() > 0 { + for _, v := range v.List() { + ni.Groups = append(ni.Groups, aws.String(v.(string))) + } + } + + networkInterfaces = append(networkInterfaces, ni) + } else { + // If we have manually specified network interfaces, build and attach those here. + vL := nInterfaces.(*schema.Set).List() + for _, v := range vL { + ini := v.(map[string]interface{}) + ni := &ec2.InstanceNetworkInterfaceSpecification{ + DeviceIndex: aws.Int64(int64(ini["device_index"].(int))), + NetworkInterfaceId: aws.String(ini["network_interface_id"].(string)), + DeleteOnTermination: aws.Bool(ini["delete_on_termination"].(bool)), + } + networkInterfaces = append(networkInterfaces, ni) + } + } + + return networkInterfaces +} + func readBlockDeviceMappingsFromConfig( d *schema.ResourceData, conn *ec2.EC2) ([]*ec2.BlockDeviceMapping, error) { blockDevices := make([]*ec2.BlockDeviceMapping, 0) @@ -1125,6 +1362,39 @@ func readBlockDeviceMappingsFromConfig( return blockDevices, nil } +func readVolumeTags(conn *ec2.EC2, d *schema.ResourceData) error { + volumeIds, err := getAwsInstanceVolumeIds(conn, d) + if err != nil { + return err + } + + tagsResp, err := conn.DescribeTags(&ec2.DescribeTagsInput{ + Filters: []*ec2.Filter{ + { + Name: aws.String("resource-id"), + Values: volumeIds, + }, + }, + }) + if err != nil { + return err + } + + var tags []*ec2.Tag + + for _, t := range tagsResp.Tags { + tag := &ec2.Tag{ + Key: t.Key, + Value: t.Value, + } + tags = append(tags, tag) + } + + d.Set("volume_tags", tagsToMap(tags)) + + return nil +} + // Determine whether we're referring to security groups with // IDs or names. We use a heuristic to figure this out. By default, // we use IDs if we're in a VPC. However, if we previously had an @@ -1260,33 +1530,14 @@ func buildAwsInstanceOpts( } } - if hasSubnet && associatePublicIPAddress { - // If we have a non-default VPC / Subnet specified, we can flag - // AssociatePublicIpAddress to get a Public IP assigned. By default these are not provided. - // You cannot specify both SubnetId and the NetworkInterface.0.* parameters though, otherwise - // you get: Network interfaces and an instance-level subnet ID may not be specified on the same request - // You also need to attach Security Groups to the NetworkInterface instead of the instance, - // to avoid: Network interfaces and an instance-level security groups may not be specified on - // the same request - ni := &ec2.InstanceNetworkInterfaceSpecification{ - AssociatePublicIpAddress: aws.Bool(associatePublicIPAddress), - DeviceIndex: aws.Int64(int64(0)), - SubnetId: aws.String(subnetID), - Groups: groups, - } + networkInterfaces, interfacesOk := d.GetOk("network_interface") - if v, ok := d.GetOk("private_ip"); ok { - ni.PrivateIpAddress = aws.String(v.(string)) - } - - if v := d.Get("vpc_security_group_ids").(*schema.Set); v.Len() > 0 { - for _, v := range v.List() { - ni.Groups = append(ni.Groups, aws.String(v.(string))) - } - } - - opts.NetworkInterfaces = []*ec2.InstanceNetworkInterfaceSpecification{ni} + // If setting subnet and public address, OR manual network interfaces, populate those now. + if hasSubnet && associatePublicIPAddress || interfacesOk { + // Otherwise we're attaching (a) network interface(s) + opts.NetworkInterfaces = buildNetworkInterfaceOpts(d, groups, networkInterfaces) } else { + // If simply specifying a subnetID, privateIP, Security Groups, or VPC Security Groups, build these now if subnetID != "" { opts.SubnetID = aws.String(subnetID) } @@ -1319,7 +1570,6 @@ func buildAwsInstanceOpts( if len(blockDevices) > 0 { opts.BlockDeviceMappings = blockDevices } - return opts, nil } @@ -1337,7 +1587,7 @@ func awsTerminateInstance(conn *ec2.EC2, id string) error { stateConf := &resource.StateChangeConf{ Pending: []string{"pending", "running", "shutting-down", "stopped", "stopping"}, Target: []string{"terminated"}, - Refresh: InstanceStateRefreshFunc(conn, id), + Refresh: InstanceStateRefreshFunc(conn, id, ""), Timeout: 10 * time.Minute, Delay: 10 * time.Second, MinTimeout: 3 * time.Second, @@ -1372,3 +1622,27 @@ func userDataHashSum(user_data string) string { hash := sha1.Sum(v) return hex.EncodeToString(hash[:]) } + +func getAwsInstanceVolumeIds(conn *ec2.EC2, d *schema.ResourceData) ([]*string, error) { + volumeIds := make([]*string, 0) + + opts := &ec2.DescribeVolumesInput{ + Filters: []*ec2.Filter{ + { + Name: aws.String("attachment.instance-id"), + Values: []*string{aws.String(d.Id())}, + }, + }, + } + + resp, err := conn.DescribeVolumes(opts) + if err != nil { + return nil, err + } + + for _, v := range resp.Volumes { + volumeIds = append(volumeIds, v.VolumeId) + } + + return volumeIds, nil +} diff --git a/builtin/providers/aws/resource_aws_instance_migrate.go b/builtin/providers/aws/resource_aws_instance_migrate.go index 28a256b7b..31f28b39f 100644 --- a/builtin/providers/aws/resource_aws_instance_migrate.go +++ b/builtin/providers/aws/resource_aws_instance_migrate.go @@ -15,13 +15,13 @@ func resourceAwsInstanceMigrateState( switch v { case 0: log.Println("[INFO] Found AWS Instance State v0; migrating to v1") - return migrateStateV0toV1(is) + return migrateAwsInstanceStateV0toV1(is) default: return is, fmt.Errorf("Unexpected schema version: %d", v) } } -func migrateStateV0toV1(is *terraform.InstanceState) (*terraform.InstanceState, error) { +func migrateAwsInstanceStateV0toV1(is *terraform.InstanceState) (*terraform.InstanceState, error) { if is.Empty() || is.Attributes == nil { log.Println("[DEBUG] Empty InstanceState; nothing to migrate.") return is, nil diff --git a/builtin/providers/aws/resource_aws_instance_test.go b/builtin/providers/aws/resource_aws_instance_test.go index 2b835f6d7..e8f93547e 100644 --- a/builtin/providers/aws/resource_aws_instance_test.go +++ b/builtin/providers/aws/resource_aws_instance_test.go @@ -3,6 +3,7 @@ package aws import ( "fmt" "reflect" + "regexp" "testing" "github.com/aws/aws-sdk-go/aws" @@ -522,6 +523,21 @@ func TestAccAWSInstance_ipv6_supportAddressCount(t *testing.T) { }) } +func TestAccAWSInstance_ipv6AddressCountAndSingleAddressCausesError(t *testing.T) { + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckInstanceDestroy, + Steps: []resource.TestStep{ + { + Config: testAccInstanceConfigIpv6ErrorConfig, + ExpectError: regexp.MustCompile("Only 1 of `ipv6_address_count` or `ipv6_addresses` can be specified"), + }, + }, + }) +} + func TestAccAWSInstance_multipleRegions(t *testing.T) { var v ec2.Instance @@ -616,7 +632,6 @@ func TestAccAWSInstance_tags(t *testing.T) { testAccCheckTags(&v.Tags, "#", ""), ), }, - { Config: testAccCheckInstanceConfigTagsUpdate, Check: resource.ComposeTestCheckFunc( @@ -629,6 +644,75 @@ func TestAccAWSInstance_tags(t *testing.T) { }) } +func TestAccAWSInstance_volumeTags(t *testing.T) { + var v ec2.Instance + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckInstanceDestroy, + Steps: []resource.TestStep{ + { + Config: testAccCheckInstanceConfigNoVolumeTags, + Check: resource.ComposeTestCheckFunc( + testAccCheckInstanceExists("aws_instance.foo", &v), + resource.TestCheckNoResourceAttr( + "aws_instance.foo", "volume_tags"), + ), + }, + { + Config: testAccCheckInstanceConfigWithVolumeTags, + Check: resource.ComposeTestCheckFunc( + testAccCheckInstanceExists("aws_instance.foo", &v), + resource.TestCheckResourceAttr( + "aws_instance.foo", "volume_tags.%", "1"), + resource.TestCheckResourceAttr( + "aws_instance.foo", "volume_tags.Name", "acceptance-test-volume-tag"), + ), + }, + { + Config: testAccCheckInstanceConfigWithVolumeTagsUpdate, + Check: resource.ComposeTestCheckFunc( + testAccCheckInstanceExists("aws_instance.foo", &v), + resource.TestCheckResourceAttr( + "aws_instance.foo", "volume_tags.%", "2"), + resource.TestCheckResourceAttr( + "aws_instance.foo", "volume_tags.Name", "acceptance-test-volume-tag"), + resource.TestCheckResourceAttr( + "aws_instance.foo", "volume_tags.Environment", "dev"), + ), + }, + { + Config: testAccCheckInstanceConfigNoVolumeTags, + Check: resource.ComposeTestCheckFunc( + testAccCheckInstanceExists("aws_instance.foo", &v), + resource.TestCheckNoResourceAttr( + "aws_instance.foo", "volume_tags"), + ), + }, + }, + }) +} + +func TestAccAWSInstance_volumeTagsComputed(t *testing.T) { + var v ec2.Instance + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckInstanceDestroy, + Steps: []resource.TestStep{ + { + Config: testAccCheckInstanceConfigWithAttachedVolume, + Check: resource.ComposeTestCheckFunc( + testAccCheckInstanceExists("aws_instance.foo", &v), + ), + ExpectNonEmptyPlan: false, + }, + }, + }) +} + func TestAccAWSInstance_instanceProfileChange(t *testing.T) { var v ec2.Instance rName := acctest.RandString(5) @@ -776,6 +860,8 @@ func TestAccAWSInstance_keyPairCheck(t *testing.T) { } } + keyPairName := fmt.Sprintf("tf-acc-test-%s", acctest.RandString(5)) + resource.Test(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, IDRefreshName: "aws_instance.foo", @@ -784,10 +870,10 @@ func TestAccAWSInstance_keyPairCheck(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfigKeyPair, + Config: testAccInstanceConfigKeyPair(keyPairName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists("aws_instance.foo", &v), - testCheckKeyPair("tmp-key"), + testCheckKeyPair(keyPairName), ), }, }, @@ -877,6 +963,107 @@ func TestAccAWSInstance_changeInstanceType(t *testing.T) { }) } +func TestAccAWSInstance_primaryNetworkInterface(t *testing.T) { + var instance ec2.Instance + var ini ec2.NetworkInterface + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckInstanceDestroy, + Steps: []resource.TestStep{ + { + Config: testAccInstanceConfigPrimaryNetworkInterface, + Check: resource.ComposeTestCheckFunc( + testAccCheckInstanceExists("aws_instance.foo", &instance), + testAccCheckAWSENIExists("aws_network_interface.bar", &ini), + resource.TestCheckResourceAttr("aws_instance.foo", "network_interface.#", "1"), + ), + }, + }, + }) +} + +func TestAccAWSInstance_primaryNetworkInterfaceSourceDestCheck(t *testing.T) { + var instance ec2.Instance + var ini ec2.NetworkInterface + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckInstanceDestroy, + Steps: []resource.TestStep{ + { + Config: testAccInstanceConfigPrimaryNetworkInterfaceSourceDestCheck, + Check: resource.ComposeTestCheckFunc( + testAccCheckInstanceExists("aws_instance.foo", &instance), + testAccCheckAWSENIExists("aws_network_interface.bar", &ini), + resource.TestCheckResourceAttr("aws_instance.foo", "source_dest_check", "false"), + ), + }, + }, + }) +} + +func TestAccAWSInstance_addSecondaryInterface(t *testing.T) { + var before ec2.Instance + var after ec2.Instance + var iniPrimary ec2.NetworkInterface + var iniSecondary ec2.NetworkInterface + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckInstanceDestroy, + Steps: []resource.TestStep{ + { + Config: testAccInstanceConfigAddSecondaryNetworkInterfaceBefore, + Check: resource.ComposeTestCheckFunc( + testAccCheckInstanceExists("aws_instance.foo", &before), + testAccCheckAWSENIExists("aws_network_interface.primary", &iniPrimary), + resource.TestCheckResourceAttr("aws_instance.foo", "network_interface.#", "1"), + ), + }, + { + Config: testAccInstanceConfigAddSecondaryNetworkInterfaceAfter, + Check: resource.ComposeTestCheckFunc( + testAccCheckInstanceExists("aws_instance.foo", &after), + testAccCheckAWSENIExists("aws_network_interface.secondary", &iniSecondary), + resource.TestCheckResourceAttr("aws_instance.foo", "network_interface.#", "1"), + ), + }, + }, + }) +} + +// https://github.com/hashicorp/terraform/issues/3205 +func TestAccAWSInstance_addSecurityGroupNetworkInterface(t *testing.T) { + var before ec2.Instance + var after ec2.Instance + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckInstanceDestroy, + Steps: []resource.TestStep{ + { + Config: testAccInstanceConfigAddSecurityGroupBefore, + Check: resource.ComposeTestCheckFunc( + testAccCheckInstanceExists("aws_instance.foo", &before), + resource.TestCheckResourceAttr("aws_instance.foo", "vpc_security_group_ids.#", "1"), + ), + }, + { + Config: testAccInstanceConfigAddSecurityGroupAfter, + Check: resource.ComposeTestCheckFunc( + testAccCheckInstanceExists("aws_instance.foo", &after), + resource.TestCheckResourceAttr("aws_instance.foo", "vpc_security_group_ids.#", "2"), + ), + }, + }, + }) +} + func testAccCheckInstanceNotRecreated(t *testing.T, before, after *ec2.Instance) resource.TestCheckFunc { return func(s *terraform.State) error { @@ -1214,6 +1401,37 @@ resource "aws_instance" "foo" { } ` +const testAccInstanceConfigIpv6ErrorConfig = ` +resource "aws_vpc" "foo" { + cidr_block = "10.1.0.0/16" + assign_generated_ipv6_cidr_block = true + tags { + Name = "tf-ipv6-instance-acc-test" + } +} + +resource "aws_subnet" "foo" { + cidr_block = "10.1.1.0/24" + vpc_id = "${aws_vpc.foo.id}" + ipv6_cidr_block = "${cidrsubnet(aws_vpc.foo.ipv6_cidr_block, 8, 1)}" + tags { + Name = "tf-ipv6-instance-acc-test" + } +} + +resource "aws_instance" "foo" { + # us-west-2 + ami = "ami-c5eabbf5" + instance_type = "t2.micro" + subnet_id = "${aws_subnet.foo.id}" + ipv6_addresses = ["2600:1f14:bb2:e501::10"] + ipv6_address_count = 1 + tags { + Name = "tf-ipv6-instance-acc-test" + } +} +` + const testAccInstanceConfigIpv6Support = ` resource "aws_vpc" "foo" { cidr_block = "10.1.0.0/16" @@ -1281,6 +1499,180 @@ resource "aws_instance" "foo" { } ` +const testAccCheckInstanceConfigWithAttachedVolume = ` +data "aws_ami" "debian_jessie_latest" { + most_recent = true + + filter { + name = "name" + values = ["debian-jessie-*"] + } + + filter { + name = "virtualization-type" + values = ["hvm"] + } + + filter { + name = "architecture" + values = ["x86_64"] + } + + filter { + name = "root-device-type" + values = ["ebs"] + } + + owners = ["379101102735"] # Debian +} + +resource "aws_instance" "foo" { + ami = "${data.aws_ami.debian_jessie_latest.id}" + associate_public_ip_address = true + count = 1 + instance_type = "t2.medium" + + root_block_device { + volume_size = "10" + volume_type = "standard" + delete_on_termination = true + } + + tags { + Name = "test-terraform" + } +} + +resource "aws_ebs_volume" "test" { + depends_on = ["aws_instance.foo"] + availability_zone = "${aws_instance.foo.availability_zone}" + type = "gp2" + size = "10" + + tags { + Name = "test-terraform" + } +} + +resource "aws_volume_attachment" "test" { + depends_on = ["aws_ebs_volume.test"] + device_name = "/dev/xvdg" + volume_id = "${aws_ebs_volume.test.id}" + instance_id = "${aws_instance.foo.id}" +} +` + +const testAccCheckInstanceConfigNoVolumeTags = ` +resource "aws_instance" "foo" { + ami = "ami-55a7ea65" + + instance_type = "m3.medium" + + root_block_device { + volume_type = "gp2" + volume_size = 11 + } + ebs_block_device { + device_name = "/dev/sdb" + volume_size = 9 + } + ebs_block_device { + device_name = "/dev/sdc" + volume_size = 10 + volume_type = "io1" + iops = 100 + } + + ebs_block_device { + device_name = "/dev/sdd" + volume_size = 12 + encrypted = true + } + + ephemeral_block_device { + device_name = "/dev/sde" + virtual_name = "ephemeral0" + } +} +` + +const testAccCheckInstanceConfigWithVolumeTags = ` +resource "aws_instance" "foo" { + ami = "ami-55a7ea65" + + instance_type = "m3.medium" + + root_block_device { + volume_type = "gp2" + volume_size = 11 + } + ebs_block_device { + device_name = "/dev/sdb" + volume_size = 9 + } + ebs_block_device { + device_name = "/dev/sdc" + volume_size = 10 + volume_type = "io1" + iops = 100 + } + + ebs_block_device { + device_name = "/dev/sdd" + volume_size = 12 + encrypted = true + } + + ephemeral_block_device { + device_name = "/dev/sde" + virtual_name = "ephemeral0" + } + + volume_tags { + Name = "acceptance-test-volume-tag" + } +} +` + +const testAccCheckInstanceConfigWithVolumeTagsUpdate = ` +resource "aws_instance" "foo" { + ami = "ami-55a7ea65" + + instance_type = "m3.medium" + + root_block_device { + volume_type = "gp2" + volume_size = 11 + } + ebs_block_device { + device_name = "/dev/sdb" + volume_size = 9 + } + ebs_block_device { + device_name = "/dev/sdc" + volume_size = 10 + volume_type = "io1" + iops = 100 + } + + ebs_block_device { + device_name = "/dev/sdd" + volume_size = 12 + encrypted = true + } + + ephemeral_block_device { + device_name = "/dev/sde" + virtual_name = "ephemeral0" + } + + volume_tags { + Name = "acceptance-test-volume-tag" + Environment = "dev" + } +} +` + const testAccCheckInstanceConfigTagsUpdate = ` resource "aws_instance" "foo" { ami = "ami-4fccb37f" @@ -1462,13 +1854,14 @@ resource "aws_eip" "foo_eip" { } ` -const testAccInstanceConfigKeyPair = ` +func testAccInstanceConfigKeyPair(keyPairName string) string { + return fmt.Sprintf(` provider "aws" { region = "us-east-1" } resource "aws_key_pair" "debugging" { - key_name = "tmp-key" + key_name = "%s" public_key = "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQD3F6tyPEFEzV0LX3X8BsXdMsQz1x2cEikKDEY0aIj41qgxMCP/iteneqXSIFZBp5vizPvaoIR3Um9xK7PGoW8giupGn+EPuxIA4cDM4vzOqOkiMPhz5XK0whEjkVzTo4+S0puvDZuwIsdiW9mxhJc7tgBNL0cYlWSYVkz4G/fslNfRPW5mYAM49f4fhtxPb5ok4Q2Lg9dPKVHO/Bgeu5woMc7RY0p1ej6D4CKFE6lymSDJpW0YHX/wqE9+cfEauh7xZcG0q9t2ta6F6fmX0agvpFyZo8aFbXeUBr7osSCJNgvavWbM/06niWrOvYX2xwWdhXmXSrbX8ZbabVohBK41 phodgson@thoughtworks.com" } @@ -1480,7 +1873,8 @@ resource "aws_instance" "foo" { Name = "testAccInstanceConfigKeyPair_TestAMI" } } -` +`, keyPairName) +} const testAccInstanceConfigRootBlockDeviceMismatch = ` resource "aws_vpc" "foo" { @@ -1536,3 +1930,296 @@ resource "aws_instance" "foo" { subnet_id = "${aws_subnet.foo.id}" } ` + +const testAccInstanceConfigPrimaryNetworkInterface = ` +resource "aws_vpc" "foo" { + cidr_block = "172.16.0.0/16" + tags { + Name = "tf-instance-test" + } +} + +resource "aws_subnet" "foo" { + vpc_id = "${aws_vpc.foo.id}" + cidr_block = "172.16.10.0/24" + availability_zone = "us-west-2a" + tags { + Name = "tf-instance-test" + } +} + +resource "aws_network_interface" "bar" { + subnet_id = "${aws_subnet.foo.id}" + private_ips = ["172.16.10.100"] + tags { + Name = "primary_network_interface" + } +} + +resource "aws_instance" "foo" { + ami = "ami-22b9a343" + instance_type = "t2.micro" + network_interface { + network_interface_id = "${aws_network_interface.bar.id}" + device_index = 0 + } +} +` + +const testAccInstanceConfigPrimaryNetworkInterfaceSourceDestCheck = ` +resource "aws_vpc" "foo" { + cidr_block = "172.16.0.0/16" + tags { + Name = "tf-instance-test" + } +} + +resource "aws_subnet" "foo" { + vpc_id = "${aws_vpc.foo.id}" + cidr_block = "172.16.10.0/24" + availability_zone = "us-west-2a" + tags { + Name = "tf-instance-test" + } +} + +resource "aws_network_interface" "bar" { + subnet_id = "${aws_subnet.foo.id}" + private_ips = ["172.16.10.100"] + source_dest_check = false + tags { + Name = "primary_network_interface" + } +} + +resource "aws_instance" "foo" { + ami = "ami-22b9a343" + instance_type = "t2.micro" + network_interface { + network_interface_id = "${aws_network_interface.bar.id}" + device_index = 0 + } +} +` + +const testAccInstanceConfigAddSecondaryNetworkInterfaceBefore = ` +resource "aws_vpc" "foo" { + cidr_block = "172.16.0.0/16" + tags { + Name = "tf-instance-test" + } +} + +resource "aws_subnet" "foo" { + vpc_id = "${aws_vpc.foo.id}" + cidr_block = "172.16.10.0/24" + availability_zone = "us-west-2a" + tags { + Name = "tf-instance-test" + } +} + +resource "aws_network_interface" "primary" { + subnet_id = "${aws_subnet.foo.id}" + private_ips = ["172.16.10.100"] + tags { + Name = "primary_network_interface" + } +} + +resource "aws_network_interface" "secondary" { + subnet_id = "${aws_subnet.foo.id}" + private_ips = ["172.16.10.101"] + tags { + Name = "secondary_network_interface" + } +} + +resource "aws_instance" "foo" { + ami = "ami-22b9a343" + instance_type = "t2.micro" + network_interface { + network_interface_id = "${aws_network_interface.primary.id}" + device_index = 0 + } +} +` + +const testAccInstanceConfigAddSecondaryNetworkInterfaceAfter = ` +resource "aws_vpc" "foo" { + cidr_block = "172.16.0.0/16" + tags { + Name = "tf-instance-test" + } +} + +resource "aws_subnet" "foo" { + vpc_id = "${aws_vpc.foo.id}" + cidr_block = "172.16.10.0/24" + availability_zone = "us-west-2a" + tags { + Name = "tf-instance-test" + } +} + +resource "aws_network_interface" "primary" { + subnet_id = "${aws_subnet.foo.id}" + private_ips = ["172.16.10.100"] + tags { + Name = "primary_network_interface" + } +} + +// Attach previously created network interface, observe no state diff on instance resource +resource "aws_network_interface" "secondary" { + subnet_id = "${aws_subnet.foo.id}" + private_ips = ["172.16.10.101"] + tags { + Name = "secondary_network_interface" + } + attachment { + instance = "${aws_instance.foo.id}" + device_index = 1 + } +} + +resource "aws_instance" "foo" { + ami = "ami-22b9a343" + instance_type = "t2.micro" + network_interface { + network_interface_id = "${aws_network_interface.primary.id}" + device_index = 0 + } +} +` + +const testAccInstanceConfigAddSecurityGroupBefore = ` +resource "aws_vpc" "foo" { + cidr_block = "172.16.0.0/16" + tags { + Name = "tf-eni-test" + } +} + +resource "aws_subnet" "foo" { + vpc_id = "${aws_vpc.foo.id}" + cidr_block = "172.16.10.0/24" + availability_zone = "us-west-2a" + tags { + Name = "tf-foo-instance-add-sg-test" + } +} + +resource "aws_subnet" "bar" { + vpc_id = "${aws_vpc.foo.id}" + cidr_block = "172.16.11.0/24" + availability_zone = "us-west-2a" + tags { + Name = "tf-bar-instance-add-sg-test" + } +} + +resource "aws_security_group" "foo" { + vpc_id = "${aws_vpc.foo.id}" + description = "foo" + name = "foo" +} + +resource "aws_security_group" "bar" { + vpc_id = "${aws_vpc.foo.id}" + description = "bar" + name = "bar" +} + +resource "aws_instance" "foo" { + ami = "ami-c5eabbf5" + instance_type = "t2.micro" + subnet_id = "${aws_subnet.bar.id}" + associate_public_ip_address = false + vpc_security_group_ids = [ + "${aws_security_group.foo.id}" + ] + tags { + Name = "foo-instance-sg-add-test" + } +} + +resource "aws_network_interface" "bar" { + subnet_id = "${aws_subnet.foo.id}" + private_ips = ["172.16.10.100"] + security_groups = ["${aws_security_group.foo.id}"] + attachment { + instance = "${aws_instance.foo.id}" + device_index = 1 + } + tags { + Name = "bar_interface" + } +} +` + +const testAccInstanceConfigAddSecurityGroupAfter = ` +resource "aws_vpc" "foo" { + cidr_block = "172.16.0.0/16" + tags { + Name = "tf-eni-test" + } +} + +resource "aws_subnet" "foo" { + vpc_id = "${aws_vpc.foo.id}" + cidr_block = "172.16.10.0/24" + availability_zone = "us-west-2a" + tags { + Name = "tf-foo-instance-add-sg-test" + } +} + +resource "aws_subnet" "bar" { + vpc_id = "${aws_vpc.foo.id}" + cidr_block = "172.16.11.0/24" + availability_zone = "us-west-2a" + tags { + Name = "tf-bar-instance-add-sg-test" + } +} + +resource "aws_security_group" "foo" { + vpc_id = "${aws_vpc.foo.id}" + description = "foo" + name = "foo" +} + +resource "aws_security_group" "bar" { + vpc_id = "${aws_vpc.foo.id}" + description = "bar" + name = "bar" +} + +resource "aws_instance" "foo" { + ami = "ami-c5eabbf5" + instance_type = "t2.micro" + subnet_id = "${aws_subnet.bar.id}" + associate_public_ip_address = false + vpc_security_group_ids = [ + "${aws_security_group.foo.id}", + "${aws_security_group.bar.id}" + ] + tags { + Name = "foo-instance-sg-add-test" + } +} + +resource "aws_network_interface" "bar" { + subnet_id = "${aws_subnet.foo.id}" + private_ips = ["172.16.10.100"] + security_groups = ["${aws_security_group.foo.id}"] + attachment { + instance = "${aws_instance.foo.id}" + device_index = 1 + } + tags { + Name = "bar_interface" + } +} +` diff --git a/builtin/providers/aws/resource_aws_kinesis_firehose_delivery_stream.go b/builtin/providers/aws/resource_aws_kinesis_firehose_delivery_stream.go index b82ec56bb..3cd476be9 100644 --- a/builtin/providers/aws/resource_aws_kinesis_firehose_delivery_stream.go +++ b/builtin/providers/aws/resource_aws_kinesis_firehose_delivery_stream.go @@ -150,8 +150,9 @@ func resourceAwsKinesisFirehoseDeliveryStream() *schema.Resource { }, "password": { - Type: schema.TypeString, - Required: true, + Type: schema.TypeString, + Required: true, + Sensitive: true, }, "role_arn": { diff --git a/builtin/providers/aws/resource_aws_kinesis_firehose_delivery_stream_test.go b/builtin/providers/aws/resource_aws_kinesis_firehose_delivery_stream_test.go index 040040e67..27f227883 100644 --- a/builtin/providers/aws/resource_aws_kinesis_firehose_delivery_stream_test.go +++ b/builtin/providers/aws/resource_aws_kinesis_firehose_delivery_stream_test.go @@ -439,7 +439,7 @@ resource "aws_cloudwatch_log_stream" "test" { resource "aws_kinesis_firehose_delivery_stream" "test_stream" { depends_on = ["aws_iam_role_policy.firehose"] - name = "terraform-kinesis-firehose-basictest-cloudwatch" + name = "terraform-kinesis-firehose-cloudwatch-%d" destination = "s3" s3_configuration { role_arn = "${aws_iam_role.firehose.arn}" @@ -451,7 +451,7 @@ resource "aws_kinesis_firehose_delivery_stream" "test_stream" { } } } -`, rInt, accountId, rInt, rInt, rInt, rInt) +`, rInt, accountId, rInt, rInt, rInt, rInt, rInt) } var testAccKinesisFirehoseDeliveryStreamConfig_s3basic = testAccKinesisFirehoseDeliveryStreamBaseConfig + ` @@ -487,6 +487,7 @@ resource "aws_redshift_cluster" "test_cluster" { master_password = "T3stPass" node_type = "dc1.large" cluster_type = "single-node" + skip_final_snapshot = true }` var testAccKinesisFirehoseDeliveryStreamConfig_RedshiftBasic = testAccKinesisFirehoseDeliveryStreamBaseRedshiftConfig + ` @@ -533,6 +534,9 @@ resource "aws_kinesis_firehose_delivery_stream" "test_stream" { var testAccKinesisFirehoseDeliveryStreamBaseElasticsearchConfig = testAccKinesisFirehoseDeliveryStreamBaseConfig + ` resource "aws_elasticsearch_domain" "test_cluster" { domain_name = "es-test-%d" + cluster_config { + instance_type = "r3.large.elasticsearch" + } access_policies = < 0 { @@ -290,23 +300,27 @@ func updateKinesisShardLevelMetrics(conn *kinesis.Kinesis, d *schema.ResourceDat type kinesisStreamState struct { arn string + creationTimestamp int64 status string - shardCount int retentionPeriod int64 + openShards []string + closedShards []string shardLevelMetrics []string } -func readKinesisStreamState(conn *kinesis.Kinesis, sn string) (kinesisStreamState, error) { +func readKinesisStreamState(conn *kinesis.Kinesis, sn string) (*kinesisStreamState, error) { describeOpts := &kinesis.DescribeStreamInput{ StreamName: aws.String(sn), } - var state kinesisStreamState + state := &kinesisStreamState{} err := conn.DescribeStreamPages(describeOpts, func(page *kinesis.DescribeStreamOutput, last bool) (shouldContinue bool) { state.arn = aws.StringValue(page.StreamDescription.StreamARN) + state.creationTimestamp = aws.TimeValue(page.StreamDescription.StreamCreationTimestamp).Unix() state.status = aws.StringValue(page.StreamDescription.StreamStatus) - state.shardCount += len(openShards(page.StreamDescription.Shards)) state.retentionPeriod = aws.Int64Value(page.StreamDescription.RetentionPeriodHours) + state.openShards = append(state.openShards, flattenShards(openShards(page.StreamDescription.Shards))...) + state.closedShards = append(state.closedShards, flattenShards(closedShards(page.StreamDescription.Shards))...) state.shardLevelMetrics = flattenKinesisShardLevelMetrics(page.StreamDescription.EnhancedMonitoring) return !last }) @@ -349,14 +363,31 @@ func waitForKinesisToBeActive(conn *kinesis.Kinesis, sn string) error { return nil } -// See http://docs.aws.amazon.com/kinesis/latest/dev/kinesis-using-sdk-java-resharding-merge.html func openShards(shards []*kinesis.Shard) []*kinesis.Shard { - var open []*kinesis.Shard + return filterShards(shards, true) +} + +func closedShards(shards []*kinesis.Shard) []*kinesis.Shard { + return filterShards(shards, false) +} + +// See http://docs.aws.amazon.com/kinesis/latest/dev/kinesis-using-sdk-java-resharding-merge.html +func filterShards(shards []*kinesis.Shard, open bool) []*kinesis.Shard { + res := make([]*kinesis.Shard, 0, len(shards)) for _, s := range shards { - if s.SequenceNumberRange.EndingSequenceNumber == nil { - open = append(open, s) + if open && s.SequenceNumberRange.EndingSequenceNumber == nil { + res = append(res, s) + } else if !open && s.SequenceNumberRange.EndingSequenceNumber != nil { + res = append(res, s) } } - - return open + return res +} + +func flattenShards(shards []*kinesis.Shard) []string { + res := make([]string, len(shards)) + for i, s := range shards { + res[i] = aws.StringValue(s.ShardId) + } + return res } diff --git a/builtin/providers/aws/resource_aws_kinesis_stream_test.go b/builtin/providers/aws/resource_aws_kinesis_stream_test.go index 8debb2336..e8afbdc6c 100644 --- a/builtin/providers/aws/resource_aws_kinesis_stream_test.go +++ b/builtin/providers/aws/resource_aws_kinesis_stream_test.go @@ -2,14 +2,13 @@ package aws import ( "fmt" - "math/rand" "strconv" "strings" "testing" - "time" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/kinesis" + "github.com/hashicorp/terraform/helper/acctest" "github.com/hashicorp/terraform/helper/resource" "github.com/hashicorp/terraform/terraform" ) @@ -17,15 +16,15 @@ import ( func TestAccAWSKinesisStream_basic(t *testing.T) { var stream kinesis.StreamDescription - config := fmt.Sprintf(testAccKinesisStreamConfig, rand.New(rand.NewSource(time.Now().UnixNano())).Int()) + rInt := acctest.RandInt() resource.Test(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, CheckDestroy: testAccCheckKinesisStreamDestroy, Steps: []resource.TestStep{ - resource.TestStep{ - Config: config, + { + Config: testAccKinesisStreamConfig(rInt), Check: resource.ComposeTestCheckFunc( testAccCheckKinesisStreamExists("aws_kinesis_stream.test_stream", &stream), testAccCheckAWSKinesisStreamAttributes(&stream), @@ -35,20 +34,42 @@ func TestAccAWSKinesisStream_basic(t *testing.T) { }) } -func TestAccAWSKinesisStream_shardCount(t *testing.T) { - var stream kinesis.StreamDescription - - ri := rand.New(rand.NewSource(time.Now().UnixNano())).Int() - config := fmt.Sprintf(testAccKinesisStreamConfig, ri) - updateConfig := fmt.Sprintf(testAccKinesisStreamConfigUpdateShardCount, ri) +func TestAccAWSKinesisStream_importBasic(t *testing.T) { + rInt := acctest.RandInt() + resourceName := "aws_kinesis_stream.test_stream" + streamName := fmt.Sprintf("terraform-kinesis-test-%d", rInt) resource.Test(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, CheckDestroy: testAccCheckKinesisStreamDestroy, Steps: []resource.TestStep{ - resource.TestStep{ - Config: config, + { + Config: testAccKinesisStreamConfig(rInt), + }, + + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateId: streamName, + }, + }, + }) +} + +func TestAccAWSKinesisStream_shardCount(t *testing.T) { + var stream kinesis.StreamDescription + + rInt := acctest.RandInt() + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckKinesisStreamDestroy, + Steps: []resource.TestStep{ + { + Config: testAccKinesisStreamConfig(rInt), Check: resource.ComposeTestCheckFunc( testAccCheckKinesisStreamExists("aws_kinesis_stream.test_stream", &stream), testAccCheckAWSKinesisStreamAttributes(&stream), @@ -57,8 +78,8 @@ func TestAccAWSKinesisStream_shardCount(t *testing.T) { ), }, - resource.TestStep{ - Config: updateConfig, + { + Config: testAccKinesisStreamConfigUpdateShardCount(rInt), Check: resource.ComposeTestCheckFunc( testAccCheckKinesisStreamExists("aws_kinesis_stream.test_stream", &stream), testAccCheckAWSKinesisStreamAttributes(&stream), @@ -73,18 +94,15 @@ func TestAccAWSKinesisStream_shardCount(t *testing.T) { func TestAccAWSKinesisStream_retentionPeriod(t *testing.T) { var stream kinesis.StreamDescription - ri := rand.New(rand.NewSource(time.Now().UnixNano())).Int() - config := fmt.Sprintf(testAccKinesisStreamConfig, ri) - updateConfig := fmt.Sprintf(testAccKinesisStreamConfigUpdateRetentionPeriod, ri) - decreaseConfig := fmt.Sprintf(testAccKinesisStreamConfigDecreaseRetentionPeriod, ri) + rInt := acctest.RandInt() resource.Test(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, CheckDestroy: testAccCheckKinesisStreamDestroy, Steps: []resource.TestStep{ - resource.TestStep{ - Config: config, + { + Config: testAccKinesisStreamConfig(rInt), Check: resource.ComposeTestCheckFunc( testAccCheckKinesisStreamExists("aws_kinesis_stream.test_stream", &stream), testAccCheckAWSKinesisStreamAttributes(&stream), @@ -93,8 +111,8 @@ func TestAccAWSKinesisStream_retentionPeriod(t *testing.T) { ), }, - resource.TestStep{ - Config: updateConfig, + { + Config: testAccKinesisStreamConfigUpdateRetentionPeriod(rInt), Check: resource.ComposeTestCheckFunc( testAccCheckKinesisStreamExists("aws_kinesis_stream.test_stream", &stream), testAccCheckAWSKinesisStreamAttributes(&stream), @@ -103,8 +121,8 @@ func TestAccAWSKinesisStream_retentionPeriod(t *testing.T) { ), }, - resource.TestStep{ - Config: decreaseConfig, + { + Config: testAccKinesisStreamConfigDecreaseRetentionPeriod(rInt), Check: resource.ComposeTestCheckFunc( testAccCheckKinesisStreamExists("aws_kinesis_stream.test_stream", &stream), testAccCheckAWSKinesisStreamAttributes(&stream), @@ -119,18 +137,15 @@ func TestAccAWSKinesisStream_retentionPeriod(t *testing.T) { func TestAccAWSKinesisStream_shardLevelMetrics(t *testing.T) { var stream kinesis.StreamDescription - ri := rand.New(rand.NewSource(time.Now().UnixNano())).Int() - config := fmt.Sprintf(testAccKinesisStreamConfig, ri) - allConfig := fmt.Sprintf(testAccKinesisStreamConfigAllShardLevelMetrics, ri) - singleConfig := fmt.Sprintf(testAccKinesisStreamConfigSingleShardLevelMetric, ri) + rInt := acctest.RandInt() resource.Test(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, CheckDestroy: testAccCheckKinesisStreamDestroy, Steps: []resource.TestStep{ - resource.TestStep{ - Config: config, + { + Config: testAccKinesisStreamConfig(rInt), Check: resource.ComposeTestCheckFunc( testAccCheckKinesisStreamExists("aws_kinesis_stream.test_stream", &stream), testAccCheckAWSKinesisStreamAttributes(&stream), @@ -139,8 +154,8 @@ func TestAccAWSKinesisStream_shardLevelMetrics(t *testing.T) { ), }, - resource.TestStep{ - Config: allConfig, + { + Config: testAccKinesisStreamConfigAllShardLevelMetrics(rInt), Check: resource.ComposeTestCheckFunc( testAccCheckKinesisStreamExists("aws_kinesis_stream.test_stream", &stream), testAccCheckAWSKinesisStreamAttributes(&stream), @@ -149,8 +164,8 @@ func TestAccAWSKinesisStream_shardLevelMetrics(t *testing.T) { ), }, - resource.TestStep{ - Config: singleConfig, + { + Config: testAccKinesisStreamConfigSingleShardLevelMetric(rInt), Check: resource.ComposeTestCheckFunc( testAccCheckKinesisStreamExists("aws_kinesis_stream.test_stream", &stream), testAccCheckAWSKinesisStreamAttributes(&stream), @@ -232,27 +247,30 @@ func testAccCheckKinesisStreamDestroy(s *terraform.State) error { return nil } -var testAccKinesisStreamConfig = ` +func testAccKinesisStreamConfig(rInt int) string { + return fmt.Sprintf(` resource "aws_kinesis_stream" "test_stream" { name = "terraform-kinesis-test-%d" shard_count = 2 tags { Name = "tf-test" } +}`, rInt) } -` -var testAccKinesisStreamConfigUpdateShardCount = ` +func testAccKinesisStreamConfigUpdateShardCount(rInt int) string { + return fmt.Sprintf(` resource "aws_kinesis_stream" "test_stream" { name = "terraform-kinesis-test-%d" shard_count = 4 tags { Name = "tf-test" } +}`, rInt) } -` -var testAccKinesisStreamConfigUpdateRetentionPeriod = ` +func testAccKinesisStreamConfigUpdateRetentionPeriod(rInt int) string { + return fmt.Sprintf(` resource "aws_kinesis_stream" "test_stream" { name = "terraform-kinesis-test-%d" shard_count = 2 @@ -260,10 +278,11 @@ resource "aws_kinesis_stream" "test_stream" { tags { Name = "tf-test" } +}`, rInt) } -` -var testAccKinesisStreamConfigDecreaseRetentionPeriod = ` +func testAccKinesisStreamConfigDecreaseRetentionPeriod(rInt int) string { + return fmt.Sprintf(` resource "aws_kinesis_stream" "test_stream" { name = "terraform-kinesis-test-%d" shard_count = 2 @@ -271,10 +290,11 @@ resource "aws_kinesis_stream" "test_stream" { tags { Name = "tf-test" } +}`, rInt) } -` -var testAccKinesisStreamConfigAllShardLevelMetrics = ` +func testAccKinesisStreamConfigAllShardLevelMetrics(rInt int) string { + return fmt.Sprintf(` resource "aws_kinesis_stream" "test_stream" { name = "terraform-kinesis-test-%d" shard_count = 2 @@ -290,10 +310,11 @@ resource "aws_kinesis_stream" "test_stream" { "ReadProvisionedThroughputExceeded", "IteratorAgeMilliseconds" ] +}`, rInt) } -` -var testAccKinesisStreamConfigSingleShardLevelMetric = ` +func testAccKinesisStreamConfigSingleShardLevelMetric(rInt int) string { + return fmt.Sprintf(` resource "aws_kinesis_stream" "test_stream" { name = "terraform-kinesis-test-%d" shard_count = 2 @@ -303,5 +324,5 @@ resource "aws_kinesis_stream" "test_stream" { shard_level_metrics = [ "IncomingBytes" ] +}`, rInt) } -` diff --git a/builtin/providers/aws/resource_aws_kms_alias.go b/builtin/providers/aws/resource_aws_kms_alias.go index 64eec56a6..b02ffefba 100644 --- a/builtin/providers/aws/resource_aws_kms_alias.go +++ b/builtin/providers/aws/resource_aws_kms_alias.go @@ -29,14 +29,7 @@ func resourceAwsKmsAlias() *schema.Resource { Optional: true, ForceNew: true, ConflictsWith: []string{"name_prefix"}, - ValidateFunc: func(v interface{}, k string) (ws []string, es []error) { - value := v.(string) - if !regexp.MustCompile(`^(alias\/)[a-zA-Z0-9:/_-]+$`).MatchString(value) { - es = append(es, fmt.Errorf( - "%q must begin with 'alias/' and be comprised of only [a-zA-Z0-9:/_-]", k)) - } - return - }, + ValidateFunc: validateAwsKmsName, }, "name_prefix": &schema.Schema{ Type: schema.TypeString, diff --git a/builtin/providers/aws/resource_aws_kms_key.go b/builtin/providers/aws/resource_aws_kms_key.go index 4c8343062..f95f76d95 100644 --- a/builtin/providers/aws/resource_aws_kms_key.go +++ b/builtin/providers/aws/resource_aws_kms_key.go @@ -6,6 +6,7 @@ import ( "time" "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/service/kms" "github.com/hashicorp/errwrap" "github.com/hashicorp/terraform/helper/resource" @@ -18,6 +19,7 @@ func resourceAwsKmsKey() *schema.Resource { Read: resourceAwsKmsKeyRead, Update: resourceAwsKmsKeyUpdate, Delete: resourceAwsKmsKeyDelete, + Exists: resourceAwsKmsKeyExists, Importer: &schema.ResourceImporter{ State: schema.ImportStatePassthrough, @@ -318,19 +320,33 @@ func updateKmsKeyStatus(conn *kms.KMS, id string, shouldBeEnabled bool) error { } func updateKmsKeyRotationStatus(conn *kms.KMS, d *schema.ResourceData) error { - var err error shouldEnableRotation := d.Get("enable_key_rotation").(bool) - if shouldEnableRotation { - log.Printf("[DEBUG] Enabling key rotation for KMS key %q", d.Id()) - _, err = conn.EnableKeyRotation(&kms.EnableKeyRotationInput{ - KeyId: aws.String(d.Id()), - }) - } else { - log.Printf("[DEBUG] Disabling key rotation for KMS key %q", d.Id()) - _, err = conn.DisableKeyRotation(&kms.DisableKeyRotationInput{ - KeyId: aws.String(d.Id()), - }) - } + + err := resource.Retry(5*time.Minute, func() *resource.RetryError { + var err error + if shouldEnableRotation { + log.Printf("[DEBUG] Enabling key rotation for KMS key %q", d.Id()) + _, err = conn.EnableKeyRotation(&kms.EnableKeyRotationInput{ + KeyId: aws.String(d.Id()), + }) + } else { + log.Printf("[DEBUG] Disabling key rotation for KMS key %q", d.Id()) + _, err = conn.DisableKeyRotation(&kms.DisableKeyRotationInput{ + KeyId: aws.String(d.Id()), + }) + } + + if err != nil { + awsErr, ok := err.(awserr.Error) + if ok && awsErr.Code() == "DisabledException" { + return resource.RetryableError(err) + } + + return resource.NonRetryableError(err) + } + + return nil + }) if err != nil { return fmt.Errorf("Failed to set key rotation for %q to %t: %q", @@ -368,6 +384,30 @@ func updateKmsKeyRotationStatus(conn *kms.KMS, d *schema.ResourceData) error { return nil } +func resourceAwsKmsKeyExists(d *schema.ResourceData, meta interface{}) (bool, error) { + conn := meta.(*AWSClient).kmsconn + + req := &kms.DescribeKeyInput{ + KeyId: aws.String(d.Id()), + } + resp, err := conn.DescribeKey(req) + if err != nil { + if awsErr, ok := err.(awserr.Error); ok { + if awsErr.Code() == "NotFoundException" { + return false, nil + } + } + return false, err + } + metadata := resp.KeyMetadata + + if *metadata.KeyState == "PendingDeletion" { + return false, nil + } + + return true, nil +} + func resourceAwsKmsKeyDelete(d *schema.ResourceData, meta interface{}) error { conn := meta.(*AWSClient).kmsconn keyId := d.Get("key_id").(string) diff --git a/builtin/providers/aws/resource_aws_kms_key_test.go b/builtin/providers/aws/resource_aws_kms_key_test.go index 86cabe4ed..b184fa30c 100644 --- a/builtin/providers/aws/resource_aws_kms_key_test.go +++ b/builtin/providers/aws/resource_aws_kms_key_test.go @@ -37,6 +37,29 @@ func TestAccAWSKmsKey_basic(t *testing.T) { }) } +func TestAccAWSKmsKey_disappears(t *testing.T) { + var key kms.KeyMetadata + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSKmsKeyDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAWSKmsKey, + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSKmsKeyExists("aws_kms_key.foo", &key), + ), + }, + { + Config: testAccAWSKmsKey_other_region, + PlanOnly: true, + ExpectNonEmptyPlan: true, + }, + }, + }) +} + func TestAccAWSKmsKey_policy(t *testing.T) { var key kms.KeyMetadata expectedPolicyText := `{"Version":"2012-10-17","Id":"kms-tf-1","Statement":[{"Sid":"Enable IAM User Permissions","Effect":"Allow","Principal":{"AWS":"*"},"Action":"kms:*","Resource":"*"}]}` @@ -238,6 +261,32 @@ resource "aws_kms_key" "foo" { POLICY }`, kmsTimestamp) +var testAccAWSKmsKey_other_region = fmt.Sprintf(` +provider "aws" { + region = "us-east-1" +} +resource "aws_kms_key" "foo" { + description = "Terraform acc test %s" + deletion_window_in_days = 7 + policy = < 1 { - return fmt.Errorf("Cannot specify more than one root_block_device.") - } + vL := v.([]interface{}) for _, v := range vL { bd := v.(map[string]interface{}) ebs := &autoscaling.Ebs{ @@ -473,7 +463,7 @@ func resourceAwsLaunchConfigurationCreate(d *schema.ResourceData, meta interface // IAM profiles can take ~10 seconds to propagate in AWS: // http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html#launch-instance-with-role-console - err = resource.Retry(30*time.Second, func() *resource.RetryError { + err = resource.Retry(90*time.Second, func() *resource.RetryError { _, err := autoscalingconn.CreateLaunchConfiguration(&createLaunchConfigurationOpts) if err != nil { if awsErr, ok := err.(awserr.Error); ok { diff --git a/builtin/providers/aws/resource_aws_launch_configuration_test.go b/builtin/providers/aws/resource_aws_launch_configuration_test.go index d26027a25..93ec981f5 100644 --- a/builtin/providers/aws/resource_aws_launch_configuration_test.go +++ b/builtin/providers/aws/resource_aws_launch_configuration_test.go @@ -11,6 +11,7 @@ import ( "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/service/autoscaling" "github.com/aws/aws-sdk-go/service/ec2" + "github.com/hashicorp/terraform/helper/acctest" "github.com/hashicorp/terraform/helper/resource" "github.com/hashicorp/terraform/terraform" ) @@ -23,7 +24,7 @@ func TestAccAWSLaunchConfiguration_basic(t *testing.T) { Providers: testAccProviders, CheckDestroy: testAccCheckAWSLaunchConfigurationDestroy, Steps: []resource.TestStep{ - resource.TestStep{ + { Config: testAccAWSLaunchConfigurationNoNameConfig, Check: resource.ComposeTestCheckFunc( testAccCheckAWSLaunchConfigurationExists("aws_launch_configuration.bar", &conf), @@ -31,7 +32,7 @@ func TestAccAWSLaunchConfiguration_basic(t *testing.T) { "aws_launch_configuration.bar", "terraform-"), ), }, - resource.TestStep{ + { Config: testAccAWSLaunchConfigurationPrefixNameConfig, Check: resource.ComposeTestCheckFunc( testAccCheckAWSLaunchConfigurationExists("aws_launch_configuration.baz", &conf), @@ -51,7 +52,7 @@ func TestAccAWSLaunchConfiguration_withBlockDevices(t *testing.T) { Providers: testAccProviders, CheckDestroy: testAccCheckAWSLaunchConfigurationDestroy, Steps: []resource.TestStep{ - resource.TestStep{ + { Config: testAccAWSLaunchConfigurationConfig, Check: resource.ComposeTestCheckFunc( testAccCheckAWSLaunchConfigurationExists("aws_launch_configuration.bar", &conf), @@ -70,6 +71,35 @@ func TestAccAWSLaunchConfiguration_withBlockDevices(t *testing.T) { }) } +func TestAccAWSLaunchConfiguration_updateRootBlockDevice(t *testing.T) { + var conf autoscaling.LaunchConfiguration + rInt := acctest.RandInt() + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSLaunchConfigurationDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAWSLaunchConfigurationConfigWithRootBlockDevice(rInt), + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSLaunchConfigurationExists("aws_launch_configuration.bar", &conf), + resource.TestCheckResourceAttr( + "aws_launch_configuration.bar", "root_block_device.0.volume_size", "11"), + ), + }, + { + Config: testAccAWSLaunchConfigurationConfigWithRootBlockDeviceUpdated(rInt), + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSLaunchConfigurationExists("aws_launch_configuration.bar", &conf), + resource.TestCheckResourceAttr( + "aws_launch_configuration.bar", "root_block_device.0.volume_size", "20"), + ), + }, + }, + }) +} + func TestAccAWSLaunchConfiguration_withSpotPrice(t *testing.T) { var conf autoscaling.LaunchConfiguration @@ -78,7 +108,7 @@ func TestAccAWSLaunchConfiguration_withSpotPrice(t *testing.T) { Providers: testAccProviders, CheckDestroy: testAccCheckAWSLaunchConfigurationDestroy, Steps: []resource.TestStep{ - resource.TestStep{ + { Config: testAccAWSLaunchConfigurationWithSpotPriceConfig, Check: resource.ComposeTestCheckFunc( testAccCheckAWSLaunchConfigurationExists("aws_launch_configuration.bar", &conf), @@ -100,7 +130,7 @@ func TestAccAWSLaunchConfiguration_withVpcClassicLink(t *testing.T) { Providers: testAccProviders, CheckDestroy: testAccCheckAWSLaunchConfigurationDestroy, Steps: []resource.TestStep{ - resource.TestStep{ + { Config: testAccAWSLaunchConfigurationConfig_withVpcClassicLink, Check: resource.ComposeTestCheckFunc( testAccCheckAWSLaunchConfigurationExists("aws_launch_configuration.foo", &conf), @@ -120,7 +150,7 @@ func TestAccAWSLaunchConfiguration_withIAMProfile(t *testing.T) { Providers: testAccProviders, CheckDestroy: testAccCheckAWSLaunchConfigurationDestroy, Steps: []resource.TestStep{ - resource.TestStep{ + { Config: testAccAWSLaunchConfigurationConfig_withIAMProfile, Check: resource.ComposeTestCheckFunc( testAccCheckAWSLaunchConfigurationExists("aws_launch_configuration.bar", &conf), @@ -164,7 +194,7 @@ func TestAccAWSLaunchConfiguration_withEncryption(t *testing.T) { Providers: testAccProviders, CheckDestroy: testAccCheckAWSLaunchConfigurationDestroy, Steps: []resource.TestStep{ - resource.TestStep{ + { Config: testAccAWSLaunchConfigurationWithEncryption, Check: resource.ComposeTestCheckFunc( testAccCheckAWSLaunchConfigurationExists("aws_launch_configuration.baz", &conf), @@ -304,6 +334,42 @@ func testAccCheckAWSLaunchConfigurationExists(n string, res *autoscaling.LaunchC } } +func testAccAWSLaunchConfigurationConfigWithRootBlockDevice(rInt int) string { + return fmt.Sprintf(` +resource "aws_launch_configuration" "bar" { + name_prefix = "tf-acc-test-%d" + image_id = "ami-21f78e11" + instance_type = "m1.small" + user_data = "foobar-user-data" + associate_public_ip_address = true + + root_block_device { + volume_type = "gp2" + volume_size = 11 + } + +} +`, rInt) +} + +func testAccAWSLaunchConfigurationConfigWithRootBlockDeviceUpdated(rInt int) string { + return fmt.Sprintf(` +resource "aws_launch_configuration" "bar" { + name_prefix = "tf-acc-test-%d" + image_id = "ami-21f78e11" + instance_type = "m1.small" + user_data = "foobar-user-data" + associate_public_ip_address = true + + root_block_device { + volume_type = "gp2" + volume_size = 20 + } + +} +`, rInt) +} + var testAccAWSLaunchConfigurationConfig = fmt.Sprintf(` resource "aws_launch_configuration" "bar" { name = "terraform-test-%d" diff --git a/builtin/providers/aws/resource_aws_lightsail_static_ip.go b/builtin/providers/aws/resource_aws_lightsail_static_ip.go new file mode 100644 index 000000000..1f593ad40 --- /dev/null +++ b/builtin/providers/aws/resource_aws_lightsail_static_ip.go @@ -0,0 +1,98 @@ +package aws + +import ( + "log" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/awserr" + "github.com/aws/aws-sdk-go/service/lightsail" + "github.com/hashicorp/terraform/helper/schema" +) + +func resourceAwsLightsailStaticIp() *schema.Resource { + return &schema.Resource{ + Create: resourceAwsLightsailStaticIpCreate, + Read: resourceAwsLightsailStaticIpRead, + Delete: resourceAwsLightsailStaticIpDelete, + + Schema: map[string]*schema.Schema{ + "name": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + "ip_address": { + Type: schema.TypeString, + Computed: true, + }, + "arn": { + Type: schema.TypeString, + Computed: true, + }, + "support_code": { + Type: schema.TypeString, + Computed: true, + }, + }, + } +} + +func resourceAwsLightsailStaticIpCreate(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*AWSClient).lightsailconn + + name := d.Get("name").(string) + log.Printf("[INFO] Allocating Lightsail Static IP: %q", name) + out, err := conn.AllocateStaticIp(&lightsail.AllocateStaticIpInput{ + StaticIpName: aws.String(name), + }) + if err != nil { + return err + } + log.Printf("[INFO] Lightsail Static IP allocated: %s", *out) + + d.SetId(name) + + return resourceAwsLightsailStaticIpRead(d, meta) +} + +func resourceAwsLightsailStaticIpRead(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*AWSClient).lightsailconn + + name := d.Get("name").(string) + log.Printf("[INFO] Reading Lightsail Static IP: %q", name) + out, err := conn.GetStaticIp(&lightsail.GetStaticIpInput{ + StaticIpName: aws.String(name), + }) + if err != nil { + if awsErr, ok := err.(awserr.Error); ok { + if awsErr.Code() == "NotFoundException" { + log.Printf("[WARN] Lightsail Static IP (%s) not found, removing from state", d.Id()) + d.SetId("") + return nil + } + } + return err + } + log.Printf("[INFO] Received Lightsail Static IP: %s", *out) + + d.Set("arn", out.StaticIp.Arn) + d.Set("ip_address", out.StaticIp.IpAddress) + d.Set("support_code", out.StaticIp.SupportCode) + + return nil +} + +func resourceAwsLightsailStaticIpDelete(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*AWSClient).lightsailconn + + name := d.Get("name").(string) + log.Printf("[INFO] Deleting Lightsail Static IP: %q", name) + out, err := conn.ReleaseStaticIp(&lightsail.ReleaseStaticIpInput{ + StaticIpName: aws.String(name), + }) + if err != nil { + return err + } + log.Printf("[INFO] Deleted Lightsail Static IP: %s", *out) + return nil +} diff --git a/builtin/providers/aws/resource_aws_lightsail_static_ip_attachment.go b/builtin/providers/aws/resource_aws_lightsail_static_ip_attachment.go new file mode 100644 index 000000000..766ccff55 --- /dev/null +++ b/builtin/providers/aws/resource_aws_lightsail_static_ip_attachment.go @@ -0,0 +1,96 @@ +package aws + +import ( + "log" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/awserr" + "github.com/aws/aws-sdk-go/service/lightsail" + "github.com/hashicorp/terraform/helper/schema" +) + +func resourceAwsLightsailStaticIpAttachment() *schema.Resource { + return &schema.Resource{ + Create: resourceAwsLightsailStaticIpAttachmentCreate, + Read: resourceAwsLightsailStaticIpAttachmentRead, + Delete: resourceAwsLightsailStaticIpAttachmentDelete, + + Schema: map[string]*schema.Schema{ + "static_ip_name": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + "instance_name": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + }, + } +} + +func resourceAwsLightsailStaticIpAttachmentCreate(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*AWSClient).lightsailconn + + staticIpName := d.Get("static_ip_name").(string) + log.Printf("[INFO] Attaching Lightsail Static IP: %q", staticIpName) + out, err := conn.AttachStaticIp(&lightsail.AttachStaticIpInput{ + StaticIpName: aws.String(staticIpName), + InstanceName: aws.String(d.Get("instance_name").(string)), + }) + if err != nil { + return err + } + log.Printf("[INFO] Lightsail Static IP attached: %s", *out) + + d.SetId(staticIpName) + + return resourceAwsLightsailStaticIpAttachmentRead(d, meta) +} + +func resourceAwsLightsailStaticIpAttachmentRead(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*AWSClient).lightsailconn + + staticIpName := d.Get("static_ip_name").(string) + log.Printf("[INFO] Reading Lightsail Static IP: %q", staticIpName) + out, err := conn.GetStaticIp(&lightsail.GetStaticIpInput{ + StaticIpName: aws.String(staticIpName), + }) + if err != nil { + if awsErr, ok := err.(awserr.Error); ok { + if awsErr.Code() == "NotFoundException" { + log.Printf("[WARN] Lightsail Static IP (%s) not found, removing from state", d.Id()) + d.SetId("") + return nil + } + } + return err + } + if !*out.StaticIp.IsAttached { + log.Printf("[WARN] Lightsail Static IP (%s) is not attached, removing from state", d.Id()) + d.SetId("") + return nil + } + + log.Printf("[INFO] Received Lightsail Static IP: %s", *out) + + d.Set("instance_name", out.StaticIp.AttachedTo) + + return nil +} + +func resourceAwsLightsailStaticIpAttachmentDelete(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*AWSClient).lightsailconn + + name := d.Get("static_ip_name").(string) + log.Printf("[INFO] Detaching Lightsail Static IP: %q", name) + out, err := conn.DetachStaticIp(&lightsail.DetachStaticIpInput{ + StaticIpName: aws.String(name), + }) + if err != nil { + return err + } + log.Printf("[INFO] Detached Lightsail Static IP: %s", *out) + return nil +} diff --git a/builtin/providers/aws/resource_aws_lightsail_static_ip_attachment_test.go b/builtin/providers/aws/resource_aws_lightsail_static_ip_attachment_test.go new file mode 100644 index 000000000..bf0aa0898 --- /dev/null +++ b/builtin/providers/aws/resource_aws_lightsail_static_ip_attachment_test.go @@ -0,0 +1,163 @@ +package aws + +import ( + "errors" + "fmt" + "testing" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/awserr" + "github.com/aws/aws-sdk-go/service/lightsail" + "github.com/hashicorp/terraform/helper/acctest" + "github.com/hashicorp/terraform/helper/resource" + "github.com/hashicorp/terraform/terraform" +) + +func TestAccAWSLightsailStaticIpAttachment_basic(t *testing.T) { + var staticIp lightsail.StaticIp + staticIpName := fmt.Sprintf("tf-test-lightsail-%s", acctest.RandString(5)) + instanceName := fmt.Sprintf("tf-test-lightsail-%s", acctest.RandString(5)) + keypairName := fmt.Sprintf("tf-test-lightsail-%s", acctest.RandString(5)) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSLightsailStaticIpAttachmentDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAWSLightsailStaticIpAttachmentConfig_basic(staticIpName, instanceName, keypairName), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckAWSLightsailStaticIpAttachmentExists("aws_lightsail_static_ip_attachment.test", &staticIp), + ), + }, + }, + }) +} + +func TestAccAWSLightsailStaticIpAttachment_disappears(t *testing.T) { + var staticIp lightsail.StaticIp + staticIpName := fmt.Sprintf("tf-test-lightsail-%s", acctest.RandString(5)) + instanceName := fmt.Sprintf("tf-test-lightsail-%s", acctest.RandString(5)) + keypairName := fmt.Sprintf("tf-test-lightsail-%s", acctest.RandString(5)) + + staticIpDestroy := func(*terraform.State) error { + conn := testAccProvider.Meta().(*AWSClient).lightsailconn + _, err := conn.DetachStaticIp(&lightsail.DetachStaticIpInput{ + StaticIpName: aws.String(staticIpName), + }) + + if err != nil { + return fmt.Errorf("Error deleting Lightsail Static IP in disappear test") + } + + return nil + } + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSLightsailStaticIpAttachmentDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAWSLightsailStaticIpAttachmentConfig_basic(staticIpName, instanceName, keypairName), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckAWSLightsailStaticIpAttachmentExists("aws_lightsail_static_ip_attachment.test", &staticIp), + staticIpDestroy, + ), + ExpectNonEmptyPlan: true, + }, + }, + }) +} + +func testAccCheckAWSLightsailStaticIpAttachmentExists(n string, staticIp *lightsail.StaticIp) resource.TestCheckFunc { + return func(s *terraform.State) error { + rs, ok := s.RootModule().Resources[n] + if !ok { + return fmt.Errorf("Not found: %s", n) + } + + if rs.Primary.ID == "" { + return errors.New("No Lightsail Static IP Attachment ID is set") + } + + conn := testAccProvider.Meta().(*AWSClient).lightsailconn + + resp, err := conn.GetStaticIp(&lightsail.GetStaticIpInput{ + StaticIpName: aws.String(rs.Primary.ID), + }) + if err != nil { + return err + } + + if resp == nil || resp.StaticIp == nil { + return fmt.Errorf("Static IP (%s) not found", rs.Primary.ID) + } + + if !*resp.StaticIp.IsAttached { + return fmt.Errorf("Static IP (%s) not attached", rs.Primary.ID) + } + + *staticIp = *resp.StaticIp + return nil + } +} + +func testAccCheckAWSLightsailStaticIpAttachmentDestroy(s *terraform.State) error { + for _, rs := range s.RootModule().Resources { + if rs.Type != "aws_lightsail_static_ip_attachment" { + continue + } + + conn := testAccProvider.Meta().(*AWSClient).lightsailconn + + resp, err := conn.GetStaticIp(&lightsail.GetStaticIpInput{ + StaticIpName: aws.String(rs.Primary.ID), + }) + + if err == nil { + if *resp.StaticIp.IsAttached { + return fmt.Errorf("Lightsail Static IP %q is still attached (to %q)", rs.Primary.ID, *resp.StaticIp.AttachedTo) + } + } + + // Verify the error + if awsErr, ok := err.(awserr.Error); ok { + if awsErr.Code() == "NotFoundException" { + return nil + } + } + return err + } + + return nil +} + +func testAccAWSLightsailStaticIpAttachmentConfig_basic(staticIpName, instanceName, keypairName string) string { + return fmt.Sprintf(` +provider "aws" { + region = "us-east-1" +} + +resource "aws_lightsail_static_ip_attachment" "test" { + static_ip_name = "${aws_lightsail_static_ip.test.name}" + instance_name = "${aws_lightsail_instance.test.name}" +} + +resource "aws_lightsail_static_ip" "test" { + name = "%s" +} + +resource "aws_lightsail_instance" "test" { + name = "%s" + availability_zone = "us-east-1b" + blueprint_id = "wordpress_4_6_1" + bundle_id = "micro_1_0" + key_pair_name = "${aws_lightsail_key_pair.test.name}" +} + +resource "aws_lightsail_key_pair" "test" { + name = "%s" +} +`, staticIpName, instanceName, keypairName) +} diff --git a/builtin/providers/aws/resource_aws_lightsail_static_ip_test.go b/builtin/providers/aws/resource_aws_lightsail_static_ip_test.go new file mode 100644 index 000000000..275a29f20 --- /dev/null +++ b/builtin/providers/aws/resource_aws_lightsail_static_ip_test.go @@ -0,0 +1,138 @@ +package aws + +import ( + "errors" + "fmt" + "testing" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/awserr" + "github.com/aws/aws-sdk-go/service/lightsail" + "github.com/hashicorp/terraform/helper/acctest" + "github.com/hashicorp/terraform/helper/resource" + "github.com/hashicorp/terraform/terraform" +) + +func TestAccAWSLightsailStaticIp_basic(t *testing.T) { + var staticIp lightsail.StaticIp + staticIpName := fmt.Sprintf("tf-test-lightsail-%s", acctest.RandString(5)) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSLightsailStaticIpDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAWSLightsailStaticIpConfig_basic(staticIpName), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckAWSLightsailStaticIpExists("aws_lightsail_static_ip.test", &staticIp), + ), + }, + }, + }) +} + +func TestAccAWSLightsailStaticIp_disappears(t *testing.T) { + var staticIp lightsail.StaticIp + staticIpName := fmt.Sprintf("tf-test-lightsail-%s", acctest.RandString(5)) + + staticIpDestroy := func(*terraform.State) error { + conn := testAccProvider.Meta().(*AWSClient).lightsailconn + _, err := conn.ReleaseStaticIp(&lightsail.ReleaseStaticIpInput{ + StaticIpName: aws.String(staticIpName), + }) + + if err != nil { + return fmt.Errorf("Error deleting Lightsail Static IP in disapear test") + } + + return nil + } + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSLightsailStaticIpDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAWSLightsailStaticIpConfig_basic(staticIpName), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckAWSLightsailStaticIpExists("aws_lightsail_static_ip.test", &staticIp), + staticIpDestroy, + ), + ExpectNonEmptyPlan: true, + }, + }, + }) +} + +func testAccCheckAWSLightsailStaticIpExists(n string, staticIp *lightsail.StaticIp) resource.TestCheckFunc { + return func(s *terraform.State) error { + rs, ok := s.RootModule().Resources[n] + if !ok { + return fmt.Errorf("Not found: %s", n) + } + + if rs.Primary.ID == "" { + return errors.New("No Lightsail Static IP ID is set") + } + + conn := testAccProvider.Meta().(*AWSClient).lightsailconn + + resp, err := conn.GetStaticIp(&lightsail.GetStaticIpInput{ + StaticIpName: aws.String(rs.Primary.ID), + }) + + if err != nil { + return err + } + + if resp == nil || resp.StaticIp == nil { + return fmt.Errorf("Static IP (%s) not found", rs.Primary.ID) + } + *staticIp = *resp.StaticIp + return nil + } +} + +func testAccCheckAWSLightsailStaticIpDestroy(s *terraform.State) error { + + for _, rs := range s.RootModule().Resources { + if rs.Type != "aws_lightsail_static_ip" { + continue + } + + conn := testAccProvider.Meta().(*AWSClient).lightsailconn + + resp, err := conn.GetStaticIp(&lightsail.GetStaticIpInput{ + StaticIpName: aws.String(rs.Primary.ID), + }) + + if err == nil { + if resp.StaticIp != nil { + return fmt.Errorf("Lightsail Static IP %q still exists", rs.Primary.ID) + } + } + + // Verify the error + if awsErr, ok := err.(awserr.Error); ok { + if awsErr.Code() == "NotFoundException" { + return nil + } + } + return err + } + + return nil +} + +func testAccAWSLightsailStaticIpConfig_basic(staticIpName string) string { + return fmt.Sprintf(` +provider "aws" { + region = "us-east-1" +} +resource "aws_lightsail_static_ip" "test" { + name = "%s" +} +`, staticIpName) +} diff --git a/builtin/providers/aws/resource_aws_network_acl_rule.go b/builtin/providers/aws/resource_aws_network_acl_rule.go index 5cce925c5..d3aa099fc 100644 --- a/builtin/providers/aws/resource_aws_network_acl_rule.go +++ b/builtin/providers/aws/resource_aws_network_acl_rule.go @@ -163,10 +163,14 @@ func resourceAwsNetworkAclRuleCreate(d *schema.ResourceData, meta interface{}) e // API (see issue GH-4721). Retry the `findNetworkAclRule` function until it is // visible (which in most cases is likely immediately). err = resource.Retry(3*time.Minute, func() *resource.RetryError { - _, findErr := findNetworkAclRule(d, meta) + r, findErr := findNetworkAclRule(d, meta) if findErr != nil { return resource.RetryableError(findErr) } + if r == nil { + err := fmt.Errorf("Network ACL rule (%s) not found", d.Id()) + return resource.RetryableError(err) + } return nil }) @@ -182,6 +186,11 @@ func resourceAwsNetworkAclRuleRead(d *schema.ResourceData, meta interface{}) err if err != nil { return err } + if resp == nil { + log.Printf("[DEBUG] Network ACL rule (%s) not found", d.Id()) + d.SetId("") + return nil + } d.Set("rule_number", resp.RuleNumber) d.Set("cidr_block", resp.CidrBlock) @@ -257,7 +266,11 @@ func findNetworkAclRule(d *schema.ResourceData, meta interface{}) (*ec2.NetworkA return nil, fmt.Errorf("Error Finding Network Acl Rule %d: %s", d.Get("rule_number").(int), err.Error()) } - if resp == nil || len(resp.NetworkAcls) != 1 || resp.NetworkAcls[0] == nil { + if resp == nil || len(resp.NetworkAcls) == 0 || resp.NetworkAcls[0] == nil { + // Missing NACL rule. + return nil, nil + } + if len(resp.NetworkAcls) > 1 { return nil, fmt.Errorf( "Expected to find one Network ACL, got: %#v", resp.NetworkAcls) diff --git a/builtin/providers/aws/resource_aws_network_acl_rule_test.go b/builtin/providers/aws/resource_aws_network_acl_rule_test.go index f9ab943a8..19b34cef7 100644 --- a/builtin/providers/aws/resource_aws_network_acl_rule_test.go +++ b/builtin/providers/aws/resource_aws_network_acl_rule_test.go @@ -137,6 +137,26 @@ func TestResourceAWSNetworkAclRule_validateICMPArgumentValue(t *testing.T) { } +func TestAccAWSNetworkAclRule_deleteRule(t *testing.T) { + var networkAcl ec2.NetworkAcl + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSNetworkAclRuleDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAWSNetworkAclRuleBasicConfig, + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSNetworkAclRuleExists("aws_network_acl_rule.baz", &networkAcl), + testAccCheckAWSNetworkAclRuleDelete("aws_network_acl_rule.baz"), + ), + ExpectNonEmptyPlan: true, + }, + }, + }) +} + func testAccCheckAWSNetworkAclRuleDestroy(s *terraform.State) error { for _, rs := range s.RootModule().Resources { @@ -179,7 +199,7 @@ func testAccCheckAWSNetworkAclRuleExists(n string, networkAcl *ec2.NetworkAcl) r } if rs.Primary.ID == "" { - return fmt.Errorf("No Network ACL Id is set") + return fmt.Errorf("No Network ACL Rule Id is set") } req := &ec2.DescribeNetworkAclsInput{ @@ -209,6 +229,40 @@ func testAccCheckAWSNetworkAclRuleExists(n string, networkAcl *ec2.NetworkAcl) r } } +func testAccCheckAWSNetworkAclRuleDelete(n string) resource.TestCheckFunc { + return func(s *terraform.State) error { + rs, ok := s.RootModule().Resources[n] + if !ok { + return fmt.Errorf("Not found: %s", n) + } + + if rs.Primary.ID == "" { + return fmt.Errorf("No Network ACL Rule Id is set") + } + + egress, err := strconv.ParseBool(rs.Primary.Attributes["egress"]) + if err != nil { + return err + } + ruleNo, err := strconv.ParseInt(rs.Primary.Attributes["rule_number"], 10, 64) + if err != nil { + return err + } + + conn := testAccProvider.Meta().(*AWSClient).ec2conn + _, err = conn.DeleteNetworkAclEntry(&ec2.DeleteNetworkAclEntryInput{ + NetworkAclId: aws.String(rs.Primary.Attributes["network_acl_id"]), + RuleNumber: aws.Int64(ruleNo), + Egress: aws.Bool(egress), + }) + if err != nil { + return fmt.Errorf("Error deleting Network ACL Rule (%s) in testAccCheckAWSNetworkAclRuleDelete: %s", rs.Primary.ID, err) + } + + return nil + } +} + const testAccAWSNetworkAclRuleBasicConfig = ` provider "aws" { region = "us-east-1" diff --git a/builtin/providers/aws/resource_aws_network_interface.go b/builtin/providers/aws/resource_aws_network_interface.go index 5c9f8263e..857237141 100644 --- a/builtin/providers/aws/resource_aws_network_interface.go +++ b/builtin/providers/aws/resource_aws_network_interface.go @@ -4,6 +4,7 @@ import ( "bytes" "fmt" "log" + "math" "strconv" "time" @@ -33,6 +34,12 @@ func resourceAwsNetworkInterface() *schema.Resource { ForceNew: true, }, + "private_ip": &schema.Schema{ + Type: schema.TypeString, + Optional: true, + Computed: true, + }, + "private_ips": &schema.Schema{ Type: schema.TypeSet, Optional: true, @@ -41,6 +48,12 @@ func resourceAwsNetworkInterface() *schema.Resource { Set: schema.HashString, }, + "private_ips_count": &schema.Schema{ + Type: schema.TypeInt, + Optional: true, + Computed: true, + }, + "security_groups": &schema.Schema{ Type: schema.TypeSet, Optional: true, @@ -110,6 +123,10 @@ func resourceAwsNetworkInterfaceCreate(d *schema.ResourceData, meta interface{}) request.Description = aws.String(v.(string)) } + if v, ok := d.GetOk("private_ips_count"); ok { + request.SecondaryPrivateIpAddressCount = aws.Int64(int64(v.(int))) + } + log.Printf("[DEBUG] Creating network interface") resp, err := conn.CreateNetworkInterface(request) if err != nil { @@ -144,6 +161,7 @@ func resourceAwsNetworkInterfaceRead(d *schema.ResourceData, meta interface{}) e eni := describeResp.NetworkInterfaces[0] d.Set("subnet_id", eni.SubnetId) + d.Set("private_ip", eni.PrivateIpAddress) d.Set("private_ips", flattenNetworkInterfacesPrivateIPAddresses(eni.PrivateIpAddresses)) d.Set("security_groups", flattenGroupIdentifiers(eni.Groups)) d.Set("source_dest_check", eni.SourceDestCheck) @@ -300,6 +318,49 @@ func resourceAwsNetworkInterfaceUpdate(d *schema.ResourceData, meta interface{}) d.SetPartial("source_dest_check") + if d.HasChange("private_ips_count") { + o, n := d.GetChange("private_ips_count") + private_ips := d.Get("private_ips").(*schema.Set).List() + private_ips_filtered := private_ips[:0] + primary_ip := d.Get("private_ip") + + for _, ip := range private_ips { + if ip != primary_ip { + private_ips_filtered = append(private_ips_filtered, ip) + } + } + + if o != nil && o != 0 && n != nil && n != len(private_ips_filtered) { + + diff := n.(int) - o.(int) + + // Surplus of IPs, add the diff + if diff > 0 { + input := &ec2.AssignPrivateIpAddressesInput{ + NetworkInterfaceId: aws.String(d.Id()), + SecondaryPrivateIpAddressCount: aws.Int64(int64(diff)), + } + _, err := conn.AssignPrivateIpAddresses(input) + if err != nil { + return fmt.Errorf("Failure to assign Private IPs: %s", err) + } + } + + if diff < 0 { + input := &ec2.UnassignPrivateIpAddressesInput{ + NetworkInterfaceId: aws.String(d.Id()), + PrivateIpAddresses: expandStringList(private_ips_filtered[0:int(math.Abs(float64(diff)))]), + } + _, err := conn.UnassignPrivateIpAddresses(input) + if err != nil { + return fmt.Errorf("Failure to unassign Private IPs: %s", err) + } + } + + d.SetPartial("private_ips_count") + } + } + if d.HasChange("security_groups") { request := &ec2.ModifyNetworkInterfaceAttributeInput{ NetworkInterfaceId: aws.String(d.Id()), diff --git a/builtin/providers/aws/resource_aws_network_interface_attachment.go b/builtin/providers/aws/resource_aws_network_interface_attachment.go new file mode 100644 index 000000000..c37b0d18f --- /dev/null +++ b/builtin/providers/aws/resource_aws_network_interface_attachment.go @@ -0,0 +1,166 @@ +package aws + +import ( + "fmt" + "log" + "time" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/awserr" + "github.com/aws/aws-sdk-go/service/ec2" + "github.com/hashicorp/terraform/helper/resource" + "github.com/hashicorp/terraform/helper/schema" +) + +func resourceAwsNetworkInterfaceAttachment() *schema.Resource { + return &schema.Resource{ + Create: resourceAwsNetworkInterfaceAttachmentCreate, + Read: resourceAwsNetworkInterfaceAttachmentRead, + Delete: resourceAwsNetworkInterfaceAttachmentDelete, + + Schema: map[string]*schema.Schema{ + "device_index": { + Type: schema.TypeInt, + Required: true, + ForceNew: true, + }, + + "instance_id": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + + "network_interface_id": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + + "attachment_id": { + Type: schema.TypeString, + Computed: true, + }, + + "status": { + Type: schema.TypeString, + Computed: true, + }, + }, + } +} + +func resourceAwsNetworkInterfaceAttachmentCreate(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*AWSClient).ec2conn + + device_index := d.Get("device_index").(int) + instance_id := d.Get("instance_id").(string) + network_interface_id := d.Get("network_interface_id").(string) + + opts := &ec2.AttachNetworkInterfaceInput{ + DeviceIndex: aws.Int64(int64(device_index)), + InstanceId: aws.String(instance_id), + NetworkInterfaceId: aws.String(network_interface_id), + } + + log.Printf("[DEBUG] Attaching network interface (%s) to instance (%s)", network_interface_id, instance_id) + resp, err := conn.AttachNetworkInterface(opts) + if err != nil { + if awsErr, ok := err.(awserr.Error); ok { + return fmt.Errorf("Error attaching network interface (%s) to instance (%s), message: \"%s\", code: \"%s\"", + network_interface_id, instance_id, awsErr.Message(), awsErr.Code()) + } + return err + } + + stateConf := &resource.StateChangeConf{ + Pending: []string{"false"}, + Target: []string{"true"}, + Refresh: networkInterfaceAttachmentRefreshFunc(conn, network_interface_id), + Timeout: 5 * time.Minute, + Delay: 10 * time.Second, + MinTimeout: 3 * time.Second, + } + + _, err = stateConf.WaitForState() + if err != nil { + return fmt.Errorf( + "Error waiting for Volume (%s) to attach to Instance: %s, error: %s", network_interface_id, instance_id, err) + } + + d.SetId(*resp.AttachmentId) + return resourceAwsNetworkInterfaceAttachmentRead(d, meta) +} + +func resourceAwsNetworkInterfaceAttachmentRead(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*AWSClient).ec2conn + + interfaceId := d.Get("network_interface_id").(string) + + req := &ec2.DescribeNetworkInterfacesInput{ + NetworkInterfaceIds: []*string{aws.String(interfaceId)}, + } + + resp, err := conn.DescribeNetworkInterfaces(req) + if err != nil { + if ec2err, ok := err.(awserr.Error); ok && ec2err.Code() == "InvalidNetworkInterfaceID.NotFound" { + // The ENI is gone now, so just remove the attachment from the state + d.SetId("") + return nil + } + + return fmt.Errorf("Error retrieving ENI: %s", err) + } + if len(resp.NetworkInterfaces) != 1 { + return fmt.Errorf("Unable to find ENI (%s): %#v", interfaceId, resp.NetworkInterfaces) + } + + eni := resp.NetworkInterfaces[0] + + if eni.Attachment == nil { + // Interface is no longer attached, remove from state + d.SetId("") + return nil + } + + d.Set("attachment_id", eni.Attachment.AttachmentId) + d.Set("device_index", eni.Attachment.DeviceIndex) + d.Set("instance_id", eni.Attachment.InstanceId) + d.Set("network_interface_id", eni.NetworkInterfaceId) + d.Set("status", eni.Attachment.Status) + + return nil +} + +func resourceAwsNetworkInterfaceAttachmentDelete(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*AWSClient).ec2conn + + interfaceId := d.Get("network_interface_id").(string) + + detach_request := &ec2.DetachNetworkInterfaceInput{ + AttachmentId: aws.String(d.Id()), + Force: aws.Bool(true), + } + + _, detach_err := conn.DetachNetworkInterface(detach_request) + if detach_err != nil { + if awsErr, _ := detach_err.(awserr.Error); awsErr.Code() != "InvalidAttachmentID.NotFound" { + return fmt.Errorf("Error detaching ENI: %s", detach_err) + } + } + + log.Printf("[DEBUG] Waiting for ENI (%s) to become dettached", interfaceId) + stateConf := &resource.StateChangeConf{ + Pending: []string{"true"}, + Target: []string{"false"}, + Refresh: networkInterfaceAttachmentRefreshFunc(conn, interfaceId), + Timeout: 10 * time.Minute, + } + + if _, err := stateConf.WaitForState(); err != nil { + return fmt.Errorf( + "Error waiting for ENI (%s) to become dettached: %s", interfaceId, err) + } + + return nil +} diff --git a/builtin/providers/aws/resource_aws_network_interface_attacment_test.go b/builtin/providers/aws/resource_aws_network_interface_attacment_test.go new file mode 100644 index 000000000..b6b1aa0eb --- /dev/null +++ b/builtin/providers/aws/resource_aws_network_interface_attacment_test.go @@ -0,0 +1,92 @@ +package aws + +import ( + "fmt" + "testing" + + "github.com/aws/aws-sdk-go/service/ec2" + "github.com/hashicorp/terraform/helper/acctest" + "github.com/hashicorp/terraform/helper/resource" +) + +func TestAccAWSNetworkInterfaceAttachment_basic(t *testing.T) { + var conf ec2.NetworkInterface + rInt := acctest.RandInt() + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + IDRefreshName: "aws_network_interface.bar", + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSENIDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAWSNetworkInterfaceAttachmentConfig_basic(rInt), + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSENIExists("aws_network_interface.bar", &conf), + resource.TestCheckResourceAttr( + "aws_network_interface_attachment.test", "device_index", "1"), + resource.TestCheckResourceAttrSet( + "aws_network_interface_attachment.test", "instance_id"), + resource.TestCheckResourceAttrSet( + "aws_network_interface_attachment.test", "network_interface_id"), + resource.TestCheckResourceAttrSet( + "aws_network_interface_attachment.test", "attachment_id"), + resource.TestCheckResourceAttrSet( + "aws_network_interface_attachment.test", "status"), + ), + }, + }, + }) +} + +func testAccAWSNetworkInterfaceAttachmentConfig_basic(rInt int) string { + return fmt.Sprintf(` +resource "aws_vpc" "foo" { + cidr_block = "172.16.0.0/16" +} + +resource "aws_subnet" "foo" { + vpc_id = "${aws_vpc.foo.id}" + cidr_block = "172.16.10.0/24" + availability_zone = "us-west-2a" +} + +resource "aws_security_group" "foo" { + vpc_id = "${aws_vpc.foo.id}" + description = "foo" + name = "foo-%d" + + egress { + from_port = 0 + to_port = 0 + protocol = "tcp" + cidr_blocks = ["10.0.0.0/16"] + } +} + +resource "aws_network_interface" "bar" { + subnet_id = "${aws_subnet.foo.id}" + private_ips = ["172.16.10.100"] + security_groups = ["${aws_security_group.foo.id}"] + description = "Managed by Terraform" + tags { + Name = "bar_interface" + } +} + +resource "aws_instance" "foo" { + ami = "ami-c5eabbf5" + instance_type = "t2.micro" + subnet_id = "${aws_subnet.foo.id}" + tags { + Name = "foo-%d" + } +} + +resource "aws_network_interface_attachment" "test" { + device_index = 1 + instance_id = "${aws_instance.foo.id}" + network_interface_id = "${aws_network_interface.bar.id}" +} +`, rInt, rInt) +} diff --git a/builtin/providers/aws/resource_aws_opsworks_application.go b/builtin/providers/aws/resource_aws_opsworks_application.go index 3ffdb9ae4..7333018e5 100644 --- a/builtin/providers/aws/resource_aws_opsworks_application.go +++ b/builtin/providers/aws/resource_aws_opsworks_application.go @@ -102,8 +102,9 @@ func resourceAwsOpsworksApplication() *schema.Resource { }, "password": { - Type: schema.TypeString, - Optional: true, + Type: schema.TypeString, + Optional: true, + Sensitive: true, }, "revision": { @@ -187,8 +188,9 @@ func resourceAwsOpsworksApplication() *schema.Resource { }, }, "private_key": { - Type: schema.TypeString, - Required: true, + Type: schema.TypeString, + Required: true, + Sensitive: true, StateFunc: func(v interface{}) string { switch v.(type) { case string: diff --git a/builtin/providers/aws/resource_aws_opsworks_instance.go b/builtin/providers/aws/resource_aws_opsworks_instance.go index 0e42e30f0..ab7a7f471 100644 --- a/builtin/providers/aws/resource_aws_opsworks_instance.go +++ b/builtin/providers/aws/resource_aws_opsworks_instance.go @@ -111,6 +111,7 @@ func resourceAwsOpsworksInstance() *schema.Resource { Type: schema.TypeString, Optional: true, Computed: true, + ForceNew: true, }, "infrastructure_class": { @@ -565,6 +566,10 @@ func resourceAwsOpsworksInstanceRead(d *schema.ResourceData, meta interface{}) e for _, v := range instance.LayerIds { layerIds = append(layerIds, *v) } + layerIds, err = sortListBasedonTFFile(layerIds, d, "layer_ids") + if err != nil { + return fmt.Errorf("[DEBUG] Error sorting layer_ids attribute: %#v", err) + } if err := d.Set("layer_ids", layerIds); err != nil { return fmt.Errorf("[DEBUG] Error setting layer_ids attribute: %#v, error: %#v", layerIds, err) } @@ -777,7 +782,7 @@ func resourceAwsOpsworksInstanceCreate(d *schema.ResourceData, meta interface{}) d.Set("id", instanceId) if v, ok := d.GetOk("state"); ok && v.(string) == "running" { - err := startOpsworksInstance(d, meta, false) + err := startOpsworksInstance(d, meta, true) if err != nil { return err } @@ -820,7 +825,6 @@ func resourceAwsOpsworksInstanceUpdate(d *schema.ResourceData, meta interface{}) if v, ok := d.GetOk("layer_ids"); ok { req.LayerIds = expandStringList(v.([]interface{})) - } if v, ok := d.GetOk("os"); ok { @@ -857,7 +861,7 @@ func resourceAwsOpsworksInstanceUpdate(d *schema.ResourceData, meta interface{}) } } else { if status != "stopped" && status != "stopping" && status != "shutting_down" { - err := stopOpsworksInstance(d, meta, false) + err := stopOpsworksInstance(d, meta, true) if err != nil { return err } diff --git a/builtin/providers/aws/resource_aws_opsworks_instance_test.go b/builtin/providers/aws/resource_aws_opsworks_instance_test.go index ed5aaa5d8..1a2bbe0f6 100644 --- a/builtin/providers/aws/resource_aws_opsworks_instance_test.go +++ b/builtin/providers/aws/resource_aws_opsworks_instance_test.go @@ -108,6 +108,44 @@ func TestAccAWSOpsworksInstance(t *testing.T) { }) } +func TestAccAWSOpsworksInstance_UpdateHostNameForceNew(t *testing.T) { + stackName := fmt.Sprintf("tf-%d", acctest.RandInt()) + + var before, after opsworks.Instance + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAwsOpsworksInstanceDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAwsOpsworksInstanceConfigCreate(stackName), + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSOpsworksInstanceExists("aws_opsworks_instance.tf-acc", &before), + resource.TestCheckResourceAttr("aws_opsworks_instance.tf-acc", "hostname", "tf-acc1"), + ), + }, + { + Config: testAccAwsOpsworksInstanceConfigUpdateHostName(stackName), + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSOpsworksInstanceExists("aws_opsworks_instance.tf-acc", &after), + resource.TestCheckResourceAttr("aws_opsworks_instance.tf-acc", "hostname", "tf-acc2"), + testAccCheckAwsOpsworksInstanceRecreated(t, &before, &after), + ), + }, + }, + }) +} + +func testAccCheckAwsOpsworksInstanceRecreated(t *testing.T, + before, after *opsworks.Instance) resource.TestCheckFunc { + return func(s *terraform.State) error { + if *before.InstanceId == *after.InstanceId { + t.Fatalf("Expected change of OpsWorks Instance IDs, but both were %s", *before.InstanceId) + } + return nil + } +} + func testAccCheckAWSOpsworksInstanceExists( n string, opsinst *opsworks.Instance) resource.TestCheckFunc { return func(s *terraform.State) error { @@ -197,6 +235,59 @@ func testAccCheckAwsOpsworksInstanceDestroy(s *terraform.State) error { return fmt.Errorf("Fall through error on OpsWorks instance test") } +func testAccAwsOpsworksInstanceConfigUpdateHostName(name string) string { + return fmt.Sprintf(` +resource "aws_security_group" "tf-ops-acc-web" { + name = "%s-web" + ingress { + from_port = 80 + to_port = 80 + protocol = "tcp" + cidr_blocks = ["0.0.0.0/0"] + } +} + +resource "aws_security_group" "tf-ops-acc-php" { + name = "%s-php" + ingress { + from_port = 8080 + to_port = 8080 + protocol = "tcp" + cidr_blocks = ["0.0.0.0/0"] + } +} + +resource "aws_opsworks_static_web_layer" "tf-acc" { + stack_id = "${aws_opsworks_stack.tf-acc.id}" + + custom_security_group_ids = [ + "${aws_security_group.tf-ops-acc-web.id}", + ] +} + +resource "aws_opsworks_php_app_layer" "tf-acc" { + stack_id = "${aws_opsworks_stack.tf-acc.id}" + + custom_security_group_ids = [ + "${aws_security_group.tf-ops-acc-php.id}", + ] +} + +resource "aws_opsworks_instance" "tf-acc" { + stack_id = "${aws_opsworks_stack.tf-acc.id}" + layer_ids = [ + "${aws_opsworks_static_web_layer.tf-acc.id}", + ] + instance_type = "t2.micro" + state = "stopped" + hostname = "tf-acc2" +} + +%s + +`, name, name, testAccAwsOpsworksStackConfigVpcCreate(name)) +} + func testAccAwsOpsworksInstanceConfigCreate(name string) string { return fmt.Sprintf(` resource "aws_security_group" "tf-ops-acc-web" { diff --git a/builtin/providers/aws/resource_aws_opsworks_stack.go b/builtin/providers/aws/resource_aws_opsworks_stack.go index aae83c267..496670506 100644 --- a/builtin/providers/aws/resource_aws_opsworks_stack.go +++ b/builtin/providers/aws/resource_aws_opsworks_stack.go @@ -53,6 +53,7 @@ func resourceAwsOpsworksStack() *schema.Resource { "service_role_arn": { Type: schema.TypeString, Required: true, + ForceNew: true, }, "default_instance_profile_arn": { @@ -111,8 +112,9 @@ func resourceAwsOpsworksStack() *schema.Resource { }, "password": { - Type: schema.TypeString, - Optional: true, + Type: schema.TypeString, + Optional: true, + Sensitive: true, }, "revision": { diff --git a/builtin/providers/aws/resource_aws_opsworks_stack_test.go b/builtin/providers/aws/resource_aws_opsworks_stack_test.go index eb366e33c..76c98a5fd 100644 --- a/builtin/providers/aws/resource_aws_opsworks_stack_test.go +++ b/builtin/providers/aws/resource_aws_opsworks_stack_test.go @@ -40,6 +40,33 @@ func TestAccAWSOpsworksStackNoVpc(t *testing.T) { }) } +func TestAccAWSOpsworksStackNoVpcChangeServiceRoleForceNew(t *testing.T) { + stackName := fmt.Sprintf("tf-opsworks-acc-%d", acctest.RandInt()) + var before, after opsworks.Stack + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAwsOpsworksStackDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAwsOpsworksStackConfigNoVpcCreate(stackName), + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSOpsworksStackExists( + "aws_opsworks_stack.tf-acc", false, &before), + ), + }, + { + Config: testAccAwsOpsworksStackConfigNoVpcCreateUpdateServiceRole(stackName), + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSOpsworksStackExists( + "aws_opsworks_stack.tf-acc", false, &after), + testAccCheckAWSOpsworksStackRecreated(t, &before, &after), + ), + }, + }, + }) +} + func TestAccAWSOpsworksStackVpc(t *testing.T) { stackName := fmt.Sprintf("tf-opsworks-acc-%d", acctest.RandInt()) var opsstack opsworks.Stack @@ -86,7 +113,7 @@ func TestAccAWSOpsWorksStack_classic_endpoints(t *testing.T) { Providers: testAccProviders, CheckDestroy: testAccCheckAwsOpsworksStackDestroy, Steps: []resource.TestStep{ - resource.TestStep{ + { Config: testAccAwsOpsWorksStack_classic_endpoint(stackName, rInt), Check: resource.ComposeTestCheckFunc( testAccCheckAWSOpsworksStackExists( @@ -94,7 +121,7 @@ func TestAccAWSOpsWorksStack_classic_endpoints(t *testing.T) { ), }, // Ensure that changing to us-west-2 region results in no plan - resource.TestStep{ + { Config: testAccAwsOpsWorksStack_regional_endpoint(stackName, rInt), PlanOnly: true, }, @@ -103,6 +130,16 @@ func TestAccAWSOpsWorksStack_classic_endpoints(t *testing.T) { } +func testAccCheckAWSOpsworksStackRecreated(t *testing.T, + before, after *opsworks.Stack) resource.TestCheckFunc { + return func(s *terraform.State) error { + if *before.StackId == *after.StackId { + t.Fatalf("Expected change of Opsworks StackIds, but both were %v", before.StackId) + } + return nil + } +} + func testAccAwsOpsWorksStack_classic_endpoint(rName string, rInt int) string { return fmt.Sprintf(` provider "aws" { @@ -625,6 +662,131 @@ resource "aws_iam_instance_profile" "opsworks_instance" { }`, name, name, name, name, name) } +func testAccAwsOpsworksStackConfigNoVpcCreateUpdateServiceRole(name string) string { + return fmt.Sprintf(` +provider "aws" { + region = "us-east-1" +} +resource "aws_opsworks_stack" "tf-acc" { + name = "%s" + region = "us-east-1" + service_role_arn = "${aws_iam_role.opsworks_service_new.arn}" + default_instance_profile_arn = "${aws_iam_instance_profile.opsworks_instance.arn}" + default_availability_zone = "us-east-1a" + default_os = "Amazon Linux 2016.09" + default_root_device_type = "ebs" + custom_json = "{\"key\": \"value\"}" + configuration_manager_version = "11.10" + use_opsworks_security_groups = false +} + +resource "aws_iam_role" "opsworks_service" { + name = "%s_opsworks_service" + assume_role_policy = <100 records to verify pagination works ok testAccCreateRandomRoute53RecordsInZoneIdWithProviders(&providers, &zone, 100), testAccCreateRandomRoute53RecordsInZoneIdWithProviders(&providers, &zone, 5), + + testAccCheckRoute53ZoneExistsWithProviders("aws_route53_zone.with_trailing_dot", &zoneWithDot, &providers), + // Add >100 records to verify pagination works ok + testAccCreateRandomRoute53RecordsInZoneIdWithProviders(&providers, &zoneWithDot, 100), + testAccCreateRandomRoute53RecordsInZoneIdWithProviders(&providers, &zoneWithDot, 5), ), }, }, @@ -417,6 +422,11 @@ resource "aws_route53_zone" "destroyable" { name = "terraform.io" force_destroy = true } + +resource "aws_route53_zone" "with_trailing_dot" { + name = "hashicorptest.io." + force_destroy = true +} ` const testAccRoute53ZoneConfigUpdateComment = ` diff --git a/builtin/providers/aws/resource_aws_route_table.go b/builtin/providers/aws/resource_aws_route_table.go index c92dbde16..242e28b2d 100644 --- a/builtin/providers/aws/resource_aws_route_table.go +++ b/builtin/providers/aws/resource_aws_route_table.go @@ -120,7 +120,7 @@ func resourceAwsRouteTableCreate(d *schema.ResourceData, meta interface{}) error Pending: []string{"pending"}, Target: []string{"ready"}, Refresh: resourceAwsRouteTableStateRefreshFunc(conn, d.Id()), - Timeout: 2 * time.Minute, + Timeout: 5 * time.Minute, } if _, err := stateConf.WaitForState(); err != nil { return fmt.Errorf( @@ -353,7 +353,7 @@ func resourceAwsRouteTableUpdate(d *schema.ResourceData, meta interface{}) error } log.Printf("[INFO] Creating route for %s: %#v", d.Id(), opts) - err := resource.Retry(1*time.Minute, func() *resource.RetryError { + err := resource.Retry(5*time.Minute, func() *resource.RetryError { _, err := conn.CreateRoute(&opts) if err != nil { if awsErr, ok := err.(awserr.Error); ok { @@ -439,7 +439,7 @@ func resourceAwsRouteTableDelete(d *schema.ResourceData, meta interface{}) error Pending: []string{"ready"}, Target: []string{}, Refresh: resourceAwsRouteTableStateRefreshFunc(conn, d.Id()), - Timeout: 2 * time.Minute, + Timeout: 5 * time.Minute, } if _, err := stateConf.WaitForState(); err != nil { return fmt.Errorf( @@ -452,7 +452,10 @@ func resourceAwsRouteTableDelete(d *schema.ResourceData, meta interface{}) error func resourceAwsRouteTableHash(v interface{}) int { var buf bytes.Buffer - m := v.(map[string]interface{}) + m, castOk := v.(map[string]interface{}) + if !castOk { + return 0 + } if v, ok := m["ipv6_cidr_block"]; ok { buf.WriteString(fmt.Sprintf("%s-", v.(string))) diff --git a/builtin/providers/aws/resource_aws_route_table_association.go b/builtin/providers/aws/resource_aws_route_table_association.go index d68107859..eb2c19409 100644 --- a/builtin/providers/aws/resource_aws_route_table_association.go +++ b/builtin/providers/aws/resource_aws_route_table_association.go @@ -49,7 +49,7 @@ func resourceAwsRouteTableAssociationCreate(d *schema.ResourceData, meta interfa var resp *ec2.AssociateRouteTableOutput var err error - err = resource.Retry(2*time.Minute, func() *resource.RetryError { + err = resource.Retry(5*time.Minute, func() *resource.RetryError { resp, err = conn.AssociateRouteTable(&associationOpts) if err != nil { if awsErr, ok := err.(awserr.Error); ok { diff --git a/builtin/providers/aws/resource_aws_route_table_test.go b/builtin/providers/aws/resource_aws_route_table_test.go index 68fd9237b..b4b764d37 100644 --- a/builtin/providers/aws/resource_aws_route_table_test.go +++ b/builtin/providers/aws/resource_aws_route_table_test.go @@ -2,6 +2,7 @@ package aws import ( "fmt" + "regexp" "testing" "github.com/aws/aws-sdk-go/aws" @@ -183,6 +184,22 @@ func TestAccAWSRouteTable_tags(t *testing.T) { }) } +// For GH-13545, Fixes panic on an empty route config block +func TestAccAWSRouteTable_panicEmptyRoute(t *testing.T) { + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + IDRefreshName: "aws_route_table.foo", + Providers: testAccProviders, + CheckDestroy: testAccCheckRouteTableDestroy, + Steps: []resource.TestStep{ + { + Config: testAccRouteTableConfigPanicEmptyRoute, + ExpectError: regexp.MustCompile("The request must contain the parameter destinationCidrBlock or destinationIpv6CidrBlock"), + }, + }, + }) +} + func testAccCheckRouteTableDestroy(s *terraform.State) error { conn := testAccProvider.Meta().(*AWSClient).ec2conn @@ -497,3 +514,17 @@ resource "aws_route_table" "foo" { propagating_vgws = ["${aws_vpn_gateway.foo.id}"] } ` + +// For GH-13545 +const testAccRouteTableConfigPanicEmptyRoute = ` +resource "aws_vpc" "foo" { + cidr_block = "10.2.0.0/16" +} + +resource "aws_route_table" "foo" { + vpc_id = "${aws_vpc.foo.id}" + + route { + } +} +` diff --git a/builtin/providers/aws/resource_aws_route_test.go b/builtin/providers/aws/resource_aws_route_test.go index a8bc00373..24459689b 100644 --- a/builtin/providers/aws/resource_aws_route_test.go +++ b/builtin/providers/aws/resource_aws_route_test.go @@ -86,6 +86,26 @@ func TestAccAWSRoute_ipv6Support(t *testing.T) { }) } +func TestAccAWSRoute_ipv6ToInternetGateway(t *testing.T) { + var route ec2.Route + + resource.Test(t, resource.TestCase{ + PreCheck: func() { + testAccPreCheck(t) + }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSRouteDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAWSRouteConfigIpv6InternetGateway, + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSRouteExists("aws_route.igw", &route), + ), + }, + }, + }) +} + func TestAccAWSRoute_changeCidr(t *testing.T) { var route ec2.Route var routeTable ec2.RouteTable @@ -288,6 +308,32 @@ resource "aws_route" "bar" { } `) +var testAccAWSRouteConfigIpv6InternetGateway = fmt.Sprintf(` +resource "aws_vpc" "foo" { + cidr_block = "10.1.0.0/16" + assign_generated_ipv6_cidr_block = true +} + +resource "aws_egress_only_internet_gateway" "foo" { + vpc_id = "${aws_vpc.foo.id}" +} + +resource "aws_internet_gateway" "foo" { + vpc_id = "${aws_vpc.foo.id}" +} + +resource "aws_route_table" "external" { + vpc_id = "${aws_vpc.foo.id}" +} + +resource "aws_route" "igw" { + route_table_id = "${aws_route_table.external.id}" + destination_ipv6_cidr_block = "::/0" + gateway_id = "${aws_internet_gateway.foo.id}" +} + +`) + var testAccAWSRouteConfigIpv6 = fmt.Sprintf(` resource "aws_vpc" "foo" { cidr_block = "10.1.0.0/16" diff --git a/builtin/providers/aws/resource_aws_s3_bucket.go b/builtin/providers/aws/resource_aws_s3_bucket.go index f75824af2..7da1ac18f 100644 --- a/builtin/providers/aws/resource_aws_s3_bucket.go +++ b/builtin/providers/aws/resource_aws_s3_bucket.go @@ -31,8 +31,15 @@ func resourceAwsS3Bucket() *schema.Resource { Schema: map[string]*schema.Schema{ "bucket": { + Type: schema.TypeString, + Optional: true, + Computed: true, + ForceNew: true, + ConflictsWith: []string{"bucket_prefix"}, + }, + "bucket_prefix": { Type: schema.TypeString, - Required: true, + Optional: true, ForceNew: true, }, @@ -389,7 +396,15 @@ func resourceAwsS3BucketCreate(d *schema.ResourceData, meta interface{}) error { s3conn := meta.(*AWSClient).s3conn // Get the bucket and acl - bucket := d.Get("bucket").(string) + var bucket string + if v, ok := d.GetOk("bucket"); ok { + bucket = v.(string) + } else if v, ok := d.GetOk("bucket_prefix"); ok { + bucket = resource.PrefixedUniqueId(v.(string)) + } else { + bucket = resource.UniqueId() + } + d.Set("bucket", bucket) acl := d.Get("acl").(string) log.Printf("[DEBUG] S3 bucket create: %s, ACL: %s", bucket, acl) @@ -728,8 +743,8 @@ func resourceAwsS3BucketRead(d *schema.ResourceData, meta interface{}) error { } log.Printf("[DEBUG] S3 Bucket: %s, logging: %v", d.Id(), logging) + lcl := make([]map[string]interface{}, 0, 1) if v := logging.LoggingEnabled; v != nil { - lcl := make([]map[string]interface{}, 0, 1) lc := make(map[string]interface{}) if *v.TargetBucket != "" { lc["target_bucket"] = *v.TargetBucket @@ -738,9 +753,9 @@ func resourceAwsS3BucketRead(d *schema.ResourceData, meta interface{}) error { lc["target_prefix"] = *v.TargetPrefix } lcl = append(lcl, lc) - if err := d.Set("logging", lcl); err != nil { - return err - } + } + if err := d.Set("logging", lcl); err != nil { + return err } // Read the lifecycle configuration diff --git a/builtin/providers/aws/resource_aws_s3_bucket_object.go b/builtin/providers/aws/resource_aws_s3_bucket_object.go index 968344f69..c14914187 100644 --- a/builtin/providers/aws/resource_aws_s3_bucket_object.go +++ b/builtin/providers/aws/resource_aws_s3_bucket_object.go @@ -127,6 +127,8 @@ func resourceAwsS3BucketObject() *schema.Resource { func resourceAwsS3BucketObjectPut(d *schema.ResourceData, meta interface{}) error { s3conn := meta.(*AWSClient).s3conn + restricted := meta.(*AWSClient).IsGovCloud() || meta.(*AWSClient).IsChinaCloud() + var body io.ReadSeeker if v, ok := d.GetOk("source"); ok { @@ -192,6 +194,10 @@ func resourceAwsS3BucketObjectPut(d *schema.ResourceData, meta interface{}) erro } if v, ok := d.GetOk("tags"); ok { + if restricted { + return fmt.Errorf("This region does not allow for tags on S3 objects") + } + // The tag-set must be encoded as URL Query parameters. values := url.Values{} for k, v := range v.(map[string]interface{}) { @@ -216,6 +222,8 @@ func resourceAwsS3BucketObjectPut(d *schema.ResourceData, meta interface{}) erro func resourceAwsS3BucketObjectRead(d *schema.ResourceData, meta interface{}) error { s3conn := meta.(*AWSClient).s3conn + restricted := meta.(*AWSClient).IsGovCloud() || meta.(*AWSClient).IsChinaCloud() + bucket := d.Get("bucket").(string) key := d.Get("key").(string) @@ -269,15 +277,17 @@ func resourceAwsS3BucketObjectRead(d *schema.ResourceData, meta interface{}) err d.Set("storage_class", resp.StorageClass) } - tagResp, err := s3conn.GetObjectTagging( - &s3.GetObjectTaggingInput{ - Bucket: aws.String(bucket), - Key: aws.String(key), - }) - if err != nil { - return fmt.Errorf("Failed to get object tags (bucket: %s, key: %s): %s", bucket, key, err) + if !restricted { + tagResp, err := s3conn.GetObjectTagging( + &s3.GetObjectTaggingInput{ + Bucket: aws.String(bucket), + Key: aws.String(key), + }) + if err != nil { + return fmt.Errorf("Failed to get object tags (bucket: %s, key: %s): %s", bucket, key, err) + } + d.Set("tags", tagsToMapS3(tagResp.TagSet)) } - d.Set("tags", tagsToMapS3(tagResp.TagSet)) return nil } diff --git a/builtin/providers/aws/resource_aws_s3_bucket_test.go b/builtin/providers/aws/resource_aws_s3_bucket_test.go index ff18b7810..a12c8ec54 100644 --- a/builtin/providers/aws/resource_aws_s3_bucket_test.go +++ b/builtin/providers/aws/resource_aws_s3_bucket_test.go @@ -56,6 +56,40 @@ func TestAccAWSS3Bucket_basic(t *testing.T) { }) } +func TestAccAWSS3Bucket_namePrefix(t *testing.T) { + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSS3BucketDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAWSS3BucketConfig_namePrefix, + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSS3BucketExists("aws_s3_bucket.test"), + resource.TestMatchResourceAttr( + "aws_s3_bucket.test", "bucket", regexp.MustCompile("^tf-test-")), + ), + }, + }, + }) +} + +func TestAccAWSS3Bucket_generatedName(t *testing.T) { + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSS3BucketDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAWSS3BucketConfig_generatedName, + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSS3BucketExists("aws_s3_bucket.test"), + ), + }, + }, + }) +} + func TestAccAWSS3Bucket_region(t *testing.T) { rInt := acctest.RandInt() @@ -1601,3 +1635,15 @@ resource "aws_s3_bucket" "destination" { } `, randInt, randInt, randInt) } + +const testAccAWSS3BucketConfig_namePrefix = ` +resource "aws_s3_bucket" "test" { + bucket_prefix = "tf-test-" +} +` + +const testAccAWSS3BucketConfig_generatedName = ` +resource "aws_s3_bucket" "test" { + bucket_prefix = "tf-test-" +} +` diff --git a/builtin/providers/aws/resource_aws_security_group.go b/builtin/providers/aws/resource_aws_security_group.go index e702c1aa0..8b83b56b5 100644 --- a/builtin/providers/aws/resource_aws_security_group.go +++ b/builtin/providers/aws/resource_aws_security_group.go @@ -253,7 +253,7 @@ func resourceAwsSecurityGroupCreate(d *schema.ResourceData, meta interface{}) er Pending: []string{""}, Target: []string{"exists"}, Refresh: SGStateRefreshFunc(conn, d.Id()), - Timeout: 1 * time.Minute, + Timeout: 3 * time.Minute, } resp, err := stateConf.WaitForState() diff --git a/builtin/providers/aws/resource_aws_security_group_test.go b/builtin/providers/aws/resource_aws_security_group_test.go index f1fe67ca9..f5a4f8d16 100644 --- a/builtin/providers/aws/resource_aws_security_group_test.go +++ b/builtin/providers/aws/resource_aws_security_group_test.go @@ -1995,6 +1995,91 @@ resource "aws_security_group_rule" "allow_test_group_3" { } ` +const testAccAWSSecurityGroupConfig_importIPRangeAndSecurityGroupWithSameRules = ` +resource "aws_vpc" "foo" { + cidr_block = "10.1.0.0/16" + + tags { + Name = "tf_sg_import_test" + } +} + +resource "aws_security_group" "test_group_1" { + name = "test group 1" + vpc_id = "${aws_vpc.foo.id}" +} + +resource "aws_security_group" "test_group_2" { + name = "test group 2" + vpc_id = "${aws_vpc.foo.id}" +} + +resource "aws_security_group_rule" "allow_security_group" { + type = "ingress" + from_port = 0 + to_port = 0 + protocol = "tcp" + + source_security_group_id = "${aws_security_group.test_group_2.id}" + security_group_id = "${aws_security_group.test_group_1.id}" +} + +resource "aws_security_group_rule" "allow_cidr_block" { + type = "ingress" + from_port = 0 + to_port = 0 + protocol = "tcp" + + cidr_blocks = ["10.0.0.0/32"] + security_group_id = "${aws_security_group.test_group_1.id}" +} + +resource "aws_security_group_rule" "allow_ipv6_cidr_block" { + type = "ingress" + from_port = 0 + to_port = 0 + protocol = "tcp" + + ipv6_cidr_blocks = ["::/0"] + security_group_id = "${aws_security_group.test_group_1.id}" +} +` + +const testAccAWSSecurityGroupConfig_importIPRangesWithSameRules = ` +resource "aws_vpc" "foo" { + cidr_block = "10.1.0.0/16" + + tags { + Name = "tf_sg_import_test" + } +} + +resource "aws_security_group" "test_group_1" { + name = "test group 1" + vpc_id = "${aws_vpc.foo.id}" +} + +resource "aws_security_group_rule" "allow_cidr_block" { + type = "ingress" + from_port = 0 + to_port = 0 + protocol = "tcp" + + cidr_blocks = ["10.0.0.0/32"] + security_group_id = "${aws_security_group.test_group_1.id}" +} + +resource "aws_security_group_rule" "allow_ipv6_cidr_block" { + type = "ingress" + from_port = 0 + to_port = 0 + protocol = "tcp" + + ipv6_cidr_blocks = ["::/0"] + security_group_id = "${aws_security_group.test_group_1.id}" +} +` + const testAccAWSSecurityGroupConfigPrefixListEgress = ` resource "aws_vpc" "tf_sg_prefix_list_egress_test" { cidr_block = "10.0.0.0/16" diff --git a/builtin/providers/aws/resource_aws_ses_configuration_set_test.go b/builtin/providers/aws/resource_aws_ses_configuration_set_test.go index 7cbbe4232..5a5bd1ec8 100644 --- a/builtin/providers/aws/resource_aws_ses_configuration_set_test.go +++ b/builtin/providers/aws/resource_aws_ses_configuration_set_test.go @@ -5,6 +5,7 @@ import ( "testing" "github.com/aws/aws-sdk-go/service/ses" + "github.com/hashicorp/terraform/helper/acctest" "github.com/hashicorp/terraform/helper/resource" "github.com/hashicorp/terraform/terraform" ) @@ -42,7 +43,7 @@ func testAccCheckSESConfigurationSetDestroy(s *terraform.State) error { found := false for _, element := range response.ConfigurationSets { - if *element.Name == "some-configuration-set" { + if *element.Name == fmt.Sprintf("some-configuration-set-%d", escRandomInteger) { found = true } } @@ -77,7 +78,7 @@ func testAccCheckAwsSESConfigurationSetExists(n string) resource.TestCheckFunc { found := false for _, element := range response.ConfigurationSets { - if *element.Name == "some-configuration-set" { + if *element.Name == fmt.Sprintf("some-configuration-set-%d", escRandomInteger) { found = true } } @@ -90,8 +91,9 @@ func testAccCheckAwsSESConfigurationSetExists(n string) resource.TestCheckFunc { } } -const testAccAWSSESConfigurationSetConfig = ` +var escRandomInteger = acctest.RandInt() +var testAccAWSSESConfigurationSetConfig = fmt.Sprintf(` resource "aws_ses_configuration_set" "test" { - name = "some-configuration-set" + name = "some-configuration-set-%d" } -` +`, escRandomInteger) diff --git a/builtin/providers/aws/resource_aws_ses_domain_identity.go b/builtin/providers/aws/resource_aws_ses_domain_identity.go new file mode 100644 index 000000000..734030cc7 --- /dev/null +++ b/builtin/providers/aws/resource_aws_ses_domain_identity.go @@ -0,0 +1,103 @@ +package aws + +import ( + "fmt" + "log" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/service/ses" + "github.com/hashicorp/terraform/helper/schema" +) + +func resourceAwsSesDomainIdentity() *schema.Resource { + return &schema.Resource{ + Create: resourceAwsSesDomainIdentityCreate, + Read: resourceAwsSesDomainIdentityRead, + Delete: resourceAwsSesDomainIdentityDelete, + Importer: &schema.ResourceImporter{ + State: schema.ImportStatePassthrough, + }, + + Schema: map[string]*schema.Schema{ + "arn": { + Type: schema.TypeString, + Computed: true, + }, + "domain": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + "verification_token": { + Type: schema.TypeString, + Computed: true, + }, + }, + } +} + +func resourceAwsSesDomainIdentityCreate(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*AWSClient).sesConn + + domainName := d.Get("domain").(string) + + createOpts := &ses.VerifyDomainIdentityInput{ + Domain: aws.String(domainName), + } + + _, err := conn.VerifyDomainIdentity(createOpts) + if err != nil { + return fmt.Errorf("Error requesting SES domain identity verification: %s", err) + } + + d.SetId(domainName) + + return resourceAwsSesDomainIdentityRead(d, meta) +} + +func resourceAwsSesDomainIdentityRead(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*AWSClient).sesConn + + domainName := d.Id() + d.Set("domain", domainName) + + readOpts := &ses.GetIdentityVerificationAttributesInput{ + Identities: []*string{ + aws.String(domainName), + }, + } + + response, err := conn.GetIdentityVerificationAttributes(readOpts) + if err != nil { + log.Printf("[WARN] Error fetching identity verification attributes for %s: %s", d.Id(), err) + return err + } + + verificationAttrs, ok := response.VerificationAttributes[domainName] + if !ok { + log.Printf("[WARN] Domain not listed in response when fetching verification attributes for %s", d.Id()) + d.SetId("") + return nil + } + + d.Set("arn", fmt.Sprintf("arn:%s:ses:%s:%s:identity/%s", meta.(*AWSClient).partition, meta.(*AWSClient).region, meta.(*AWSClient).accountid, d.Id())) + d.Set("verification_token", verificationAttrs.VerificationToken) + return nil +} + +func resourceAwsSesDomainIdentityDelete(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*AWSClient).sesConn + + domainName := d.Get("domain").(string) + + deleteOpts := &ses.DeleteIdentityInput{ + Identity: aws.String(domainName), + } + + _, err := conn.DeleteIdentity(deleteOpts) + if err != nil { + return fmt.Errorf("Error deleting SES domain identity: %s", err) + } + + return nil +} diff --git a/builtin/providers/aws/resource_aws_ses_domain_identity_test.go b/builtin/providers/aws/resource_aws_ses_domain_identity_test.go new file mode 100644 index 000000000..a151c39cf --- /dev/null +++ b/builtin/providers/aws/resource_aws_ses_domain_identity_test.go @@ -0,0 +1,121 @@ +package aws + +import ( + "fmt" + "testing" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/service/ses" + "github.com/hashicorp/terraform/helper/acctest" + "github.com/hashicorp/terraform/helper/resource" + "github.com/hashicorp/terraform/terraform" +) + +func TestAccAwsSESDomainIdentity_basic(t *testing.T) { + domain := fmt.Sprintf( + "%s.terraformtesting.com", + acctest.RandStringFromCharSet(10, acctest.CharSetAlphaNum)) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { + testAccPreCheck(t) + }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAwsSESDomainIdentityDestroy, + Steps: []resource.TestStep{ + { + Config: fmt.Sprintf(testAccAwsSESDomainIdentityConfig, domain), + Check: resource.ComposeTestCheckFunc( + testAccCheckAwsSESDomainIdentityExists("aws_ses_domain_identity.test"), + testAccCheckAwsSESDomainIdentityArn("aws_ses_domain_identity.test", domain), + ), + }, + }, + }) +} + +func testAccCheckAwsSESDomainIdentityDestroy(s *terraform.State) error { + conn := testAccProvider.Meta().(*AWSClient).sesConn + + for _, rs := range s.RootModule().Resources { + if rs.Type != "aws_ses_domain_identity" { + continue + } + + domain := rs.Primary.ID + params := &ses.GetIdentityVerificationAttributesInput{ + Identities: []*string{ + aws.String(domain), + }, + } + + response, err := conn.GetIdentityVerificationAttributes(params) + if err != nil { + return err + } + + if response.VerificationAttributes[domain] != nil { + return fmt.Errorf("SES Domain Identity %s still exists. Failing!", domain) + } + } + + return nil +} + +func testAccCheckAwsSESDomainIdentityExists(n string) resource.TestCheckFunc { + return func(s *terraform.State) error { + rs, ok := s.RootModule().Resources[n] + if !ok { + return fmt.Errorf("SES Domain Identity not found: %s", n) + } + + if rs.Primary.ID == "" { + return fmt.Errorf("SES Domain Identity name not set") + } + + domain := rs.Primary.ID + conn := testAccProvider.Meta().(*AWSClient).sesConn + + params := &ses.GetIdentityVerificationAttributesInput{ + Identities: []*string{ + aws.String(domain), + }, + } + + response, err := conn.GetIdentityVerificationAttributes(params) + if err != nil { + return err + } + + if response.VerificationAttributes[domain] == nil { + return fmt.Errorf("SES Domain Identity %s not found in AWS", domain) + } + + return nil + } +} + +func testAccCheckAwsSESDomainIdentityArn(n string, domain string) resource.TestCheckFunc { + return func(s *terraform.State) error { + rs, _ := s.RootModule().Resources[n] + + expected := fmt.Sprintf( + "arn:%s:ses:%s:%s:identity/%s", + testAccProvider.Meta().(*AWSClient).partition, + testAccProvider.Meta().(*AWSClient).region, + testAccProvider.Meta().(*AWSClient).accountid, + domain) + + if rs.Primary.Attributes["arn"] != expected { + return fmt.Errorf("Incorrect ARN: expected %q, got %q", expected, rs.Primary.Attributes["arn"]) + } + + return nil + } +} + +const testAccAwsSESDomainIdentityConfig = ` +resource "aws_ses_domain_identity" "test" { + domain = "%s" +} +` diff --git a/builtin/providers/aws/resource_aws_ses_event_destination_test.go b/builtin/providers/aws/resource_aws_ses_event_destination_test.go index 378e2042c..624ce0c83 100644 --- a/builtin/providers/aws/resource_aws_ses_event_destination_test.go +++ b/builtin/providers/aws/resource_aws_ses_event_destination_test.go @@ -5,6 +5,7 @@ import ( "testing" "github.com/aws/aws-sdk-go/service/ses" + "github.com/hashicorp/terraform/helper/acctest" "github.com/hashicorp/terraform/helper/resource" "github.com/hashicorp/terraform/terraform" ) @@ -46,7 +47,7 @@ func testAccCheckSESEventDestinationDestroy(s *terraform.State) error { found := false for _, element := range response.ConfigurationSets { - if *element.Name == "some-configuration-set" { + if *element.Name == fmt.Sprintf("some-configuration-set-%d", edRandomInteger) { found = true } } @@ -81,7 +82,7 @@ func testAccCheckAwsSESEventDestinationExists(n string) resource.TestCheckFunc { found := false for _, element := range response.ConfigurationSets { - if *element.Name == "some-configuration-set" { + if *element.Name == fmt.Sprintf("some-configuration-set-%d", edRandomInteger) { found = true } } @@ -94,7 +95,8 @@ func testAccCheckAwsSESEventDestinationExists(n string) resource.TestCheckFunc { } } -const testAccAWSSESEventDestinationConfig = ` +var edRandomInteger = acctest.RandInt() +var testAccAWSSESEventDestinationConfig = fmt.Sprintf(` resource "aws_s3_bucket" "bucket" { bucket = "tf-test-bucket-format" acl = "private" @@ -155,7 +157,7 @@ data "aws_iam_policy_document" "fh_felivery_document" { } resource "aws_ses_configuration_set" "test" { - name = "some-configuration-set" + name = "some-configuration-set-%d" } resource "aws_ses_event_destination" "kinesis" { @@ -182,4 +184,4 @@ resource "aws_ses_event_destination" "cloudwatch" { value_source = "emailHeader" } } -` +`, edRandomInteger) diff --git a/builtin/providers/aws/resource_aws_ses_receipt_rule_test.go b/builtin/providers/aws/resource_aws_ses_receipt_rule_test.go index f5770fcc4..a443ef939 100644 --- a/builtin/providers/aws/resource_aws_ses_receipt_rule_test.go +++ b/builtin/providers/aws/resource_aws_ses_receipt_rule_test.go @@ -8,6 +8,7 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/service/ses" + "github.com/hashicorp/terraform/helper/acctest" "github.com/hashicorp/terraform/helper/resource" "github.com/hashicorp/terraform/terraform" ) @@ -111,7 +112,7 @@ func testAccCheckAwsSESReceiptRuleExists(n string) resource.TestCheckFunc { params := &ses.DescribeReceiptRuleInput{ RuleName: aws.String("basic"), - RuleSetName: aws.String("test-me"), + RuleSetName: aws.String(fmt.Sprintf("test-me-%d", srrsRandomInt)), } response, err := conn.DescribeReceiptRule(params) @@ -153,7 +154,7 @@ func testAccCheckAwsSESReceiptRuleOrder(n string) resource.TestCheckFunc { conn := testAccProvider.Meta().(*AWSClient).sesConn params := &ses.DescribeReceiptRuleSetInput{ - RuleSetName: aws.String("test-me"), + RuleSetName: aws.String(fmt.Sprintf("test-me-%d", srrsRandomInt)), } response, err := conn.DescribeReceiptRuleSet(params) @@ -185,8 +186,8 @@ func testAccCheckAwsSESReceiptRuleActions(n string) resource.TestCheckFunc { conn := testAccProvider.Meta().(*AWSClient).sesConn params := &ses.DescribeReceiptRuleInput{ - RuleName: aws.String("actions"), - RuleSetName: aws.String("test-me"), + RuleName: aws.String("actions4"), + RuleSetName: aws.String(fmt.Sprintf("test-me-%d", srrsRandomInt)), } response, err := conn.DescribeReceiptRule(params) @@ -227,9 +228,10 @@ func testAccCheckAwsSESReceiptRuleActions(n string) resource.TestCheckFunc { } } -const testAccAWSSESReceiptRuleBasicConfig = ` +var srrsRandomInt = acctest.RandInt() +var testAccAWSSESReceiptRuleBasicConfig = fmt.Sprintf(` resource "aws_ses_receipt_rule_set" "test" { - rule_set_name = "test-me" + rule_set_name = "test-me-%d" } resource "aws_ses_receipt_rule" "basic" { @@ -240,11 +242,11 @@ resource "aws_ses_receipt_rule" "basic" { scan_enabled = true tls_policy = "Require" } -` +`, srrsRandomInt) -const testAccAWSSESReceiptRuleOrderConfig = ` +var testAccAWSSESReceiptRuleOrderConfig = fmt.Sprintf(` resource "aws_ses_receipt_rule_set" "test" { - rule_set_name = "test-me" + rule_set_name = "test-me-%d" } resource "aws_ses_receipt_rule" "second" { @@ -257,36 +259,36 @@ resource "aws_ses_receipt_rule" "first" { name = "first" rule_set_name = "${aws_ses_receipt_rule_set.test.rule_set_name}" } -` +`, srrsRandomInt) -const testAccAWSSESReceiptRuleActionsConfig = ` +var testAccAWSSESReceiptRuleActionsConfig = fmt.Sprintf(` resource "aws_s3_bucket" "emails" { bucket = "ses-terraform-emails" } resource "aws_ses_receipt_rule_set" "test" { - rule_set_name = "test-me" + rule_set_name = "test-me-%d" } resource "aws_ses_receipt_rule" "actions" { - name = "actions" + name = "actions4" rule_set_name = "${aws_ses_receipt_rule_set.test.rule_set_name}" add_header_action { - header_name = "Added-By" - header_value = "Terraform" - position = 1 + header_name = "Added-By" + header_value = "Terraform" + position = 2 } add_header_action { - header_name = "Another-Header" - header_value = "First" - position = 0 + header_name = "Another-Header" + header_value = "First" + position = 1 } stop_action { - scope = "RuleSet" - position = 2 + scope = "RuleSet" + position = 3 } } -` +`, srrsRandomInt) diff --git a/builtin/providers/aws/resource_aws_sns_topic.go b/builtin/providers/aws/resource_aws_sns_topic.go index f3320866a..63d308518 100644 --- a/builtin/providers/aws/resource_aws_sns_topic.go +++ b/builtin/providers/aws/resource_aws_sns_topic.go @@ -55,9 +55,15 @@ func resourceAwsSnsTopic() *schema.Resource { }, }, "delivery_policy": &schema.Schema{ - Type: schema.TypeString, - Optional: true, - ForceNew: false, + Type: schema.TypeString, + Optional: true, + ForceNew: false, + ValidateFunc: validateJsonString, + DiffSuppressFunc: suppressEquivalentJsonDiffs, + StateFunc: func(v interface{}) string { + json, _ := normalizeJsonString(v) + return json + }, }, "arn": &schema.Schema{ Type: schema.TypeString, diff --git a/builtin/providers/aws/resource_aws_sns_topic_subscription_test.go b/builtin/providers/aws/resource_aws_sns_topic_subscription_test.go index 146d2fa92..3f730c9f7 100644 --- a/builtin/providers/aws/resource_aws_sns_topic_subscription_test.go +++ b/builtin/providers/aws/resource_aws_sns_topic_subscription_test.go @@ -31,6 +31,25 @@ func TestAccAWSSNSTopicSubscription_basic(t *testing.T) { }) } +func TestAccAWSSNSTopicSubscription_autoConfirmingEndpoint(t *testing.T) { + ri := acctest.RandInt() + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSSNSTopicSubscriptionDestroy, + Steps: []resource.TestStep{ + resource.TestStep{ + Config: testAccAWSSNSTopicSubscriptionConfig_autoConfirmingEndpoint(ri), + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSSNSTopicExists("aws_sns_topic.test_topic"), + testAccCheckAWSSNSTopicSubscriptionExists("aws_sns_topic_subscription.test_subscription"), + ), + }, + }, + }) +} + func testAccCheckAWSSNSTopicSubscriptionDestroy(s *terraform.State) error { conn := testAccProvider.Meta().(*AWSClient).snsconn @@ -103,3 +122,126 @@ resource "aws_sns_topic_subscription" "test_subscription" { } `, i) } + +func testAccAWSSNSTopicSubscriptionConfig_autoConfirmingEndpoint(i int) string { + return fmt.Sprintf(` +resource "aws_sns_topic" "test_topic" { + name = "tf-acc-test-sns-%d" +} + +resource "aws_api_gateway_rest_api" "test" { + name = "tf-acc-test-sns-%d" + description = "Terraform Acceptance test for SNS subscription" +} + +resource "aws_api_gateway_method" "test" { + rest_api_id = "${aws_api_gateway_rest_api.test.id}" + resource_id = "${aws_api_gateway_rest_api.test.root_resource_id}" + http_method = "POST" + authorization = "NONE" +} + +resource "aws_api_gateway_method_response" "test" { + rest_api_id = "${aws_api_gateway_rest_api.test.id}" + resource_id = "${aws_api_gateway_rest_api.test.root_resource_id}" + http_method = "${aws_api_gateway_method.test.http_method}" + status_code = "200" + + response_parameters { + "method.response.header.Access-Control-Allow-Origin" = true + } +} + +resource "aws_api_gateway_integration" "test" { + rest_api_id = "${aws_api_gateway_rest_api.test.id}" + resource_id = "${aws_api_gateway_rest_api.test.root_resource_id}" + http_method = "${aws_api_gateway_method.test.http_method}" + integration_http_method = "POST" + type = "AWS" + uri = "${aws_lambda_function.lambda.invoke_arn}" +} + +resource "aws_api_gateway_integration_response" "test" { + depends_on = ["aws_api_gateway_integration.test"] + rest_api_id = "${aws_api_gateway_rest_api.test.id}" + resource_id = "${aws_api_gateway_rest_api.test.root_resource_id}" + http_method = "${aws_api_gateway_method.test.http_method}" + status_code = "${aws_api_gateway_method_response.test.status_code}" + + response_parameters { + "method.response.header.Access-Control-Allow-Origin" = "'*'" + } +} + +resource "aws_iam_role" "iam_for_lambda" { + name = "tf-acc-test-sns-%d" + + assume_role_policy = < 0 { + return fmt.Errorf("Expected AWS SSM Maintenance Target to be gone, but was still found") + } + + return nil + } + + return nil +} + +func testAccAWSSSMMaintenanceWindowTargetBasicConfig(rName string) string { + return fmt.Sprintf(` +resource "aws_ssm_maintenance_window" "foo" { + name = "maintenance-window-%s" + schedule = "cron(0 16 ? * TUE *)" + duration = 3 + cutoff = 1 +} + +resource "aws_ssm_maintenance_window_target" "target" { + window_id = "${aws_ssm_maintenance_window.foo.id}" + resource_type = "INSTANCE" + targets { + key = "tag:Name" + values = ["acceptance_test"] + } +} +`, rName) +} diff --git a/builtin/providers/aws/resource_aws_ssm_maintenance_window_task.go b/builtin/providers/aws/resource_aws_ssm_maintenance_window_task.go new file mode 100644 index 000000000..1665bbfb1 --- /dev/null +++ b/builtin/providers/aws/resource_aws_ssm_maintenance_window_task.go @@ -0,0 +1,230 @@ +package aws + +import ( + "fmt" + "log" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/service/ssm" + "github.com/hashicorp/terraform/helper/schema" +) + +func resourceAwsSsmMaintenanceWindowTask() *schema.Resource { + return &schema.Resource{ + Create: resourceAwsSsmMaintenanceWindowTaskCreate, + Read: resourceAwsSsmMaintenanceWindowTaskRead, + Delete: resourceAwsSsmMaintenanceWindowTaskDelete, + + Schema: map[string]*schema.Schema{ + "window_id": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + + "max_concurrency": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + + "max_errors": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + + "task_type": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + + "task_arn": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + + "service_role_arn": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + + "targets": { + Type: schema.TypeList, + Required: true, + ForceNew: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "key": { + Type: schema.TypeString, + Required: true, + }, + "values": { + Type: schema.TypeList, + Required: true, + Elem: &schema.Schema{Type: schema.TypeString}, + }, + }, + }, + }, + + "priority": { + Type: schema.TypeInt, + Optional: true, + ForceNew: true, + }, + + "logging_info": { + Type: schema.TypeList, + MaxItems: 1, + Optional: true, + ForceNew: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "s3_bucket_name": { + Type: schema.TypeString, + Required: true, + }, + "s3_region": { + Type: schema.TypeString, + Required: true, + }, + "s3_bucket_prefix": { + Type: schema.TypeString, + Optional: true, + }, + }, + }, + }, + }, + } +} + +func expandAwsSsmMaintenanceWindowLoggingInfo(config []interface{}) *ssm.LoggingInfo { + + loggingConfig := config[0].(map[string]interface{}) + + loggingInfo := &ssm.LoggingInfo{ + S3BucketName: aws.String(loggingConfig["s3_bucket_name"].(string)), + S3Region: aws.String(loggingConfig["s3_region"].(string)), + } + + if s := loggingConfig["s3_bucket_prefix"].(string); s != "" { + loggingInfo.S3KeyPrefix = aws.String(s) + } + + return loggingInfo +} + +func flattenAwsSsmMaintenanceWindowLoggingInfo(loggingInfo *ssm.LoggingInfo) []interface{} { + + result := make(map[string]interface{}) + result["s3_bucket_name"] = *loggingInfo.S3BucketName + result["s3_region"] = *loggingInfo.S3Region + + if loggingInfo.S3KeyPrefix != nil { + result["s3_bucket_prefix"] = *loggingInfo.S3KeyPrefix + } + + return []interface{}{result} +} + +func resourceAwsSsmMaintenanceWindowTaskCreate(d *schema.ResourceData, meta interface{}) error { + ssmconn := meta.(*AWSClient).ssmconn + + log.Printf("[INFO] Registering SSM Maintenance Window Task") + + params := &ssm.RegisterTaskWithMaintenanceWindowInput{ + WindowId: aws.String(d.Get("window_id").(string)), + MaxConcurrency: aws.String(d.Get("max_concurrency").(string)), + MaxErrors: aws.String(d.Get("max_errors").(string)), + TaskType: aws.String(d.Get("task_type").(string)), + ServiceRoleArn: aws.String(d.Get("service_role_arn").(string)), + TaskArn: aws.String(d.Get("task_arn").(string)), + Targets: expandAwsSsmTargets(d), + } + + if v, ok := d.GetOk("priority"); ok { + params.Priority = aws.Int64(int64(v.(int))) + } + + if v, ok := d.GetOk("logging_info"); ok { + params.LoggingInfo = expandAwsSsmMaintenanceWindowLoggingInfo(v.([]interface{})) + } + + resp, err := ssmconn.RegisterTaskWithMaintenanceWindow(params) + if err != nil { + return err + } + + d.SetId(*resp.WindowTaskId) + + return resourceAwsSsmMaintenanceWindowTaskRead(d, meta) +} + +func resourceAwsSsmMaintenanceWindowTaskRead(d *schema.ResourceData, meta interface{}) error { + ssmconn := meta.(*AWSClient).ssmconn + + params := &ssm.DescribeMaintenanceWindowTasksInput{ + WindowId: aws.String(d.Get("window_id").(string)), + } + + resp, err := ssmconn.DescribeMaintenanceWindowTasks(params) + if err != nil { + return err + } + + found := false + for _, t := range resp.Tasks { + if *t.WindowTaskId == d.Id() { + found = true + + d.Set("window_id", t.WindowId) + d.Set("max_concurrency", t.MaxConcurrency) + d.Set("max_errors", t.MaxErrors) + d.Set("task_type", t.Type) + d.Set("service_role_arn", t.ServiceRoleArn) + d.Set("task_arn", t.TaskArn) + d.Set("priority", t.Priority) + + if t.LoggingInfo != nil { + if err := d.Set("logging_info", flattenAwsSsmMaintenanceWindowLoggingInfo(t.LoggingInfo)); err != nil { + return fmt.Errorf("[DEBUG] Error setting logging_info error: %#v", err) + } + } + + if err := d.Set("targets", flattenAwsSsmTargets(t.Targets)); err != nil { + return fmt.Errorf("[DEBUG] Error setting targets error: %#v", err) + } + } + } + + if !found { + log.Printf("[INFO] Maintenance Window Target not found. Removing from state") + d.SetId("") + return nil + } + + return nil +} + +func resourceAwsSsmMaintenanceWindowTaskDelete(d *schema.ResourceData, meta interface{}) error { + ssmconn := meta.(*AWSClient).ssmconn + + log.Printf("[INFO] Deregistering SSM Maintenance Window Task: %s", d.Id()) + + params := &ssm.DeregisterTaskFromMaintenanceWindowInput{ + WindowId: aws.String(d.Get("window_id").(string)), + WindowTaskId: aws.String(d.Id()), + } + + _, err := ssmconn.DeregisterTaskFromMaintenanceWindow(params) + if err != nil { + return err + } + + return nil +} diff --git a/builtin/providers/aws/resource_aws_ssm_maintenance_window_task_test.go b/builtin/providers/aws/resource_aws_ssm_maintenance_window_task_test.go new file mode 100644 index 000000000..797d75766 --- /dev/null +++ b/builtin/providers/aws/resource_aws_ssm_maintenance_window_task_test.go @@ -0,0 +1,158 @@ +package aws + +import ( + "fmt" + "testing" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/awserr" + "github.com/aws/aws-sdk-go/service/ssm" + "github.com/hashicorp/terraform/helper/acctest" + "github.com/hashicorp/terraform/helper/resource" + "github.com/hashicorp/terraform/terraform" +) + +func TestAccAWSSSMMaintenanceWindowTask_basic(t *testing.T) { + name := acctest.RandString(10) + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSSSMMaintenanceWindowTaskDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAWSSSMMaintenanceWindowTaskBasicConfig(name), + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSSSMMaintenanceWindowTaskExists("aws_ssm_maintenance_window_task.target"), + ), + }, + }, + }) +} + +func testAccCheckAWSSSMMaintenanceWindowTaskExists(n string) resource.TestCheckFunc { + return func(s *terraform.State) error { + rs, ok := s.RootModule().Resources[n] + if !ok { + return fmt.Errorf("Not found: %s", n) + } + + if rs.Primary.ID == "" { + return fmt.Errorf("No SSM Maintenance Window Task Window ID is set") + } + + conn := testAccProvider.Meta().(*AWSClient).ssmconn + + resp, err := conn.DescribeMaintenanceWindowTasks(&ssm.DescribeMaintenanceWindowTasksInput{ + WindowId: aws.String(rs.Primary.Attributes["window_id"]), + }) + if err != nil { + return err + } + + for _, i := range resp.Tasks { + if *i.WindowTaskId == rs.Primary.ID { + return nil + } + } + + return fmt.Errorf("No AWS SSM Maintenance window task found") + } +} + +func testAccCheckAWSSSMMaintenanceWindowTaskDestroy(s *terraform.State) error { + conn := testAccProvider.Meta().(*AWSClient).ssmconn + + for _, rs := range s.RootModule().Resources { + if rs.Type != "aws_ssm_maintenance_window_target" { + continue + } + + out, err := conn.DescribeMaintenanceWindowTasks(&ssm.DescribeMaintenanceWindowTasksInput{ + WindowId: aws.String(rs.Primary.Attributes["window_id"]), + }) + + if err != nil { + // Verify the error is what we want + if ae, ok := err.(awserr.Error); ok && ae.Code() == "DoesNotExistException" { + continue + } + return err + } + + if len(out.Tasks) > 0 { + return fmt.Errorf("Expected AWS SSM Maintenance Task to be gone, but was still found") + } + + return nil + } + + return nil +} + +func testAccAWSSSMMaintenanceWindowTaskBasicConfig(rName string) string { + return fmt.Sprintf(` +resource "aws_ssm_maintenance_window" "foo" { + name = "maintenance-window-%s" + schedule = "cron(0 16 ? * TUE *)" + duration = 3 + cutoff = 1 +} + +resource "aws_ssm_maintenance_window_task" "target" { + window_id = "${aws_ssm_maintenance_window.foo.id}" + task_type = "RUN_COMMAND" + task_arn = "AWS-RunShellScript" + priority = 1 + service_role_arn = "${aws_iam_role.ssm_role.arn}" + max_concurrency = "2" + max_errors = "1" + targets { + key = "InstanceIds" + values = ["${aws_instance.foo.id}"] + } +} + +resource "aws_instance" "foo" { + ami = "ami-4fccb37f" + + instance_type = "m1.small" +} + +resource "aws_iam_role" "ssm_role" { + name = "ssm-role-%s" + + assume_role_policy = < 0 { + return fmt.Errorf("Expected AWS SSM Maintenance Document to be gone, but was still found") + } + + return nil + } + + return nil +} + +func testAccAWSSSMMaintenanceWindowBasicConfig(rName string) string { + return fmt.Sprintf(` +resource "aws_ssm_maintenance_window" "foo" { + name = "maintenance-window-%s" + schedule = "cron(0 16 ? * TUE *)" + duration = 3 + cutoff = 1 +} + +`, rName) +} + +func testAccAWSSSMMaintenanceWindowBasicConfigUpdated(rName string) string { + return fmt.Sprintf(` +resource "aws_ssm_maintenance_window" "foo" { + name = "updated-maintenance-window-%s" + schedule = "cron(0 16 ? * WED *)" + duration = 10 + cutoff = 8 +} + +`, rName) +} diff --git a/builtin/providers/aws/resource_aws_subnet.go b/builtin/providers/aws/resource_aws_subnet.go index 68bf1e0f4..a466c2ae9 100644 --- a/builtin/providers/aws/resource_aws_subnet.go +++ b/builtin/providers/aws/resource_aws_subnet.go @@ -22,6 +22,9 @@ func resourceAwsSubnet() *schema.Resource { State: schema.ImportStatePassthrough, }, + SchemaVersion: 1, + MigrateState: resourceAwsSubnetMigrateState, + Schema: map[string]*schema.Schema{ "vpc_id": { Type: schema.TypeString, @@ -38,7 +41,7 @@ func resourceAwsSubnet() *schema.Resource { "ipv6_cidr_block": { Type: schema.TypeString, Optional: true, - ForceNew: true, + Computed: true, }, "availability_zone": { @@ -141,9 +144,15 @@ func resourceAwsSubnetRead(d *schema.ResourceData, meta interface{}) error { d.Set("cidr_block", subnet.CidrBlock) d.Set("map_public_ip_on_launch", subnet.MapPublicIpOnLaunch) d.Set("assign_ipv6_address_on_creation", subnet.AssignIpv6AddressOnCreation) - if subnet.Ipv6CidrBlockAssociationSet != nil { - d.Set("ipv6_cidr_block", subnet.Ipv6CidrBlockAssociationSet[0].Ipv6CidrBlock) - d.Set("ipv6_cidr_block_association_id", subnet.Ipv6CidrBlockAssociationSet[0].AssociationId) + for _, a := range subnet.Ipv6CidrBlockAssociationSet { + if *a.Ipv6CidrBlockState.State == "associated" { //we can only ever have 1 IPv6 block associated at once + d.Set("ipv6_cidr_block_association_id", a.AssociationId) + d.Set("ipv6_cidr_block", a.Ipv6CidrBlock) + break + } else { + d.Set("ipv6_cidr_block_association_id", "") // we blank these out to remove old entries + d.Set("ipv6_cidr_block", "") + } } d.Set("tags", tagsToMap(subnet.Tags)) @@ -199,6 +208,73 @@ func resourceAwsSubnetUpdate(d *schema.ResourceData, meta interface{}) error { } } + // We have to be careful here to not go through a change of association if this is a new resource + // A New resource here would denote that the Update func is called by the Create func + if d.HasChange("ipv6_cidr_block") && !d.IsNewResource() { + // We need to handle that we disassociate the IPv6 CIDR block before we try and associate the new one + // This could be an issue as, we could error out when we try and add the new one + // We may need to roll back the state and reattach the old one if this is the case + + _, new := d.GetChange("ipv6_cidr_block") + + //Firstly we have to disassociate the old IPv6 CIDR Block + disassociateOps := &ec2.DisassociateSubnetCidrBlockInput{ + AssociationId: aws.String(d.Get("ipv6_cidr_block_association_id").(string)), + } + + _, err := conn.DisassociateSubnetCidrBlock(disassociateOps) + if err != nil { + return err + } + + // Wait for the CIDR to become disassociated + log.Printf( + "[DEBUG] Waiting for IPv6 CIDR (%s) to become disassociated", + d.Id()) + stateConf := &resource.StateChangeConf{ + Pending: []string{"disassociating", "associated"}, + Target: []string{"disassociated"}, + Refresh: SubnetIpv6CidrStateRefreshFunc(conn, d.Id(), d.Get("ipv6_cidr_block_association_id").(string)), + Timeout: 3 * time.Minute, + } + if _, err := stateConf.WaitForState(); err != nil { + return fmt.Errorf( + "Error waiting for IPv6 CIDR (%s) to become disassociated: %s", + d.Id(), err) + } + + //Now we need to try and associate the new CIDR block + associatesOpts := &ec2.AssociateSubnetCidrBlockInput{ + SubnetId: aws.String(d.Id()), + Ipv6CidrBlock: aws.String(new.(string)), + } + + resp, err := conn.AssociateSubnetCidrBlock(associatesOpts) + if err != nil { + //The big question here is, do we want to try and reassociate the old one?? + //If we have a failure here, then we may be in a situation that we have nothing associated + return err + } + + // Wait for the CIDR to become associated + log.Printf( + "[DEBUG] Waiting for IPv6 CIDR (%s) to become associated", + d.Id()) + stateConf = &resource.StateChangeConf{ + Pending: []string{"associating", "disassociated"}, + Target: []string{"associated"}, + Refresh: SubnetIpv6CidrStateRefreshFunc(conn, d.Id(), *resp.Ipv6CidrBlockAssociation.AssociationId), + Timeout: 3 * time.Minute, + } + if _, err := stateConf.WaitForState(); err != nil { + return fmt.Errorf( + "Error waiting for IPv6 CIDR (%s) to become associated: %s", + d.Id(), err) + } + + d.SetPartial("ipv6_cidr_block") + } + d.Partial(false) return resourceAwsSubnetRead(d, meta) @@ -215,7 +291,7 @@ func resourceAwsSubnetDelete(d *schema.ResourceData, meta interface{}) error { wait := resource.StateChangeConf{ Pending: []string{"pending"}, Target: []string{"destroyed"}, - Timeout: 5 * time.Minute, + Timeout: 10 * time.Minute, MinTimeout: 1 * time.Second, Refresh: func() (interface{}, string, error) { _, err := conn.DeleteSubnet(req) @@ -271,3 +347,38 @@ func SubnetStateRefreshFunc(conn *ec2.EC2, id string) resource.StateRefreshFunc return subnet, *subnet.State, nil } } + +func SubnetIpv6CidrStateRefreshFunc(conn *ec2.EC2, id string, associationId string) resource.StateRefreshFunc { + return func() (interface{}, string, error) { + opts := &ec2.DescribeSubnetsInput{ + SubnetIds: []*string{aws.String(id)}, + } + resp, err := conn.DescribeSubnets(opts) + if err != nil { + if ec2err, ok := err.(awserr.Error); ok && ec2err.Code() == "InvalidSubnetID.NotFound" { + resp = nil + } else { + log.Printf("Error on SubnetIpv6CidrStateRefreshFunc: %s", err) + return nil, "", err + } + } + + if resp == nil { + // Sometimes AWS just has consistency issues and doesn't see + // our instance yet. Return an empty state. + return nil, "", nil + } + + if resp.Subnets[0].Ipv6CidrBlockAssociationSet == nil { + return nil, "", nil + } + + for _, association := range resp.Subnets[0].Ipv6CidrBlockAssociationSet { + if *association.AssociationId == associationId { + return association, *association.Ipv6CidrBlockState.State, nil + } + } + + return nil, "", nil + } +} diff --git a/builtin/providers/aws/resource_aws_subnet_migrate.go b/builtin/providers/aws/resource_aws_subnet_migrate.go new file mode 100644 index 000000000..0e0f19cf6 --- /dev/null +++ b/builtin/providers/aws/resource_aws_subnet_migrate.go @@ -0,0 +1,33 @@ +package aws + +import ( + "fmt" + "log" + + "github.com/hashicorp/terraform/terraform" +) + +func resourceAwsSubnetMigrateState( + v int, is *terraform.InstanceState, meta interface{}) (*terraform.InstanceState, error) { + switch v { + case 0: + log.Println("[INFO] Found AWS Subnet State v0; migrating to v1") + return migrateSubnetStateV0toV1(is) + default: + return is, fmt.Errorf("Unexpected schema version: %d", v) + } +} + +func migrateSubnetStateV0toV1(is *terraform.InstanceState) (*terraform.InstanceState, error) { + if is.Empty() || is.Attributes == nil { + log.Println("[DEBUG] Empty Subnet State; nothing to migrate.") + return is, nil + } + + log.Printf("[DEBUG] Attributes before migration: %#v", is.Attributes) + + is.Attributes["assign_ipv6_address_on_creation"] = "false" + + log.Printf("[DEBUG] Attributes after migration: %#v", is.Attributes) + return is, nil +} diff --git a/builtin/providers/aws/resource_aws_subnet_migrate_test.go b/builtin/providers/aws/resource_aws_subnet_migrate_test.go new file mode 100644 index 000000000..c3bdae859 --- /dev/null +++ b/builtin/providers/aws/resource_aws_subnet_migrate_test.go @@ -0,0 +1,41 @@ +package aws + +import ( + "testing" + + "github.com/hashicorp/terraform/terraform" +) + +func TestAWSSubnetMigrateState(t *testing.T) { + cases := map[string]struct { + StateVersion int + ID string + Attributes map[string]string + Expected string + Meta interface{} + }{ + "v0_1_without_value": { + StateVersion: 0, + ID: "some_id", + Attributes: map[string]string{}, + Expected: "false", + }, + } + + for tn, tc := range cases { + is := &terraform.InstanceState{ + ID: tc.ID, + Attributes: tc.Attributes, + } + is, err := resourceAwsSubnetMigrateState( + tc.StateVersion, is, tc.Meta) + + if err != nil { + t.Fatalf("bad: %s, err: %#v", tn, err) + } + + if is.Attributes["assign_ipv6_address_on_creation"] != tc.Expected { + t.Fatalf("bad Subnet Migrate: %s\n\n expected: %s", is.Attributes["assign_ipv6_address_on_creation"], tc.Expected) + } + } +} diff --git a/builtin/providers/aws/resource_aws_subnet_test.go b/builtin/providers/aws/resource_aws_subnet_test.go index b86284fdb..4a1c55739 100644 --- a/builtin/providers/aws/resource_aws_subnet_test.go +++ b/builtin/providers/aws/resource_aws_subnet_test.go @@ -45,27 +45,7 @@ func TestAccAWSSubnet_basic(t *testing.T) { } func TestAccAWSSubnet_ipv6(t *testing.T) { - var v ec2.Subnet - - testCheck := func(*terraform.State) error { - if v.Ipv6CidrBlockAssociationSet == nil { - return fmt.Errorf("Expected IPV6 CIDR Block Association") - } - - if *v.AssignIpv6AddressOnCreation != true { - return fmt.Errorf("bad AssignIpv6AddressOnCreation: %t", *v.AssignIpv6AddressOnCreation) - } - - return nil - } - - testCheckUpdated := func(*terraform.State) error { - if *v.AssignIpv6AddressOnCreation != false { - return fmt.Errorf("bad AssignIpv6AddressOnCreation: %t", *v.AssignIpv6AddressOnCreation) - } - - return nil - } + var before, after ec2.Subnet resource.Test(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, @@ -77,22 +57,65 @@ func TestAccAWSSubnet_ipv6(t *testing.T) { Config: testAccSubnetConfigIpv6, Check: resource.ComposeTestCheckFunc( testAccCheckSubnetExists( - "aws_subnet.foo", &v), - testCheck, + "aws_subnet.foo", &before), + testAccCheckAwsSubnetIpv6BeforeUpdate(t, &before), ), }, { - Config: testAccSubnetConfigIpv6Updated, + Config: testAccSubnetConfigIpv6UpdateAssignIpv6OnCreation, Check: resource.ComposeTestCheckFunc( testAccCheckSubnetExists( - "aws_subnet.foo", &v), - testCheckUpdated, + "aws_subnet.foo", &after), + testAccCheckAwsSubnetIpv6AfterUpdate(t, &after), + ), + }, + { + Config: testAccSubnetConfigIpv6UpdateIpv6Cidr, + Check: resource.ComposeTestCheckFunc( + testAccCheckSubnetExists( + "aws_subnet.foo", &after), + + testAccCheckAwsSubnetNotRecreated(t, &before, &after), ), }, }, }) } +func testAccCheckAwsSubnetIpv6BeforeUpdate(t *testing.T, subnet *ec2.Subnet) resource.TestCheckFunc { + return func(s *terraform.State) error { + if subnet.Ipv6CidrBlockAssociationSet == nil { + return fmt.Errorf("Expected IPV6 CIDR Block Association") + } + + if *subnet.AssignIpv6AddressOnCreation != true { + return fmt.Errorf("bad AssignIpv6AddressOnCreation: %t", *subnet.AssignIpv6AddressOnCreation) + } + + return nil + } +} + +func testAccCheckAwsSubnetIpv6AfterUpdate(t *testing.T, subnet *ec2.Subnet) resource.TestCheckFunc { + return func(s *terraform.State) error { + if *subnet.AssignIpv6AddressOnCreation != false { + return fmt.Errorf("bad AssignIpv6AddressOnCreation: %t", *subnet.AssignIpv6AddressOnCreation) + } + + return nil + } +} + +func testAccCheckAwsSubnetNotRecreated(t *testing.T, + before, after *ec2.Subnet) resource.TestCheckFunc { + return func(s *terraform.State) error { + if *before.SubnetId != *after.SubnetId { + t.Fatalf("Expected SubnetIDs not to change, but both got before: %s and after: %s", *before.SubnetId, *after.SubnetId) + } + return nil + } +} + func testAccCheckSubnetDestroy(s *terraform.State) error { conn := testAccProvider.Meta().(*AWSClient).ec2conn @@ -187,7 +210,25 @@ resource "aws_subnet" "foo" { } ` -const testAccSubnetConfigIpv6Updated = ` +const testAccSubnetConfigIpv6UpdateAssignIpv6OnCreation = ` +resource "aws_vpc" "foo" { + cidr_block = "10.10.0.0/16" + assign_generated_ipv6_cidr_block = true +} + +resource "aws_subnet" "foo" { + cidr_block = "10.10.1.0/24" + vpc_id = "${aws_vpc.foo.id}" + ipv6_cidr_block = "${cidrsubnet(aws_vpc.foo.ipv6_cidr_block, 8, 1)}" + map_public_ip_on_launch = true + assign_ipv6_address_on_creation = false + tags { + Name = "tf-subnet-acc-test" + } +} +` + +const testAccSubnetConfigIpv6UpdateIpv6Cidr = ` resource "aws_vpc" "foo" { cidr_block = "10.10.0.0/16" assign_generated_ipv6_cidr_block = true diff --git a/builtin/providers/aws/resource_aws_volume_attachment.go b/builtin/providers/aws/resource_aws_volume_attachment.go index 9aed74a42..2afcd6c67 100644 --- a/builtin/providers/aws/resource_aws_volume_attachment.go +++ b/builtin/providers/aws/resource_aws_volume_attachment.go @@ -83,7 +83,7 @@ func resourceAwsVolumeAttachmentCreate(d *schema.ResourceData, meta interface{}) stateConf := &resource.StateChangeConf{ Pending: []string{"pending"}, Target: []string{"running"}, - Refresh: InstanceStateRefreshFunc(conn, iID), + Refresh: InstanceStateRefreshFunc(conn, iID, "terminated"), Timeout: 10 * time.Minute, Delay: 10 * time.Second, MinTimeout: 3 * time.Second, diff --git a/builtin/providers/aws/resource_aws_vpc.go b/builtin/providers/aws/resource_aws_vpc.go index 6807706b6..6a8edca4b 100644 --- a/builtin/providers/aws/resource_aws_vpc.go +++ b/builtin/providers/aws/resource_aws_vpc.go @@ -60,7 +60,6 @@ func resourceAwsVpc() *schema.Resource { "assign_generated_ipv6_cidr_block": { Type: schema.TypeBool, - ForceNew: true, Optional: true, Default: false, }, @@ -178,7 +177,7 @@ func resourceAwsVpcRead(d *schema.ResourceData, meta interface{}) error { d.Set("tags", tagsToMap(vpc.Tags)) for _, a := range vpc.Ipv6CidrBlockAssociationSet { - if *a.Ipv6CidrBlockState.State == "associated" { + if *a.Ipv6CidrBlockState.State == "associated" { //we can only ever have 1 IPv6 block associated at once d.Set("assign_generated_ipv6_cidr_block", true) d.Set("ipv6_association_id", a.AssociationId) d.Set("ipv6_cidr_block", a.Ipv6CidrBlock) @@ -344,6 +343,68 @@ func resourceAwsVpcUpdate(d *schema.ResourceData, meta interface{}) error { d.SetPartial("enable_classiclink") } + if d.HasChange("assign_generated_ipv6_cidr_block") && !d.IsNewResource() { + toAssign := d.Get("assign_generated_ipv6_cidr_block").(bool) + + log.Printf("[INFO] Modifying assign_generated_ipv6_cidr_block to %#v", toAssign) + + if toAssign { + modifyOpts := &ec2.AssociateVpcCidrBlockInput{ + VpcId: &vpcid, + AmazonProvidedIpv6CidrBlock: aws.Bool(toAssign), + } + log.Printf("[INFO] Enabling assign_generated_ipv6_cidr_block vpc attribute for %s: %#v", + d.Id(), modifyOpts) + resp, err := conn.AssociateVpcCidrBlock(modifyOpts) + if err != nil { + return err + } + + // Wait for the CIDR to become available + log.Printf( + "[DEBUG] Waiting for IPv6 CIDR (%s) to become associated", + d.Id()) + stateConf := &resource.StateChangeConf{ + Pending: []string{"associating", "disassociated"}, + Target: []string{"associated"}, + Refresh: Ipv6CidrStateRefreshFunc(conn, d.Id(), *resp.Ipv6CidrBlockAssociation.AssociationId), + Timeout: 1 * time.Minute, + } + if _, err := stateConf.WaitForState(); err != nil { + return fmt.Errorf( + "Error waiting for IPv6 CIDR (%s) to become associated: %s", + d.Id(), err) + } + } else { + modifyOpts := &ec2.DisassociateVpcCidrBlockInput{ + AssociationId: aws.String(d.Get("ipv6_association_id").(string)), + } + log.Printf("[INFO] Disabling assign_generated_ipv6_cidr_block vpc attribute for %s: %#v", + d.Id(), modifyOpts) + if _, err := conn.DisassociateVpcCidrBlock(modifyOpts); err != nil { + return err + } + + // Wait for the CIDR to become available + log.Printf( + "[DEBUG] Waiting for IPv6 CIDR (%s) to become disassociated", + d.Id()) + stateConf := &resource.StateChangeConf{ + Pending: []string{"disassociating", "associated"}, + Target: []string{"disassociated"}, + Refresh: Ipv6CidrStateRefreshFunc(conn, d.Id(), d.Get("ipv6_association_id").(string)), + Timeout: 1 * time.Minute, + } + if _, err := stateConf.WaitForState(); err != nil { + return fmt.Errorf( + "Error waiting for IPv6 CIDR (%s) to become disassociated: %s", + d.Id(), err) + } + } + + d.SetPartial("assign_generated_ipv6_cidr_block") + } + if err := setTags(conn, d); err != nil { return err } else { @@ -412,6 +473,41 @@ func VPCStateRefreshFunc(conn *ec2.EC2, id string) resource.StateRefreshFunc { } } +func Ipv6CidrStateRefreshFunc(conn *ec2.EC2, id string, associationId string) resource.StateRefreshFunc { + return func() (interface{}, string, error) { + describeVpcOpts := &ec2.DescribeVpcsInput{ + VpcIds: []*string{aws.String(id)}, + } + resp, err := conn.DescribeVpcs(describeVpcOpts) + if err != nil { + if ec2err, ok := err.(awserr.Error); ok && ec2err.Code() == "InvalidVpcID.NotFound" { + resp = nil + } else { + log.Printf("Error on VPCStateRefresh: %s", err) + return nil, "", err + } + } + + if resp == nil { + // Sometimes AWS just has consistency issues and doesn't see + // our instance yet. Return an empty state. + return nil, "", nil + } + + if resp.Vpcs[0].Ipv6CidrBlockAssociationSet == nil { + return nil, "", nil + } + + for _, association := range resp.Vpcs[0].Ipv6CidrBlockAssociationSet { + if *association.AssociationId == associationId { + return association, *association.Ipv6CidrBlockState.State, nil + } + } + + return nil, "", nil + } +} + func resourceAwsVpcSetDefaultNetworkAcl(conn *ec2.EC2, d *schema.ResourceData) error { filter1 := &ec2.Filter{ Name: aws.String("default"), diff --git a/builtin/providers/aws/resource_aws_vpc_dhcp_options.go b/builtin/providers/aws/resource_aws_vpc_dhcp_options.go index 16c33fd4d..66de6dbeb 100644 --- a/builtin/providers/aws/resource_aws_vpc_dhcp_options.go +++ b/builtin/providers/aws/resource_aws_vpc_dhcp_options.go @@ -147,7 +147,18 @@ func resourceAwsVpcDhcpOptionsRead(d *schema.ResourceData, meta interface{}) err resp, err := conn.DescribeDhcpOptions(req) if err != nil { - return fmt.Errorf("Error retrieving DHCP Options: %s", err) + ec2err, ok := err.(awserr.Error) + if !ok { + return fmt.Errorf("Error retrieving DHCP Options: %s", err.Error()) + } + + if ec2err.Code() == "InvalidDhcpOptionID.NotFound" { + log.Printf("[WARN] DHCP Options (%s) not found, removing from state", d.Id()) + d.SetId("") + return nil + } + + return fmt.Errorf("Error retrieving DHCP Options: %s", err.Error()) } if len(resp.DhcpOptions) == 0 { diff --git a/builtin/providers/aws/resource_aws_vpc_dhcp_options_test.go b/builtin/providers/aws/resource_aws_vpc_dhcp_options_test.go index baa86f7d7..f101f95f3 100644 --- a/builtin/providers/aws/resource_aws_vpc_dhcp_options_test.go +++ b/builtin/providers/aws/resource_aws_vpc_dhcp_options_test.go @@ -36,6 +36,26 @@ func TestAccAWSDHCPOptions_basic(t *testing.T) { }) } +func TestAccAWSDHCPOptions_deleteOptions(t *testing.T) { + var d ec2.DhcpOptions + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckDHCPOptionsDestroy, + Steps: []resource.TestStep{ + resource.TestStep{ + Config: testAccDHCPOptionsConfig, + Check: resource.ComposeTestCheckFunc( + testAccCheckDHCPOptionsExists("aws_vpc_dhcp_options.foo", &d), + testAccCheckDHCPOptionsDelete("aws_vpc_dhcp_options.foo"), + ), + ExpectNonEmptyPlan: true, + }, + }, + }) +} + func testAccCheckDHCPOptionsDestroy(s *terraform.State) error { conn := testAccProvider.Meta().(*AWSClient).ec2conn @@ -104,6 +124,26 @@ func testAccCheckDHCPOptionsExists(n string, d *ec2.DhcpOptions) resource.TestCh } } +func testAccCheckDHCPOptionsDelete(n string) resource.TestCheckFunc { + return func(s *terraform.State) error { + rs, ok := s.RootModule().Resources[n] + if !ok { + return fmt.Errorf("Not found: %s", n) + } + + if rs.Primary.ID == "" { + return fmt.Errorf("No ID is set") + } + + conn := testAccProvider.Meta().(*AWSClient).ec2conn + _, err := conn.DeleteDhcpOptions(&ec2.DeleteDhcpOptionsInput{ + DhcpOptionsId: aws.String(rs.Primary.ID), + }) + + return err + } +} + const testAccDHCPOptionsConfig = ` resource "aws_vpc_dhcp_options" "foo" { domain_name = "service.consul" diff --git a/builtin/providers/aws/resource_aws_vpc_test.go b/builtin/providers/aws/resource_aws_vpc_test.go index 44f672268..ca68bdfe8 100644 --- a/builtin/providers/aws/resource_aws_vpc_test.go +++ b/builtin/providers/aws/resource_aws_vpc_test.go @@ -46,7 +46,7 @@ func TestAccAWSVpc_enableIpv6(t *testing.T) { Steps: []resource.TestStep{ { Config: testAccVpcConfigIpv6Enabled, - Check: resource.ComposeTestCheckFunc( + Check: resource.ComposeAggregateTestCheckFunc( testAccCheckVpcExists("aws_vpc.foo", &vpc), testAccCheckVpcCidr(&vpc, "10.1.0.0/16"), resource.TestCheckResourceAttr( @@ -55,6 +55,34 @@ func TestAccAWSVpc_enableIpv6(t *testing.T) { "aws_vpc.foo", "ipv6_association_id"), resource.TestCheckResourceAttrSet( "aws_vpc.foo", "ipv6_cidr_block"), + resource.TestCheckResourceAttr( + "aws_vpc.foo", "assign_generated_ipv6_cidr_block", "true"), + ), + }, + { + Config: testAccVpcConfigIpv6Disabled, + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckVpcExists("aws_vpc.foo", &vpc), + testAccCheckVpcCidr(&vpc, "10.1.0.0/16"), + resource.TestCheckResourceAttr( + "aws_vpc.foo", "cidr_block", "10.1.0.0/16"), + resource.TestCheckResourceAttr( + "aws_vpc.foo", "assign_generated_ipv6_cidr_block", "false"), + ), + }, + { + Config: testAccVpcConfigIpv6Enabled, + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckVpcExists("aws_vpc.foo", &vpc), + testAccCheckVpcCidr(&vpc, "10.1.0.0/16"), + resource.TestCheckResourceAttr( + "aws_vpc.foo", "cidr_block", "10.1.0.0/16"), + resource.TestCheckResourceAttrSet( + "aws_vpc.foo", "ipv6_association_id"), + resource.TestCheckResourceAttrSet( + "aws_vpc.foo", "ipv6_cidr_block"), + resource.TestCheckResourceAttr( + "aws_vpc.foo", "assign_generated_ipv6_cidr_block", "true"), ), }, }, @@ -283,6 +311,12 @@ resource "aws_vpc" "foo" { } ` +const testAccVpcConfigIpv6Disabled = ` +resource "aws_vpc" "foo" { + cidr_block = "10.1.0.0/16" +} +` + const testAccVpcConfigUpdate = ` resource "aws_vpc" "foo" { cidr_block = "10.1.0.0/16" diff --git a/builtin/providers/aws/resource_aws_vpn_connection.go b/builtin/providers/aws/resource_aws_vpn_connection.go index b38d903cf..1cdd83efd 100644 --- a/builtin/providers/aws/resource_aws_vpn_connection.go +++ b/builtin/providers/aws/resource_aws_vpn_connection.go @@ -294,6 +294,11 @@ func resourceAwsVpnConnectionRead(d *schema.ResourceData, meta interface{}) erro } vpnConnection := resp.VpnConnections[0] + if vpnConnection == nil || *vpnConnection.State == "deleted" { + // Seems we have lost our VPN Connection + d.SetId("") + return nil + } // Set attributes under the user's control. d.Set("vpn_gateway_id", vpnConnection.VpnGatewayId) diff --git a/builtin/providers/aws/resource_aws_vpn_connection_test.go b/builtin/providers/aws/resource_aws_vpn_connection_test.go index a07bdd10b..c5b9c4581 100644 --- a/builtin/providers/aws/resource_aws_vpn_connection_test.go +++ b/builtin/providers/aws/resource_aws_vpn_connection_test.go @@ -3,16 +3,22 @@ package aws import ( "fmt" "testing" + "time" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/service/ec2" + "github.com/hashicorp/terraform/helper/acctest" "github.com/hashicorp/terraform/helper/resource" "github.com/hashicorp/terraform/terraform" ) func TestAccAWSVpnConnection_basic(t *testing.T) { + rInt := acctest.RandInt() + rBgpAsn := acctest.RandIntRange(64512, 65534) + var vpn ec2.VpnConnection + resource.Test(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, IDRefreshName: "aws_vpn_connection.foo", @@ -20,24 +26,26 @@ func TestAccAWSVpnConnection_basic(t *testing.T) { CheckDestroy: testAccAwsVpnConnectionDestroy, Steps: []resource.TestStep{ { - Config: testAccAwsVpnConnectionConfig, + Config: testAccAwsVpnConnectionConfig(rBgpAsn), Check: resource.ComposeTestCheckFunc( testAccAwsVpnConnection( "aws_vpc.vpc", "aws_vpn_gateway.vpn_gateway", "aws_customer_gateway.customer_gateway", "aws_vpn_connection.foo", + &vpn, ), ), }, { - Config: testAccAwsVpnConnectionConfigUpdate, + Config: testAccAwsVpnConnectionConfigUpdate(rInt, rBgpAsn), Check: resource.ComposeTestCheckFunc( testAccAwsVpnConnection( "aws_vpc.vpc", "aws_vpn_gateway.vpn_gateway", "aws_customer_gateway.customer_gateway", "aws_vpn_connection.foo", + &vpn, ), ), }, @@ -46,6 +54,9 @@ func TestAccAWSVpnConnection_basic(t *testing.T) { } func TestAccAWSVpnConnection_withoutStaticRoutes(t *testing.T) { + rInt := acctest.RandInt() + rBgpAsn := acctest.RandIntRange(64512, 65534) + var vpn ec2.VpnConnection resource.Test(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, IDRefreshName: "aws_vpn_connection.foo", @@ -53,13 +64,14 @@ func TestAccAWSVpnConnection_withoutStaticRoutes(t *testing.T) { CheckDestroy: testAccAwsVpnConnectionDestroy, Steps: []resource.TestStep{ { - Config: testAccAwsVpnConnectionConfigUpdate, + Config: testAccAwsVpnConnectionConfigUpdate(rInt, rBgpAsn), Check: resource.ComposeTestCheckFunc( testAccAwsVpnConnection( "aws_vpc.vpc", "aws_vpn_gateway.vpn_gateway", "aws_customer_gateway.customer_gateway", "aws_vpn_connection.foo", + &vpn, ), resource.TestCheckResourceAttr("aws_vpn_connection.foo", "static_routes_only", "false"), ), @@ -68,6 +80,75 @@ func TestAccAWSVpnConnection_withoutStaticRoutes(t *testing.T) { }) } +func TestAccAWSVpnConnection_disappears(t *testing.T) { + rBgpAsn := acctest.RandIntRange(64512, 65534) + var vpn ec2.VpnConnection + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccAwsVpnConnectionDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAwsVpnConnectionConfig(rBgpAsn), + Check: resource.ComposeTestCheckFunc( + testAccAwsVpnConnection( + "aws_vpc.vpc", + "aws_vpn_gateway.vpn_gateway", + "aws_customer_gateway.customer_gateway", + "aws_vpn_connection.foo", + &vpn, + ), + testAccAWSVpnConnectionDisappears(&vpn), + ), + ExpectNonEmptyPlan: true, + }, + }, + }) +} + +func testAccAWSVpnConnectionDisappears(connection *ec2.VpnConnection) resource.TestCheckFunc { + return func(s *terraform.State) error { + conn := testAccProvider.Meta().(*AWSClient).ec2conn + + _, err := conn.DeleteVpnConnection(&ec2.DeleteVpnConnectionInput{ + VpnConnectionId: connection.VpnConnectionId, + }) + if err != nil { + if ec2err, ok := err.(awserr.Error); ok && ec2err.Code() == "InvalidVpnConnectionID.NotFound" { + return nil + } + if err != nil { + return err + } + } + + return resource.Retry(40*time.Minute, func() *resource.RetryError { + opts := &ec2.DescribeVpnConnectionsInput{ + VpnConnectionIds: []*string{connection.VpnConnectionId}, + } + resp, err := conn.DescribeVpnConnections(opts) + if err != nil { + cgw, ok := err.(awserr.Error) + if ok && cgw.Code() == "InvalidVpnConnectionID.NotFound" { + return nil + } + if ok && cgw.Code() == "IncorrectState" { + return resource.RetryableError(fmt.Errorf( + "Waiting for VPN Connection to be in the correct state: %v", connection.VpnConnectionId)) + } + return resource.NonRetryableError( + fmt.Errorf("Error retrieving VPN Connection: %s", err)) + } + if *resp.VpnConnections[0].State == "deleted" { + return nil + } + return resource.RetryableError(fmt.Errorf( + "Waiting for VPN Connection: %v", connection.VpnConnectionId)) + }) + } +} + func testAccAwsVpnConnectionDestroy(s *terraform.State) error { conn := testAccProvider.Meta().(*AWSClient).ec2conn for _, rs := range s.RootModule().Resources { @@ -112,7 +193,8 @@ func testAccAwsVpnConnection( vpcResource string, vpnGatewayResource string, customerGatewayResource string, - vpnConnectionResource string) resource.TestCheckFunc { + vpnConnectionResource string, + vpnConnection *ec2.VpnConnection) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[vpnConnectionResource] if !ok { @@ -129,7 +211,7 @@ func testAccAwsVpnConnection( ec2conn := testAccProvider.Meta().(*AWSClient).ec2conn - _, err := ec2conn.DescribeVpnConnections(&ec2.DescribeVpnConnectionsInput{ + resp, err := ec2conn.DescribeVpnConnections(&ec2.DescribeVpnConnectionsInput{ VpnConnectionIds: []*string{aws.String(connection.Primary.ID)}, }) @@ -137,6 +219,8 @@ func testAccAwsVpnConnection( return err } + *vpnConnection = *resp.VpnConnections[0] + return nil } } @@ -160,48 +244,58 @@ func TestAWSVpnConnection_xmlconfig(t *testing.T) { } } -const testAccAwsVpnConnectionConfig = ` -resource "aws_vpn_gateway" "vpn_gateway" { - tags { - Name = "vpn_gateway" - } -} +func testAccAwsVpnConnectionConfig(rBgpAsn int) string { + return fmt.Sprintf(` + resource "aws_vpn_gateway" "vpn_gateway" { + tags { + Name = "vpn_gateway" + } + } -resource "aws_customer_gateway" "customer_gateway" { - bgp_asn = 65000 - ip_address = "178.0.0.1" - type = "ipsec.1" -} + resource "aws_customer_gateway" "customer_gateway" { + bgp_asn = %d + ip_address = "178.0.0.1" + type = "ipsec.1" + tags { + Name = "main-customer-gateway" + } + } -resource "aws_vpn_connection" "foo" { - vpn_gateway_id = "${aws_vpn_gateway.vpn_gateway.id}" - customer_gateway_id = "${aws_customer_gateway.customer_gateway.id}" - type = "ipsec.1" - static_routes_only = true + resource "aws_vpn_connection" "foo" { + vpn_gateway_id = "${aws_vpn_gateway.vpn_gateway.id}" + customer_gateway_id = "${aws_customer_gateway.customer_gateway.id}" + type = "ipsec.1" + static_routes_only = true + } + `, rBgpAsn) } -` // Change static_routes_only to be false, forcing a refresh. -const testAccAwsVpnConnectionConfigUpdate = ` -resource "aws_vpn_gateway" "vpn_gateway" { - tags { - Name = "vpn_gateway" - } -} +func testAccAwsVpnConnectionConfigUpdate(rInt, rBgpAsn int) string { + return fmt.Sprintf(` + resource "aws_vpn_gateway" "vpn_gateway" { + tags { + Name = "vpn_gateway" + } + } -resource "aws_customer_gateway" "customer_gateway" { - bgp_asn = 65000 - ip_address = "178.0.0.1" - type = "ipsec.1" -} + resource "aws_customer_gateway" "customer_gateway" { + bgp_asn = %d + ip_address = "178.0.0.1" + type = "ipsec.1" + tags { + Name = "main-customer-gateway-%d" + } + } -resource "aws_vpn_connection" "foo" { - vpn_gateway_id = "${aws_vpn_gateway.vpn_gateway.id}" - customer_gateway_id = "${aws_customer_gateway.customer_gateway.id}" - type = "ipsec.1" - static_routes_only = false + resource "aws_vpn_connection" "foo" { + vpn_gateway_id = "${aws_vpn_gateway.vpn_gateway.id}" + customer_gateway_id = "${aws_customer_gateway.customer_gateway.id}" + type = "ipsec.1" + static_routes_only = false + } + `, rBgpAsn, rInt) } -` // Test our VPN tunnel config XML parsing const testAccAwsVpnTunnelInfoXML = ` diff --git a/builtin/providers/aws/resource_aws_vpn_gateway.go b/builtin/providers/aws/resource_aws_vpn_gateway.go index 89c7bea88..19be0e324 100644 --- a/builtin/providers/aws/resource_aws_vpn_gateway.go +++ b/builtin/providers/aws/resource_aws_vpn_gateway.go @@ -205,7 +205,7 @@ func resourceAwsVpnGatewayAttach(d *schema.ResourceData, meta interface{}) error Pending: []string{"detached", "attaching"}, Target: []string{"attached"}, Refresh: vpnGatewayAttachStateRefreshFunc(conn, d.Id(), "available"), - Timeout: 1 * time.Minute, + Timeout: 5 * time.Minute, } if _, err := stateConf.WaitForState(); err != nil { return fmt.Errorf( @@ -266,7 +266,7 @@ func resourceAwsVpnGatewayDetach(d *schema.ResourceData, meta interface{}) error Pending: []string{"attached", "detaching", "available"}, Target: []string{"detached"}, Refresh: vpnGatewayAttachStateRefreshFunc(conn, d.Id(), "detached"), - Timeout: 1 * time.Minute, + Timeout: 5 * time.Minute, } if _, err := stateConf.WaitForState(); err != nil { return fmt.Errorf( diff --git a/builtin/providers/aws/resource_aws_waf_byte_match_set.go b/builtin/providers/aws/resource_aws_waf_byte_match_set.go index b3a02b7d0..c28359351 100644 --- a/builtin/providers/aws/resource_aws_waf_byte_match_set.go +++ b/builtin/providers/aws/resource_aws_waf_byte_match_set.go @@ -69,24 +69,18 @@ func resourceAwsWafByteMatchSetCreate(d *schema.ResourceData, meta interface{}) log.Printf("[INFO] Creating ByteMatchSet: %s", d.Get("name").(string)) - // ChangeToken - var ct *waf.GetChangeTokenInput - - res, err := conn.GetChangeToken(ct) - if err != nil { - return errwrap.Wrapf("[ERROR] Error getting change token: {{err}}", err) - } - - params := &waf.CreateByteMatchSetInput{ - ChangeToken: res.ChangeToken, - Name: aws.String(d.Get("name").(string)), - } - - resp, err := conn.CreateByteMatchSet(params) - + wr := newWafRetryer(conn, "global") + out, err := wr.RetryWithToken(func(token *string) (interface{}, error) { + params := &waf.CreateByteMatchSetInput{ + ChangeToken: token, + Name: aws.String(d.Get("name").(string)), + } + return conn.CreateByteMatchSet(params) + }) if err != nil { return errwrap.Wrapf("[ERROR] Error creating ByteMatchSet: {{err}}", err) } + resp := out.(*waf.CreateByteMatchSetOutput) d.SetId(*resp.ByteMatchSet.ByteMatchSetId) @@ -134,17 +128,14 @@ func resourceAwsWafByteMatchSetDelete(d *schema.ResourceData, meta interface{}) return errwrap.Wrapf("[ERROR] Error deleting ByteMatchSet: {{err}}", err) } - var ct *waf.GetChangeTokenInput - - resp, err := conn.GetChangeToken(ct) - - req := &waf.DeleteByteMatchSetInput{ - ChangeToken: resp.ChangeToken, - ByteMatchSetId: aws.String(d.Id()), - } - - _, err = conn.DeleteByteMatchSet(req) - + wr := newWafRetryer(conn, "global") + _, err = wr.RetryWithToken(func(token *string) (interface{}, error) { + req := &waf.DeleteByteMatchSetInput{ + ChangeToken: token, + ByteMatchSetId: aws.String(d.Id()), + } + return conn.DeleteByteMatchSet(req) + }) if err != nil { return errwrap.Wrapf("[ERROR] Error deleting ByteMatchSet: {{err}}", err) } @@ -155,34 +146,30 @@ func resourceAwsWafByteMatchSetDelete(d *schema.ResourceData, meta interface{}) func updateByteMatchSetResource(d *schema.ResourceData, meta interface{}, ChangeAction string) error { conn := meta.(*AWSClient).wafconn - var ct *waf.GetChangeTokenInput - - resp, err := conn.GetChangeToken(ct) - if err != nil { - return errwrap.Wrapf("[ERROR] Error getting change token: {{err}}", err) - } - - req := &waf.UpdateByteMatchSetInput{ - ChangeToken: resp.ChangeToken, - ByteMatchSetId: aws.String(d.Id()), - } - - ByteMatchTuples := d.Get("byte_match_tuples").(*schema.Set) - for _, ByteMatchTuple := range ByteMatchTuples.List() { - ByteMatch := ByteMatchTuple.(map[string]interface{}) - ByteMatchUpdate := &waf.ByteMatchSetUpdate{ - Action: aws.String(ChangeAction), - ByteMatchTuple: &waf.ByteMatchTuple{ - FieldToMatch: expandFieldToMatch(ByteMatch["field_to_match"].(*schema.Set).List()[0].(map[string]interface{})), - PositionalConstraint: aws.String(ByteMatch["positional_constraint"].(string)), - TargetString: []byte(ByteMatch["target_string"].(string)), - TextTransformation: aws.String(ByteMatch["text_transformation"].(string)), - }, + wr := newWafRetryer(conn, "global") + _, err := wr.RetryWithToken(func(token *string) (interface{}, error) { + req := &waf.UpdateByteMatchSetInput{ + ChangeToken: token, + ByteMatchSetId: aws.String(d.Id()), } - req.Updates = append(req.Updates, ByteMatchUpdate) - } - _, err = conn.UpdateByteMatchSet(req) + ByteMatchTuples := d.Get("byte_match_tuples").(*schema.Set) + for _, ByteMatchTuple := range ByteMatchTuples.List() { + ByteMatch := ByteMatchTuple.(map[string]interface{}) + ByteMatchUpdate := &waf.ByteMatchSetUpdate{ + Action: aws.String(ChangeAction), + ByteMatchTuple: &waf.ByteMatchTuple{ + FieldToMatch: expandFieldToMatch(ByteMatch["field_to_match"].(*schema.Set).List()[0].(map[string]interface{})), + PositionalConstraint: aws.String(ByteMatch["positional_constraint"].(string)), + TargetString: []byte(ByteMatch["target_string"].(string)), + TextTransformation: aws.String(ByteMatch["text_transformation"].(string)), + }, + } + req.Updates = append(req.Updates, ByteMatchUpdate) + } + + return conn.UpdateByteMatchSet(req) + }) if err != nil { return errwrap.Wrapf("[ERROR] Error updating ByteMatchSet: {{err}}", err) } diff --git a/builtin/providers/aws/resource_aws_waf_byte_match_set_test.go b/builtin/providers/aws/resource_aws_waf_byte_match_set_test.go index ae9dae099..c5e0ce213 100644 --- a/builtin/providers/aws/resource_aws_waf_byte_match_set_test.go +++ b/builtin/providers/aws/resource_aws_waf_byte_match_set_test.go @@ -96,49 +96,43 @@ func testAccCheckAWSWafByteMatchSetDisappears(v *waf.ByteMatchSet) resource.Test return func(s *terraform.State) error { conn := testAccProvider.Meta().(*AWSClient).wafconn - // ChangeToken - var ct *waf.GetChangeTokenInput - - resp, err := conn.GetChangeToken(ct) - if err != nil { - return fmt.Errorf("Error getting change token: %s", err) - } - - req := &waf.UpdateByteMatchSetInput{ - ChangeToken: resp.ChangeToken, - ByteMatchSetId: v.ByteMatchSetId, - } - - for _, ByteMatchTuple := range v.ByteMatchTuples { - ByteMatchUpdate := &waf.ByteMatchSetUpdate{ - Action: aws.String("DELETE"), - ByteMatchTuple: &waf.ByteMatchTuple{ - FieldToMatch: ByteMatchTuple.FieldToMatch, - PositionalConstraint: ByteMatchTuple.PositionalConstraint, - TargetString: ByteMatchTuple.TargetString, - TextTransformation: ByteMatchTuple.TextTransformation, - }, + wr := newWafRetryer(conn, "global") + _, err := wr.RetryWithToken(func(token *string) (interface{}, error) { + req := &waf.UpdateByteMatchSetInput{ + ChangeToken: token, + ByteMatchSetId: v.ByteMatchSetId, } - req.Updates = append(req.Updates, ByteMatchUpdate) - } - _, err = conn.UpdateByteMatchSet(req) + for _, ByteMatchTuple := range v.ByteMatchTuples { + ByteMatchUpdate := &waf.ByteMatchSetUpdate{ + Action: aws.String("DELETE"), + ByteMatchTuple: &waf.ByteMatchTuple{ + FieldToMatch: ByteMatchTuple.FieldToMatch, + PositionalConstraint: ByteMatchTuple.PositionalConstraint, + TargetString: ByteMatchTuple.TargetString, + TextTransformation: ByteMatchTuple.TextTransformation, + }, + } + req.Updates = append(req.Updates, ByteMatchUpdate) + } + + return conn.UpdateByteMatchSet(req) + }) if err != nil { return errwrap.Wrapf("[ERROR] Error updating ByteMatchSet: {{err}}", err) } - resp, err = conn.GetChangeToken(ct) + _, err = wr.RetryWithToken(func(token *string) (interface{}, error) { + opts := &waf.DeleteByteMatchSetInput{ + ChangeToken: token, + ByteMatchSetId: v.ByteMatchSetId, + } + return conn.DeleteByteMatchSet(opts) + }) if err != nil { - return errwrap.Wrapf("[ERROR] Error getting change token: {{err}}", err) + return errwrap.Wrapf("[ERROR] Error deleting ByteMatchSet: {{err}}", err) } - opts := &waf.DeleteByteMatchSetInput{ - ChangeToken: resp.ChangeToken, - ByteMatchSetId: v.ByteMatchSetId, - } - if _, err := conn.DeleteByteMatchSet(opts); err != nil { - return err - } return nil } } diff --git a/builtin/providers/aws/resource_aws_waf_ipset.go b/builtin/providers/aws/resource_aws_waf_ipset.go index 4b07f6419..40ef54ff3 100644 --- a/builtin/providers/aws/resource_aws_waf_ipset.go +++ b/builtin/providers/aws/resource_aws_waf_ipset.go @@ -46,23 +46,18 @@ func resourceAwsWafIPSet() *schema.Resource { func resourceAwsWafIPSetCreate(d *schema.ResourceData, meta interface{}) error { conn := meta.(*AWSClient).wafconn - // ChangeToken - var ct *waf.GetChangeTokenInput - - res, err := conn.GetChangeToken(ct) - if err != nil { - return fmt.Errorf("Error getting change token: %s", err) - } - - params := &waf.CreateIPSetInput{ - ChangeToken: res.ChangeToken, - Name: aws.String(d.Get("name").(string)), - } - - resp, err := conn.CreateIPSet(params) + wr := newWafRetryer(conn, "global") + out, err := wr.RetryWithToken(func(token *string) (interface{}, error) { + params := &waf.CreateIPSetInput{ + ChangeToken: token, + Name: aws.String(d.Get("name").(string)), + } + return conn.CreateIPSet(params) + }) if err != nil { return err } + resp := out.(*waf.CreateIPSetOutput) d.SetId(*resp.IPSet.IPSetId) return resourceAwsWafIPSetUpdate(d, meta) } @@ -85,17 +80,17 @@ func resourceAwsWafIPSetRead(d *schema.ResourceData, meta interface{}) error { return err } - var IPSetDescriptors []map[string]interface{} + var descriptors []map[string]interface{} - for _, IPSetDescriptor := range resp.IPSet.IPSetDescriptors { - IPSet := map[string]interface{}{ - "type": *IPSetDescriptor.Type, - "value": *IPSetDescriptor.Value, + for _, descriptor := range resp.IPSet.IPSetDescriptors { + d := map[string]interface{}{ + "type": *descriptor.Type, + "value": *descriptor.Value, } - IPSetDescriptors = append(IPSetDescriptors, IPSet) + descriptors = append(descriptors, d) } - d.Set("ip_set_descriptors", IPSetDescriptors) + d.Set("ip_set_descriptors", descriptors) d.Set("name", resp.IPSet.Name) @@ -103,32 +98,43 @@ func resourceAwsWafIPSetRead(d *schema.ResourceData, meta interface{}) error { } func resourceAwsWafIPSetUpdate(d *schema.ResourceData, meta interface{}) error { - err := updateIPSetResource(d, meta, waf.ChangeActionInsert) - if err != nil { - return fmt.Errorf("Error Updating WAF IPSet: %s", err) + conn := meta.(*AWSClient).wafconn + + if d.HasChange("ip_set_descriptors") { + o, n := d.GetChange("ip_set_descriptors") + oldD, newD := o.(*schema.Set).List(), n.(*schema.Set).List() + + err := updateWafIpSetDescriptors(d.Id(), oldD, newD, conn) + if err != nil { + return fmt.Errorf("Error Updating WAF IPSet: %s", err) + } } + return resourceAwsWafIPSetRead(d, meta) } func resourceAwsWafIPSetDelete(d *schema.ResourceData, meta interface{}) error { conn := meta.(*AWSClient).wafconn - err := updateIPSetResource(d, meta, waf.ChangeActionDelete) - if err != nil { - return fmt.Errorf("Error Removing IPSetDescriptors: %s", err) + + oldDescriptors := d.Get("ip_set_descriptors").(*schema.Set).List() + + if len(oldDescriptors) > 0 { + noDescriptors := []interface{}{} + err := updateWafIpSetDescriptors(d.Id(), oldDescriptors, noDescriptors, conn) + if err != nil { + return fmt.Errorf("Error updating IPSetDescriptors: %s", err) + } } - // ChangeToken - var ct *waf.GetChangeTokenInput - - resp, err := conn.GetChangeToken(ct) - - req := &waf.DeleteIPSetInput{ - ChangeToken: resp.ChangeToken, - IPSetId: aws.String(d.Id()), - } - log.Printf("[INFO] Deleting WAF IPSet") - _, err = conn.DeleteIPSet(req) - + wr := newWafRetryer(conn, "global") + _, err := wr.RetryWithToken(func(token *string) (interface{}, error) { + req := &waf.DeleteIPSetInput{ + ChangeToken: token, + IPSetId: aws.String(d.Id()), + } + log.Printf("[INFO] Deleting WAF IPSet") + return conn.DeleteIPSet(req) + }) if err != nil { return fmt.Errorf("Error Deleting WAF IPSet: %s", err) } @@ -136,39 +142,54 @@ func resourceAwsWafIPSetDelete(d *schema.ResourceData, meta interface{}) error { return nil } -func updateIPSetResource(d *schema.ResourceData, meta interface{}, ChangeAction string) error { - conn := meta.(*AWSClient).wafconn - - // ChangeToken - var ct *waf.GetChangeTokenInput - - resp, err := conn.GetChangeToken(ct) - if err != nil { - return fmt.Errorf("Error getting change token: %s", err) - } - - req := &waf.UpdateIPSetInput{ - ChangeToken: resp.ChangeToken, - IPSetId: aws.String(d.Id()), - } - - IPSetDescriptors := d.Get("ip_set_descriptors").(*schema.Set) - for _, IPSetDescriptor := range IPSetDescriptors.List() { - IPSet := IPSetDescriptor.(map[string]interface{}) - IPSetUpdate := &waf.IPSetUpdate{ - Action: aws.String(ChangeAction), - IPSetDescriptor: &waf.IPSetDescriptor{ - Type: aws.String(IPSet["type"].(string)), - Value: aws.String(IPSet["value"].(string)), - }, +func updateWafIpSetDescriptors(id string, oldD, newD []interface{}, conn *waf.WAF) error { + wr := newWafRetryer(conn, "global") + _, err := wr.RetryWithToken(func(token *string) (interface{}, error) { + req := &waf.UpdateIPSetInput{ + ChangeToken: token, + IPSetId: aws.String(id), + Updates: diffWafIpSetDescriptors(oldD, newD), } - req.Updates = append(req.Updates, IPSetUpdate) - } - - _, err = conn.UpdateIPSet(req) + log.Printf("[INFO] Updating IPSet descriptors: %s", req) + return conn.UpdateIPSet(req) + }) if err != nil { return fmt.Errorf("Error Updating WAF IPSet: %s", err) } return nil } + +func diffWafIpSetDescriptors(oldD, newD []interface{}) []*waf.IPSetUpdate { + updates := make([]*waf.IPSetUpdate, 0) + + for _, od := range oldD { + descriptor := od.(map[string]interface{}) + + if idx, contains := sliceContainsMap(newD, descriptor); contains { + newD = append(newD[:idx], newD[idx+1:]...) + continue + } + + updates = append(updates, &waf.IPSetUpdate{ + Action: aws.String(waf.ChangeActionDelete), + IPSetDescriptor: &waf.IPSetDescriptor{ + Type: aws.String(descriptor["type"].(string)), + Value: aws.String(descriptor["value"].(string)), + }, + }) + } + + for _, nd := range newD { + descriptor := nd.(map[string]interface{}) + + updates = append(updates, &waf.IPSetUpdate{ + Action: aws.String(waf.ChangeActionInsert), + IPSetDescriptor: &waf.IPSetDescriptor{ + Type: aws.String(descriptor["type"].(string)), + Value: aws.String(descriptor["value"].(string)), + }, + }) + } + return updates +} diff --git a/builtin/providers/aws/resource_aws_waf_ipset_test.go b/builtin/providers/aws/resource_aws_waf_ipset_test.go index ffb4d6cb0..ee7593116 100644 --- a/builtin/providers/aws/resource_aws_waf_ipset_test.go +++ b/builtin/providers/aws/resource_aws_waf_ipset_test.go @@ -2,6 +2,7 @@ package aws import ( "fmt" + "reflect" "testing" "github.com/hashicorp/terraform/helper/resource" @@ -96,50 +97,206 @@ func TestAccAWSWafIPSet_changeNameForceNew(t *testing.T) { }) } +func TestAccAWSWafIPSet_changeDescriptors(t *testing.T) { + var before, after waf.IPSet + ipsetName := fmt.Sprintf("ip-set-%s", acctest.RandString(5)) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSWafIPSetDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAWSWafIPSetConfig(ipsetName), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckAWSWafIPSetExists("aws_waf_ipset.ipset", &before), + resource.TestCheckResourceAttr( + "aws_waf_ipset.ipset", "name", ipsetName), + resource.TestCheckResourceAttr( + "aws_waf_ipset.ipset", "ip_set_descriptors.#", "1"), + resource.TestCheckResourceAttr( + "aws_waf_ipset.ipset", "ip_set_descriptors.4037960608.type", "IPV4"), + resource.TestCheckResourceAttr( + "aws_waf_ipset.ipset", "ip_set_descriptors.4037960608.value", "192.0.7.0/24"), + ), + }, + { + Config: testAccAWSWafIPSetConfigChangeIPSetDescriptors(ipsetName), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckAWSWafIPSetExists("aws_waf_ipset.ipset", &after), + resource.TestCheckResourceAttr( + "aws_waf_ipset.ipset", "name", ipsetName), + resource.TestCheckResourceAttr( + "aws_waf_ipset.ipset", "ip_set_descriptors.#", "1"), + resource.TestCheckResourceAttr( + "aws_waf_ipset.ipset", "ip_set_descriptors.115741513.type", "IPV4"), + resource.TestCheckResourceAttr( + "aws_waf_ipset.ipset", "ip_set_descriptors.115741513.value", "192.0.8.0/24"), + ), + }, + }, + }) +} + +func TestAccAWSWafIPSet_noDescriptors(t *testing.T) { + var ipset waf.IPSet + ipsetName := fmt.Sprintf("ip-set-%s", acctest.RandString(5)) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSWafIPSetDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAWSWafIPSetConfig_noDescriptors(ipsetName), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckAWSWafIPSetExists("aws_waf_ipset.ipset", &ipset), + resource.TestCheckResourceAttr( + "aws_waf_ipset.ipset", "name", ipsetName), + resource.TestCheckResourceAttr( + "aws_waf_ipset.ipset", "ip_set_descriptors.#", "0"), + ), + }, + }, + }) +} + +func TestDiffWafIpSetDescriptors(t *testing.T) { + testCases := []struct { + Old []interface{} + New []interface{} + ExpectedUpdates []*waf.IPSetUpdate + }{ + { + // Change + Old: []interface{}{ + map[string]interface{}{"type": "IPV4", "value": "192.0.7.0/24"}, + }, + New: []interface{}{ + map[string]interface{}{"type": "IPV4", "value": "192.0.8.0/24"}, + }, + ExpectedUpdates: []*waf.IPSetUpdate{ + &waf.IPSetUpdate{ + Action: aws.String(waf.ChangeActionDelete), + IPSetDescriptor: &waf.IPSetDescriptor{ + Type: aws.String("IPV4"), + Value: aws.String("192.0.7.0/24"), + }, + }, + &waf.IPSetUpdate{ + Action: aws.String(waf.ChangeActionInsert), + IPSetDescriptor: &waf.IPSetDescriptor{ + Type: aws.String("IPV4"), + Value: aws.String("192.0.8.0/24"), + }, + }, + }, + }, + { + // Fresh IPSet + Old: []interface{}{}, + New: []interface{}{ + map[string]interface{}{"type": "IPV4", "value": "10.0.1.0/24"}, + map[string]interface{}{"type": "IPV4", "value": "10.0.2.0/24"}, + map[string]interface{}{"type": "IPV4", "value": "10.0.3.0/24"}, + }, + ExpectedUpdates: []*waf.IPSetUpdate{ + &waf.IPSetUpdate{ + Action: aws.String(waf.ChangeActionInsert), + IPSetDescriptor: &waf.IPSetDescriptor{ + Type: aws.String("IPV4"), + Value: aws.String("10.0.1.0/24"), + }, + }, + &waf.IPSetUpdate{ + Action: aws.String(waf.ChangeActionInsert), + IPSetDescriptor: &waf.IPSetDescriptor{ + Type: aws.String("IPV4"), + Value: aws.String("10.0.2.0/24"), + }, + }, + &waf.IPSetUpdate{ + Action: aws.String(waf.ChangeActionInsert), + IPSetDescriptor: &waf.IPSetDescriptor{ + Type: aws.String("IPV4"), + Value: aws.String("10.0.3.0/24"), + }, + }, + }, + }, + { + // Deletion + Old: []interface{}{ + map[string]interface{}{"type": "IPV4", "value": "192.0.7.0/24"}, + map[string]interface{}{"type": "IPV4", "value": "192.0.8.0/24"}, + }, + New: []interface{}{}, + ExpectedUpdates: []*waf.IPSetUpdate{ + &waf.IPSetUpdate{ + Action: aws.String(waf.ChangeActionDelete), + IPSetDescriptor: &waf.IPSetDescriptor{ + Type: aws.String("IPV4"), + Value: aws.String("192.0.7.0/24"), + }, + }, + &waf.IPSetUpdate{ + Action: aws.String(waf.ChangeActionDelete), + IPSetDescriptor: &waf.IPSetDescriptor{ + Type: aws.String("IPV4"), + Value: aws.String("192.0.8.0/24"), + }, + }, + }, + }, + } + for i, tc := range testCases { + t.Run(fmt.Sprintf("%d", i), func(t *testing.T) { + updates := diffWafIpSetDescriptors(tc.Old, tc.New) + if !reflect.DeepEqual(updates, tc.ExpectedUpdates) { + t.Fatalf("IPSet updates don't match.\nGiven: %s\nExpected: %s", + updates, tc.ExpectedUpdates) + } + }) + } +} + func testAccCheckAWSWafIPSetDisappears(v *waf.IPSet) resource.TestCheckFunc { return func(s *terraform.State) error { conn := testAccProvider.Meta().(*AWSClient).wafconn - // ChangeToken - var ct *waf.GetChangeTokenInput - - resp, err := conn.GetChangeToken(ct) - if err != nil { - return fmt.Errorf("Error getting change token: %s", err) - } - - req := &waf.UpdateIPSetInput{ - ChangeToken: resp.ChangeToken, - IPSetId: v.IPSetId, - } - - for _, IPSetDescriptor := range v.IPSetDescriptors { - IPSetUpdate := &waf.IPSetUpdate{ - Action: aws.String("DELETE"), - IPSetDescriptor: &waf.IPSetDescriptor{ - Type: IPSetDescriptor.Type, - Value: IPSetDescriptor.Value, - }, + wr := newWafRetryer(conn, "global") + _, err := wr.RetryWithToken(func(token *string) (interface{}, error) { + req := &waf.UpdateIPSetInput{ + ChangeToken: token, + IPSetId: v.IPSetId, } - req.Updates = append(req.Updates, IPSetUpdate) - } - _, err = conn.UpdateIPSet(req) + for _, IPSetDescriptor := range v.IPSetDescriptors { + IPSetUpdate := &waf.IPSetUpdate{ + Action: aws.String("DELETE"), + IPSetDescriptor: &waf.IPSetDescriptor{ + Type: IPSetDescriptor.Type, + Value: IPSetDescriptor.Value, + }, + } + req.Updates = append(req.Updates, IPSetUpdate) + } + + return conn.UpdateIPSet(req) + }) if err != nil { return fmt.Errorf("Error Updating WAF IPSet: %s", err) } - resp, err = conn.GetChangeToken(ct) + _, err = wr.RetryWithToken(func(token *string) (interface{}, error) { + opts := &waf.DeleteIPSetInput{ + ChangeToken: token, + IPSetId: v.IPSetId, + } + return conn.DeleteIPSet(opts) + }) if err != nil { - return fmt.Errorf("Error getting change token for waf IPSet: %s", err) - } - - opts := &waf.DeleteIPSetInput{ - ChangeToken: resp.ChangeToken, - IPSetId: v.IPSetId, - } - if _, err := conn.DeleteIPSet(opts); err != nil { - return err + return fmt.Errorf("Error Deleting WAF IPSet: %s", err) } return nil } @@ -235,3 +392,9 @@ func testAccAWSWafIPSetConfigChangeIPSetDescriptors(name string) string { } }`, name) } + +func testAccAWSWafIPSetConfig_noDescriptors(name string) string { + return fmt.Sprintf(`resource "aws_waf_ipset" "ipset" { + name = "%s" +}`, name) +} diff --git a/builtin/providers/aws/resource_aws_waf_rule.go b/builtin/providers/aws/resource_aws_waf_rule.go index ba59bf222..e7d44d7be 100644 --- a/builtin/providers/aws/resource_aws_waf_rule.go +++ b/builtin/providers/aws/resource_aws_waf_rule.go @@ -24,9 +24,10 @@ func resourceAwsWafRule() *schema.Resource { ForceNew: true, }, "metric_name": &schema.Schema{ - Type: schema.TypeString, - Required: true, - ForceNew: true, + Type: schema.TypeString, + Required: true, + ForceNew: true, + ValidateFunc: validateWafMetricName, }, "predicates": &schema.Schema{ Type: schema.TypeSet, @@ -71,24 +72,20 @@ func resourceAwsWafRule() *schema.Resource { func resourceAwsWafRuleCreate(d *schema.ResourceData, meta interface{}) error { conn := meta.(*AWSClient).wafconn - // ChangeToken - var ct *waf.GetChangeTokenInput + wr := newWafRetryer(conn, "global") + out, err := wr.RetryWithToken(func(token *string) (interface{}, error) { + params := &waf.CreateRuleInput{ + ChangeToken: token, + MetricName: aws.String(d.Get("metric_name").(string)), + Name: aws.String(d.Get("name").(string)), + } - res, err := conn.GetChangeToken(ct) - if err != nil { - return fmt.Errorf("Error getting change token: %s", err) - } - - params := &waf.CreateRuleInput{ - ChangeToken: res.ChangeToken, - MetricName: aws.String(d.Get("metric_name").(string)), - Name: aws.String(d.Get("name").(string)), - } - - resp, err := conn.CreateRule(params) + return conn.CreateRule(params) + }) if err != nil { return err } + resp := out.(*waf.CreateRuleOutput) d.SetId(*resp.Rule.RuleId) return resourceAwsWafRuleUpdate(d, meta) } @@ -130,31 +127,42 @@ func resourceAwsWafRuleRead(d *schema.ResourceData, meta interface{}) error { } func resourceAwsWafRuleUpdate(d *schema.ResourceData, meta interface{}) error { - err := updateWafRuleResource(d, meta, waf.ChangeActionInsert) - if err != nil { - return fmt.Errorf("Error Updating WAF Rule: %s", err) + conn := meta.(*AWSClient).wafconn + + if d.HasChange("predicates") { + o, n := d.GetChange("predicates") + oldP, newP := o.(*schema.Set).List(), n.(*schema.Set).List() + + err := updateWafRuleResource(d.Id(), oldP, newP, conn) + if err != nil { + return fmt.Errorf("Error Updating WAF Rule: %s", err) + } } + return resourceAwsWafRuleRead(d, meta) } func resourceAwsWafRuleDelete(d *schema.ResourceData, meta interface{}) error { conn := meta.(*AWSClient).wafconn - err := updateWafRuleResource(d, meta, waf.ChangeActionDelete) - if err != nil { - return fmt.Errorf("Error Removing WAF Rule Predicates: %s", err) + + oldPredicates := d.Get("predicates").(*schema.Set).List() + if len(oldPredicates) > 0 { + noPredicates := []interface{}{} + err := updateWafRuleResource(d.Id(), oldPredicates, noPredicates, conn) + if err != nil { + return fmt.Errorf("Error updating WAF Rule Predicates: %s", err) + } } - // ChangeToken - var ct *waf.GetChangeTokenInput - - resp, err := conn.GetChangeToken(ct) - - req := &waf.DeleteRuleInput{ - ChangeToken: resp.ChangeToken, - RuleId: aws.String(d.Id()), - } - log.Printf("[INFO] Deleting WAF Rule") - _, err = conn.DeleteRule(req) + wr := newWafRetryer(conn, "global") + _, err := wr.RetryWithToken(func(token *string) (interface{}, error) { + req := &waf.DeleteRuleInput{ + ChangeToken: token, + RuleId: aws.String(d.Id()), + } + log.Printf("[INFO] Deleting WAF Rule") + return conn.DeleteRule(req) + }) if err != nil { return fmt.Errorf("Error deleting WAF Rule: %s", err) } @@ -162,40 +170,56 @@ func resourceAwsWafRuleDelete(d *schema.ResourceData, meta interface{}) error { return nil } -func updateWafRuleResource(d *schema.ResourceData, meta interface{}, ChangeAction string) error { - conn := meta.(*AWSClient).wafconn - - // ChangeToken - var ct *waf.GetChangeTokenInput - - resp, err := conn.GetChangeToken(ct) - if err != nil { - return fmt.Errorf("Error getting change token: %s", err) - } - - req := &waf.UpdateRuleInput{ - ChangeToken: resp.ChangeToken, - RuleId: aws.String(d.Id()), - } - - predicatesSet := d.Get("predicates").(*schema.Set) - for _, predicateI := range predicatesSet.List() { - predicate := predicateI.(map[string]interface{}) - updatePredicate := &waf.RuleUpdate{ - Action: aws.String(ChangeAction), - Predicate: &waf.Predicate{ - Negated: aws.Bool(predicate["negated"].(bool)), - Type: aws.String(predicate["type"].(string)), - DataId: aws.String(predicate["data_id"].(string)), - }, +func updateWafRuleResource(id string, oldP, newP []interface{}, conn *waf.WAF) error { + wr := newWafRetryer(conn, "global") + _, err := wr.RetryWithToken(func(token *string) (interface{}, error) { + req := &waf.UpdateRuleInput{ + ChangeToken: token, + RuleId: aws.String(id), + Updates: diffWafRulePredicates(oldP, newP), } - req.Updates = append(req.Updates, updatePredicate) - } - _, err = conn.UpdateRule(req) + return conn.UpdateRule(req) + }) if err != nil { return fmt.Errorf("Error Updating WAF Rule: %s", err) } return nil } + +func diffWafRulePredicates(oldP, newP []interface{}) []*waf.RuleUpdate { + updates := make([]*waf.RuleUpdate, 0) + + for _, op := range oldP { + predicate := op.(map[string]interface{}) + + if idx, contains := sliceContainsMap(newP, predicate); contains { + newP = append(newP[:idx], newP[idx+1:]...) + continue + } + + updates = append(updates, &waf.RuleUpdate{ + Action: aws.String(waf.ChangeActionDelete), + Predicate: &waf.Predicate{ + Negated: aws.Bool(predicate["negated"].(bool)), + Type: aws.String(predicate["type"].(string)), + DataId: aws.String(predicate["data_id"].(string)), + }, + }) + } + + for _, np := range newP { + predicate := np.(map[string]interface{}) + + updates = append(updates, &waf.RuleUpdate{ + Action: aws.String(waf.ChangeActionInsert), + Predicate: &waf.Predicate{ + Negated: aws.Bool(predicate["negated"].(bool)), + Type: aws.String(predicate["type"].(string)), + DataId: aws.String(predicate["data_id"].(string)), + }, + }) + } + return updates +} diff --git a/builtin/providers/aws/resource_aws_waf_rule_test.go b/builtin/providers/aws/resource_aws_waf_rule_test.go index 52065b106..456b1f5aa 100644 --- a/builtin/providers/aws/resource_aws_waf_rule_test.go +++ b/builtin/providers/aws/resource_aws_waf_rule_test.go @@ -5,6 +5,7 @@ import ( "testing" "github.com/hashicorp/terraform/helper/resource" + "github.com/hashicorp/terraform/helper/schema" "github.com/hashicorp/terraform/terraform" "github.com/aws/aws-sdk-go/aws" @@ -95,51 +96,152 @@ func TestAccAWSWafRule_disappears(t *testing.T) { }) } +func TestAccAWSWafRule_changePredicates(t *testing.T) { + var ipset waf.IPSet + var byteMatchSet waf.ByteMatchSet + + var before, after waf.Rule + var idx int + ruleName := fmt.Sprintf("wafrule%s", acctest.RandString(5)) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSWafRuleDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAWSWafRuleConfig(ruleName), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckAWSWafIPSetExists("aws_waf_ipset.ipset", &ipset), + testAccCheckAWSWafRuleExists("aws_waf_rule.wafrule", &before), + resource.TestCheckResourceAttr("aws_waf_rule.wafrule", "name", ruleName), + resource.TestCheckResourceAttr("aws_waf_rule.wafrule", "predicates.#", "1"), + computeWafRulePredicateWithIpSet(&ipset, false, "IPMatch", &idx), + testCheckResourceAttrWithIndexesAddr("aws_waf_rule.wafrule", "predicates.%d.negated", &idx, "false"), + testCheckResourceAttrWithIndexesAddr("aws_waf_rule.wafrule", "predicates.%d.type", &idx, "IPMatch"), + ), + }, + { + Config: testAccAWSWafRuleConfig_changePredicates(ruleName), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckAWSWafByteMatchSetExists("aws_waf_byte_match_set.set", &byteMatchSet), + testAccCheckAWSWafRuleExists("aws_waf_rule.wafrule", &after), + resource.TestCheckResourceAttr("aws_waf_rule.wafrule", "name", ruleName), + resource.TestCheckResourceAttr("aws_waf_rule.wafrule", "predicates.#", "1"), + computeWafRulePredicateWithByteMatchSet(&byteMatchSet, true, "ByteMatch", &idx), + testCheckResourceAttrWithIndexesAddr("aws_waf_rule.wafrule", "predicates.%d.negated", &idx, "true"), + testCheckResourceAttrWithIndexesAddr("aws_waf_rule.wafrule", "predicates.%d.type", &idx, "ByteMatch"), + ), + }, + }, + }) +} + +// computeWafRulePredicateWithIpSet calculates index +// which isn't static because dataId is generated as part of the test +func computeWafRulePredicateWithIpSet(ipSet *waf.IPSet, negated bool, pType string, idx *int) resource.TestCheckFunc { + return func(s *terraform.State) error { + predicateResource := resourceAwsWafRule().Schema["predicates"].Elem.(*schema.Resource) + + m := map[string]interface{}{ + "data_id": *ipSet.IPSetId, + "negated": negated, + "type": pType, + } + + f := schema.HashResource(predicateResource) + *idx = f(m) + + return nil + } +} + +// computeWafRulePredicateWithByteMatchSet calculates index +// which isn't static because dataId is generated as part of the test +func computeWafRulePredicateWithByteMatchSet(set *waf.ByteMatchSet, negated bool, pType string, idx *int) resource.TestCheckFunc { + return func(s *terraform.State) error { + predicateResource := resourceAwsWafRule().Schema["predicates"].Elem.(*schema.Resource) + + m := map[string]interface{}{ + "data_id": *set.ByteMatchSetId, + "negated": negated, + "type": pType, + } + + f := schema.HashResource(predicateResource) + *idx = f(m) + + return nil + } +} + +func testCheckResourceAttrWithIndexesAddr(name, format string, idx *int, value string) resource.TestCheckFunc { + return func(s *terraform.State) error { + return resource.TestCheckResourceAttr(name, fmt.Sprintf(format, *idx), value)(s) + } +} + +func TestAccAWSWafRule_noPredicates(t *testing.T) { + var rule waf.Rule + ruleName := fmt.Sprintf("wafrule%s", acctest.RandString(5)) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSWafRuleDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAWSWafRuleConfig_noPredicates(ruleName), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckAWSWafRuleExists("aws_waf_rule.wafrule", &rule), + resource.TestCheckResourceAttr( + "aws_waf_rule.wafrule", "name", ruleName), + resource.TestCheckResourceAttr( + "aws_waf_rule.wafrule", "predicates.#", "0"), + ), + }, + }, + }) +} + func testAccCheckAWSWafRuleDisappears(v *waf.Rule) resource.TestCheckFunc { return func(s *terraform.State) error { conn := testAccProvider.Meta().(*AWSClient).wafconn - // ChangeToken - var ct *waf.GetChangeTokenInput - - resp, err := conn.GetChangeToken(ct) - if err != nil { - return fmt.Errorf("Error getting change token: %s", err) - } - - req := &waf.UpdateRuleInput{ - ChangeToken: resp.ChangeToken, - RuleId: v.RuleId, - } - - for _, Predicate := range v.Predicates { - Predicate := &waf.RuleUpdate{ - Action: aws.String("DELETE"), - Predicate: &waf.Predicate{ - Negated: Predicate.Negated, - Type: Predicate.Type, - DataId: Predicate.DataId, - }, + wr := newWafRetryer(conn, "global") + _, err := wr.RetryWithToken(func(token *string) (interface{}, error) { + req := &waf.UpdateRuleInput{ + ChangeToken: token, + RuleId: v.RuleId, } - req.Updates = append(req.Updates, Predicate) - } - _, err = conn.UpdateRule(req) + for _, Predicate := range v.Predicates { + Predicate := &waf.RuleUpdate{ + Action: aws.String("DELETE"), + Predicate: &waf.Predicate{ + Negated: Predicate.Negated, + Type: Predicate.Type, + DataId: Predicate.DataId, + }, + } + req.Updates = append(req.Updates, Predicate) + } + + return conn.UpdateRule(req) + }) if err != nil { return fmt.Errorf("Error Updating WAF Rule: %s", err) } - resp, err = conn.GetChangeToken(ct) + _, err = wr.RetryWithToken(func(token *string) (interface{}, error) { + opts := &waf.DeleteRuleInput{ + ChangeToken: token, + RuleId: v.RuleId, + } + return conn.DeleteRule(opts) + }) if err != nil { - return fmt.Errorf("Error getting change token for waf Rule: %s", err) - } - - opts := &waf.DeleteRuleInput{ - ChangeToken: resp.ChangeToken, - RuleId: v.RuleId, - } - if _, err := conn.DeleteRule(opts); err != nil { - return err + return fmt.Errorf("Error Deleting WAF Rule: %s", err) } return nil } @@ -248,3 +350,46 @@ resource "aws_waf_rule" "wafrule" { } }`, name, name, name) } + +func testAccAWSWafRuleConfig_changePredicates(name string) string { + return fmt.Sprintf(` +resource "aws_waf_ipset" "ipset" { + name = "%s" + ip_set_descriptors { + type = "IPV4" + value = "192.0.7.0/24" + } +} + +resource "aws_waf_byte_match_set" "set" { + name = "%s" + byte_match_tuples { + text_transformation = "NONE" + target_string = "badrefer1" + positional_constraint = "CONTAINS" + + field_to_match { + type = "HEADER" + data = "referer" + } + } +} + +resource "aws_waf_rule" "wafrule" { + name = "%s" + metric_name = "%s" + predicates { + data_id = "${aws_waf_byte_match_set.set.id}" + negated = true + type = "ByteMatch" + } +}`, name, name, name, name) +} + +func testAccAWSWafRuleConfig_noPredicates(name string) string { + return fmt.Sprintf(` +resource "aws_waf_rule" "wafrule" { + name = "%s" + metric_name = "%s" +}`, name, name) +} diff --git a/builtin/providers/aws/resource_aws_waf_size_constraint_set.go b/builtin/providers/aws/resource_aws_waf_size_constraint_set.go index 9f384e82c..db9d5c516 100644 --- a/builtin/providers/aws/resource_aws_waf_size_constraint_set.go +++ b/builtin/providers/aws/resource_aws_waf_size_constraint_set.go @@ -69,24 +69,19 @@ func resourceAwsWafSizeConstraintSetCreate(d *schema.ResourceData, meta interfac log.Printf("[INFO] Creating SizeConstraintSet: %s", d.Get("name").(string)) - // ChangeToken - var ct *waf.GetChangeTokenInput - - res, err := conn.GetChangeToken(ct) - if err != nil { - return errwrap.Wrapf("[ERROR] Error getting change token: {{err}}", err) - } - - params := &waf.CreateSizeConstraintSetInput{ - ChangeToken: res.ChangeToken, - Name: aws.String(d.Get("name").(string)), - } - - resp, err := conn.CreateSizeConstraintSet(params) + wr := newWafRetryer(conn, "global") + out, err := wr.RetryWithToken(func(token *string) (interface{}, error) { + params := &waf.CreateSizeConstraintSetInput{ + ChangeToken: token, + Name: aws.String(d.Get("name").(string)), + } + return conn.CreateSizeConstraintSet(params) + }) if err != nil { return errwrap.Wrapf("[ERROR] Error creating SizeConstraintSet: {{err}}", err) } + resp := out.(*waf.CreateSizeConstraintSetOutput) d.SetId(*resp.SizeConstraintSet.SizeConstraintSetId) @@ -134,17 +129,14 @@ func resourceAwsWafSizeConstraintSetDelete(d *schema.ResourceData, meta interfac return errwrap.Wrapf("[ERROR] Error deleting SizeConstraintSet: {{err}}", err) } - var ct *waf.GetChangeTokenInput - - resp, err := conn.GetChangeToken(ct) - - req := &waf.DeleteSizeConstraintSetInput{ - ChangeToken: resp.ChangeToken, - SizeConstraintSetId: aws.String(d.Id()), - } - - _, err = conn.DeleteSizeConstraintSet(req) - + wr := newWafRetryer(conn, "global") + _, err = wr.RetryWithToken(func(token *string) (interface{}, error) { + req := &waf.DeleteSizeConstraintSetInput{ + ChangeToken: token, + SizeConstraintSetId: aws.String(d.Id()), + } + return conn.DeleteSizeConstraintSet(req) + }) if err != nil { return errwrap.Wrapf("[ERROR] Error deleting SizeConstraintSet: {{err}}", err) } @@ -155,34 +147,30 @@ func resourceAwsWafSizeConstraintSetDelete(d *schema.ResourceData, meta interfac func updateSizeConstraintSetResource(d *schema.ResourceData, meta interface{}, ChangeAction string) error { conn := meta.(*AWSClient).wafconn - var ct *waf.GetChangeTokenInput - - resp, err := conn.GetChangeToken(ct) - if err != nil { - return errwrap.Wrapf("[ERROR] Error getting change token: {{err}}", err) - } - - req := &waf.UpdateSizeConstraintSetInput{ - ChangeToken: resp.ChangeToken, - SizeConstraintSetId: aws.String(d.Id()), - } - - sizeConstraints := d.Get("size_constraints").(*schema.Set) - for _, sizeConstraint := range sizeConstraints.List() { - sc := sizeConstraint.(map[string]interface{}) - sizeConstraintUpdate := &waf.SizeConstraintSetUpdate{ - Action: aws.String(ChangeAction), - SizeConstraint: &waf.SizeConstraint{ - FieldToMatch: expandFieldToMatch(sc["field_to_match"].(*schema.Set).List()[0].(map[string]interface{})), - ComparisonOperator: aws.String(sc["comparison_operator"].(string)), - Size: aws.Int64(int64(sc["size"].(int))), - TextTransformation: aws.String(sc["text_transformation"].(string)), - }, + wr := newWafRetryer(conn, "global") + _, err := wr.RetryWithToken(func(token *string) (interface{}, error) { + req := &waf.UpdateSizeConstraintSetInput{ + ChangeToken: token, + SizeConstraintSetId: aws.String(d.Id()), } - req.Updates = append(req.Updates, sizeConstraintUpdate) - } - _, err = conn.UpdateSizeConstraintSet(req) + sizeConstraints := d.Get("size_constraints").(*schema.Set) + for _, sizeConstraint := range sizeConstraints.List() { + sc := sizeConstraint.(map[string]interface{}) + sizeConstraintUpdate := &waf.SizeConstraintSetUpdate{ + Action: aws.String(ChangeAction), + SizeConstraint: &waf.SizeConstraint{ + FieldToMatch: expandFieldToMatch(sc["field_to_match"].(*schema.Set).List()[0].(map[string]interface{})), + ComparisonOperator: aws.String(sc["comparison_operator"].(string)), + Size: aws.Int64(int64(sc["size"].(int))), + TextTransformation: aws.String(sc["text_transformation"].(string)), + }, + } + req.Updates = append(req.Updates, sizeConstraintUpdate) + } + + return conn.UpdateSizeConstraintSet(req) + }) if err != nil { return errwrap.Wrapf("[ERROR] Error updating SizeConstraintSet: {{err}}", err) } diff --git a/builtin/providers/aws/resource_aws_waf_size_constraint_set_test.go b/builtin/providers/aws/resource_aws_waf_size_constraint_set_test.go index 13eee40e4..a6bd5156e 100644 --- a/builtin/providers/aws/resource_aws_waf_size_constraint_set_test.go +++ b/builtin/providers/aws/resource_aws_waf_size_constraint_set_test.go @@ -96,45 +96,39 @@ func testAccCheckAWSWafSizeConstraintSetDisappears(v *waf.SizeConstraintSet) res return func(s *terraform.State) error { conn := testAccProvider.Meta().(*AWSClient).wafconn - var ct *waf.GetChangeTokenInput - - resp, err := conn.GetChangeToken(ct) - if err != nil { - return fmt.Errorf("Error getting change token: %s", err) - } - - req := &waf.UpdateSizeConstraintSetInput{ - ChangeToken: resp.ChangeToken, - SizeConstraintSetId: v.SizeConstraintSetId, - } - - for _, sizeConstraint := range v.SizeConstraints { - sizeConstraintUpdate := &waf.SizeConstraintSetUpdate{ - Action: aws.String("DELETE"), - SizeConstraint: &waf.SizeConstraint{ - FieldToMatch: sizeConstraint.FieldToMatch, - ComparisonOperator: sizeConstraint.ComparisonOperator, - Size: sizeConstraint.Size, - TextTransformation: sizeConstraint.TextTransformation, - }, + wr := newWafRetryer(conn, "global") + _, err := wr.RetryWithToken(func(token *string) (interface{}, error) { + req := &waf.UpdateSizeConstraintSetInput{ + ChangeToken: token, + SizeConstraintSetId: v.SizeConstraintSetId, } - req.Updates = append(req.Updates, sizeConstraintUpdate) - } - _, err = conn.UpdateSizeConstraintSet(req) + + for _, sizeConstraint := range v.SizeConstraints { + sizeConstraintUpdate := &waf.SizeConstraintSetUpdate{ + Action: aws.String("DELETE"), + SizeConstraint: &waf.SizeConstraint{ + FieldToMatch: sizeConstraint.FieldToMatch, + ComparisonOperator: sizeConstraint.ComparisonOperator, + Size: sizeConstraint.Size, + TextTransformation: sizeConstraint.TextTransformation, + }, + } + req.Updates = append(req.Updates, sizeConstraintUpdate) + } + return conn.UpdateSizeConstraintSet(req) + }) if err != nil { return errwrap.Wrapf("[ERROR] Error updating SizeConstraintSet: {{err}}", err) } - resp, err = conn.GetChangeToken(ct) + _, err = wr.RetryWithToken(func(token *string) (interface{}, error) { + opts := &waf.DeleteSizeConstraintSetInput{ + ChangeToken: token, + SizeConstraintSetId: v.SizeConstraintSetId, + } + return conn.DeleteSizeConstraintSet(opts) + }) if err != nil { - return errwrap.Wrapf("[ERROR] Error getting change token: {{err}}", err) - } - - opts := &waf.DeleteSizeConstraintSetInput{ - ChangeToken: resp.ChangeToken, - SizeConstraintSetId: v.SizeConstraintSetId, - } - if _, err := conn.DeleteSizeConstraintSet(opts); err != nil { return err } return nil diff --git a/builtin/providers/aws/resource_aws_waf_sql_injection_match_set.go b/builtin/providers/aws/resource_aws_waf_sql_injection_match_set.go index 01efd6a32..c888efe5a 100644 --- a/builtin/providers/aws/resource_aws_waf_sql_injection_match_set.go +++ b/builtin/providers/aws/resource_aws_waf_sql_injection_match_set.go @@ -61,25 +61,19 @@ func resourceAwsWafSqlInjectionMatchSetCreate(d *schema.ResourceData, meta inter log.Printf("[INFO] Creating SqlInjectionMatchSet: %s", d.Get("name").(string)) - // ChangeToken - var ct *waf.GetChangeTokenInput - - res, err := conn.GetChangeToken(ct) - if err != nil { - return errwrap.Wrapf("[ERROR] Error getting change token: {{err}}", err) - } - - params := &waf.CreateSqlInjectionMatchSetInput{ - ChangeToken: res.ChangeToken, - Name: aws.String(d.Get("name").(string)), - } - - resp, err := conn.CreateSqlInjectionMatchSet(params) + wr := newWafRetryer(conn, "global") + out, err := wr.RetryWithToken(func(token *string) (interface{}, error) { + params := &waf.CreateSqlInjectionMatchSetInput{ + ChangeToken: token, + Name: aws.String(d.Get("name").(string)), + } + return conn.CreateSqlInjectionMatchSet(params) + }) if err != nil { return errwrap.Wrapf("[ERROR] Error creating SqlInjectionMatchSet: {{err}}", err) } - + resp := out.(*waf.CreateSqlInjectionMatchSetOutput) d.SetId(*resp.SqlInjectionMatchSet.SqlInjectionMatchSetId) return resourceAwsWafSqlInjectionMatchSetUpdate(d, meta) @@ -126,17 +120,15 @@ func resourceAwsWafSqlInjectionMatchSetDelete(d *schema.ResourceData, meta inter return errwrap.Wrapf("[ERROR] Error deleting SqlInjectionMatchSet: {{err}}", err) } - var ct *waf.GetChangeTokenInput - - resp, err := conn.GetChangeToken(ct) - - req := &waf.DeleteSqlInjectionMatchSetInput{ - ChangeToken: resp.ChangeToken, - SqlInjectionMatchSetId: aws.String(d.Id()), - } - - _, err = conn.DeleteSqlInjectionMatchSet(req) + wr := newWafRetryer(conn, "global") + _, err = wr.RetryWithToken(func(token *string) (interface{}, error) { + req := &waf.DeleteSqlInjectionMatchSetInput{ + ChangeToken: token, + SqlInjectionMatchSetId: aws.String(d.Id()), + } + return conn.DeleteSqlInjectionMatchSet(req) + }) if err != nil { return errwrap.Wrapf("[ERROR] Error deleting SqlInjectionMatchSet: {{err}}", err) } @@ -147,32 +139,28 @@ func resourceAwsWafSqlInjectionMatchSetDelete(d *schema.ResourceData, meta inter func updateSqlInjectionMatchSetResource(d *schema.ResourceData, meta interface{}, ChangeAction string) error { conn := meta.(*AWSClient).wafconn - var ct *waf.GetChangeTokenInput - - resp, err := conn.GetChangeToken(ct) - if err != nil { - return errwrap.Wrapf("[ERROR] Error getting change token: {{err}}", err) - } - - req := &waf.UpdateSqlInjectionMatchSetInput{ - ChangeToken: resp.ChangeToken, - SqlInjectionMatchSetId: aws.String(d.Id()), - } - - sqlInjectionMatchTuples := d.Get("sql_injection_match_tuples").(*schema.Set) - for _, sqlInjectionMatchTuple := range sqlInjectionMatchTuples.List() { - simt := sqlInjectionMatchTuple.(map[string]interface{}) - sizeConstraintUpdate := &waf.SqlInjectionMatchSetUpdate{ - Action: aws.String(ChangeAction), - SqlInjectionMatchTuple: &waf.SqlInjectionMatchTuple{ - FieldToMatch: expandFieldToMatch(simt["field_to_match"].(*schema.Set).List()[0].(map[string]interface{})), - TextTransformation: aws.String(simt["text_transformation"].(string)), - }, + wr := newWafRetryer(conn, "global") + _, err := wr.RetryWithToken(func(token *string) (interface{}, error) { + req := &waf.UpdateSqlInjectionMatchSetInput{ + ChangeToken: token, + SqlInjectionMatchSetId: aws.String(d.Id()), } - req.Updates = append(req.Updates, sizeConstraintUpdate) - } - _, err = conn.UpdateSqlInjectionMatchSet(req) + sqlInjectionMatchTuples := d.Get("sql_injection_match_tuples").(*schema.Set) + for _, sqlInjectionMatchTuple := range sqlInjectionMatchTuples.List() { + simt := sqlInjectionMatchTuple.(map[string]interface{}) + sizeConstraintUpdate := &waf.SqlInjectionMatchSetUpdate{ + Action: aws.String(ChangeAction), + SqlInjectionMatchTuple: &waf.SqlInjectionMatchTuple{ + FieldToMatch: expandFieldToMatch(simt["field_to_match"].(*schema.Set).List()[0].(map[string]interface{})), + TextTransformation: aws.String(simt["text_transformation"].(string)), + }, + } + req.Updates = append(req.Updates, sizeConstraintUpdate) + } + + return conn.UpdateSqlInjectionMatchSet(req) + }) if err != nil { return errwrap.Wrapf("[ERROR] Error updating SqlInjectionMatchSet: {{err}}", err) } diff --git a/builtin/providers/aws/resource_aws_waf_sql_injection_match_set_test.go b/builtin/providers/aws/resource_aws_waf_sql_injection_match_set_test.go index f13f6711e..5ea8bca0f 100644 --- a/builtin/providers/aws/resource_aws_waf_sql_injection_match_set_test.go +++ b/builtin/providers/aws/resource_aws_waf_sql_injection_match_set_test.go @@ -96,44 +96,38 @@ func testAccCheckAWSWafSqlInjectionMatchSetDisappears(v *waf.SqlInjectionMatchSe return func(s *terraform.State) error { conn := testAccProvider.Meta().(*AWSClient).wafconn - var ct *waf.GetChangeTokenInput - - resp, err := conn.GetChangeToken(ct) - if err != nil { - return fmt.Errorf("Error getting change token: %s", err) - } - - req := &waf.UpdateSqlInjectionMatchSetInput{ - ChangeToken: resp.ChangeToken, - SqlInjectionMatchSetId: v.SqlInjectionMatchSetId, - } - - for _, sqlInjectionMatchTuple := range v.SqlInjectionMatchTuples { - sqlInjectionMatchTupleUpdate := &waf.SqlInjectionMatchSetUpdate{ - Action: aws.String("DELETE"), - SqlInjectionMatchTuple: &waf.SqlInjectionMatchTuple{ - FieldToMatch: sqlInjectionMatchTuple.FieldToMatch, - TextTransformation: sqlInjectionMatchTuple.TextTransformation, - }, + wr := newWafRetryer(conn, "global") + _, err := wr.RetryWithToken(func(token *string) (interface{}, error) { + req := &waf.UpdateSqlInjectionMatchSetInput{ + ChangeToken: token, + SqlInjectionMatchSetId: v.SqlInjectionMatchSetId, } - req.Updates = append(req.Updates, sqlInjectionMatchTupleUpdate) - } - _, err = conn.UpdateSqlInjectionMatchSet(req) + + for _, sqlInjectionMatchTuple := range v.SqlInjectionMatchTuples { + sqlInjectionMatchTupleUpdate := &waf.SqlInjectionMatchSetUpdate{ + Action: aws.String("DELETE"), + SqlInjectionMatchTuple: &waf.SqlInjectionMatchTuple{ + FieldToMatch: sqlInjectionMatchTuple.FieldToMatch, + TextTransformation: sqlInjectionMatchTuple.TextTransformation, + }, + } + req.Updates = append(req.Updates, sqlInjectionMatchTupleUpdate) + } + return conn.UpdateSqlInjectionMatchSet(req) + }) if err != nil { return errwrap.Wrapf("[ERROR] Error updating SqlInjectionMatchSet: {{err}}", err) } - resp, err = conn.GetChangeToken(ct) + _, err = wr.RetryWithToken(func(token *string) (interface{}, error) { + opts := &waf.DeleteSqlInjectionMatchSetInput{ + ChangeToken: token, + SqlInjectionMatchSetId: v.SqlInjectionMatchSetId, + } + return conn.DeleteSqlInjectionMatchSet(opts) + }) if err != nil { - return errwrap.Wrapf("[ERROR] Error getting change token: {{err}}", err) - } - - opts := &waf.DeleteSqlInjectionMatchSetInput{ - ChangeToken: resp.ChangeToken, - SqlInjectionMatchSetId: v.SqlInjectionMatchSetId, - } - if _, err := conn.DeleteSqlInjectionMatchSet(opts); err != nil { - return err + return errwrap.Wrapf("[ERROR] Error deleting SqlInjectionMatchSet: {{err}}", err) } return nil } diff --git a/builtin/providers/aws/resource_aws_waf_web_acl.go b/builtin/providers/aws/resource_aws_waf_web_acl.go index dd3a9d1d3..7e3ac7237 100644 --- a/builtin/providers/aws/resource_aws_waf_web_acl.go +++ b/builtin/providers/aws/resource_aws_waf_web_acl.go @@ -37,9 +37,10 @@ func resourceAwsWafWebAcl() *schema.Resource { }, }, "metric_name": &schema.Schema{ - Type: schema.TypeString, - Required: true, - ForceNew: true, + Type: schema.TypeString, + Required: true, + ForceNew: true, + ValidateFunc: validateWafMetricName, }, "rules": &schema.Schema{ Type: schema.TypeSet, @@ -77,25 +78,21 @@ func resourceAwsWafWebAcl() *schema.Resource { func resourceAwsWafWebAclCreate(d *schema.ResourceData, meta interface{}) error { conn := meta.(*AWSClient).wafconn - // ChangeToken - var ct *waf.GetChangeTokenInput + wr := newWafRetryer(conn, "global") + out, err := wr.RetryWithToken(func(token *string) (interface{}, error) { + params := &waf.CreateWebACLInput{ + ChangeToken: token, + DefaultAction: expandDefaultAction(d), + MetricName: aws.String(d.Get("metric_name").(string)), + Name: aws.String(d.Get("name").(string)), + } - res, err := conn.GetChangeToken(ct) - if err != nil { - return fmt.Errorf("Error getting change token: %s", err) - } - - params := &waf.CreateWebACLInput{ - ChangeToken: res.ChangeToken, - DefaultAction: expandDefaultAction(d), - MetricName: aws.String(d.Get("metric_name").(string)), - Name: aws.String(d.Get("name").(string)), - } - - resp, err := conn.CreateWebACL(params) + return conn.CreateWebACL(params) + }) if err != nil { return err } + resp := out.(*waf.CreateWebACLOutput) d.SetId(*resp.WebACL.WebACLId) return resourceAwsWafWebAclUpdate(d, meta) } @@ -144,18 +141,16 @@ func resourceAwsWafWebAclDelete(d *schema.ResourceData, meta interface{}) error return fmt.Errorf("Error Removing WAF ACL Rules: %s", err) } - var ct *waf.GetChangeTokenInput - - resp, err := conn.GetChangeToken(ct) - - req := &waf.DeleteWebACLInput{ - ChangeToken: resp.ChangeToken, - WebACLId: aws.String(d.Id()), - } - - log.Printf("[INFO] Deleting WAF ACL") - _, err = conn.DeleteWebACL(req) + wr := newWafRetryer(conn, "global") + _, err = wr.RetryWithToken(func(token *string) (interface{}, error) { + req := &waf.DeleteWebACLInput{ + ChangeToken: token, + WebACLId: aws.String(d.Id()), + } + log.Printf("[INFO] Deleting WAF ACL") + return conn.DeleteWebACL(req) + }) if err != nil { return fmt.Errorf("Error Deleting WAF ACL: %s", err) } @@ -164,38 +159,34 @@ func resourceAwsWafWebAclDelete(d *schema.ResourceData, meta interface{}) error func updateWebAclResource(d *schema.ResourceData, meta interface{}, ChangeAction string) error { conn := meta.(*AWSClient).wafconn - // ChangeToken - var ct *waf.GetChangeTokenInput - resp, err := conn.GetChangeToken(ct) - if err != nil { - return fmt.Errorf("Error getting change token: %s", err) - } - - req := &waf.UpdateWebACLInput{ - ChangeToken: resp.ChangeToken, - WebACLId: aws.String(d.Id()), - } - - if d.HasChange("default_action") { - req.DefaultAction = expandDefaultAction(d) - } - - rules := d.Get("rules").(*schema.Set) - for _, rule := range rules.List() { - aclRule := rule.(map[string]interface{}) - action := aclRule["action"].(*schema.Set).List()[0].(map[string]interface{}) - aclRuleUpdate := &waf.WebACLUpdate{ - Action: aws.String(ChangeAction), - ActivatedRule: &waf.ActivatedRule{ - Priority: aws.Int64(int64(aclRule["priority"].(int))), - RuleId: aws.String(aclRule["rule_id"].(string)), - Action: &waf.WafAction{Type: aws.String(action["type"].(string))}, - }, + wr := newWafRetryer(conn, "global") + _, err := wr.RetryWithToken(func(token *string) (interface{}, error) { + req := &waf.UpdateWebACLInput{ + ChangeToken: token, + WebACLId: aws.String(d.Id()), } - req.Updates = append(req.Updates, aclRuleUpdate) - } - _, err = conn.UpdateWebACL(req) + + if d.HasChange("default_action") { + req.DefaultAction = expandDefaultAction(d) + } + + rules := d.Get("rules").(*schema.Set) + for _, rule := range rules.List() { + aclRule := rule.(map[string]interface{}) + action := aclRule["action"].(*schema.Set).List()[0].(map[string]interface{}) + aclRuleUpdate := &waf.WebACLUpdate{ + Action: aws.String(ChangeAction), + ActivatedRule: &waf.ActivatedRule{ + Priority: aws.Int64(int64(aclRule["priority"].(int))), + RuleId: aws.String(aclRule["rule_id"].(string)), + Action: &waf.WafAction{Type: aws.String(action["type"].(string))}, + }, + } + req.Updates = append(req.Updates, aclRuleUpdate) + } + return conn.UpdateWebACL(req) + }) if err != nil { return fmt.Errorf("Error Updating WAF ACL: %s", err) } diff --git a/builtin/providers/aws/resource_aws_waf_web_acl_test.go b/builtin/providers/aws/resource_aws_waf_web_acl_test.go index 265cb15a4..6591fed0e 100644 --- a/builtin/providers/aws/resource_aws_waf_web_acl_test.go +++ b/builtin/providers/aws/resource_aws_waf_web_acl_test.go @@ -159,47 +159,40 @@ func testAccCheckAWSWafWebAclDisappears(v *waf.WebACL) resource.TestCheckFunc { return func(s *terraform.State) error { conn := testAccProvider.Meta().(*AWSClient).wafconn - // ChangeToken - var ct *waf.GetChangeTokenInput - - resp, err := conn.GetChangeToken(ct) - if err != nil { - return fmt.Errorf("Error getting change token: %s", err) - } - - req := &waf.UpdateWebACLInput{ - ChangeToken: resp.ChangeToken, - WebACLId: v.WebACLId, - } - - for _, ActivatedRule := range v.Rules { - WebACLUpdate := &waf.WebACLUpdate{ - Action: aws.String("DELETE"), - ActivatedRule: &waf.ActivatedRule{ - Priority: ActivatedRule.Priority, - RuleId: ActivatedRule.RuleId, - Action: ActivatedRule.Action, - }, + wr := newWafRetryer(conn, "global") + _, err := wr.RetryWithToken(func(token *string) (interface{}, error) { + req := &waf.UpdateWebACLInput{ + ChangeToken: token, + WebACLId: v.WebACLId, } - req.Updates = append(req.Updates, WebACLUpdate) - } - _, err = conn.UpdateWebACL(req) + for _, ActivatedRule := range v.Rules { + WebACLUpdate := &waf.WebACLUpdate{ + Action: aws.String("DELETE"), + ActivatedRule: &waf.ActivatedRule{ + Priority: ActivatedRule.Priority, + RuleId: ActivatedRule.RuleId, + Action: ActivatedRule.Action, + }, + } + req.Updates = append(req.Updates, WebACLUpdate) + } + + return conn.UpdateWebACL(req) + }) if err != nil { return fmt.Errorf("Error Updating WAF ACL: %s", err) } - resp, err = conn.GetChangeToken(ct) + _, err = wr.RetryWithToken(func(token *string) (interface{}, error) { + opts := &waf.DeleteWebACLInput{ + ChangeToken: token, + WebACLId: v.WebACLId, + } + return conn.DeleteWebACL(opts) + }) if err != nil { - return fmt.Errorf("Error getting change token for waf ACL: %s", err) - } - - opts := &waf.DeleteWebACLInput{ - ChangeToken: resp.ChangeToken, - WebACLId: v.WebACLId, - } - if _, err := conn.DeleteWebACL(opts); err != nil { - return err + return fmt.Errorf("Error Deleting WAF ACL: %s", err) } return nil } diff --git a/builtin/providers/aws/resource_aws_waf_xss_match_set.go b/builtin/providers/aws/resource_aws_waf_xss_match_set.go index 574245f8b..222940dd0 100644 --- a/builtin/providers/aws/resource_aws_waf_xss_match_set.go +++ b/builtin/providers/aws/resource_aws_waf_xss_match_set.go @@ -61,24 +61,19 @@ func resourceAwsWafXssMatchSetCreate(d *schema.ResourceData, meta interface{}) e log.Printf("[INFO] Creating XssMatchSet: %s", d.Get("name").(string)) - // ChangeToken - var ct *waf.GetChangeTokenInput - - res, err := conn.GetChangeToken(ct) - if err != nil { - return errwrap.Wrapf("[ERROR] Error getting change token: {{err}}", err) - } - - params := &waf.CreateXssMatchSetInput{ - ChangeToken: res.ChangeToken, - Name: aws.String(d.Get("name").(string)), - } - - resp, err := conn.CreateXssMatchSet(params) + wr := newWafRetryer(conn, "global") + out, err := wr.RetryWithToken(func(token *string) (interface{}, error) { + params := &waf.CreateXssMatchSetInput{ + ChangeToken: token, + Name: aws.String(d.Get("name").(string)), + } + return conn.CreateXssMatchSet(params) + }) if err != nil { return errwrap.Wrapf("[ERROR] Error creating XssMatchSet: {{err}}", err) } + resp := out.(*waf.CreateXssMatchSetOutput) d.SetId(*resp.XssMatchSet.XssMatchSetId) @@ -126,17 +121,15 @@ func resourceAwsWafXssMatchSetDelete(d *schema.ResourceData, meta interface{}) e return errwrap.Wrapf("[ERROR] Error deleting XssMatchSet: {{err}}", err) } - var ct *waf.GetChangeTokenInput - - resp, err := conn.GetChangeToken(ct) - - req := &waf.DeleteXssMatchSetInput{ - ChangeToken: resp.ChangeToken, - XssMatchSetId: aws.String(d.Id()), - } - - _, err = conn.DeleteXssMatchSet(req) + wr := newWafRetryer(conn, "global") + _, err = wr.RetryWithToken(func(token *string) (interface{}, error) { + req := &waf.DeleteXssMatchSetInput{ + ChangeToken: token, + XssMatchSetId: aws.String(d.Id()), + } + return conn.DeleteXssMatchSet(req) + }) if err != nil { return errwrap.Wrapf("[ERROR] Error deleting XssMatchSet: {{err}}", err) } @@ -147,32 +140,28 @@ func resourceAwsWafXssMatchSetDelete(d *schema.ResourceData, meta interface{}) e func updateXssMatchSetResource(d *schema.ResourceData, meta interface{}, ChangeAction string) error { conn := meta.(*AWSClient).wafconn - var ct *waf.GetChangeTokenInput - - resp, err := conn.GetChangeToken(ct) - if err != nil { - return errwrap.Wrapf("[ERROR] Error getting change token: {{err}}", err) - } - - req := &waf.UpdateXssMatchSetInput{ - ChangeToken: resp.ChangeToken, - XssMatchSetId: aws.String(d.Id()), - } - - xssMatchTuples := d.Get("xss_match_tuples").(*schema.Set) - for _, xssMatchTuple := range xssMatchTuples.List() { - xmt := xssMatchTuple.(map[string]interface{}) - xssMatchTupleUpdate := &waf.XssMatchSetUpdate{ - Action: aws.String(ChangeAction), - XssMatchTuple: &waf.XssMatchTuple{ - FieldToMatch: expandFieldToMatch(xmt["field_to_match"].(*schema.Set).List()[0].(map[string]interface{})), - TextTransformation: aws.String(xmt["text_transformation"].(string)), - }, + wr := newWafRetryer(conn, "global") + _, err := wr.RetryWithToken(func(token *string) (interface{}, error) { + req := &waf.UpdateXssMatchSetInput{ + ChangeToken: token, + XssMatchSetId: aws.String(d.Id()), } - req.Updates = append(req.Updates, xssMatchTupleUpdate) - } - _, err = conn.UpdateXssMatchSet(req) + xssMatchTuples := d.Get("xss_match_tuples").(*schema.Set) + for _, xssMatchTuple := range xssMatchTuples.List() { + xmt := xssMatchTuple.(map[string]interface{}) + xssMatchTupleUpdate := &waf.XssMatchSetUpdate{ + Action: aws.String(ChangeAction), + XssMatchTuple: &waf.XssMatchTuple{ + FieldToMatch: expandFieldToMatch(xmt["field_to_match"].(*schema.Set).List()[0].(map[string]interface{})), + TextTransformation: aws.String(xmt["text_transformation"].(string)), + }, + } + req.Updates = append(req.Updates, xssMatchTupleUpdate) + } + + return conn.UpdateXssMatchSet(req) + }) if err != nil { return errwrap.Wrapf("[ERROR] Error updating XssMatchSet: {{err}}", err) } diff --git a/builtin/providers/aws/resource_aws_waf_xss_match_set_test.go b/builtin/providers/aws/resource_aws_waf_xss_match_set_test.go index 5128fc813..b2d223086 100644 --- a/builtin/providers/aws/resource_aws_waf_xss_match_set_test.go +++ b/builtin/providers/aws/resource_aws_waf_xss_match_set_test.go @@ -96,44 +96,38 @@ func testAccCheckAWSWafXssMatchSetDisappears(v *waf.XssMatchSet) resource.TestCh return func(s *terraform.State) error { conn := testAccProvider.Meta().(*AWSClient).wafconn - var ct *waf.GetChangeTokenInput - - resp, err := conn.GetChangeToken(ct) - if err != nil { - return fmt.Errorf("Error getting change token: %s", err) - } - - req := &waf.UpdateXssMatchSetInput{ - ChangeToken: resp.ChangeToken, - XssMatchSetId: v.XssMatchSetId, - } - - for _, xssMatchTuple := range v.XssMatchTuples { - xssMatchTupleUpdate := &waf.XssMatchSetUpdate{ - Action: aws.String("DELETE"), - XssMatchTuple: &waf.XssMatchTuple{ - FieldToMatch: xssMatchTuple.FieldToMatch, - TextTransformation: xssMatchTuple.TextTransformation, - }, + wr := newWafRetryer(conn, "global") + _, err := wr.RetryWithToken(func(token *string) (interface{}, error) { + req := &waf.UpdateXssMatchSetInput{ + ChangeToken: token, + XssMatchSetId: v.XssMatchSetId, } - req.Updates = append(req.Updates, xssMatchTupleUpdate) - } - _, err = conn.UpdateXssMatchSet(req) + + for _, xssMatchTuple := range v.XssMatchTuples { + xssMatchTupleUpdate := &waf.XssMatchSetUpdate{ + Action: aws.String("DELETE"), + XssMatchTuple: &waf.XssMatchTuple{ + FieldToMatch: xssMatchTuple.FieldToMatch, + TextTransformation: xssMatchTuple.TextTransformation, + }, + } + req.Updates = append(req.Updates, xssMatchTupleUpdate) + } + return conn.UpdateXssMatchSet(req) + }) if err != nil { return errwrap.Wrapf("[ERROR] Error updating XssMatchSet: {{err}}", err) } - resp, err = conn.GetChangeToken(ct) + _, err = wr.RetryWithToken(func(token *string) (interface{}, error) { + opts := &waf.DeleteXssMatchSetInput{ + ChangeToken: token, + XssMatchSetId: v.XssMatchSetId, + } + return conn.DeleteXssMatchSet(opts) + }) if err != nil { - return errwrap.Wrapf("[ERROR] Error getting change token: {{err}}", err) - } - - opts := &waf.DeleteXssMatchSetInput{ - ChangeToken: resp.ChangeToken, - XssMatchSetId: v.XssMatchSetId, - } - if _, err := conn.DeleteXssMatchSet(opts); err != nil { - return err + return errwrap.Wrapf("[ERROR] Error deleting XssMatchSet: {{err}}", err) } return nil } diff --git a/builtin/providers/aws/resource_aws_wafregional_byte_match_set.go b/builtin/providers/aws/resource_aws_wafregional_byte_match_set.go new file mode 100644 index 000000000..d7f916ad3 --- /dev/null +++ b/builtin/providers/aws/resource_aws_wafregional_byte_match_set.go @@ -0,0 +1,266 @@ +package aws + +import ( + "log" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/awserr" + "github.com/aws/aws-sdk-go/service/waf" + "github.com/aws/aws-sdk-go/service/wafregional" + "github.com/hashicorp/errwrap" + "github.com/hashicorp/terraform/helper/schema" +) + +func resourceAwsWafRegionalByteMatchSet() *schema.Resource { + return &schema.Resource{ + Create: resourceAwsWafRegionalByteMatchSetCreate, + Read: resourceAwsWafRegionalByteMatchSetRead, + Update: resourceAwsWafRegionalByteMatchSetUpdate, + Delete: resourceAwsWafRegionalByteMatchSetDelete, + + Schema: map[string]*schema.Schema{ + "name": &schema.Schema{ + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + "byte_match_tuple": &schema.Schema{ + Type: schema.TypeSet, + Optional: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "field_to_match": { + Type: schema.TypeSet, + Required: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "data": { + Type: schema.TypeString, + Optional: true, + }, + "type": { + Type: schema.TypeString, + Required: true, + }, + }, + }, + }, + "positional_constraint": &schema.Schema{ + Type: schema.TypeString, + Required: true, + }, + "target_string": &schema.Schema{ + Type: schema.TypeString, + Optional: true, + }, + "text_transformation": &schema.Schema{ + Type: schema.TypeString, + Required: true, + }, + }, + }, + }, + }, + } +} + +func resourceAwsWafRegionalByteMatchSetCreate(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*AWSClient).wafregionalconn + region := meta.(*AWSClient).region + + log.Printf("[INFO] Creating ByteMatchSet: %s", d.Get("name").(string)) + + wr := newWafRegionalRetryer(conn, region) + out, err := wr.RetryWithToken(func(token *string) (interface{}, error) { + params := &waf.CreateByteMatchSetInput{ + ChangeToken: token, + Name: aws.String(d.Get("name").(string)), + } + return conn.CreateByteMatchSet(params) + }) + + if err != nil { + return errwrap.Wrapf("[ERROR] Error creating ByteMatchSet: {{err}}", err) + } + resp := out.(*waf.CreateByteMatchSetOutput) + + d.SetId(*resp.ByteMatchSet.ByteMatchSetId) + + return resourceAwsWafRegionalByteMatchSetUpdate(d, meta) +} + +func resourceAwsWafRegionalByteMatchSetRead(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*AWSClient).wafregionalconn + + log.Printf("[INFO] Reading ByteMatchSet: %s", d.Get("name").(string)) + + params := &waf.GetByteMatchSetInput{ + ByteMatchSetId: aws.String(d.Id()), + } + + resp, err := conn.GetByteMatchSet(params) + if err != nil { + if awsErr, ok := err.(awserr.Error); ok && awsErr.Code() == "WAFNonexistentItemException" { + log.Printf("[WARN] WAF IPSet (%s) not found, error code (404)", d.Id()) + d.SetId("") + return nil + } + + return err + } + + d.Set("byte_match_tuple", flattenWafByteMatchTuplesWR(resp.ByteMatchSet.ByteMatchTuples)) + d.Set("name", resp.ByteMatchSet.Name) + + return nil +} + +func flattenWafByteMatchTuplesWR(in []*waf.ByteMatchTuple) []interface{} { + tuples := make([]interface{}, len(in), len(in)) + + for i, tuple := range in { + field_to_match := tuple.FieldToMatch + m := map[string]interface{}{ + "type": *field_to_match.Type, + } + + if field_to_match.Data == nil { + m["data"] = "" + } else { + m["data"] = *field_to_match.Data + } + + var ms []map[string]interface{} + ms = append(ms, m) + + tuple := map[string]interface{}{ + "field_to_match": ms, + "positional_constraint": *tuple.PositionalConstraint, + "target_string": tuple.TargetString, + "text_transformation": *tuple.TextTransformation, + } + tuples[i] = tuple + } + + return tuples +} + +func resourceAwsWafRegionalByteMatchSetUpdate(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*AWSClient).wafregionalconn + region := meta.(*AWSClient).region + log.Printf("[INFO] Updating ByteMatchSet: %s", d.Get("name").(string)) + + if d.HasChange("byte_match_tuple") { + o, n := d.GetChange("byte_match_tuple") + oldT, newT := o.(*schema.Set).List(), n.(*schema.Set).List() + + err := updateByteMatchSetResourceWR(d, oldT, newT, conn, region) + if err != nil { + return errwrap.Wrapf("[ERROR] Error updating ByteMatchSet: {{err}}", err) + } + } + return resourceAwsWafRegionalByteMatchSetRead(d, meta) +} + +func resourceAwsWafRegionalByteMatchSetDelete(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*AWSClient).wafregionalconn + region := meta.(*AWSClient).region + + log.Printf("[INFO] Deleting ByteMatchSet: %s", d.Get("name").(string)) + + oldT := d.Get("byte_match_tuple").(*schema.Set).List() + + if len(oldT) > 0 { + var newT []interface{} + + err := updateByteMatchSetResourceWR(d, oldT, newT, conn, region) + if err != nil { + return errwrap.Wrapf("[ERROR] Error deleting ByteMatchSet: {{err}}", err) + } + } + + wr := newWafRegionalRetryer(conn, region) + _, err := wr.RetryWithToken(func(token *string) (interface{}, error) { + req := &waf.DeleteByteMatchSetInput{ + ChangeToken: token, + ByteMatchSetId: aws.String(d.Id()), + } + return conn.DeleteByteMatchSet(req) + }) + if err != nil { + return errwrap.Wrapf("[ERROR] Error deleting ByteMatchSet: {{err}}", err) + } + + return nil +} + +func updateByteMatchSetResourceWR(d *schema.ResourceData, oldT, newT []interface{}, conn *wafregional.WAFRegional, region string) error { + wr := newWafRegionalRetryer(conn, region) + _, err := wr.RetryWithToken(func(token *string) (interface{}, error) { + req := &waf.UpdateByteMatchSetInput{ + ChangeToken: token, + ByteMatchSetId: aws.String(d.Id()), + Updates: diffByteMatchSetTuple(oldT, newT), + } + + return conn.UpdateByteMatchSet(req) + }) + if err != nil { + return errwrap.Wrapf("[ERROR] Error updating ByteMatchSet: {{err}}", err) + } + + return nil +} + +func expandFieldToMatchWR(d map[string]interface{}) *waf.FieldToMatch { + return &waf.FieldToMatch{ + Type: aws.String(d["type"].(string)), + Data: aws.String(d["data"].(string)), + } +} + +func flattenFieldToMatchWR(fm *waf.FieldToMatch) map[string]interface{} { + m := make(map[string]interface{}) + m["data"] = *fm.Data + m["type"] = *fm.Type + return m +} + +func diffByteMatchSetTuple(oldT, newT []interface{}) []*waf.ByteMatchSetUpdate { + updates := make([]*waf.ByteMatchSetUpdate, 0) + + for _, ot := range oldT { + tuple := ot.(map[string]interface{}) + + if idx, contains := sliceContainsMap(newT, tuple); contains { + newT = append(newT[:idx], newT[idx+1:]...) + continue + } + + updates = append(updates, &waf.ByteMatchSetUpdate{ + Action: aws.String(waf.ChangeActionDelete), + ByteMatchTuple: &waf.ByteMatchTuple{ + FieldToMatch: expandFieldToMatch(tuple["field_to_match"].(*schema.Set).List()[0].(map[string]interface{})), + PositionalConstraint: aws.String(tuple["positional_constraint"].(string)), + TargetString: []byte(tuple["target_string"].(string)), + TextTransformation: aws.String(tuple["text_transformation"].(string)), + }, + }) + } + + for _, nt := range newT { + tuple := nt.(map[string]interface{}) + + updates = append(updates, &waf.ByteMatchSetUpdate{ + Action: aws.String(waf.ChangeActionInsert), + ByteMatchTuple: &waf.ByteMatchTuple{ + FieldToMatch: expandFieldToMatch(tuple["field_to_match"].(*schema.Set).List()[0].(map[string]interface{})), + PositionalConstraint: aws.String(tuple["positional_constraint"].(string)), + TargetString: []byte(tuple["target_string"].(string)), + TextTransformation: aws.String(tuple["text_transformation"].(string)), + }, + }) + } + return updates +} diff --git a/builtin/providers/aws/resource_aws_wafregional_byte_match_set_test.go b/builtin/providers/aws/resource_aws_wafregional_byte_match_set_test.go new file mode 100644 index 000000000..2600349ae --- /dev/null +++ b/builtin/providers/aws/resource_aws_wafregional_byte_match_set_test.go @@ -0,0 +1,437 @@ +package aws + +import ( + "fmt" + "testing" + + "github.com/hashicorp/terraform/helper/resource" + "github.com/hashicorp/terraform/terraform" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/awserr" + "github.com/aws/aws-sdk-go/service/waf" + "github.com/hashicorp/errwrap" + "github.com/hashicorp/terraform/helper/acctest" +) + +func TestAccAWSWafRegionalByteMatchSet_basic(t *testing.T) { + var v waf.ByteMatchSet + byteMatchSet := fmt.Sprintf("byteMatchSet-%s", acctest.RandString(5)) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSWafRegionalByteMatchSetDestroy, + Steps: []resource.TestStep{ + resource.TestStep{ + Config: testAccAWSWafRegionalByteMatchSetConfig(byteMatchSet), + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSWafRegionalByteMatchSetExists("aws_wafregional_byte_match_set.byte_set", &v), + resource.TestCheckResourceAttr( + "aws_wafregional_byte_match_set.byte_set", "name", byteMatchSet), + resource.TestCheckResourceAttr( + "aws_wafregional_byte_match_set.byte_set", "byte_match_tuple.#", "2"), + resource.TestCheckResourceAttr( + "aws_wafregional_byte_match_set.byte_set", "byte_match_tuple.2174619346.field_to_match.2991901334.data", "referer"), + resource.TestCheckResourceAttr( + "aws_wafregional_byte_match_set.byte_set", "byte_match_tuple.2174619346.field_to_match.2991901334.type", "HEADER"), + resource.TestCheckResourceAttr( + "aws_wafregional_byte_match_set.byte_set", "byte_match_tuple.2174619346.positional_constraint", "CONTAINS"), + resource.TestCheckResourceAttr( + "aws_wafregional_byte_match_set.byte_set", "byte_match_tuple.2174619346.target_string", "badrefer1"), + resource.TestCheckResourceAttr( + "aws_wafregional_byte_match_set.byte_set", "byte_match_tuple.2174619346.text_transformation", "NONE"), + resource.TestCheckResourceAttr( + "aws_wafregional_byte_match_set.byte_set", "byte_match_tuple.839525137.field_to_match.2991901334.data", "referer"), + resource.TestCheckResourceAttr( + "aws_wafregional_byte_match_set.byte_set", "byte_match_tuple.839525137.field_to_match.2991901334.type", "HEADER"), + resource.TestCheckResourceAttr( + "aws_wafregional_byte_match_set.byte_set", "byte_match_tuple.839525137.positional_constraint", "CONTAINS"), + resource.TestCheckResourceAttr( + "aws_wafregional_byte_match_set.byte_set", "byte_match_tuple.839525137.target_string", "badrefer2"), + resource.TestCheckResourceAttr( + "aws_wafregional_byte_match_set.byte_set", "byte_match_tuple.839525137.text_transformation", "NONE"), + ), + }, + }, + }) +} + +func TestAccAWSWafRegionalByteMatchSet_changeNameForceNew(t *testing.T) { + var before, after waf.ByteMatchSet + byteMatchSet := fmt.Sprintf("byteMatchSet-%s", acctest.RandString(5)) + byteMatchSetNewName := fmt.Sprintf("byteMatchSet-%s", acctest.RandString(5)) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSWafRegionalByteMatchSetDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAWSWafRegionalByteMatchSetConfig(byteMatchSet), + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSWafRegionalByteMatchSetExists("aws_wafregional_byte_match_set.byte_set", &before), + resource.TestCheckResourceAttr( + "aws_wafregional_byte_match_set.byte_set", "name", byteMatchSet), + resource.TestCheckResourceAttr( + "aws_wafregional_byte_match_set.byte_set", "byte_match_tuple.#", "2"), + resource.TestCheckResourceAttr( + "aws_wafregional_byte_match_set.byte_set", "byte_match_tuple.2174619346.field_to_match.2991901334.data", "referer"), + resource.TestCheckResourceAttr( + "aws_wafregional_byte_match_set.byte_set", "byte_match_tuple.2174619346.field_to_match.2991901334.type", "HEADER"), + resource.TestCheckResourceAttr( + "aws_wafregional_byte_match_set.byte_set", "byte_match_tuple.2174619346.positional_constraint", "CONTAINS"), + resource.TestCheckResourceAttr( + "aws_wafregional_byte_match_set.byte_set", "byte_match_tuple.2174619346.target_string", "badrefer1"), + resource.TestCheckResourceAttr( + "aws_wafregional_byte_match_set.byte_set", "byte_match_tuple.2174619346.text_transformation", "NONE"), + resource.TestCheckResourceAttr( + "aws_wafregional_byte_match_set.byte_set", "byte_match_tuple.839525137.field_to_match.2991901334.data", "referer"), + resource.TestCheckResourceAttr( + "aws_wafregional_byte_match_set.byte_set", "byte_match_tuple.839525137.field_to_match.2991901334.type", "HEADER"), + resource.TestCheckResourceAttr( + "aws_wafregional_byte_match_set.byte_set", "byte_match_tuple.839525137.positional_constraint", "CONTAINS"), + resource.TestCheckResourceAttr( + "aws_wafregional_byte_match_set.byte_set", "byte_match_tuple.839525137.target_string", "badrefer2"), + resource.TestCheckResourceAttr( + "aws_wafregional_byte_match_set.byte_set", "byte_match_tuple.839525137.text_transformation", "NONE"), + ), + }, + { + Config: testAccAWSWafRegionalByteMatchSetConfigChangeName(byteMatchSetNewName), + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSWafRegionalByteMatchSetExists("aws_wafregional_byte_match_set.byte_set", &after), + resource.TestCheckResourceAttr( + "aws_wafregional_byte_match_set.byte_set", "name", byteMatchSetNewName), + resource.TestCheckResourceAttr( + "aws_wafregional_byte_match_set.byte_set", "byte_match_tuple.#", "2"), + resource.TestCheckResourceAttr( + "aws_wafregional_byte_match_set.byte_set", "byte_match_tuple.2174619346.field_to_match.2991901334.data", "referer"), + resource.TestCheckResourceAttr( + "aws_wafregional_byte_match_set.byte_set", "byte_match_tuple.2174619346.field_to_match.2991901334.type", "HEADER"), + resource.TestCheckResourceAttr( + "aws_wafregional_byte_match_set.byte_set", "byte_match_tuple.2174619346.positional_constraint", "CONTAINS"), + resource.TestCheckResourceAttr( + "aws_wafregional_byte_match_set.byte_set", "byte_match_tuple.2174619346.target_string", "badrefer1"), + resource.TestCheckResourceAttr( + "aws_wafregional_byte_match_set.byte_set", "byte_match_tuple.2174619346.text_transformation", "NONE"), + resource.TestCheckResourceAttr( + "aws_wafregional_byte_match_set.byte_set", "byte_match_tuple.839525137.field_to_match.2991901334.data", "referer"), + resource.TestCheckResourceAttr( + "aws_wafregional_byte_match_set.byte_set", "byte_match_tuple.839525137.field_to_match.2991901334.type", "HEADER"), + resource.TestCheckResourceAttr( + "aws_wafregional_byte_match_set.byte_set", "byte_match_tuple.839525137.positional_constraint", "CONTAINS"), + resource.TestCheckResourceAttr( + "aws_wafregional_byte_match_set.byte_set", "byte_match_tuple.839525137.target_string", "badrefer2"), + resource.TestCheckResourceAttr( + "aws_wafregional_byte_match_set.byte_set", "byte_match_tuple.839525137.text_transformation", "NONE"), + ), + }, + }, + }) +} + +func TestAccAWSWafRegionalByteMatchSet_changeByteMatchTuple(t *testing.T) { + var before, after waf.ByteMatchSet + byteMatchSetName := fmt.Sprintf("byte-batch-set-%s", acctest.RandString(5)) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSWafRegionalByteMatchSetDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAWSWafRegionalByteMatchSetConfig(byteMatchSetName), + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSWafRegionalByteMatchSetExists("aws_wafregional_byte_match_set.byte_set", &before), + resource.TestCheckResourceAttr( + "aws_wafregional_byte_match_set.byte_set", "name", byteMatchSetName), + resource.TestCheckResourceAttr( + "aws_wafregional_byte_match_set.byte_set", "byte_match_tuple.#", "2"), + resource.TestCheckResourceAttr( + "aws_wafregional_byte_match_set.byte_set", "byte_match_tuple.2174619346.field_to_match.2991901334.data", "referer"), + resource.TestCheckResourceAttr( + "aws_wafregional_byte_match_set.byte_set", "byte_match_tuple.2174619346.field_to_match.2991901334.type", "HEADER"), + resource.TestCheckResourceAttr( + "aws_wafregional_byte_match_set.byte_set", "byte_match_tuple.2174619346.positional_constraint", "CONTAINS"), + resource.TestCheckResourceAttr( + "aws_wafregional_byte_match_set.byte_set", "byte_match_tuple.2174619346.target_string", "badrefer1"), + resource.TestCheckResourceAttr( + "aws_wafregional_byte_match_set.byte_set", "byte_match_tuple.2174619346.text_transformation", "NONE"), + resource.TestCheckResourceAttr( + "aws_wafregional_byte_match_set.byte_set", "byte_match_tuple.839525137.field_to_match.2991901334.data", "referer"), + resource.TestCheckResourceAttr( + "aws_wafregional_byte_match_set.byte_set", "byte_match_tuple.839525137.field_to_match.2991901334.type", "HEADER"), + resource.TestCheckResourceAttr( + "aws_wafregional_byte_match_set.byte_set", "byte_match_tuple.839525137.positional_constraint", "CONTAINS"), + resource.TestCheckResourceAttr( + "aws_wafregional_byte_match_set.byte_set", "byte_match_tuple.839525137.target_string", "badrefer2"), + resource.TestCheckResourceAttr( + "aws_wafregional_byte_match_set.byte_set", "byte_match_tuple.839525137.text_transformation", "NONE"), + ), + }, + { + Config: testAccAWSWafRegionalByteMatchSetConfigChangeByteMatchTuple(byteMatchSetName), + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSWafRegionalByteMatchSetExists("aws_wafregional_byte_match_set.byte_set", &after), + resource.TestCheckResourceAttr( + "aws_wafregional_byte_match_set.byte_set", "name", byteMatchSetName), + resource.TestCheckResourceAttr( + "aws_wafregional_byte_match_set.byte_set", "byte_match_tuple.#", "2"), + resource.TestCheckResourceAttr( + "aws_wafregional_byte_match_set.byte_set", "byte_match_tuple.2397850647.field_to_match.4253810390.data", "GET"), + resource.TestCheckResourceAttr( + "aws_wafregional_byte_match_set.byte_set", "byte_match_tuple.2397850647.field_to_match.4253810390.type", "METHOD"), + resource.TestCheckResourceAttr( + "aws_wafregional_byte_match_set.byte_set", "byte_match_tuple.2397850647.positional_constraint", "STARTS_WITH"), + resource.TestCheckResourceAttr( + "aws_wafregional_byte_match_set.byte_set", "byte_match_tuple.2397850647.target_string", "badrefer1+"), + resource.TestCheckResourceAttr( + "aws_wafregional_byte_match_set.byte_set", "byte_match_tuple.2397850647.text_transformation", "LOWERCASE"), + resource.TestCheckResourceAttr( + "aws_wafregional_byte_match_set.byte_set", "byte_match_tuple.4153613423.field_to_match.3756326843.data", ""), + resource.TestCheckResourceAttr( + "aws_wafregional_byte_match_set.byte_set", "byte_match_tuple.4153613423.field_to_match.3756326843.type", "URI"), + resource.TestCheckResourceAttr( + "aws_wafregional_byte_match_set.byte_set", "byte_match_tuple.4153613423.positional_constraint", "ENDS_WITH"), + resource.TestCheckResourceAttr( + "aws_wafregional_byte_match_set.byte_set", "byte_match_tuple.4153613423.target_string", "badrefer2+"), + resource.TestCheckResourceAttr( + "aws_wafregional_byte_match_set.byte_set", "byte_match_tuple.4153613423.text_transformation", "LOWERCASE"), + ), + }, + }, + }) +} + +func TestAccAWSWafRegionalByteMatchSet_noByteMatchTuples(t *testing.T) { + var byteMatchSet waf.ByteMatchSet + byteMatchSetName := fmt.Sprintf("byte-batch-set-%s", acctest.RandString(5)) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSWafRegionalByteMatchSetDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAWSWafRegionalByteMatchSetConfig_noDescriptors(byteMatchSetName), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckAWSWafRegionalByteMatchSetExists("aws_wafregional_byte_match_set.byte_match_set", &byteMatchSet), + resource.TestCheckResourceAttr("aws_wafregional_byte_match_set.byte_match_set", "name", byteMatchSetName), + resource.TestCheckResourceAttr("aws_wafregional_byte_match_set.byte_match_set", "byte_match_tuple.#", "0"), + ), + }, + }, + }) +} + +func TestAccAWSWafRegionalByteMatchSet_disappears(t *testing.T) { + var v waf.ByteMatchSet + byteMatchSet := fmt.Sprintf("byteMatchSet-%s", acctest.RandString(5)) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSWafRegionalByteMatchSetDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAWSWafRegionalByteMatchSetConfig(byteMatchSet), + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSWafRegionalByteMatchSetExists("aws_wafregional_byte_match_set.byte_set", &v), + testAccCheckAWSWafRegionalByteMatchSetDisappears(&v), + ), + ExpectNonEmptyPlan: true, + }, + }, + }) +} + +func testAccCheckAWSWafRegionalByteMatchSetDisappears(v *waf.ByteMatchSet) resource.TestCheckFunc { + return func(s *terraform.State) error { + conn := testAccProvider.Meta().(*AWSClient).wafregionalconn + region := testAccProvider.Meta().(*AWSClient).region + + wr := newWafRegionalRetryer(conn, region) + _, err := wr.RetryWithToken(func(token *string) (interface{}, error) { + req := &waf.UpdateByteMatchSetInput{ + ChangeToken: token, + ByteMatchSetId: v.ByteMatchSetId, + } + + for _, ByteMatchTuple := range v.ByteMatchTuples { + ByteMatchUpdate := &waf.ByteMatchSetUpdate{ + Action: aws.String("DELETE"), + ByteMatchTuple: &waf.ByteMatchTuple{ + FieldToMatch: ByteMatchTuple.FieldToMatch, + PositionalConstraint: ByteMatchTuple.PositionalConstraint, + TargetString: ByteMatchTuple.TargetString, + TextTransformation: ByteMatchTuple.TextTransformation, + }, + } + req.Updates = append(req.Updates, ByteMatchUpdate) + } + + return conn.UpdateByteMatchSet(req) + }) + if err != nil { + return errwrap.Wrapf("[ERROR] Error updating ByteMatchSet: {{err}}", err) + } + + _, err = wr.RetryWithToken(func(token *string) (interface{}, error) { + opts := &waf.DeleteByteMatchSetInput{ + ChangeToken: token, + ByteMatchSetId: v.ByteMatchSetId, + } + return conn.DeleteByteMatchSet(opts) + }) + if err != nil { + return errwrap.Wrapf("[ERROR] Error deleting ByteMatchSet: {{err}}", err) + } + + return nil + } +} + +func testAccCheckAWSWafRegionalByteMatchSetExists(n string, v *waf.ByteMatchSet) resource.TestCheckFunc { + return func(s *terraform.State) error { + rs, ok := s.RootModule().Resources[n] + if !ok { + return fmt.Errorf("Not found: %s", n) + } + + if rs.Primary.ID == "" { + return fmt.Errorf("No WAF ByteMatchSet ID is set") + } + + conn := testAccProvider.Meta().(*AWSClient).wafregionalconn + resp, err := conn.GetByteMatchSet(&waf.GetByteMatchSetInput{ + ByteMatchSetId: aws.String(rs.Primary.ID), + }) + + if err != nil { + return err + } + + if *resp.ByteMatchSet.ByteMatchSetId == rs.Primary.ID { + *v = *resp.ByteMatchSet + return nil + } + + return fmt.Errorf("WAF ByteMatchSet (%s) not found", rs.Primary.ID) + } +} + +func testAccCheckAWSWafRegionalByteMatchSetDestroy(s *terraform.State) error { + for _, rs := range s.RootModule().Resources { + if rs.Type != "aws_wafregional_byte_match_set" { + continue + } + + conn := testAccProvider.Meta().(*AWSClient).wafregionalconn + resp, err := conn.GetByteMatchSet( + &waf.GetByteMatchSetInput{ + ByteMatchSetId: aws.String(rs.Primary.ID), + }) + + if err == nil { + if *resp.ByteMatchSet.ByteMatchSetId == rs.Primary.ID { + return fmt.Errorf("WAF ByteMatchSet %s still exists", rs.Primary.ID) + } + } + + // Return nil if the ByteMatchSet is already destroyed + if awsErr, ok := err.(awserr.Error); ok { + if awsErr.Code() == "WAFNonexistentItemException" { + return nil + } + } + + return err + } + + return nil +} + +func testAccAWSWafRegionalByteMatchSetConfig(name string) string { + return fmt.Sprintf(` +resource "aws_wafregional_byte_match_set" "byte_set" { + name = "%s" + byte_match_tuple { + text_transformation = "NONE" + target_string = "badrefer1" + positional_constraint = "CONTAINS" + field_to_match { + type = "HEADER" + data = "referer" + } + } + + byte_match_tuple { + text_transformation = "NONE" + target_string = "badrefer2" + positional_constraint = "CONTAINS" + field_to_match { + type = "HEADER" + data = "referer" + } + } +}`, name) +} + +func testAccAWSWafRegionalByteMatchSetConfigChangeName(name string) string { + return fmt.Sprintf(` +resource "aws_wafregional_byte_match_set" "byte_set" { + name = "%s" + byte_match_tuple { + text_transformation = "NONE" + target_string = "badrefer1" + positional_constraint = "CONTAINS" + field_to_match { + type = "HEADER" + data = "referer" + } + } + + byte_match_tuple { + text_transformation = "NONE" + target_string = "badrefer2" + positional_constraint = "CONTAINS" + field_to_match { + type = "HEADER" + data = "referer" + } + } +}`, name) +} + +func testAccAWSWafRegionalByteMatchSetConfig_noDescriptors(name string) string { + return fmt.Sprintf(` +resource "aws_wafregional_byte_match_set" "byte_match_set" { + name = "%s" +}`, name) +} + +func testAccAWSWafRegionalByteMatchSetConfigChangeByteMatchTuple(name string) string { + return fmt.Sprintf(` +resource "aws_wafregional_byte_match_set" "byte_set" { + name = "%s" + byte_match_tuple { + text_transformation = "LOWERCASE" + target_string = "badrefer1+" + positional_constraint = "STARTS_WITH" + field_to_match { + type = "METHOD" + data = "GET" + } + } + + byte_match_tuple { + text_transformation = "LOWERCASE" + target_string = "badrefer2+" + positional_constraint = "ENDS_WITH" + field_to_match { + type = "URI" + } + } +}`, name) +} diff --git a/builtin/providers/aws/resource_aws_wafregional_ipset.go b/builtin/providers/aws/resource_aws_wafregional_ipset.go new file mode 100644 index 000000000..0507621ee --- /dev/null +++ b/builtin/providers/aws/resource_aws_wafregional_ipset.go @@ -0,0 +1,170 @@ +package aws + +import ( + "fmt" + "log" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/awserr" + "github.com/aws/aws-sdk-go/service/waf" + "github.com/aws/aws-sdk-go/service/wafregional" + "github.com/hashicorp/terraform/helper/schema" +) + +func resourceAwsWafRegionalIPSet() *schema.Resource { + return &schema.Resource{ + Create: resourceAwsWafRegionalIPSetCreate, + Read: resourceAwsWafRegionalIPSetRead, + Update: resourceAwsWafRegionalIPSetUpdate, + Delete: resourceAwsWafRegionalIPSetDelete, + + Schema: map[string]*schema.Schema{ + "name": &schema.Schema{ + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + "ip_set_descriptor": &schema.Schema{ + Type: schema.TypeSet, + Optional: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "type": &schema.Schema{ + Type: schema.TypeString, + Required: true, + }, + "value": &schema.Schema{ + Type: schema.TypeString, + Required: true, + }, + }, + }, + }, + }, + } +} + +func resourceAwsWafRegionalIPSetCreate(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*AWSClient).wafregionalconn + region := meta.(*AWSClient).region + + wr := newWafRegionalRetryer(conn, region) + out, err := wr.RetryWithToken(func(token *string) (interface{}, error) { + params := &waf.CreateIPSetInput{ + ChangeToken: token, + Name: aws.String(d.Get("name").(string)), + } + return conn.CreateIPSet(params) + }) + if err != nil { + return err + } + resp := out.(*waf.CreateIPSetOutput) + d.SetId(*resp.IPSet.IPSetId) + return resourceAwsWafRegionalIPSetUpdate(d, meta) +} + +func resourceAwsWafRegionalIPSetRead(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*AWSClient).wafregionalconn + + params := &waf.GetIPSetInput{ + IPSetId: aws.String(d.Id()), + } + + resp, err := conn.GetIPSet(params) + if err != nil { + if awsErr, ok := err.(awserr.Error); ok && awsErr.Code() == "WAFNonexistentItemException" { + log.Printf("[WARN] WAF IPSet (%s) not found, error code (404)", d.Id()) + d.SetId("") + return nil + } + + return err + } + + d.Set("ip_set_descriptor", flattenWafIpSetDescriptorWR(resp.IPSet.IPSetDescriptors)) + d.Set("name", resp.IPSet.Name) + + return nil +} + +func flattenWafIpSetDescriptorWR(in []*waf.IPSetDescriptor) []interface{} { + descriptors := make([]interface{}, len(in), len(in)) + + for i, descriptor := range in { + d := map[string]interface{}{ + "type": *descriptor.Type, + "value": *descriptor.Value, + } + descriptors[i] = d + } + + return descriptors +} + +func resourceAwsWafRegionalIPSetUpdate(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*AWSClient).wafregionalconn + region := meta.(*AWSClient).region + + if d.HasChange("ip_set_descriptor") { + o, n := d.GetChange("ip_set_descriptor") + oldD, newD := o.(*schema.Set).List(), n.(*schema.Set).List() + + err := updateIPSetResourceWR(d.Id(), oldD, newD, conn, region) + if err != nil { + return fmt.Errorf("Error Updating WAF IPSet: %s", err) + } + } + return resourceAwsWafRegionalIPSetRead(d, meta) +} + +func resourceAwsWafRegionalIPSetDelete(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*AWSClient).wafregionalconn + region := meta.(*AWSClient).region + + oldD := d.Get("ip_set_descriptor").(*schema.Set).List() + + if len(oldD) > 0 { + noD := []interface{}{} + err := updateIPSetResourceWR(d.Id(), oldD, noD, conn, region) + + if err != nil { + return fmt.Errorf("Error Removing IPSetDescriptors: %s", err) + } + } + + wr := newWafRegionalRetryer(conn, region) + _, err := wr.RetryWithToken(func(token *string) (interface{}, error) { + req := &waf.DeleteIPSetInput{ + ChangeToken: token, + IPSetId: aws.String(d.Id()), + } + log.Printf("[INFO] Deleting WAF IPSet") + return conn.DeleteIPSet(req) + }) + if err != nil { + return fmt.Errorf("Error Deleting WAF IPSet: %s", err) + } + + return nil +} + +func updateIPSetResourceWR(id string, oldD, newD []interface{}, conn *wafregional.WAFRegional, region string) error { + + wr := newWafRegionalRetryer(conn, region) + _, err := wr.RetryWithToken(func(token *string) (interface{}, error) { + req := &waf.UpdateIPSetInput{ + ChangeToken: token, + IPSetId: aws.String(id), + Updates: diffWafIpSetDescriptors(oldD, newD), + } + log.Printf("[INFO] Updating IPSet descriptor: %s", req) + + return conn.UpdateIPSet(req) + }) + if err != nil { + return fmt.Errorf("Error Updating WAF IPSet: %s", err) + } + + return nil +} diff --git a/builtin/providers/aws/resource_aws_wafregional_ipset_test.go b/builtin/providers/aws/resource_aws_wafregional_ipset_test.go new file mode 100644 index 000000000..3aa251d43 --- /dev/null +++ b/builtin/providers/aws/resource_aws_wafregional_ipset_test.go @@ -0,0 +1,402 @@ +package aws + +import ( + "fmt" + "reflect" + "testing" + + "github.com/hashicorp/terraform/helper/resource" + "github.com/hashicorp/terraform/terraform" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/awserr" + "github.com/aws/aws-sdk-go/service/waf" + "github.com/aws/aws-sdk-go/service/wafregional" + "github.com/hashicorp/terraform/helper/acctest" +) + +func TestAccAWSWafRegionalIPSet_basic(t *testing.T) { + var v waf.IPSet + ipsetName := fmt.Sprintf("ip-set-%s", acctest.RandString(5)) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSWafRegionalIPSetDestroy, + Steps: []resource.TestStep{ + resource.TestStep{ + Config: testAccAWSWafRegionalIPSetConfig(ipsetName), + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSWafRegionalIPSetExists("aws_wafregional_ipset.ipset", &v), + resource.TestCheckResourceAttr( + "aws_wafregional_ipset.ipset", "name", ipsetName), + resource.TestCheckResourceAttr( + "aws_wafregional_ipset.ipset", "ip_set_descriptor.4037960608.type", "IPV4"), + resource.TestCheckResourceAttr( + "aws_wafregional_ipset.ipset", "ip_set_descriptor.4037960608.value", "192.0.7.0/24"), + ), + }, + }, + }) +} + +func TestAccAWSWafRegionalIPSet_disappears(t *testing.T) { + var v waf.IPSet + ipsetName := fmt.Sprintf("ip-set-%s", acctest.RandString(5)) + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSWafRegionalIPSetDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAWSWafRegionalIPSetConfig(ipsetName), + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSWafRegionalIPSetExists("aws_wafregional_ipset.ipset", &v), + testAccCheckAWSWafRegionalIPSetDisappears(&v), + ), + ExpectNonEmptyPlan: true, + }, + }, + }) +} + +func TestAccAWSWafRegionalIPSet_changeNameForceNew(t *testing.T) { + var before, after waf.IPSet + ipsetName := fmt.Sprintf("ip-set-%s", acctest.RandString(5)) + ipsetNewName := fmt.Sprintf("ip-set-new-%s", acctest.RandString(5)) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSWafRegionalIPSetDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAWSWafRegionalIPSetConfig(ipsetName), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckAWSWafRegionalIPSetExists("aws_wafregional_ipset.ipset", &before), + resource.TestCheckResourceAttr( + "aws_wafregional_ipset.ipset", "name", ipsetName), + resource.TestCheckResourceAttr( + "aws_wafregional_ipset.ipset", "ip_set_descriptor.4037960608.type", "IPV4"), + resource.TestCheckResourceAttr( + "aws_wafregional_ipset.ipset", "ip_set_descriptor.4037960608.value", "192.0.7.0/24"), + ), + }, + { + Config: testAccAWSWafRegionalIPSetConfigChangeName(ipsetNewName), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckAWSWafRegionalIPSetExists("aws_wafregional_ipset.ipset", &after), + resource.TestCheckResourceAttr( + "aws_wafregional_ipset.ipset", "name", ipsetNewName), + resource.TestCheckResourceAttr( + "aws_wafregional_ipset.ipset", "ip_set_descriptor.4037960608.type", "IPV4"), + resource.TestCheckResourceAttr( + "aws_wafregional_ipset.ipset", "ip_set_descriptor.4037960608.value", "192.0.7.0/24"), + ), + }, + }, + }) +} + +func TestAccAWSWafRegionalIPSet_changeDescriptors(t *testing.T) { + var before, after waf.IPSet + ipsetName := fmt.Sprintf("ip-set-%s", acctest.RandString(5)) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSWafRegionalIPSetDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAWSWafRegionalIPSetConfig(ipsetName), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckAWSWafRegionalIPSetExists("aws_wafregional_ipset.ipset", &before), + resource.TestCheckResourceAttr( + "aws_wafregional_ipset.ipset", "name", ipsetName), + resource.TestCheckResourceAttr( + "aws_wafregional_ipset.ipset", "ip_set_descriptor.#", "1"), + resource.TestCheckResourceAttr( + "aws_wafregional_ipset.ipset", "ip_set_descriptor.4037960608.type", "IPV4"), + resource.TestCheckResourceAttr( + "aws_wafregional_ipset.ipset", "ip_set_descriptor.4037960608.value", "192.0.7.0/24"), + ), + }, + { + Config: testAccAWSWafRegionalIPSetConfigChangeIPSetDescriptors(ipsetName), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckAWSWafRegionalIPSetExists("aws_wafregional_ipset.ipset", &after), + resource.TestCheckResourceAttr( + "aws_wafregional_ipset.ipset", "name", ipsetName), + resource.TestCheckResourceAttr( + "aws_wafregional_ipset.ipset", "ip_set_descriptor.#", "1"), + resource.TestCheckResourceAttr( + "aws_wafregional_ipset.ipset", "ip_set_descriptor.115741513.type", "IPV4"), + resource.TestCheckResourceAttr( + "aws_wafregional_ipset.ipset", "ip_set_descriptor.115741513.value", "192.0.8.0/24"), + ), + }, + }, + }) +} + +func TestAccAWSWafRegionalIPSet_noDescriptors(t *testing.T) { + var ipset waf.IPSet + ipsetName := fmt.Sprintf("ip-set-%s", acctest.RandString(5)) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSWafRegionalIPSetDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAWSWafRegionalIPSetConfig_noDescriptors(ipsetName), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckAWSWafRegionalIPSetExists("aws_wafregional_ipset.ipset", &ipset), + resource.TestCheckResourceAttr( + "aws_wafregional_ipset.ipset", "name", ipsetName), + resource.TestCheckResourceAttr( + "aws_wafregional_ipset.ipset", "ip_set_descriptor.#", "0"), + ), + }, + }, + }) +} + +func TestDiffWafRegionalIpSetDescriptors(t *testing.T) { + testCases := []struct { + Old []interface{} + New []interface{} + ExpectedUpdates []*waf.IPSetUpdate + }{ + { + // Change + Old: []interface{}{ + map[string]interface{}{"type": "IPV4", "value": "192.0.7.0/24"}, + }, + New: []interface{}{ + map[string]interface{}{"type": "IPV4", "value": "192.0.8.0/24"}, + }, + ExpectedUpdates: []*waf.IPSetUpdate{ + &waf.IPSetUpdate{ + Action: aws.String(wafregional.ChangeActionDelete), + IPSetDescriptor: &waf.IPSetDescriptor{ + Type: aws.String("IPV4"), + Value: aws.String("192.0.7.0/24"), + }, + }, + &waf.IPSetUpdate{ + Action: aws.String(wafregional.ChangeActionInsert), + IPSetDescriptor: &waf.IPSetDescriptor{ + Type: aws.String("IPV4"), + Value: aws.String("192.0.8.0/24"), + }, + }, + }, + }, + { + // Fresh IPSet + Old: []interface{}{}, + New: []interface{}{ + map[string]interface{}{"type": "IPV4", "value": "10.0.1.0/24"}, + map[string]interface{}{"type": "IPV4", "value": "10.0.2.0/24"}, + map[string]interface{}{"type": "IPV4", "value": "10.0.3.0/24"}, + }, + ExpectedUpdates: []*waf.IPSetUpdate{ + &waf.IPSetUpdate{ + Action: aws.String(wafregional.ChangeActionInsert), + IPSetDescriptor: &waf.IPSetDescriptor{ + Type: aws.String("IPV4"), + Value: aws.String("10.0.1.0/24"), + }, + }, + &waf.IPSetUpdate{ + Action: aws.String(wafregional.ChangeActionInsert), + IPSetDescriptor: &waf.IPSetDescriptor{ + Type: aws.String("IPV4"), + Value: aws.String("10.0.2.0/24"), + }, + }, + &waf.IPSetUpdate{ + Action: aws.String(wafregional.ChangeActionInsert), + IPSetDescriptor: &waf.IPSetDescriptor{ + Type: aws.String("IPV4"), + Value: aws.String("10.0.3.0/24"), + }, + }, + }, + }, + { + // Deletion + Old: []interface{}{ + map[string]interface{}{"type": "IPV4", "value": "192.0.7.0/24"}, + map[string]interface{}{"type": "IPV4", "value": "192.0.8.0/24"}, + }, + New: []interface{}{}, + ExpectedUpdates: []*waf.IPSetUpdate{ + &waf.IPSetUpdate{ + Action: aws.String(wafregional.ChangeActionDelete), + IPSetDescriptor: &waf.IPSetDescriptor{ + Type: aws.String("IPV4"), + Value: aws.String("192.0.7.0/24"), + }, + }, + &waf.IPSetUpdate{ + Action: aws.String(wafregional.ChangeActionDelete), + IPSetDescriptor: &waf.IPSetDescriptor{ + Type: aws.String("IPV4"), + Value: aws.String("192.0.8.0/24"), + }, + }, + }, + }, + } + for i, tc := range testCases { + t.Run(fmt.Sprintf("%d", i), func(t *testing.T) { + updates := diffWafIpSetDescriptors(tc.Old, tc.New) + if !reflect.DeepEqual(updates, tc.ExpectedUpdates) { + t.Fatalf("IPSet updates don't match.\nGiven: %s\nExpected: %s", + updates, tc.ExpectedUpdates) + } + }) + } +} + +func testAccCheckAWSWafRegionalIPSetDisappears(v *waf.IPSet) resource.TestCheckFunc { + return func(s *terraform.State) error { + conn := testAccProvider.Meta().(*AWSClient).wafregionalconn + region := testAccProvider.Meta().(*AWSClient).region + + wr := newWafRegionalRetryer(conn, region) + _, err := wr.RetryWithToken(func(token *string) (interface{}, error) { + req := &waf.UpdateIPSetInput{ + ChangeToken: token, + IPSetId: v.IPSetId, + } + + for _, IPSetDescriptor := range v.IPSetDescriptors { + IPSetUpdate := &waf.IPSetUpdate{ + Action: aws.String("DELETE"), + IPSetDescriptor: &waf.IPSetDescriptor{ + Type: IPSetDescriptor.Type, + Value: IPSetDescriptor.Value, + }, + } + req.Updates = append(req.Updates, IPSetUpdate) + } + + return conn.UpdateIPSet(req) + }) + if err != nil { + return fmt.Errorf("Error Updating WAF IPSet: %s", err) + } + + _, err = wr.RetryWithToken(func(token *string) (interface{}, error) { + opts := &waf.DeleteIPSetInput{ + ChangeToken: token, + IPSetId: v.IPSetId, + } + return conn.DeleteIPSet(opts) + }) + if err != nil { + return fmt.Errorf("Error Deleting WAF IPSet: %s", err) + } + return nil + } +} + +func testAccCheckAWSWafRegionalIPSetDestroy(s *terraform.State) error { + for _, rs := range s.RootModule().Resources { + if rs.Type != "aws_wafregional_ipset" { + continue + } + + conn := testAccProvider.Meta().(*AWSClient).wafregionalconn + resp, err := conn.GetIPSet( + &waf.GetIPSetInput{ + IPSetId: aws.String(rs.Primary.ID), + }) + + if err == nil { + if *resp.IPSet.IPSetId == rs.Primary.ID { + return fmt.Errorf("WAF IPSet %s still exists", rs.Primary.ID) + } + } + + // Return nil if the IPSet is already destroyed + if awsErr, ok := err.(awserr.Error); ok { + if awsErr.Code() == "WAFNonexistentItemException" { + return nil + } + } + + return err + } + + return nil +} + +func testAccCheckAWSWafRegionalIPSetExists(n string, v *waf.IPSet) resource.TestCheckFunc { + return func(s *terraform.State) error { + rs, ok := s.RootModule().Resources[n] + if !ok { + return fmt.Errorf("Not found: %s", n) + } + + if rs.Primary.ID == "" { + return fmt.Errorf("No WAF IPSet ID is set") + } + + conn := testAccProvider.Meta().(*AWSClient).wafregionalconn + resp, err := conn.GetIPSet(&waf.GetIPSetInput{ + IPSetId: aws.String(rs.Primary.ID), + }) + + if err != nil { + return err + } + + if *resp.IPSet.IPSetId == rs.Primary.ID { + *v = *resp.IPSet + return nil + } + + return fmt.Errorf("WAF IPSet (%s) not found", rs.Primary.ID) + } +} + +func testAccAWSWafRegionalIPSetConfig(name string) string { + return fmt.Sprintf(` +resource "aws_wafregional_ipset" "ipset" { + name = "%s" + ip_set_descriptor { + type = "IPV4" + value = "192.0.7.0/24" + } +}`, name) +} + +func testAccAWSWafRegionalIPSetConfigChangeName(name string) string { + return fmt.Sprintf(`resource "aws_wafregional_ipset" "ipset" { + name = "%s" + ip_set_descriptor { + type = "IPV4" + value = "192.0.7.0/24" + } +}`, name) +} + +func testAccAWSWafRegionalIPSetConfigChangeIPSetDescriptors(name string) string { + return fmt.Sprintf(`resource "aws_wafregional_ipset" "ipset" { + name = "%s" + ip_set_descriptor { + type = "IPV4" + value = "192.0.8.0/24" + } +}`, name) +} + +func testAccAWSWafRegionalIPSetConfig_noDescriptors(name string) string { + return fmt.Sprintf(`resource "aws_wafregional_ipset" "ipset" { + name = "%s" + }`, name) +} diff --git a/builtin/providers/aws/resource_vpn_connection_route_test.go b/builtin/providers/aws/resource_vpn_connection_route_test.go index 24e048003..23229b0f9 100644 --- a/builtin/providers/aws/resource_vpn_connection_route_test.go +++ b/builtin/providers/aws/resource_vpn_connection_route_test.go @@ -8,18 +8,20 @@ import ( "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/service/ec2" + "github.com/hashicorp/terraform/helper/acctest" "github.com/hashicorp/terraform/helper/resource" "github.com/hashicorp/terraform/terraform" ) func TestAccAWSVpnConnectionRoute_basic(t *testing.T) { + rBgpAsn := acctest.RandIntRange(64512, 65534) resource.Test(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, CheckDestroy: testAccAwsVpnConnectionRouteDestroy, Steps: []resource.TestStep{ resource.TestStep{ - Config: testAccAwsVpnConnectionRouteConfig, + Config: testAccAwsVpnConnectionRouteConfig(rBgpAsn), Check: resource.ComposeTestCheckFunc( testAccAwsVpnConnectionRoute( "aws_vpn_gateway.vpn_gateway", @@ -30,7 +32,7 @@ func TestAccAWSVpnConnectionRoute_basic(t *testing.T) { ), }, resource.TestStep{ - Config: testAccAwsVpnConnectionRouteConfigUpdate, + Config: testAccAwsVpnConnectionRouteConfigUpdate(rBgpAsn), Check: resource.ComposeTestCheckFunc( testAccAwsVpnConnectionRoute( "aws_vpn_gateway.vpn_gateway", @@ -143,55 +145,59 @@ func testAccAwsVpnConnectionRoute( } } -const testAccAwsVpnConnectionRouteConfig = ` -resource "aws_vpn_gateway" "vpn_gateway" { - tags { - Name = "vpn_gateway" +func testAccAwsVpnConnectionRouteConfig(rBgpAsn int) string { + return fmt.Sprintf(` + resource "aws_vpn_gateway" "vpn_gateway" { + tags { + Name = "vpn_gateway" + } } -} -resource "aws_customer_gateway" "customer_gateway" { - bgp_asn = 65000 - ip_address = "182.0.0.1" - type = "ipsec.1" -} + resource "aws_customer_gateway" "customer_gateway" { + bgp_asn = %d + ip_address = "182.0.0.1" + type = "ipsec.1" + } -resource "aws_vpn_connection" "vpn_connection" { - vpn_gateway_id = "${aws_vpn_gateway.vpn_gateway.id}" - customer_gateway_id = "${aws_customer_gateway.customer_gateway.id}" - type = "ipsec.1" - static_routes_only = true -} + resource "aws_vpn_connection" "vpn_connection" { + vpn_gateway_id = "${aws_vpn_gateway.vpn_gateway.id}" + customer_gateway_id = "${aws_customer_gateway.customer_gateway.id}" + type = "ipsec.1" + static_routes_only = true + } -resource "aws_vpn_connection_route" "foo" { - destination_cidr_block = "172.168.10.0/24" - vpn_connection_id = "${aws_vpn_connection.vpn_connection.id}" + resource "aws_vpn_connection_route" "foo" { + destination_cidr_block = "172.168.10.0/24" + vpn_connection_id = "${aws_vpn_connection.vpn_connection.id}" + } + `, rBgpAsn) } -` // Change destination_cidr_block -const testAccAwsVpnConnectionRouteConfigUpdate = ` -resource "aws_vpn_gateway" "vpn_gateway" { - tags { - Name = "vpn_gateway" +func testAccAwsVpnConnectionRouteConfigUpdate(rBgpAsn int) string { + return fmt.Sprintf(` + resource "aws_vpn_gateway" "vpn_gateway" { + tags { + Name = "vpn_gateway" + } } -} -resource "aws_customer_gateway" "customer_gateway" { - bgp_asn = 65000 - ip_address = "182.0.0.1" - type = "ipsec.1" -} + resource "aws_customer_gateway" "customer_gateway" { + bgp_asn = %d + ip_address = "182.0.0.1" + type = "ipsec.1" + } -resource "aws_vpn_connection" "vpn_connection" { - vpn_gateway_id = "${aws_vpn_gateway.vpn_gateway.id}" - customer_gateway_id = "${aws_customer_gateway.customer_gateway.id}" - type = "ipsec.1" - static_routes_only = true -} + resource "aws_vpn_connection" "vpn_connection" { + vpn_gateway_id = "${aws_vpn_gateway.vpn_gateway.id}" + customer_gateway_id = "${aws_customer_gateway.customer_gateway.id}" + type = "ipsec.1" + static_routes_only = true + } -resource "aws_vpn_connection_route" "foo" { - destination_cidr_block = "172.168.20.0/24" - vpn_connection_id = "${aws_vpn_connection.vpn_connection.id}" + resource "aws_vpn_connection_route" "foo" { + destination_cidr_block = "172.168.20.0/24" + vpn_connection_id = "${aws_vpn_connection.vpn_connection.id}" + } + `, rBgpAsn) } -` diff --git a/builtin/providers/aws/s3_tags.go b/builtin/providers/aws/s3_tags.go index 696821b79..f691cff46 100644 --- a/builtin/providers/aws/s3_tags.go +++ b/builtin/providers/aws/s3_tags.go @@ -121,7 +121,7 @@ func getTagSetS3(s3conn *s3.S3, bucket string) ([]*s3.Tag, error) { // compare a tag against a list of strings and checks if it should // be ignored or not func tagIgnoredS3(t *s3.Tag) bool { - filter := []string{"^aws:*"} + filter := []string{"^aws:"} for _, v := range filter { log.Printf("[DEBUG] Matching %v with %v\n", v, *t.Key) if r, _ := regexp.MatchString(v, *t.Key); r == true { diff --git a/builtin/providers/aws/s3_tags_test.go b/builtin/providers/aws/s3_tags_test.go index 48d38b715..42d5b605d 100644 --- a/builtin/providers/aws/s3_tags_test.go +++ b/builtin/providers/aws/s3_tags_test.go @@ -1,14 +1,11 @@ package aws import ( - "fmt" "reflect" "testing" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/s3" - "github.com/hashicorp/terraform/helper/resource" - "github.com/hashicorp/terraform/terraform" ) func TestDiffTagsS3(t *testing.T) { @@ -78,26 +75,3 @@ func TestIgnoringTagsS3(t *testing.T) { } } } - -// testAccCheckTags can be used to check the tags on a resource. -func testAccCheckTagsS3( - ts *[]*s3.Tag, key string, value string) resource.TestCheckFunc { - return func(s *terraform.State) error { - m := tagsToMapS3(*ts) - v, ok := m[key] - if value != "" && !ok { - return fmt.Errorf("Missing tag: %s", key) - } else if value == "" && ok { - return fmt.Errorf("Extra tag: %s", key) - } - if value == "" { - return nil - } - - if v != value { - return fmt.Errorf("%s: bad value: %s", key, v) - } - - return nil - } -} diff --git a/builtin/providers/aws/sort.go b/builtin/providers/aws/sort.go new file mode 100644 index 000000000..0d90458eb --- /dev/null +++ b/builtin/providers/aws/sort.go @@ -0,0 +1,53 @@ +package aws + +import ( + "sort" + "time" + + "github.com/aws/aws-sdk-go/service/ec2" +) + +type imageSort []*ec2.Image +type snapshotSort []*ec2.Snapshot + +func (a imageSort) Len() int { + return len(a) +} + +func (a imageSort) Swap(i, j int) { + a[i], a[j] = a[j], a[i] +} + +func (a imageSort) Less(i, j int) bool { + itime, _ := time.Parse(time.RFC3339, *a[i].CreationDate) + jtime, _ := time.Parse(time.RFC3339, *a[j].CreationDate) + return itime.Unix() < jtime.Unix() +} + +// Sort images by creation date, in descending order. +func sortImages(images []*ec2.Image) []*ec2.Image { + sortedImages := images + sort.Sort(sort.Reverse(imageSort(sortedImages))) + return sortedImages +} + +func (a snapshotSort) Len() int { + return len(a) +} + +func (a snapshotSort) Swap(i, j int) { + a[i], a[j] = a[j], a[i] +} + +func (a snapshotSort) Less(i, j int) bool { + itime := *a[i].StartTime + jtime := *a[j].StartTime + return itime.Unix() < jtime.Unix() +} + +// Sort snapshots by creation date, in descending order. +func sortSnapshots(snapshots []*ec2.Snapshot) []*ec2.Snapshot { + sortedSnapshots := snapshots + sort.Sort(sort.Reverse(snapshotSort(sortedSnapshots))) + return sortedSnapshots +} diff --git a/builtin/providers/aws/structure.go b/builtin/providers/aws/structure.go index 302571c6c..56861d46f 100644 --- a/builtin/providers/aws/structure.go +++ b/builtin/providers/aws/structure.go @@ -14,6 +14,7 @@ import ( "github.com/aws/aws-sdk-go/service/autoscaling" "github.com/aws/aws-sdk-go/service/cloudformation" "github.com/aws/aws-sdk-go/service/cloudwatchlogs" + "github.com/aws/aws-sdk-go/service/cognitoidentity" "github.com/aws/aws-sdk-go/service/configservice" "github.com/aws/aws-sdk-go/service/directoryservice" "github.com/aws/aws-sdk-go/service/ec2" @@ -27,6 +28,7 @@ import ( "github.com/aws/aws-sdk-go/service/rds" "github.com/aws/aws-sdk-go/service/redshift" "github.com/aws/aws-sdk-go/service/route53" + "github.com/aws/aws-sdk-go/service/ssm" "github.com/hashicorp/terraform/helper/schema" "gopkg.in/yaml.v2" ) @@ -813,11 +815,14 @@ func flattenStepAdjustments(adjustments []*autoscaling.StepAdjustment) []map[str return result } -func flattenResourceRecords(recs []*route53.ResourceRecord) []string { +func flattenResourceRecords(recs []*route53.ResourceRecord, typeStr string) []string { strs := make([]string, 0, len(recs)) for _, r := range recs { if r.Value != nil { - s := strings.Replace(*r.Value, "\"", "", 2) + s := *r.Value + if typeStr == "TXT" || typeStr == "SPF" { + s = expandTxtEntry(s) + } strs = append(strs, s) } } @@ -828,17 +833,72 @@ func expandResourceRecords(recs []interface{}, typeStr string) []*route53.Resour records := make([]*route53.ResourceRecord, 0, len(recs)) for _, r := range recs { s := r.(string) - switch typeStr { - case "TXT", "SPF": - str := fmt.Sprintf("\"%s\"", s) - records = append(records, &route53.ResourceRecord{Value: aws.String(str)}) - default: - records = append(records, &route53.ResourceRecord{Value: aws.String(s)}) + if typeStr == "TXT" || typeStr == "SPF" { + s = flattenTxtEntry(s) } + records = append(records, &route53.ResourceRecord{Value: aws.String(s)}) } return records } +// How 'flattenTxtEntry' and 'expandTxtEntry' work. +// +// In the Route 53, TXT entries are written using quoted strings, one per line. +// Example: +// "x=foo" +// "bar=12" +// +// In Terraform, there are two differences: +// - We use a list of strings instead of separating strings with newlines. +// - Within each string, we dont' include the surrounding quotes. +// Example: +// records = ["x=foo", "bar=12"] # Instead of ["\"x=foo\", \"bar=12\""] +// +// When we pull from Route 53, `expandTxtEntry` removes the surrounding quotes; +// when we push to Route 53, `flattenTxtEntry` adds them back. +// +// One complication is that a single TXT entry can have multiple quoted strings. +// For example, here are two TXT entries, one with two quoted strings and the +// other with three. +// "x=" "foo" +// "ba" "r" "=12" +// +// DNS clients are expected to merge the quoted strings before interpreting the +// value. Since `expandTxtEntry` only removes the quotes at the end we can still +// (hackily) represent the above configuration in Terraform: +// records = ["x=\" \"foo", "ba\" \"r\" \"=12"] +// +// The primary reason to use multiple strings for an entry is that DNS (and Route +// 53) doesn't allow a quoted string to be more than 255 characters long. If you +// want a longer TXT entry, you must use multiple quoted strings. +// +// It would be nice if this Terraform automatically split strings longer than 255 +// characters. For example, imagine "xxx..xxx" has 256 "x" characters. +// records = ["xxx..xxx"] +// When pushing to Route 53, this could be converted to: +// "xxx..xx" "x" +// +// This could also work when the user is already using multiple quoted strings: +// records = ["xxx.xxx\" \"yyy..yyy"] +// When pushing to Route 53, this could be converted to: +// "xxx..xx" "xyyy...y" "yy" +// +// If you want to add this feature, make sure to follow all the quoting rules in +// . If you make a mistake, people +// might end up relying on that mistake so fixing it would be a breaking change. + +func flattenTxtEntry(s string) string { + return fmt.Sprintf(`"%s"`, s) +} + +func expandTxtEntry(s string) string { + last := len(s) - 1 + if last != 0 && s[0] == '"' && s[last] == '"' { + s = s[1:last] + } + return s +} + func expandESClusterConfig(m map[string]interface{}) *elasticsearch.ElasticsearchClusterConfig { config := elasticsearch.ElasticsearchClusterConfig{} @@ -1490,6 +1550,22 @@ func sortInterfaceSlice(in []interface{}) []interface{} { return b } +// This function sorts List A to look like a list found in the tf file. +func sortListBasedonTFFile(in []string, d *schema.ResourceData, listName string) ([]string, error) { + if attributeCount, ok := d.Get(listName + ".#").(int); ok { + for i := 0; i < attributeCount; i++ { + currAttributeId := d.Get(listName + "." + strconv.Itoa(i)) + for j := 0; j < len(in); j++ { + if currAttributeId == in[j] { + in[i], in[j] = in[j], in[i] + } + } + } + return in, nil + } + return in, fmt.Errorf("Could not find list: %s", listName) +} + func flattenApiGatewayThrottleSettings(settings *apigateway.ThrottleSettings) []map[string]interface{} { result := make([]map[string]interface{}, 0, 1) @@ -1909,3 +1985,140 @@ func flattenApiGatewayUsagePlanQuota(s *apigateway.QuotaSettings) []map[string]i return []map[string]interface{}{settings} } + +func buildApiGatewayInvokeURL(restApiId, region, stageName string) string { + return fmt.Sprintf("https://%s.execute-api.%s.amazonaws.com/%s", + restApiId, region, stageName) +} + +func buildApiGatewayExecutionARN(restApiId, region, accountId string) (string, error) { + if accountId == "" { + return "", fmt.Errorf("Unable to build execution ARN for %s as account ID is missing", + restApiId) + } + return fmt.Sprintf("arn:aws:execute-api:%s:%s:%s", + region, accountId, restApiId), nil +} + +func expandCognitoSupportedLoginProviders(config map[string]interface{}) map[string]*string { + m := map[string]*string{} + for k, v := range config { + s := v.(string) + m[k] = &s + } + return m +} + +func flattenCognitoSupportedLoginProviders(config map[string]*string) map[string]string { + m := map[string]string{} + for k, v := range config { + m[k] = *v + } + return m +} + +func expandCognitoIdentityProviders(s *schema.Set) []*cognitoidentity.Provider { + ips := make([]*cognitoidentity.Provider, 0) + + for _, v := range s.List() { + s := v.(map[string]interface{}) + + ip := &cognitoidentity.Provider{} + + if sv, ok := s["client_id"].(string); ok { + ip.ClientId = aws.String(sv) + } + + if sv, ok := s["provider_name"].(string); ok { + ip.ProviderName = aws.String(sv) + } + + if sv, ok := s["server_side_token_check"].(bool); ok { + ip.ServerSideTokenCheck = aws.Bool(sv) + } + + ips = append(ips, ip) + } + + return ips +} + +func flattenCognitoIdentityProviders(ips []*cognitoidentity.Provider) []map[string]interface{} { + values := make([]map[string]interface{}, 0) + + for _, v := range ips { + ip := make(map[string]interface{}) + + if v == nil { + return nil + } + + if v.ClientId != nil { + ip["client_id"] = *v.ClientId + } + + if v.ProviderName != nil { + ip["provider_name"] = *v.ProviderName + } + + if v.ServerSideTokenCheck != nil { + ip["server_side_token_check"] = *v.ServerSideTokenCheck + } + + values = append(values, ip) + } + + return values +} + +func buildLambdaInvokeArn(lambdaArn, region string) string { + apiVersion := "2015-03-31" + return fmt.Sprintf("arn:aws:apigateway:%s:lambda:path/%s/functions/%s/invocations", + region, apiVersion, lambdaArn) +} + +func sliceContainsMap(l []interface{}, m map[string]interface{}) (int, bool) { + for i, t := range l { + if reflect.DeepEqual(m, t.(map[string]interface{})) { + return i, true + } + } + + return -1, false +} + +func expandAwsSsmTargets(d *schema.ResourceData) []*ssm.Target { + var targets []*ssm.Target + + targetConfig := d.Get("targets").([]interface{}) + + for _, tConfig := range targetConfig { + config := tConfig.(map[string]interface{}) + + target := &ssm.Target{ + Key: aws.String(config["key"].(string)), + Values: expandStringList(config["values"].([]interface{})), + } + + targets = append(targets, target) + } + + return targets +} + +func flattenAwsSsmTargets(targets []*ssm.Target) []map[string]interface{} { + if len(targets) == 0 { + return nil + } + + result := make([]map[string]interface{}, 0, len(targets)) + target := targets[0] + + t := make(map[string]interface{}) + t["key"] = *target.Key + t["values"] = flattenStringList(target.Values) + + result = append(result, t) + + return result +} diff --git a/builtin/providers/aws/structure_test.go b/builtin/providers/aws/structure_test.go index 057058b43..11e74d2ba 100644 --- a/builtin/providers/aws/structure_test.go +++ b/builtin/providers/aws/structure_test.go @@ -819,23 +819,60 @@ func TestFlattenStepAdjustments(t *testing.T) { } func TestFlattenResourceRecords(t *testing.T) { - expanded := []*route53.ResourceRecord{ - &route53.ResourceRecord{ - Value: aws.String("127.0.0.1"), - }, - &route53.ResourceRecord{ - Value: aws.String("127.0.0.3"), - }, + original := []string{ + `127.0.0.1`, + `"abc def"`, + `"abc" "def"`, + `"abc" ""`, } - result := flattenResourceRecords(expanded) + dequoted := []string{ + `127.0.0.1`, + `abc def`, + `abc" "def`, + `abc" "`, + } + + var wrapped []*route53.ResourceRecord = nil + for _, original := range original { + wrapped = append(wrapped, &route53.ResourceRecord{Value: aws.String(original)}) + } + + sub := func(recordType string, expected []string) { + t.Run(recordType, func(t *testing.T) { + checkFlattenResourceRecords(t, recordType, wrapped, expected) + }) + } + + // These record types should be dequoted. + sub("TXT", dequoted) + sub("SPF", dequoted) + + // These record types should not be touched. + sub("CNAME", original) + sub("MX", original) +} + +func checkFlattenResourceRecords( + t *testing.T, + recordType string, + expanded []*route53.ResourceRecord, + expected []string) { + + result := flattenResourceRecords(expanded, recordType) if result == nil { t.Fatal("expected result to have value, but got nil") } - if len(result) != 2 { - t.Fatal("expected result to have value, but got nil") + if len(result) != len(expected) { + t.Fatalf("expected %v, got %v", expected, result) + } + + for i, e := range expected { + if result[i] != e { + t.Fatalf("expected %v, got %v", expected, result) + } } } diff --git a/builtin/providers/aws/tags.go b/builtin/providers/aws/tags.go index 90fda0146..46438c0fd 100644 --- a/builtin/providers/aws/tags.go +++ b/builtin/providers/aws/tags.go @@ -69,6 +69,63 @@ func setElbV2Tags(conn *elbv2.ELBV2, d *schema.ResourceData) error { return nil } +func setVolumeTags(conn *ec2.EC2, d *schema.ResourceData) error { + if d.HasChange("volume_tags") { + oraw, nraw := d.GetChange("volume_tags") + o := oraw.(map[string]interface{}) + n := nraw.(map[string]interface{}) + create, remove := diffTags(tagsFromMap(o), tagsFromMap(n)) + + volumeIds, err := getAwsInstanceVolumeIds(conn, d) + if err != nil { + return err + } + + if len(remove) > 0 { + err := resource.Retry(2*time.Minute, func() *resource.RetryError { + log.Printf("[DEBUG] Removing volume tags: %#v from %s", remove, d.Id()) + _, err := conn.DeleteTags(&ec2.DeleteTagsInput{ + Resources: volumeIds, + Tags: remove, + }) + if err != nil { + ec2err, ok := err.(awserr.Error) + if ok && strings.Contains(ec2err.Code(), ".NotFound") { + return resource.RetryableError(err) // retry + } + return resource.NonRetryableError(err) + } + return nil + }) + if err != nil { + return err + } + } + if len(create) > 0 { + err := resource.Retry(2*time.Minute, func() *resource.RetryError { + log.Printf("[DEBUG] Creating vol tags: %s for %s", create, d.Id()) + _, err := conn.CreateTags(&ec2.CreateTagsInput{ + Resources: volumeIds, + Tags: create, + }) + if err != nil { + ec2err, ok := err.(awserr.Error) + if ok && strings.Contains(ec2err.Code(), ".NotFound") { + return resource.RetryableError(err) // retry + } + return resource.NonRetryableError(err) + } + return nil + }) + if err != nil { + return err + } + } + } + + return nil +} + // setTags is a helper to set the tags for a resource. It expects the // tags field to be named "tags" func setTags(conn *ec2.EC2, d *schema.ResourceData) error { @@ -80,7 +137,7 @@ func setTags(conn *ec2.EC2, d *schema.ResourceData) error { // Set tags if len(remove) > 0 { - err := resource.Retry(2*time.Minute, func() *resource.RetryError { + err := resource.Retry(5*time.Minute, func() *resource.RetryError { log.Printf("[DEBUG] Removing tags: %#v from %s", remove, d.Id()) _, err := conn.DeleteTags(&ec2.DeleteTagsInput{ Resources: []*string{aws.String(d.Id())}, @@ -100,7 +157,7 @@ func setTags(conn *ec2.EC2, d *schema.ResourceData) error { } } if len(create) > 0 { - err := resource.Retry(2*time.Minute, func() *resource.RetryError { + err := resource.Retry(5*time.Minute, func() *resource.RetryError { log.Printf("[DEBUG] Creating tags: %s for %s", create, d.Id()) _, err := conn.CreateTags(&ec2.CreateTagsInput{ Resources: []*string{aws.String(d.Id())}, @@ -225,7 +282,7 @@ func tagsFromMapELBv2(m map[string]interface{}) []*elbv2.Tag { // tagIgnored compares a tag against a list of strings and checks if it should // be ignored or not func tagIgnored(t *ec2.Tag) bool { - filter := []string{"^aws:*"} + filter := []string{"^aws:"} for _, v := range filter { log.Printf("[DEBUG] Matching %v with %v\n", v, *t.Key) if r, _ := regexp.MatchString(v, *t.Key); r == true { @@ -238,7 +295,7 @@ func tagIgnored(t *ec2.Tag) bool { // and for ELBv2 as well func tagIgnoredELBv2(t *elbv2.Tag) bool { - filter := []string{"^aws:*"} + filter := []string{"^aws:"} for _, v := range filter { log.Printf("[DEBUG] Matching %v with %v\n", v, *t.Key) if r, _ := regexp.MatchString(v, *t.Key); r == true { diff --git a/builtin/providers/aws/tagsBeanstalk.go b/builtin/providers/aws/tagsBeanstalk.go index c3b7b95da..7b85d6116 100644 --- a/builtin/providers/aws/tagsBeanstalk.go +++ b/builtin/providers/aws/tagsBeanstalk.go @@ -62,7 +62,7 @@ func tagsToMapBeanstalk(ts []*elasticbeanstalk.Tag) map[string]string { // compare a tag against a list of strings and checks if it should // be ignored or not func tagIgnoredBeanstalk(t *elasticbeanstalk.Tag) bool { - filter := []string{"^aws:*"} + filter := []string{"^aws:"} for _, v := range filter { log.Printf("[DEBUG] Matching %v with %v\n", v, *t.Key) if r, _ := regexp.MatchString(v, *t.Key); r == true { diff --git a/builtin/providers/aws/tagsCloudtrail.go b/builtin/providers/aws/tagsCloudtrail.go index 020a6ea92..b4302ddd1 100644 --- a/builtin/providers/aws/tagsCloudtrail.go +++ b/builtin/providers/aws/tagsCloudtrail.go @@ -100,7 +100,7 @@ func tagsToMapCloudtrail(ts []*cloudtrail.Tag) map[string]string { // compare a tag against a list of strings and checks if it should // be ignored or not func tagIgnoredCloudtrail(t *cloudtrail.Tag) bool { - filter := []string{"^aws:*"} + filter := []string{"^aws:"} for _, v := range filter { log.Printf("[DEBUG] Matching %v with %v\n", v, *t.Key) if r, _ := regexp.MatchString(v, *t.Key); r == true { diff --git a/builtin/providers/aws/tagsCodeBuild.go b/builtin/providers/aws/tagsCodeBuild.go index e28fc2146..3302d7426 100644 --- a/builtin/providers/aws/tagsCodeBuild.go +++ b/builtin/providers/aws/tagsCodeBuild.go @@ -55,7 +55,7 @@ func tagsToMapCodeBuild(ts []*codebuild.Tag) map[string]string { // compare a tag against a list of strings and checks if it should // be ignored or not func tagIgnoredCodeBuild(t *codebuild.Tag) bool { - filter := []string{"^aws:*"} + filter := []string{"^aws:"} for _, v := range filter { log.Printf("[DEBUG] Matching %v with %v\n", v, *t.Key) if r, _ := regexp.MatchString(v, *t.Key); r == true { diff --git a/builtin/providers/aws/tagsEC.go b/builtin/providers/aws/tagsEC.go index 6b29057ad..b9b22af9c 100644 --- a/builtin/providers/aws/tagsEC.go +++ b/builtin/providers/aws/tagsEC.go @@ -103,7 +103,7 @@ func tagsToMapEC(ts []*elasticache.Tag) map[string]string { // compare a tag against a list of strings and checks if it should // be ignored or not func tagIgnoredEC(t *elasticache.Tag) bool { - filter := []string{"^aws:*"} + filter := []string{"^aws:"} for _, v := range filter { log.Printf("[DEBUG] Matching %v with %v\n", v, *t.Key) if r, _ := regexp.MatchString(v, *t.Key); r == true { diff --git a/builtin/providers/aws/tagsEFS.go b/builtin/providers/aws/tagsEFS.go index 2dc6189cc..b61973165 100644 --- a/builtin/providers/aws/tagsEFS.go +++ b/builtin/providers/aws/tagsEFS.go @@ -102,7 +102,7 @@ func tagsToMapEFS(ts []*efs.Tag) map[string]string { // compare a tag against a list of strings and checks if it should // be ignored or not func tagIgnoredEFS(t *efs.Tag) bool { - filter := []string{"^aws:*"} + filter := []string{"^aws:"} for _, v := range filter { log.Printf("[DEBUG] Matching %v with %v\n", v, *t.Key) if r, _ := regexp.MatchString(v, *t.Key); r == true { diff --git a/builtin/providers/aws/tagsELB.go b/builtin/providers/aws/tagsELB.go index 4c177b878..081de9cc1 100644 --- a/builtin/providers/aws/tagsELB.go +++ b/builtin/providers/aws/tagsELB.go @@ -102,7 +102,7 @@ func tagsToMapELB(ts []*elb.Tag) map[string]string { // compare a tag against a list of strings and checks if it should // be ignored or not func tagIgnoredELB(t *elb.Tag) bool { - filter := []string{"^aws:*"} + filter := []string{"^aws:"} for _, v := range filter { log.Printf("[DEBUG] Matching %v with %v\n", v, *t.Key) if r, _ := regexp.MatchString(v, *t.Key); r == true { diff --git a/builtin/providers/aws/tagsGeneric.go b/builtin/providers/aws/tagsGeneric.go new file mode 100644 index 000000000..d494a4972 --- /dev/null +++ b/builtin/providers/aws/tagsGeneric.go @@ -0,0 +1,69 @@ +package aws + +import ( + "log" + "regexp" + + "github.com/aws/aws-sdk-go/aws" +) + +// diffTags takes our tags locally and the ones remotely and returns +// the set of tags that must be created, and the set of tags that must +// be destroyed. +func diffTagsGeneric(oldTags, newTags map[string]interface{}) (map[string]*string, map[string]*string) { + // First, we're creating everything we have + create := make(map[string]*string) + for k, v := range newTags { + create[k] = aws.String(v.(string)) + } + + // Build the map of what to remove + remove := make(map[string]*string) + for k, v := range oldTags { + old, ok := create[k] + if !ok || old != aws.String(v.(string)) { + // Delete it! + remove[k] = aws.String(v.(string)) + } + } + + return create, remove +} + +// tagsFromMap returns the tags for the given map of data. +func tagsFromMapGeneric(m map[string]interface{}) map[string]*string { + result := make(map[string]*string) + for k, v := range m { + if !tagIgnoredGeneric(k) { + result[k] = aws.String(v.(string)) + } + } + + return result +} + +// tagsToMap turns the tags into a map. +func tagsToMapGeneric(ts map[string]*string) map[string]string { + result := make(map[string]string) + for k, v := range ts { + if !tagIgnoredGeneric(k) { + result[k] = aws.StringValue(v) + } + } + + return result +} + +// compare a tag against a list of strings and checks if it should +// be ignored or not +func tagIgnoredGeneric(k string) bool { + filter := []string{"^aws:"} + for _, v := range filter { + log.Printf("[DEBUG] Matching %v with %v\n", v, k) + if r, _ := regexp.MatchString(v, k); r == true { + log.Printf("[DEBUG] Found AWS specific tag %s, ignoring.\n", k) + return true + } + } + return false +} diff --git a/builtin/providers/aws/tagsGeneric_test.go b/builtin/providers/aws/tagsGeneric_test.go new file mode 100644 index 000000000..2477f3aa5 --- /dev/null +++ b/builtin/providers/aws/tagsGeneric_test.go @@ -0,0 +1,73 @@ +package aws + +import ( + "reflect" + "testing" + + "github.com/aws/aws-sdk-go/aws" +) + +// go test -v -run="TestDiffGenericTags" +func TestDiffGenericTags(t *testing.T) { + cases := []struct { + Old, New map[string]interface{} + Create, Remove map[string]string + }{ + // Basic add/remove + { + Old: map[string]interface{}{ + "foo": "bar", + }, + New: map[string]interface{}{ + "bar": "baz", + }, + Create: map[string]string{ + "bar": "baz", + }, + Remove: map[string]string{ + "foo": "bar", + }, + }, + + // Modify + { + Old: map[string]interface{}{ + "foo": "bar", + }, + New: map[string]interface{}{ + "foo": "baz", + }, + Create: map[string]string{ + "foo": "baz", + }, + Remove: map[string]string{ + "foo": "bar", + }, + }, + } + + for i, tc := range cases { + c, r := diffTagsGeneric(tc.Old, tc.New) + cm := tagsToMapGeneric(c) + rm := tagsToMapGeneric(r) + if !reflect.DeepEqual(cm, tc.Create) { + t.Fatalf("%d: bad create: %#v", i, cm) + } + if !reflect.DeepEqual(rm, tc.Remove) { + t.Fatalf("%d: bad remove: %#v", i, rm) + } + } +} + +// go test -v -run="TestIgnoringTagsGeneric" +func TestIgnoringTagsGeneric(t *testing.T) { + ignoredTags := map[string]*string{ + "aws:cloudformation:logical-id": aws.String("foo"), + "aws:foo:bar": aws.String("baz"), + } + for k, v := range ignoredTags { + if !tagIgnoredGeneric(k) { + t.Fatalf("Tag %v with value %v not ignored, but should be!", k, *v) + } + } +} diff --git a/builtin/providers/aws/tagsInspector.go b/builtin/providers/aws/tagsInspector.go index f846319f9..ef18f33c2 100644 --- a/builtin/providers/aws/tagsInspector.go +++ b/builtin/providers/aws/tagsInspector.go @@ -62,7 +62,7 @@ func tagsToMapInspector(ts []*inspector.ResourceGroupTag) map[string]string { // compare a tag against a list of strings and checks if it should // be ignored or not func tagIgnoredInspector(t *inspector.ResourceGroupTag) bool { - filter := []string{"^aws:*"} + filter := []string{"^aws:"} for _, v := range filter { log.Printf("[DEBUG] Matching %v with %v\n", v, *t.Key) if r, _ := regexp.MatchString(v, *t.Key); r == true { diff --git a/builtin/providers/aws/tagsKMS.go b/builtin/providers/aws/tagsKMS.go index d4d2eca1c..4e918414e 100644 --- a/builtin/providers/aws/tagsKMS.go +++ b/builtin/providers/aws/tagsKMS.go @@ -103,7 +103,7 @@ func tagsToMapKMS(ts []*kms.Tag) map[string]string { // compare a tag against a list of strings and checks if it should // be ignored or not func tagIgnoredKMS(t *kms.Tag) bool { - filter := []string{"^aws:*"} + filter := []string{"^aws:"} for _, v := range filter { log.Printf("[DEBUG] Matching %v with %v\n", v, *t.TagKey) if r, _ := regexp.MatchString(v, *t.TagKey); r == true { diff --git a/builtin/providers/aws/tagsLambda.go b/builtin/providers/aws/tagsLambda.go new file mode 100644 index 000000000..28aa25121 --- /dev/null +++ b/builtin/providers/aws/tagsLambda.go @@ -0,0 +1,50 @@ +package aws + +import ( + "log" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/service/lambda" + "github.com/hashicorp/terraform/helper/schema" +) + +// setTags is a helper to set the tags for a resource. It expects the +// tags field to be named "tags" +func setTagsLambda(conn *lambda.Lambda, d *schema.ResourceData, arn string) error { + if d.HasChange("tags") { + oraw, nraw := d.GetChange("tags") + o := oraw.(map[string]interface{}) + n := nraw.(map[string]interface{}) + create, remove := diffTagsGeneric(o, n) + + // Set tags + if len(remove) > 0 { + log.Printf("[DEBUG] Removing tags: %#v", remove) + keys := make([]*string, 0, len(remove)) + for k := range remove { + keys = append(keys, aws.String(k)) + } + + _, err := conn.UntagResource(&lambda.UntagResourceInput{ + Resource: aws.String(arn), + TagKeys: keys, + }) + if err != nil { + return err + } + } + if len(create) > 0 { + log.Printf("[DEBUG] Creating tags: %#v", create) + + _, err := conn.TagResource(&lambda.TagResourceInput{ + Resource: aws.String(arn), + Tags: create, + }) + if err != nil { + return err + } + } + } + + return nil +} diff --git a/builtin/providers/aws/tagsRDS.go b/builtin/providers/aws/tagsRDS.go index 1a5b0c1c7..2d6411348 100644 --- a/builtin/providers/aws/tagsRDS.go +++ b/builtin/providers/aws/tagsRDS.go @@ -121,7 +121,7 @@ func saveTagsRDS(conn *rds.RDS, d *schema.ResourceData, arn string) error { // compare a tag against a list of strings and checks if it should // be ignored or not func tagIgnoredRDS(t *rds.Tag) bool { - filter := []string{"^aws:*"} + filter := []string{"^aws:"} for _, v := range filter { log.Printf("[DEBUG] Matching %v with %v\n", v, *t.Key) if r, _ := regexp.MatchString(v, *t.Key); r == true { diff --git a/builtin/providers/aws/tagsRedshift.go b/builtin/providers/aws/tagsRedshift.go index 0a87f7114..715e82045 100644 --- a/builtin/providers/aws/tagsRedshift.go +++ b/builtin/providers/aws/tagsRedshift.go @@ -96,7 +96,7 @@ func tagsToMapRedshift(ts []*redshift.Tag) map[string]string { // compare a tag against a list of strings and checks if it should // be ignored or not func tagIgnoredRedshift(t *redshift.Tag) bool { - filter := []string{"^aws:*"} + filter := []string{"^aws:"} for _, v := range filter { log.Printf("[DEBUG] Matching %v with %v\n", v, *t.Key) if r, _ := regexp.MatchString(v, *t.Key); r == true { diff --git a/builtin/providers/aws/tags_elasticsearchservice.go b/builtin/providers/aws/tags_elasticsearchservice.go index f048e4681..e585d1afa 100644 --- a/builtin/providers/aws/tags_elasticsearchservice.go +++ b/builtin/providers/aws/tags_elasticsearchservice.go @@ -102,7 +102,7 @@ func tagsToMapElasticsearchService(ts []*elasticsearch.Tag) map[string]string { // compare a tag against a list of strings and checks if it should // be ignored or not func tagIgnoredElasticsearchService(t *elasticsearch.Tag) bool { - filter := []string{"^aws:*"} + filter := []string{"^aws:"} for _, v := range filter { log.Printf("[DEBUG] Matching %v with %v\n", v, *t.Key) if r, _ := regexp.MatchString(v, *t.Key); r == true { diff --git a/builtin/providers/aws/tags_kinesis.go b/builtin/providers/aws/tags_kinesis.go index 5c5935988..a5622e95d 100644 --- a/builtin/providers/aws/tags_kinesis.go +++ b/builtin/providers/aws/tags_kinesis.go @@ -113,7 +113,7 @@ func tagsToMapKinesis(ts []*kinesis.Tag) map[string]string { // compare a tag against a list of strings and checks if it should // be ignored or not func tagIgnoredKinesis(t *kinesis.Tag) bool { - filter := []string{"^aws:*"} + filter := []string{"^aws:"} for _, v := range filter { log.Printf("[DEBUG] Matching %v with %v\n", v, *t.Key) if r, _ := regexp.MatchString(v, *t.Key); r == true { diff --git a/builtin/providers/aws/tags_route53.go b/builtin/providers/aws/tags_route53.go index d675f42e0..372167291 100644 --- a/builtin/providers/aws/tags_route53.go +++ b/builtin/providers/aws/tags_route53.go @@ -99,7 +99,7 @@ func tagsToMapR53(ts []*route53.Tag) map[string]string { // compare a tag against a list of strings and checks if it should // be ignored or not func tagIgnoredRoute53(t *route53.Tag) bool { - filter := []string{"^aws:*"} + filter := []string{"^aws:"} for _, v := range filter { log.Printf("[DEBUG] Matching %v with %v\n", v, *t.Key) if r, _ := regexp.MatchString(v, *t.Key); r == true { diff --git a/builtin/providers/aws/test-fixtures/lambda_confirm_sns.zip b/builtin/providers/aws/test-fixtures/lambda_confirm_sns.zip new file mode 100644 index 000000000..c88d2d400 Binary files /dev/null and b/builtin/providers/aws/test-fixtures/lambda_confirm_sns.zip differ diff --git a/builtin/providers/aws/validators.go b/builtin/providers/aws/validators.go index a8f9c66cf..f46c550d2 100644 --- a/builtin/providers/aws/validators.go +++ b/builtin/providers/aws/validators.go @@ -3,6 +3,7 @@ package aws import ( "fmt" "net" + "net/url" "regexp" "strings" "time" @@ -12,7 +13,7 @@ import ( "github.com/hashicorp/terraform/helper/schema" ) -func validateRdsId(v interface{}, k string) (ws []string, errors []error) { +func validateRdsIdentifier(v interface{}, k string) (ws []string, errors []error) { value := v.(string) if !regexp.MustCompile(`^[0-9a-z-]+$`).MatchString(value) { errors = append(errors, fmt.Errorf( @@ -33,6 +34,23 @@ func validateRdsId(v interface{}, k string) (ws []string, errors []error) { return } +func validateRdsIdentifierPrefix(v interface{}, k string) (ws []string, errors []error) { + value := v.(string) + if !regexp.MustCompile(`^[0-9a-z-]+$`).MatchString(value) { + errors = append(errors, fmt.Errorf( + "only lowercase alphanumeric characters and hyphens allowed in %q", k)) + } + if !regexp.MustCompile(`^[a-z]`).MatchString(value) { + errors = append(errors, fmt.Errorf( + "first character of %q must be a letter", k)) + } + if regexp.MustCompile(`--`).MatchString(value) { + errors = append(errors, fmt.Errorf( + "%q cannot contain two consecutive hyphens", k)) + } + return +} + func validateElastiCacheClusterId(v interface{}, k string) (ws []string, errors []error) { value := v.(string) if (len(value) < 1) || (len(value) > 20) { @@ -103,7 +121,27 @@ func validateDbParamGroupName(v interface{}, k string) (ws []string, errors []er "%q cannot be greater than 255 characters", k)) } return +} +func validateDbParamGroupNamePrefix(v interface{}, k string) (ws []string, errors []error) { + value := v.(string) + if !regexp.MustCompile(`^[0-9a-z-]+$`).MatchString(value) { + errors = append(errors, fmt.Errorf( + "only lowercase alphanumeric characters and hyphens allowed in %q", k)) + } + if !regexp.MustCompile(`^[a-z]`).MatchString(value) { + errors = append(errors, fmt.Errorf( + "first character of %q must be a letter", k)) + } + if regexp.MustCompile(`--`).MatchString(value) { + errors = append(errors, fmt.Errorf( + "%q cannot contain two consecutive hyphens", k)) + } + if len(value) > 255 { + errors = append(errors, fmt.Errorf( + "%q cannot be greater than 226 characters", k)) + } + return } func validateStreamViewType(v interface{}, k string) (ws []string, errors []error) { @@ -116,22 +154,25 @@ func validateStreamViewType(v interface{}, k string) (ws []string, errors []erro } if !viewTypes[value] { - errors = append(errors, fmt.Errorf("%q be a valid DynamoDB StreamViewType", k)) + errors = append(errors, fmt.Errorf("%q must be a valid DynamoDB StreamViewType", k)) } return } func validateElbName(v interface{}, k string) (ws []string, errors []error) { value := v.(string) - if !regexp.MustCompile(`^[0-9A-Za-z-]+$`).MatchString(value) { - errors = append(errors, fmt.Errorf( - "only alphanumeric characters and hyphens allowed in %q: %q", - k, value)) + if len(value) == 0 { + return // short-circuit } if len(value) > 32 { errors = append(errors, fmt.Errorf( "%q cannot be longer than 32 characters: %q", k, value)) } + if !regexp.MustCompile(`^[0-9A-Za-z-]+$`).MatchString(value) { + errors = append(errors, fmt.Errorf( + "only alphanumeric characters and hyphens allowed in %q: %q", + k, value)) + } if regexp.MustCompile(`^-`).MatchString(value) { errors = append(errors, fmt.Errorf( "%q cannot begin with a hyphen: %q", k, value)) @@ -315,7 +356,7 @@ func validateArn(v interface{}, k string) (ws []string, errors []error) { } // http://docs.aws.amazon.com/lambda/latest/dg/API_AddPermission.html - pattern := `^arn:[\w-]+:([a-zA-Z0-9\-])+:([a-z]{2}-[a-z]+-\d{1})?:(\d{12})?:(.*)$` + pattern := `^arn:[\w-]+:([a-zA-Z0-9\-])+:([a-z]{2}-(gov-)?[a-z]+-\d{1})?:(\d{12})?:(.*)$` if !regexp.MustCompile(pattern).MatchString(value) { errors = append(errors, fmt.Errorf( "%q doesn't look like a valid ARN (%q): %q", @@ -445,6 +486,26 @@ func validateLogGroupName(v interface{}, k string) (ws []string, errors []error) return } +func validateLogGroupNamePrefix(v interface{}, k string) (ws []string, errors []error) { + value := v.(string) + + if len(value) > 483 { + errors = append(errors, fmt.Errorf( + "%q cannot be longer than 483 characters: %q", k, value)) + } + + // http://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_CreateLogGroup.html + pattern := `^[\.\-_/#A-Za-z0-9]+$` + if !regexp.MustCompile(pattern).MatchString(value) { + errors = append(errors, fmt.Errorf( + "%q isn't a valid log group name (alphanumeric characters, underscores,"+ + " hyphens, slashes, hash signs and dots are allowed): %q", + k, value)) + } + + return +} + func validateS3BucketLifecycleTimestamp(v interface{}, k string) (ws []string, errors []error) { value := v.(string) _, err := time.Parse(time.RFC3339, fmt.Sprintf("%sT00:00:00Z", value)) @@ -889,8 +950,9 @@ func validateDmsReplicationTaskId(v interface{}, k string) (ws []string, es []er func validateAppautoscalingScalableDimension(v interface{}, k string) (ws []string, errors []error) { value := v.(string) dimensions := map[string]bool{ - "ecs:service:DesiredCount": true, - "ec2:spot-fleet-request:TargetCapacity": true, + "ecs:service:DesiredCount": true, + "ec2:spot-fleet-request:TargetCapacity": true, + "elasticmapreduce:instancegroup:InstanceCount": true, } if !dimensions[value] { @@ -902,8 +964,9 @@ func validateAppautoscalingScalableDimension(v interface{}, k string) (ws []stri func validateAppautoscalingServiceNamespace(v interface{}, k string) (ws []string, errors []error) { value := v.(string) namespaces := map[string]bool{ - "ecs": true, - "ec2": true, + "ecs": true, + "ec2": true, + "elasticmapreduce": true, } if !namespaces[value] { @@ -1041,3 +1104,218 @@ func validateApiGatewayUsagePlanQuotaSettings(v map[string]interface{}) (errors return } + +func validateDbSubnetGroupName(v interface{}, k string) (ws []string, errors []error) { + value := v.(string) + if !regexp.MustCompile(`^[ .0-9a-z-_]+$`).MatchString(value) { + errors = append(errors, fmt.Errorf( + "only lowercase alphanumeric characters, hyphens, underscores, periods, and spaces allowed in %q", k)) + } + if len(value) > 255 { + errors = append(errors, fmt.Errorf( + "%q cannot be longer than 255 characters", k)) + } + if regexp.MustCompile(`(?i)^default$`).MatchString(value) { + errors = append(errors, fmt.Errorf( + "%q is not allowed as %q", "Default", k)) + } + return +} + +func validateDbSubnetGroupNamePrefix(v interface{}, k string) (ws []string, errors []error) { + value := v.(string) + if !regexp.MustCompile(`^[ .0-9a-z-_]+$`).MatchString(value) { + errors = append(errors, fmt.Errorf( + "only lowercase alphanumeric characters, hyphens, underscores, periods, and spaces allowed in %q", k)) + } + if len(value) > 229 { + errors = append(errors, fmt.Errorf( + "%q cannot be longer than 229 characters", k)) + } + return +} + +func validateDbOptionGroupName(v interface{}, k string) (ws []string, errors []error) { + value := v.(string) + if !regexp.MustCompile(`^[a-z]`).MatchString(value) { + errors = append(errors, fmt.Errorf( + "first character of %q must be a letter", k)) + } + if !regexp.MustCompile(`^[0-9a-z-]+$`).MatchString(value) { + errors = append(errors, fmt.Errorf( + "only lowercase alphanumeric characters and hyphens allowed in %q", k)) + } + if regexp.MustCompile(`--`).MatchString(value) { + errors = append(errors, fmt.Errorf( + "%q cannot contain two consecutive hyphens", k)) + } + if regexp.MustCompile(`-$`).MatchString(value) { + errors = append(errors, fmt.Errorf( + "%q cannot end with a hyphen", k)) + } + if len(value) > 255 { + errors = append(errors, fmt.Errorf( + "%q cannot be greater than 255 characters", k)) + } + return +} + +func validateDbOptionGroupNamePrefix(v interface{}, k string) (ws []string, errors []error) { + value := v.(string) + if !regexp.MustCompile(`^[a-z]`).MatchString(value) { + errors = append(errors, fmt.Errorf( + "first character of %q must be a letter", k)) + } + if !regexp.MustCompile(`^[0-9a-z-]+$`).MatchString(value) { + errors = append(errors, fmt.Errorf( + "only alphanumeric characters and hyphens allowed in %q", k)) + } + if regexp.MustCompile(`--`).MatchString(value) { + errors = append(errors, fmt.Errorf( + "%q cannot contain two consecutive hyphens", k)) + } + if len(value) > 229 { + errors = append(errors, fmt.Errorf( + "%q cannot be greater than 229 characters", k)) + } + return +} + +func validateAwsAlbTargetGroupName(v interface{}, k string) (ws []string, errors []error) { + name := v.(string) + if len(name) > 32 { + errors = append(errors, fmt.Errorf("%q (%q) cannot be longer than '32' characters", k, name)) + } + return +} + +func validateAwsAlbTargetGroupNamePrefix(v interface{}, k string) (ws []string, errors []error) { + name := v.(string) + if len(name) > 32 { + errors = append(errors, fmt.Errorf("%q (%q) cannot be longer than '6' characters", k, name)) + } + return +} + +func validateOpenIdURL(v interface{}, k string) (ws []string, errors []error) { + value := v.(string) + u, err := url.Parse(value) + if err != nil { + errors = append(errors, fmt.Errorf("%q has to be a valid URL", k)) + return + } + if u.Scheme != "https" { + errors = append(errors, fmt.Errorf("%q has to use HTTPS scheme (i.e. begin with https://)", k)) + } + if len(u.Query()) > 0 { + errors = append(errors, fmt.Errorf("%q cannot contain query parameters per the OIDC standard", k)) + } + return +} + +func validateAwsKmsName(v interface{}, k string) (ws []string, es []error) { + value := v.(string) + if !regexp.MustCompile(`^(alias\/)[a-zA-Z0-9:/_-]+$`).MatchString(value) { + es = append(es, fmt.Errorf( + "%q must begin with 'alias/' and be comprised of only [a-zA-Z0-9:/_-]", k)) + } + return +} + +func validateCognitoIdentityPoolName(v interface{}, k string) (ws []string, errors []error) { + val := v.(string) + if !regexp.MustCompile("^[\\w _]+$").MatchString(val) { + errors = append(errors, fmt.Errorf("%q must contain only alphanumeric caracters and spaces", k)) + } + + return +} + +func validateCognitoProviderDeveloperName(v interface{}, k string) (ws []string, errors []error) { + value := v.(string) + if len(value) > 100 { + errors = append(errors, fmt.Errorf("%q cannot be longer than 100 caracters", k)) + } + + if !regexp.MustCompile("^[\\w._-]+$").MatchString(value) { + errors = append(errors, fmt.Errorf("%q must contain only alphanumeric caracters, dots, underscores and hyphens", k)) + } + + return +} + +func validateCognitoSupportedLoginProviders(v interface{}, k string) (ws []string, errors []error) { + value := v.(string) + if len(value) < 1 { + errors = append(errors, fmt.Errorf("%q cannot be less than 1 character", k)) + } + + if len(value) > 128 { + errors = append(errors, fmt.Errorf("%q cannot be longer than 128 caracters", k)) + } + + if !regexp.MustCompile("^[\\w.;_/-]+$").MatchString(value) { + errors = append(errors, fmt.Errorf("%q must contain only alphanumeric caracters, dots, semicolons, underscores, slashes and hyphens", k)) + } + + return +} + +func validateCognitoIdentityProvidersClientId(v interface{}, k string) (ws []string, errors []error) { + value := v.(string) + if len(value) < 1 { + errors = append(errors, fmt.Errorf("%q cannot be less than 1 character", k)) + } + + if len(value) > 128 { + errors = append(errors, fmt.Errorf("%q cannot be longer than 128 caracters", k)) + } + + if !regexp.MustCompile("^[\\w_]+$").MatchString(value) { + errors = append(errors, fmt.Errorf("%q must contain only alphanumeric caracters and underscores", k)) + } + + return +} + +func validateCognitoIdentityProvidersProviderName(v interface{}, k string) (ws []string, errors []error) { + value := v.(string) + if len(value) < 1 { + errors = append(errors, fmt.Errorf("%q cannot be less than 1 character", k)) + } + + if len(value) > 128 { + errors = append(errors, fmt.Errorf("%q cannot be longer than 128 caracters", k)) + } + + if !regexp.MustCompile("^[\\w._:/-]+$").MatchString(value) { + errors = append(errors, fmt.Errorf("%q must contain only alphanumeric caracters, dots, underscores, colons, slashes and hyphens", k)) + } + + return +} + +func validateWafMetricName(v interface{}, k string) (ws []string, errors []error) { + value := v.(string) + if !regexp.MustCompile(`^[0-9A-Za-z]+$`).MatchString(value) { + errors = append(errors, fmt.Errorf( + "Only alphanumeric characters allowed in %q: %q", + k, value)) + } + return +} + +func validateIamRoleDescription(v interface{}, k string) (ws []string, errors []error) { + value := v.(string) + + if len(value) > 1000 { + errors = append(errors, fmt.Errorf("%q cannot be longer than 1000 caracters", k)) + } + + if !regexp.MustCompile(`[\p{L}\p{M}\p{Z}\p{S}\p{N}\p{P}]*`).MatchString(value) { + errors = append(errors, fmt.Errorf( + "Only alphanumeric & accented characters allowed in %q: %q (Must satisfy regular expression pattern: [\\p{L}\\p{M}\\p{Z}\\p{S}\\p{N}\\p{P}]*)", + k, value)) + } + return +} diff --git a/builtin/providers/aws/validators_test.go b/builtin/providers/aws/validators_test.go index 0c37308fe..3d323ca51 100644 --- a/builtin/providers/aws/validators_test.go +++ b/builtin/providers/aws/validators_test.go @@ -207,6 +207,7 @@ func TestValidateArn(t *testing.T) { "arn:aws:lambda:eu-west-1:319201112229:function:myCustomFunction", // Lambda function "arn:aws:lambda:eu-west-1:319201112229:function:myCustomFunction:Qualifier", // Lambda func qualifier "arn:aws-us-gov:s3:::corp_bucket/object.png", // GovCloud ARN + "arn:aws-us-gov:kms:us-gov-west-1:123456789012:key/some-uuid-abc123", // GovCloud KMS ARN } for _, v := range validNames { _, errors := validateArn(v, "arn") @@ -410,7 +411,7 @@ func TestValidateLogGroupName(t *testing.T) { for _, v := range validNames { _, errors := validateLogGroupName(v, "name") if len(errors) != 0 { - t.Fatalf("%q should be a valid Log Metric Filter Transformation Name: %q", v, errors) + t.Fatalf("%q should be a valid Log Group name: %q", v, errors) } } @@ -427,7 +428,42 @@ func TestValidateLogGroupName(t *testing.T) { for _, v := range invalidNames { _, errors := validateLogGroupName(v, "name") if len(errors) == 0 { - t.Fatalf("%q should be an invalid Log Metric Filter Transformation Name", v) + t.Fatalf("%q should be an invalid Log Group name", v) + } + } +} + +func TestValidateLogGroupNamePrefix(t *testing.T) { + validNames := []string{ + "ValidLogGroupName", + "ValidLogGroup.Name", + "valid/Log-group", + "1234", + "YadaValid#0123", + "Also_valid-name", + strings.Repeat("W", 483), + } + for _, v := range validNames { + _, errors := validateLogGroupNamePrefix(v, "name_prefix") + if len(errors) != 0 { + t.Fatalf("%q should be a valid Log Group name prefix: %q", v, errors) + } + } + + invalidNames := []string{ + "Here is a name with: colon", + "and here is another * invalid name", + "also $ invalid", + "This . is also %% invalid@!)+(", + "*", + "", + // length > 483 + strings.Repeat("W", 484), + } + for _, v := range invalidNames { + _, errors := validateLogGroupNamePrefix(v, "name_prefix") + if len(errors) == 0 { + t.Fatalf("%q should be an invalid Log Group name prefix", v) } } } @@ -1785,3 +1821,414 @@ func TestValidateElbNamePrefix(t *testing.T) { } } } + +func TestValidateDbSubnetGroupName(t *testing.T) { + cases := []struct { + Value string + ErrCount int + }{ + { + Value: "tEsting", + ErrCount: 1, + }, + { + Value: "testing?", + ErrCount: 1, + }, + { + Value: "default", + ErrCount: 1, + }, + { + Value: randomString(300), + ErrCount: 1, + }, + } + + for _, tc := range cases { + _, errors := validateDbSubnetGroupName(tc.Value, "aws_db_subnet_group") + + if len(errors) != tc.ErrCount { + t.Fatalf("Expected the DB Subnet Group name to trigger a validation error") + } + } +} + +func TestValidateDbSubnetGroupNamePrefix(t *testing.T) { + cases := []struct { + Value string + ErrCount int + }{ + { + Value: "tEsting", + ErrCount: 1, + }, + { + Value: "testing?", + ErrCount: 1, + }, + { + Value: randomString(230), + ErrCount: 1, + }, + } + + for _, tc := range cases { + _, errors := validateDbSubnetGroupNamePrefix(tc.Value, "aws_db_subnet_group") + + if len(errors) != tc.ErrCount { + t.Fatalf("Expected the DB Subnet Group name prefix to trigger a validation error") + } + } +} + +func TestValidateDbOptionGroupName(t *testing.T) { + cases := []struct { + Value string + ErrCount int + }{ + { + Value: "testing123!", + ErrCount: 1, + }, + { + Value: "1testing123", + ErrCount: 1, + }, + { + Value: "testing--123", + ErrCount: 1, + }, + { + Value: "testing123-", + ErrCount: 1, + }, + { + Value: randomString(256), + ErrCount: 1, + }, + } + + for _, tc := range cases { + _, errors := validateDbOptionGroupName(tc.Value, "aws_db_option_group_name") + + if len(errors) != tc.ErrCount { + t.Fatalf("Expected the DB Option Group Name to trigger a validation error") + } + } +} + +func TestValidateDbOptionGroupNamePrefix(t *testing.T) { + cases := []struct { + Value string + ErrCount int + }{ + { + Value: "testing123!", + ErrCount: 1, + }, + { + Value: "1testing123", + ErrCount: 1, + }, + { + Value: "testing--123", + ErrCount: 1, + }, + { + Value: randomString(230), + ErrCount: 1, + }, + } + + for _, tc := range cases { + _, errors := validateDbOptionGroupNamePrefix(tc.Value, "aws_db_option_group_name") + + if len(errors) != tc.ErrCount { + t.Fatalf("Expected the DB Option Group name prefix to trigger a validation error") + } + } +} + +func TestValidateOpenIdURL(t *testing.T) { + cases := []struct { + Value string + ErrCount int + }{ + { + Value: "http://wrong.scheme.com", + ErrCount: 1, + }, + { + Value: "ftp://wrong.scheme.co.uk", + ErrCount: 1, + }, + { + Value: "%@invalidUrl", + ErrCount: 1, + }, + { + Value: "https://example.com/?query=param", + ErrCount: 1, + }, + } + + for _, tc := range cases { + _, errors := validateOpenIdURL(tc.Value, "url") + + if len(errors) != tc.ErrCount { + t.Fatalf("Expected %d of OpenID URL validation errors, got %d", tc.ErrCount, len(errors)) + } + } +} + +func TestValidateAwsKmsName(t *testing.T) { + cases := []struct { + Value string + ErrCount int + }{ + { + Value: "alias/aws/s3", + ErrCount: 0, + }, + { + Value: "alias/hashicorp", + ErrCount: 0, + }, + { + Value: "hashicorp", + ErrCount: 1, + }, + { + Value: "hashicorp/terraform", + ErrCount: 1, + }, + } + + for _, tc := range cases { + _, errors := validateAwsKmsName(tc.Value, "name") + if len(errors) != tc.ErrCount { + t.Fatalf("AWS KMS Alias Name validation failed: %v", errors) + } + } +} + +func TestValidateCognitoIdentityPoolName(t *testing.T) { + validValues := []string{ + "123", + "1 2 3", + "foo", + "foo bar", + "foo_bar", + "1foo 2bar 3", + } + + for _, s := range validValues { + _, errors := validateCognitoIdentityPoolName(s, "identity_pool_name") + if len(errors) > 0 { + t.Fatalf("%q should be a valid Cognito Identity Pool Name: %v", s, errors) + } + } + + invalidValues := []string{ + "1-2-3", + "foo!", + "foo-bar", + "foo-bar", + "foo1-bar2", + } + + for _, s := range invalidValues { + _, errors := validateCognitoIdentityPoolName(s, "identity_pool_name") + if len(errors) == 0 { + t.Fatalf("%q should not be a valid Cognito Identity Pool Name: %v", s, errors) + } + } +} + +func TestValidateCognitoProviderDeveloperName(t *testing.T) { + validValues := []string{ + "1", + "foo", + "1.2", + "foo1-bar2-baz3", + "foo_bar", + } + + for _, s := range validValues { + _, errors := validateCognitoProviderDeveloperName(s, "developer_provider_name") + if len(errors) > 0 { + t.Fatalf("%q should be a valid Cognito Provider Developer Name: %v", s, errors) + } + } + + invalidValues := []string{ + "foo!", + "foo:bar", + "foo/bar", + "foo;bar", + } + + for _, s := range invalidValues { + _, errors := validateCognitoProviderDeveloperName(s, "developer_provider_name") + if len(errors) == 0 { + t.Fatalf("%q should not be a valid Cognito Provider Developer Name: %v", s, errors) + } + } +} + +func TestValidateCognitoSupportedLoginProviders(t *testing.T) { + validValues := []string{ + "foo", + "7346241598935552", + "123456789012.apps.googleusercontent.com", + "foo_bar", + "foo;bar", + "foo/bar", + "foo-bar", + "xvz1evFS4wEEPTGEFPHBog;kAcSOqF21Fu85e7zjz7ZN2U4ZRhfV3WpwPAoE3Z7kBw", + strings.Repeat("W", 128), + } + + for _, s := range validValues { + _, errors := validateCognitoSupportedLoginProviders(s, "supported_login_providers") + if len(errors) > 0 { + t.Fatalf("%q should be a valid Cognito Supported Login Providers: %v", s, errors) + } + } + + invalidValues := []string{ + "", + strings.Repeat("W", 129), // > 128 + "foo:bar_baz", + "foobar,foobaz", + "foobar=foobaz", + } + + for _, s := range invalidValues { + _, errors := validateCognitoSupportedLoginProviders(s, "supported_login_providers") + if len(errors) == 0 { + t.Fatalf("%q should not be a valid Cognito Supported Login Providers: %v", s, errors) + } + } +} + +func TestValidateCognitoIdentityProvidersClientId(t *testing.T) { + validValues := []string{ + "7lhlkkfbfb4q5kpp90urffao", + "12345678", + "foo_123", + strings.Repeat("W", 128), + } + + for _, s := range validValues { + _, errors := validateCognitoIdentityProvidersClientId(s, "client_id") + if len(errors) > 0 { + t.Fatalf("%q should be a valid Cognito Identity Provider Client ID: %v", s, errors) + } + } + + invalidValues := []string{ + "", + strings.Repeat("W", 129), // > 128 + "foo-bar", + "foo:bar", + "foo;bar", + } + + for _, s := range invalidValues { + _, errors := validateCognitoIdentityProvidersClientId(s, "client_id") + if len(errors) == 0 { + t.Fatalf("%q should not be a valid Cognito Identity Provider Client ID: %v", s, errors) + } + } +} + +func TestValidateCognitoIdentityProvidersProviderName(t *testing.T) { + validValues := []string{ + "foo", + "7346241598935552", + "foo_bar", + "foo:bar", + "foo/bar", + "foo-bar", + "cognito-idp.us-east-1.amazonaws.com/us-east-1_Zr231apJu", + strings.Repeat("W", 128), + } + + for _, s := range validValues { + _, errors := validateCognitoIdentityProvidersProviderName(s, "provider_name") + if len(errors) > 0 { + t.Fatalf("%q should be a valid Cognito Identity Provider Name: %v", s, errors) + } + } + + invalidValues := []string{ + "", + strings.Repeat("W", 129), // > 128 + "foo;bar_baz", + "foobar,foobaz", + "foobar=foobaz", + } + + for _, s := range invalidValues { + _, errors := validateCognitoIdentityProvidersProviderName(s, "provider_name") + if len(errors) == 0 { + t.Fatalf("%q should not be a valid Cognito Identity Provider Name: %v", s, errors) + } + } +} + +func TestValidateWafMetricName(t *testing.T) { + validNames := []string{ + "testrule", + "testRule", + "testRule123", + } + for _, v := range validNames { + _, errors := validateWafMetricName(v, "name") + if len(errors) != 0 { + t.Fatalf("%q should be a valid WAF metric name: %q", v, errors) + } + } + + invalidNames := []string{ + "!", + "/", + " ", + ":", + ";", + "white space", + "/slash-at-the-beginning", + "slash-at-the-end/", + } + for _, v := range invalidNames { + _, errors := validateWafMetricName(v, "name") + if len(errors) == 0 { + t.Fatalf("%q should be an invalid WAF metric name", v) + } + } +} + +func TestValidateIamRoleDescription(t *testing.T) { + validNames := []string{ + "This 1s a D3scr!pti0n with weird content: @ #^ù£ê®æ ø]ŒîÏî~ÈÙ£÷=,ë", + strings.Repeat("W", 1000), + } + for _, v := range validNames { + _, errors := validateIamRoleDescription(v, "description") + if len(errors) != 0 { + t.Fatalf("%q should be a valid IAM Role Description: %q", v, errors) + } + } + + invalidNames := []string{ + strings.Repeat("W", 1001), // > 1000 + } + for _, v := range invalidNames { + _, errors := validateIamRoleDescription(v, "description") + if len(errors) == 0 { + t.Fatalf("%q should be an invalid IAM Role Description", v) + } + } +} diff --git a/builtin/providers/aws/waf_token_handlers.go b/builtin/providers/aws/waf_token_handlers.go new file mode 100644 index 000000000..ac99f0950 --- /dev/null +++ b/builtin/providers/aws/waf_token_handlers.go @@ -0,0 +1,49 @@ +package aws + +import ( + "time" + + "github.com/aws/aws-sdk-go/aws/awserr" + "github.com/aws/aws-sdk-go/service/waf" + "github.com/hashicorp/errwrap" + "github.com/hashicorp/terraform/helper/resource" +) + +type WafRetryer struct { + Connection *waf.WAF + Region string +} + +type withTokenFunc func(token *string) (interface{}, error) + +func (t *WafRetryer) RetryWithToken(f withTokenFunc) (interface{}, error) { + awsMutexKV.Lock(t.Region) + defer awsMutexKV.Unlock(t.Region) + + var out interface{} + err := resource.Retry(15*time.Minute, func() *resource.RetryError { + var err error + var tokenOut *waf.GetChangeTokenOutput + + tokenOut, err = t.Connection.GetChangeToken(&waf.GetChangeTokenInput{}) + if err != nil { + return resource.NonRetryableError(errwrap.Wrapf("Failed to acquire change token: {{err}}", err)) + } + + out, err = f(tokenOut.ChangeToken) + if err != nil { + awsErr, ok := err.(awserr.Error) + if ok && awsErr.Code() == "WAFStaleDataException" { + return resource.RetryableError(err) + } + return resource.NonRetryableError(err) + } + return nil + }) + + return out, err +} + +func newWafRetryer(conn *waf.WAF, region string) *WafRetryer { + return &WafRetryer{Connection: conn, Region: region} +} diff --git a/builtin/providers/aws/wafregionl_token_handlers.go b/builtin/providers/aws/wafregionl_token_handlers.go new file mode 100644 index 000000000..da3d8b58f --- /dev/null +++ b/builtin/providers/aws/wafregionl_token_handlers.go @@ -0,0 +1,50 @@ +package aws + +import ( + "time" + + "github.com/aws/aws-sdk-go/aws/awserr" + "github.com/aws/aws-sdk-go/service/waf" + "github.com/aws/aws-sdk-go/service/wafregional" + "github.com/hashicorp/errwrap" + "github.com/hashicorp/terraform/helper/resource" +) + +type WafRegionalRetryer struct { + Connection *wafregional.WAFRegional + Region string +} + +type withRegionalTokenFunc func(token *string) (interface{}, error) + +func (t *WafRegionalRetryer) RetryWithToken(f withRegionalTokenFunc) (interface{}, error) { + awsMutexKV.Lock(t.Region) + defer awsMutexKV.Unlock(t.Region) + + var out interface{} + err := resource.Retry(15*time.Minute, func() *resource.RetryError { + var err error + var tokenOut *waf.GetChangeTokenOutput + + tokenOut, err = t.Connection.GetChangeToken(&waf.GetChangeTokenInput{}) + if err != nil { + return resource.NonRetryableError(errwrap.Wrapf("Failed to acquire change token: {{err}}", err)) + } + + out, err = f(tokenOut.ChangeToken) + if err != nil { + awsErr, ok := err.(awserr.Error) + if ok && awsErr.Code() == "WAFStaleDataException" { + return resource.RetryableError(err) + } + return resource.NonRetryableError(err) + } + return nil + }) + + return out, err +} + +func newWafRegionalRetryer(conn *wafregional.WAFRegional, region string) *WafRegionalRetryer { + return &WafRegionalRetryer{Connection: conn, Region: region} +} diff --git a/builtin/providers/azurerm/config.go b/builtin/providers/azurerm/config.go index bbf15712f..80e2d5bb8 100644 --- a/builtin/providers/azurerm/config.go +++ b/builtin/providers/azurerm/config.go @@ -11,6 +11,7 @@ import ( "github.com/Azure/azure-sdk-for-go/arm/compute" "github.com/Azure/azure-sdk-for-go/arm/containerregistry" "github.com/Azure/azure-sdk-for-go/arm/containerservice" + "github.com/Azure/azure-sdk-for-go/arm/disk" "github.com/Azure/azure-sdk-for-go/arm/eventhub" "github.com/Azure/azure-sdk-for-go/arm/keyvault" "github.com/Azure/azure-sdk-for-go/arm/network" @@ -18,6 +19,7 @@ import ( "github.com/Azure/azure-sdk-for-go/arm/resources/resources" "github.com/Azure/azure-sdk-for-go/arm/scheduler" "github.com/Azure/azure-sdk-for-go/arm/servicebus" + "github.com/Azure/azure-sdk-for-go/arm/sql" "github.com/Azure/azure-sdk-for-go/arm/storage" "github.com/Azure/azure-sdk-for-go/arm/trafficmanager" mainStorage "github.com/Azure/azure-sdk-for-go/storage" @@ -47,8 +49,11 @@ type ArmClient struct { vmImageClient compute.VirtualMachineImagesClient vmClient compute.VirtualMachinesClient + diskClient disk.DisksClient + appGatewayClient network.ApplicationGatewaysClient ifaceClient network.InterfacesClient + expressRouteCircuitClient network.ExpressRouteCircuitsClient loadBalancerClient network.LoadBalancersClient localNetConnClient network.LocalNetworkGatewaysClient publicIPClient network.PublicIPAddressesClient @@ -96,6 +101,8 @@ type ArmClient struct { serviceBusSubscriptionsClient servicebus.SubscriptionsClient keyVaultClient keyvault.VaultsClient + + sqlElasticPoolsClient sql.ElasticPoolsClient } func withRequestLogging() autorest.SendDecorator { @@ -245,6 +252,12 @@ func (c *Config) getArmClient() (*ArmClient, error) { csc.Sender = autorest.CreateSender(withRequestLogging()) client.containerServicesClient = csc + dkc := disk.NewDisksClientWithBaseURI(endpoint, c.SubscriptionID) + setUserAgent(&dkc.Client) + dkc.Authorizer = spt + dkc.Sender = autorest.CreateSender(withRequestLogging()) + client.diskClient = dkc + ehc := eventhub.NewEventHubsClientWithBaseURI(endpoint, c.SubscriptionID) setUserAgent(&ehc.Client) ehc.Authorizer = spt @@ -269,6 +282,12 @@ func (c *Config) getArmClient() (*ArmClient, error) { ifc.Sender = autorest.CreateSender(withRequestLogging()) client.ifaceClient = ifc + erc := network.NewExpressRouteCircuitsClientWithBaseURI(endpoint, c.SubscriptionID) + setUserAgent(&erc.Client) + erc.Authorizer = spt + erc.Sender = autorest.CreateSender(withRequestLogging()) + client.expressRouteCircuitClient = erc + lbc := network.NewLoadBalancersClientWithBaseURI(endpoint, c.SubscriptionID) setUserAgent(&lbc.Client) lbc.Authorizer = spt @@ -449,6 +468,12 @@ func (c *Config) getArmClient() (*ArmClient, error) { kvc.Sender = autorest.CreateSender(withRequestLogging()) client.keyVaultClient = kvc + sqlepc := sql.NewElasticPoolsClientWithBaseURI(endpoint, c.SubscriptionID) + setUserAgent(&sqlepc.Client) + sqlepc.Authorizer = spt + sqlepc.Sender = autorest.CreateSender(withRequestLogging()) + client.sqlElasticPoolsClient = sqlepc + return &client, nil } diff --git a/builtin/providers/azurerm/express_route_circuit.go b/builtin/providers/azurerm/express_route_circuit.go new file mode 100644 index 000000000..297b55f56 --- /dev/null +++ b/builtin/providers/azurerm/express_route_circuit.go @@ -0,0 +1,40 @@ +package azurerm + +import ( + "fmt" + "net/http" + + "github.com/Azure/azure-sdk-for-go/arm/network" + "github.com/hashicorp/errwrap" +) + +func extractResourceGroupAndErcName(resourceId string) (resourceGroup string, name string, err error) { + id, err := parseAzureResourceID(resourceId) + + if err != nil { + return "", "", err + } + resourceGroup = id.ResourceGroup + name = id.Path["expressRouteCircuits"] + + return +} + +func retrieveErcByResourceId(resourceId string, meta interface{}) (erc *network.ExpressRouteCircuit, resourceGroup string, e error) { + ercClient := meta.(*ArmClient).expressRouteCircuitClient + + resGroup, name, err := extractResourceGroupAndErcName(resourceId) + if err != nil { + return nil, "", errwrap.Wrapf("Error Parsing Azure Resource ID - {{err}}", err) + } + + resp, err := ercClient.Get(resGroup, name) + if err != nil { + if resp.StatusCode == http.StatusNotFound { + return nil, "", nil + } + return nil, "", errwrap.Wrapf(fmt.Sprintf("Error making Read request on Express Route Circuit %s: {{err}}", name), err) + } + + return &resp, resGroup, nil +} diff --git a/builtin/providers/azurerm/import_arm_express_route_circuit_test.go b/builtin/providers/azurerm/import_arm_express_route_circuit_test.go new file mode 100644 index 000000000..3e887c44f --- /dev/null +++ b/builtin/providers/azurerm/import_arm_express_route_circuit_test.go @@ -0,0 +1,29 @@ +package azurerm + +import ( + "testing" + + "github.com/hashicorp/terraform/helper/acctest" + "github.com/hashicorp/terraform/helper/resource" +) + +func TestAccAzureRMExpressRouteCircuit_importBasic(t *testing.T) { + resourceName := "azurerm_express_route_circuit.test" + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testCheckAzureRMExpressRouteCircuitDestroy, + Steps: []resource.TestStep{ + resource.TestStep{ + Config: testAccAzureRMExpressRouteCircuit_basic(acctest.RandInt()), + }, + + resource.TestStep{ + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} diff --git a/builtin/providers/azurerm/import_arm_managed_disk_test.go b/builtin/providers/azurerm/import_arm_managed_disk_test.go new file mode 100644 index 000000000..51eaa6abd --- /dev/null +++ b/builtin/providers/azurerm/import_arm_managed_disk_test.go @@ -0,0 +1,30 @@ +package azurerm + +import ( + "fmt" + "testing" + + "github.com/hashicorp/terraform/helper/acctest" + "github.com/hashicorp/terraform/helper/resource" +) + +func TestAccAzureRMManagedDisk_importEmpty(t *testing.T) { + ri := acctest.RandInt() + config := fmt.Sprintf(testAccAzureRMManagedDisk_empty, ri, ri) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testCheckAzureRMManagedDiskDestroy, + Steps: []resource.TestStep{ + { + Config: config, + }, + { + ResourceName: "azurerm_managed_disk.test", + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} diff --git a/builtin/providers/azurerm/import_arm_sql_elasticpool_test.go b/builtin/providers/azurerm/import_arm_sql_elasticpool_test.go new file mode 100644 index 000000000..1657f5c15 --- /dev/null +++ b/builtin/providers/azurerm/import_arm_sql_elasticpool_test.go @@ -0,0 +1,32 @@ +package azurerm + +import ( + "fmt" + "github.com/hashicorp/terraform/helper/acctest" + "github.com/hashicorp/terraform/helper/resource" + "testing" +) + +func TestAccAzureRMSqlElasticPool_importBasic(t *testing.T) { + resourceName := "azurerm_sql_elasticpool.test" + + ri := acctest.RandInt() + config := fmt.Sprintf(testAccAzureRMSqlElasticPool_basic, ri) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testCheckAzureRMSqlElasticPoolDestroy, + Steps: []resource.TestStep{ + resource.TestStep{ + Config: config, + }, + + resource.TestStep{ + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} diff --git a/builtin/providers/azurerm/import_arm_subnet_test.go b/builtin/providers/azurerm/import_arm_subnet_test.go index 90cf28fe5..8384d8b3f 100644 --- a/builtin/providers/azurerm/import_arm_subnet_test.go +++ b/builtin/providers/azurerm/import_arm_subnet_test.go @@ -12,7 +12,7 @@ func TestAccAzureRMSubnet_importBasic(t *testing.T) { resourceName := "azurerm_subnet.test" ri := acctest.RandInt() - config := fmt.Sprintf(testAccAzureRMSubnet_basic, ri, ri, ri) + config := fmt.Sprintf(testAccAzureRMSubnet_basic, ri, ri, ri, ri, ri) resource.Test(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, diff --git a/builtin/providers/azurerm/import_arm_virtual_machine_scale_set_test.go b/builtin/providers/azurerm/import_arm_virtual_machine_scale_set_test.go new file mode 100644 index 000000000..a8c6602ab --- /dev/null +++ b/builtin/providers/azurerm/import_arm_virtual_machine_scale_set_test.go @@ -0,0 +1,158 @@ +package azurerm + +import ( + "fmt" + "testing" + + "github.com/hashicorp/terraform/helper/acctest" + "github.com/hashicorp/terraform/helper/resource" +) + +func TestAccAzureRMVirtualMachineScaleSet_importBasic(t *testing.T) { + resourceName := "azurerm_virtual_machine_scale_set.test" + + ri := acctest.RandInt() + config := fmt.Sprintf(testAccAzureRMVirtualMachineScaleSet_basic, ri, ri, ri, ri, ri, ri, ri, ri) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testCheckAzureRMVirtualMachineScaleSetDestroy, + Steps: []resource.TestStep{ + { + Config: config, + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func TestAccAzureRMVirtualMachineScaleSet_importBasic_managedDisk(t *testing.T) { + resourceName := "azurerm_virtual_machine_scale_set.test" + + ri := acctest.RandInt() + config := fmt.Sprintf(testAccAzureRMVirtualMachineScaleSet_basicLinux_managedDisk, ri, ri, ri, ri, ri, ri) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testCheckAzureRMVirtualMachineScaleSetDestroy, + Steps: []resource.TestStep{ + { + Config: config, + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func TestAccAzureRMVirtualMachineScaleSet_importLinux(t *testing.T) { + resourceName := "azurerm_virtual_machine_scale_set.test" + + ri := acctest.RandInt() + config := testAccAzureRMVirtualMachineScaleSet_linux(ri) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testCheckAzureRMVirtualMachineScaleSetDestroy, + Steps: []resource.TestStep{ + { + Config: config, + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func TestAccAzureRMVirtualMachineScaleSet_importLoadBalancer(t *testing.T) { + resourceName := "azurerm_virtual_machine_scale_set.test" + + ri := acctest.RandInt() + config := fmt.Sprintf(testAccAzureRMVirtualMachineScaleSetLoadbalancerTemplate, ri, ri, ri, ri, ri, ri, ri) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testCheckAzureRMVirtualMachineScaleSetDestroy, + Steps: []resource.TestStep{ + { + Config: config, + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func TestAccAzureRMVirtualMachineScaleSet_importOverProvision(t *testing.T) { + ri := acctest.RandInt() + config := fmt.Sprintf(testAccAzureRMVirtualMachineScaleSetOverprovisionTemplate, ri, ri, ri, ri, ri, ri) + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testCheckAzureRMVirtualMachineScaleSetDestroy, + Steps: []resource.TestStep{ + { + Config: config, + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMVirtualMachineScaleSetExists("azurerm_virtual_machine_scale_set.test"), + testCheckAzureRMVirtualMachineScaleSetOverprovision("azurerm_virtual_machine_scale_set.test"), + ), + }, + }, + }) +} + +func TestAccAzureRMVirtualMachineScaleSet_importExtension(t *testing.T) { + ri := acctest.RandInt() + config := fmt.Sprintf(testAccAzureRMVirtualMachineScaleSetExtensionTemplate, ri, ri, ri, ri, ri, ri) + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testCheckAzureRMVirtualMachineScaleSetDestroy, + Steps: []resource.TestStep{ + { + Config: config, + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMVirtualMachineScaleSetExists("azurerm_virtual_machine_scale_set.test"), + testCheckAzureRMVirtualMachineScaleSetExtension("azurerm_virtual_machine_scale_set.test"), + ), + }, + }, + }) +} + +func TestAccAzureRMVirtualMachineScaleSet_importMultipleExtensions(t *testing.T) { + ri := acctest.RandInt() + config := fmt.Sprintf(testAccAzureRMVirtualMachineScaleSetMultipleExtensionsTemplate, ri, ri, ri, ri, ri, ri) + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testCheckAzureRMVirtualMachineScaleSetDestroy, + Steps: []resource.TestStep{ + { + Config: config, + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMVirtualMachineScaleSetExists("azurerm_virtual_machine_scale_set.test"), + testCheckAzureRMVirtualMachineScaleSetExtension("azurerm_virtual_machine_scale_set.test"), + ), + }, + }, + }) +} diff --git a/builtin/providers/azurerm/import_arm_virtual_machine_test.go b/builtin/providers/azurerm/import_arm_virtual_machine_test.go index 806d44987..f6b72e208 100644 --- a/builtin/providers/azurerm/import_arm_virtual_machine_test.go +++ b/builtin/providers/azurerm/import_arm_virtual_machine_test.go @@ -19,11 +19,39 @@ func TestAccAzureRMVirtualMachine_importBasic(t *testing.T) { Providers: testAccProviders, CheckDestroy: testCheckAzureRMVirtualMachineDestroy, Steps: []resource.TestStep{ - resource.TestStep{ + { Config: config, }, - resource.TestStep{ + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{ + "delete_data_disks_on_termination", + "delete_os_disk_on_termination", + }, + }, + }, + }) +} + +func TestAccAzureRMVirtualMachine_importBasic_managedDisk(t *testing.T) { + resourceName := "azurerm_virtual_machine.test" + + ri := acctest.RandInt() + config := fmt.Sprintf(testAccAzureRMVirtualMachine_basicLinuxMachine_managedDisk_explicit, ri, ri, ri, ri, ri, ri, ri) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testCheckAzureRMVirtualMachineDestroy, + Steps: []resource.TestStep{ + { + Config: config, + }, + + { ResourceName: resourceName, ImportState: true, ImportStateVerify: true, diff --git a/builtin/providers/azurerm/locks.go b/builtin/providers/azurerm/locks.go new file mode 100644 index 000000000..ee6774af6 --- /dev/null +++ b/builtin/providers/azurerm/locks.go @@ -0,0 +1,12 @@ +package azurerm + +func azureRMUnlockMultiple(names *[]string) { + for _, name := range *names { + armMutexKV.Unlock(name) + } +} +func azureRMLockMultiple(names *[]string) { + for _, name := range *names { + armMutexKV.Lock(name) + } +} diff --git a/builtin/providers/azurerm/provider.go b/builtin/providers/azurerm/provider.go index 8364fe4cf..220b34d99 100644 --- a/builtin/providers/azurerm/provider.go +++ b/builtin/providers/azurerm/provider.go @@ -78,6 +78,8 @@ func Provider() terraform.ResourceProvider { "azurerm_eventhub_consumer_group": resourceArmEventHubConsumerGroup(), "azurerm_eventhub_namespace": resourceArmEventHubNamespace(), + "azurerm_express_route_circuit": resourceArmExpressRouteCircuit(), + "azurerm_lb": resourceArmLoadBalancer(), "azurerm_lb_backend_address_pool": resourceArmLoadBalancerBackendAddressPool(), "azurerm_lb_nat_rule": resourceArmLoadBalancerNatRule(), @@ -85,6 +87,8 @@ func Provider() terraform.ResourceProvider { "azurerm_lb_probe": resourceArmLoadBalancerProbe(), "azurerm_lb_rule": resourceArmLoadBalancerRule(), + "azurerm_managed_disk": resourceArmManagedDisk(), + "azurerm_key_vault": resourceArmKeyVault(), "azurerm_local_network_gateway": resourceArmLocalNetworkGateway(), "azurerm_network_interface": resourceArmNetworkInterface(), @@ -97,6 +101,7 @@ func Provider() terraform.ResourceProvider { "azurerm_servicebus_namespace": resourceArmServiceBusNamespace(), "azurerm_servicebus_subscription": resourceArmServiceBusSubscription(), "azurerm_servicebus_topic": resourceArmServiceBusTopic(), + "azurerm_sql_elasticpool": resourceArmSqlElasticPool(), "azurerm_storage_account": resourceArmStorageAccount(), "azurerm_storage_blob": resourceArmStorageBlob(), "azurerm_storage_container": resourceArmStorageContainer(), @@ -344,7 +349,7 @@ func userDataStateFunc(v interface{}) string { } } -// Base64Encode encodes data if the input isn't already encoded using +// base64Encode encodes data if the input isn't already encoded using // base64.StdEncoding.EncodeToString. If the input is already base64 encoded, // return the original input unchanged. func base64Encode(data string) string { diff --git a/builtin/providers/azurerm/resource_arm_eventhub_authorization_rule.go b/builtin/providers/azurerm/resource_arm_eventhub_authorization_rule.go index 4b3f1fc81..f6f081677 100644 --- a/builtin/providers/azurerm/resource_arm_eventhub_authorization_rule.go +++ b/builtin/providers/azurerm/resource_arm_eventhub_authorization_rule.go @@ -45,11 +45,7 @@ func resourceArmEventHubAuthorizationRule() *schema.Resource { ForceNew: true, }, - "location": { - Type: schema.TypeString, - Required: true, - ForceNew: true, - }, + "location": locationSchema(), "listen": { Type: schema.TypeBool, @@ -148,7 +144,7 @@ func resourceArmEventHubAuthorizationRuleRead(d *schema.ResourceData, meta inter resp, err := client.GetAuthorizationRule(resGroup, namespaceName, eventHubName, name) if err != nil { - return fmt.Errorf("Error making Read request on Azure EventHub Authorization Rule %s: %s", name, err) + return fmt.Errorf("Error making Read request on Azure EventHub Authorization Rule %s: %+v", name, err) } if resp.StatusCode == http.StatusNotFound { d.SetId("") @@ -157,7 +153,7 @@ func resourceArmEventHubAuthorizationRuleRead(d *schema.ResourceData, meta inter keysResp, err := client.ListKeys(resGroup, namespaceName, eventHubName, name) if err != nil { - return fmt.Errorf("Error making Read request on Azure EventHub Authorization Rule List Keys %s: %s", name, err) + return fmt.Errorf("Error making Read request on Azure EventHub Authorization Rule List Keys %s: %+v", name, err) } d.Set("name", name) @@ -191,7 +187,7 @@ func resourceArmEventHubAuthorizationRuleDelete(d *schema.ResourceData, meta int resp, err := eventhubClient.DeleteAuthorizationRule(resGroup, namespaceName, eventHubName, name) if resp.StatusCode != http.StatusOK { - return fmt.Errorf("Error issuing Azure ARM delete request of EventHub Authorization Rule '%s': %s", name, err) + return fmt.Errorf("Error issuing Azure ARM delete request of EventHub Authorization Rule '%s': %+v", name, err) } return nil diff --git a/builtin/providers/azurerm/resource_arm_eventhub_consumer_group.go b/builtin/providers/azurerm/resource_arm_eventhub_consumer_group.go index 648fc761c..f098ff808 100644 --- a/builtin/providers/azurerm/resource_arm_eventhub_consumer_group.go +++ b/builtin/providers/azurerm/resource_arm_eventhub_consumer_group.go @@ -45,11 +45,7 @@ func resourceArmEventHubConsumerGroup() *schema.Resource { ForceNew: true, }, - "location": { - Type: schema.TypeString, - Required: true, - ForceNew: true, - }, + "location": locationSchema(), "user_metadata": { Type: schema.TypeString, @@ -113,7 +109,7 @@ func resourceArmEventHubConsumerGroupRead(d *schema.ResourceData, meta interface resp, err := eventhubClient.Get(resGroup, namespaceName, eventHubName, name) if err != nil { - return fmt.Errorf("Error making Read request on Azure EventHub Consumer Group %s: %s", name, err) + return fmt.Errorf("Error making Read request on Azure EventHub Consumer Group %s: %+v", name, err) } if resp.StatusCode == http.StatusNotFound { d.SetId("") @@ -145,7 +141,7 @@ func resourceArmEventHubConsumerGroupDelete(d *schema.ResourceData, meta interfa resp, err := eventhubClient.Delete(resGroup, namespaceName, eventHubName, name) if resp.StatusCode != http.StatusOK { - return fmt.Errorf("Error issuing Azure ARM delete request of EventHub Consumer Group '%s': %s", name, err) + return fmt.Errorf("Error issuing Azure ARM delete request of EventHub Consumer Group '%s': %+v", name, err) } return nil diff --git a/builtin/providers/azurerm/resource_arm_eventhub_namespace.go b/builtin/providers/azurerm/resource_arm_eventhub_namespace.go index e03281e22..d39016799 100644 --- a/builtin/providers/azurerm/resource_arm_eventhub_namespace.go +++ b/builtin/providers/azurerm/resource_arm_eventhub_namespace.go @@ -131,7 +131,7 @@ func resourceArmEventHubNamespaceRead(d *schema.ResourceData, meta interface{}) resp, err := namespaceClient.Get(resGroup, name) if err != nil { - return fmt.Errorf("Error making Read request on Azure EventHub Namespace %s: %s", name, err) + return fmt.Errorf("Error making Read request on Azure EventHub Namespace %s: %+v", name, err) } if resp.StatusCode == http.StatusNotFound { d.SetId("") @@ -146,7 +146,7 @@ func resourceArmEventHubNamespaceRead(d *schema.ResourceData, meta interface{}) keys, err := namespaceClient.ListKeys(resGroup, name, eventHubNamespaceDefaultAuthorizationRule) if err != nil { - log.Printf("[ERROR] Unable to List default keys for Namespace %s: %s", name, err) + log.Printf("[ERROR] Unable to List default keys for Namespace %s: %+v", name, err) } else { d.Set("default_primary_connection_string", keys.PrimaryConnectionString) d.Set("default_secondary_connection_string", keys.SecondaryConnectionString) @@ -160,7 +160,6 @@ func resourceArmEventHubNamespaceRead(d *schema.ResourceData, meta interface{}) } func resourceArmEventHubNamespaceDelete(d *schema.ResourceData, meta interface{}) error { - namespaceClient := meta.(*ArmClient).eventHubNamespacesClient id, err := parseAzureResourceID(d.Id()) @@ -173,7 +172,7 @@ func resourceArmEventHubNamespaceDelete(d *schema.ResourceData, meta interface{} resp, err := namespaceClient.Delete(resGroup, name, make(chan struct{})) if resp.StatusCode != http.StatusNotFound { - return fmt.Errorf("Error issuing Azure ARM delete request of EventHub Namespace'%s': %s", name, err) + return fmt.Errorf("Error issuing Azure ARM delete request of EventHub Namespace '%s': %+v", name, err) } return nil diff --git a/builtin/providers/azurerm/resource_arm_express_route_circuit.go b/builtin/providers/azurerm/resource_arm_express_route_circuit.go new file mode 100644 index 000000000..3f17fff79 --- /dev/null +++ b/builtin/providers/azurerm/resource_arm_express_route_circuit.go @@ -0,0 +1,240 @@ +package azurerm + +import ( + "bytes" + "log" + "strings" + + "fmt" + + "github.com/Azure/azure-sdk-for-go/arm/network" + "github.com/hashicorp/errwrap" + "github.com/hashicorp/terraform/helper/hashcode" + "github.com/hashicorp/terraform/helper/schema" + "github.com/hashicorp/terraform/helper/validation" +) + +func resourceArmExpressRouteCircuit() *schema.Resource { + return &schema.Resource{ + Create: resourceArmExpressRouteCircuitCreateOrUpdate, + Read: resourceArmExpressRouteCircuitRead, + Update: resourceArmExpressRouteCircuitCreateOrUpdate, + Delete: resourceArmExpressRouteCircuitDelete, + Importer: &schema.ResourceImporter{ + State: schema.ImportStatePassthrough, + }, + + Schema: map[string]*schema.Schema{ + "name": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + + "resource_group_name": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + + "location": locationSchema(), + + "service_provider_name": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + DiffSuppressFunc: ignoreCaseDiffSuppressFunc, + }, + + "peering_location": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + DiffSuppressFunc: ignoreCaseDiffSuppressFunc, + }, + + "bandwidth_in_mbps": { + Type: schema.TypeInt, + Required: true, + }, + + "sku": { + Type: schema.TypeSet, + Required: true, + MinItems: 1, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "tier": { + Type: schema.TypeString, + Required: true, + ValidateFunc: validation.StringInSlice([]string{ + string(network.ExpressRouteCircuitSkuTierStandard), + string(network.ExpressRouteCircuitSkuTierPremium), + }, true), + DiffSuppressFunc: ignoreCaseDiffSuppressFunc, + }, + + "family": { + Type: schema.TypeString, + Required: true, + ValidateFunc: validation.StringInSlice([]string{ + string(network.MeteredData), + string(network.UnlimitedData), + }, true), + DiffSuppressFunc: ignoreCaseDiffSuppressFunc, + }, + }, + }, + Set: resourceArmExpressRouteCircuitSkuHash, + }, + + "allow_classic_operations": { + Type: schema.TypeBool, + Optional: true, + Default: false, + }, + + "service_provider_provisioning_state": { + Type: schema.TypeString, + Computed: true, + }, + + "service_key": { + Type: schema.TypeString, + Computed: true, + }, + + "tags": tagsSchema(), + }, + } +} + +func resourceArmExpressRouteCircuitCreateOrUpdate(d *schema.ResourceData, meta interface{}) error { + client := meta.(*ArmClient) + ercClient := client.expressRouteCircuitClient + + log.Printf("[INFO] preparing arguments for Azure ARM ExpressRouteCircuit creation.") + + name := d.Get("name").(string) + resGroup := d.Get("resource_group_name").(string) + location := d.Get("location").(string) + serviceProviderName := d.Get("service_provider_name").(string) + peeringLocation := d.Get("peering_location").(string) + bandwidthInMbps := int32(d.Get("bandwidth_in_mbps").(int)) + sku := expandExpressRouteCircuitSku(d) + allowRdfeOps := d.Get("allow_classic_operations").(bool) + tags := d.Get("tags").(map[string]interface{}) + expandedTags := expandTags(tags) + + erc := network.ExpressRouteCircuit{ + Name: &name, + Location: &location, + Sku: sku, + ExpressRouteCircuitPropertiesFormat: &network.ExpressRouteCircuitPropertiesFormat{ + AllowClassicOperations: &allowRdfeOps, + ServiceProviderProperties: &network.ExpressRouteCircuitServiceProviderProperties{ + ServiceProviderName: &serviceProviderName, + PeeringLocation: &peeringLocation, + BandwidthInMbps: &bandwidthInMbps, + }, + }, + Tags: expandedTags, + } + + _, err := ercClient.CreateOrUpdate(resGroup, name, erc, make(chan struct{})) + if err != nil { + return errwrap.Wrapf("Error Creating/Updating ExpressRouteCircuit {{err}}", err) + } + + read, err := ercClient.Get(resGroup, name) + if err != nil { + return errwrap.Wrapf("Error Getting ExpressRouteCircuit {{err}}", err) + } + if read.ID == nil { + return fmt.Errorf("Cannot read ExpressRouteCircuit %s (resource group %s) ID", name, resGroup) + } + + d.SetId(*read.ID) + + return resourceArmExpressRouteCircuitRead(d, meta) +} + +func resourceArmExpressRouteCircuitRead(d *schema.ResourceData, meta interface{}) error { + erc, resGroup, err := retrieveErcByResourceId(d.Id(), meta) + if err != nil { + return err + } + + if erc == nil { + d.SetId("") + log.Printf("[INFO] Express Route Circuit %q not found. Removing from state", d.Get("name").(string)) + return nil + } + + d.Set("name", erc.Name) + d.Set("resource_group_name", resGroup) + d.Set("location", erc.Location) + + if erc.ServiceProviderProperties != nil { + d.Set("service_provider_name", erc.ServiceProviderProperties.ServiceProviderName) + d.Set("peering_location", erc.ServiceProviderProperties.PeeringLocation) + d.Set("bandwidth_in_mbps", erc.ServiceProviderProperties.BandwidthInMbps) + } + + if erc.Sku != nil { + d.Set("sku", schema.NewSet(resourceArmExpressRouteCircuitSkuHash, flattenExpressRouteCircuitSku(erc.Sku))) + } + + d.Set("service_provider_provisioning_state", string(erc.ServiceProviderProvisioningState)) + d.Set("service_key", erc.ServiceKey) + d.Set("allow_classic_operations", erc.AllowClassicOperations) + + flattenAndSetTags(d, erc.Tags) + + return nil +} + +func resourceArmExpressRouteCircuitDelete(d *schema.ResourceData, meta interface{}) error { + ercClient := meta.(*ArmClient).expressRouteCircuitClient + + resGroup, name, err := extractResourceGroupAndErcName(d.Id()) + if err != nil { + return errwrap.Wrapf("Error Parsing Azure Resource ID {{err}}", err) + } + + _, err = ercClient.Delete(resGroup, name, make(chan struct{})) + return err +} + +func expandExpressRouteCircuitSku(d *schema.ResourceData) *network.ExpressRouteCircuitSku { + skuSettings := d.Get("sku").(*schema.Set) + v := skuSettings.List()[0].(map[string]interface{}) // [0] is guarded by MinItems in schema. + tier := v["tier"].(string) + family := v["family"].(string) + name := fmt.Sprintf("%s_%s", tier, family) + + return &network.ExpressRouteCircuitSku{ + Name: &name, + Tier: network.ExpressRouteCircuitSkuTier(tier), + Family: network.ExpressRouteCircuitSkuFamily(family), + } +} + +func flattenExpressRouteCircuitSku(sku *network.ExpressRouteCircuitSku) []interface{} { + return []interface{}{ + map[string]interface{}{ + "tier": string(sku.Tier), + "family": string(sku.Family), + }, + } +} + +func resourceArmExpressRouteCircuitSkuHash(v interface{}) int { + var buf bytes.Buffer + m := v.(map[string]interface{}) + buf.WriteString(fmt.Sprintf("%s-", strings.ToLower(m["tier"].(string)))) + buf.WriteString(fmt.Sprintf("%s-", strings.ToLower(m["family"].(string)))) + + return hashcode.String(buf.String()) +} diff --git a/builtin/providers/azurerm/resource_arm_express_route_circuit_test.go b/builtin/providers/azurerm/resource_arm_express_route_circuit_test.go new file mode 100644 index 000000000..24c6c7fae --- /dev/null +++ b/builtin/providers/azurerm/resource_arm_express_route_circuit_test.go @@ -0,0 +1,113 @@ +package azurerm + +import ( + "fmt" + "net/http" + "testing" + + "github.com/Azure/azure-sdk-for-go/arm/network" + "github.com/hashicorp/terraform/helper/acctest" + "github.com/hashicorp/terraform/helper/resource" + "github.com/hashicorp/terraform/terraform" +) + +func TestAccAzureRMExpressRouteCircuit_basic(t *testing.T) { + var erc network.ExpressRouteCircuit + ri := acctest.RandInt() + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testCheckAzureRMExpressRouteCircuitDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAzureRMExpressRouteCircuit_basic(ri), + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMExpressRouteCircuitExists("azurerm_express_route_circuit.test", &erc), + ), + }, + }, + }) +} + +func testCheckAzureRMExpressRouteCircuitExists(name string, erc *network.ExpressRouteCircuit) resource.TestCheckFunc { + return func(s *terraform.State) error { + rs, ok := s.RootModule().Resources[name] + if !ok { + return fmt.Errorf("Not found: %s", name) + } + + expressRouteCircuitName := rs.Primary.Attributes["name"] + resourceGroup, hasResourceGroup := rs.Primary.Attributes["resource_group_name"] + if !hasResourceGroup { + return fmt.Errorf("Bad: no resource group found in state for Express Route Circuit: %s", expressRouteCircuitName) + } + + conn := testAccProvider.Meta().(*ArmClient).expressRouteCircuitClient + + resp, err := conn.Get(resourceGroup, expressRouteCircuitName) + if err != nil { + if resp.StatusCode == http.StatusNotFound { + return fmt.Errorf("Bad: Express Route Circuit %q (resource group: %q) does not exist", expressRouteCircuitName, resourceGroup) + } + + return fmt.Errorf("Bad: Get on expressRouteCircuitClient: %s", err) + } + + *erc = resp + + return nil + } +} + +func testCheckAzureRMExpressRouteCircuitDestroy(s *terraform.State) error { + conn := testAccProvider.Meta().(*ArmClient).expressRouteCircuitClient + + for _, rs := range s.RootModule().Resources { + if rs.Type != "azurerm_express_route_circuit" { + continue + } + + name := rs.Primary.Attributes["name"] + resourceGroup := rs.Primary.Attributes["resource_group_name"] + + resp, err := conn.Get(resourceGroup, name) + + if err != nil { + return nil + } + + if resp.StatusCode != http.StatusNotFound { + return fmt.Errorf("Express Route Circuit still exists:\n%#v", resp.ExpressRouteCircuitPropertiesFormat) + } + } + + return nil +} + +func testAccAzureRMExpressRouteCircuit_basic(rInt int) string { + return fmt.Sprintf(` + resource "azurerm_resource_group" "test" { + name = "acctestrg-%d" + location = "West US" + } + + resource "azurerm_express_route_circuit" "test" { + name = "acctest-erc-%[1]d" + location = "West US" + resource_group_name = "${azurerm_resource_group.test.name}" + service_provider_name = "Equinix" + peering_location = "Silicon Valley" + bandwidth_in_mbps = 50 + sku { + tier = "Standard" + family = "MeteredData" + } + allow_classic_operations = false + + tags { + Environment = "production" + Purpose = "AcceptanceTests" + } + }`, rInt) +} diff --git a/builtin/providers/azurerm/resource_arm_loadbalancer.go b/builtin/providers/azurerm/resource_arm_loadbalancer.go index 60bb95990..940b3fb98 100644 --- a/builtin/providers/azurerm/resource_arm_loadbalancer.go +++ b/builtin/providers/azurerm/resource_arm_loadbalancer.go @@ -92,6 +92,11 @@ func resourceArmLoadBalancer() *schema.Resource { }, }, + "private_ip_address": { + Type: schema.TypeString, + Computed: true, + }, + "tags": tagsSchema(), }, } @@ -172,7 +177,17 @@ func resourecArmLoadBalancerRead(d *schema.ResourceData, meta interface{}) error d.Set("resource_group_name", id.ResourceGroup) if loadBalancer.LoadBalancerPropertiesFormat != nil && loadBalancer.LoadBalancerPropertiesFormat.FrontendIPConfigurations != nil { - d.Set("frontend_ip_configuration", flattenLoadBalancerFrontendIpConfiguration(loadBalancer.LoadBalancerPropertiesFormat.FrontendIPConfigurations)) + ipconfigs := loadBalancer.LoadBalancerPropertiesFormat.FrontendIPConfigurations + d.Set("frontend_ip_configuration", flattenLoadBalancerFrontendIpConfiguration(ipconfigs)) + + for _, config := range *ipconfigs { + if config.FrontendIPConfigurationPropertiesFormat.PrivateIPAddress != nil { + d.Set("private_ip_address", config.FrontendIPConfigurationPropertiesFormat.PrivateIPAddress) + + // set the private IP address at most once + break + } + } } flattenAndSetTags(d, loadBalancer.Tags) diff --git a/builtin/providers/azurerm/resource_arm_local_network_gateway.go b/builtin/providers/azurerm/resource_arm_local_network_gateway.go index 6287f0ce2..64c2243fb 100644 --- a/builtin/providers/azurerm/resource_arm_local_network_gateway.go +++ b/builtin/providers/azurerm/resource_arm_local_network_gateway.go @@ -101,6 +101,9 @@ func resourceArmLocalNetworkGatewayRead(d *schema.ResourceData, meta interface{} return err } name := id.Path["localNetworkGateways"] + if name == "" { + return fmt.Errorf("Cannot find 'localNetworkGateways' in '%s', make sure it is specified in the ID parameter", d.Id()) + } resGroup := id.ResourceGroup resp, err := lnetClient.Get(resGroup, name) diff --git a/builtin/providers/azurerm/resource_arm_managed_disk.go b/builtin/providers/azurerm/resource_arm_managed_disk.go new file mode 100644 index 000000000..9f3fdc4c5 --- /dev/null +++ b/builtin/providers/azurerm/resource_arm_managed_disk.go @@ -0,0 +1,238 @@ +package azurerm + +import ( + "fmt" + "github.com/Azure/azure-sdk-for-go/arm/disk" + "github.com/hashicorp/terraform/helper/schema" + "github.com/hashicorp/terraform/helper/validation" + "log" + "net/http" + "strings" +) + +func resourceArmManagedDisk() *schema.Resource { + return &schema.Resource{ + Create: resourceArmManagedDiskCreate, + Read: resourceArmManagedDiskRead, + Update: resourceArmManagedDiskCreate, + Delete: resourceArmManagedDiskDelete, + Importer: &schema.ResourceImporter{ + State: schema.ImportStatePassthrough, + }, + + Schema: map[string]*schema.Schema{ + "name": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + + "location": locationSchema(), + + "resource_group_name": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + + "storage_account_type": { + Type: schema.TypeString, + Required: true, + ValidateFunc: validation.StringInSlice([]string{ + string(disk.PremiumLRS), + string(disk.StandardLRS), + }, true), + }, + + "create_option": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + ValidateFunc: validation.StringInSlice([]string{ + string(disk.Import), + string(disk.Empty), + string(disk.Copy), + }, true), + }, + + "source_uri": { + Type: schema.TypeString, + Optional: true, + Computed: true, + ForceNew: true, + }, + + "source_resource_id": { + Type: schema.TypeString, + Optional: true, + ForceNew: true, + }, + + "os_type": { + Type: schema.TypeString, + Optional: true, + ValidateFunc: validation.StringInSlice([]string{ + string(disk.Windows), + string(disk.Linux), + }, true), + }, + + "disk_size_gb": { + Type: schema.TypeInt, + Required: true, + ValidateFunc: validateDiskSizeGB, + }, + + "tags": tagsSchema(), + }, + } +} + +func validateDiskSizeGB(v interface{}, k string) (ws []string, errors []error) { + value := v.(int) + if value < 1 || value > 1023 { + errors = append(errors, fmt.Errorf( + "The `disk_size_gb` can only be between 1 and 1023")) + } + return +} + +func resourceArmManagedDiskCreate(d *schema.ResourceData, meta interface{}) error { + client := meta.(*ArmClient) + diskClient := client.diskClient + + log.Printf("[INFO] preparing arguments for Azure ARM Managed Disk creation.") + + name := d.Get("name").(string) + location := d.Get("location").(string) + resGroup := d.Get("resource_group_name").(string) + tags := d.Get("tags").(map[string]interface{}) + expandedTags := expandTags(tags) + + createDisk := disk.Model{ + Name: &name, + Location: &location, + Tags: expandedTags, + } + + storageAccountType := d.Get("storage_account_type").(string) + osType := d.Get("os_type").(string) + + createDisk.Properties = &disk.Properties{ + AccountType: disk.StorageAccountTypes(storageAccountType), + OsType: disk.OperatingSystemTypes(osType), + } + + if v := d.Get("disk_size_gb"); v != 0 { + diskSize := int32(v.(int)) + createDisk.Properties.DiskSizeGB = &diskSize + } + createOption := d.Get("create_option").(string) + + creationData := &disk.CreationData{ + CreateOption: disk.CreateOption(createOption), + } + + if strings.EqualFold(createOption, string(disk.Import)) { + if sourceUri := d.Get("source_uri").(string); sourceUri != "" { + creationData.SourceURI = &sourceUri + } else { + return fmt.Errorf("[ERROR] source_uri must be specified when create_option is `%s`", disk.Import) + } + } else if strings.EqualFold(createOption, string(disk.Copy)) { + if sourceResourceId := d.Get("source_resource_id").(string); sourceResourceId != "" { + creationData.SourceResourceID = &sourceResourceId + } else { + return fmt.Errorf("[ERROR] source_resource_id must be specified when create_option is `%s`", disk.Copy) + } + } + + createDisk.CreationData = creationData + + _, diskErr := diskClient.CreateOrUpdate(resGroup, name, createDisk, make(chan struct{})) + if diskErr != nil { + return diskErr + } + + read, err := diskClient.Get(resGroup, name) + if err != nil { + return err + } + if read.ID == nil { + return fmt.Errorf("[ERROR] Cannot read Managed Disk %s (resource group %s) ID", name, resGroup) + } + + d.SetId(*read.ID) + + return resourceArmManagedDiskRead(d, meta) +} + +func resourceArmManagedDiskRead(d *schema.ResourceData, meta interface{}) error { + diskClient := meta.(*ArmClient).diskClient + + id, err := parseAzureResourceID(d.Id()) + if err != nil { + return err + } + resGroup := id.ResourceGroup + name := id.Path["disks"] + + resp, err := diskClient.Get(resGroup, name) + if err != nil { + if resp.StatusCode == http.StatusNotFound { + d.SetId("") + return nil + } + return fmt.Errorf("[ERROR] Error making Read request on Azure Managed Disk %s (resource group %s): %s", name, resGroup, err) + } + + d.Set("name", resp.Name) + d.Set("resource_group_name", resGroup) + d.Set("location", resp.Location) + + if resp.Properties != nil { + flattenAzureRmManagedDiskProperties(d, resp.Properties) + } + + if resp.CreationData != nil { + flattenAzureRmManagedDiskCreationData(d, resp.CreationData) + } + + flattenAndSetTags(d, resp.Tags) + + return nil +} + +func resourceArmManagedDiskDelete(d *schema.ResourceData, meta interface{}) error { + diskClient := meta.(*ArmClient).diskClient + + id, err := parseAzureResourceID(d.Id()) + if err != nil { + return err + } + resGroup := id.ResourceGroup + name := id.Path["disks"] + + if _, err = diskClient.Delete(resGroup, name, make(chan struct{})); err != nil { + return err + } + + return nil +} + +func flattenAzureRmManagedDiskProperties(d *schema.ResourceData, properties *disk.Properties) { + d.Set("storage_account_type", string(properties.AccountType)) + if properties.DiskSizeGB != nil { + d.Set("disk_size_gb", *properties.DiskSizeGB) + } + if properties.OsType != "" { + d.Set("os_type", string(properties.OsType)) + } +} + +func flattenAzureRmManagedDiskCreationData(d *schema.ResourceData, creationData *disk.CreationData) { + d.Set("create_option", string(creationData.CreateOption)) + if creationData.SourceURI != nil { + d.Set("source_uri", *creationData.SourceURI) + } +} diff --git a/builtin/providers/azurerm/resource_arm_managed_disk_test.go b/builtin/providers/azurerm/resource_arm_managed_disk_test.go new file mode 100644 index 000000000..b7512e2a7 --- /dev/null +++ b/builtin/providers/azurerm/resource_arm_managed_disk_test.go @@ -0,0 +1,321 @@ +package azurerm + +import ( + "fmt" + "net/http" + "testing" + + "github.com/Azure/azure-sdk-for-go/arm/compute" + "github.com/Azure/azure-sdk-for-go/arm/disk" + "github.com/hashicorp/terraform/helper/acctest" + "github.com/hashicorp/terraform/helper/resource" + "github.com/hashicorp/terraform/terraform" +) + +func TestAccAzureRMManagedDisk_empty(t *testing.T) { + var d disk.Model + ri := acctest.RandInt() + config := fmt.Sprintf(testAccAzureRMManagedDisk_empty, ri, ri) + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testCheckAzureRMManagedDiskDestroy, + Steps: []resource.TestStep{ + { + Config: config, + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMManagedDiskExists("azurerm_managed_disk.test", &d, true), + ), + }, + }, + }) +} + +func TestAccAzureRMManagedDisk_import(t *testing.T) { + var d disk.Model + var vm compute.VirtualMachine + ri := acctest.RandInt() + vmConfig := fmt.Sprintf(testAccAzureRMVirtualMachine_basicLinuxMachine, ri, ri, ri, ri, ri, ri, ri) + config := fmt.Sprintf(testAccAzureRMManagedDisk_import, ri, ri, ri) + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testCheckAzureRMManagedDiskDestroy, + Steps: []resource.TestStep{ + { + //need to create a vm and then delete it so we can use the vhd to test import + Config: vmConfig, + Destroy: false, + ExpectNonEmptyPlan: true, + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMVirtualMachineExists("azurerm_virtual_machine.test", &vm), + testDeleteAzureRMVirtualMachine("azurerm_virtual_machine.test"), + ), + }, + { + Config: config, + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMManagedDiskExists("azurerm_managed_disk.test", &d, true), + ), + }, + }, + }) +} + +func TestAccAzureRMManagedDisk_copy(t *testing.T) { + var d disk.Model + ri := acctest.RandInt() + config := fmt.Sprintf(testAccAzureRMManagedDisk_copy, ri, ri, ri) + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testCheckAzureRMManagedDiskDestroy, + Steps: []resource.TestStep{ + { + Config: config, + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMManagedDiskExists("azurerm_managed_disk.test", &d, true), + ), + }, + }, + }) +} + +func TestAccAzureRMManagedDisk_update(t *testing.T) { + var d disk.Model + + ri := acctest.RandInt() + preConfig := fmt.Sprintf(testAccAzureRMManagedDisk_empty, ri, ri) + postConfig := fmt.Sprintf(testAccAzureRMManagedDisk_empty_updated, ri, ri) + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testCheckAzureRMManagedDiskDestroy, + Steps: []resource.TestStep{ + { + Config: preConfig, + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMManagedDiskExists("azurerm_managed_disk.test", &d, true), + resource.TestCheckResourceAttr( + "azurerm_managed_disk.test", "tags.%", "2"), + resource.TestCheckResourceAttr( + "azurerm_managed_disk.test", "tags.environment", "acctest"), + resource.TestCheckResourceAttr( + "azurerm_managed_disk.test", "tags.cost-center", "ops"), + resource.TestCheckResourceAttr( + "azurerm_managed_disk.test", "disk_size_gb", "1"), + resource.TestCheckResourceAttr( + "azurerm_managed_disk.test", "storage_account_type", string(disk.StandardLRS)), + ), + }, + { + Config: postConfig, + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMManagedDiskExists("azurerm_managed_disk.test", &d, true), + resource.TestCheckResourceAttr( + "azurerm_managed_disk.test", "tags.%", "1"), + resource.TestCheckResourceAttr( + "azurerm_managed_disk.test", "tags.environment", "acctest"), + resource.TestCheckResourceAttr( + "azurerm_managed_disk.test", "disk_size_gb", "2"), + resource.TestCheckResourceAttr( + "azurerm_managed_disk.test", "storage_account_type", string(disk.PremiumLRS)), + ), + }, + }, + }) +} + +func testCheckAzureRMManagedDiskExists(name string, d *disk.Model, shouldExist bool) resource.TestCheckFunc { + return func(s *terraform.State) error { + rs, ok := s.RootModule().Resources[name] + if !ok { + return fmt.Errorf("Not found: %s", name) + } + + dName := rs.Primary.Attributes["name"] + resourceGroup, hasResourceGroup := rs.Primary.Attributes["resource_group_name"] + if !hasResourceGroup { + return fmt.Errorf("Bad: no resource group found in state for disk: %s", dName) + } + + conn := testAccProvider.Meta().(*ArmClient).diskClient + + resp, err := conn.Get(resourceGroup, dName) + if err != nil { + return fmt.Errorf("Bad: Get on diskClient: %s", err) + } + + if resp.StatusCode == http.StatusNotFound && shouldExist { + return fmt.Errorf("Bad: ManagedDisk %q (resource group %q) does not exist", dName, resourceGroup) + } + if resp.StatusCode != http.StatusNotFound && !shouldExist { + return fmt.Errorf("Bad: ManagedDisk %q (resource group %q) still exists", dName, resourceGroup) + } + + *d = resp + + return nil + } +} + +func testCheckAzureRMManagedDiskDestroy(s *terraform.State) error { + conn := testAccProvider.Meta().(*ArmClient).diskClient + + for _, rs := range s.RootModule().Resources { + if rs.Type != "azurerm_managed_disk" { + continue + } + + name := rs.Primary.Attributes["name"] + resourceGroup := rs.Primary.Attributes["resource_group_name"] + + resp, err := conn.Get(resourceGroup, name) + + if err != nil { + return nil + } + + if resp.StatusCode != http.StatusNotFound { + return fmt.Errorf("Managed Disk still exists: \n%#v", resp.Properties) + } + } + + return nil +} + +func testDeleteAzureRMVirtualMachine(name string) resource.TestCheckFunc { + return func(s *terraform.State) error { + rs, ok := s.RootModule().Resources[name] + if !ok { + return fmt.Errorf("Not found: %s", name) + } + + vmName := rs.Primary.Attributes["name"] + resourceGroup, hasResourceGroup := rs.Primary.Attributes["resource_group_name"] + if !hasResourceGroup { + return fmt.Errorf("Bad: no resource group found in state for virtual machine: %s", vmName) + } + + conn := testAccProvider.Meta().(*ArmClient).vmClient + + _, err := conn.Delete(resourceGroup, vmName, make(chan struct{})) + if err != nil { + return fmt.Errorf("Bad: Delete on vmClient: %s", err) + } + + return nil + } +} + +var testAccAzureRMManagedDisk_empty = ` +resource "azurerm_resource_group" "test" { + name = "acctestRG-%d" + location = "West US 2" +} + +resource "azurerm_managed_disk" "test" { + name = "acctestd-%d" + location = "West US 2" + resource_group_name = "${azurerm_resource_group.test.name}" + storage_account_type = "Standard_LRS" + create_option = "Empty" + disk_size_gb = "1" + + tags { + environment = "acctest" + cost-center = "ops" + } +}` + +var testAccAzureRMManagedDisk_import = ` +resource "azurerm_resource_group" "test" { + name = "acctestRG-%d" + location = "West US 2" +} + +resource "azurerm_storage_account" "test" { + name = "accsa%d" + resource_group_name = "${azurerm_resource_group.test.name}" + location = "West US 2" + account_type = "Standard_LRS" + + tags { + environment = "staging" + } +} + +resource "azurerm_storage_container" "test" { + name = "vhds" + resource_group_name = "${azurerm_resource_group.test.name}" + storage_account_name = "${azurerm_storage_account.test.name}" + container_access_type = "private" +} + +resource "azurerm_managed_disk" "test" { + name = "acctestd-%d" + location = "West US 2" + resource_group_name = "${azurerm_resource_group.test.name}" + storage_account_type = "Standard_LRS" + create_option = "Import" + source_uri = "${azurerm_storage_account.test.primary_blob_endpoint}${azurerm_storage_container.test.name}/myosdisk1.vhd" + disk_size_gb = "45" + + tags { + environment = "acctest" + } +}` + +var testAccAzureRMManagedDisk_copy = ` +resource "azurerm_resource_group" "test" { + name = "acctestRG-%d" + location = "West US 2" +} + +resource "azurerm_managed_disk" "source" { + name = "acctestd1-%d" + location = "West US 2" + resource_group_name = "${azurerm_resource_group.test.name}" + storage_account_type = "Standard_LRS" + create_option = "Empty" + disk_size_gb = "1" + + tags { + environment = "acctest" + cost-center = "ops" + } +} + +resource "azurerm_managed_disk" "test" { + name = "acctestd2-%d" + location = "West US 2" + resource_group_name = "${azurerm_resource_group.test.name}" + storage_account_type = "Standard_LRS" + create_option = "Copy" + source_resource_id = "${azurerm_managed_disk.source.id}" + disk_size_gb = "1" + + tags { + environment = "acctest" + cost-center = "ops" + } +}` + +var testAccAzureRMManagedDisk_empty_updated = ` +resource "azurerm_resource_group" "test" { + name = "acctestRG-%d" + location = "West US 2" +} + +resource "azurerm_managed_disk" "test" { + name = "acctestd-%d" + location = "West US 2" + resource_group_name = "${azurerm_resource_group.test.name}" + storage_account_type = "Premium_LRS" + create_option = "Empty" + disk_size_gb = "2" + + tags { + environment = "acctest" + } +}` diff --git a/builtin/providers/azurerm/resource_arm_network_interface_card.go b/builtin/providers/azurerm/resource_arm_network_interface_card.go index 7450519b1..7baf33e9d 100644 --- a/builtin/providers/azurerm/resource_arm_network_interface_card.go +++ b/builtin/providers/azurerm/resource_arm_network_interface_card.go @@ -172,6 +172,14 @@ func resourceArmNetworkInterfaceCreate(d *schema.ResourceData, meta interface{}) properties.NetworkSecurityGroup = &network.SecurityGroup{ ID: &nsgId, } + + networkSecurityGroupName, err := parseNetworkSecurityGroupName(nsgId) + if err != nil { + return err + } + + armMutexKV.Lock(networkSecurityGroupName) + defer armMutexKV.Unlock(networkSecurityGroupName) } dns, hasDns := d.GetOk("dns_servers") @@ -192,16 +200,19 @@ func resourceArmNetworkInterfaceCreate(d *schema.ResourceData, meta interface{}) if hasNameLabel { name_label := nameLabel.(string) ifaceDnsSettings.InternalDNSNameLabel = &name_label - } properties.DNSSettings = &ifaceDnsSettings } - ipConfigs, sgErr := expandAzureRmNetworkInterfaceIpConfigurations(d) + ipConfigs, namesToLock, sgErr := expandAzureRmNetworkInterfaceIpConfigurations(d) if sgErr != nil { return fmt.Errorf("Error Building list of Network Interface IP Configurations: %s", sgErr) } + + azureRMLockMultiple(namesToLock) + defer azureRMUnlockMultiple(namesToLock) + if len(ipConfigs) > 0 { properties.IPConfigurations = &ipConfigs } @@ -308,6 +319,37 @@ func resourceArmNetworkInterfaceDelete(d *schema.ResourceData, meta interface{}) resGroup := id.ResourceGroup name := id.Path["networkInterfaces"] + if v, ok := d.GetOk("network_security_group_id"); ok { + networkSecurityGroupId := v.(string) + networkSecurityGroupName, err := parseNetworkSecurityGroupName(networkSecurityGroupId) + if err != nil { + return err + } + + armMutexKV.Lock(networkSecurityGroupName) + defer armMutexKV.Unlock(networkSecurityGroupName) + } + + configs := d.Get("ip_configuration").(*schema.Set).List() + namesToLock := make([]string, 0) + + for _, configRaw := range configs { + data := configRaw.(map[string]interface{}) + + subnet_id := data["subnet_id"].(string) + subnetId, err := parseAzureResourceID(subnet_id) + if err != nil { + return err + } + subnetName := subnetId.Path["subnets"] + virtualNetworkName := subnetId.Path["virtualNetworks"] + namesToLock = append(namesToLock, subnetName) + namesToLock = append(namesToLock, virtualNetworkName) + } + + azureRMLockMultiple(&namesToLock) + defer azureRMUnlockMultiple(&namesToLock) + _, err = ifaceClient.Delete(resGroup, name, make(chan struct{})) return err @@ -354,9 +396,10 @@ func validateNetworkInterfacePrivateIpAddressAllocation(v interface{}, k string) return } -func expandAzureRmNetworkInterfaceIpConfigurations(d *schema.ResourceData) ([]network.InterfaceIPConfiguration, error) { +func expandAzureRmNetworkInterfaceIpConfigurations(d *schema.ResourceData) ([]network.InterfaceIPConfiguration, *[]string, error) { configs := d.Get("ip_configuration").(*schema.Set).List() ipConfigs := make([]network.InterfaceIPConfiguration, 0, len(configs)) + namesToLock := make([]string, 0) for _, configRaw := range configs { data := configRaw.(map[string]interface{}) @@ -371,7 +414,7 @@ func expandAzureRmNetworkInterfaceIpConfigurations(d *schema.ResourceData) ([]ne case "static": allocationMethod = network.Static default: - return []network.InterfaceIPConfiguration{}, fmt.Errorf( + return []network.InterfaceIPConfiguration{}, nil, fmt.Errorf( "valid values for private_ip_allocation_method are 'dynamic' and 'static' - got '%s'", private_ip_allocation_method) } @@ -383,6 +426,15 @@ func expandAzureRmNetworkInterfaceIpConfigurations(d *schema.ResourceData) ([]ne PrivateIPAllocationMethod: allocationMethod, } + subnetId, err := parseAzureResourceID(subnet_id) + if err != nil { + return []network.InterfaceIPConfiguration{}, nil, err + } + subnetName := subnetId.Path["subnets"] + virtualNetworkName := subnetId.Path["virtualNetworks"] + namesToLock = append(namesToLock, subnetName) + namesToLock = append(namesToLock, virtualNetworkName) + if v := data["private_ip_address"].(string); v != "" { properties.PrivateIPAddress = &v } @@ -432,5 +484,5 @@ func expandAzureRmNetworkInterfaceIpConfigurations(d *schema.ResourceData) ([]ne ipConfigs = append(ipConfigs, ipConfig) } - return ipConfigs, nil + return ipConfigs, &namesToLock, nil } diff --git a/builtin/providers/azurerm/resource_arm_network_security_group.go b/builtin/providers/azurerm/resource_arm_network_security_group.go index 7ba17e8a7..c538e6103 100644 --- a/builtin/providers/azurerm/resource_arm_network_security_group.go +++ b/builtin/providers/azurerm/resource_arm_network_security_group.go @@ -66,6 +66,7 @@ func resourceArmNetworkSecurityGroup() *schema.Resource { Type: schema.TypeString, Required: true, ValidateFunc: validateNetworkSecurityRuleProtocol, + StateFunc: ignoreCaseStateFunc, }, "source_port_range": { diff --git a/builtin/providers/azurerm/resource_arm_network_security_group_test.go b/builtin/providers/azurerm/resource_arm_network_security_group_test.go index 39fa092e0..3e7685ae3 100644 --- a/builtin/providers/azurerm/resource_arm_network_security_group_test.go +++ b/builtin/providers/azurerm/resource_arm_network_security_group_test.go @@ -204,7 +204,7 @@ resource "azurerm_network_security_group" "test" { priority = 100 direction = "Inbound" access = "Allow" - protocol = "Tcp" + protocol = "TCP" source_port_range = "*" destination_port_range = "*" source_address_prefix = "*" diff --git a/builtin/providers/azurerm/resource_arm_redis_cache.go b/builtin/providers/azurerm/resource_arm_redis_cache.go index 80395026f..9ff08a872 100644 --- a/builtin/providers/azurerm/resource_arm_redis_cache.go +++ b/builtin/providers/azurerm/resource_arm_redis_cache.go @@ -281,14 +281,17 @@ func resourceArmRedisCacheRead(d *schema.ResourceData, meta interface{}) error { name := id.Path["Redis"] resp, err := client.Get(resGroup, name) - if err != nil { - return fmt.Errorf("Error making Read request on Azure Redis Cache %s: %s", name, err) - } + + // covers if the resource has been deleted outside of TF, but is still in the state if resp.StatusCode == http.StatusNotFound { d.SetId("") return nil } + if err != nil { + return fmt.Errorf("Error making Read request on Azure Redis Cache %s: %s", name, err) + } + keysResp, err := client.ListKeys(resGroup, name) if err != nil { return fmt.Errorf("Error making ListKeys request on Azure Redis Cache %s: %s", name, err) @@ -298,7 +301,7 @@ func resourceArmRedisCacheRead(d *schema.ResourceData, meta interface{}) error { d.Set("resource_group_name", resGroup) d.Set("location", azureRMNormalizeLocation(*resp.Location)) d.Set("ssl_port", resp.SslPort) - d.Set("host_name", resp.HostName) + d.Set("hostname", resp.HostName) d.Set("port", resp.Port) d.Set("enable_non_ssl_port", resp.EnableNonSslPort) d.Set("capacity", resp.Sku.Capacity) diff --git a/builtin/providers/azurerm/resource_arm_servicebus_namespace.go b/builtin/providers/azurerm/resource_arm_servicebus_namespace.go index c0538c25e..1226560f8 100644 --- a/builtin/providers/azurerm/resource_arm_servicebus_namespace.go +++ b/builtin/providers/azurerm/resource_arm_servicebus_namespace.go @@ -132,7 +132,7 @@ func resourceArmServiceBusNamespaceRead(d *schema.ResourceData, meta interface{} resp, err := namespaceClient.Get(resGroup, name) if err != nil { - return fmt.Errorf("Error making Read request on Azure ServiceBus Namespace %s: %s", name, err) + return fmt.Errorf("Error making Read request on Azure ServiceBus Namespace %s: %+v", name, err) } if resp.StatusCode == http.StatusNotFound { d.SetId("") @@ -147,7 +147,7 @@ func resourceArmServiceBusNamespaceRead(d *schema.ResourceData, meta interface{} keys, err := namespaceClient.ListKeys(resGroup, name, serviceBusNamespaceDefaultAuthorizationRule) if err != nil { - log.Printf("[ERROR] Unable to List default keys for Namespace %s: %s", name, err) + log.Printf("[ERROR] Unable to List default keys for Namespace %s: %+v", name, err) } else { d.Set("default_primary_connection_string", keys.PrimaryConnectionString) d.Set("default_secondary_connection_string", keys.SecondaryConnectionString) @@ -173,7 +173,7 @@ func resourceArmServiceBusNamespaceDelete(d *schema.ResourceData, meta interface resp, err := namespaceClient.Delete(resGroup, name, make(chan struct{})) if resp.StatusCode != http.StatusNotFound { - return fmt.Errorf("Error issuing Azure ARM delete request of ServiceBus Namespace'%s': %s", name, err) + return fmt.Errorf("Error issuing Azure ARM delete request of ServiceBus Namespace'%s': %+v", name, err) } return nil diff --git a/builtin/providers/azurerm/resource_arm_servicebus_namespace_test.go b/builtin/providers/azurerm/resource_arm_servicebus_namespace_test.go index 8f0955511..84c89925b 100644 --- a/builtin/providers/azurerm/resource_arm_servicebus_namespace_test.go +++ b/builtin/providers/azurerm/resource_arm_servicebus_namespace_test.go @@ -140,7 +140,7 @@ func testCheckAzureRMServiceBusNamespaceDestroy(s *terraform.State) error { } if resp.StatusCode != http.StatusNotFound { - return fmt.Errorf("ServiceBus Namespace still exists:\n%#v", resp.NamespaceProperties) + return fmt.Errorf("ServiceBus Namespace still exists:\n%+v", resp) } } @@ -165,7 +165,7 @@ func testCheckAzureRMServiceBusNamespaceExists(name string) resource.TestCheckFu resp, err := conn.Get(resourceGroup, namespaceName) if err != nil { - return fmt.Errorf("Bad: Get on serviceBusNamespacesClient: %s", err) + return fmt.Errorf("Bad: Get on serviceBusNamespacesClient: %+v", err) } if resp.StatusCode == http.StatusNotFound { diff --git a/builtin/providers/azurerm/resource_arm_servicebus_subscription.go b/builtin/providers/azurerm/resource_arm_servicebus_subscription.go index cd2fc6fee..d0c4fc64e 100644 --- a/builtin/providers/azurerm/resource_arm_servicebus_subscription.go +++ b/builtin/providers/azurerm/resource_arm_servicebus_subscription.go @@ -163,7 +163,7 @@ func resourceArmServiceBusSubscriptionRead(d *schema.ResourceData, meta interfac resp, err := client.Get(resGroup, namespaceName, topicName, name) if err != nil { - return fmt.Errorf("Error making Read request on Azure ServiceBus Subscription %s: %s", name, err) + return fmt.Errorf("Error making Read request on Azure ServiceBus Subscription %s: %+v", name, err) } if resp.StatusCode == http.StatusNotFound { d.SetId("") diff --git a/builtin/providers/azurerm/resource_arm_servicebus_subscription_test.go b/builtin/providers/azurerm/resource_arm_servicebus_subscription_test.go index 23c6f600a..a5efbc820 100644 --- a/builtin/providers/azurerm/resource_arm_servicebus_subscription_test.go +++ b/builtin/providers/azurerm/resource_arm_servicebus_subscription_test.go @@ -105,7 +105,7 @@ func testCheckAzureRMServiceBusSubscriptionDestroy(s *terraform.State) error { } if resp.StatusCode != http.StatusNotFound { - return fmt.Errorf("ServiceBus Subscription still exists:\n%#v", resp.SubscriptionProperties) + return fmt.Errorf("ServiceBus Subscription still exists:\n%+v", resp.SubscriptionProperties) } } @@ -132,7 +132,7 @@ func testCheckAzureRMServiceBusSubscriptionExists(name string) resource.TestChec resp, err := client.Get(resourceGroup, namespaceName, topicName, subscriptionName) if err != nil { - return fmt.Errorf("Bad: Get on serviceBusSubscriptionsClient: %s", err) + return fmt.Errorf("Bad: Get on serviceBusSubscriptionsClient: %+v", err) } if resp.StatusCode == http.StatusNotFound { diff --git a/builtin/providers/azurerm/resource_arm_servicebus_topic.go b/builtin/providers/azurerm/resource_arm_servicebus_topic.go index 1f4165fb4..982b8ea73 100644 --- a/builtin/providers/azurerm/resource_arm_servicebus_topic.go +++ b/builtin/providers/azurerm/resource_arm_servicebus_topic.go @@ -55,6 +55,7 @@ func resourceArmServiceBusTopic() *schema.Resource { "duplicate_detection_history_time_window": { Type: schema.TypeString, Optional: true, + Computed: true, }, "enable_batched_operations": { @@ -172,7 +173,7 @@ func resourceArmServiceBusTopicRead(d *schema.ResourceData, meta interface{}) er resp, err := client.Get(resGroup, namespaceName, name) if err != nil { - return fmt.Errorf("Error making Read request on Azure ServiceBus Topic %s: %s", name, err) + return fmt.Errorf("Error making Read request on Azure ServiceBus Topic %s: %+v", name, err) } if resp.StatusCode == http.StatusNotFound { d.SetId("") diff --git a/builtin/providers/azurerm/resource_arm_servicebus_topic_test.go b/builtin/providers/azurerm/resource_arm_servicebus_topic_test.go index ee6906538..8ea9fd9dd 100644 --- a/builtin/providers/azurerm/resource_arm_servicebus_topic_test.go +++ b/builtin/providers/azurerm/resource_arm_servicebus_topic_test.go @@ -165,7 +165,7 @@ func testCheckAzureRMServiceBusTopicDestroy(s *terraform.State) error { } if resp.StatusCode != http.StatusNotFound { - return fmt.Errorf("ServiceBus Topic still exists:\n%#v", resp.TopicProperties) + return fmt.Errorf("ServiceBus Topic still exists:\n%+v", resp.TopicProperties) } } @@ -191,7 +191,7 @@ func testCheckAzureRMServiceBusTopicExists(name string) resource.TestCheckFunc { resp, err := client.Get(resourceGroup, namespaceName, topicName) if err != nil { - return fmt.Errorf("Bad: Get on serviceBusTopicsClient: %s", err) + return fmt.Errorf("Bad: Get on serviceBusTopicsClient: %+v", err) } if resp.StatusCode == http.StatusNotFound { diff --git a/builtin/providers/azurerm/resource_arm_sql_database.go b/builtin/providers/azurerm/resource_arm_sql_database.go index b022c7d1b..6959586b5 100644 --- a/builtin/providers/azurerm/resource_arm_sql_database.go +++ b/builtin/providers/azurerm/resource_arm_sql_database.go @@ -158,6 +158,10 @@ func resourceArmSqlDatabaseCreate(d *schema.ResourceData, meta interface{}) erro command.RequestedServiceObjectiveID = azure.String(v.(string)) } + if v, ok := d.GetOk("elastic_pool_name"); ok { + command.ElasticPoolName = azure.String(v.(string)) + } + if v, ok := d.GetOk("requested_service_objective_name"); ok { command.RequestedServiceObjectiveName = azure.String(v.(string)) } @@ -216,6 +220,7 @@ func resourceArmSqlDatabaseRead(d *schema.ResourceData, meta interface{}) error d.Set("name", resp.Name) d.Set("creation_date", resp.CreationDate) d.Set("default_secondary_location", resp.DefaultSecondaryLocation) + d.Set("elastic_pool_name", resp.ElasticPoolName) flattenAndSetTags(d, resp.Tags) diff --git a/builtin/providers/azurerm/resource_arm_sql_database_test.go b/builtin/providers/azurerm/resource_arm_sql_database_test.go index 9f80eb426..fb306e04a 100644 --- a/builtin/providers/azurerm/resource_arm_sql_database_test.go +++ b/builtin/providers/azurerm/resource_arm_sql_database_test.go @@ -65,6 +65,26 @@ func TestAccAzureRMSqlDatabase_basic(t *testing.T) { }) } +func TestAccAzureRMSqlDatabase_elasticPool(t *testing.T) { + ri := acctest.RandInt() + config := fmt.Sprintf(testAccAzureRMSqlDatabase_elasticPool, ri, ri, ri, ri) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testCheckAzureRMSqlDatabaseDestroy, + Steps: []resource.TestStep{ + { + Config: config, + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMSqlDatabaseExists("azurerm_sql_database.test"), + resource.TestCheckResourceAttr("azurerm_sql_database.test", "elastic_pool_name", fmt.Sprintf("acctestep%d", ri)), + ), + }, + }, + }) +} + func TestAccAzureRMSqlDatabase_withTags(t *testing.T) { ri := acctest.RandInt() preConfig := fmt.Sprintf(testAccAzureRMSqlDatabase_withTags, ri, ri, ri) @@ -163,6 +183,44 @@ func testCheckAzureRMSqlDatabaseDestroy(s *terraform.State) error { return nil } +var testAccAzureRMSqlDatabase_elasticPool = ` +resource "azurerm_resource_group" "test" { + name = "acctestRG_%d" + location = "West US" +} + +resource "azurerm_sql_server" "test" { + name = "acctestsqlserver%d" + resource_group_name = "${azurerm_resource_group.test.name}" + location = "West US" + version = "12.0" + administrator_login = "mradministrator" + administrator_login_password = "thisIsDog11" +} + +resource "azurerm_sql_elasticpool" "test" { + name = "acctestep%d" + resource_group_name = "${azurerm_resource_group.test.name}" + location = "West US" + server_name = "${azurerm_sql_server.test.name}" + edition = "Basic" + dtu = 50 + pool_size = 5000 +} + +resource "azurerm_sql_database" "test" { + name = "acctestdb%d" + resource_group_name = "${azurerm_resource_group.test.name}" + server_name = "${azurerm_sql_server.test.name}" + location = "West US" + edition = "${azurerm_sql_elasticpool.test.edition}" + collation = "SQL_Latin1_General_CP1_CI_AS" + max_size_bytes = "1073741824" + elastic_pool_name = "${azurerm_sql_elasticpool.test.name}" + requested_service_objective_name = "ElasticPool" +} +` + var testAccAzureRMSqlDatabase_basic = ` resource "azurerm_resource_group" "test" { name = "acctestRG_%d" diff --git a/builtin/providers/azurerm/resource_arm_sql_elasticpool.go b/builtin/providers/azurerm/resource_arm_sql_elasticpool.go new file mode 100644 index 000000000..6231950fb --- /dev/null +++ b/builtin/providers/azurerm/resource_arm_sql_elasticpool.go @@ -0,0 +1,220 @@ +package azurerm + +import ( + "fmt" + "github.com/Azure/azure-sdk-for-go/arm/sql" + "github.com/hashicorp/terraform/helper/schema" + "github.com/hashicorp/terraform/helper/validation" + "log" + "net/http" + "time" +) + +func resourceArmSqlElasticPool() *schema.Resource { + return &schema.Resource{ + Create: resourceArmSqlElasticPoolCreate, + Read: resourceArmSqlElasticPoolRead, + Update: resourceArmSqlElasticPoolCreate, + Delete: resourceArmSqlElasticPoolDelete, + + Importer: &schema.ResourceImporter{ + State: schema.ImportStatePassthrough, + }, + + Schema: map[string]*schema.Schema{ + "name": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + + "location": locationSchema(), + + "resource_group_name": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + + "server_name": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + + "edition": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + ValidateFunc: validateSqlElasticPoolEdition(), + }, + + "dtu": { + Type: schema.TypeInt, + Required: true, + }, + + "db_dtu_min": { + Type: schema.TypeInt, + Optional: true, + Computed: true, + }, + + "db_dtu_max": { + Type: schema.TypeInt, + Optional: true, + Computed: true, + }, + + "pool_size": { + Type: schema.TypeInt, + Optional: true, + Computed: true, + }, + + "creation_date": { + Type: schema.TypeString, + Computed: true, + }, + + "tags": tagsSchema(), + }, + } +} + +func resourceArmSqlElasticPoolCreate(d *schema.ResourceData, meta interface{}) error { + client := meta.(*ArmClient) + elasticPoolsClient := client.sqlElasticPoolsClient + + log.Printf("[INFO] preparing arguments for Azure ARM SQL ElasticPool creation.") + + name := d.Get("name").(string) + serverName := d.Get("server_name").(string) + location := d.Get("location").(string) + resGroup := d.Get("resource_group_name").(string) + tags := d.Get("tags").(map[string]interface{}) + + elasticPool := sql.ElasticPool{ + Name: &name, + Location: &location, + ElasticPoolProperties: getArmSqlElasticPoolProperties(d), + Tags: expandTags(tags), + } + + _, err := elasticPoolsClient.CreateOrUpdate(resGroup, serverName, name, elasticPool, make(chan struct{})) + if err != nil { + return err + } + + read, err := elasticPoolsClient.Get(resGroup, serverName, name) + if err != nil { + return err + } + if read.ID == nil { + return fmt.Errorf("Cannot read SQL ElasticPool %s (resource group %s) ID", name, resGroup) + } + + d.SetId(*read.ID) + + return resourceArmSqlElasticPoolRead(d, meta) +} + +func resourceArmSqlElasticPoolRead(d *schema.ResourceData, meta interface{}) error { + client := meta.(*ArmClient) + elasticPoolsClient := client.sqlElasticPoolsClient + + resGroup, serverName, name, err := parseArmSqlElasticPoolId(d.Id()) + if err != nil { + return err + } + + resp, err := elasticPoolsClient.Get(resGroup, serverName, name) + if err != nil { + if resp.StatusCode == http.StatusNotFound { + d.SetId("") + return nil + } + return fmt.Errorf("Error making Read request on Sql Elastic Pool %s: %s", name, err) + } + + d.Set("name", resp.Name) + d.Set("resource_group_name", resGroup) + d.Set("location", azureRMNormalizeLocation(*resp.Location)) + d.Set("server_name", serverName) + + elasticPool := resp.ElasticPoolProperties + + if elasticPool != nil { + d.Set("edition", string(elasticPool.Edition)) + d.Set("dtu", int(*elasticPool.Dtu)) + d.Set("db_dtu_min", int(*elasticPool.DatabaseDtuMin)) + d.Set("db_dtu_max", int(*elasticPool.DatabaseDtuMax)) + d.Set("pool_size", int(*elasticPool.StorageMB)) + + if elasticPool.CreationDate != nil { + d.Set("creation_date", elasticPool.CreationDate.Format(time.RFC3339)) + } + } + + flattenAndSetTags(d, resp.Tags) + + return nil +} + +func resourceArmSqlElasticPoolDelete(d *schema.ResourceData, meta interface{}) error { + client := meta.(*ArmClient) + elasticPoolsClient := client.sqlElasticPoolsClient + + resGroup, serverName, name, err := parseArmSqlElasticPoolId(d.Id()) + if err != nil { + return err + } + + _, err = elasticPoolsClient.Delete(resGroup, serverName, name) + + return err +} + +func getArmSqlElasticPoolProperties(d *schema.ResourceData) *sql.ElasticPoolProperties { + edition := sql.ElasticPoolEditions(d.Get("edition").(string)) + dtu := int32(d.Get("dtu").(int)) + + props := &sql.ElasticPoolProperties{ + Edition: edition, + Dtu: &dtu, + } + + if databaseDtuMin, ok := d.GetOk("db_dtu_min"); ok { + databaseDtuMin := int32(databaseDtuMin.(int)) + props.DatabaseDtuMin = &databaseDtuMin + } + + if databaseDtuMax, ok := d.GetOk("db_dtu_max"); ok { + databaseDtuMax := int32(databaseDtuMax.(int)) + props.DatabaseDtuMax = &databaseDtuMax + } + + if poolSize, ok := d.GetOk("pool_size"); ok { + poolSize := int32(poolSize.(int)) + props.StorageMB = &poolSize + } + + return props +} + +func parseArmSqlElasticPoolId(sqlElasticPoolId string) (string, string, string, error) { + id, err := parseAzureResourceID(sqlElasticPoolId) + if err != nil { + return "", "", "", fmt.Errorf("[ERROR] Unable to parse SQL ElasticPool ID '%s': %+v", sqlElasticPoolId, err) + } + + return id.ResourceGroup, id.Path["servers"], id.Path["elasticPools"], nil +} + +func validateSqlElasticPoolEdition() schema.SchemaValidateFunc { + return validation.StringInSlice([]string{ + string(sql.ElasticPoolEditionsBasic), + string(sql.ElasticPoolEditionsStandard), + string(sql.ElasticPoolEditionsPremium), + }, false) +} diff --git a/builtin/providers/azurerm/resource_arm_sql_elasticpool_test.go b/builtin/providers/azurerm/resource_arm_sql_elasticpool_test.go new file mode 100644 index 000000000..991eb691b --- /dev/null +++ b/builtin/providers/azurerm/resource_arm_sql_elasticpool_test.go @@ -0,0 +1,168 @@ +package azurerm + +import ( + "fmt" + "github.com/hashicorp/terraform/helper/acctest" + "github.com/hashicorp/terraform/helper/resource" + "github.com/hashicorp/terraform/terraform" + "net/http" + "testing" +) + +func TestAccAzureRMSqlElasticPool_basic(t *testing.T) { + ri := acctest.RandInt() + config := fmt.Sprintf(testAccAzureRMSqlElasticPool_basic, ri) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testCheckAzureRMSqlElasticPoolDestroy, + Steps: []resource.TestStep{ + { + Config: config, + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMSqlElasticPoolExists("azurerm_sql_elasticpool.test"), + ), + }, + }, + }) +} + +func TestAccAzureRMSqlElasticPool_resizeDtu(t *testing.T) { + ri := acctest.RandInt() + preConfig := fmt.Sprintf(testAccAzureRMSqlElasticPool_basic, ri) + postConfig := fmt.Sprintf(testAccAzureRMSqlElasticPool_resizedDtu, ri) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testCheckAzureRMSqlElasticPoolDestroy, + Steps: []resource.TestStep{ + { + Config: preConfig, + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMSqlElasticPoolExists("azurerm_sql_elasticpool.test"), + resource.TestCheckResourceAttr( + "azurerm_sql_elasticpool.test", "dtu", "50"), + resource.TestCheckResourceAttr( + "azurerm_sql_elasticpool.test", "pool_size", "5000"), + ), + }, + { + Config: postConfig, + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMSqlElasticPoolExists("azurerm_sql_elasticpool.test"), + resource.TestCheckResourceAttr( + "azurerm_sql_elasticpool.test", "dtu", "100"), + resource.TestCheckResourceAttr( + "azurerm_sql_elasticpool.test", "pool_size", "10000"), + ), + }, + }, + }) +} + +func testCheckAzureRMSqlElasticPoolExists(name string) resource.TestCheckFunc { + return func(s *terraform.State) error { + ressource, ok := s.RootModule().Resources[name] + if !ok { + return fmt.Errorf("Not found: %s", name) + } + + resourceGroup, serverName, name, err := parseArmSqlElasticPoolId(ressource.Primary.ID) + if err != nil { + return err + } + + conn := testAccProvider.Meta().(*ArmClient).sqlElasticPoolsClient + + resp, err := conn.Get(resourceGroup, serverName, name) + if err != nil { + return fmt.Errorf("Bad: Get on sqlElasticPoolsClient: %s", err) + } + + if resp.StatusCode == http.StatusNotFound { + return fmt.Errorf("Bad: SQL Elastic Pool %q on server: %q (resource group: %q) does not exist", name, serverName, resourceGroup) + } + + return nil + } +} + +func testCheckAzureRMSqlElasticPoolDestroy(s *terraform.State) error { + conn := testAccProvider.Meta().(*ArmClient).sqlElasticPoolsClient + + for _, rs := range s.RootModule().Resources { + if rs.Type != "azurerm_sql_elasticpool" { + continue + } + + name := rs.Primary.Attributes["name"] + serverName := rs.Primary.Attributes["server_name"] + resourceGroup := rs.Primary.Attributes["resource_group_name"] + + resp, err := conn.Get(resourceGroup, serverName, name) + + if err != nil { + return nil + } + + if resp.StatusCode != http.StatusNotFound { + return fmt.Errorf("SQL Elastic Pool still exists:\n%#v", resp.ElasticPoolProperties) + } + } + + return nil +} + +var testAccAzureRMSqlElasticPool_basic = ` +resource "azurerm_resource_group" "test" { + name = "acctest-%[1]d" + location = "West US" +} + +resource "azurerm_sql_server" "test" { + name = "acctest%[1]d" + resource_group_name = "${azurerm_resource_group.test.name}" + location = "West US" + version = "12.0" + administrator_login = "4dm1n157r470r" + administrator_login_password = "4-v3ry-53cr37-p455w0rd" +} + +resource "azurerm_sql_elasticpool" "test" { + name = "acctest-pool-%[1]d" + resource_group_name = "${azurerm_resource_group.test.name}" + location = "West US" + server_name = "${azurerm_sql_server.test.name}" + edition = "Basic" + dtu = 50 + pool_size = 5000 +} +` + +var testAccAzureRMSqlElasticPool_resizedDtu = ` +resource "azurerm_resource_group" "test" { + name = "acctest-%[1]d" + location = "West US" +} + +resource "azurerm_sql_server" "test" { + name = "acctest%[1]d" + resource_group_name = "${azurerm_resource_group.test.name}" + location = "West US" + version = "12.0" + administrator_login = "4dm1n157r470r" + administrator_login_password = "4-v3ry-53cr37-p455w0rd" +} + +resource "azurerm_sql_elasticpool" "test" { + name = "acctest-pool-%[1]d" + resource_group_name = "${azurerm_resource_group.test.name}" + location = "West US" + server_name = "${azurerm_sql_server.test.name}" + edition = "Basic" + dtu = 100 + pool_size = 10000 +} +` diff --git a/builtin/providers/azurerm/resource_arm_storage_account.go b/builtin/providers/azurerm/resource_arm_storage_account.go index d47b089f4..721ab8097 100644 --- a/builtin/providers/azurerm/resource_arm_storage_account.go +++ b/builtin/providers/azurerm/resource_arm_storage_account.go @@ -1,7 +1,6 @@ package azurerm import ( - "context" "fmt" "log" "net/http" @@ -188,10 +187,8 @@ func resourceArmStorageAccountCreate(d *schema.ResourceData, meta interface{}) e } // Create - cancelCtx, cancelFunc := context.WithTimeout(client.StopContext, 1*time.Hour) _, createErr := storageClient.Create( - resourceGroupName, storageAccountName, opts, cancelCtx.Done()) - cancelFunc() + resourceGroupName, storageAccountName, opts, make(chan struct{})) // The only way to get the ID back apparently is to read the resource again read, err := storageClient.GetProperties(resourceGroupName, storageAccountName) diff --git a/builtin/providers/azurerm/resource_arm_subnet.go b/builtin/providers/azurerm/resource_arm_subnet.go index c5329b9f8..8094e6a3a 100644 --- a/builtin/providers/azurerm/resource_arm_subnet.go +++ b/builtin/providers/azurerm/resource_arm_subnet.go @@ -77,6 +77,9 @@ func resourceArmSubnetCreate(d *schema.ResourceData, meta interface{}) error { resGroup := d.Get("resource_group_name").(string) addressPrefix := d.Get("address_prefix").(string) + armMutexKV.Lock(name) + defer armMutexKV.Unlock(name) + armMutexKV.Lock(vnetName) defer armMutexKV.Unlock(vnetName) @@ -89,6 +92,14 @@ func resourceArmSubnetCreate(d *schema.ResourceData, meta interface{}) error { properties.NetworkSecurityGroup = &network.SecurityGroup{ ID: &nsgId, } + + networkSecurityGroupName, err := parseNetworkSecurityGroupName(nsgId) + if err != nil { + return err + } + + armMutexKV.Lock(networkSecurityGroupName) + defer armMutexKV.Unlock(networkSecurityGroupName) } if v, ok := d.GetOk("route_table_id"); ok { @@ -96,6 +107,14 @@ func resourceArmSubnetCreate(d *schema.ResourceData, meta interface{}) error { properties.RouteTable = &network.RouteTable{ ID: &rtId, } + + routeTableName, err := parseRouteTableName(rtId) + if err != nil { + return err + } + + armMutexKV.Lock(routeTableName) + defer armMutexKV.Unlock(routeTableName) } subnet := network.Subnet{ @@ -182,9 +201,34 @@ func resourceArmSubnetDelete(d *schema.ResourceData, meta interface{}) error { name := id.Path["subnets"] vnetName := id.Path["virtualNetworks"] + if v, ok := d.GetOk("network_security_group_id"); ok { + networkSecurityGroupId := v.(string) + networkSecurityGroupName, err := parseNetworkSecurityGroupName(networkSecurityGroupId) + if err != nil { + return err + } + + armMutexKV.Lock(networkSecurityGroupName) + defer armMutexKV.Unlock(networkSecurityGroupName) + } + + if v, ok := d.GetOk("route_table_id"); ok { + rtId := v.(string) + routeTableName, err := parseRouteTableName(rtId) + if err != nil { + return err + } + + armMutexKV.Lock(routeTableName) + defer armMutexKV.Unlock(routeTableName) + } + armMutexKV.Lock(vnetName) defer armMutexKV.Unlock(vnetName) + armMutexKV.Lock(name) + defer armMutexKV.Unlock(name) + _, err = subnetClient.Delete(resGroup, vnetName, name, make(chan struct{})) return err diff --git a/builtin/providers/azurerm/resource_arm_subnet_test.go b/builtin/providers/azurerm/resource_arm_subnet_test.go index 5f1f2bcbe..264b0a540 100644 --- a/builtin/providers/azurerm/resource_arm_subnet_test.go +++ b/builtin/providers/azurerm/resource_arm_subnet_test.go @@ -13,7 +13,7 @@ import ( func TestAccAzureRMSubnet_basic(t *testing.T) { ri := acctest.RandInt() - config := fmt.Sprintf(testAccAzureRMSubnet_basic, ri, ri, ri) + config := fmt.Sprintf(testAccAzureRMSubnet_basic, ri, ri, ri, ri, ri) resource.Test(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, @@ -33,7 +33,7 @@ func TestAccAzureRMSubnet_basic(t *testing.T) { func TestAccAzureRMSubnet_disappears(t *testing.T) { ri := acctest.RandInt() - config := fmt.Sprintf(testAccAzureRMSubnet_basic, ri, ri, ri) + config := fmt.Sprintf(testAccAzureRMSubnet_basic, ri, ri, ri, ri, ri) resource.Test(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, @@ -152,5 +152,22 @@ resource "azurerm_subnet" "test" { resource_group_name = "${azurerm_resource_group.test.name}" virtual_network_name = "${azurerm_virtual_network.test.name}" address_prefix = "10.0.2.0/24" + route_table_id = "${azurerm_route_table.test.id}" +} + +resource "azurerm_route_table" "test" { + name = "acctestroutetable%d" + resource_group_name = "${azurerm_resource_group.test.name}" + location = "West US" +} + +resource "azurerm_route" "test" { + name = "acctestroute%d" + resource_group_name = "${azurerm_resource_group.test.name}" + route_table_name = "${azurerm_route_table.test.name}" + + address_prefix = "10.100.0.0/14" + next_hop_type = "VirtualAppliance" + next_hop_in_ip_address = "10.10.1.1" } ` diff --git a/builtin/providers/azurerm/resource_arm_template_deployment.go b/builtin/providers/azurerm/resource_arm_template_deployment.go index 9349c9b6a..9538f61ee 100644 --- a/builtin/providers/azurerm/resource_arm_template_deployment.go +++ b/builtin/providers/azurerm/resource_arm_template_deployment.go @@ -5,6 +5,7 @@ import ( "fmt" "log" "net/http" + "strconv" "strings" "time" @@ -155,20 +156,40 @@ func resourceArmTemplateDeploymentRead(d *schema.ResourceData, meta interface{}) if resp.Properties.Outputs != nil && len(*resp.Properties.Outputs) > 0 { outputs = make(map[string]string) for key, output := range *resp.Properties.Outputs { + log.Printf("[DEBUG] Processing deployment output %s", key) outputMap := output.(map[string]interface{}) outputValue, ok := outputMap["value"] if !ok { - // No value + log.Printf("[DEBUG] No value - skipping") + continue + } + outputType, ok := outputMap["type"] + if !ok { + log.Printf("[DEBUG] No type - skipping") continue } - outputs[key] = outputValue.(string) + var outputValueString string + switch strings.ToLower(outputType.(string)) { + case "bool": + outputValueString = strconv.FormatBool(outputValue.(bool)) + + case "string": + outputValueString = outputValue.(string) + + case "int": + outputValueString = fmt.Sprint(outputValue) + + default: + log.Printf("[WARN] Ignoring output %s: Outputs of type %s are not currently supported in azurerm_template_deployment.", + key, outputType) + continue + } + outputs[key] = outputValueString } } - d.Set("outputs", outputs) - - return nil + return d.Set("outputs", outputs) } func resourceArmTemplateDeploymentDelete(d *schema.ResourceData, meta interface{}) error { diff --git a/builtin/providers/azurerm/resource_arm_template_deployment_test.go b/builtin/providers/azurerm/resource_arm_template_deployment_test.go index d69716d8b..b3ade2e0a 100644 --- a/builtin/providers/azurerm/resource_arm_template_deployment_test.go +++ b/builtin/providers/azurerm/resource_arm_template_deployment_test.go @@ -68,6 +68,29 @@ func TestAccAzureRMTemplateDeployment_withParams(t *testing.T) { }) } +func TestAccAzureRMTemplateDeployment_withOutputs(t *testing.T) { + ri := acctest.RandInt() + config := fmt.Sprintf(testAccAzureRMTemplateDeployment_withOutputs, ri, ri, ri) + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testCheckAzureRMTemplateDeploymentDestroy, + Steps: []resource.TestStep{ + { + Config: config, + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMTemplateDeploymentExists("azurerm_template_deployment.test"), + resource.TestCheckOutput("tfIntOutput", "-123"), + resource.TestCheckOutput("tfStringOutput", "Standard_GRS"), + resource.TestCheckOutput("tfFalseOutput", "false"), + resource.TestCheckOutput("tfTrueOutput", "true"), + resource.TestCheckResourceAttr("azurerm_template_deployment.test", "outputs.stringOutput", "Standard_GRS"), + ), + }, + }, + }) +} + func TestAccAzureRMTemplateDeployment_withError(t *testing.T) { ri := acctest.RandInt() config := fmt.Sprintf(testAccAzureRMTemplateDeployment_withError, ri, ri) @@ -275,7 +298,14 @@ var testAccAzureRMTemplateDeployment_withParams = ` } output "test" { - value = "${azurerm_template_deployment.test.outputs.testOutput}" + value = "${azurerm_template_deployment.test.outputs["testOutput"]}" + } + + resource "azurerm_storage_container" "using-outputs" { + name = "vhds" + resource_group_name = "${azurerm_resource_group.test.name}" + storage_account_name = "${azurerm_template_deployment.test.outputs["accountName"]}" + container_access_type = "private" } resource "azurerm_template_deployment" "test" { @@ -339,6 +369,10 @@ var testAccAzureRMTemplateDeployment_withParams = ` "testOutput": { "type": "string", "value": "Output Value" + }, + "accountName": { + "type": "string", + "value": "[variables('storageAccountName')]" } } } @@ -352,6 +386,126 @@ DEPLOY ` +var testAccAzureRMTemplateDeployment_withOutputs = ` + resource "azurerm_resource_group" "test" { + name = "acctestRG-%d" + location = "West US" + } + + output "tfStringOutput" { + value = "${azurerm_template_deployment.test.outputs.stringOutput}" + } + + output "tfIntOutput" { + value = "${azurerm_template_deployment.test.outputs.intOutput}" + } + + output "tfFalseOutput" { + value = "${azurerm_template_deployment.test.outputs.falseOutput}" + } + + output "tfTrueOutput" { + value = "${azurerm_template_deployment.test.outputs.trueOutput}" + } + + resource "azurerm_template_deployment" "test" { + name = "acctesttemplate-%d" + resource_group_name = "${azurerm_resource_group.test.name}" + template_body = < 1023 { - errors = append(errors, fmt.Errorf( - "The `disk_size_gb` can only be between 1 and 1023")) - } - return -} - func resourceArmVirtualMachineCreate(d *schema.ResourceData, meta interface{}) error { client := meta.(*ArmClient) vmClient := client.vmClient @@ -685,21 +718,29 @@ func resourceArmVirtualMachineDelete(d *schema.ResourceData, meta interface{}) e // delete OS Disk if opted in if deleteOsDisk := d.Get("delete_os_disk_on_termination").(bool); deleteOsDisk { - log.Printf("[INFO] delete_os_disk_on_termination is enabled, deleting") + log.Printf("[INFO] delete_os_disk_on_termination is enabled, deleting disk from %s", name) osDisk, err := expandAzureRmVirtualMachineOsDisk(d) if err != nil { return fmt.Errorf("Error expanding OS Disk: %s", err) } - if err = resourceArmVirtualMachineDeleteVhd(*osDisk.Vhd.URI, meta); err != nil { - return fmt.Errorf("Error deleting OS Disk VHD: %s", err) + if osDisk.Vhd != nil { + if err = resourceArmVirtualMachineDeleteVhd(*osDisk.Vhd.URI, meta); err != nil { + return fmt.Errorf("Error deleting OS Disk VHD: %s", err) + } + } else if osDisk.ManagedDisk != nil { + if err = resourceArmVirtualMachineDeleteManagedDisk(*osDisk.ManagedDisk.ID, meta); err != nil { + return fmt.Errorf("Error deleting OS Managed Disk: %s", err) + } + } else { + return fmt.Errorf("Unable to locate OS managed disk properties from %s", name) } } // delete Data disks if opted in if deleteDataDisks := d.Get("delete_data_disks_on_termination").(bool); deleteDataDisks { - log.Printf("[INFO] delete_data_disks_on_termination is enabled, deleting each data disk") + log.Printf("[INFO] delete_data_disks_on_termination is enabled, deleting each data disk from %s", name) disks, err := expandAzureRmVirtualMachineDataDisk(d) if err != nil { @@ -707,8 +748,16 @@ func resourceArmVirtualMachineDelete(d *schema.ResourceData, meta interface{}) e } for _, disk := range disks { - if err = resourceArmVirtualMachineDeleteVhd(*disk.Vhd.URI, meta); err != nil { - return fmt.Errorf("Error deleting Data Disk VHD: %s", err) + if disk.Vhd != nil { + if err = resourceArmVirtualMachineDeleteVhd(*disk.Vhd.URI, meta); err != nil { + return fmt.Errorf("Error deleting Data Disk VHD: %s", err) + } + } else if disk.ManagedDisk != nil { + if err = resourceArmVirtualMachineDeleteManagedDisk(*disk.ManagedDisk.ID, meta); err != nil { + return fmt.Errorf("Error deleting Data Managed Disk: %s", err) + } + } else { + return fmt.Errorf("Unable to locate data managed disk properties from %s", name) } } } @@ -752,6 +801,24 @@ func resourceArmVirtualMachineDeleteVhd(uri string, meta interface{}) error { return nil } +func resourceArmVirtualMachineDeleteManagedDisk(managedDiskID string, meta interface{}) error { + diskClient := meta.(*ArmClient).diskClient + + id, err := parseAzureResourceID(managedDiskID) + if err != nil { + return err + } + resGroup := id.ResourceGroup + name := id.Path["disks"] + + _, err = diskClient.Delete(resGroup, name, make(chan struct{})) + if err != nil { + return fmt.Errorf("Error deleting Managed Disk (%s %s) %s", name, resGroup, err) + } + + return nil +} + func resourceArmVirtualMachinePlanHash(v interface{}) int { var buf bytes.Buffer m := v.(map[string]interface{}) @@ -784,8 +851,9 @@ func resourceArmVirtualMachineStorageOsDiskHash(v interface{}) int { var buf bytes.Buffer m := v.(map[string]interface{}) buf.WriteString(fmt.Sprintf("%s-", m["name"].(string))) - buf.WriteString(fmt.Sprintf("%s-", m["vhd_uri"].(string))) - + if m["vhd_uri"] != nil { + buf.WriteString(fmt.Sprintf("%s-", m["vhd_uri"].(string))) + } return hashcode.String(buf.String()) } @@ -883,7 +951,13 @@ func flattenAzureRmVirtualMachineDataDisk(disks *[]compute.DataDisk) interface{} for i, disk := range *disks { l := make(map[string]interface{}) l["name"] = *disk.Name - l["vhd_uri"] = *disk.Vhd.URI + if disk.Vhd != nil { + l["vhd_uri"] = *disk.Vhd.URI + } + if disk.ManagedDisk != nil { + l["managed_disk_type"] = string(disk.ManagedDisk.StorageAccountType) + l["managed_disk_id"] = *disk.ManagedDisk.ID + } l["create_option"] = disk.CreateOption l["caching"] = string(disk.Caching) if disk.DiskSizeGB != nil { @@ -961,7 +1035,7 @@ func flattenAzureRmVirtualMachineOsProfileLinuxConfiguration(config *compute.Lin result["disable_password_authentication"] = *config.DisablePasswordAuthentication if config.SSH != nil && len(*config.SSH.PublicKeys) > 0 { - ssh_keys := make([]map[string]interface{}, len(*config.SSH.PublicKeys)) + ssh_keys := make([]map[string]interface{}, 0, len(*config.SSH.PublicKeys)) for _, i := range *config.SSH.PublicKeys { key := make(map[string]interface{}) key["path"] = *i.Path @@ -982,7 +1056,13 @@ func flattenAzureRmVirtualMachineOsProfileLinuxConfiguration(config *compute.Lin func flattenAzureRmVirtualMachineOsDisk(disk *compute.OSDisk) []interface{} { result := make(map[string]interface{}) result["name"] = *disk.Name - result["vhd_uri"] = *disk.Vhd.URI + if disk.Vhd != nil { + result["vhd_uri"] = *disk.Vhd.URI + } + if disk.ManagedDisk != nil { + result["managed_disk_type"] = string(disk.ManagedDisk.StorageAccountType) + result["managed_disk_id"] = *disk.ManagedDisk.ID + } result["create_option"] = disk.CreateOption result["caching"] = disk.Caching if disk.DiskSizeGB != nil { @@ -1157,22 +1237,22 @@ func expandAzureRmVirtualMachineOsProfileWindowsConfig(d *schema.ResourceData) ( if v := osProfileConfig["winrm"]; v != nil { winRm := v.([]interface{}) if len(winRm) > 0 { - winRmListners := make([]compute.WinRMListener, 0, len(winRm)) + winRmListeners := make([]compute.WinRMListener, 0, len(winRm)) for _, winRmConfig := range winRm { config := winRmConfig.(map[string]interface{}) protocol := config["protocol"].(string) - winRmListner := compute.WinRMListener{ + winRmListener := compute.WinRMListener{ Protocol: compute.ProtocolTypes(protocol), } if v := config["certificate_url"].(string); v != "" { - winRmListner.CertificateURL = &v + winRmListener.CertificateURL = &v } - winRmListners = append(winRmListners, winRmListner) + winRmListeners = append(winRmListeners, winRmListener) } config.WinRM = &compute.WinRMConfiguration{ - Listeners: &winRmListners, + Listeners: &winRmListeners, } } } @@ -1209,19 +1289,48 @@ func expandAzureRmVirtualMachineDataDisk(d *schema.ResourceData) ([]compute.Data config := disk_config.(map[string]interface{}) name := config["name"].(string) - vhd := config["vhd_uri"].(string) createOption := config["create_option"].(string) + vhdURI := config["vhd_uri"].(string) + managedDiskType := config["managed_disk_type"].(string) + managedDiskID := config["managed_disk_id"].(string) lun := int32(config["lun"].(int)) data_disk := compute.DataDisk{ - Name: &name, - Vhd: &compute.VirtualHardDisk{ - URI: &vhd, - }, + Name: &name, Lun: &lun, CreateOption: compute.DiskCreateOptionTypes(createOption), } + if vhdURI != "" { + data_disk.Vhd = &compute.VirtualHardDisk{ + URI: &vhdURI, + } + } + + managedDisk := &compute.ManagedDiskParameters{} + + if managedDiskType != "" { + managedDisk.StorageAccountType = compute.StorageAccountTypes(managedDiskType) + data_disk.ManagedDisk = managedDisk + } + + if managedDiskID != "" { + managedDisk.ID = &managedDiskID + data_disk.ManagedDisk = managedDisk + } + + //BEGIN: code to be removed after GH-13016 is merged + if vhdURI != "" && managedDiskID != "" { + return nil, fmt.Errorf("[ERROR] Conflict between `vhd_uri` and `managed_disk_id` (only one or the other can be used)") + } + if vhdURI != "" && managedDiskType != "" { + return nil, fmt.Errorf("[ERROR] Conflict between `vhd_uri` and `managed_disk_type` (only one or the other can be used)") + } + //END: code to be removed after GH-13016 is merged + if managedDiskID == "" && strings.EqualFold(string(data_disk.CreateOption), string(compute.Attach)) { + return nil, fmt.Errorf("[ERROR] Must specify which disk to attach") + } + if v := config["caching"].(string); v != "" { data_disk.Caching = compute.CachingTypes(v) } @@ -1303,28 +1412,57 @@ func expandAzureRmVirtualMachineNetworkProfile(d *schema.ResourceData) compute.N func expandAzureRmVirtualMachineOsDisk(d *schema.ResourceData) (*compute.OSDisk, error) { disks := d.Get("storage_os_disk").(*schema.Set).List() - disk := disks[0].(map[string]interface{}) + config := disks[0].(map[string]interface{}) - name := disk["name"].(string) - vhdURI := disk["vhd_uri"].(string) - imageURI := disk["image_uri"].(string) - createOption := disk["create_option"].(string) + name := config["name"].(string) + imageURI := config["image_uri"].(string) + createOption := config["create_option"].(string) + vhdURI := config["vhd_uri"].(string) + managedDiskType := config["managed_disk_type"].(string) + managedDiskID := config["managed_disk_id"].(string) osDisk := &compute.OSDisk{ - Name: &name, - Vhd: &compute.VirtualHardDisk{ - URI: &vhdURI, - }, + Name: &name, CreateOption: compute.DiskCreateOptionTypes(createOption), } - if v := disk["image_uri"].(string); v != "" { + if vhdURI != "" { + osDisk.Vhd = &compute.VirtualHardDisk{ + URI: &vhdURI, + } + } + + managedDisk := &compute.ManagedDiskParameters{} + + if managedDiskType != "" { + managedDisk.StorageAccountType = compute.StorageAccountTypes(managedDiskType) + osDisk.ManagedDisk = managedDisk + } + + if managedDiskID != "" { + managedDisk.ID = &managedDiskID + osDisk.ManagedDisk = managedDisk + } + + //BEGIN: code to be removed after GH-13016 is merged + if vhdURI != "" && managedDiskID != "" { + return nil, fmt.Errorf("[ERROR] Conflict between `vhd_uri` and `managed_disk_id` (only one or the other can be used)") + } + if vhdURI != "" && managedDiskType != "" { + return nil, fmt.Errorf("[ERROR] Conflict between `vhd_uri` and `managed_disk_type` (only one or the other can be used)") + } + //END: code to be removed after GH-13016 is merged + if managedDiskID == "" && strings.EqualFold(string(osDisk.CreateOption), string(compute.Attach)) { + return nil, fmt.Errorf("[ERROR] Must specify which disk to attach") + } + + if v := config["image_uri"].(string); v != "" { osDisk.Image = &compute.VirtualHardDisk{ URI: &imageURI, } } - if v := disk["os_type"].(string); v != "" { + if v := config["os_type"].(string); v != "" { if v == "linux" { osDisk.OsType = compute.Linux } else if v == "windows" { @@ -1334,11 +1472,11 @@ func expandAzureRmVirtualMachineOsDisk(d *schema.ResourceData) (*compute.OSDisk, } } - if v := disk["caching"].(string); v != "" { + if v := config["caching"].(string); v != "" { osDisk.Caching = compute.CachingTypes(v) } - if v := disk["disk_size_gb"].(int); v != 0 { + if v := config["disk_size_gb"].(int); v != 0 { diskSize := int32(v) osDisk.DiskSizeGB = &diskSize } diff --git a/builtin/providers/azurerm/resource_arm_virtual_machine_extension.go b/builtin/providers/azurerm/resource_arm_virtual_machine_extension.go index 129e205c5..be772ce55 100644 --- a/builtin/providers/azurerm/resource_arm_virtual_machine_extension.go +++ b/builtin/providers/azurerm/resource_arm_virtual_machine_extension.go @@ -1,13 +1,13 @@ package azurerm import ( - "encoding/json" "fmt" "net/http" - "reflect" "github.com/Azure/azure-sdk-for-go/arm/compute" "github.com/hashicorp/terraform/helper/schema" + "github.com/hashicorp/terraform/helper/structure" + "github.com/hashicorp/terraform/helper/validation" ) func resourceArmVirtualMachineExtensions() *schema.Resource { @@ -21,7 +21,7 @@ func resourceArmVirtualMachineExtensions() *schema.Resource { }, Schema: map[string]*schema.Schema{ - "name": &schema.Schema{ + "name": { Type: schema.TypeString, Required: true, ForceNew: true, @@ -29,29 +29,29 @@ func resourceArmVirtualMachineExtensions() *schema.Resource { "location": locationSchema(), - "resource_group_name": &schema.Schema{ + "resource_group_name": { Type: schema.TypeString, Required: true, ForceNew: true, }, - "virtual_machine_name": &schema.Schema{ + "virtual_machine_name": { Type: schema.TypeString, Required: true, ForceNew: true, }, - "publisher": &schema.Schema{ + "publisher": { Type: schema.TypeString, Required: true, }, - "type": &schema.Schema{ + "type": { Type: schema.TypeString, Required: true, }, - "type_handler_version": &schema.Schema{ + "type_handler_version": { Type: schema.TypeString, Required: true, }, @@ -61,20 +61,20 @@ func resourceArmVirtualMachineExtensions() *schema.Resource { Optional: true, }, - "settings": &schema.Schema{ + "settings": { Type: schema.TypeString, Optional: true, - ValidateFunc: validateJsonString, - DiffSuppressFunc: suppressDiffVirtualMachineExtensionSettings, + ValidateFunc: validation.ValidateJsonString, + DiffSuppressFunc: structure.SuppressJsonDiff, }, // due to the sensitive nature, these are not returned by the API - "protected_settings": &schema.Schema{ + "protected_settings": { Type: schema.TypeString, Optional: true, Sensitive: true, - ValidateFunc: validateJsonString, - DiffSuppressFunc: suppressDiffVirtualMachineExtensionSettings, + ValidateFunc: validation.ValidateJsonString, + DiffSuppressFunc: structure.SuppressJsonDiff, }, "tags": tagsSchema(), @@ -107,7 +107,7 @@ func resourceArmVirtualMachineExtensionsCreate(d *schema.ResourceData, meta inte } if settingsString := d.Get("settings").(string); settingsString != "" { - settings, err := expandArmVirtualMachineExtensionSettings(settingsString) + settings, err := structure.ExpandJsonFromString(settingsString) if err != nil { return fmt.Errorf("unable to parse settings: %s", err) } @@ -115,7 +115,7 @@ func resourceArmVirtualMachineExtensionsCreate(d *schema.ResourceData, meta inte } if protectedSettingsString := d.Get("protected_settings").(string); protectedSettingsString != "" { - protectedSettings, err := expandArmVirtualMachineExtensionSettings(protectedSettingsString) + protectedSettings, err := structure.ExpandJsonFromString(protectedSettingsString) if err != nil { return fmt.Errorf("unable to parse protected_settings: %s", err) } @@ -172,7 +172,7 @@ func resourceArmVirtualMachineExtensionsRead(d *schema.ResourceData, meta interf d.Set("auto_upgrade_minor_version", resp.VirtualMachineExtensionProperties.AutoUpgradeMinorVersion) if resp.VirtualMachineExtensionProperties.Settings != nil { - settings, err := flattenArmVirtualMachineExtensionSettings(*resp.VirtualMachineExtensionProperties.Settings) + settings, err := structure.FlattenJsonToString(*resp.VirtualMachineExtensionProperties.Settings) if err != nil { return fmt.Errorf("unable to parse settings from response: %s", err) } @@ -199,34 +199,3 @@ func resourceArmVirtualMachineExtensionsDelete(d *schema.ResourceData, meta inte return nil } - -func expandArmVirtualMachineExtensionSettings(jsonString string) (map[string]interface{}, error) { - var result map[string]interface{} - - err := json.Unmarshal([]byte(jsonString), &result) - - return result, err -} - -func flattenArmVirtualMachineExtensionSettings(settingsMap map[string]interface{}) (string, error) { - result, err := json.Marshal(settingsMap) - if err != nil { - return "", err - } - - return string(result), nil -} - -func suppressDiffVirtualMachineExtensionSettings(k, old, new string, d *schema.ResourceData) bool { - oldMap, err := expandArmVirtualMachineExtensionSettings(old) - if err != nil { - return false - } - - newMap, err := expandArmVirtualMachineExtensionSettings(new) - if err != nil { - return false - } - - return reflect.DeepEqual(oldMap, newMap) -} diff --git a/builtin/providers/azurerm/resource_arm_virtual_machine_scale_set.go b/builtin/providers/azurerm/resource_arm_virtual_machine_scale_set.go index afadf6552..f810bde97 100644 --- a/builtin/providers/azurerm/resource_arm_virtual_machine_scale_set.go +++ b/builtin/providers/azurerm/resource_arm_virtual_machine_scale_set.go @@ -9,6 +9,8 @@ import ( "github.com/Azure/azure-sdk-for-go/arm/compute" "github.com/hashicorp/terraform/helper/hashcode" "github.com/hashicorp/terraform/helper/schema" + "github.com/hashicorp/terraform/helper/structure" + "github.com/hashicorp/terraform/helper/validation" ) func resourceArmVirtualMachineScaleSet() *schema.Resource { @@ -17,6 +19,9 @@ func resourceArmVirtualMachineScaleSet() *schema.Resource { Read: resourceArmVirtualMachineScaleSetRead, Update: resourceArmVirtualMachineScaleSetCreate, Delete: resourceArmVirtualMachineScaleSetDelete, + Importer: &schema.ResourceImporter{ + State: schema.ImportStatePassthrough, + }, Schema: map[string]*schema.Schema{ "name": { @@ -69,6 +74,13 @@ func resourceArmVirtualMachineScaleSet() *schema.Resource { Optional: true, }, + "single_placement_group": { + Type: schema.TypeBool, + Optional: true, + Default: true, + ForceNew: true, + }, + "os_profile": { Type: schema.TypeSet, Required: true, @@ -94,6 +106,7 @@ func resourceArmVirtualMachineScaleSet() *schema.Resource { "custom_data": { Type: schema.TypeString, Optional: true, + ForceNew: true, StateFunc: userDataStateFunc, }, }, @@ -260,6 +273,14 @@ func resourceArmVirtualMachineScaleSet() *schema.Resource { Elem: &schema.Schema{Type: schema.TypeString}, Set: schema.HashString, }, + + "load_balancer_inbound_nat_rules_ids": { + Type: schema.TypeSet, + Optional: true, + Computed: true, + Elem: &schema.Schema{Type: schema.TypeString}, + Set: schema.HashString, + }, }, }, }, @@ -291,9 +312,21 @@ func resourceArmVirtualMachineScaleSet() *schema.Resource { Set: schema.HashString, }, + "managed_disk_type": { + Type: schema.TypeString, + Optional: true, + Computed: true, + ConflictsWith: []string{"storage_profile_os_disk.vhd_containers"}, + ValidateFunc: validation.StringInSlice([]string{ + string(compute.PremiumLRS), + string(compute.StandardLRS), + }, true), + }, + "caching": { Type: schema.TypeString, - Required: true, + Optional: true, + Computed: true, }, "os_type": { @@ -374,16 +407,16 @@ func resourceArmVirtualMachineScaleSet() *schema.Resource { "settings": { Type: schema.TypeString, Optional: true, - ValidateFunc: validateJsonString, - DiffSuppressFunc: suppressDiffVirtualMachineExtensionSettings, + ValidateFunc: validation.ValidateJsonString, + DiffSuppressFunc: structure.SuppressJsonDiff, }, "protected_settings": { Type: schema.TypeString, Optional: true, Sensitive: true, - ValidateFunc: validateJsonString, - DiffSuppressFunc: suppressDiffVirtualMachineExtensionSettings, + ValidateFunc: validation.ValidateJsonString, + DiffSuppressFunc: structure.SuppressJsonDiff, }, }, }, @@ -437,6 +470,8 @@ func resourceArmVirtualMachineScaleSetCreate(d *schema.ResourceData, meta interf updatePolicy := d.Get("upgrade_policy_mode").(string) overprovision := d.Get("overprovision").(bool) + singlePlacementGroup := d.Get("single_placement_group").(bool) + scaleSetProps := compute.VirtualMachineScaleSetProperties{ UpgradePolicy: &compute.UpgradePolicy{ Mode: compute.UpgradeMode(updatePolicy), @@ -447,7 +482,8 @@ func resourceArmVirtualMachineScaleSetCreate(d *schema.ResourceData, meta interf OsProfile: osProfile, ExtensionProfile: extensions, }, - Overprovision: &overprovision, + Overprovision: &overprovision, + SinglePlacementGroup: &singlePlacementGroup, } scaleSetParams := compute.VirtualMachineScaleSet{ @@ -495,8 +531,9 @@ func resourceArmVirtualMachineScaleSetRead(d *schema.ResourceData, meta interfac return fmt.Errorf("Error making Read request on Azure Virtual Machine Scale Set %s: %s", name, err) } - d.Set("location", resp.Location) d.Set("name", resp.Name) + d.Set("resource_group_name", resGroup) + d.Set("location", azureRMNormalizeLocation(*resp.Location)) if err := d.Set("sku", flattenAzureRmVirtualMachineScaleSetSku(resp.Sku)); err != nil { return fmt.Errorf("[DEBUG] Error setting Virtual Machine Scale Set Sku error: %#v", err) @@ -506,8 +543,14 @@ func resourceArmVirtualMachineScaleSetRead(d *schema.ResourceData, meta interfac d.Set("upgrade_policy_mode", properties.UpgradePolicy.Mode) d.Set("overprovision", properties.Overprovision) + d.Set("single_placement_group", properties.SinglePlacementGroup) - if err := d.Set("os_profile", flattenAzureRMVirtualMachineScaleSetOsProfile(properties.VirtualMachineProfile.OsProfile)); err != nil { + osProfile, err := flattenAzureRMVirtualMachineScaleSetOsProfile(properties.VirtualMachineProfile.OsProfile) + if err != nil { + return fmt.Errorf("[DEBUG] Error flattening Virtual Machine Scale Set OS Profile. Error: %#v", err) + } + + if err := d.Set("os_profile", osProfile); err != nil { return fmt.Errorf("[DEBUG] Error setting Virtual Machine Scale Set OS Profile error: %#v", err) } @@ -576,7 +619,7 @@ func flattenAzureRmVirtualMachineScaleSetOsProfileLinuxConfig(config *compute.Li result["disable_password_authentication"] = *config.DisablePasswordAuthentication if config.SSH != nil && len(*config.SSH.PublicKeys) > 0 { - ssh_keys := make([]map[string]interface{}, len(*config.SSH.PublicKeys)) + ssh_keys := make([]map[string]interface{}, 0, len(*config.SSH.PublicKeys)) for _, i := range *config.SSH.PublicKeys { key := make(map[string]interface{}) key["path"] = *i.Path @@ -696,6 +739,14 @@ func flattenAzureRmVirtualMachineScaleSetNetworkProfile(profile *compute.Virtual config["load_balancer_backend_address_pool_ids"] = schema.NewSet(schema.HashString, addressPools) } + if properties.LoadBalancerInboundNatPools != nil { + inboundNatPools := make([]interface{}, 0, len(*properties.LoadBalancerInboundNatPools)) + for _, rule := range *properties.LoadBalancerInboundNatPools { + inboundNatPools = append(inboundNatPools, *rule.ID) + } + config["load_balancer_inbound_nat_rules_ids"] = schema.NewSet(schema.HashString, inboundNatPools) + } + ipConfigs = append(ipConfigs, config) } @@ -708,7 +759,7 @@ func flattenAzureRmVirtualMachineScaleSetNetworkProfile(profile *compute.Virtual return result } -func flattenAzureRMVirtualMachineScaleSetOsProfile(profile *compute.VirtualMachineScaleSetOSProfile) []interface{} { +func flattenAzureRMVirtualMachineScaleSetOsProfile(profile *compute.VirtualMachineScaleSetOSProfile) ([]interface{}, error) { result := make(map[string]interface{}) result["computer_name_prefix"] = *profile.ComputerNamePrefix @@ -718,12 +769,16 @@ func flattenAzureRMVirtualMachineScaleSetOsProfile(profile *compute.VirtualMachi result["custom_data"] = *profile.CustomData } - return []interface{}{result} + return []interface{}{result}, nil } func flattenAzureRmVirtualMachineScaleSetStorageProfileOSDisk(profile *compute.VirtualMachineScaleSetOSDisk) []interface{} { result := make(map[string]interface{}) - result["name"] = *profile.Name + + if profile.Name != nil { + result["name"] = *profile.Name + } + if profile.Image != nil { result["image"] = *profile.Image.URI } @@ -736,6 +791,10 @@ func flattenAzureRmVirtualMachineScaleSetStorageProfileOSDisk(profile *compute.V result["vhd_containers"] = schema.NewSet(schema.HashString, containers) } + if profile.ManagedDisk != nil { + result["managed_disk_type"] = string(profile.ManagedDisk.StorageAccountType) + } + result["caching"] = profile.Caching result["create_option"] = profile.CreateOption result["os_type"] = profile.OsType @@ -784,7 +843,7 @@ func flattenAzureRmVirtualMachineScaleSetExtensionProfile(profile *compute.Virtu } if properties.Settings != nil { - settings, err := flattenArmVirtualMachineExtensionSettings(*properties.Settings) + settings, err := structure.FlattenJsonToString(*properties.Settings) if err != nil { return nil, err } @@ -826,8 +885,8 @@ func resourceArmVirtualMachineScaleSetStorageProfileOsDiskHash(v interface{}) in m := v.(map[string]interface{}) buf.WriteString(fmt.Sprintf("%s-", m["name"].(string))) - if m["image"] != nil { - buf.WriteString(fmt.Sprintf("%s-", m["image"].(string))) + if m["vhd_containers"] != nil { + buf.WriteString(fmt.Sprintf("%s-", m["vhd_containers"].(*schema.Set).List())) } return hashcode.String(buf.String()) @@ -847,7 +906,11 @@ func resourceArmVirtualMachineScaleSetsOsProfileHash(v interface{}) int { buf.WriteString(fmt.Sprintf("%s-", m["computer_name_prefix"].(string))) buf.WriteString(fmt.Sprintf("%s-", m["admin_username"].(string))) if m["custom_data"] != nil { - buf.WriteString(fmt.Sprintf("%s-", m["custom_data"].(string))) + customData := m["custom_data"].(string) + if !isBase64Encoded(customData) { + customData = base64Encode(customData) + } + buf.WriteString(fmt.Sprintf("%s-", customData)) } return hashcode.String(buf.String()) } @@ -945,6 +1008,18 @@ func expandAzureRmVirtualMachineScaleSetNetworkProfile(d *schema.ResourceData) * ipConfiguration.LoadBalancerBackendAddressPools = &resources } + if v := ipconfig["load_balancer_inbound_nat_rules_ids"]; v != nil { + rules := v.(*schema.Set).List() + rulesResources := make([]compute.SubResource, 0, len(rules)) + for _, m := range rules { + id := m.(string) + rulesResources = append(rulesResources, compute.SubResource{ + ID: &id, + }) + } + ipConfiguration.LoadBalancerInboundNatPools = &rulesResources + } + ipConfigurations = append(ipConfigurations, ipConfiguration) } @@ -1021,9 +1096,11 @@ func expandAzureRMVirtualMachineScaleSetsStorageProfileOsDisk(d *schema.Resource osDiskConfig := osDiskConfigs[0].(map[string]interface{}) name := osDiskConfig["name"].(string) image := osDiskConfig["image"].(string) + vhd_containers := osDiskConfig["vhd_containers"].(*schema.Set).List() caching := osDiskConfig["caching"].(string) osType := osDiskConfig["os_type"].(string) createOption := osDiskConfig["create_option"].(string) + managedDiskType := osDiskConfig["managed_disk_type"].(string) osDisk := &compute.VirtualMachineScaleSetOSDisk{ Name: &name, @@ -1036,18 +1113,40 @@ func expandAzureRMVirtualMachineScaleSetsStorageProfileOsDisk(d *schema.Resource osDisk.Image = &compute.VirtualHardDisk{ URI: &image, } - } else { + } + + if len(vhd_containers) > 0 { var vhdContainers []string - containers := osDiskConfig["vhd_containers"].(*schema.Set).List() - for _, v := range containers { + for _, v := range vhd_containers { str := v.(string) vhdContainers = append(vhdContainers, str) } osDisk.VhdContainers = &vhdContainers } - return osDisk, nil + managedDisk := &compute.VirtualMachineScaleSetManagedDiskParameters{} + if managedDiskType != "" { + if name == "" { + osDisk.Name = nil + managedDisk.StorageAccountType = compute.StorageAccountTypes(managedDiskType) + osDisk.ManagedDisk = managedDisk + } else { + return nil, fmt.Errorf("[ERROR] Conflict between `name` and `managed_disk_type` on `storage_profile_os_disk` (please set name to blank)") + } + } + + //BEGIN: code to be removed after GH-13016 is merged + if image != "" && managedDiskType != "" { + return nil, fmt.Errorf("[ERROR] Conflict between `image` and `managed_disk_type` on `storage_profile_os_disk` (only one or the other can be used)") + } + + if len(vhd_containers) > 0 && managedDiskType != "" { + return nil, fmt.Errorf("[ERROR] Conflict between `vhd_containers` and `managed_disk_type` on `storage_profile_os_disk` (only one or the other can be used)") + } + //END: code to be removed after GH-13016 is merged + + return osDisk, nil } func expandAzureRmVirtualMachineScaleSetStorageProfileImageReference(d *schema.ResourceData) (*compute.ImageReference, error) { @@ -1074,12 +1173,12 @@ func expandAzureRmVirtualMachineScaleSetOsProfileLinuxConfig(d *schema.ResourceD linuxConfig := osProfilesLinuxConfig[0].(map[string]interface{}) disablePasswordAuth := linuxConfig["disable_password_authentication"].(bool) - config := &compute.LinuxConfiguration{ - DisablePasswordAuthentication: &disablePasswordAuth, - } linuxKeys := linuxConfig["ssh_keys"].([]interface{}) sshPublicKeys := make([]compute.SSHPublicKey, 0, len(linuxKeys)) for _, key := range linuxKeys { + if key == nil { + continue + } sshKey := key.(map[string]interface{}) path := sshKey["path"].(string) keyData := sshKey["key_data"].(string) @@ -1092,8 +1191,11 @@ func expandAzureRmVirtualMachineScaleSetOsProfileLinuxConfig(d *schema.ResourceD sshPublicKeys = append(sshPublicKeys, sshPublicKey) } - config.SSH = &compute.SSHConfiguration{ - PublicKeys: &sshPublicKeys, + config := &compute.LinuxConfiguration{ + DisablePasswordAuthentication: &disablePasswordAuth, + SSH: &compute.SSHConfiguration{ + PublicKeys: &sshPublicKeys, + }, } return config, nil @@ -1118,22 +1220,22 @@ func expandAzureRmVirtualMachineScaleSetOsProfileWindowsConfig(d *schema.Resourc if v := osProfileConfig["winrm"]; v != nil { winRm := v.(*schema.Set).List() if len(winRm) > 0 { - winRmListners := make([]compute.WinRMListener, 0, len(winRm)) + winRmListeners := make([]compute.WinRMListener, 0, len(winRm)) for _, winRmConfig := range winRm { config := winRmConfig.(map[string]interface{}) protocol := config["protocol"].(string) - winRmListner := compute.WinRMListener{ + winRmListener := compute.WinRMListener{ Protocol: compute.ProtocolTypes(protocol), } if v := config["certificate_url"].(string); v != "" { - winRmListner.CertificateURL = &v + winRmListener.CertificateURL = &v } - winRmListners = append(winRmListners, winRmListner) + winRmListeners = append(winRmListeners, winRmListener) } config.WinRM = &compute.WinRMConfiguration{ - Listeners: &winRmListners, + Listeners: &winRmListeners, } } } @@ -1227,7 +1329,7 @@ func expandAzureRMVirtualMachineScaleSetExtensions(d *schema.ResourceData) (*com } if s := config["settings"].(string); s != "" { - settings, err := expandArmVirtualMachineExtensionSettings(s) + settings, err := structure.ExpandJsonFromString(s) if err != nil { return nil, fmt.Errorf("unable to parse settings: %s", err) } @@ -1235,7 +1337,7 @@ func expandAzureRMVirtualMachineScaleSetExtensions(d *schema.ResourceData) (*com } if s := config["protected_settings"].(string); s != "" { - protectedSettings, err := expandArmVirtualMachineExtensionSettings(s) + protectedSettings, err := structure.ExpandJsonFromString(s) if err != nil { return nil, fmt.Errorf("unable to parse protected_settings: %s", err) } diff --git a/builtin/providers/azurerm/resource_arm_virtual_machine_scale_set_test.go b/builtin/providers/azurerm/resource_arm_virtual_machine_scale_set_test.go index e9f3d1ef9..2873b9ba3 100644 --- a/builtin/providers/azurerm/resource_arm_virtual_machine_scale_set_test.go +++ b/builtin/providers/azurerm/resource_arm_virtual_machine_scale_set_test.go @@ -3,16 +3,85 @@ package azurerm import ( "fmt" "net/http" + "regexp" "testing" + "github.com/Azure/azure-sdk-for-go/arm/compute" "github.com/hashicorp/terraform/helper/acctest" "github.com/hashicorp/terraform/helper/resource" "github.com/hashicorp/terraform/terraform" ) -func TestAccAzureRMVirtualMachineScaleSet_basicLinux(t *testing.T) { +func TestAccAzureRMVirtualMachineScaleSet_basic(t *testing.T) { ri := acctest.RandInt() - config := fmt.Sprintf(testAccAzureRMVirtualMachineScaleSet_basicLinux, ri, ri, ri, ri, ri, ri, ri, ri) + config := fmt.Sprintf(testAccAzureRMVirtualMachineScaleSet_basic, ri, ri, ri, ri, ri, ri, ri, ri) + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testCheckAzureRMVirtualMachineScaleSetDestroy, + Steps: []resource.TestStep{ + { + Config: config, + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMVirtualMachineScaleSetExists("azurerm_virtual_machine_scale_set.test"), + + // single placement group should default to true + testCheckAzureRMVirtualMachineScaleSetSinglePlacementGroup("azurerm_virtual_machine_scale_set.test", true), + ), + }, + }, + }) +} + +func TestAccAzureRMVirtualMachineScaleSet_singlePlacementGroupFalse(t *testing.T) { + ri := acctest.RandInt() + config := fmt.Sprintf(testAccAzureRMVirtualMachineScaleSet_singlePlacementGroupFalse, ri) + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testCheckAzureRMVirtualMachineScaleSetDestroy, + Steps: []resource.TestStep{ + { + Config: config, + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMVirtualMachineScaleSetExists("azurerm_virtual_machine_scale_set.test"), + testCheckAzureRMVirtualMachineScaleSetSinglePlacementGroup("azurerm_virtual_machine_scale_set.test", false), + ), + }, + }, + }) +} + +func TestAccAzureRMVirtualMachineScaleSet_linuxUpdated(t *testing.T) { + resourceName := "azurerm_virtual_machine_scale_set.test" + ri := acctest.RandInt() + config := testAccAzureRMVirtualMachineScaleSet_linux(ri) + updatedConfig := testAccAzureRMVirtualMachineScaleSet_linuxUpdated(ri) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testCheckAzureRMVirtualMachineScaleSetDestroy, + Steps: []resource.TestStep{ + { + Config: config, + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMVirtualMachineScaleSetExists(resourceName), + ), + }, + { + Config: updatedConfig, + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMVirtualMachineScaleSetExists(resourceName), + ), + }, + }, + }) +} + +func TestAccAzureRMVirtualMachineScaleSet_basicLinux_managedDisk(t *testing.T) { + ri := acctest.RandInt() + config := fmt.Sprintf(testAccAzureRMVirtualMachineScaleSet_basicLinux_managedDisk, ri, ri, ri, ri, ri, ri) resource.Test(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, @@ -30,7 +99,7 @@ func TestAccAzureRMVirtualMachineScaleSet_basicLinux(t *testing.T) { func TestAccAzureRMVirtualMachineScaleSet_basicLinux_disappears(t *testing.T) { ri := acctest.RandInt() - config := fmt.Sprintf(testAccAzureRMVirtualMachineScaleSet_basicLinux, ri, ri, ri, ri, ri, ri, ri, ri) + config := fmt.Sprintf(testAccAzureRMVirtualMachineScaleSet_basic, ri, ri, ri, ri, ri, ri, ri, ri) resource.Test(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, @@ -124,32 +193,57 @@ func TestAccAzureRMVirtualMachineScaleSet_multipleExtensions(t *testing.T) { }) } +func TestAccAzureRMVirtualMachineScaleSet_osDiskTypeConflict(t *testing.T) { + ri := acctest.RandInt() + config := fmt.Sprintf(testAccAzureRMVirtualMachineScaleSet_osDiskTypeConflict, ri, ri, ri, ri, ri, ri, ri) + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testCheckAzureRMVirtualMachineScaleSetDestroy, + Steps: []resource.TestStep{ + { + Config: config, + ExpectError: regexp.MustCompile("Conflict between `vhd_containers`"), + //Use below code instead once GH-13019 has been merged + //ExpectError: regexp.MustCompile("conflicts with storage_profile_os_disk.0.vhd_containers"), + }, + }, + }) +} + +func testGetAzureRMVirtualMachineScaleSet(s *terraform.State, resourceName string) (result *compute.VirtualMachineScaleSet, err error) { + // Ensure we have enough information in state to look up in API + rs, ok := s.RootModule().Resources[resourceName] + if !ok { + return nil, fmt.Errorf("Not found: %s", resourceName) + } + + // Name of the actual scale set + name := rs.Primary.Attributes["name"] + + resourceGroup, hasResourceGroup := rs.Primary.Attributes["resource_group_name"] + if !hasResourceGroup { + return nil, fmt.Errorf("Bad: no resource group found in state for virtual machine: scale set %s", name) + } + + conn := testAccProvider.Meta().(*ArmClient).vmScaleSetClient + + vmss, err := conn.Get(resourceGroup, name) + if err != nil { + return nil, fmt.Errorf("Bad: Get on vmScaleSetClient: %s", err) + } + + if vmss.StatusCode == http.StatusNotFound { + return nil, fmt.Errorf("Bad: VirtualMachineScaleSet %q (resource group: %q) does not exist", name, resourceGroup) + } + + return &vmss, err +} + func testCheckAzureRMVirtualMachineScaleSetExists(name string) resource.TestCheckFunc { return func(s *terraform.State) error { - // Ensure we have enough information in state to look up in API - rs, ok := s.RootModule().Resources[name] - if !ok { - return fmt.Errorf("Not found: %s", name) - } - - name := rs.Primary.Attributes["name"] - resourceGroup, hasResourceGroup := rs.Primary.Attributes["resource_group_name"] - if !hasResourceGroup { - return fmt.Errorf("Bad: no resource group found in state for virtual machine: scale set %s", name) - } - - conn := testAccProvider.Meta().(*ArmClient).vmScaleSetClient - - resp, err := conn.Get(resourceGroup, name) - if err != nil { - return fmt.Errorf("Bad: Get on vmScaleSetClient: %s", err) - } - - if resp.StatusCode == http.StatusNotFound { - return fmt.Errorf("Bad: VirtualMachineScaleSet %q (resource group: %q) does not exist", name, resourceGroup) - } - - return nil + _, err := testGetAzureRMVirtualMachineScaleSet(s, name) + return err } } @@ -205,26 +299,9 @@ func testCheckAzureRMVirtualMachineScaleSetDestroy(s *terraform.State) error { func testCheckAzureRMVirtualMachineScaleSetHasLoadbalancer(name string) resource.TestCheckFunc { return func(s *terraform.State) error { - // Ensure we have enough information in state to look up in API - rs, ok := s.RootModule().Resources[name] - if !ok { - return fmt.Errorf("Not found: %s", name) - } - - name := rs.Primary.Attributes["name"] - resourceGroup, hasResourceGroup := rs.Primary.Attributes["resource_group_name"] - if !hasResourceGroup { - return fmt.Errorf("Bad: no resource group found in state for virtual machine: scale set %s", name) - } - - conn := testAccProvider.Meta().(*ArmClient).vmScaleSetClient - resp, err := conn.Get(resourceGroup, name) + resp, err := testGetAzureRMVirtualMachineScaleSet(s, name) if err != nil { - return fmt.Errorf("Bad: Get on vmScaleSetClient: %s", err) - } - - if resp.StatusCode == http.StatusNotFound { - return fmt.Errorf("Bad: VirtualMachineScaleSet %q (resource group: %q) does not exist", name, resourceGroup) + return err } n := resp.VirtualMachineProfile.NetworkProfile.NetworkInterfaceConfigurations @@ -248,26 +325,9 @@ func testCheckAzureRMVirtualMachineScaleSetHasLoadbalancer(name string) resource func testCheckAzureRMVirtualMachineScaleSetOverprovision(name string) resource.TestCheckFunc { return func(s *terraform.State) error { - // Ensure we have enough information in state to look up in API - rs, ok := s.RootModule().Resources[name] - if !ok { - return fmt.Errorf("Not found: %s", name) - } - - name := rs.Primary.Attributes["name"] - resourceGroup, hasResourceGroup := rs.Primary.Attributes["resource_group_name"] - if !hasResourceGroup { - return fmt.Errorf("Bad: no resource group found in state for virtual machine: scale set %s", name) - } - - conn := testAccProvider.Meta().(*ArmClient).vmScaleSetClient - resp, err := conn.Get(resourceGroup, name) + resp, err := testGetAzureRMVirtualMachineScaleSet(s, name) if err != nil { - return fmt.Errorf("Bad: Get on vmScaleSetClient: %s", err) - } - - if resp.StatusCode == http.StatusNotFound { - return fmt.Errorf("Bad: VirtualMachineScaleSet %q (resource group: %q) does not exist", name, resourceGroup) + return err } if *resp.Overprovision { @@ -278,28 +338,26 @@ func testCheckAzureRMVirtualMachineScaleSetOverprovision(name string) resource.T } } +func testCheckAzureRMVirtualMachineScaleSetSinglePlacementGroup(name string, expectedSinglePlacementGroup bool) resource.TestCheckFunc { + return func(s *terraform.State) error { + resp, err := testGetAzureRMVirtualMachineScaleSet(s, name) + if err != nil { + return err + } + + if *resp.SinglePlacementGroup != expectedSinglePlacementGroup { + return fmt.Errorf("Bad: Overprovision should have been %t for scale set %v", expectedSinglePlacementGroup, name) + } + + return nil + } +} + func testCheckAzureRMVirtualMachineScaleSetExtension(name string) resource.TestCheckFunc { return func(s *terraform.State) error { - // Ensure we have enough information in state to look up in API - rs, ok := s.RootModule().Resources[name] - if !ok { - return fmt.Errorf("Not found: %s", name) - } - - name := rs.Primary.Attributes["name"] - resourceGroup, hasResourceGroup := rs.Primary.Attributes["resource_group_name"] - if !hasResourceGroup { - return fmt.Errorf("Bad: no resource group found in state for virtual machine: scale set %s", name) - } - - conn := testAccProvider.Meta().(*ArmClient).vmScaleSetClient - resp, err := conn.Get(resourceGroup, name) + resp, err := testGetAzureRMVirtualMachineScaleSet(s, name) if err != nil { - return fmt.Errorf("Bad: Get on vmScaleSetClient: %s", err) - } - - if resp.StatusCode == http.StatusNotFound { - return fmt.Errorf("Bad: VirtualMachineScaleSet %q (resource group: %q) does not exist", name, resourceGroup) + return err } n := resp.VirtualMachineProfile.ExtensionProfile.Extensions @@ -311,16 +369,16 @@ func testCheckAzureRMVirtualMachineScaleSetExtension(name string) resource.TestC } } -var testAccAzureRMVirtualMachineScaleSet_basicLinux = ` +var testAccAzureRMVirtualMachineScaleSet_basic = ` resource "azurerm_resource_group" "test" { name = "acctestRG-%d" - location = "West US" + location = "West US 2" } resource "azurerm_virtual_network" "test" { name = "acctvn-%d" address_space = ["10.0.0.0/16"] - location = "West US" + location = "West US 2" resource_group_name = "${azurerm_resource_group.test.name}" } @@ -333,7 +391,7 @@ resource "azurerm_subnet" "test" { resource "azurerm_network_interface" "test" { name = "acctni-%d" - location = "West US" + location = "West US 2" resource_group_name = "${azurerm_resource_group.test.name}" ip_configuration { @@ -346,7 +404,7 @@ resource "azurerm_network_interface" "test" { resource "azurerm_storage_account" "test" { name = "accsa%d" resource_group_name = "${azurerm_resource_group.test.name}" - location = "westus" + location = "West US 2" account_type = "Standard_LRS" tags { @@ -363,12 +421,12 @@ resource "azurerm_storage_container" "test" { resource "azurerm_virtual_machine_scale_set" "test" { name = "acctvmss-%d" - location = "West US" + location = "West US 2" resource_group_name = "${azurerm_resource_group.test.name}" upgrade_policy_mode = "Manual" sku { - name = "Standard_A0" + name = "Standard_D1_v2" tier = "Standard" capacity = 2 } @@ -395,6 +453,198 @@ resource "azurerm_virtual_machine_scale_set" "test" { vhd_containers = ["${azurerm_storage_account.test.primary_blob_endpoint}${azurerm_storage_container.test.name}"] } + storage_profile_image_reference { + publisher = "Canonical" + offer = "UbuntuServer" + sku = "16.04-LTS" + version = "latest" + } +} +` + +var testAccAzureRMVirtualMachineScaleSet_singlePlacementGroupFalse = ` +resource "azurerm_resource_group" "test" { + name = "acctestRG-%[1]d" + location = "West US 2" +} + +resource "azurerm_virtual_network" "test" { + name = "acctvn-%[1]d" + address_space = ["10.0.0.0/16"] + location = "West US 2" + resource_group_name = "${azurerm_resource_group.test.name}" +} + +resource "azurerm_subnet" "test" { + name = "acctsub-%[1]d" + resource_group_name = "${azurerm_resource_group.test.name}" + virtual_network_name = "${azurerm_virtual_network.test.name}" + address_prefix = "10.0.2.0/24" +} + +resource "azurerm_network_interface" "test" { + name = "acctni-%[1]d" + location = "West US 2" + resource_group_name = "${azurerm_resource_group.test.name}" + + ip_configuration { + name = "testconfiguration1" + subnet_id = "${azurerm_subnet.test.id}" + private_ip_address_allocation = "dynamic" + } +} + +resource "azurerm_storage_account" "test" { + name = "accsa%[1]d" + resource_group_name = "${azurerm_resource_group.test.name}" + location = "West US 2" + account_type = "Standard_LRS" + + tags { + environment = "staging" + } +} + +resource "azurerm_storage_container" "test" { + name = "vhds" + resource_group_name = "${azurerm_resource_group.test.name}" + storage_account_name = "${azurerm_storage_account.test.name}" + container_access_type = "private" +} + +resource "azurerm_virtual_machine_scale_set" "test" { + name = "acctvmss-%[1]d" + location = "West US 2" + resource_group_name = "${azurerm_resource_group.test.name}" + upgrade_policy_mode = "Manual" + single_placement_group = false + + sku { + name = "Standard_D1_v2" + tier = "Standard" + capacity = 2 + } + + os_profile { + computer_name_prefix = "testvm-%[1]d" + admin_username = "myadmin" + admin_password = "Passwword1234" + } + + network_profile { + name = "TestNetworkProfile-%[1]d" + primary = true + ip_configuration { + name = "TestIPConfiguration" + subnet_id = "${azurerm_subnet.test.id}" + } + } + + storage_profile_os_disk { + name = "" + caching = "ReadWrite" + create_option = "FromImage" + managed_disk_type = "Standard_LRS" + } + + storage_profile_image_reference { + publisher = "Canonical" + offer = "UbuntuServer" + sku = "16.04-LTS" + version = "latest" + } +} +` + +func testAccAzureRMVirtualMachineScaleSet_linux(rInt int) string { + return fmt.Sprintf(` + resource "azurerm_resource_group" "test" { + name = "acctestrg-%d" + location = "West Europe" +} +resource "azurerm_virtual_network" "test" { + name = "acctestvn-%d" + resource_group_name = "${azurerm_resource_group.test.name}" + location = "${azurerm_resource_group.test.location}" + address_space = ["10.0.0.0/8"] +} +resource "azurerm_subnet" "test" { + name = "acctestsn-%d" + resource_group_name = "${azurerm_resource_group.test.name}" + virtual_network_name = "${azurerm_virtual_network.test.name}" + address_prefix = "10.0.1.0/24" +} +resource "azurerm_storage_account" "test" { + name = "accsa%d" + resource_group_name = "${azurerm_resource_group.test.name}" + location = "${azurerm_resource_group.test.location}" + account_type = "Standard_LRS" +} +resource "azurerm_storage_container" "test" { + name = "acctestsc-%d" + resource_group_name = "${azurerm_resource_group.test.name}" + storage_account_name = "${azurerm_storage_account.test.name}" + container_access_type = "private" +} +resource "azurerm_public_ip" "test" { + name = "acctestpip-%d" + resource_group_name = "${azurerm_resource_group.test.name}" + location = "${azurerm_resource_group.test.location}" + public_ip_address_allocation = "static" +} +resource "azurerm_lb" "test" { + name = "acctestlb-%d" + resource_group_name = "${azurerm_resource_group.test.name}" + location = "${azurerm_resource_group.test.location}" + frontend_ip_configuration { + name = "ip-address" + public_ip_address_id = "${azurerm_public_ip.test.id}" + } +} +resource "azurerm_lb_backend_address_pool" "test" { + name = "acctestbap-%d" + resource_group_name = "${azurerm_resource_group.test.name}" + loadbalancer_id = "${azurerm_lb.test.id}" +} +resource "azurerm_virtual_machine_scale_set" "test" { + name = "acctestvmss-%d" + resource_group_name = "${azurerm_resource_group.test.name}" + location = "${azurerm_resource_group.test.location}" + upgrade_policy_mode = "Automatic" + sku { + name = "Standard_A0" + tier = "Standard" + capacity = "1" + } + os_profile { + computer_name_prefix = "prefix" + admin_username = "ubuntu" + admin_password = "password" + custom_data = "custom data!" + } + os_profile_linux_config { + disable_password_authentication = true + ssh_keys { + path = "/home/ubuntu/.ssh/authorized_keys" + key_data = "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAACAQDCsTcryUl51Q2VSEHqDRNmceUFo55ZtcIwxl2QITbN1RREti5ml/VTytC0yeBOvnZA4x4CFpdw/lCDPk0yrH9Ei5vVkXmOrExdTlT3qI7YaAzj1tUVlBd4S6LX1F7y6VLActvdHuDDuXZXzCDd/97420jrDfWZqJMlUK/EmCE5ParCeHIRIvmBxcEnGfFIsw8xQZl0HphxWOtJil8qsUWSdMyCiJYYQpMoMliO99X40AUc4/AlsyPyT5ddbKk08YrZ+rKDVHF7o29rh4vi5MmHkVgVQHKiKybWlHq+b71gIAUQk9wrJxD+dqt4igrmDSpIjfjwnd+l5UIn5fJSO5DYV4YT/4hwK7OKmuo7OFHD0WyY5YnkYEMtFgzemnRBdE8ulcT60DQpVgRMXFWHvhyCWy0L6sgj1QWDZlLpvsIvNfHsyhKFMG1frLnMt/nP0+YCcfg+v1JYeCKjeoJxB8DWcRBsjzItY0CGmzP8UYZiYKl/2u+2TgFS5r7NWH11bxoUzjKdaa1NLw+ieA8GlBFfCbfWe6YVB9ggUte4VtYFMZGxOjS2bAiYtfgTKFJv+XqORAwExG6+G2eDxIDyo80/OA9IG7Xv/jwQr7D6KDjDuULFcN/iTxuttoKrHeYz1hf5ZQlBdllwJHYx6fK2g8kha6r2JIQKocvsAXiiONqSfw== hello@world.com" + } + } + network_profile { + name = "TestNetworkProfile" + primary = true + ip_configuration { + name = "TestIPConfiguration" + subnet_id = "${azurerm_subnet.test.id}" + load_balancer_backend_address_pool_ids = ["${azurerm_lb_backend_address_pool.test.id}"] + } + } + storage_profile_os_disk { + name = "osDiskProfile" + caching = "ReadWrite" + create_option = "FromImage" + os_type = "linux" + vhd_containers = ["${azurerm_storage_account.test.primary_blob_endpoint}${azurerm_storage_container.test.name}"] + } storage_profile_image_reference { publisher = "Canonical" offer = "UbuntuServer" @@ -402,6 +652,172 @@ resource "azurerm_virtual_machine_scale_set" "test" { version = "latest" } } +`, rInt, rInt, rInt, rInt, rInt, rInt, rInt, rInt, rInt) +} + +func testAccAzureRMVirtualMachineScaleSet_linuxUpdated(rInt int) string { + return fmt.Sprintf(` + resource "azurerm_resource_group" "test" { + name = "acctestrg-%d" + location = "West Europe" +} +resource "azurerm_virtual_network" "test" { + name = "acctestvn-%d" + resource_group_name = "${azurerm_resource_group.test.name}" + location = "${azurerm_resource_group.test.location}" + address_space = ["10.0.0.0/8"] +} +resource "azurerm_subnet" "test" { + name = "acctestsn-%d" + resource_group_name = "${azurerm_resource_group.test.name}" + virtual_network_name = "${azurerm_virtual_network.test.name}" + address_prefix = "10.0.1.0/24" +} +resource "azurerm_storage_account" "test" { + name = "accsa%d" + resource_group_name = "${azurerm_resource_group.test.name}" + location = "${azurerm_resource_group.test.location}" + account_type = "Standard_LRS" +} +resource "azurerm_storage_container" "test" { + name = "acctestsc-%d" + resource_group_name = "${azurerm_resource_group.test.name}" + storage_account_name = "${azurerm_storage_account.test.name}" + container_access_type = "private" +} +resource "azurerm_public_ip" "test" { + name = "acctestpip-%d" + resource_group_name = "${azurerm_resource_group.test.name}" + location = "${azurerm_resource_group.test.location}" + public_ip_address_allocation = "static" +} +resource "azurerm_lb" "test" { + name = "acctestlb-%d" + resource_group_name = "${azurerm_resource_group.test.name}" + location = "${azurerm_resource_group.test.location}" + frontend_ip_configuration { + name = "ip-address" + public_ip_address_id = "${azurerm_public_ip.test.id}" + } +} +resource "azurerm_lb_backend_address_pool" "test" { + name = "acctestbap-%d" + resource_group_name = "${azurerm_resource_group.test.name}" + loadbalancer_id = "${azurerm_lb.test.id}" +} +resource "azurerm_virtual_machine_scale_set" "test" { + name = "acctestvmss-%d" + resource_group_name = "${azurerm_resource_group.test.name}" + location = "${azurerm_resource_group.test.location}" + upgrade_policy_mode = "Automatic" + sku { + name = "Standard_A0" + tier = "Standard" + capacity = "1" + } + os_profile { + computer_name_prefix = "prefix" + admin_username = "ubuntu" + admin_password = "password" + custom_data = "custom data!" + } + os_profile_linux_config { + disable_password_authentication = true + ssh_keys { + path = "/home/ubuntu/.ssh/authorized_keys" + key_data = "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAACAQDCsTcryUl51Q2VSEHqDRNmceUFo55ZtcIwxl2QITbN1RREti5ml/VTytC0yeBOvnZA4x4CFpdw/lCDPk0yrH9Ei5vVkXmOrExdTlT3qI7YaAzj1tUVlBd4S6LX1F7y6VLActvdHuDDuXZXzCDd/97420jrDfWZqJMlUK/EmCE5ParCeHIRIvmBxcEnGfFIsw8xQZl0HphxWOtJil8qsUWSdMyCiJYYQpMoMliO99X40AUc4/AlsyPyT5ddbKk08YrZ+rKDVHF7o29rh4vi5MmHkVgVQHKiKybWlHq+b71gIAUQk9wrJxD+dqt4igrmDSpIjfjwnd+l5UIn5fJSO5DYV4YT/4hwK7OKmuo7OFHD0WyY5YnkYEMtFgzemnRBdE8ulcT60DQpVgRMXFWHvhyCWy0L6sgj1QWDZlLpvsIvNfHsyhKFMG1frLnMt/nP0+YCcfg+v1JYeCKjeoJxB8DWcRBsjzItY0CGmzP8UYZiYKl/2u+2TgFS5r7NWH11bxoUzjKdaa1NLw+ieA8GlBFfCbfWe6YVB9ggUte4VtYFMZGxOjS2bAiYtfgTKFJv+XqORAwExG6+G2eDxIDyo80/OA9IG7Xv/jwQr7D6KDjDuULFcN/iTxuttoKrHeYz1hf5ZQlBdllwJHYx6fK2g8kha6r2JIQKocvsAXiiONqSfw== hello@world.com" + } + } + network_profile { + name = "TestNetworkProfile" + primary = true + ip_configuration { + name = "TestIPConfiguration" + subnet_id = "${azurerm_subnet.test.id}" + load_balancer_backend_address_pool_ids = ["${azurerm_lb_backend_address_pool.test.id}"] + } + } + storage_profile_os_disk { + name = "osDiskProfile" + caching = "ReadWrite" + create_option = "FromImage" + os_type = "linux" + vhd_containers = ["${azurerm_storage_account.test.primary_blob_endpoint}${azurerm_storage_container.test.name}"] + } + storage_profile_image_reference { + publisher = "Canonical" + offer = "UbuntuServer" + sku = "14.04.2-LTS" + version = "latest" + } + tags { + ThisIs = "a test" + } +} +`, rInt, rInt, rInt, rInt, rInt, rInt, rInt, rInt, rInt) +} + +var testAccAzureRMVirtualMachineScaleSet_basicLinux_managedDisk = ` +resource "azurerm_resource_group" "test" { + name = "acctestRG-%d" + location = "West US 2" +} + +resource "azurerm_virtual_network" "test" { + name = "acctvn-%d" + address_space = ["10.0.0.0/16"] + location = "West US 2" + resource_group_name = "${azurerm_resource_group.test.name}" +} + +resource "azurerm_subnet" "test" { + name = "acctsub-%d" + resource_group_name = "${azurerm_resource_group.test.name}" + virtual_network_name = "${azurerm_virtual_network.test.name}" + address_prefix = "10.0.2.0/24" +} + +resource "azurerm_virtual_machine_scale_set" "test" { + name = "acctvmss-%d" + location = "West US 2" + resource_group_name = "${azurerm_resource_group.test.name}" + upgrade_policy_mode = "Manual" + + sku { + name = "Standard_D1_v2" + tier = "Standard" + capacity = 2 + } + + os_profile { + computer_name_prefix = "testvm-%d" + admin_username = "myadmin" + admin_password = "Passwword1234" + } + + network_profile { + name = "TestNetworkProfile-%d" + primary = true + ip_configuration { + name = "TestIPConfiguration" + subnet_id = "${azurerm_subnet.test.id}" + } + } + + storage_profile_os_disk { + name = "" + caching = "ReadWrite" + create_option = "FromImage" + managed_disk_type = "Standard_LRS" + } + + storage_profile_image_reference { + publisher = "Canonical" + offer = "UbuntuServer" + sku = "16.04-LTS" + version = "latest" + } +} ` var testAccAzureRMVirtualMachineScaleSetLoadbalancerTemplate = ` @@ -457,6 +873,17 @@ resource "azurerm_lb_backend_address_pool" "test" { loadbalancer_id = "${azurerm_lb.test.id}" } +resource "azurerm_lb_nat_pool" "test" { + resource_group_name = "${azurerm_resource_group.test.name}" + name = "ssh" + loadbalancer_id = "${azurerm_lb.test.id}" + protocol = "Tcp" + frontend_port_start = 50000 + frontend_port_end = 50119 + backend_port = 22 + frontend_ip_configuration_name = "default" +} + resource "azurerm_virtual_machine_scale_set" "test" { name = "acctvmss-%d" location = "southcentralus" @@ -464,7 +891,7 @@ resource "azurerm_virtual_machine_scale_set" "test" { upgrade_policy_mode = "Manual" sku { - name = "Standard_A0" + name = "Standard_D1_v2" tier = "Standard" capacity = 1 } @@ -482,6 +909,7 @@ resource "azurerm_virtual_machine_scale_set" "test" { name = "TestIPConfiguration" subnet_id = "${azurerm_subnet.test.id}" load_balancer_backend_address_pool_ids = [ "${azurerm_lb_backend_address_pool.test.id}" ] + load_balancer_inbound_nat_rules_ids = ["${azurerm_lb_nat_pool.test.id}"] } } @@ -495,7 +923,7 @@ resource "azurerm_virtual_machine_scale_set" "test" { storage_profile_image_reference { publisher = "Canonical" offer = "UbuntuServer" - sku = "14.04.2-LTS" + sku = "16.04-LTS" version = "latest" } } @@ -543,7 +971,7 @@ resource "azurerm_virtual_machine_scale_set" "test" { overprovision = false sku { - name = "Standard_A0" + name = "Standard_D1_v2" tier = "Standard" capacity = 1 } @@ -573,7 +1001,7 @@ resource "azurerm_virtual_machine_scale_set" "test" { storage_profile_image_reference { publisher = "Canonical" offer = "UbuntuServer" - sku = "14.04.2-LTS" + sku = "16.04-LTS" version = "latest" } } @@ -621,7 +1049,7 @@ resource "azurerm_virtual_machine_scale_set" "test" { overprovision = false sku { - name = "Standard_A0" + name = "Standard_D1_v2" tier = "Standard" capacity = 1 } @@ -651,7 +1079,7 @@ resource "azurerm_virtual_machine_scale_set" "test" { storage_profile_image_reference { publisher = "Canonical" offer = "UbuntuServer" - sku = "14.04.2-LTS" + sku = "16.04-LTS" version = "latest" } @@ -719,7 +1147,7 @@ resource "azurerm_virtual_machine_scale_set" "test" { overprovision = false sku { - name = "Standard_A0" + name = "Standard_D1_v2" tier = "Standard" capacity = 1 } @@ -749,7 +1177,7 @@ resource "azurerm_virtual_machine_scale_set" "test" { storage_profile_image_reference { publisher = "Canonical" offer = "UbuntuServer" - sku = "14.04.2-LTS" + sku = "16.04-LTS" version = "latest" } @@ -782,3 +1210,79 @@ SETTINGS } } ` + +var testAccAzureRMVirtualMachineScaleSet_osDiskTypeConflict = ` +resource "azurerm_resource_group" "test" { + name = "acctestRG-%d" + location = "West US 2" +} + +resource "azurerm_virtual_network" "test" { + name = "acctvn-%d" + address_space = ["10.0.0.0/16"] + location = "West US 2" + resource_group_name = "${azurerm_resource_group.test.name}" +} + +resource "azurerm_subnet" "test" { + name = "acctsub-%d" + resource_group_name = "${azurerm_resource_group.test.name}" + virtual_network_name = "${azurerm_virtual_network.test.name}" + address_prefix = "10.0.2.0/24" +} + +resource "azurerm_network_interface" "test" { + name = "acctni-%d" + location = "West US 2" + resource_group_name = "${azurerm_resource_group.test.name}" + + ip_configuration { + name = "testconfiguration1" + subnet_id = "${azurerm_subnet.test.id}" + private_ip_address_allocation = "dynamic" + } +} + +resource "azurerm_virtual_machine_scale_set" "test" { + name = "acctvmss-%d" + location = "West US 2" + resource_group_name = "${azurerm_resource_group.test.name}" + upgrade_policy_mode = "Manual" + + sku { + name = "Standard_D1_v2" + tier = "Standard" + capacity = 2 + } + + os_profile { + computer_name_prefix = "testvm-%d" + admin_username = "myadmin" + admin_password = "Passwword1234" + } + + network_profile { + name = "TestNetworkProfile-%d" + primary = true + ip_configuration { + name = "TestIPConfiguration" + subnet_id = "${azurerm_subnet.test.id}" + } + } + + storage_profile_os_disk { + name = "" + caching = "ReadWrite" + create_option = "FromImage" + managed_disk_type = "Standard_LRS" + vhd_containers = ["should_cause_conflict"] + } + + storage_profile_image_reference { + publisher = "Canonical" + offer = "UbuntuServer" + sku = "16.04-LTS" + version = "latest" + } +} +` diff --git a/builtin/providers/azurerm/resource_arm_virtual_machine_test.go b/builtin/providers/azurerm/resource_arm_virtual_machine_test.go index b3a42728a..5a81d8e24 100644 --- a/builtin/providers/azurerm/resource_arm_virtual_machine_test.go +++ b/builtin/providers/azurerm/resource_arm_virtual_machine_test.go @@ -6,7 +6,10 @@ import ( "strings" "testing" + "regexp" + "github.com/Azure/azure-sdk-for-go/arm/compute" + "github.com/Azure/azure-sdk-for-go/arm/disk" "github.com/hashicorp/terraform/helper/acctest" "github.com/hashicorp/terraform/helper/resource" "github.com/hashicorp/terraform/terraform" @@ -31,6 +34,63 @@ func TestAccAzureRMVirtualMachine_basicLinuxMachine(t *testing.T) { }) } +func TestAccAzureRMVirtualMachine_basicLinuxMachine_managedDisk_explicit(t *testing.T) { + var vm compute.VirtualMachine + ri := acctest.RandInt() + config := fmt.Sprintf(testAccAzureRMVirtualMachine_basicLinuxMachine_managedDisk_explicit, ri, ri, ri, ri, ri, ri, ri) + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testCheckAzureRMVirtualMachineDestroy, + Steps: []resource.TestStep{ + { + Config: config, + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMVirtualMachineExists("azurerm_virtual_machine.test", &vm), + ), + }, + }, + }) +} + +func TestAccAzureRMVirtualMachine_basicLinuxMachine_managedDisk_implicit(t *testing.T) { + var vm compute.VirtualMachine + ri := acctest.RandInt() + config := fmt.Sprintf(testAccAzureRMVirtualMachine_basicLinuxMachine_managedDisk_implicit, ri, ri, ri, ri, ri, ri, ri) + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testCheckAzureRMVirtualMachineDestroy, + Steps: []resource.TestStep{ + { + Config: config, + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMVirtualMachineExists("azurerm_virtual_machine.test", &vm), + ), + }, + }, + }) +} + +func TestAccAzureRMVirtualMachine_basicLinuxMachine_managedDisk_attach(t *testing.T) { + var vm compute.VirtualMachine + ri := acctest.RandInt() + config := fmt.Sprintf(testAccAzureRMVirtualMachine_basicLinuxMachine_managedDisk_attach, ri, ri, ri, ri, ri, ri, ri, ri) + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testCheckAzureRMVirtualMachineDestroy, + Steps: []resource.TestStep{ + { + Config: config, + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMVirtualMachineExists("azurerm_virtual_machine.test", &vm), + ), + }, + }, + }) +} + func TestAccAzureRMVirtualMachine_basicLinuxMachine_disappears(t *testing.T) { var vm compute.VirtualMachine ri := acctest.RandInt() @@ -44,7 +104,7 @@ func TestAccAzureRMVirtualMachine_basicLinuxMachine_disappears(t *testing.T) { Config: config, Check: resource.ComposeTestCheckFunc( testCheckAzureRMVirtualMachineExists("azurerm_virtual_machine.test", &vm), - testCheckAzureRMVirtualMachineDisappears("azurerm_virtual_machine.test", &vm), + testCheckAzureRMVirtualMachineDisappears("azurerm_virtual_machine.test"), ), ExpectNonEmptyPlan: true, }, @@ -72,6 +132,46 @@ func TestAccAzureRMVirtualMachine_withDataDisk(t *testing.T) { }) } +func TestAccAzureRMVirtualMachine_withDataDisk_managedDisk_explicit(t *testing.T) { + var vm compute.VirtualMachine + + ri := acctest.RandInt() + config := fmt.Sprintf(testAccAzureRMVirtualMachine_withDataDisk_managedDisk_explicit, ri, ri, ri, ri, ri, ri, ri, ri) + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testCheckAzureRMVirtualMachineDestroy, + Steps: []resource.TestStep{ + { + Config: config, + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMVirtualMachineExists("azurerm_virtual_machine.test", &vm), + ), + }, + }, + }) +} + +func TestAccAzureRMVirtualMachine_withDataDisk_managedDisk_implicit(t *testing.T) { + var vm compute.VirtualMachine + + ri := acctest.RandInt() + config := fmt.Sprintf(testAccAzureRMVirtualMachine_withDataDisk_managedDisk_implicit, ri, ri, ri, ri, ri, ri) + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testCheckAzureRMVirtualMachineDestroy, + Steps: []resource.TestStep{ + { + Config: config, + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMVirtualMachineExists("azurerm_virtual_machine.test", &vm), + ), + }, + }, + }) +} + func TestAccAzureRMVirtualMachine_tags(t *testing.T) { var vm compute.VirtualMachine @@ -128,7 +228,7 @@ func TestAccAzureRMVirtualMachine_updateMachineSize(t *testing.T) { Check: resource.ComposeTestCheckFunc( testCheckAzureRMVirtualMachineExists("azurerm_virtual_machine.test", &vm), resource.TestCheckResourceAttr( - "azurerm_virtual_machine.test", "vm_size", "Standard_A0"), + "azurerm_virtual_machine.test", "vm_size", "Standard_D1_v2"), ), }, { @@ -136,7 +236,7 @@ func TestAccAzureRMVirtualMachine_updateMachineSize(t *testing.T) { Check: resource.ComposeTestCheckFunc( testCheckAzureRMVirtualMachineExists("azurerm_virtual_machine.test", &vm), resource.TestCheckResourceAttr( - "azurerm_virtual_machine.test", "vm_size", "Standard_A1"), + "azurerm_virtual_machine.test", "vm_size", "Standard_D2_v2"), ), }, }, @@ -238,8 +338,40 @@ func TestAccAzureRMVirtualMachine_deleteVHDOptOut(t *testing.T) { { Config: postConfig, Check: resource.ComposeTestCheckFunc( - testCheckAzureRMVirtualMachineVHDExistance("myosdisk1.vhd", true), - testCheckAzureRMVirtualMachineVHDExistance("mydatadisk1.vhd", true), + testCheckAzureRMVirtualMachineVHDExistence("myosdisk1.vhd", true), + testCheckAzureRMVirtualMachineVHDExistence("mydatadisk1.vhd", true), + ), + }, + }, + }) +} + +func TestAccAzureRMVirtualMachine_deleteManagedDiskOptOut(t *testing.T) { + var vm compute.VirtualMachine + var osd string + var dtd string + ri := acctest.RandInt() + preConfig := fmt.Sprintf(testAccAzureRMVirtualMachine_withDataDisk_managedDisk_implicit, ri, ri, ri, ri, ri, ri) + postConfig := fmt.Sprintf(testAccAzureRMVirtualMachine_basicLinuxMachineDeleteVM_managedDisk, ri, ri, ri, ri) + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testCheckAzureRMVirtualMachineDestroy, + Steps: []resource.TestStep{ + { + Destroy: false, + Config: preConfig, + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMVirtualMachineExists("azurerm_virtual_machine.test", &vm), + testLookupAzureRMVirtualMachineManagedDiskID(&vm, "myosdisk1", &osd), + testLookupAzureRMVirtualMachineManagedDiskID(&vm, "mydatadisk1", &dtd), + ), + }, + { + Config: postConfig, + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMVirtualMachineManagedDiskExists(&osd, true), + testCheckAzureRMVirtualMachineManagedDiskExists(&dtd, true), ), }, }, @@ -265,8 +397,40 @@ func TestAccAzureRMVirtualMachine_deleteVHDOptIn(t *testing.T) { { Config: postConfig, Check: resource.ComposeTestCheckFunc( - testCheckAzureRMVirtualMachineVHDExistance("myosdisk1.vhd", false), - testCheckAzureRMVirtualMachineVHDExistance("mydatadisk1.vhd", false), + testCheckAzureRMVirtualMachineVHDExistence("myosdisk1.vhd", false), + testCheckAzureRMVirtualMachineVHDExistence("mydatadisk1.vhd", false), + ), + }, + }, + }) +} + +func TestAccAzureRMVirtualMachine_deleteManagedDiskOptIn(t *testing.T) { + var vm compute.VirtualMachine + var osd string + var dtd string + ri := acctest.RandInt() + preConfig := fmt.Sprintf(testAccAzureRMVirtualMachine_basicLinuxMachine_managedDisk_DestroyDisksBefore, ri, ri, ri, ri, ri, ri) + postConfig := fmt.Sprintf(testAccAzureRMVirtualMachine_basicLinuxMachine_managedDisk_DestroyDisksAfter, ri, ri, ri, ri) + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testCheckAzureRMVirtualMachineDestroy, + Steps: []resource.TestStep{ + { + Destroy: false, + Config: preConfig, + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMVirtualMachineExists("azurerm_virtual_machine.test", &vm), + testLookupAzureRMVirtualMachineManagedDiskID(&vm, "myosdisk1", &osd), + testLookupAzureRMVirtualMachineManagedDiskID(&vm, "mydatadisk1", &dtd), + ), + }, + { + Config: postConfig, + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMVirtualMachineManagedDiskExists(&osd, false), + testCheckAzureRMVirtualMachineManagedDiskExists(&dtd, false), ), }, }, @@ -284,14 +448,14 @@ func TestAccAzureRMVirtualMachine_ChangeComputerName(t *testing.T) { Providers: testAccProviders, CheckDestroy: testCheckAzureRMVirtualMachineDestroy, Steps: []resource.TestStep{ - resource.TestStep{ + { Config: preConfig, Check: resource.ComposeTestCheckFunc( testCheckAzureRMVirtualMachineExists("azurerm_virtual_machine.test", &afterCreate), ), }, - resource.TestStep{ + { Config: postConfig, Check: resource.ComposeTestCheckFunc( testCheckAzureRMVirtualMachineExists("azurerm_virtual_machine.test", &afterUpdate), @@ -303,7 +467,7 @@ func TestAccAzureRMVirtualMachine_ChangeComputerName(t *testing.T) { }) } -func TestAccAzureRMVirtualMachine_ChangeAvailbilitySet(t *testing.T) { +func TestAccAzureRMVirtualMachine_ChangeAvailabilitySet(t *testing.T) { var afterCreate, afterUpdate compute.VirtualMachine ri := acctest.RandInt() @@ -314,14 +478,14 @@ func TestAccAzureRMVirtualMachine_ChangeAvailbilitySet(t *testing.T) { Providers: testAccProviders, CheckDestroy: testCheckAzureRMVirtualMachineDestroy, Steps: []resource.TestStep{ - resource.TestStep{ + { Config: preConfig, Check: resource.ComposeTestCheckFunc( testCheckAzureRMVirtualMachineExists("azurerm_virtual_machine.test", &afterCreate), ), }, - resource.TestStep{ + { Config: postConfig, Check: resource.ComposeTestCheckFunc( testCheckAzureRMVirtualMachineExists("azurerm_virtual_machine.test", &afterUpdate), @@ -344,14 +508,14 @@ func TestAccAzureRMVirtualMachine_changeStorageImageReference(t *testing.T) { Providers: testAccProviders, CheckDestroy: testCheckAzureRMVirtualMachineDestroy, Steps: []resource.TestStep{ - resource.TestStep{ + { Config: preConfig, Check: resource.ComposeTestCheckFunc( testCheckAzureRMVirtualMachineExists("azurerm_virtual_machine.test", &afterCreate), ), }, - resource.TestStep{ + { Config: postConfig, Check: resource.ComposeTestCheckFunc( testCheckAzureRMVirtualMachineExists("azurerm_virtual_machine.test", &afterUpdate), @@ -374,14 +538,14 @@ func TestAccAzureRMVirtualMachine_changeOSDiskVhdUri(t *testing.T) { Providers: testAccProviders, CheckDestroy: testCheckAzureRMVirtualMachineDestroy, Steps: []resource.TestStep{ - resource.TestStep{ + { Config: preConfig, Check: resource.ComposeTestCheckFunc( testCheckAzureRMVirtualMachineExists("azurerm_virtual_machine.test", &afterCreate), ), }, - resource.TestStep{ + { Config: postConfig, Check: resource.ComposeTestCheckFunc( testCheckAzureRMVirtualMachineExists("azurerm_virtual_machine.test", &afterUpdate), @@ -438,6 +602,42 @@ func TestAccAzureRMVirtualMachine_changeSSHKey(t *testing.T) { }) } +func TestAccAzureRMVirtualMachine_osDiskTypeConflict(t *testing.T) { + ri := acctest.RandInt() + config := fmt.Sprintf(testAccAzureRMVirtualMachine_osDiskTypeConflict, ri, ri, ri, ri, ri, ri, ri) + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testCheckAzureRMVirtualMachineDestroy, + Steps: []resource.TestStep{ + { + Config: config, + ExpectError: regexp.MustCompile("Conflict between `vhd_uri`"), + //Use below code instead once GH-13019 has been merged + //ExpectError: regexp.MustCompile("conflicts with storage_os_disk.0.vhd_uri"), + }, + }, + }) +} + +func TestAccAzureRMVirtualMachine_dataDiskTypeConflict(t *testing.T) { + ri := acctest.RandInt() + config := fmt.Sprintf(testAccAzureRMVirtualMachine_dataDiskTypeConflict, ri, ri, ri, ri, ri, ri, ri) + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testCheckAzureRMVirtualMachineDestroy, + Steps: []resource.TestStep{ + { + Config: config, + ExpectError: regexp.MustCompile("Conflict between `vhd_uri`"), + //Use below code instead once GH-13019 has been merged + //ExpectError: regexp.MustCompile("conflicts with storage_data_disk.1.vhd_uri"), + }, + }, + }) +} + func testCheckAzureRMVirtualMachineExists(name string, vm *compute.VirtualMachine) resource.TestCheckFunc { return func(s *terraform.State) error { // Ensure we have enough information in state to look up in API @@ -469,6 +669,23 @@ func testCheckAzureRMVirtualMachineExists(name string, vm *compute.VirtualMachin } } +func testCheckAzureRMVirtualMachineManagedDiskExists(managedDiskID *string, shouldExist bool) resource.TestCheckFunc { + return func(s *terraform.State) error { + d, err := testGetAzureRMVirtualMachineManagedDisk(managedDiskID) + if err != nil { + return fmt.Errorf("Error trying to retrieve Managed Disk %s, %s", *managedDiskID, err) + } + if d.StatusCode == http.StatusNotFound && shouldExist { + return fmt.Errorf("Unable to find Managed Disk %s", *managedDiskID) + } + if d.StatusCode != http.StatusNotFound && !shouldExist { + return fmt.Errorf("Found unexpected Managed Disk %s", *managedDiskID) + } + + return nil + } +} + func testAccCheckVirtualMachineRecreated(t *testing.T, before, after *compute.VirtualMachine) resource.TestCheckFunc { return func(s *terraform.State) error { @@ -504,7 +721,7 @@ func testCheckAzureRMVirtualMachineDestroy(s *terraform.State) error { return nil } -func testCheckAzureRMVirtualMachineVHDExistance(name string, shouldExist bool) resource.TestCheckFunc { +func testCheckAzureRMVirtualMachineVHDExistence(name string, shouldExist bool) resource.TestCheckFunc { return func(s *terraform.State) error { for _, rs := range s.RootModule().Resources { if rs.Type != "azurerm_storage_container" { @@ -526,9 +743,9 @@ func testCheckAzureRMVirtualMachineVHDExistance(name string, shouldExist bool) r } if exists && !shouldExist { - return fmt.Errorf("Disk VHD Blob still exists") + return fmt.Errorf("Disk VHD Blob still exists %s %s", containerName, name) } else if !exists && shouldExist { - return fmt.Errorf("Disk VHD Blob should exist") + return fmt.Errorf("Disk VHD Blob should exist %s %s", containerName, name) } } @@ -536,7 +753,7 @@ func testCheckAzureRMVirtualMachineVHDExistance(name string, shouldExist bool) r } } -func testCheckAzureRMVirtualMachineDisappears(name string, vm *compute.VirtualMachine) resource.TestCheckFunc { +func testCheckAzureRMVirtualMachineDisappears(name string) resource.TestCheckFunc { return func(s *terraform.State) error { // Ensure we have enough information in state to look up in API rs, ok := s.RootModule().Resources[name] @@ -599,16 +816,76 @@ func TestAccAzureRMVirtualMachine_primaryNetworkInterfaceId(t *testing.T) { }) } +func testLookupAzureRMVirtualMachineManagedDiskID(vm *compute.VirtualMachine, diskName string, managedDiskID *string) resource.TestCheckFunc { + return func(s *terraform.State) error { + if osd := vm.StorageProfile.OsDisk; osd != nil { + if strings.EqualFold(*osd.Name, diskName) { + if osd.ManagedDisk != nil { + id, err := findAzureRMVirtualMachineManagedDiskID(osd.ManagedDisk) + if err != nil { + return fmt.Errorf("Unable to parse Managed Disk ID for OS Disk %s, %s", diskName, err) + } + *managedDiskID = id + return nil + } + } + } + + for _, dataDisk := range *vm.StorageProfile.DataDisks { + if strings.EqualFold(*dataDisk.Name, diskName) { + if dataDisk.ManagedDisk != nil { + id, err := findAzureRMVirtualMachineManagedDiskID(dataDisk.ManagedDisk) + if err != nil { + return fmt.Errorf("Unable to parse Managed Disk ID for Data Disk %s, %s", diskName, err) + } + *managedDiskID = id + return nil + } + } + } + + return fmt.Errorf("Unable to locate disk %s on vm %s", diskName, *vm.Name) + } +} + +func findAzureRMVirtualMachineManagedDiskID(md *compute.ManagedDiskParameters) (string, error) { + _, err := parseAzureResourceID(*md.ID) + if err != nil { + return "", err + } + return *md.ID, nil +} + +func testGetAzureRMVirtualMachineManagedDisk(managedDiskID *string) (*disk.Model, error) { + armID, err := parseAzureResourceID(*managedDiskID) + if err != nil { + return nil, fmt.Errorf("Unable to parse Managed Disk ID %s, %s", *managedDiskID, err) + } + name := armID.Path["disks"] + resourceGroup := armID.ResourceGroup + conn := testAccProvider.Meta().(*ArmClient).diskClient + d, err := conn.Get(resourceGroup, name) + //check status first since sdk client returns error if not 200 + if d.Response.StatusCode == http.StatusNotFound { + return &d, nil + } + if err != nil { + return nil, err + } + + return &d, nil +} + var testAccAzureRMVirtualMachine_basicLinuxMachine = ` resource "azurerm_resource_group" "test" { name = "acctestRG-%d" - location = "West US" + location = "West US 2" } resource "azurerm_virtual_network" "test" { name = "acctvn-%d" address_space = ["10.0.0.0/16"] - location = "West US" + location = "West US 2" resource_group_name = "${azurerm_resource_group.test.name}" } @@ -621,7 +898,7 @@ resource "azurerm_subnet" "test" { resource "azurerm_network_interface" "test" { name = "acctni-%d" - location = "West US" + location = "West US 2" resource_group_name = "${azurerm_resource_group.test.name}" ip_configuration { @@ -634,7 +911,7 @@ resource "azurerm_network_interface" "test" { resource "azurerm_storage_account" "test" { name = "accsa%d" resource_group_name = "${azurerm_resource_group.test.name}" - location = "westus" + location = "West US 2" account_type = "Standard_LRS" tags { @@ -651,10 +928,10 @@ resource "azurerm_storage_container" "test" { resource "azurerm_virtual_machine" "test" { name = "acctvm-%d" - location = "West US" + location = "West US 2" resource_group_name = "${azurerm_resource_group.test.name}" network_interface_ids = ["${azurerm_network_interface.test.id}"] - vm_size = "Standard_A0" + vm_size = "Standard_D1_v2" storage_image_reference { publisher = "Canonical" @@ -672,7 +949,236 @@ resource "azurerm_virtual_machine" "test" { } os_profile { - computer_name = "hostname%d" + computer_name = "hn%d" + admin_username = "testadmin" + admin_password = "Password1234!" + } + + os_profile_linux_config { + disable_password_authentication = false + } + + tags { + environment = "Production" + cost-center = "Ops" + } +} +` + +var testAccAzureRMVirtualMachine_basicLinuxMachine_managedDisk_explicit = ` +resource "azurerm_resource_group" "test" { + name = "acctestRG-%d" + location = "West US 2" +} + +resource "azurerm_virtual_network" "test" { + name = "acctvn-%d" + address_space = ["10.0.0.0/16"] + location = "West US 2" + resource_group_name = "${azurerm_resource_group.test.name}" +} + +resource "azurerm_subnet" "test" { + name = "acctsub-%d" + resource_group_name = "${azurerm_resource_group.test.name}" + virtual_network_name = "${azurerm_virtual_network.test.name}" + address_prefix = "10.0.2.0/24" +} + +resource "azurerm_network_interface" "test" { + name = "acctni-%d" + location = "West US 2" + resource_group_name = "${azurerm_resource_group.test.name}" + + ip_configuration { + name = "testconfiguration1" + subnet_id = "${azurerm_subnet.test.id}" + private_ip_address_allocation = "dynamic" + } +} + +resource "azurerm_virtual_machine" "test" { + name = "acctvm-%d" + location = "West US 2" + resource_group_name = "${azurerm_resource_group.test.name}" + network_interface_ids = ["${azurerm_network_interface.test.id}"] + vm_size = "Standard_D1_v2" + + storage_image_reference { + publisher = "Canonical" + offer = "UbuntuServer" + sku = "14.04.2-LTS" + version = "latest" + } + + storage_os_disk { + name = "osd-%d" + caching = "ReadWrite" + create_option = "FromImage" + disk_size_gb = "10" + managed_disk_type = "Standard_LRS" + } + + os_profile { + computer_name = "hn%d" + admin_username = "testadmin" + admin_password = "Password1234!" + } + + os_profile_linux_config { + disable_password_authentication = false + } + + tags { + environment = "Production" + cost-center = "Ops" + } +} +` + +var testAccAzureRMVirtualMachine_basicLinuxMachine_managedDisk_implicit = ` +resource "azurerm_resource_group" "test" { + name = "acctestRG-%d" + location = "West US 2" +} + +resource "azurerm_virtual_network" "test" { + name = "acctvn-%d" + address_space = ["10.0.0.0/16"] + location = "West US 2" + resource_group_name = "${azurerm_resource_group.test.name}" +} + +resource "azurerm_subnet" "test" { + name = "acctsub-%d" + resource_group_name = "${azurerm_resource_group.test.name}" + virtual_network_name = "${azurerm_virtual_network.test.name}" + address_prefix = "10.0.2.0/24" +} + +resource "azurerm_network_interface" "test" { + name = "acctni-%d" + location = "West US 2" + resource_group_name = "${azurerm_resource_group.test.name}" + + ip_configuration { + name = "testconfiguration1" + subnet_id = "${azurerm_subnet.test.id}" + private_ip_address_allocation = "dynamic" + } +} + +resource "azurerm_virtual_machine" "test" { + name = "acctvm-%d" + location = "West US 2" + resource_group_name = "${azurerm_resource_group.test.name}" + network_interface_ids = ["${azurerm_network_interface.test.id}"] + vm_size = "Standard_D1_v2" + + storage_image_reference { + publisher = "Canonical" + offer = "UbuntuServer" + sku = "14.04.2-LTS" + version = "latest" + } + + storage_os_disk { + name = "osd-%d" + caching = "ReadWrite" + create_option = "FromImage" + disk_size_gb = "10" + } + + os_profile { + computer_name = "hn%d" + admin_username = "testadmin" + admin_password = "Password1234!" + } + + os_profile_linux_config { + disable_password_authentication = false + } + + tags { + environment = "Production" + cost-center = "Ops" + } +} +` + +var testAccAzureRMVirtualMachine_basicLinuxMachine_managedDisk_attach = ` +resource "azurerm_resource_group" "test" { + name = "acctestRG-%d" + location = "West US 2" +} + +resource "azurerm_virtual_network" "test" { + name = "acctvn-%d" + address_space = ["10.0.0.0/16"] + location = "West US 2" + resource_group_name = "${azurerm_resource_group.test.name}" +} + +resource "azurerm_subnet" "test" { + name = "acctsub-%d" + resource_group_name = "${azurerm_resource_group.test.name}" + virtual_network_name = "${azurerm_virtual_network.test.name}" + address_prefix = "10.0.2.0/24" +} + +resource "azurerm_network_interface" "test" { + name = "acctni-%d" + location = "West US 2" + resource_group_name = "${azurerm_resource_group.test.name}" + + ip_configuration { + name = "testconfiguration1" + subnet_id = "${azurerm_subnet.test.id}" + private_ip_address_allocation = "dynamic" + } +} + +resource "azurerm_managed_disk" "test" { + name = "acctmd-%d" + location = "West US 2" + resource_group_name = "${azurerm_resource_group.test.name}" + storage_account_type = "Standard_LRS" + create_option = "Empty" + disk_size_gb = "1" +} + +resource "azurerm_virtual_machine" "test" { + name = "acctvm-%d" + location = "West US 2" + resource_group_name = "${azurerm_resource_group.test.name}" + network_interface_ids = ["${azurerm_network_interface.test.id}"] + vm_size = "Standard_D1_v2" + + storage_image_reference { + publisher = "Canonical" + offer = "UbuntuServer" + sku = "14.04.2-LTS" + version = "latest" + } + + storage_os_disk { + name = "osd-%d" + caching = "ReadWrite" + create_option = "FromImage" + disk_size_gb = "10" + managed_disk_type = "Standard_LRS" + } + + storage_data_disk { + name = "${azurerm_managed_disk.test.name}" + create_option = "Attach" + disk_size_gb = "1" + lun = 0 + managed_disk_id = "${azurerm_managed_disk.test.id}" + } + + os_profile { + computer_name = "hn%d" admin_username = "testadmin" admin_password = "Password1234!" } @@ -691,13 +1197,13 @@ resource "azurerm_virtual_machine" "test" { var testAccAzureRMVirtualMachine_machineNameBeforeUpdate = ` resource "azurerm_resource_group" "test" { name = "acctestRG-%d" - location = "West US" + location = "West US 2" } resource "azurerm_virtual_network" "test" { name = "acctvn-%d" address_space = ["10.0.0.0/16"] - location = "West US" + location = "West US 2" resource_group_name = "${azurerm_resource_group.test.name}" } @@ -710,7 +1216,7 @@ resource "azurerm_subnet" "test" { resource "azurerm_network_interface" "test" { name = "acctni-%d" - location = "West US" + location = "West US 2" resource_group_name = "${azurerm_resource_group.test.name}" ip_configuration { @@ -723,7 +1229,7 @@ resource "azurerm_network_interface" "test" { resource "azurerm_storage_account" "test" { name = "accsa%d" resource_group_name = "${azurerm_resource_group.test.name}" - location = "westus" + location = "West US 2" account_type = "Standard_LRS" tags { @@ -740,10 +1246,10 @@ resource "azurerm_storage_container" "test" { resource "azurerm_virtual_machine" "test" { name = "acctvm-%d" - location = "West US" + location = "West US 2" resource_group_name = "${azurerm_resource_group.test.name}" network_interface_ids = ["${azurerm_network_interface.test.id}"] - vm_size = "Standard_A0" + vm_size = "Standard_D1_v2" delete_os_disk_on_termination = true storage_image_reference { @@ -761,7 +1267,7 @@ resource "azurerm_virtual_machine" "test" { } os_profile { - computer_name = "hostname%d" + computer_name = "hn%d" admin_username = "testadmin" admin_password = "Password1234!" } @@ -780,18 +1286,18 @@ resource "azurerm_virtual_machine" "test" { var testAccAzureRMVirtualMachine_basicLinuxMachineDestroyDisksBefore = ` resource "azurerm_resource_group" "test" { name = "acctestRG-%d" - location = "West US" + location = "West US 2" } resource "azurerm_resource_group" "test-sa" { name = "acctestRG-sa-%d" - location = "West US" + location = "West US 2" } resource "azurerm_virtual_network" "test" { name = "acctvn-%d" address_space = ["10.0.0.0/16"] - location = "West US" + location = "West US 2" resource_group_name = "${azurerm_resource_group.test.name}" } @@ -804,7 +1310,7 @@ resource "azurerm_subnet" "test" { resource "azurerm_network_interface" "test" { name = "acctni-%d" - location = "West US" + location = "West US 2" resource_group_name = "${azurerm_resource_group.test.name}" ip_configuration { @@ -817,7 +1323,7 @@ resource "azurerm_network_interface" "test" { resource "azurerm_storage_account" "test" { name = "accsa%d" resource_group_name = "${azurerm_resource_group.test-sa.name}" - location = "westus" + location = "West US 2" account_type = "Standard_LRS" tags { @@ -834,10 +1340,10 @@ resource "azurerm_storage_container" "test" { resource "azurerm_virtual_machine" "test" { name = "acctvm-%d" - location = "West US" + location = "West US 2" resource_group_name = "${azurerm_resource_group.test.name}" network_interface_ids = ["${azurerm_network_interface.test.id}"] - vm_size = "Standard_A0" + vm_size = "Standard_D1_v2" storage_image_reference { publisher = "Canonical" @@ -858,7 +1364,7 @@ resource "azurerm_virtual_machine" "test" { storage_data_disk { name = "mydatadisk1" vhd_uri = "${azurerm_storage_account.test.primary_blob_endpoint}${azurerm_storage_container.test.name}/mydatadisk1.vhd" - disk_size_gb = "1023" + disk_size_gb = "1" create_option = "Empty" lun = 0 } @@ -866,7 +1372,87 @@ resource "azurerm_virtual_machine" "test" { delete_data_disks_on_termination = true os_profile { - computer_name = "hostname%d" + computer_name = "hn%d" + admin_username = "testadmin" + admin_password = "Password1234!" + } + + os_profile_linux_config { + disable_password_authentication = false + } + + tags { + environment = "Production" + cost-center = "Ops" + } +} +` + +var testAccAzureRMVirtualMachine_basicLinuxMachine_managedDisk_DestroyDisksBefore = ` +resource "azurerm_resource_group" "test" { + name = "acctestRG-%d" + location = "West US 2" +} + +resource "azurerm_virtual_network" "test" { + name = "acctvn-%d" + address_space = ["10.0.0.0/16"] + location = "West US 2" + resource_group_name = "${azurerm_resource_group.test.name}" +} + +resource "azurerm_subnet" "test" { + name = "acctsub-%d" + resource_group_name = "${azurerm_resource_group.test.name}" + virtual_network_name = "${azurerm_virtual_network.test.name}" + address_prefix = "10.0.2.0/24" +} + +resource "azurerm_network_interface" "test" { + name = "acctni-%d" + location = "West US 2" + resource_group_name = "${azurerm_resource_group.test.name}" + + ip_configuration { + name = "testconfiguration1" + subnet_id = "${azurerm_subnet.test.id}" + private_ip_address_allocation = "dynamic" + } +} + +resource "azurerm_virtual_machine" "test" { + name = "acctvm-%d" + location = "West US 2" + resource_group_name = "${azurerm_resource_group.test.name}" + network_interface_ids = ["${azurerm_network_interface.test.id}"] + vm_size = "Standard_D1_v2" + + storage_image_reference { + publisher = "Canonical" + offer = "UbuntuServer" + sku = "14.04.2-LTS" + version = "latest" + } + + storage_os_disk { + name = "myosdisk1" + caching = "ReadWrite" + create_option = "FromImage" + } + + delete_os_disk_on_termination = true + + storage_data_disk { + name = "mydatadisk1" + disk_size_gb = "1" + create_option = "Empty" + lun = 0 + } + + delete_data_disks_on_termination = true + + os_profile { + computer_name = "hn%d" admin_username = "testadmin" admin_password = "Password1234!" } @@ -885,18 +1471,18 @@ resource "azurerm_virtual_machine" "test" { var testAccAzureRMVirtualMachine_basicLinuxMachineDestroyDisksAfter = ` resource "azurerm_resource_group" "test" { name = "acctestRG-%d" - location = "West US" + location = "West US 2" } resource "azurerm_resource_group" "test-sa" { name = "acctestRG-sa-%d" - location = "West US" + location = "West US 2" } resource "azurerm_virtual_network" "test" { name = "acctvn-%d" address_space = ["10.0.0.0/16"] - location = "West US" + location = "West US 2" resource_group_name = "${azurerm_resource_group.test.name}" } @@ -909,7 +1495,7 @@ resource "azurerm_subnet" "test" { resource "azurerm_network_interface" "test" { name = "acctni-%d" - location = "West US" + location = "West US 2" resource_group_name = "${azurerm_resource_group.test.name}" ip_configuration { @@ -922,7 +1508,7 @@ resource "azurerm_network_interface" "test" { resource "azurerm_storage_account" "test" { name = "accsa%d" resource_group_name = "${azurerm_resource_group.test-sa.name}" - location = "westus" + location = "West US 2" account_type = "Standard_LRS" tags { @@ -938,16 +1524,49 @@ resource "azurerm_storage_container" "test" { } ` +var testAccAzureRMVirtualMachine_basicLinuxMachine_managedDisk_DestroyDisksAfter = ` +resource "azurerm_resource_group" "test" { + name = "acctestRG-%d" + location = "West US 2" +} + +resource "azurerm_virtual_network" "test" { + name = "acctvn-%d" + address_space = ["10.0.0.0/16"] + location = "West US 2" + resource_group_name = "${azurerm_resource_group.test.name}" +} + +resource "azurerm_subnet" "test" { + name = "acctsub-%d" + resource_group_name = "${azurerm_resource_group.test.name}" + virtual_network_name = "${azurerm_virtual_network.test.name}" + address_prefix = "10.0.2.0/24" +} + +resource "azurerm_network_interface" "test" { + name = "acctni-%d" + location = "West US 2" + resource_group_name = "${azurerm_resource_group.test.name}" + + ip_configuration { + name = "testconfiguration1" + subnet_id = "${azurerm_subnet.test.id}" + private_ip_address_allocation = "dynamic" + } +} +` + var testAccAzureRMVirtualMachine_basicLinuxMachineDeleteVM = ` resource "azurerm_resource_group" "test" { name = "acctestRG-%d" - location = "West US" + location = "West US 2" } resource "azurerm_virtual_network" "test" { name = "acctvn-%d" address_space = ["10.0.0.0/16"] - location = "West US" + location = "West US 2" resource_group_name = "${azurerm_resource_group.test.name}" } @@ -960,7 +1579,7 @@ resource "azurerm_subnet" "test" { resource "azurerm_network_interface" "test" { name = "acctni-%d" - location = "West US" + location = "West US 2" resource_group_name = "${azurerm_resource_group.test.name}" ip_configuration { @@ -973,7 +1592,7 @@ resource "azurerm_network_interface" "test" { resource "azurerm_storage_account" "test" { name = "accsa%d" resource_group_name = "${azurerm_resource_group.test.name}" - location = "westus" + location = "West US 2" account_type = "Standard_LRS" tags { @@ -989,16 +1608,16 @@ resource "azurerm_storage_container" "test" { } ` -var testAccAzureRMVirtualMachine_withDataDisk = ` +var testAccAzureRMVirtualMachine_basicLinuxMachineDeleteVM_managedDisk = ` resource "azurerm_resource_group" "test" { name = "acctestRG-%d" - location = "West US" + location = "West US 2" } resource "azurerm_virtual_network" "test" { name = "acctvn-%d" address_space = ["10.0.0.0/16"] - location = "West US" + location = "West US 2" resource_group_name = "${azurerm_resource_group.test.name}" } @@ -1011,7 +1630,40 @@ resource "azurerm_subnet" "test" { resource "azurerm_network_interface" "test" { name = "acctni-%d" - location = "West US" + location = "West US 2" + resource_group_name = "${azurerm_resource_group.test.name}" + + ip_configuration { + name = "testconfiguration1" + subnet_id = "${azurerm_subnet.test.id}" + private_ip_address_allocation = "dynamic" + } +} +` + +var testAccAzureRMVirtualMachine_withDataDisk = ` +resource "azurerm_resource_group" "test" { + name = "acctestRG-%d" + location = "West US 2" +} + +resource "azurerm_virtual_network" "test" { + name = "acctvn-%d" + address_space = ["10.0.0.0/16"] + location = "West US 2" + resource_group_name = "${azurerm_resource_group.test.name}" +} + +resource "azurerm_subnet" "test" { + name = "acctsub-%d" + resource_group_name = "${azurerm_resource_group.test.name}" + virtual_network_name = "${azurerm_virtual_network.test.name}" + address_prefix = "10.0.2.0/24" +} + +resource "azurerm_network_interface" "test" { + name = "acctni-%d" + location = "West US 2" resource_group_name = "${azurerm_resource_group.test.name}" ip_configuration { @@ -1024,7 +1676,7 @@ resource "azurerm_network_interface" "test" { resource "azurerm_storage_account" "test" { name = "accsa%d" resource_group_name = "${azurerm_resource_group.test.name}" - location = "westus" + location = "West US 2" account_type = "Standard_LRS" tags { @@ -1041,10 +1693,10 @@ resource "azurerm_storage_container" "test" { resource "azurerm_virtual_machine" "test" { name = "acctvm-%d" - location = "West US" + location = "West US 2" resource_group_name = "${azurerm_resource_group.test.name}" network_interface_ids = ["${azurerm_network_interface.test.id}"] - vm_size = "Standard_A0" + vm_size = "Standard_D1_v2" storage_image_reference { publisher = "Canonical" @@ -1063,14 +1715,170 @@ resource "azurerm_virtual_machine" "test" { storage_data_disk { name = "mydatadisk1" vhd_uri = "${azurerm_storage_account.test.primary_blob_endpoint}${azurerm_storage_container.test.name}/mydatadisk1.vhd" - disk_size_gb = "1023" + disk_size_gb = "1" create_option = "Empty" caching = "ReadWrite" lun = 0 } os_profile { - computer_name = "hostname%d" + computer_name = "hn%d" + admin_username = "testadmin" + admin_password = "Password1234!" + } + + os_profile_linux_config { + disable_password_authentication = false + } + + tags { + environment = "Production" + cost-center = "Ops" + } +} +` + +var testAccAzureRMVirtualMachine_withDataDisk_managedDisk_explicit = ` +resource "azurerm_resource_group" "test" { + name = "acctestRG-%d" + location = "West US 2" +} + +resource "azurerm_virtual_network" "test" { + name = "acctvn-%d" + address_space = ["10.0.0.0/16"] + location = "West US 2" + resource_group_name = "${azurerm_resource_group.test.name}" +} + +resource "azurerm_subnet" "test" { + name = "acctsub-%d" + resource_group_name = "${azurerm_resource_group.test.name}" + virtual_network_name = "${azurerm_virtual_network.test.name}" + address_prefix = "10.0.2.0/24" +} + +resource "azurerm_network_interface" "test" { + name = "acctni-%d" + location = "West US 2" + resource_group_name = "${azurerm_resource_group.test.name}" + + ip_configuration { + name = "testconfiguration1" + subnet_id = "${azurerm_subnet.test.id}" + private_ip_address_allocation = "dynamic" + } +} + +resource "azurerm_virtual_machine" "test" { + name = "acctvm-%d" + location = "West US 2" + resource_group_name = "${azurerm_resource_group.test.name}" + network_interface_ids = ["${azurerm_network_interface.test.id}"] + vm_size = "Standard_D1_v2" + + storage_image_reference { + publisher = "Canonical" + offer = "UbuntuServer" + sku = "14.04.2-LTS" + version = "latest" + } + + storage_os_disk { + name = "osd-%d" + caching = "ReadWrite" + create_option = "FromImage" + managed_disk_type = "Standard_LRS" + } + + storage_data_disk { + name = "dtd-%d" + disk_size_gb = "1" + create_option = "Empty" + caching = "ReadWrite" + lun = 0 + managed_disk_type = "Standard_LRS" + } + + os_profile { + computer_name = "hn%d" + admin_username = "testadmin" + admin_password = "Password1234!" + } + + os_profile_linux_config { + disable_password_authentication = false + } + + tags { + environment = "Production" + cost-center = "Ops" + } +} +` + +var testAccAzureRMVirtualMachine_withDataDisk_managedDisk_implicit = ` +resource "azurerm_resource_group" "test" { + name = "acctestRG-%d" + location = "West US 2" +} + +resource "azurerm_virtual_network" "test" { + name = "acctvn-%d" + address_space = ["10.0.0.0/16"] + location = "West US 2" + resource_group_name = "${azurerm_resource_group.test.name}" +} + +resource "azurerm_subnet" "test" { + name = "acctsub-%d" + resource_group_name = "${azurerm_resource_group.test.name}" + virtual_network_name = "${azurerm_virtual_network.test.name}" + address_prefix = "10.0.2.0/24" +} + +resource "azurerm_network_interface" "test" { + name = "acctni-%d" + location = "West US 2" + resource_group_name = "${azurerm_resource_group.test.name}" + + ip_configuration { + name = "testconfiguration1" + subnet_id = "${azurerm_subnet.test.id}" + private_ip_address_allocation = "dynamic" + } +} + +resource "azurerm_virtual_machine" "test" { + name = "acctvm-%d" + location = "West US 2" + resource_group_name = "${azurerm_resource_group.test.name}" + network_interface_ids = ["${azurerm_network_interface.test.id}"] + vm_size = "Standard_D1_v2" + + storage_image_reference { + publisher = "Canonical" + offer = "UbuntuServer" + sku = "14.04.2-LTS" + version = "latest" + } + + storage_os_disk { + name = "myosdisk1" + caching = "ReadWrite" + create_option = "FromImage" + } + + storage_data_disk { + name = "mydatadisk1" + disk_size_gb = "1" + create_option = "Empty" + caching = "ReadWrite" + lun = 0 + } + + os_profile { + computer_name = "hn%d" admin_username = "testadmin" admin_password = "Password1234!" } @@ -1089,13 +1897,13 @@ resource "azurerm_virtual_machine" "test" { var testAccAzureRMVirtualMachine_basicLinuxMachineUpdated = ` resource "azurerm_resource_group" "test" { name = "acctestRG-%d" - location = "West US" + location = "West US 2" } resource "azurerm_virtual_network" "test" { name = "acctvn-%d" address_space = ["10.0.0.0/16"] - location = "West US" + location = "West US 2" resource_group_name = "${azurerm_resource_group.test.name}" } @@ -1108,7 +1916,7 @@ resource "azurerm_subnet" "test" { resource "azurerm_network_interface" "test" { name = "acctni-%d" - location = "West US" + location = "West US 2" resource_group_name = "${azurerm_resource_group.test.name}" ip_configuration { @@ -1121,7 +1929,7 @@ resource "azurerm_network_interface" "test" { resource "azurerm_storage_account" "test" { name = "accsa%d" resource_group_name = "${azurerm_resource_group.test.name}" - location = "westus" + location = "West US 2" account_type = "Standard_LRS" tags { @@ -1138,10 +1946,10 @@ resource "azurerm_storage_container" "test" { resource "azurerm_virtual_machine" "test" { name = "acctvm-%d" - location = "West US" + location = "West US 2" resource_group_name = "${azurerm_resource_group.test.name}" network_interface_ids = ["${azurerm_network_interface.test.id}"] - vm_size = "Standard_A0" + vm_size = "Standard_D1_v2" storage_image_reference { publisher = "Canonical" @@ -1158,7 +1966,7 @@ resource "azurerm_virtual_machine" "test" { } os_profile { - computer_name = "hostname%d" + computer_name = "hn%d" admin_username = "testadmin" admin_password = "Password1234!" } @@ -1176,13 +1984,13 @@ resource "azurerm_virtual_machine" "test" { var testAccAzureRMVirtualMachine_updatedLinuxMachine = ` resource "azurerm_resource_group" "test" { name = "acctestRG-%d" - location = "West US" + location = "West US 2" } resource "azurerm_virtual_network" "test" { name = "acctvn-%d" address_space = ["10.0.0.0/16"] - location = "West US" + location = "West US 2" resource_group_name = "${azurerm_resource_group.test.name}" } @@ -1195,7 +2003,7 @@ resource "azurerm_subnet" "test" { resource "azurerm_network_interface" "test" { name = "acctni-%d" - location = "West US" + location = "West US 2" resource_group_name = "${azurerm_resource_group.test.name}" ip_configuration { @@ -1208,7 +2016,7 @@ resource "azurerm_network_interface" "test" { resource "azurerm_storage_account" "test" { name = "accsa%d" resource_group_name = "${azurerm_resource_group.test.name}" - location = "westus" + location = "West US 2" account_type = "Standard_LRS" tags { @@ -1225,10 +2033,10 @@ resource "azurerm_storage_container" "test" { resource "azurerm_virtual_machine" "test" { name = "acctvm-%d" - location = "West US" + location = "West US 2" resource_group_name = "${azurerm_resource_group.test.name}" network_interface_ids = ["${azurerm_network_interface.test.id}"] - vm_size = "Standard_A1" + vm_size = "Standard_D2_v2" storage_image_reference { publisher = "Canonical" @@ -1245,7 +2053,7 @@ resource "azurerm_virtual_machine" "test" { } os_profile { - computer_name = "hostname%d" + computer_name = "hn%d" admin_username = "testadmin" admin_password = "Password1234!" } @@ -1259,13 +2067,13 @@ resource "azurerm_virtual_machine" "test" { var testAccAzureRMVirtualMachine_basicWindowsMachine = ` resource "azurerm_resource_group" "test" { name = "acctestRG-%d" - location = "West US" + location = "West US 2" } resource "azurerm_virtual_network" "test" { name = "acctvn-%d" address_space = ["10.0.0.0/16"] - location = "West US" + location = "West US 2" resource_group_name = "${azurerm_resource_group.test.name}" } @@ -1278,7 +2086,7 @@ resource "azurerm_subnet" "test" { resource "azurerm_network_interface" "test" { name = "acctni-%d" - location = "West US" + location = "West US 2" resource_group_name = "${azurerm_resource_group.test.name}" ip_configuration { @@ -1291,7 +2099,7 @@ resource "azurerm_network_interface" "test" { resource "azurerm_storage_account" "test" { name = "accsa%d" resource_group_name = "${azurerm_resource_group.test.name}" - location = "westus" + location = "West US 2" account_type = "Standard_LRS" tags { @@ -1308,10 +2116,10 @@ resource "azurerm_storage_container" "test" { resource "azurerm_virtual_machine" "test" { name = "acctvm-%d" - location = "West US" + location = "West US 2" resource_group_name = "${azurerm_resource_group.test.name}" network_interface_ids = ["${azurerm_network_interface.test.id}"] - vm_size = "Standard_A0" + vm_size = "Standard_D1_v2" storage_image_reference { publisher = "MicrosoftWindowsServer" @@ -1343,13 +2151,13 @@ resource "azurerm_virtual_machine" "test" { var testAccAzureRMVirtualMachine_windowsUnattendedConfig = ` resource "azurerm_resource_group" "test" { name = "acctestRG-%d" - location = "West US" + location = "West US 2" } resource "azurerm_virtual_network" "test" { name = "acctvn-%d" address_space = ["10.0.0.0/16"] - location = "West US" + location = "West US 2" resource_group_name = "${azurerm_resource_group.test.name}" } @@ -1362,7 +2170,7 @@ resource "azurerm_subnet" "test" { resource "azurerm_network_interface" "test" { name = "acctni-%d" - location = "West US" + location = "West US 2" resource_group_name = "${azurerm_resource_group.test.name}" ip_configuration { @@ -1375,7 +2183,7 @@ resource "azurerm_network_interface" "test" { resource "azurerm_storage_account" "test" { name = "accsa%d" resource_group_name = "${azurerm_resource_group.test.name}" - location = "westus" + location = "West US 2" account_type = "Standard_LRS" tags { @@ -1392,10 +2200,10 @@ resource "azurerm_storage_container" "test" { resource "azurerm_virtual_machine" "test" { name = "acctvm-%d" - location = "West US" + location = "West US 2" resource_group_name = "${azurerm_resource_group.test.name}" network_interface_ids = ["${azurerm_network_interface.test.id}"] - vm_size = "Standard_A0" + vm_size = "Standard_D1_v2" storage_image_reference { publisher = "MicrosoftWindowsServer" @@ -1433,13 +2241,13 @@ resource "azurerm_virtual_machine" "test" { var testAccAzureRMVirtualMachine_diagnosticsProfile = ` resource "azurerm_resource_group" "test" { name = "acctestRG-%d" - location = "West US" + location = "West US 2" } resource "azurerm_virtual_network" "test" { name = "acctvn-%d" address_space = ["10.0.0.0/16"] - location = "West US" + location = "West US 2" resource_group_name = "${azurerm_resource_group.test.name}" } @@ -1452,7 +2260,7 @@ resource "azurerm_subnet" "test" { resource "azurerm_network_interface" "test" { name = "acctni-%d" - location = "West US" + location = "West US 2" resource_group_name = "${azurerm_resource_group.test.name}" ip_configuration { @@ -1465,7 +2273,7 @@ resource "azurerm_network_interface" "test" { resource "azurerm_storage_account" "test" { name = "accsa%d" resource_group_name = "${azurerm_resource_group.test.name}" - location = "westus" + location = "West US 2" account_type = "Standard_LRS" tags { @@ -1482,10 +2290,10 @@ resource "azurerm_storage_container" "test" { resource "azurerm_virtual_machine" "test" { name = "acctvm-%d" - location = "West US" + location = "West US 2" resource_group_name = "${azurerm_resource_group.test.name}" network_interface_ids = ["${azurerm_network_interface.test.id}"] - vm_size = "Standard_A0" + vm_size = "Standard_D1_v2" storage_image_reference { publisher = "MicrosoftWindowsServer" @@ -1524,13 +2332,13 @@ resource "azurerm_virtual_machine" "test" { var testAccAzureRMVirtualMachine_winRMConfig = ` resource "azurerm_resource_group" "test" { name = "acctestRG-%d" - location = "West US" + location = "West US 2" } resource "azurerm_virtual_network" "test" { name = "acctvn-%d" address_space = ["10.0.0.0/16"] - location = "West US" + location = "West US 2" resource_group_name = "${azurerm_resource_group.test.name}" } @@ -1543,7 +2351,7 @@ resource "azurerm_subnet" "test" { resource "azurerm_network_interface" "test" { name = "acctni-%d" - location = "West US" + location = "West US 2" resource_group_name = "${azurerm_resource_group.test.name}" ip_configuration { @@ -1556,7 +2364,7 @@ resource "azurerm_network_interface" "test" { resource "azurerm_storage_account" "test" { name = "accsa%d" resource_group_name = "${azurerm_resource_group.test.name}" - location = "westus" + location = "West US 2" account_type = "Standard_LRS" tags { @@ -1573,10 +2381,10 @@ resource "azurerm_storage_container" "test" { resource "azurerm_virtual_machine" "test" { name = "acctvm-%d" - location = "West US" + location = "West US 2" resource_group_name = "${azurerm_resource_group.test.name}" network_interface_ids = ["${azurerm_network_interface.test.id}"] - vm_size = "Standard_A0" + vm_size = "Standard_D1_v2" storage_image_reference { publisher = "MicrosoftWindowsServer" @@ -1609,13 +2417,13 @@ resource "azurerm_virtual_machine" "test" { var testAccAzureRMVirtualMachine_withAvailabilitySet = ` resource "azurerm_resource_group" "test" { name = "acctestRG-%d" - location = "West US" + location = "West US 2" } resource "azurerm_virtual_network" "test" { name = "acctvn-%d" address_space = ["10.0.0.0/16"] - location = "West US" + location = "West US 2" resource_group_name = "${azurerm_resource_group.test.name}" } @@ -1628,7 +2436,7 @@ var testAccAzureRMVirtualMachine_withAvailabilitySet = ` resource "azurerm_network_interface" "test" { name = "acctni-%d" - location = "West US" + location = "West US 2" resource_group_name = "${azurerm_resource_group.test.name}" ip_configuration { @@ -1641,7 +2449,7 @@ var testAccAzureRMVirtualMachine_withAvailabilitySet = ` resource "azurerm_storage_account" "test" { name = "accsa%d" resource_group_name = "${azurerm_resource_group.test.name}" - location = "westus" + location = "West US 2" account_type = "Standard_LRS" tags { @@ -1651,7 +2459,7 @@ var testAccAzureRMVirtualMachine_withAvailabilitySet = ` resource "azurerm_availability_set" "test" { name = "availabilityset%d" - location = "West US" + location = "West US 2" resource_group_name = "${azurerm_resource_group.test.name}" } @@ -1664,10 +2472,10 @@ var testAccAzureRMVirtualMachine_withAvailabilitySet = ` resource "azurerm_virtual_machine" "test" { name = "acctvm-%d" - location = "West US" + location = "West US 2" resource_group_name = "${azurerm_resource_group.test.name}" network_interface_ids = ["${azurerm_network_interface.test.id}"] - vm_size = "Standard_A0" + vm_size = "Standard_D1_v2" availability_set_id = "${azurerm_availability_set.test.id}" delete_os_disk_on_termination = true @@ -1686,7 +2494,7 @@ var testAccAzureRMVirtualMachine_withAvailabilitySet = ` } os_profile { - computer_name = "hostname%d" + computer_name = "hn%d" admin_username = "testadmin" admin_password = "Password1234!" } @@ -1700,13 +2508,13 @@ var testAccAzureRMVirtualMachine_withAvailabilitySet = ` var testAccAzureRMVirtualMachine_updateAvailabilitySet = ` resource "azurerm_resource_group" "test" { name = "acctestRG-%d" - location = "West US" + location = "West US 2" } resource "azurerm_virtual_network" "test" { name = "acctvn-%d" address_space = ["10.0.0.0/16"] - location = "West US" + location = "West US 2" resource_group_name = "${azurerm_resource_group.test.name}" } @@ -1719,7 +2527,7 @@ var testAccAzureRMVirtualMachine_updateAvailabilitySet = ` resource "azurerm_network_interface" "test" { name = "acctni-%d" - location = "West US" + location = "West US 2" resource_group_name = "${azurerm_resource_group.test.name}" ip_configuration { @@ -1732,7 +2540,7 @@ var testAccAzureRMVirtualMachine_updateAvailabilitySet = ` resource "azurerm_storage_account" "test" { name = "accsa%d" resource_group_name = "${azurerm_resource_group.test.name}" - location = "westus" + location = "West US 2" account_type = "Standard_LRS" tags { @@ -1742,7 +2550,7 @@ var testAccAzureRMVirtualMachine_updateAvailabilitySet = ` resource "azurerm_availability_set" "test" { name = "updatedAvailabilitySet%d" - location = "West US" + location = "West US 2" resource_group_name = "${azurerm_resource_group.test.name}" } @@ -1755,10 +2563,10 @@ var testAccAzureRMVirtualMachine_updateAvailabilitySet = ` resource "azurerm_virtual_machine" "test" { name = "acctvm-%d" - location = "West US" + location = "West US 2" resource_group_name = "${azurerm_resource_group.test.name}" network_interface_ids = ["${azurerm_network_interface.test.id}"] - vm_size = "Standard_A0" + vm_size = "Standard_D1_v2" availability_set_id = "${azurerm_availability_set.test.id}" delete_os_disk_on_termination = true @@ -1777,7 +2585,7 @@ var testAccAzureRMVirtualMachine_updateAvailabilitySet = ` } os_profile { - computer_name = "hostname%d" + computer_name = "hn%d" admin_username = "testadmin" admin_password = "Password1234!" } @@ -1791,13 +2599,13 @@ var testAccAzureRMVirtualMachine_updateAvailabilitySet = ` var testAccAzureRMVirtualMachine_updateMachineName = ` resource "azurerm_resource_group" "test" { name = "acctestRG-%d" - location = "West US" + location = "West US 2" } resource "azurerm_virtual_network" "test" { name = "acctvn-%d" address_space = ["10.0.0.0/16"] - location = "West US" + location = "West US 2" resource_group_name = "${azurerm_resource_group.test.name}" } @@ -1810,7 +2618,7 @@ var testAccAzureRMVirtualMachine_updateMachineName = ` resource "azurerm_network_interface" "test" { name = "acctni-%d" - location = "West US" + location = "West US 2" resource_group_name = "${azurerm_resource_group.test.name}" ip_configuration { @@ -1823,7 +2631,7 @@ var testAccAzureRMVirtualMachine_updateMachineName = ` resource "azurerm_storage_account" "test" { name = "accsa%d" resource_group_name = "${azurerm_resource_group.test.name}" - location = "westus" + location = "West US 2" account_type = "Standard_LRS" tags { @@ -1840,10 +2648,10 @@ var testAccAzureRMVirtualMachine_updateMachineName = ` resource "azurerm_virtual_machine" "test" { name = "acctvm-%d" - location = "West US" + location = "West US 2" resource_group_name = "${azurerm_resource_group.test.name}" network_interface_ids = ["${azurerm_network_interface.test.id}"] - vm_size = "Standard_A0" + vm_size = "Standard_D1_v2" delete_os_disk_on_termination = true storage_image_reference { @@ -1875,13 +2683,13 @@ var testAccAzureRMVirtualMachine_updateMachineName = ` var testAccAzureRMVirtualMachine_basicLinuxMachineStorageImageBefore = ` resource "azurerm_resource_group" "test" { name = "acctestRG-%d" - location = "West US" + location = "West US 2" } resource "azurerm_virtual_network" "test" { name = "acctvn-%d" address_space = ["10.0.0.0/16"] - location = "West US" + location = "West US 2" resource_group_name = "${azurerm_resource_group.test.name}" } @@ -1894,7 +2702,7 @@ resource "azurerm_subnet" "test" { resource "azurerm_network_interface" "test" { name = "acctni-%d" - location = "West US" + location = "West US 2" resource_group_name = "${azurerm_resource_group.test.name}" ip_configuration { @@ -1907,7 +2715,7 @@ resource "azurerm_network_interface" "test" { resource "azurerm_storage_account" "test" { name = "accsa%d" resource_group_name = "${azurerm_resource_group.test.name}" - location = "westus" + location = "West US 2" account_type = "Standard_LRS" tags { @@ -1924,10 +2732,10 @@ resource "azurerm_storage_container" "test" { resource "azurerm_virtual_machine" "test" { name = "acctvm-%d" - location = "West US" + location = "West US 2" resource_group_name = "${azurerm_resource_group.test.name}" network_interface_ids = ["${azurerm_network_interface.test.id}"] - vm_size = "Standard_A0" + vm_size = "Standard_D1_v2" delete_os_disk_on_termination = true storage_image_reference { @@ -1946,7 +2754,7 @@ resource "azurerm_virtual_machine" "test" { } os_profile { - computer_name = "hostname%d" + computer_name = "hn%d" admin_username = "testadmin" admin_password = "Password1234!" } @@ -1965,13 +2773,13 @@ resource "azurerm_virtual_machine" "test" { var testAccAzureRMVirtualMachine_basicLinuxMachineStorageImageAfter = ` resource "azurerm_resource_group" "test" { name = "acctestRG-%d" - location = "West US" + location = "West US 2" } resource "azurerm_virtual_network" "test" { name = "acctvn-%d" address_space = ["10.0.0.0/16"] - location = "West US" + location = "West US 2" resource_group_name = "${azurerm_resource_group.test.name}" } @@ -1984,7 +2792,7 @@ resource "azurerm_subnet" "test" { resource "azurerm_network_interface" "test" { name = "acctni-%d" - location = "West US" + location = "West US 2" resource_group_name = "${azurerm_resource_group.test.name}" ip_configuration { @@ -1997,7 +2805,7 @@ resource "azurerm_network_interface" "test" { resource "azurerm_storage_account" "test" { name = "accsa%d" resource_group_name = "${azurerm_resource_group.test.name}" - location = "westus" + location = "West US 2" account_type = "Standard_LRS" tags { @@ -2014,10 +2822,10 @@ resource "azurerm_storage_container" "test" { resource "azurerm_virtual_machine" "test" { name = "acctvm-%d" - location = "West US" + location = "West US 2" resource_group_name = "${azurerm_resource_group.test.name}" network_interface_ids = ["${azurerm_network_interface.test.id}"] - vm_size = "Standard_A0" + vm_size = "Standard_D1_v2" delete_os_disk_on_termination = true storage_image_reference { @@ -2036,7 +2844,7 @@ resource "azurerm_virtual_machine" "test" { } os_profile { - computer_name = "hostname%d" + computer_name = "hn%d" admin_username = "testadmin" admin_password = "Password1234!" } @@ -2055,13 +2863,13 @@ resource "azurerm_virtual_machine" "test" { var testAccAzureRMVirtualMachine_basicLinuxMachineWithOSDiskVhdUriChanged = ` resource "azurerm_resource_group" "test" { name = "acctestRG-%d" - location = "West US" + location = "West US 2" } resource "azurerm_virtual_network" "test" { name = "acctvn-%d" address_space = ["10.0.0.0/16"] - location = "West US" + location = "West US 2" resource_group_name = "${azurerm_resource_group.test.name}" } @@ -2074,7 +2882,7 @@ resource "azurerm_subnet" "test" { resource "azurerm_network_interface" "test" { name = "acctni-%d" - location = "West US" + location = "West US 2" resource_group_name = "${azurerm_resource_group.test.name}" ip_configuration { @@ -2087,7 +2895,7 @@ resource "azurerm_network_interface" "test" { resource "azurerm_storage_account" "test" { name = "accsa%d" resource_group_name = "${azurerm_resource_group.test.name}" - location = "westus" + location = "West US 2" account_type = "Standard_LRS" tags { @@ -2104,10 +2912,10 @@ resource "azurerm_storage_container" "test" { resource "azurerm_virtual_machine" "test" { name = "acctvm-%d" - location = "West US" + location = "West US 2" resource_group_name = "${azurerm_resource_group.test.name}" network_interface_ids = ["${azurerm_network_interface.test.id}"] - vm_size = "Standard_A0" + vm_size = "Standard_D1_v2" storage_image_reference { publisher = "Canonical" @@ -2125,7 +2933,7 @@ resource "azurerm_virtual_machine" "test" { } os_profile { - computer_name = "hostname%d" + computer_name = "hn%d" admin_username = "testadmin" admin_password = "Password1234!" } @@ -2144,13 +2952,13 @@ resource "azurerm_virtual_machine" "test" { var testAccAzureRMVirtualMachine_windowsLicenseType = ` resource "azurerm_resource_group" "test" { name = "acctestRG-%d" - location = "West US" + location = "West US 2" } resource "azurerm_virtual_network" "test" { name = "acctvn-%d" address_space = ["10.0.0.0/16"] - location = "West US" + location = "West US 2" resource_group_name = "${azurerm_resource_group.test.name}" } @@ -2163,7 +2971,7 @@ resource "azurerm_subnet" "test" { resource "azurerm_network_interface" "test" { name = "acctni-%d" - location = "West US" + location = "West US 2" resource_group_name = "${azurerm_resource_group.test.name}" ip_configuration { @@ -2176,7 +2984,7 @@ resource "azurerm_network_interface" "test" { resource "azurerm_storage_account" "test" { name = "accsa%d" resource_group_name = "${azurerm_resource_group.test.name}" - location = "westus" + location = "West US 2" account_type = "Standard_LRS" tags { @@ -2193,10 +3001,10 @@ resource "azurerm_storage_container" "test" { resource "azurerm_virtual_machine" "test" { name = "acctvm-%d" - location = "West US" + location = "West US 2" resource_group_name = "${azurerm_resource_group.test.name}" network_interface_ids = ["${azurerm_network_interface.test.id}"] - vm_size = "Standard_A0" + vm_size = "Standard_D1_v2" license_type = "Windows_Server" storage_image_reference { @@ -2229,13 +3037,13 @@ resource "azurerm_virtual_machine" "test" { var testAccAzureRMVirtualMachine_plan = ` resource "azurerm_resource_group" "test" { name = "acctestRG-%d" - location = "West US" + location = "West US 2" } resource "azurerm_virtual_network" "test" { name = "acctvn-%d" address_space = ["10.0.0.0/16"] - location = "West US" + location = "West US 2" resource_group_name = "${azurerm_resource_group.test.name}" } @@ -2248,7 +3056,7 @@ resource "azurerm_subnet" "test" { resource "azurerm_network_interface" "test" { name = "acctni-%d" - location = "West US" + location = "West US 2" resource_group_name = "${azurerm_resource_group.test.name}" ip_configuration { @@ -2261,7 +3069,7 @@ resource "azurerm_network_interface" "test" { resource "azurerm_storage_account" "test" { name = "accsa%d" resource_group_name = "${azurerm_resource_group.test.name}" - location = "westus" + location = "West US 2" account_type = "Standard_LRS" tags { @@ -2278,7 +3086,7 @@ resource "azurerm_storage_container" "test" { resource "azurerm_virtual_machine" "test" { name = "acctvm-%d" - location = "West US" + location = "West US 2" resource_group_name = "${azurerm_resource_group.test.name}" network_interface_ids = ["${azurerm_network_interface.test.id}"] vm_size = "Standard_DS1_v2" @@ -2299,7 +3107,7 @@ resource "azurerm_virtual_machine" "test" { } os_profile { - computer_name = "hostname%d" + computer_name = "hn%d" admin_username = "testadmin" admin_password = "Password1234!" } @@ -2372,7 +3180,7 @@ resource "azurerm_virtual_machine" "test" { location = "southcentralus" resource_group_name = "${azurerm_resource_group.test.name}" network_interface_ids = ["${azurerm_network_interface.test.id}"] - vm_size = "Standard_A0" + vm_size = "Standard_D1_v2" storage_image_reference { publisher = "Canonical" @@ -2456,7 +3264,7 @@ resource "azurerm_virtual_machine" "test" { location = "southcentralus" resource_group_name = "${azurerm_resource_group.test.name}" network_interface_ids = ["${azurerm_network_interface.test.id}"] - vm_size = "Standard_A0" + vm_size = "Standard_D1_v2" storage_image_reference { publisher = "Canonical" @@ -2484,6 +3292,176 @@ resource "azurerm_virtual_machine" "test" { } } ` +var testAccAzureRMVirtualMachine_osDiskTypeConflict = ` +resource "azurerm_resource_group" "test" { + name = "acctestRG-%d" + location = "West US 2" +} + +resource "azurerm_virtual_network" "test" { + name = "acctvn-%d" + address_space = ["10.0.0.0/16"] + location = "West US 2" + resource_group_name = "${azurerm_resource_group.test.name}" +} + +resource "azurerm_subnet" "test" { + name = "acctsub-%d" + resource_group_name = "${azurerm_resource_group.test.name}" + virtual_network_name = "${azurerm_virtual_network.test.name}" + address_prefix = "10.0.2.0/24" +} + +resource "azurerm_network_interface" "test" { + name = "acctni-%d" + location = "West US 2" + resource_group_name = "${azurerm_resource_group.test.name}" + + ip_configuration { + name = "testconfiguration1" + subnet_id = "${azurerm_subnet.test.id}" + private_ip_address_allocation = "dynamic" + } +} + +resource "azurerm_virtual_machine" "test" { + name = "acctvm-%d" + location = "West US 2" + resource_group_name = "${azurerm_resource_group.test.name}" + network_interface_ids = ["${azurerm_network_interface.test.id}"] + vm_size = "Standard_D1_v2" + + storage_image_reference { + publisher = "Canonical" + offer = "UbuntuServer" + sku = "14.04.2-LTS" + version = "latest" + } + + storage_os_disk { + name = "osd-%d" + caching = "ReadWrite" + create_option = "FromImage" + disk_size_gb = "10" + managed_disk_type = "Standard_LRS" + vhd_uri = "should_cause_conflict" + } + + storage_data_disk { + name = "mydatadisk1" + caching = "ReadWrite" + create_option = "Empty" + disk_size_gb = "45" + managed_disk_type = "Standard_LRS" + lun = "0" + } + + os_profile { + computer_name = "hn%d" + admin_username = "testadmin" + admin_password = "Password1234!" + } + + os_profile_linux_config { + disable_password_authentication = false + } + + tags { + environment = "Production" + cost-center = "Ops" + } +} +` + +var testAccAzureRMVirtualMachine_dataDiskTypeConflict = ` +resource "azurerm_resource_group" "test" { + name = "acctestRG-%d" + location = "West US 2" +} + +resource "azurerm_virtual_network" "test" { + name = "acctvn-%d" + address_space = ["10.0.0.0/16"] + location = "West US 2" + resource_group_name = "${azurerm_resource_group.test.name}" +} + +resource "azurerm_subnet" "test" { + name = "acctsub-%d" + resource_group_name = "${azurerm_resource_group.test.name}" + virtual_network_name = "${azurerm_virtual_network.test.name}" + address_prefix = "10.0.2.0/24" +} + +resource "azurerm_network_interface" "test" { + name = "acctni-%d" + location = "West US 2" + resource_group_name = "${azurerm_resource_group.test.name}" + + ip_configuration { + name = "testconfiguration1" + subnet_id = "${azurerm_subnet.test.id}" + private_ip_address_allocation = "dynamic" + } +} + +resource "azurerm_virtual_machine" "test" { + name = "acctvm-%d" + location = "West US 2" + resource_group_name = "${azurerm_resource_group.test.name}" + network_interface_ids = ["${azurerm_network_interface.test.id}"] + vm_size = "Standard_D1_v2" + + storage_image_reference { + publisher = "Canonical" + offer = "UbuntuServer" + sku = "14.04.2-LTS" + version = "latest" + } + + storage_os_disk { + name = "osd-%d" + caching = "ReadWrite" + create_option = "FromImage" + disk_size_gb = "10" + managed_disk_type = "Standard_LRS" + } + + storage_data_disk { + name = "mydatadisk1" + caching = "ReadWrite" + create_option = "Empty" + disk_size_gb = "45" + managed_disk_type = "Standard_LRS" + lun = "0" + } + + storage_data_disk { + name = "mydatadisk1" + vhd_uri = "should_cause_conflict" + caching = "ReadWrite" + create_option = "Empty" + disk_size_gb = "45" + managed_disk_type = "Standard_LRS" + lun = "1" + } + + os_profile { + computer_name = "hn%d" + admin_username = "testadmin" + admin_password = "Password1234!" + } + + os_profile_linux_config { + disable_password_authentication = false + } + + tags { + environment = "Production" + cost-center = "Ops" + } +} +` var testAccAzureRMVirtualMachine_primaryNetworkInterfaceId = ` resource "azurerm_resource_group" "test" { diff --git a/builtin/providers/azurerm/resource_arm_virtual_network.go b/builtin/providers/azurerm/resource_arm_virtual_network.go index 5d4ba9a29..c9bdb063c 100644 --- a/builtin/providers/azurerm/resource_arm_virtual_network.go +++ b/builtin/providers/azurerm/resource_arm_virtual_network.go @@ -97,6 +97,21 @@ func resourceArmVirtualNetworkCreate(d *schema.ResourceData, meta interface{}) e Tags: expandTags(tags), } + networkSecurityGroupNames := make([]string, 0) + for _, subnet := range *vnet.VirtualNetworkPropertiesFormat.Subnets { + if subnet.NetworkSecurityGroup != nil { + nsgName, err := parseNetworkSecurityGroupName(*subnet.NetworkSecurityGroup.ID) + if err != nil { + return err + } + + networkSecurityGroupNames = append(networkSecurityGroupNames, nsgName) + } + } + + azureRMLockMultiple(&networkSecurityGroupNames) + defer azureRMUnlockMultiple(&networkSecurityGroupNames) + _, err := vnetClient.CreateOrUpdate(resGroup, name, vnet, make(chan struct{})) if err != nil { return err @@ -182,6 +197,14 @@ func resourceArmVirtualNetworkDelete(d *schema.ResourceData, meta interface{}) e resGroup := id.ResourceGroup name := id.Path["virtualNetworks"] + nsgNames, err := expandAzureRmVirtualNetworkVirtualNetworkSecurityGroupNames(d) + if err != nil { + return fmt.Errorf("[ERROR] Error parsing Network Security Group ID's: %+v", err) + } + + azureRMLockMultiple(&nsgNames) + defer azureRMUnlockMultiple(&nsgNames) + _, err = vnetClient.Delete(resGroup, name, make(chan struct{})) return err @@ -245,3 +268,29 @@ func resourceAzureSubnetHash(v interface{}) int { } return hashcode.String(subnet) } + +func expandAzureRmVirtualNetworkVirtualNetworkSecurityGroupNames(d *schema.ResourceData) ([]string, error) { + nsgNames := make([]string, 0) + + if v, ok := d.GetOk("subnet"); ok { + subnets := v.(*schema.Set).List() + for _, subnet := range subnets { + subnet, ok := subnet.(map[string]interface{}) + if !ok { + return nil, fmt.Errorf("[ERROR] Subnet should be a Hash - was '%+v'", subnet) + } + + networkSecurityGroupId := subnet["security_group"].(string) + if networkSecurityGroupId != "" { + nsgName, err := parseNetworkSecurityGroupName(networkSecurityGroupId) + if err != nil { + return nil, err + } + + nsgNames = append(nsgNames, nsgName) + } + } + } + + return nsgNames, nil +} diff --git a/builtin/providers/azurerm/resourceid.go b/builtin/providers/azurerm/resourceid.go index b05f4d75f..4f89945e7 100644 --- a/builtin/providers/azurerm/resourceid.go +++ b/builtin/providers/azurerm/resourceid.go @@ -53,6 +53,11 @@ func parseAzureResourceID(id string) (*ResourceID, error) { key := components[current] value := components[current+1] + // Check key/value for empty strings. + if key == "" || value == "" { + return nil, fmt.Errorf("Key/Value cannot be empty strings. Key: '%s', Value: '%s'", key, value) + } + // Catch the subscriptionID before it can be overwritten by another "subscriptions" // value in the ID which is the case for the Service Bus subscription resource if key == "subscriptions" && subscriptionID == "" { @@ -95,3 +100,21 @@ func parseAzureResourceID(id string) (*ResourceID, error) { return idObj, nil } + +func parseNetworkSecurityGroupName(networkSecurityGroupId string) (string, error) { + id, err := parseAzureResourceID(networkSecurityGroupId) + if err != nil { + return "", fmt.Errorf("[ERROR] Unable to Parse Network Security Group ID '%s': %+v", networkSecurityGroupId, err) + } + + return id.Path["networkSecurityGroups"], nil +} + +func parseRouteTableName(routeTableId string) (string, error) { + id, err := parseAzureResourceID(routeTableId) + if err != nil { + return "", fmt.Errorf("[ERROR] Unable to parse Route Table ID '%s': %+v", routeTableId, err) + } + + return id.Path["routeTables"], nil +} diff --git a/builtin/providers/azurerm/resourceid_test.go b/builtin/providers/azurerm/resourceid_test.go index dff6ed800..4359b70d1 100644 --- a/builtin/providers/azurerm/resourceid_test.go +++ b/builtin/providers/azurerm/resourceid_test.go @@ -11,6 +11,18 @@ func TestParseAzureResourceID(t *testing.T) { expectedResourceID *ResourceID expectError bool }{ + { + // Missing "resourceGroups". + "/subscriptions/00000000-0000-0000-0000-000000000000//myResourceGroup/", + nil, + true, + }, + { + // Empty resource group ID. + "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups//", + nil, + true, + }, { "random", nil, diff --git a/builtin/providers/azurerm/validators.go b/builtin/providers/azurerm/validators.go index 2b8ef82f2..2151f09e0 100644 --- a/builtin/providers/azurerm/validators.go +++ b/builtin/providers/azurerm/validators.go @@ -6,13 +6,6 @@ import ( "github.com/satori/uuid" ) -func validateJsonString(v interface{}, k string) (ws []string, errors []error) { - if _, err := normalizeJsonString(v); err != nil { - errors = append(errors, fmt.Errorf("%q contains an invalid JSON: %s", k, err)) - } - return -} - func validateUUID(v interface{}, k string) (ws []string, errors []error) { if _, err := uuid.FromString(v.(string)); err != nil { errors = append(errors, fmt.Errorf("%q is an invalid UUUID: %s", k, err)) diff --git a/builtin/providers/azurerm/validators_test.go b/builtin/providers/azurerm/validators_test.go deleted file mode 100644 index 66984be06..000000000 --- a/builtin/providers/azurerm/validators_test.go +++ /dev/null @@ -1,58 +0,0 @@ -package azurerm - -import "testing" - -func TestValidateJsonString(t *testing.T) { - type testCases struct { - Value string - ErrCount int - } - - invalidCases := []testCases{ - { - Value: `{0:"1"}`, - ErrCount: 1, - }, - { - Value: `{'abc':1}`, - ErrCount: 1, - }, - { - Value: `{"def":}`, - ErrCount: 1, - }, - { - Value: `{"xyz":[}}`, - ErrCount: 1, - }, - } - - for _, tc := range invalidCases { - _, errors := validateJsonString(tc.Value, "json") - if len(errors) != tc.ErrCount { - t.Fatalf("Expected %q to trigger a validation error.", tc.Value) - } - } - - validCases := []testCases{ - { - Value: ``, - ErrCount: 0, - }, - { - Value: `{}`, - ErrCount: 0, - }, - { - Value: `{"abc":["1","2"]}`, - ErrCount: 0, - }, - } - - for _, tc := range validCases { - _, errors := validateJsonString(tc.Value, "json") - if len(errors) != tc.ErrCount { - t.Fatalf("Expected %q not to trigger a validation error.", tc.Value) - } - } -} diff --git a/builtin/providers/bitbucket/client.go b/builtin/providers/bitbucket/client.go index 02b9ed0db..bd2cebcce 100644 --- a/builtin/providers/bitbucket/client.go +++ b/builtin/providers/bitbucket/client.go @@ -2,64 +2,107 @@ package bitbucket import ( "bytes" + "encoding/json" + "fmt" + "io" + "io/ioutil" + "log" "net/http" ) +// Error represents a error from the bitbucket api. +type Error struct { + APIError struct { + Message string `json:"message,omitempty"` + } `json:"error,omitempty"` + Type string `json:"type,omitempty"` + StatusCode int + Endpoint string +} + +func (e Error) Error() string { + return fmt.Sprintf("API Error: %d %s %s", e.StatusCode, e.Endpoint, e.APIError.Message) +} + +const ( + // BitbucketEndpoint is the fqdn used to talk to bitbucket + BitbucketEndpoint string = "https://api.bitbucket.org/" +) + type BitbucketClient struct { - Username string - Password string + Username string + Password string + HTTPClient *http.Client +} + +func (c *BitbucketClient) Do(method, endpoint string, payload *bytes.Buffer) (*http.Response, error) { + + absoluteendpoint := BitbucketEndpoint + endpoint + log.Printf("[DEBUG] Sending request to %s %s", method, absoluteendpoint) + + var bodyreader io.Reader + + if payload != nil { + log.Printf("[DEBUG] With payload %s", payload.String()) + bodyreader = payload + } + + req, err := http.NewRequest(method, absoluteendpoint, bodyreader) + if err != nil { + return nil, err + } + + req.SetBasicAuth(c.Username, c.Password) + + if payload != nil { + // Can cause bad request when putting default reviews if set. + req.Header.Add("Content-Type", "application/json") + } + + req.Close = true + + resp, err := c.HTTPClient.Do(req) + log.Printf("[DEBUG] Resp: %v Err: %v", resp, err) + if resp.StatusCode >= 400 || resp.StatusCode < 200 { + apiError := Error{ + StatusCode: resp.StatusCode, + Endpoint: endpoint, + } + + body, err := ioutil.ReadAll(resp.Body) + if err != nil { + return nil, err + } + + log.Printf("[DEBUG] Resp Body: %s", string(body)) + + err = json.Unmarshal(body, &apiError) + if err != nil { + apiError.APIError.Message = string(body) + } + + return resp, error(apiError) + + } + return resp, err } func (c *BitbucketClient) Get(endpoint string) (*http.Response, error) { - client := &http.Client{} - req, err := http.NewRequest("GET", "https://api.bitbucket.org/"+endpoint, nil) - if err != nil { - return nil, err - } - - req.SetBasicAuth(c.Username, c.Password) - return client.Do(req) - + return c.Do("GET", endpoint, nil) } func (c *BitbucketClient) Post(endpoint string, jsonpayload *bytes.Buffer) (*http.Response, error) { - client := &http.Client{} - req, err := http.NewRequest("POST", "https://api.bitbucket.org/"+endpoint, jsonpayload) - if err != nil { - return nil, err - } - req.SetBasicAuth(c.Username, c.Password) - req.Header.Add("content-type", "application/json") - return client.Do(req) + return c.Do("POST", endpoint, jsonpayload) } func (c *BitbucketClient) Put(endpoint string, jsonpayload *bytes.Buffer) (*http.Response, error) { - client := &http.Client{} - req, err := http.NewRequest("PUT", "https://api.bitbucket.org/"+endpoint, jsonpayload) - if err != nil { - return nil, err - } - req.SetBasicAuth(c.Username, c.Password) - req.Header.Add("content-type", "application/json") - return client.Do(req) + return c.Do("PUT", endpoint, jsonpayload) } func (c *BitbucketClient) PutOnly(endpoint string) (*http.Response, error) { - client := &http.Client{} - req, err := http.NewRequest("PUT", "https://api.bitbucket.org/"+endpoint, nil) - if err != nil { - return nil, err - } - req.SetBasicAuth(c.Username, c.Password) - return client.Do(req) + return c.Do("PUT", endpoint, nil) } func (c *BitbucketClient) Delete(endpoint string) (*http.Response, error) { - client := &http.Client{} - req, err := http.NewRequest("DELETE", "https://api.bitbucket.org/"+endpoint, nil) - if err != nil { - return nil, err - } - req.SetBasicAuth(c.Username, c.Password) - return client.Do(req) + return c.Do("DELETE", endpoint, nil) } diff --git a/builtin/providers/bitbucket/provider.go b/builtin/providers/bitbucket/provider.go index afeb71249..e50f9295f 100644 --- a/builtin/providers/bitbucket/provider.go +++ b/builtin/providers/bitbucket/provider.go @@ -1,6 +1,8 @@ package bitbucket import ( + "net/http" + "github.com/hashicorp/terraform/helper/schema" "github.com/hashicorp/terraform/terraform" ) @@ -30,8 +32,9 @@ func Provider() terraform.ResourceProvider { func providerConfigure(d *schema.ResourceData) (interface{}, error) { client := &BitbucketClient{ - Username: d.Get("username").(string), - Password: d.Get("password").(string), + Username: d.Get("username").(string), + Password: d.Get("password").(string), + HTTPClient: &http.Client{}, } return client, nil diff --git a/builtin/providers/bitbucket/resource_default_reviewers.go b/builtin/providers/bitbucket/resource_default_reviewers.go index 37a0f5883..9fc5d1e0a 100644 --- a/builtin/providers/bitbucket/resource_default_reviewers.go +++ b/builtin/providers/bitbucket/resource_default_reviewers.go @@ -3,6 +3,7 @@ package bitbucket import ( "encoding/json" "fmt" + "github.com/hashicorp/terraform/helper/schema" ) @@ -49,7 +50,7 @@ func resourceDefaultReviewersCreate(d *schema.ResourceData, m interface{}) error client := m.(*BitbucketClient) for _, user := range d.Get("reviewers").(*schema.Set).List() { - reviewer_resp, err := client.PutOnly(fmt.Sprintf("2.0/repositories/%s/%s/default-reviewers/%s", + reviewerResp, err := client.PutOnly(fmt.Sprintf("2.0/repositories/%s/%s/default-reviewers/%s", d.Get("owner").(string), d.Get("repository").(string), user, @@ -59,11 +60,11 @@ func resourceDefaultReviewersCreate(d *schema.ResourceData, m interface{}) error return err } - if reviewer_resp.StatusCode != 200 { - return fmt.Errorf("Failed to create reviewer %s got code %d", user.(string), reviewer_resp.StatusCode) + if reviewerResp.StatusCode != 200 { + return fmt.Errorf("Failed to create reviewer %s got code %d", user.(string), reviewerResp.StatusCode) } - defer reviewer_resp.Body.Close() + defer reviewerResp.Body.Close() } d.SetId(fmt.Sprintf("%s/%s/reviewers", d.Get("owner").(string), d.Get("repository").(string))) @@ -72,26 +73,26 @@ func resourceDefaultReviewersCreate(d *schema.ResourceData, m interface{}) error func resourceDefaultReviewersRead(d *schema.ResourceData, m interface{}) error { client := m.(*BitbucketClient) - reviewers_response, err := client.Get(fmt.Sprintf("2.0/repositories/%s/%s/default-reviewers", + reviewersResponse, err := client.Get(fmt.Sprintf("2.0/repositories/%s/%s/default-reviewers", d.Get("owner").(string), d.Get("repository").(string), )) var reviewers PaginatedReviewers - decoder := json.NewDecoder(reviewers_response.Body) + decoder := json.NewDecoder(reviewersResponse.Body) err = decoder.Decode(&reviewers) if err != nil { return err } - terraform_reviewers := make([]string, 0, len(reviewers.Values)) + terraformReviewers := make([]string, 0, len(reviewers.Values)) for _, reviewer := range reviewers.Values { - terraform_reviewers = append(terraform_reviewers, reviewer.Username) + terraformReviewers = append(terraformReviewers, reviewer.Username) } - d.Set("reviewers", terraform_reviewers) + d.Set("reviewers", terraformReviewers) return nil } diff --git a/builtin/providers/bitbucket/resource_hook.go b/builtin/providers/bitbucket/resource_hook.go index c93862798..745292ad1 100644 --- a/builtin/providers/bitbucket/resource_hook.go +++ b/builtin/providers/bitbucket/resource_hook.go @@ -4,6 +4,10 @@ import ( "bytes" "encoding/json" "fmt" + "io/ioutil" + "log" + "net/url" + "github.com/hashicorp/terraform/helper/schema" ) @@ -81,86 +85,89 @@ func resourceHookCreate(d *schema.ResourceData, m interface{}) error { client := m.(*BitbucketClient) hook := createHook(d) - var jsonbuffer []byte - - jsonpayload := bytes.NewBuffer(jsonbuffer) - enc := json.NewEncoder(jsonpayload) - enc.Encode(hook) - - hook_req, err := client.Post(fmt.Sprintf("2.0/repositories/%s/%s/hooks", - d.Get("owner").(string), - d.Get("repository").(string), - ), jsonpayload) - - decoder := json.NewDecoder(hook_req.Body) - err = decoder.Decode(&hook) + payload, err := json.Marshal(hook) if err != nil { return err } + hook_req, err := client.Post(fmt.Sprintf("2.0/repositories/%s/%s/hooks", + d.Get("owner").(string), + d.Get("repository").(string), + ), bytes.NewBuffer(payload)) + + if err != nil { + return err + } + + body, readerr := ioutil.ReadAll(hook_req.Body) + if readerr != nil { + return readerr + } + + decodeerr := json.Unmarshal(body, &hook) + if decodeerr != nil { + return decodeerr + } + d.SetId(hook.Uuid) - d.Set("uuid", hook.Uuid) return resourceHookRead(d, m) } func resourceHookRead(d *schema.ResourceData, m interface{}) error { client := m.(*BitbucketClient) - hook_req, err := client.Get(fmt.Sprintf("2.0/repositories/%s/%s/hooks/%s", + + hook_req, _ := client.Get(fmt.Sprintf("2.0/repositories/%s/%s/hooks/%s", d.Get("owner").(string), d.Get("repository").(string), - d.Get("uuid").(string), + url.PathEscape(d.Id()), )) - if err != nil { - return err + log.Printf("ID: %s", url.PathEscape(d.Id())) + + if hook_req.StatusCode == 200 { + var hook Hook + + body, readerr := ioutil.ReadAll(hook_req.Body) + if readerr != nil { + return readerr + } + + decodeerr := json.Unmarshal(body, &hook) + if decodeerr != nil { + return decodeerr + } + + d.Set("uuid", hook.Uuid) + d.Set("description", hook.Description) + d.Set("active", hook.Active) + d.Set("url", hook.Url) + + eventsList := make([]string, 0, len(hook.Events)) + + for _, event := range hook.Events { + eventsList = append(eventsList, event) + } + + d.Set("events", eventsList) } - var hook Hook - - decoder := json.NewDecoder(hook_req.Body) - err = decoder.Decode(&hook) - if err != nil { - return err - } - - d.Set("uuid", hook.Uuid) - d.Set("description", hook.Description) - d.Set("active", hook.Active) - d.Set("url", hook.Url) - - eventsList := make([]string, 0, len(hook.Events)) - - for _, event := range hook.Events { - eventsList = append(eventsList, event) - } - - d.Set("events", eventsList) - return nil } func resourceHookUpdate(d *schema.ResourceData, m interface{}) error { client := m.(*BitbucketClient) hook := createHook(d) - - var jsonbuffer []byte - - jsonpayload := bytes.NewBuffer(jsonbuffer) - enc := json.NewEncoder(jsonpayload) - enc.Encode(hook) - - hook_req, err := client.Put(fmt.Sprintf("2.0/repositories/%s/%s/hooks/%s", - d.Get("owner").(string), - d.Get("repository").(string), - d.Get("uuid").(string), - ), jsonpayload) - + payload, err := json.Marshal(hook) if err != nil { return err } - decoder := json.NewDecoder(hook_req.Body) - err = decoder.Decode(&hook) + _, err = client.Put(fmt.Sprintf("2.0/repositories/%s/%s/hooks/%s", + d.Get("owner").(string), + d.Get("repository").(string), + url.PathEscape(d.Id()), + ), bytes.NewBuffer(payload)) + if err != nil { return err } @@ -174,7 +181,7 @@ func resourceHookExists(d *schema.ResourceData, m interface{}) (bool, error) { hook_req, err := client.Get(fmt.Sprintf("2.0/repositories/%s/%s/hooks/%s", d.Get("owner").(string), d.Get("repository").(string), - d.Get("uuid").(string), + url.PathEscape(d.Id()), )) if err != nil { @@ -182,15 +189,14 @@ func resourceHookExists(d *schema.ResourceData, m interface{}) (bool, error) { } if hook_req.StatusCode != 200 { - d.SetId("") - return false, nil + return false, err } return true, nil - } else { - return false, nil } + return false, nil + } func resourceHookDelete(d *schema.ResourceData, m interface{}) error { @@ -198,11 +204,9 @@ func resourceHookDelete(d *schema.ResourceData, m interface{}) error { _, err := client.Delete(fmt.Sprintf("2.0/repositories/%s/%s/hooks/%s", d.Get("owner").(string), d.Get("repository").(string), - d.Get("uuid").(string), + url.PathEscape(d.Id()), )) - if err != nil { - return err - } - return nil + return err + } diff --git a/builtin/providers/bitbucket/resource_hook_test.go b/builtin/providers/bitbucket/resource_hook_test.go index 178ebf27b..59a719b87 100644 --- a/builtin/providers/bitbucket/resource_hook_test.go +++ b/builtin/providers/bitbucket/resource_hook_test.go @@ -2,6 +2,7 @@ package bitbucket import ( "fmt" + "net/url" "os" "testing" @@ -16,7 +17,7 @@ func TestAccBitbucketHook_basic(t *testing.T) { testAccBitbucketHookConfig := fmt.Sprintf(` resource "bitbucket_repository" "test_repo" { owner = "%s" - name = "test-repo" + name = "test-repo-for-webhook-test" } resource "bitbucket_hook" "test_repo_hook" { owner = "%s" @@ -51,10 +52,10 @@ func testAccCheckBitbucketHookDestroy(s *terraform.State) error { return fmt.Errorf("Not found %s", "bitbucket_hook.test_repo_hook") } - response, err := client.Get(fmt.Sprintf("2.0/repositories/%s/%s/hooks/%s", rs.Primary.Attributes["owner"], rs.Primary.Attributes["repository"], rs.Primary.Attributes["uuid"])) + response, err := client.Get(fmt.Sprintf("2.0/repositories/%s/%s/hooks/%s", rs.Primary.Attributes["owner"], rs.Primary.Attributes["repository"], url.PathEscape(rs.Primary.Attributes["uuid"]))) - if err != nil { - return err + if err == nil { + return fmt.Errorf("The resource was found should have errored") } if response.StatusCode != 404 { diff --git a/builtin/providers/bitbucket/resource_repository.go b/builtin/providers/bitbucket/resource_repository.go index 050ddd9b2..f57db3ea8 100644 --- a/builtin/providers/bitbucket/resource_repository.go +++ b/builtin/providers/bitbucket/resource_repository.go @@ -4,8 +4,9 @@ import ( "bytes" "encoding/json" "fmt" + "io/ioutil" + "github.com/hashicorp/terraform/helper/schema" - "log" ) type CloneUrl struct { @@ -131,7 +132,7 @@ func resourceRepositoryUpdate(d *schema.ResourceData, m interface{}) error { enc := json.NewEncoder(jsonpayload) enc.Encode(repository) - repository_response, err := client.Put(fmt.Sprintf("2.0/repositories/%s/%s", + _, err := client.Put(fmt.Sprintf("2.0/repositories/%s/%s", d.Get("owner").(string), d.Get("name").(string), ), jsonpayload) @@ -140,16 +141,6 @@ func resourceRepositoryUpdate(d *schema.ResourceData, m interface{}) error { return err } - if repository_response.StatusCode == 200 { - decoder := json.NewDecoder(repository_response.Body) - err = decoder.Decode(&repository) - if err != nil { - return err - } - } else { - return fmt.Errorf("Failed to put: %d", repository_response.StatusCode) - } - return resourceRepositoryRead(d, m) } @@ -157,29 +148,19 @@ func resourceRepositoryCreate(d *schema.ResourceData, m interface{}) error { client := m.(*BitbucketClient) repo := newRepositoryFromResource(d) - var jsonbuffer []byte + bytedata, err := json.Marshal(repo) - jsonpayload := bytes.NewBuffer(jsonbuffer) - enc := json.NewEncoder(jsonpayload) - enc.Encode(repo) - - log.Printf("Sending %s \n", jsonpayload) - - repo_req, err := client.Post(fmt.Sprintf("2.0/repositories/%s/%s", - d.Get("owner").(string), - d.Get("name").(string), - ), jsonpayload) - - decoder := json.NewDecoder(repo_req.Body) - err = decoder.Decode(&repo) if err != nil { return err } - log.Printf("Received %s \n", repo_req.Body) + _, err = client.Post(fmt.Sprintf("2.0/repositories/%s/%s", + d.Get("owner").(string), + d.Get("name").(string), + ), bytes.NewBuffer(bytedata)) - if repo_req.StatusCode != 200 { - return fmt.Errorf("Failed to create repository got status code %d", repo_req.StatusCode) + if err != nil { + return err } d.SetId(string(fmt.Sprintf("%s/%s", d.Get("owner").(string), d.Get("name").(string)))) @@ -189,39 +170,42 @@ func resourceRepositoryCreate(d *schema.ResourceData, m interface{}) error { func resourceRepositoryRead(d *schema.ResourceData, m interface{}) error { client := m.(*BitbucketClient) - repo_req, err := client.Get(fmt.Sprintf("2.0/repositories/%s/%s", + repo_req, _ := client.Get(fmt.Sprintf("2.0/repositories/%s/%s", d.Get("owner").(string), d.Get("name").(string), )) - if err != nil { - return err - } + if repo_req.StatusCode == 200 { - var repo Repository + var repo Repository - decoder := json.NewDecoder(repo_req.Body) - err = decoder.Decode(&repo) - if err != nil { - return err - } + body, readerr := ioutil.ReadAll(repo_req.Body) + if readerr != nil { + return readerr + } - d.Set("scm", repo.SCM) - d.Set("is_private", repo.IsPrivate) - d.Set("has_wiki", repo.HasWiki) - d.Set("has_issues", repo.HasIssues) - d.Set("name", repo.Name) - d.Set("language", repo.Language) - d.Set("fork_policy", repo.ForkPolicy) - d.Set("website", repo.Website) - d.Set("description", repo.Description) - d.Set("project_key", repo.Project.Key) + decodeerr := json.Unmarshal(body, &repo) + if decodeerr != nil { + return decodeerr + } - for _, clone_url := range repo.Links.Clone { - if clone_url.Name == "https" { - d.Set("clone_https", clone_url.Href) - } else { - d.Set("clone_ssh", clone_url.Href) + d.Set("scm", repo.SCM) + d.Set("is_private", repo.IsPrivate) + d.Set("has_wiki", repo.HasWiki) + d.Set("has_issues", repo.HasIssues) + d.Set("name", repo.Name) + d.Set("language", repo.Language) + d.Set("fork_policy", repo.ForkPolicy) + d.Set("website", repo.Website) + d.Set("description", repo.Description) + d.Set("project_key", repo.Project.Key) + + for _, clone_url := range repo.Links.Clone { + if clone_url.Name == "https" { + d.Set("clone_https", clone_url.Href) + } else { + d.Set("clone_ssh", clone_url.Href) + } } } @@ -230,18 +214,10 @@ func resourceRepositoryRead(d *schema.ResourceData, m interface{}) error { func resourceRepositoryDelete(d *schema.ResourceData, m interface{}) error { client := m.(*BitbucketClient) - delete_response, err := client.Delete(fmt.Sprintf("2.0/repositories/%s/%s", + _, err := client.Delete(fmt.Sprintf("2.0/repositories/%s/%s", d.Get("owner").(string), d.Get("name").(string), )) - if err != nil { - return err - } - - if delete_response.StatusCode != 204 { - return fmt.Errorf("Failed to delete the repository got status code %d", delete_response.StatusCode) - } - - return nil + return err } diff --git a/builtin/providers/bitbucket/resource_repository_test.go b/builtin/providers/bitbucket/resource_repository_test.go index 47d4f4405..1fa47a71f 100644 --- a/builtin/providers/bitbucket/resource_repository_test.go +++ b/builtin/providers/bitbucket/resource_repository_test.go @@ -16,9 +16,9 @@ func TestAccBitbucketRepository_basic(t *testing.T) { testAccBitbucketRepositoryConfig := fmt.Sprintf(` resource "bitbucket_repository" "test_repo" { owner = "%s" - name = "%s" + name = "test-repo-for-repository-test" } - `, testUser, testRepo) + `, testUser) resource.Test(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, @@ -42,11 +42,7 @@ func testAccCheckBitbucketRepositoryDestroy(s *terraform.State) error { return fmt.Errorf("Not found %s", "bitbucket_repository.test_repo") } - response, err := client.Get(fmt.Sprintf("2.0/repositories/%s/%s", rs.Primary.Attributes["owner"], rs.Primary.Attributes["name"])) - - if err != nil { - return err - } + response, _ := client.Get(fmt.Sprintf("2.0/repositories/%s/%s", rs.Primary.Attributes["owner"], rs.Primary.Attributes["name"])) if response.StatusCode != 404 { return fmt.Errorf("Repository still exists") diff --git a/builtin/providers/circonus/resource_circonus_metric_cluster.go b/builtin/providers/circonus/resource_circonus_metric_cluster.go index f8776099b..77fde410a 100644 --- a/builtin/providers/circonus/resource_circonus_metric_cluster.go +++ b/builtin/providers/circonus/resource_circonus_metric_cluster.go @@ -6,7 +6,6 @@ import ( "strings" "github.com/circonus-labs/circonus-gometrics/api" - "github.com/circonus-labs/circonus-gometrics/api/config" "github.com/hashicorp/errwrap" "github.com/hashicorp/terraform/helper/hashcode" "github.com/hashicorp/terraform/helper/schema" @@ -85,9 +84,8 @@ func resourceMetricCluster() *schema.Resource { // Out parameters metricClusterIDAttr: &schema.Schema{ - Computed: true, - Type: schema.TypeString, - ValidateFunc: validateRegexp(metricClusterIDAttr, config.MetricClusterCIDRegex), + Computed: true, + Type: schema.TypeString, }, }), } diff --git a/builtin/providers/cloudstack/resource_cloudstack_loadbalancer_rule.go b/builtin/providers/cloudstack/resource_cloudstack_loadbalancer_rule.go index 2c3c25334..d5a5ffe92 100644 --- a/builtin/providers/cloudstack/resource_cloudstack_loadbalancer_rule.go +++ b/builtin/providers/cloudstack/resource_cloudstack_loadbalancer_rule.go @@ -58,10 +58,11 @@ func resourceCloudStackLoadBalancerRule() *schema.Resource { }, "member_ids": &schema.Schema{ - Type: schema.TypeList, + Type: schema.TypeSet, Required: true, - ForceNew: true, + ForceNew: false, Elem: &schema.Schema{Type: schema.TypeString}, + Set: schema.HashString, }, "project": &schema.Schema{ @@ -124,7 +125,7 @@ func resourceCloudStackLoadBalancerRuleCreate(d *schema.ResourceData, meta inter ap := cs.LoadBalancer.NewAssignToLoadBalancerRuleParams(r.Id) var mbs []string - for _, id := range d.Get("member_ids").([]interface{}) { + for _, id := range d.Get("member_ids").(*schema.Set).List() { mbs = append(mbs, id.(string)) } @@ -171,6 +172,18 @@ func resourceCloudStackLoadBalancerRuleRead(d *schema.ResourceData, meta interfa setValueOrID(d, "project", lb.Project, lb.Projectid) + p := cs.LoadBalancer.NewListLoadBalancerRuleInstancesParams(d.Id()) + l, err := cs.LoadBalancer.ListLoadBalancerRuleInstances(p) + if err != nil { + return err + } + + var mbs []string + for _, i := range l.LoadBalancerRuleInstances { + mbs = append(mbs, i.Id) + } + d.Set("member_ids", mbs) + return nil } @@ -215,6 +228,41 @@ func resourceCloudStackLoadBalancerRuleUpdate(d *schema.ResourceData, meta inter "Error updating load balancer rule %s", name) } } + + if d.HasChange("member_ids") { + o, n := d.GetChange("member_ids") + ombs, nmbs := o.(*schema.Set), n.(*schema.Set) + + setToStringList := func(s *schema.Set) []string { + l := make([]string, s.Len()) + for i, v := range s.List() { + l[i] = v.(string) + } + return l + } + + membersToAdd := setToStringList(nmbs.Difference(ombs)) + membersToRemove := setToStringList(ombs.Difference(nmbs)) + + log.Printf("[DEBUG] Members to add: %v, remove: %v", membersToAdd, membersToRemove) + + if len(membersToAdd) > 0 { + p := cs.LoadBalancer.NewAssignToLoadBalancerRuleParams(d.Id()) + p.SetVirtualmachineids(membersToAdd) + if _, err := cs.LoadBalancer.AssignToLoadBalancerRule(p); err != nil { + return err + } + } + + if len(membersToRemove) > 0 { + p := cs.LoadBalancer.NewRemoveFromLoadBalancerRuleParams(d.Id()) + p.SetVirtualmachineids(membersToRemove) + if _, err := cs.LoadBalancer.RemoveFromLoadBalancerRule(p); err != nil { + return err + } + } + } + return resourceCloudStackLoadBalancerRuleRead(d, meta) } diff --git a/builtin/providers/consul/config.go b/builtin/providers/consul/config.go index 959293f84..99897505d 100644 --- a/builtin/providers/consul/config.go +++ b/builtin/providers/consul/config.go @@ -52,7 +52,7 @@ func (c *Config) Client() (*consulapi.Client, error) { } else { username = c.HttpAuth } - config.HttpAuth = &consulapi.HttpBasicAuth{username, password} + config.HttpAuth = &consulapi.HttpBasicAuth{Username: username, Password: password} } if c.Token != "" { diff --git a/builtin/providers/consul/data_source_consul_agent_self.go b/builtin/providers/consul/data_source_consul_agent_self.go index c49800bc7..17beaa626 100644 --- a/builtin/providers/consul/data_source_consul_agent_self.go +++ b/builtin/providers/consul/data_source_consul_agent_self.go @@ -181,9 +181,6 @@ func dataSourceConsulAgentSelf() *schema.Resource { agentSelfACLDisabledTTL: { Computed: true, Type: schema.TypeString, - ValidateFunc: makeValidationFunc(agentSelfACLDisabledTTL, validatorInputs{ - validateDurationMin("0ns"), - }), }, agentSelfACLDownPolicy: { Computed: true, @@ -196,9 +193,6 @@ func dataSourceConsulAgentSelf() *schema.Resource { agentSelfACLTTL: { Computed: true, Type: schema.TypeString, - ValidateFunc: makeValidationFunc(agentSelfACLTTL, validatorInputs{ - validateDurationMin("0ns"), - }), }, agentSelfAddresses: { Computed: true, @@ -275,23 +269,14 @@ func dataSourceConsulAgentSelf() *schema.Resource { agentSelfCheckDeregisterIntervalMin: { Computed: true, Type: schema.TypeString, - ValidateFunc: makeValidationFunc(agentSelfCheckDeregisterIntervalMin, validatorInputs{ - validateDurationMin("0ns"), - }), }, agentSelfCheckReapInterval: { Computed: true, Type: schema.TypeString, - ValidateFunc: makeValidationFunc(agentSelfCheckReapInterval, validatorInputs{ - validateDurationMin("0ns"), - }), }, agentSelfCheckUpdateInterval: { Computed: true, Type: schema.TypeString, - ValidateFunc: makeValidationFunc(agentSelfCheckUpdateInterval, validatorInputs{ - validateDurationMin("0ns"), - }), }, agentSelfClientAddr: { Computed: true, @@ -317,16 +302,10 @@ func dataSourceConsulAgentSelf() *schema.Resource { agentSelfDNSMaxStale: { Computed: true, Type: schema.TypeString, - ValidateFunc: makeValidationFunc(agentSelfDNSMaxStale, validatorInputs{ - validateDurationMin("0ns"), - }), }, agentSelfDNSNodeTTL: { Computed: true, Type: schema.TypeString, - ValidateFunc: makeValidationFunc(agentSelfDNSNodeTTL, validatorInputs{ - validateDurationMin("0ns"), - }), }, agentSelfDNSOnlyPassing: { Computed: true, @@ -335,16 +314,10 @@ func dataSourceConsulAgentSelf() *schema.Resource { agentSelfDNSRecursorTimeout: { Computed: true, Type: schema.TypeString, - ValidateFunc: makeValidationFunc(agentSelfDNSRecursorTimeout, validatorInputs{ - validateDurationMin("0ns"), - }), }, agentSelfDNSServiceTTL: { Computed: true, Type: schema.TypeString, - ValidateFunc: makeValidationFunc(agentSelfDNSServiceTTL, validatorInputs{ - validateDurationMin("0ns"), - }), }, agentSelfDNSUDPAnswerLimit: { Computed: true, @@ -406,9 +379,6 @@ func dataSourceConsulAgentSelf() *schema.Resource { agentSelfID: { Computed: true, Type: schema.TypeString, - ValidateFunc: makeValidationFunc(agentSelfID, validatorInputs{ - validateRegexp(`(?i)^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$`), - }), }, agentSelfLeaveOnInt: { Computed: true, @@ -434,9 +404,6 @@ func dataSourceConsulAgentSelf() *schema.Resource { agentSelfPerformanceRaftMultiplier: { Computed: true, Type: schema.TypeString, // FIXME(sean@): should be schema.TypeInt - ValidateFunc: makeValidationFunc(agentSelfPerformanceRaftMultiplier, validatorInputs{ - validateIntMin(0), - }), }, }, }, @@ -453,58 +420,30 @@ func dataSourceConsulAgentSelf() *schema.Resource { agentSelfSchemaPortsDNS: { Computed: true, Type: schema.TypeInt, - ValidateFunc: makeValidationFunc(agentSelfSchemaPortsDNS, validatorInputs{ - validateIntMin(1), - validateIntMax(65535), - }), }, agentSelfSchemaPortsHTTP: { Computed: true, Type: schema.TypeInt, - ValidateFunc: makeValidationFunc(agentSelfSchemaPortsHTTP, validatorInputs{ - validateIntMin(1), - validateIntMax(65535), - }), }, agentSelfSchemaPortsHTTPS: { Computed: true, Type: schema.TypeInt, - ValidateFunc: makeValidationFunc(agentSelfSchemaPortsHTTPS, validatorInputs{ - validateIntMin(1), - validateIntMax(65535), - }), }, agentSelfSchemaPortsRPC: { Computed: true, Type: schema.TypeInt, - ValidateFunc: makeValidationFunc(agentSelfSchemaPortsRPC, validatorInputs{ - validateIntMin(1), - validateIntMax(65535), - }), }, agentSelfSchemaPortsSerfLAN: { Computed: true, Type: schema.TypeInt, - ValidateFunc: makeValidationFunc(agentSelfSchemaPortsSerfLAN, validatorInputs{ - validateIntMin(1), - validateIntMax(65535), - }), }, agentSelfSchemaPortsSerfWAN: { Computed: true, Type: schema.TypeInt, - ValidateFunc: makeValidationFunc(agentSelfSchemaPortsSerfWAN, validatorInputs{ - validateIntMin(1), - validateIntMax(65535), - }), }, agentSelfSchemaPortsServer: { Computed: true, Type: schema.TypeInt, - ValidateFunc: makeValidationFunc(agentSelfSchemaPortsServer, validatorInputs{ - validateIntMin(1), - validateIntMax(65535), - }), }, }, }, @@ -516,16 +455,10 @@ func dataSourceConsulAgentSelf() *schema.Resource { agentSelfReconnectTimeoutLAN: { Computed: true, Type: schema.TypeString, - ValidateFunc: makeValidationFunc(agentSelfReconnectTimeoutLAN, validatorInputs{ - validateDurationMin("0ns"), - }), }, agentSelfReconnectTimeoutWAN: { Computed: true, Type: schema.TypeString, - ValidateFunc: makeValidationFunc(agentSelfReconnectTimeoutWAN, validatorInputs{ - validateDurationMin("0ns"), - }), }, agentSelfRejoinAfterLeave: { Computed: true, @@ -612,9 +545,6 @@ func dataSourceConsulAgentSelf() *schema.Resource { agentSelfSessionTTLMin: { Computed: true, Type: schema.TypeString, - ValidateFunc: makeValidationFunc(agentSelfSessionTTLMin, validatorInputs{ - validateDurationMin("0ns"), - }), }, agentSelfStartJoin: { Computed: true, @@ -702,9 +632,6 @@ func dataSourceConsulAgentSelf() *schema.Resource { agentSelfTelemetryCirconusSubmissionInterval: &schema.Schema{ Type: schema.TypeString, Computed: true, - ValidateFunc: makeValidationFunc(agentSelfTelemetryCirconusSubmissionInterval, validatorInputs{ - validateDurationMin("0ns"), - }), }, agentSelfTelemetryEnableHostname: &schema.Schema{ Type: schema.TypeString, diff --git a/builtin/providers/consul/data_source_consul_catalog_nodes.go b/builtin/providers/consul/data_source_consul_catalog_nodes.go index 666d71653..b93da423a 100644 --- a/builtin/providers/consul/data_source_consul_catalog_nodes.go +++ b/builtin/providers/consul/data_source_consul_catalog_nodes.go @@ -56,14 +56,12 @@ func dataSourceConsulCatalogNodes() *schema.Resource { Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ catalogNodesNodeID: &schema.Schema{ - Type: schema.TypeString, - Computed: true, - ValidateFunc: makeValidationFunc(catalogNodesNodeID, []interface{}{validateRegexp(`^[\S]+$`)}), + Type: schema.TypeString, + Computed: true, }, catalogNodesNodeName: &schema.Schema{ - Type: schema.TypeString, - Computed: true, - ValidateFunc: makeValidationFunc(catalogNodesNodeName, []interface{}{validateRegexp(`^[\S]+$`)}), + Type: schema.TypeString, + Computed: true, }, catalogNodesNodeAddress: &schema.Schema{ Type: schema.TypeString, diff --git a/builtin/providers/datadog/resource_datadog_monitor.go b/builtin/providers/datadog/resource_datadog_monitor.go index 4d4d25d2c..4aeb0d637 100644 --- a/builtin/providers/datadog/resource_datadog_monitor.go +++ b/builtin/providers/datadog/resource_datadog_monitor.go @@ -85,6 +85,11 @@ func resourceDatadogMonitor() *schema.Resource { Computed: true, Optional: true, }, + "evaluation_delay": { + Type: schema.TypeInt, + Computed: true, + Optional: true, + }, "no_data_timeframe": { Type: schema.TypeInt, Optional: true, @@ -163,6 +168,9 @@ func buildMonitorStruct(d *schema.ResourceData) *datadog.Monitor { if attr, ok := d.GetOk("new_host_delay"); ok { o.SetNewHostDelay(attr.(int)) } + if attr, ok := d.GetOk("evaluation_delay"); ok { + o.SetNewHostDelay(attr.(int)) + } if attr, ok := d.GetOk("no_data_timeframe"); ok { o.NoDataTimeframe = datadog.NoDataTimeframe(attr.(int)) } @@ -274,6 +282,7 @@ func resourceDatadogMonitorRead(d *schema.ResourceData, meta interface{}) error d.Set("thresholds", thresholds) d.Set("new_host_delay", m.Options.GetNewHostDelay()) + d.Set("evaluation_delay", m.Options.GetNewHostDelay()) d.Set("notify_no_data", m.Options.GetNotifyNoData()) d.Set("no_data_timeframe", m.Options.NoDataTimeframe) d.Set("renotify_interval", m.Options.GetRenotifyInterval()) @@ -340,6 +349,9 @@ func resourceDatadogMonitorUpdate(d *schema.ResourceData, meta interface{}) erro if attr, ok := d.GetOk("new_host_delay"); ok { o.SetNewHostDelay(attr.(int)) } + if attr, ok := d.GetOk("evaluation_delay"); ok { + o.SetNewHostDelay(attr.(int)) + } if attr, ok := d.GetOk("no_data_timeframe"); ok { o.NoDataTimeframe = datadog.NoDataTimeframe(attr.(int)) } diff --git a/builtin/providers/datadog/resource_datadog_monitor_test.go b/builtin/providers/datadog/resource_datadog_monitor_test.go index 41791455e..f2cce05fb 100644 --- a/builtin/providers/datadog/resource_datadog_monitor_test.go +++ b/builtin/providers/datadog/resource_datadog_monitor_test.go @@ -33,6 +33,8 @@ func TestAccDatadogMonitor_Basic(t *testing.T) { "datadog_monitor.foo", "notify_no_data", "false"), resource.TestCheckResourceAttr( "datadog_monitor.foo", "new_host_delay", "600"), + resource.TestCheckResourceAttr( + "datadog_monitor.foo", "evaluation_delay", "600"), resource.TestCheckResourceAttr( "datadog_monitor.foo", "renotify_interval", "60"), resource.TestCheckResourceAttr( @@ -113,6 +115,8 @@ func TestAccDatadogMonitor_Updated(t *testing.T) { "datadog_monitor.foo", "notify_no_data", "false"), resource.TestCheckResourceAttr( "datadog_monitor.foo", "new_host_delay", "600"), + resource.TestCheckResourceAttr( + "datadog_monitor.foo", "evaluation_delay", "600"), resource.TestCheckResourceAttr( "datadog_monitor.foo", "renotify_interval", "60"), resource.TestCheckResourceAttr( @@ -153,6 +157,8 @@ func TestAccDatadogMonitor_Updated(t *testing.T) { "datadog_monitor.foo", "notify_no_data", "true"), resource.TestCheckResourceAttr( "datadog_monitor.foo", "new_host_delay", "900"), + resource.TestCheckResourceAttr( + "datadog_monitor.foo", "evaluation_delay", "900"), resource.TestCheckResourceAttr( "datadog_monitor.foo", "no_data_timeframe", "20"), resource.TestCheckResourceAttr( @@ -288,6 +294,7 @@ resource "datadog_monitor" "foo" { notify_audit = false timeout_h = 60 new_host_delay = 600 + evaluation_delay = 600 include_tags = true require_full_window = true locked = false @@ -386,6 +393,7 @@ resource "datadog_monitor" "foo" { notify_no_data = true new_host_delay = 900 + evaluation_delay = 900 no_data_timeframe = 20 renotify_interval = 40 escalation_message = "the situation has escalated! @pagerduty" diff --git a/builtin/providers/datadog/resource_datadog_timeboard.go b/builtin/providers/datadog/resource_datadog_timeboard.go index bfaa1fb9e..1f9efc8a7 100644 --- a/builtin/providers/datadog/resource_datadog_timeboard.go +++ b/builtin/providers/datadog/resource_datadog_timeboard.go @@ -704,14 +704,15 @@ func resourceDatadogTimeboardExists(d *schema.ResourceData, meta interface{}) (b func validateAggregatorMethod(v interface{}, k string) (ws []string, errors []error) { value := v.(string) validMethods := map[string]struct{}{ - "average": {}, - "max": {}, - "min": {}, - "sum": {}, + "avg": {}, + "max": {}, + "min": {}, + "sum": {}, + "last": {}, } if _, ok := validMethods[value]; !ok { errors = append(errors, fmt.Errorf( - `%q contains an invalid method %q. Valid methods are either "average", "max", "min", or "sum"`, k, value)) + `%q contains an invalid method %q. Valid methods are either "avg", "max", "min", "sum", or "last"`, k, value)) } return } diff --git a/builtin/providers/datadog/resource_datadog_timeboard_test.go b/builtin/providers/datadog/resource_datadog_timeboard_test.go index 87498c736..3673b9506 100644 --- a/builtin/providers/datadog/resource_datadog_timeboard_test.go +++ b/builtin/providers/datadog/resource_datadog_timeboard_test.go @@ -224,7 +224,7 @@ func checkDestroy(s *terraform.State) error { func TestValidateAggregatorMethod(t *testing.T) { validMethods := []string{ - "average", + "avg", "max", "min", "sum", @@ -237,7 +237,7 @@ func TestValidateAggregatorMethod(t *testing.T) { } invalidMethods := []string{ - "avg", + "average", "suM", "m", "foo", diff --git a/builtin/providers/digitalocean/config.go b/builtin/providers/digitalocean/config.go index a0a9115ae..b32be5938 100644 --- a/builtin/providers/digitalocean/config.go +++ b/builtin/providers/digitalocean/config.go @@ -2,9 +2,12 @@ package digitalocean import ( "log" + "net/http" + "net/http/httputil" "time" "github.com/digitalocean/godo" + "github.com/hashicorp/terraform/helper/logging" "github.com/hashicorp/terraform/helper/resource" "golang.org/x/oauth2" ) @@ -21,11 +24,31 @@ func (c *Config) Client() (*godo.Client, error) { client := godo.NewClient(oauth2.NewClient(oauth2.NoContext, tokenSrc)) + if logging.IsDebugOrHigher() { + client.OnRequestCompleted(logRequestAndResponse) + } + log.Printf("[INFO] DigitalOcean Client configured for URL: %s", client.BaseURL.String()) return client, nil } +func logRequestAndResponse(req *http.Request, resp *http.Response) { + reqData, err := httputil.DumpRequest(req, true) + if err == nil { + log.Printf("[DEBUG] "+logReqMsg, string(reqData)) + } else { + log.Printf("[ERROR] DigitalOcean API Request error: %#v", err) + } + + respData, err := httputil.DumpResponse(resp, true) + if err == nil { + log.Printf("[DEBUG] "+logRespMsg, string(respData)) + } else { + log.Printf("[ERROR] DigitalOcean API Response error: %#v", err) + } +} + // waitForAction waits for the action to finish using the resource.StateChangeConf. func waitForAction(client *godo.Client, action *godo.Action) error { var ( @@ -61,3 +84,13 @@ func waitForAction(client *godo.Client, action *godo.Action) error { }).WaitForState() return err } + +const logReqMsg = `DigitalOcean API Request Details: +---[ REQUEST ]--------------------------------------- +%s +-----------------------------------------------------` + +const logRespMsg = `DigitalOcean API Response Details: +---[ RESPONSE ]-------------------------------------- +%s +-----------------------------------------------------` diff --git a/builtin/providers/digitalocean/datasource_digitalocean_image.go b/builtin/providers/digitalocean/datasource_digitalocean_image.go new file mode 100644 index 000000000..d4023daf8 --- /dev/null +++ b/builtin/providers/digitalocean/datasource_digitalocean_image.go @@ -0,0 +1,93 @@ +package digitalocean + +import ( + "fmt" + "strconv" + + "github.com/digitalocean/godo" + "github.com/hashicorp/terraform/helper/schema" +) + +func dataSourceDigitalOceanImage() *schema.Resource { + return &schema.Resource{ + Read: dataSourceDigitalOceanImageRead, + Schema: map[string]*schema.Schema{ + + "name": &schema.Schema{ + Type: schema.TypeString, + Required: true, + Description: "name of the image", + }, + // computed attributes + "image": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "slug or id of the image", + }, + "min_disk_size": &schema.Schema{ + Type: schema.TypeInt, + Computed: true, + Description: "minimum disk size required by the image", + }, + "private": &schema.Schema{ + Type: schema.TypeBool, + Computed: true, + Description: "Is the image private or non-private", + }, + "regions": &schema.Schema{ + Type: schema.TypeList, + Computed: true, + Description: "list of the regions that the image is available in", + Elem: &schema.Schema{Type: schema.TypeString}, + }, + "type": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "type of the image", + }, + }, + } +} + +func dataSourceDigitalOceanImageRead(d *schema.ResourceData, meta interface{}) error { + client := meta.(*godo.Client) + + opts := &godo.ListOptions{} + + images, _, err := client.Images.ListUser(opts) + if err != nil { + d.SetId("") + return err + } + image, err := findImageByName(images, d.Get("name").(string)) + + if err != nil { + return err + } + + d.SetId(image.Name) + d.Set("name", image.Name) + d.Set("image", strconv.Itoa(image.ID)) + d.Set("min_disk_size", image.MinDiskSize) + d.Set("private", !image.Public) + d.Set("regions", image.Regions) + d.Set("type", image.Type) + + return nil +} + +func findImageByName(images []godo.Image, name string) (*godo.Image, error) { + results := make([]godo.Image, 0) + for _, v := range images { + if v.Name == name { + results = append(results, v) + } + } + if len(results) == 1 { + return &results[0], nil + } + if len(results) == 0 { + return nil, fmt.Errorf("no user image found with name %s", name) + } + return nil, fmt.Errorf("too many user images found with name %s (found %d, expected 1)", name, len(results)) +} diff --git a/builtin/providers/digitalocean/datasource_digitalocean_image_test.go b/builtin/providers/digitalocean/datasource_digitalocean_image_test.go new file mode 100644 index 000000000..ab77c75ae --- /dev/null +++ b/builtin/providers/digitalocean/datasource_digitalocean_image_test.go @@ -0,0 +1,122 @@ +package digitalocean + +import ( + "fmt" + "log" + "regexp" + "testing" + + "github.com/digitalocean/godo" + "github.com/hashicorp/terraform/helper/acctest" + "github.com/hashicorp/terraform/helper/resource" + "github.com/hashicorp/terraform/terraform" +) + +func TestAccDigitalOceanImage_Basic(t *testing.T) { + var droplet godo.Droplet + var snapshotsId []int + rInt := acctest.RandInt() + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckDigitalOceanDropletDestroy, + Steps: []resource.TestStep{ + { + Config: testAccCheckDigitalOceanDropletConfig_basic(rInt), + Check: resource.ComposeTestCheckFunc( + testAccCheckDigitalOceanDropletExists("digitalocean_droplet.foobar", &droplet), + takeSnapshotsOfDroplet(rInt, &droplet, &snapshotsId), + ), + }, + { + Config: testAccCheckDigitalOceanImageConfig_basic(rInt, 1), + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttr( + "data.digitalocean_image.foobar", "name", fmt.Sprintf("snap-%d-1", rInt)), + resource.TestCheckResourceAttr( + "data.digitalocean_image.foobar", "min_disk_size", "20"), + resource.TestCheckResourceAttr( + "data.digitalocean_image.foobar", "private", "true"), + resource.TestCheckResourceAttr( + "data.digitalocean_image.foobar", "type", "snapshot"), + ), + }, + { + Config: testAccCheckDigitalOceanImageConfig_basic(rInt, 0), + ExpectError: regexp.MustCompile(`.*too many user images found with name snap-.*\ .found 2, expected 1.`), + }, + { + Config: testAccCheckDigitalOceanImageConfig_nonexisting(rInt), + Destroy: false, + ExpectError: regexp.MustCompile(`.*no user image found with name snap-.*-nonexisting`), + }, + { + Config: " ", + Check: resource.ComposeTestCheckFunc( + deleteSnapshots(&snapshotsId), + ), + }, + }, + }) +} + +func takeSnapshotsOfDroplet(rInt int, droplet *godo.Droplet, snapshotsId *[]int) resource.TestCheckFunc { + return func(s *terraform.State) error { + client := testAccProvider.Meta().(*godo.Client) + for i := 0; i < 3; i++ { + err := takeSnapshotOfDroplet(rInt, i%2, droplet) + if err != nil { + return err + } + } + retrieveDroplet, _, err := client.Droplets.Get((*droplet).ID) + if err != nil { + return err + } + *snapshotsId = retrieveDroplet.SnapshotIDs + return nil + } +} + +func takeSnapshotOfDroplet(rInt, sInt int, droplet *godo.Droplet) error { + client := testAccProvider.Meta().(*godo.Client) + action, _, err := client.DropletActions.Snapshot((*droplet).ID, fmt.Sprintf("snap-%d-%d", rInt, sInt)) + if err != nil { + return err + } + waitForAction(client, action) + return nil +} + +func deleteSnapshots(snapshotsId *[]int) resource.TestCheckFunc { + return func(s *terraform.State) error { + log.Printf("XXX Deleting snaps") + client := testAccProvider.Meta().(*godo.Client) + snapshots := *snapshotsId + for _, value := range snapshots { + log.Printf("XXX Deleting %d", value) + _, err := client.Images.Delete(value) + if err != nil { + return err + } + } + return nil + } +} + +func testAccCheckDigitalOceanImageConfig_basic(rInt, sInt int) string { + return fmt.Sprintf(` +data "digitalocean_image" "foobar" { + name = "snap-%d-%d" +} +`, rInt, sInt) +} + +func testAccCheckDigitalOceanImageConfig_nonexisting(rInt int) string { + return fmt.Sprintf(` +data "digitalocean_image" "foobar" { + name = "snap-%d-nonexisting" +} +`, rInt) +} diff --git a/builtin/providers/digitalocean/provider.go b/builtin/providers/digitalocean/provider.go index 5ab2cab43..e885e0823 100644 --- a/builtin/providers/digitalocean/provider.go +++ b/builtin/providers/digitalocean/provider.go @@ -17,6 +17,10 @@ func Provider() terraform.ResourceProvider { }, }, + DataSourcesMap: map[string]*schema.Resource{ + "digitalocean_image": dataSourceDigitalOceanImage(), + }, + ResourcesMap: map[string]*schema.Resource{ "digitalocean_domain": resourceDigitalOceanDomain(), "digitalocean_droplet": resourceDigitalOceanDroplet(), diff --git a/builtin/providers/digitalocean/resource_digitalocean_droplet.go b/builtin/providers/digitalocean/resource_digitalocean_droplet.go index 76212d579..fdae4dd03 100644 --- a/builtin/providers/digitalocean/resource_digitalocean_droplet.go +++ b/builtin/providers/digitalocean/resource_digitalocean_droplet.go @@ -63,6 +63,16 @@ func resourceDigitalOceanDroplet() *schema.Resource { Computed: true, }, + "price_hourly": { + Type: schema.TypeFloat, + Computed: true, + }, + + "price_monthly": { + Type: schema.TypeFloat, + Computed: true, + }, + "resize_disk": { Type: schema.TypeBool, Optional: true, @@ -250,15 +260,20 @@ func resourceDigitalOceanDropletRead(d *schema.ResourceData, meta interface{}) e return fmt.Errorf("Error retrieving droplet: %s", err) } - if droplet.Image.Slug != "" { - d.Set("image", droplet.Image.Slug) - } else { + _, err = strconv.Atoi(d.Get("image").(string)) + if err == nil || droplet.Image.Slug == "" { + // The image field is provided as an ID (number), or + // the image bash no slug. In both cases we store it as an ID. d.Set("image", droplet.Image.ID) + } else { + d.Set("image", droplet.Image.Slug) } d.Set("name", droplet.Name) d.Set("region", droplet.Region.Slug) d.Set("size", droplet.Size.Slug) + d.Set("price_hourly", droplet.Size.PriceHourly) + d.Set("price_monthly", droplet.Size.PriceMonthly) d.Set("disk", droplet.Disk) d.Set("vcpus", droplet.Vcpus) d.Set("status", droplet.Status) diff --git a/builtin/providers/digitalocean/resource_digitalocean_droplet_test.go b/builtin/providers/digitalocean/resource_digitalocean_droplet_test.go index 1c3d5601c..1d6f78042 100644 --- a/builtin/providers/digitalocean/resource_digitalocean_droplet_test.go +++ b/builtin/providers/digitalocean/resource_digitalocean_droplet_test.go @@ -30,6 +30,10 @@ func TestAccDigitalOceanDroplet_Basic(t *testing.T) { "digitalocean_droplet.foobar", "name", fmt.Sprintf("foo-%d", rInt)), resource.TestCheckResourceAttr( "digitalocean_droplet.foobar", "size", "512mb"), + resource.TestCheckResourceAttr( + "digitalocean_droplet.foobar", "price_hourly", "0.00744"), + resource.TestCheckResourceAttr( + "digitalocean_droplet.foobar", "price_monthly", "5"), resource.TestCheckResourceAttr( "digitalocean_droplet.foobar", "image", "centos-7-x64"), resource.TestCheckResourceAttr( @@ -42,6 +46,26 @@ func TestAccDigitalOceanDroplet_Basic(t *testing.T) { }) } +func TestAccDigitalOceanDroplet_WithID(t *testing.T) { + var droplet godo.Droplet + rInt := acctest.RandInt() + // TODO: not hardcode this as it will change over time + centosID := 22995941 + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckDigitalOceanDropletDestroy, + Steps: []resource.TestStep{ + { + Config: testAccCheckDigitalOceanDropletConfig_withID(centosID, rInt), + Check: resource.ComposeTestCheckFunc( + testAccCheckDigitalOceanDropletExists("digitalocean_droplet.foobar", &droplet), + ), + }, + }, + }) +} func TestAccDigitalOceanDroplet_withSSH(t *testing.T) { var droplet godo.Droplet rInt := acctest.RandInt() @@ -333,6 +357,14 @@ func testAccCheckDigitalOceanDropletAttributes(droplet *godo.Droplet) resource.T return fmt.Errorf("Bad size_slug: %s", droplet.Size.Slug) } + if droplet.Size.PriceHourly != 0.00744 { + return fmt.Errorf("Bad price_hourly: %v", droplet.Size.PriceHourly) + } + + if droplet.Size.PriceMonthly != 5.0 { + return fmt.Errorf("Bad price_monthly: %v", droplet.Size.PriceMonthly) + } + if droplet.Region.Slug != "nyc3" { return fmt.Errorf("Bad region_slug: %s", droplet.Region.Slug) } @@ -487,6 +519,17 @@ resource "digitalocean_droplet" "foobar" { }`, rInt) } +func testAccCheckDigitalOceanDropletConfig_withID(imageID, rInt int) string { + return fmt.Sprintf(` +resource "digitalocean_droplet" "foobar" { + name = "foo-%d" + size = "512mb" + image = "%d" + region = "nyc3" + user_data = "foobar" +}`, rInt, imageID) +} + func testAccCheckDigitalOceanDropletConfig_withSSH(rInt int) string { return fmt.Sprintf(` resource "digitalocean_ssh_key" "foobar" { diff --git a/builtin/providers/digitalocean/resource_digitalocean_record.go b/builtin/providers/digitalocean/resource_digitalocean_record.go index 40ff3730a..794787eae 100644 --- a/builtin/providers/digitalocean/resource_digitalocean_record.go +++ b/builtin/providers/digitalocean/resource_digitalocean_record.go @@ -132,16 +132,11 @@ func resourceDigitalOceanRecordRead(d *schema.ResourceData, meta interface{}) er return err } - // Update response data for records with domain value if t := rec.Type; t == "CNAME" || t == "MX" || t == "NS" || t == "SRV" { - // Append dot to response if resource value is absolute - if value := d.Get("value").(string); strings.HasSuffix(value, ".") { - rec.Data += "." - // If resource value ends with current domain, make response data absolute - if strings.HasSuffix(value, domain+".") { - rec.Data += domain + "." - } + if rec.Data == "@" { + rec.Data = domain } + rec.Data += "." } d.Set("name", rec.Name) diff --git a/builtin/providers/digitalocean/resource_digitalocean_record_test.go b/builtin/providers/digitalocean/resource_digitalocean_record_test.go index af4066ca4..bb62db240 100644 --- a/builtin/providers/digitalocean/resource_digitalocean_record_test.go +++ b/builtin/providers/digitalocean/resource_digitalocean_record_test.go @@ -164,6 +164,64 @@ func TestAccDigitalOceanRecord_ExternalHostnameValue(t *testing.T) { }) } +func TestAccDigitalOceanRecord_MX(t *testing.T) { + var record godo.DomainRecord + domain := fmt.Sprintf("foobar-test-terraform-%s.com", acctest.RandString(10)) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckDigitalOceanRecordDestroy, + Steps: []resource.TestStep{ + { + Config: fmt.Sprintf( + testAccCheckDigitalOceanRecordConfig_mx, domain), + Check: resource.ComposeTestCheckFunc( + testAccCheckDigitalOceanRecordExists("digitalocean_record.foo_record", &record), + testAccCheckDigitalOceanRecordAttributesHostname("foobar."+domain, &record), + resource.TestCheckResourceAttr( + "digitalocean_record.foo_record", "name", "terraform"), + resource.TestCheckResourceAttr( + "digitalocean_record.foo_record", "domain", domain), + resource.TestCheckResourceAttr( + "digitalocean_record.foo_record", "value", "foobar."+domain+"."), + resource.TestCheckResourceAttr( + "digitalocean_record.foo_record", "type", "MX"), + ), + }, + }, + }) +} + +func TestAccDigitalOceanRecord_MX_at(t *testing.T) { + var record godo.DomainRecord + domain := fmt.Sprintf("foobar-test-terraform-%s.com", acctest.RandString(10)) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckDigitalOceanRecordDestroy, + Steps: []resource.TestStep{ + { + Config: fmt.Sprintf( + testAccCheckDigitalOceanRecordConfig_mx_at, domain), + Check: resource.ComposeTestCheckFunc( + testAccCheckDigitalOceanRecordExists("digitalocean_record.foo_record", &record), + testAccCheckDigitalOceanRecordAttributesHostname("@", &record), + resource.TestCheckResourceAttr( + "digitalocean_record.foo_record", "name", "terraform"), + resource.TestCheckResourceAttr( + "digitalocean_record.foo_record", "domain", domain), + resource.TestCheckResourceAttr( + "digitalocean_record.foo_record", "value", domain+"."), + resource.TestCheckResourceAttr( + "digitalocean_record.foo_record", "type", "MX"), + ), + }, + }, + }) +} + func testAccCheckDigitalOceanRecordDestroy(s *terraform.State) error { client := testAccProvider.Meta().(*godo.Client) @@ -298,6 +356,36 @@ resource "digitalocean_record" "foobar" { type = "CNAME" }` +const testAccCheckDigitalOceanRecordConfig_mx_at = ` +resource "digitalocean_domain" "foobar" { + name = "%s" + ip_address = "192.168.0.10" +} + +resource "digitalocean_record" "foo_record" { + domain = "${digitalocean_domain.foobar.name}" + + name = "terraform" + value = "${digitalocean_domain.foobar.name}." + type = "MX" + priority = "10" +}` + +const testAccCheckDigitalOceanRecordConfig_mx = ` +resource "digitalocean_domain" "foobar" { + name = "%s" + ip_address = "192.168.0.10" +} + +resource "digitalocean_record" "foo_record" { + domain = "${digitalocean_domain.foobar.name}" + + name = "terraform" + value = "foobar.${digitalocean_domain.foobar.name}." + type = "MX" + priority = "10" +}` + const testAccCheckDigitalOceanRecordConfig_external_cname = ` resource "digitalocean_domain" "foobar" { name = "%s" diff --git a/builtin/providers/dme/resource_dme_record.go b/builtin/providers/dme/resource_dme_record.go index 4578dd5f9..adc7cee6e 100644 --- a/builtin/providers/dme/resource_dme_record.go +++ b/builtin/providers/dme/resource_dme_record.go @@ -33,6 +33,9 @@ func resourceDMERecord() *schema.Resource { "value": &schema.Schema{ Type: schema.TypeString, Required: true, + StateFunc: func(value interface{}) string { + return strings.ToLower(value.(string)) + }, }, "ttl": &schema.Schema{ Type: schema.TypeInt, diff --git a/builtin/providers/dns/data_dns_a_record_set_test.go b/builtin/providers/dns/data_dns_a_record_set_test.go index 7c6ba8a33..9209b5f5c 100644 --- a/builtin/providers/dns/data_dns_a_record_set_test.go +++ b/builtin/providers/dns/data_dns_a_record_set_test.go @@ -12,6 +12,7 @@ func TestAccDataDnsARecordSet_Basic(t *testing.T) { DataSourceBlock string DataSourceName string Expected []string + Host string }{ { ` @@ -23,6 +24,7 @@ func TestAccDataDnsARecordSet_Basic(t *testing.T) { []string{ "127.0.0.1", }, + "127.0.0.1.nip.io", }, { ` @@ -34,23 +36,30 @@ func TestAccDataDnsARecordSet_Basic(t *testing.T) { []string{ "129.6.15.30", }, + "time-c.nist.gov", }, } - var steps []resource.TestStep - for _, test := range tests { - ts := resource.TestStep{ - Config: test.DataSourceBlock, - Check: resource.ComposeTestCheckFunc( - testCheckAttrStringArray(fmt.Sprintf("data.dns_a_record_set.%s", test.DataSourceName), "addrs", test.Expected), - ), - } - steps = append(steps, ts) + recordName := fmt.Sprintf("data.dns_a_record_set.%s", test.DataSourceName) + + resource.UnitTest(t, resource.TestCase{ + Providers: testAccProviders, + Steps: []resource.TestStep{ + resource.TestStep{ + Config: test.DataSourceBlock, + Check: resource.ComposeTestCheckFunc( + testCheckAttrStringArray(recordName, "addrs", test.Expected), + ), + }, + resource.TestStep{ + Config: test.DataSourceBlock, + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttr(recordName, "id", test.Host), + ), + }, + }, + }) } - resource.Test(t, resource.TestCase{ - Providers: testAccProviders, - Steps: steps, - }) } diff --git a/builtin/providers/dns/data_dns_cname_record_set_test.go b/builtin/providers/dns/data_dns_cname_record_set_test.go index 84270ff04..21e8eeb77 100644 --- a/builtin/providers/dns/data_dns_cname_record_set_test.go +++ b/builtin/providers/dns/data_dns_cname_record_set_test.go @@ -10,6 +10,7 @@ func TestAccDnsCnameRecordSet_Basic(t *testing.T) { tests := []struct { DataSourceBlock string Expected string + Host string }{ { ` @@ -17,7 +18,8 @@ func TestAccDnsCnameRecordSet_Basic(t *testing.T) { host = "www.hashicorp.com" } `, - "s.shared.global.fastly.net.", + "dualstack.s.shared.global.fastly.net.", + "www.hashicorp.com", }, } @@ -31,6 +33,12 @@ func TestAccDnsCnameRecordSet_Basic(t *testing.T) { r.TestCheckResourceAttr("data.dns_cname_record_set.foo", "cname", test.Expected), ), }, + r.TestStep{ + Config: test.DataSourceBlock, + Check: r.ComposeTestCheckFunc( + r.TestCheckResourceAttr("data.dns_cname_record_set.foo", "id", test.Host), + ), + }, }, }) } diff --git a/builtin/providers/dns/data_dns_txt_record_set.go b/builtin/providers/dns/data_dns_txt_record_set.go index 67cb47e82..ad03ccb24 100644 --- a/builtin/providers/dns/data_dns_txt_record_set.go +++ b/builtin/providers/dns/data_dns_txt_record_set.go @@ -34,6 +34,7 @@ func dataSourceDnsTxtRecordSet() *schema.Resource { func dataSourceDnsTxtRecordSetRead(d *schema.ResourceData, meta interface{}) error { host := d.Get("host").(string) + records, err := net.LookupTXT(host) if err != nil { return fmt.Errorf("error looking up TXT records for %q: %s", host, err) @@ -45,5 +46,7 @@ func dataSourceDnsTxtRecordSetRead(d *schema.ResourceData, meta interface{}) err d.Set("record", "") } d.Set("records", records) + d.SetId(host) + return nil } diff --git a/builtin/providers/dns/data_dns_txt_record_set_test.go b/builtin/providers/dns/data_dns_txt_record_set_test.go new file mode 100644 index 000000000..6958ee269 --- /dev/null +++ b/builtin/providers/dns/data_dns_txt_record_set_test.go @@ -0,0 +1,59 @@ +package dns + +import ( + "fmt" + "testing" + + "github.com/hashicorp/terraform/helper/resource" +) + +func TestAccDataDnsTxtRecordSet_Basic(t *testing.T) { + tests := []struct { + DataSourceBlock string + DataSourceName string + Expected []string + Host string + }{ + { + ` + data "dns_txt_record_set" "foo" { + host = "hashicorp.com" + } + `, + "foo", + []string{ + "google-site-verification=oqoe6Z7OB_726BNm33g4OdKK57KDtCfH266f8wAvLBo", + "v=spf1 include:_spf.google.com include:spf.mail.intercom.io include:stspg-customer.com include:mail.zendesk.com ~all", + "status-page-domain-verification=dgtdvzlp8tfn", + }, + "hashicorp.com", + }, + } + + for _, test := range tests { + recordName := fmt.Sprintf("data.dns_txt_record_set.%s", test.DataSourceName) + resource.UnitTest(t, resource.TestCase{ + Providers: testAccProviders, + Steps: []resource.TestStep{ + resource.TestStep{ + Config: test.DataSourceBlock, + Check: resource.ComposeTestCheckFunc( + testCheckAttrStringArray(recordName, "records", test.Expected), + ), + }, + resource.TestStep{ + Config: test.DataSourceBlock, + Check: resource.ComposeTestCheckFunc( + testCheckAttrStringArrayMember(recordName, "record", test.Expected), + ), + }, + resource.TestStep{ + Config: test.DataSourceBlock, + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttr(recordName, "id", test.Host), + ), + }, + }, + }) + } +} diff --git a/builtin/providers/dns/test_check_attr_string_array.go b/builtin/providers/dns/test_check_attr_string_array.go index 344c7cb8d..978b62a00 100644 --- a/builtin/providers/dns/test_check_attr_string_array.go +++ b/builtin/providers/dns/test_check_attr_string_array.go @@ -27,24 +27,27 @@ func testCheckAttrStringArray(name, key string, value []string) r.TestCheckFunc return fmt.Errorf("Attributes not found for %s", attrKey) } - got, _ := strconv.Atoi(count) - if got != len(value) { + gotCount, _ := strconv.Atoi(count) + if gotCount != len(value) { return fmt.Errorf("Mismatch array count for %s: got %s, wanted %d", key, count, len(value)) } - for i, want := range value { + Next: + for i := 0; i < gotCount; i++ { attrKey = fmt.Sprintf("%s.%d", key, i) got, ok := is.Attributes[attrKey] if !ok { return fmt.Errorf("Missing array item for %s", attrKey) } - if got != want { - return fmt.Errorf( - "Mismatched array item for %s: got %s, want %s", - attrKey, - got, - want) + for _, want := range value { + if got == want { + continue Next + } } + return fmt.Errorf( + "Unexpected array item for %s: got %s", + attrKey, + got) } return nil diff --git a/builtin/providers/dns/test_check_attr_string_array_member.go b/builtin/providers/dns/test_check_attr_string_array_member.go new file mode 100644 index 000000000..e246ed32e --- /dev/null +++ b/builtin/providers/dns/test_check_attr_string_array_member.go @@ -0,0 +1,39 @@ +package dns + +import ( + "fmt" + + r "github.com/hashicorp/terraform/helper/resource" + "github.com/hashicorp/terraform/terraform" +) + +func testCheckAttrStringArrayMember(name, key string, value []string) r.TestCheckFunc { + return func(s *terraform.State) error { + ms := s.RootModule() + rs, ok := ms.Resources[name] + if !ok { + return fmt.Errorf("Not found: %s", name) + } + + is := rs.Primary + if is == nil { + return fmt.Errorf("No primary instance: %s", name) + } + + got, ok := is.Attributes[key] + if !ok { + return fmt.Errorf("Attributes not found for %s", key) + } + + for _, want := range value { + if got == want { + return nil + } + } + + return fmt.Errorf( + "Unexpected value for %s: got %s", + key, + got) + } +} diff --git a/builtin/providers/dnsimple/import_dnsimple_record_test.go b/builtin/providers/dnsimple/import_dnsimple_record_test.go new file mode 100644 index 000000000..420a6e4c2 --- /dev/null +++ b/builtin/providers/dnsimple/import_dnsimple_record_test.go @@ -0,0 +1,41 @@ +package dnsimple + +import ( + "fmt" + "os" + "testing" + + "github.com/hashicorp/terraform/helper/resource" +) + +func TestAccDnsimpleRecord_import(t *testing.T) { + resourceName := "dnsimple_record.foobar" + domain := os.Getenv("DNSIMPLE_DOMAIN") + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckDNSimpleRecordDestroy, + Steps: []resource.TestStep{ + resource.TestStep{ + Config: fmt.Sprintf(testAccCheckDNSimpleRecordConfig_import, domain), + }, + resource.TestStep{ + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateIdPrefix: fmt.Sprintf("%s_", domain), + }, + }, + }) +} + +const testAccCheckDNSimpleRecordConfig_import = ` +resource "dnsimple_record" "foobar" { + domain = "%s" + + name = "terraform" + value = "192.168.0.10" + type = "A" + ttl = 3600 +}` diff --git a/builtin/providers/dnsimple/resource_dnsimple_record.go b/builtin/providers/dnsimple/resource_dnsimple_record.go index a5e39472c..af1c26de9 100644 --- a/builtin/providers/dnsimple/resource_dnsimple_record.go +++ b/builtin/providers/dnsimple/resource_dnsimple_record.go @@ -4,6 +4,7 @@ import ( "fmt" "log" "strconv" + "strings" "github.com/dnsimple/dnsimple-go/dnsimple" "github.com/hashicorp/terraform/helper/schema" @@ -15,6 +16,9 @@ func resourceDNSimpleRecord() *schema.Resource { Read: resourceDNSimpleRecordRead, Update: resourceDNSimpleRecordUpdate, Delete: resourceDNSimpleRecordDelete, + Importer: &schema.ResourceImporter{ + State: resourceDNSimpleRecordImport, + }, Schema: map[string]*schema.Schema{ "domain": { @@ -104,6 +108,11 @@ func resourceDNSimpleRecordRead(d *schema.ResourceData, meta interface{}) error resp, err := provider.client.Zones.GetRecord(provider.config.Account, d.Get("domain").(string), recordID) if err != nil { + if err != nil && strings.Contains(err.Error(), "404") { + log.Printf("DNSimple Record Not Found - Refreshing from State") + d.SetId("") + return nil + } return fmt.Errorf("Couldn't find DNSimple Record: %s", err) } @@ -178,3 +187,19 @@ func resourceDNSimpleRecordDelete(d *schema.ResourceData, meta interface{}) erro return nil } + +func resourceDNSimpleRecordImport(d *schema.ResourceData, meta interface{}) ([]*schema.ResourceData, error) { + parts := strings.Split(d.Id(), "_") + + if len(parts) != 2 { + return nil, fmt.Errorf("Error Importing dnsimple_record. Please make sure the record ID is in the form DOMAIN_RECORDID (i.e. example.com_1234") + } + + d.SetId(parts[1]) + d.Set("domain", parts[0]) + + if err := resourceDNSimpleRecordRead(d, meta); err != nil { + return nil, err + } + return []*schema.ResourceData{d}, nil +} diff --git a/builtin/providers/dnsimple/resource_dnsimple_record_test.go b/builtin/providers/dnsimple/resource_dnsimple_record_test.go index e7e5e876f..8b19697bd 100644 --- a/builtin/providers/dnsimple/resource_dnsimple_record_test.go +++ b/builtin/providers/dnsimple/resource_dnsimple_record_test.go @@ -20,7 +20,7 @@ func TestAccDNSimpleRecord_Basic(t *testing.T) { Providers: testAccProviders, CheckDestroy: testAccCheckDNSimpleRecordDestroy, Steps: []resource.TestStep{ - resource.TestStep{ + { Config: fmt.Sprintf(testAccCheckDNSimpleRecordConfig_basic, domain), Check: resource.ComposeTestCheckFunc( testAccCheckDNSimpleRecordExists("dnsimple_record.foobar", &record), @@ -46,7 +46,7 @@ func TestAccDNSimpleRecord_CreateMxWithPriority(t *testing.T) { Providers: testAccProviders, CheckDestroy: testAccCheckDNSimpleRecordDestroy, Steps: []resource.TestStep{ - resource.TestStep{ + { Config: fmt.Sprintf(testAccCheckDNSimpleRecordConfig_mx, domain), Check: resource.ComposeTestCheckFunc( testAccCheckDNSimpleRecordExists("dnsimple_record.foobar", &record), @@ -73,7 +73,7 @@ func TestAccDNSimpleRecord_Updated(t *testing.T) { Providers: testAccProviders, CheckDestroy: testAccCheckDNSimpleRecordDestroy, Steps: []resource.TestStep{ - resource.TestStep{ + { Config: fmt.Sprintf(testAccCheckDNSimpleRecordConfig_basic, domain), Check: resource.ComposeTestCheckFunc( testAccCheckDNSimpleRecordExists("dnsimple_record.foobar", &record), @@ -86,7 +86,7 @@ func TestAccDNSimpleRecord_Updated(t *testing.T) { "dnsimple_record.foobar", "value", "192.168.0.10"), ), }, - resource.TestStep{ + { Config: fmt.Sprintf(testAccCheckDNSimpleRecordConfig_new_value, domain), Check: resource.ComposeTestCheckFunc( testAccCheckDNSimpleRecordExists("dnsimple_record.foobar", &record), @@ -103,6 +103,27 @@ func TestAccDNSimpleRecord_Updated(t *testing.T) { }) } +func TestAccDNSimpleRecord_disappears(t *testing.T) { + var record dnsimple.ZoneRecord + domain := os.Getenv("DNSIMPLE_DOMAIN") + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckDNSimpleRecordDestroy, + Steps: []resource.TestStep{ + { + Config: fmt.Sprintf(testAccCheckDNSimpleRecordConfig_basic, domain), + Check: resource.ComposeTestCheckFunc( + testAccCheckDNSimpleRecordExists("dnsimple_record.foobar", &record), + testAccCheckDNSimpleRecordDisappears(&record, domain), + ), + ExpectNonEmptyPlan: true, + }, + }, + }) +} + func TestAccDNSimpleRecord_UpdatedMx(t *testing.T) { var record dnsimple.ZoneRecord domain := os.Getenv("DNSIMPLE_DOMAIN") @@ -112,7 +133,7 @@ func TestAccDNSimpleRecord_UpdatedMx(t *testing.T) { Providers: testAccProviders, CheckDestroy: testAccCheckDNSimpleRecordDestroy, Steps: []resource.TestStep{ - resource.TestStep{ + { Config: fmt.Sprintf(testAccCheckDNSimpleRecordConfig_mx, domain), Check: resource.ComposeTestCheckFunc( testAccCheckDNSimpleRecordExists("dnsimple_record.foobar", &record), @@ -126,7 +147,7 @@ func TestAccDNSimpleRecord_UpdatedMx(t *testing.T) { "dnsimple_record.foobar", "priority", "5"), ), }, - resource.TestStep{ + { Config: fmt.Sprintf(testAccCheckDNSimpleRecordConfig_mx_new_value, domain), Check: resource.ComposeTestCheckFunc( testAccCheckDNSimpleRecordExists("dnsimple_record.foobar", &record), @@ -144,6 +165,21 @@ func TestAccDNSimpleRecord_UpdatedMx(t *testing.T) { }) } +func testAccCheckDNSimpleRecordDisappears(record *dnsimple.ZoneRecord, domain string) resource.TestCheckFunc { + return func(s *terraform.State) error { + + provider := testAccProvider.Meta().(*Client) + + _, err := provider.client.Zones.DeleteRecord(provider.config.Account, domain, record.ID) + if err != nil { + return err + } + + return nil + } + +} + func testAccCheckDNSimpleRecordDestroy(s *terraform.State) error { provider := testAccProvider.Meta().(*Client) diff --git a/builtin/providers/docker/resource_docker_container.go b/builtin/providers/docker/resource_docker_container.go index 6bc03de3e..a084ad434 100644 --- a/builtin/providers/docker/resource_docker_container.go +++ b/builtin/providers/docker/resource_docker_container.go @@ -184,17 +184,10 @@ func resourceDockerContainer() *schema.Resource { }, "host_path": &schema.Schema{ - Type: schema.TypeString, - Optional: true, - ForceNew: true, - ValidateFunc: func(v interface{}, k string) (ws []string, es []error) { - value := v.(string) - if !regexp.MustCompile(`^/`).MatchString(value) { - es = append(es, fmt.Errorf( - "%q must be an absolute path", k)) - } - return - }, + Type: schema.TypeString, + Optional: true, + ForceNew: true, + ValidateFunc: validateDockerContainerPath, }, "volume_name": &schema.Schema{ @@ -515,3 +508,13 @@ func resourceDockerUploadHash(v interface{}) int { return hashcode.String(buf.String()) } + +func validateDockerContainerPath(v interface{}, k string) (ws []string, errors []error) { + + value := v.(string) + if !regexp.MustCompile(`^[a-zA-Z]:\\|^/`).MatchString(value) { + errors = append(errors, fmt.Errorf("%q must be an absolute path", k)) + } + + return +} diff --git a/builtin/providers/docker/resource_docker_container_test.go b/builtin/providers/docker/resource_docker_container_test.go index 1da7e87e6..e9c3bb950 100644 --- a/builtin/providers/docker/resource_docker_container_test.go +++ b/builtin/providers/docker/resource_docker_container_test.go @@ -27,6 +27,29 @@ func TestAccDockerContainer_basic(t *testing.T) { }) } +func TestAccDockerContainerPath_validation(t *testing.T) { + cases := []struct { + Value string + ErrCount int + }{ + {Value: "/var/log", ErrCount: 0}, + {Value: "/tmp", ErrCount: 0}, + {Value: "C:\\Windows\\System32", ErrCount: 0}, + {Value: "C:\\Program Files\\MSBuild", ErrCount: 0}, + {Value: "test", ErrCount: 1}, + {Value: "C:Test", ErrCount: 1}, + {Value: "", ErrCount: 1}, + } + + for _, tc := range cases { + _, errors := validateDockerContainerPath(tc.Value, "docker_container") + + if len(errors) != tc.ErrCount { + t.Fatalf("Expected the Docker Container Path to trigger a validation error") + } + } +} + func TestAccDockerContainer_volume(t *testing.T) { var c dc.Container diff --git a/builtin/providers/dyn/config.go b/builtin/providers/dyn/config.go index 091c929d9..6910ef76d 100644 --- a/builtin/providers/dyn/config.go +++ b/builtin/providers/dyn/config.go @@ -4,6 +4,7 @@ import ( "fmt" "log" + "github.com/hashicorp/terraform/helper/logging" "github.com/nesv/go-dynect/dynect" ) @@ -16,8 +17,11 @@ type Config struct { // Client() returns a new client for accessing dyn. func (c *Config) Client() (*dynect.ConvenientClient, error) { client := dynect.NewConvenientClient(c.CustomerName) - err := client.Login(c.Username, c.Password) + if logging.IsDebugOrHigher() { + client.Verbose(true) + } + err := client.Login(c.Username, c.Password) if err != nil { return nil, fmt.Errorf("Error setting up Dyn client: %s", err) } diff --git a/builtin/providers/external/data_source_test.go b/builtin/providers/external/data_source_test.go index dbdf00386..b1ceabddf 100644 --- a/builtin/providers/external/data_source_test.go +++ b/builtin/providers/external/data_source_test.go @@ -5,6 +5,7 @@ import ( "os" "os/exec" "path" + "path/filepath" "regexp" "testing" @@ -117,8 +118,13 @@ func buildDataSourceTestProgram() (string, error) { return "", fmt.Errorf("failed to build test stub program: %s", err) } + gopath := os.Getenv("GOPATH") + if gopath == "" { + gopath = filepath.Join(os.Getenv("HOME") + "/go") + } + programPath := path.Join( - os.Getenv("GOPATH"), "bin", "tf-acc-external-data-source", + filepath.SplitList(gopath)[0], "bin", "tf-acc-external-data-source", ) return programPath, nil } diff --git a/builtin/providers/fastly/resource_fastly_service_v1.go b/builtin/providers/fastly/resource_fastly_service_v1.go index 852af30ce..bb3fb6bfd 100644 --- a/builtin/providers/fastly/resource_fastly_service_v1.go +++ b/builtin/providers/fastly/resource_fastly_service_v1.go @@ -37,7 +37,7 @@ func resourceServiceV1() *schema.Resource { // creating and activating. It's used internally, but also exported for // users to see. "active_version": { - Type: schema.TypeString, + Type: schema.TypeInt, Computed: true, }, @@ -107,6 +107,80 @@ func resourceServiceV1() *schema.Resource { Description: "The default hostname for the version", }, + "healthcheck": { + Type: schema.TypeSet, + Optional: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + // required fields + "name": { + Type: schema.TypeString, + Required: true, + Description: "A name to refer to this healthcheck", + }, + "host": { + Type: schema.TypeString, + Required: true, + Description: "Which host to check", + }, + "path": { + Type: schema.TypeString, + Required: true, + Description: "The path to check", + }, + // optional fields + "check_interval": { + Type: schema.TypeInt, + Optional: true, + Default: 5000, + Description: "How often to run the healthcheck in milliseconds", + }, + "expected_response": { + Type: schema.TypeInt, + Optional: true, + Default: 200, + Description: "The status code expected from the host", + }, + "http_version": { + Type: schema.TypeString, + Optional: true, + Default: "1.1", + Description: "Whether to use version 1.0 or 1.1 HTTP", + }, + "initial": { + Type: schema.TypeInt, + Optional: true, + Default: 2, + Description: "When loading a config, the initial number of probes to be seen as OK", + }, + "method": { + Type: schema.TypeString, + Optional: true, + Default: "HEAD", + Description: "Which HTTP method to use", + }, + "threshold": { + Type: schema.TypeInt, + Optional: true, + Default: 3, + Description: "How many healthchecks must succeed to be considered healthy", + }, + "timeout": { + Type: schema.TypeInt, + Optional: true, + Default: 500, + Description: "Timeout in milliseconds", + }, + "window": { + Type: schema.TypeInt, + Optional: true, + Default: 5, + Description: "The number of most recent healthcheck queries to keep for this healthcheck", + }, + }, + }, + }, + "backend": { Type: schema.TypeSet, Optional: true, @@ -154,6 +228,12 @@ func resourceServiceV1() *schema.Resource { Default: 15000, Description: "How long to wait for the first bytes in milliseconds", }, + "healthcheck": { + Type: schema.TypeString, + Optional: true, + Default: "", + Description: "The healthcheck name that should be used for this Backend", + }, "max_conn": { Type: schema.TypeInt, Optional: true, @@ -238,17 +318,18 @@ func resourceServiceV1() *schema.Resource { Required: true, Description: "A name to refer to this Cache Setting", }, - "cache_condition": { - Type: schema.TypeString, - Required: true, - Description: "Name of a condition to check if this Cache Setting applies", - }, "action": { Type: schema.TypeString, Optional: true, Description: "Action to take", }, // optional + "cache_condition": { + Type: schema.TypeString, + Optional: true, + Default: "", + Description: "Name of a condition to check if this Cache Setting applies", + }, "stale_ttl": { Type: schema.TypeInt, Optional: true, @@ -403,80 +484,6 @@ func resourceServiceV1() *schema.Resource { }, }, - "healthcheck": { - Type: schema.TypeSet, - Optional: true, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - // required fields - "name": { - Type: schema.TypeString, - Required: true, - Description: "A name to refer to this healthcheck", - }, - "host": { - Type: schema.TypeString, - Required: true, - Description: "Which host to check", - }, - "path": { - Type: schema.TypeString, - Required: true, - Description: "The path to check", - }, - // optional fields - "check_interval": { - Type: schema.TypeInt, - Optional: true, - Default: 5000, - Description: "How often to run the healthcheck in milliseconds", - }, - "expected_response": { - Type: schema.TypeInt, - Optional: true, - Default: 200, - Description: "The status code expected from the host", - }, - "http_version": { - Type: schema.TypeString, - Optional: true, - Default: "1.1", - Description: "Whether to use version 1.0 or 1.1 HTTP", - }, - "initial": { - Type: schema.TypeInt, - Optional: true, - Default: 2, - Description: "When loading a config, the initial number of probes to be seen as OK", - }, - "method": { - Type: schema.TypeString, - Optional: true, - Default: "HEAD", - Description: "Which HTTP method to use", - }, - "threshold": { - Type: schema.TypeInt, - Optional: true, - Default: 3, - Description: "How many healthchecks must succeed to be considered healthy", - }, - "timeout": { - Type: schema.TypeInt, - Optional: true, - Default: 500, - Description: "Timeout in milliseconds", - }, - "window": { - Type: schema.TypeInt, - Optional: true, - Default: 5, - Description: "The number of most recent healthcheck queries to keep for this healthcheck", - }, - }, - }, - }, - "s3logging": { Type: schema.TypeSet, Optional: true, @@ -539,7 +546,7 @@ func resourceServiceV1() *schema.Resource { Optional: true, Default: 1, Description: "The version of the custom logging format used for the configured endpoint. Can be either 1 or 2. (Default: 1)", - ValidateFunc: validateS3FormatVersion, + ValidateFunc: validateLoggingFormatVersion, }, "timestamp_format": { Type: schema.TypeString, @@ -594,6 +601,118 @@ func resourceServiceV1() *schema.Resource { }, }, }, + "sumologic": { + Type: schema.TypeSet, + Optional: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + // Required fields + "name": { + Type: schema.TypeString, + Required: true, + Description: "Unique name to refer to this logging setup", + }, + "url": { + Type: schema.TypeString, + Required: true, + Description: "The URL to POST to.", + }, + // Optional fields + "format": { + Type: schema.TypeString, + Optional: true, + Default: "%h %l %u %t %r %>s", + Description: "Apache-style string or VCL variables to use for log formatting", + }, + "format_version": { + Type: schema.TypeInt, + Optional: true, + Default: 1, + Description: "The version of the custom logging format used for the configured endpoint. Can be either 1 or 2. (Default: 1)", + ValidateFunc: validateLoggingFormatVersion, + }, + "response_condition": { + Type: schema.TypeString, + Optional: true, + Default: "", + Description: "Name of a condition to apply this logging.", + }, + "message_type": { + Type: schema.TypeString, + Optional: true, + Default: "classic", + Description: "How the message should be formatted.", + ValidateFunc: validateLoggingMessageType, + }, + }, + }, + }, + + "gcslogging": { + Type: schema.TypeSet, + Optional: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + // Required fields + "name": { + Type: schema.TypeString, + Required: true, + Description: "Unique name to refer to this logging setup", + }, + "email": { + Type: schema.TypeString, + Required: true, + Description: "The email address associated with the target GCS bucket on your account.", + }, + "bucket_name": { + Type: schema.TypeString, + Required: true, + Description: "The name of the bucket in which to store the logs.", + }, + "secret_key": { + Type: schema.TypeString, + Required: true, + Description: "The secret key associated with the target gcs bucket on your account.", + }, + // Optional fields + "path": { + Type: schema.TypeString, + Optional: true, + Description: "Path to store the files. Must end with a trailing slash", + }, + "gzip_level": { + Type: schema.TypeInt, + Optional: true, + Default: 0, + Description: "Gzip Compression level", + }, + "period": { + Type: schema.TypeInt, + Optional: true, + Default: 3600, + Description: "How frequently the logs should be transferred, in seconds (Default 3600)", + }, + "format": { + Type: schema.TypeString, + Optional: true, + Default: "%h %l %u %t %r %>s", + Description: "Apache-style string or VCL variables to use for log formatting", + }, + "timestamp_format": { + Type: schema.TypeString, + Optional: true, + Default: "%Y-%m-%dT%H:%M:%S.000", + Description: "specified timestamp formatting (default `%Y-%m-%dT%H:%M:%S.000`)", + }, + "response_condition": { + Type: schema.TypeString, + Optional: true, + Default: "", + Description: "Name of a condition to apply this logging.", + }, + }, + }, + }, "response_object": { Type: schema.TypeSet, @@ -658,12 +777,13 @@ func resourceServiceV1() *schema.Resource { Required: true, Description: "Unique name to refer to this Request Setting", }, + // Optional fields "request_condition": { Type: schema.TypeString, - Required: true, - Description: "Name of a request condition to apply.", + Optional: true, + Default: "", + Description: "Name of a request condition to apply. If there is no condition this setting will always be applied.", }, - // Optional fields "max_stale_age": { Type: schema.TypeInt, Optional: true, @@ -820,14 +940,14 @@ func resourceServiceV1Update(d *schema.ResourceData, meta interface{}) error { } if needsChange { - latestVersion := d.Get("active_version").(string) - if latestVersion == "" { + latestVersion := d.Get("active_version").(int) + if latestVersion == 0 { // If the service was just created, there is an empty Version 1 available // that is unlocked and can be updated - latestVersion = "1" + latestVersion = 1 } else { // Clone the latest version, giving us an unlocked version we can modify - log.Printf("[DEBUG] Creating clone of version (%s) for updates", latestVersion) + log.Printf("[DEBUG] Creating clone of version (%d) for updates", latestVersion) newVersion, err := conn.CloneVersion(&gofastly.CloneVersionInput{ Service: d.Id(), Version: latestVersion, @@ -982,6 +1102,65 @@ func resourceServiceV1Update(d *schema.ResourceData, meta interface{}) error { } } + // Healthchecks need to be updated BEFORE backends + if d.HasChange("healthcheck") { + oh, nh := d.GetChange("healthcheck") + if oh == nil { + oh = new(schema.Set) + } + if nh == nil { + nh = new(schema.Set) + } + + ohs := oh.(*schema.Set) + nhs := nh.(*schema.Set) + removeHealthCheck := ohs.Difference(nhs).List() + addHealthCheck := nhs.Difference(ohs).List() + + // DELETE old healthcheck configurations + for _, hRaw := range removeHealthCheck { + hf := hRaw.(map[string]interface{}) + opts := gofastly.DeleteHealthCheckInput{ + Service: d.Id(), + Version: latestVersion, + Name: hf["name"].(string), + } + + log.Printf("[DEBUG] Fastly Healthcheck removal opts: %#v", opts) + err := conn.DeleteHealthCheck(&opts) + if err != nil { + return err + } + } + + // POST new/updated Healthcheck + for _, hRaw := range addHealthCheck { + hf := hRaw.(map[string]interface{}) + + opts := gofastly.CreateHealthCheckInput{ + Service: d.Id(), + Version: latestVersion, + Name: hf["name"].(string), + Host: hf["host"].(string), + Path: hf["path"].(string), + CheckInterval: uint(hf["check_interval"].(int)), + ExpectedResponse: uint(hf["expected_response"].(int)), + HTTPVersion: hf["http_version"].(string), + Initial: uint(hf["initial"].(int)), + Method: hf["method"].(string), + Threshold: uint(hf["threshold"].(int)), + Timeout: uint(hf["timeout"].(int)), + Window: uint(hf["window"].(int)), + } + + log.Printf("[DEBUG] Create Healthcheck Opts: %#v", opts) + _, err := conn.CreateHealthCheck(&opts) + if err != nil { + return err + } + } + } + // find difference in backends if d.HasChange("backend") { ob, nb := d.GetChange("backend") @@ -1035,6 +1214,7 @@ func resourceServiceV1Update(d *schema.ResourceData, meta interface{}) error { MaxConn: uint(df["max_conn"].(int)), Weight: uint(df["weight"].(int)), RequestCondition: df["request_condition"].(string), + HealthCheck: df["healthcheck"].(string), } log.Printf("[DEBUG] Create Backend Opts: %#v", opts) @@ -1164,65 +1344,6 @@ func resourceServiceV1Update(d *schema.ResourceData, meta interface{}) error { } } - // find difference in Healthcheck - if d.HasChange("healthcheck") { - oh, nh := d.GetChange("healthcheck") - if oh == nil { - oh = new(schema.Set) - } - if nh == nil { - nh = new(schema.Set) - } - - ohs := oh.(*schema.Set) - nhs := nh.(*schema.Set) - removeHealthCheck := ohs.Difference(nhs).List() - addHealthCheck := nhs.Difference(ohs).List() - - // DELETE old healthcheck configurations - for _, hRaw := range removeHealthCheck { - hf := hRaw.(map[string]interface{}) - opts := gofastly.DeleteHealthCheckInput{ - Service: d.Id(), - Version: latestVersion, - Name: hf["name"].(string), - } - - log.Printf("[DEBUG] Fastly Healthcheck removal opts: %#v", opts) - err := conn.DeleteHealthCheck(&opts) - if err != nil { - return err - } - } - - // POST new/updated Healthcheck - for _, hRaw := range addHealthCheck { - hf := hRaw.(map[string]interface{}) - - opts := gofastly.CreateHealthCheckInput{ - Service: d.Id(), - Version: latestVersion, - Name: hf["name"].(string), - Host: hf["host"].(string), - Path: hf["path"].(string), - CheckInterval: uint(hf["check_interval"].(int)), - ExpectedResponse: uint(hf["expected_response"].(int)), - HTTPVersion: hf["http_version"].(string), - Initial: uint(hf["initial"].(int)), - Method: hf["method"].(string), - Threshold: uint(hf["threshold"].(int)), - Timeout: uint(hf["timeout"].(int)), - Window: uint(hf["window"].(int)), - } - - log.Printf("[DEBUG] Create Healthcheck Opts: %#v", opts) - _, err := conn.CreateHealthCheck(&opts) - if err != nil { - return err - } - } - } - // find difference in s3logging if d.HasChange("s3logging") { os, ns := d.GetChange("s3logging") @@ -1344,6 +1465,112 @@ func resourceServiceV1Update(d *schema.ResourceData, meta interface{}) error { } } + // find difference in Sumologic + if d.HasChange("sumologic") { + os, ns := d.GetChange("sumologic") + if os == nil { + os = new(schema.Set) + } + if ns == nil { + ns = new(schema.Set) + } + + oss := os.(*schema.Set) + nss := ns.(*schema.Set) + removeSumologic := oss.Difference(nss).List() + addSumologic := nss.Difference(oss).List() + + // DELETE old sumologic configurations + for _, pRaw := range removeSumologic { + sf := pRaw.(map[string]interface{}) + opts := gofastly.DeleteSumologicInput{ + Service: d.Id(), + Version: latestVersion, + Name: sf["name"].(string), + } + + log.Printf("[DEBUG] Fastly Sumologic removal opts: %#v", opts) + err := conn.DeleteSumologic(&opts) + if err != nil { + return err + } + } + + // POST new/updated Sumologic + for _, pRaw := range addSumologic { + sf := pRaw.(map[string]interface{}) + opts := gofastly.CreateSumologicInput{ + Service: d.Id(), + Version: latestVersion, + Name: sf["name"].(string), + URL: sf["url"].(string), + Format: sf["format"].(string), + FormatVersion: sf["format_version"].(int), + ResponseCondition: sf["response_condition"].(string), + MessageType: sf["message_type"].(string), + } + + log.Printf("[DEBUG] Create Sumologic Opts: %#v", opts) + _, err := conn.CreateSumologic(&opts) + if err != nil { + return err + } + } + } + + // find difference in gcslogging + if d.HasChange("gcslogging") { + os, ns := d.GetChange("gcslogging") + if os == nil { + os = new(schema.Set) + } + if ns == nil { + ns = new(schema.Set) + } + + oss := os.(*schema.Set) + nss := ns.(*schema.Set) + removeGcslogging := oss.Difference(nss).List() + addGcslogging := nss.Difference(oss).List() + + // DELETE old gcslogging configurations + for _, pRaw := range removeGcslogging { + sf := pRaw.(map[string]interface{}) + opts := gofastly.DeleteGCSInput{ + Service: d.Id(), + Version: latestVersion, + Name: sf["name"].(string), + } + + log.Printf("[DEBUG] Fastly gcslogging removal opts: %#v", opts) + err := conn.DeleteGCS(&opts) + if err != nil { + return err + } + } + + // POST new/updated gcslogging + for _, pRaw := range addGcslogging { + sf := pRaw.(map[string]interface{}) + opts := gofastly.CreateGCSInput{ + Service: d.Id(), + Version: latestVersion, + Name: sf["name"].(string), + User: sf["email"].(string), + Bucket: sf["bucket_name"].(string), + SecretKey: sf["secret_key"].(string), + Format: sf["format"].(string), + ResponseCondition: sf["response_condition"].(string), + } + + log.Printf("[DEBUG] Create GCS Opts: %#v", opts) + _, err := conn.CreateGCS(&opts) + if err != nil { + return err + } + } + } + // find difference in Response Object if d.HasChange("response_object") { or, nr := d.GetChange("response_object") @@ -1565,7 +1792,7 @@ func resourceServiceV1Update(d *schema.ResourceData, meta interface{}) error { } // validate version - log.Printf("[DEBUG] Validating Fastly Service (%s), Version (%s)", d.Id(), latestVersion) + log.Printf("[DEBUG] Validating Fastly Service (%s), Version (%v)", d.Id(), latestVersion) valid, msg, err := conn.ValidateVersion(&gofastly.ValidateVersionInput{ Service: d.Id(), Version: latestVersion, @@ -1579,13 +1806,13 @@ func resourceServiceV1Update(d *schema.ResourceData, meta interface{}) error { return fmt.Errorf("[ERR] Invalid configuration for Fastly Service (%s): %s", d.Id(), msg) } - log.Printf("[DEBUG] Activating Fastly Service (%s), Version (%s)", d.Id(), latestVersion) + log.Printf("[DEBUG] Activating Fastly Service (%s), Version (%v)", d.Id(), latestVersion) _, err = conn.ActivateVersion(&gofastly.ActivateVersionInput{ Service: d.Id(), Version: latestVersion, }) if err != nil { - return fmt.Errorf("[ERR] Error activating version (%s): %s", latestVersion, err) + return fmt.Errorf("[ERR] Error activating version (%d): %s", latestVersion, err) } // Only if the version is valid and activated do we set the active_version. @@ -1627,7 +1854,7 @@ func resourceServiceV1Read(d *schema.ResourceData, meta interface{}) error { // If CreateService succeeds, but initial updates to the Service fail, we'll // have an empty ActiveService version (no version is active, so we can't // query for information on it) - if s.ActiveVersion.Number != "" { + if s.ActiveVersion.Number != 0 { settingsOpts := gofastly.GetSettingsInput{ Service: d.Id(), Version: s.ActiveVersion.Number, @@ -1636,7 +1863,7 @@ func resourceServiceV1Read(d *schema.ResourceData, meta interface{}) error { d.Set("default_host", settings.DefaultHost) d.Set("default_ttl", settings.DefaultTTL) } else { - return fmt.Errorf("[ERR] Error looking up Version settings for (%s), version (%s): %s", d.Id(), s.ActiveVersion.Number, err) + return fmt.Errorf("[ERR] Error looking up Version settings for (%s), version (%v): %s", d.Id(), s.ActiveVersion.Number, err) } // TODO: update go-fastly to support an ActiveVersion struct, which contains @@ -1649,7 +1876,7 @@ func resourceServiceV1Read(d *schema.ResourceData, meta interface{}) error { }) if err != nil { - return fmt.Errorf("[ERR] Error looking up Domains for (%s), version (%s): %s", d.Id(), s.ActiveVersion.Number, err) + return fmt.Errorf("[ERR] Error looking up Domains for (%s), version (%v): %s", d.Id(), s.ActiveVersion.Number, err) } // Refresh Domains @@ -1667,7 +1894,7 @@ func resourceServiceV1Read(d *schema.ResourceData, meta interface{}) error { }) if err != nil { - return fmt.Errorf("[ERR] Error looking up Backends for (%s), version (%s): %s", d.Id(), s.ActiveVersion.Number, err) + return fmt.Errorf("[ERR] Error looking up Backends for (%s), version (%v): %s", d.Id(), s.ActiveVersion.Number, err) } bl := flattenBackends(backendList) @@ -1684,7 +1911,7 @@ func resourceServiceV1Read(d *schema.ResourceData, meta interface{}) error { }) if err != nil { - return fmt.Errorf("[ERR] Error looking up Headers for (%s), version (%s): %s", d.Id(), s.ActiveVersion.Number, err) + return fmt.Errorf("[ERR] Error looking up Headers for (%s), version (%v): %s", d.Id(), s.ActiveVersion.Number, err) } hl := flattenHeaders(headerList) @@ -1701,7 +1928,7 @@ func resourceServiceV1Read(d *schema.ResourceData, meta interface{}) error { }) if err != nil { - return fmt.Errorf("[ERR] Error looking up Gzips for (%s), version (%s): %s", d.Id(), s.ActiveVersion.Number, err) + return fmt.Errorf("[ERR] Error looking up Gzips for (%s), version (%v): %s", d.Id(), s.ActiveVersion.Number, err) } gl := flattenGzips(gzipsList) @@ -1718,7 +1945,7 @@ func resourceServiceV1Read(d *schema.ResourceData, meta interface{}) error { }) if err != nil { - return fmt.Errorf("[ERR] Error looking up Healthcheck for (%s), version (%s): %s", d.Id(), s.ActiveVersion.Number, err) + return fmt.Errorf("[ERR] Error looking up Healthcheck for (%s), version (%v): %s", d.Id(), s.ActiveVersion.Number, err) } hcl := flattenHealthchecks(healthcheckList) @@ -1735,7 +1962,7 @@ func resourceServiceV1Read(d *schema.ResourceData, meta interface{}) error { }) if err != nil { - return fmt.Errorf("[ERR] Error looking up S3 Logging for (%s), version (%s): %s", d.Id(), s.ActiveVersion.Number, err) + return fmt.Errorf("[ERR] Error looking up S3 Logging for (%s), version (%v): %s", d.Id(), s.ActiveVersion.Number, err) } sl := flattenS3s(s3List) @@ -1752,7 +1979,7 @@ func resourceServiceV1Read(d *schema.ResourceData, meta interface{}) error { }) if err != nil { - return fmt.Errorf("[ERR] Error looking up Papertrail for (%s), version (%s): %s", d.Id(), s.ActiveVersion.Number, err) + return fmt.Errorf("[ERR] Error looking up Papertrail for (%s), version (%v): %s", d.Id(), s.ActiveVersion.Number, err) } pl := flattenPapertrails(papertrailList) @@ -1761,6 +1988,38 @@ func resourceServiceV1Read(d *schema.ResourceData, meta interface{}) error { log.Printf("[WARN] Error setting Papertrail for (%s): %s", d.Id(), err) } + // refresh Sumologic Logging + log.Printf("[DEBUG] Refreshing Sumologic for (%s)", d.Id()) + sumologicList, err := conn.ListSumologics(&gofastly.ListSumologicsInput{ + Service: d.Id(), + Version: s.ActiveVersion.Number, + }) + + if err != nil { + return fmt.Errorf("[ERR] Error looking up Sumologic for (%s), version (%v): %s", d.Id(), s.ActiveVersion.Number, err) + } + + sul := flattenSumologics(sumologicList) + if err := d.Set("sumologic", sul); err != nil { + log.Printf("[WARN] Error setting Sumologic for (%s): %s", d.Id(), err) + } + + // refresh GCS Logging + log.Printf("[DEBUG] Refreshing GCS for (%s)", d.Id()) + GCSList, err := conn.ListGCSs(&gofastly.ListGCSsInput{ + Service: d.Id(), + Version: s.ActiveVersion.Number, + }) + + if err != nil { + return fmt.Errorf("[ERR] Error looking up GCS for (%s), version (%v): %s", d.Id(), s.ActiveVersion.Number, err) + } + + gcsl := flattenGCS(GCSList) + if err := d.Set("gcs", gcsl); err != nil { + log.Printf("[WARN] Error setting gcs for (%s): %s", d.Id(), err) + } + // refresh Response Objects log.Printf("[DEBUG] Refreshing Response Object for (%s)", d.Id()) responseObjectList, err := conn.ListResponseObjects(&gofastly.ListResponseObjectsInput{ @@ -1769,7 +2028,7 @@ func resourceServiceV1Read(d *schema.ResourceData, meta interface{}) error { }) if err != nil { - return fmt.Errorf("[ERR] Error looking up Response Object for (%s), version (%s): %s", d.Id(), s.ActiveVersion.Number, err) + return fmt.Errorf("[ERR] Error looking up Response Object for (%s), version (%v): %s", d.Id(), s.ActiveVersion.Number, err) } rol := flattenResponseObjects(responseObjectList) @@ -1786,7 +2045,7 @@ func resourceServiceV1Read(d *schema.ResourceData, meta interface{}) error { }) if err != nil { - return fmt.Errorf("[ERR] Error looking up Conditions for (%s), version (%s): %s", d.Id(), s.ActiveVersion.Number, err) + return fmt.Errorf("[ERR] Error looking up Conditions for (%s), version (%v): %s", d.Id(), s.ActiveVersion.Number, err) } cl := flattenConditions(conditionList) @@ -1803,7 +2062,7 @@ func resourceServiceV1Read(d *schema.ResourceData, meta interface{}) error { }) if err != nil { - return fmt.Errorf("[ERR] Error looking up Request Settings for (%s), version (%s): %s", d.Id(), s.ActiveVersion.Number, err) + return fmt.Errorf("[ERR] Error looking up Request Settings for (%s), version (%v): %s", d.Id(), s.ActiveVersion.Number, err) } rl := flattenRequestSettings(rsList) @@ -1819,7 +2078,7 @@ func resourceServiceV1Read(d *schema.ResourceData, meta interface{}) error { Version: s.ActiveVersion.Number, }) if err != nil { - return fmt.Errorf("[ERR] Error looking up VCLs for (%s), version (%s): %s", d.Id(), s.ActiveVersion.Number, err) + return fmt.Errorf("[ERR] Error looking up VCLs for (%s), version (%v): %s", d.Id(), s.ActiveVersion.Number, err) } vl := flattenVCLs(vclList) @@ -1835,7 +2094,7 @@ func resourceServiceV1Read(d *schema.ResourceData, meta interface{}) error { Version: s.ActiveVersion.Number, }) if err != nil { - return fmt.Errorf("[ERR] Error looking up Cache Settings for (%s), version (%s): %s", d.Id(), s.ActiveVersion.Number, err) + return fmt.Errorf("[ERR] Error looking up Cache Settings for (%s), version (%v): %s", d.Id(), s.ActiveVersion.Number, err) } csl := flattenCacheSettings(cslList) @@ -1866,7 +2125,7 @@ func resourceServiceV1Delete(d *schema.ResourceData, meta interface{}) error { return err } - if s.ActiveVersion.Number != "" { + if s.ActiveVersion.Number != 0 { _, err := conn.DeactivateVersion(&gofastly.DeactivateVersionInput{ Service: d.Id(), Version: s.ActiveVersion.Number, @@ -1936,6 +2195,7 @@ func flattenBackends(backendList []*gofastly.Backend) []map[string]interface{} { "ssl_sni_hostname": b.SSLSNIHostname, "weight": int(b.Weight), "request_condition": b.RequestCondition, + "healthcheck": b.HealthCheck, } bl = append(bl, nb) @@ -2179,7 +2439,7 @@ func flattenS3s(s3List []*gofastly.S3) []map[string]interface{} { func flattenPapertrails(papertrailList []*gofastly.Papertrail) []map[string]interface{} { var pl []map[string]interface{} for _, p := range papertrailList { - // Convert S3s to a map for saving to state. + // Convert Papertrails to a map for saving to state. ns := map[string]interface{}{ "name": p.Name, "address": p.Address, @@ -2201,6 +2461,61 @@ func flattenPapertrails(papertrailList []*gofastly.Papertrail) []map[string]inte return pl } +func flattenSumologics(sumologicList []*gofastly.Sumologic) []map[string]interface{} { + var l []map[string]interface{} + for _, p := range sumologicList { + // Convert Sumologic to a map for saving to state. + ns := map[string]interface{}{ + "name": p.Name, + "url": p.URL, + "format": p.Format, + "response_condition": p.ResponseCondition, + "message_type": p.MessageType, + "format_version": int(p.FormatVersion), + } + + // prune any empty values that come from the default string value in structs + for k, v := range ns { + if v == "" { + delete(ns, k) + } + } + + l = append(l, ns) + } + + return l +} + +func flattenGCS(gcsList []*gofastly.GCS) []map[string]interface{} { + var GCSList []map[string]interface{} + for _, currentGCS := range gcsList { + // Convert gcs to a map for saving to state. + GCSMapString := map[string]interface{}{ + "name": currentGCS.Name, + "email": currentGCS.User, + "bucket_name": currentGCS.Bucket, + "secret_key": currentGCS.SecretKey, + "path": currentGCS.Path, + "period": int(currentGCS.Period), + "gzip_level": int(currentGCS.GzipLevel), + "response_condition": currentGCS.ResponseCondition, + "format": currentGCS.Format, + } + + // prune any empty values that come from the default string value in structs + for k, v := range GCSMapString { + if v == "" { + delete(GCSMapString, k) + } + } + + GCSList = append(GCSList, GCSMapString) + } + + return GCSList +} + func flattenResponseObjects(responseObjectList []*gofastly.ResponseObject) []map[string]interface{} { var rol []map[string]interface{} for _, ro := range responseObjectList { diff --git a/builtin/providers/fastly/resource_fastly_service_v1_cache_setting_test.go b/builtin/providers/fastly/resource_fastly_service_v1_cache_setting_test.go index 194a55586..68b9dcee2 100644 --- a/builtin/providers/fastly/resource_fastly_service_v1_cache_setting_test.go +++ b/builtin/providers/fastly/resource_fastly_service_v1_cache_setting_test.go @@ -75,7 +75,7 @@ func testAccCheckFastlyServiceV1CacheSettingsAttributes(service *gofastly.Servic }) if err != nil { - return fmt.Errorf("[ERR] Error looking up Request Setting for (%s), version (%s): %s", service.Name, service.ActiveVersion.Number, err) + return fmt.Errorf("[ERR] Error looking up Request Setting for (%s), version (%v): %s", service.Name, service.ActiveVersion.Number, err) } if len(rqList) != len(rqs) { diff --git a/builtin/providers/fastly/resource_fastly_service_v1_conditionals_test.go b/builtin/providers/fastly/resource_fastly_service_v1_conditionals_test.go index ab64a20d9..0599b7a9c 100644 --- a/builtin/providers/fastly/resource_fastly_service_v1_conditionals_test.go +++ b/builtin/providers/fastly/resource_fastly_service_v1_conditionals_test.go @@ -57,7 +57,7 @@ func testAccCheckFastlyServiceV1ConditionalAttributes(service *gofastly.ServiceD }) if err != nil { - return fmt.Errorf("[ERR] Error looking up Conditions for (%s), version (%s): %s", service.Name, service.ActiveVersion.Number, err) + return fmt.Errorf("[ERR] Error looking up Conditions for (%s), version (%v): %s", service.Name, service.ActiveVersion.Number, err) } if len(conditionList) != len(conditions) { diff --git a/builtin/providers/fastly/resource_fastly_service_v1_gcslogging_test.go b/builtin/providers/fastly/resource_fastly_service_v1_gcslogging_test.go new file mode 100644 index 000000000..a16240f30 --- /dev/null +++ b/builtin/providers/fastly/resource_fastly_service_v1_gcslogging_test.go @@ -0,0 +1,131 @@ +package fastly + +import ( + "fmt" + "reflect" + "testing" + + "github.com/hashicorp/terraform/helper/acctest" + "github.com/hashicorp/terraform/helper/resource" + "github.com/hashicorp/terraform/terraform" + gofastly "github.com/sethvargo/go-fastly" +) + +func TestResourceFastlyFlattenGCS(t *testing.T) { + cases := []struct { + remote []*gofastly.GCS + local []map[string]interface{} + }{ + { + remote: []*gofastly.GCS{ + &gofastly.GCS{ + Name: "GCS collector", + User: "email@example.com", + Bucket: "bucketName", + SecretKey: "secretKey", + Format: "log format", + Period: 3600, + GzipLevel: 0, + }, + }, + local: []map[string]interface{}{ + map[string]interface{}{ + "name": "GCS collector", + "email": "email@example.com", + "bucket_name": "bucketName", + "secret_key": "secretKey", + "format": "log format", + "period": 3600, + "gzip_level": 0, + }, + }, + }, + } + + for _, c := range cases { + out := flattenGCS(c.remote) + if !reflect.DeepEqual(out, c.local) { + t.Fatalf("Error matching:\nexpected: %#v\ngot: %#v", c.local, out) + } + } +} + +func TestAccFastlyServiceV1_gcslogging(t *testing.T) { + var service gofastly.ServiceDetail + name := fmt.Sprintf("tf-test-%s", acctest.RandString(10)) + gcsName := fmt.Sprintf("gcs %s", acctest.RandString(10)) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckServiceV1Destroy, + Steps: []resource.TestStep{ + { + Config: testAccServiceV1Config_gcs(name, gcsName), + Check: resource.ComposeTestCheckFunc( + testAccCheckServiceV1Exists("fastly_service_v1.foo", &service), + testAccCheckFastlyServiceV1Attributes_gcs(&service, name, gcsName), + ), + }, + }, + }) +} + +func testAccCheckFastlyServiceV1Attributes_gcs(service *gofastly.ServiceDetail, name, gcsName string) resource.TestCheckFunc { + return func(s *terraform.State) error { + + if service.Name != name { + return fmt.Errorf("Bad name, expected (%s), got (%s)", name, service.Name) + } + + conn := testAccProvider.Meta().(*FastlyClient).conn + gcsList, err := conn.ListGCSs(&gofastly.ListGCSsInput{ + Service: service.ID, + Version: service.ActiveVersion.Number, + }) + + if err != nil { + return fmt.Errorf("[ERR] Error looking up GCSs for (%s), version (%v): %s", service.Name, service.ActiveVersion.Number, err) + } + + if len(gcsList) != 1 { + return fmt.Errorf("GCS missing, expected: 1, got: %d", len(gcsList)) + } + + if gcsList[0].Name != gcsName { + return fmt.Errorf("GCS name mismatch, expected: %s, got: %#v", gcsName, gcsList[0].Name) + } + + return nil + } +} + +func testAccServiceV1Config_gcs(name, gcsName string) string { + backendName := fmt.Sprintf("%s.aws.amazon.com", acctest.RandString(3)) + + return fmt.Sprintf(` +resource "fastly_service_v1" "foo" { + name = "%s" + + domain { + name = "test.notadomain.com" + comment = "tf-testing-domain" + } + + backend { + address = "%s" + name = "tf -test backend" + } + + gcslogging { + name = "%s" + email = "email@example.com", + bucket_name = "bucketName", + secret_key = "secretKey", + format = "log format", + response_condition = "", + } + + force_destroy = true +}`, name, backendName, gcsName) +} diff --git a/builtin/providers/fastly/resource_fastly_service_v1_gzip_test.go b/builtin/providers/fastly/resource_fastly_service_v1_gzip_test.go index 8c4e2be5a..91560d4e5 100644 --- a/builtin/providers/fastly/resource_fastly_service_v1_gzip_test.go +++ b/builtin/providers/fastly/resource_fastly_service_v1_gzip_test.go @@ -108,20 +108,20 @@ func TestAccFastlyServiceV1_gzips_basic(t *testing.T) { domainName1 := fmt.Sprintf("%s.notadomain.com", acctest.RandString(10)) log1 := gofastly.Gzip{ - Version: "1", + Version: 1, Name: "gzip file types", Extensions: "js css", CacheCondition: "testing_condition", } log2 := gofastly.Gzip{ - Version: "1", + Version: 1, Name: "gzip extensions", ContentTypes: "text/css text/html", } log3 := gofastly.Gzip{ - Version: "1", + Version: 1, Name: "all", Extensions: "js html css", ContentTypes: "text/javascript application/x-javascript application/javascript text/css text/html", @@ -169,7 +169,7 @@ func testAccCheckFastlyServiceV1GzipsAttributes(service *gofastly.ServiceDetail, }) if err != nil { - return fmt.Errorf("[ERR] Error looking up Gzips for (%s), version (%s): %s", service.Name, service.ActiveVersion.Number, err) + return fmt.Errorf("[ERR] Error looking up Gzips for (%s), version (%v): %s", service.Name, service.ActiveVersion.Number, err) } if len(gzipsList) != len(gzips) { diff --git a/builtin/providers/fastly/resource_fastly_service_v1_headers_test.go b/builtin/providers/fastly/resource_fastly_service_v1_headers_test.go index 3ad1e2879..8428c3fcb 100644 --- a/builtin/providers/fastly/resource_fastly_service_v1_headers_test.go +++ b/builtin/providers/fastly/resource_fastly_service_v1_headers_test.go @@ -81,7 +81,7 @@ func TestAccFastlyServiceV1_headers_basic(t *testing.T) { domainName1 := fmt.Sprintf("%s.notadomain.com", acctest.RandString(10)) log1 := gofastly.Header{ - Version: "1", + Version: 1, Name: "remove x-amz-request-id", Destination: "http.x-amz-request-id", Type: "cache", @@ -90,7 +90,7 @@ func TestAccFastlyServiceV1_headers_basic(t *testing.T) { } log2 := gofastly.Header{ - Version: "1", + Version: 1, Name: "remove s3 server", Destination: "http.Server", Type: "cache", @@ -100,7 +100,7 @@ func TestAccFastlyServiceV1_headers_basic(t *testing.T) { } log3 := gofastly.Header{ - Version: "1", + Version: 1, Name: "DESTROY S3", Destination: "http.Server", Type: "cache", @@ -109,7 +109,7 @@ func TestAccFastlyServiceV1_headers_basic(t *testing.T) { } log4 := gofastly.Header{ - Version: "1", + Version: 1, Name: "Add server name", Destination: "http.server-name", Type: "request", @@ -163,7 +163,7 @@ func testAccCheckFastlyServiceV1HeaderAttributes(service *gofastly.ServiceDetail }) if err != nil { - return fmt.Errorf("[ERR] Error looking up Headers for (%s), version (%s): %s", service.Name, service.ActiveVersion.Number, err) + return fmt.Errorf("[ERR] Error looking up Headers for (%s), version (%v): %s", service.Name, service.ActiveVersion.Number, err) } if len(headersList) != len(headers) { diff --git a/builtin/providers/fastly/resource_fastly_service_v1_healthcheck_test.go b/builtin/providers/fastly/resource_fastly_service_v1_healthcheck_test.go index 04ee8dd25..c456aa958 100644 --- a/builtin/providers/fastly/resource_fastly_service_v1_healthcheck_test.go +++ b/builtin/providers/fastly/resource_fastly_service_v1_healthcheck_test.go @@ -17,7 +17,7 @@ func TestAccFastlyServiceV1_healthcheck_basic(t *testing.T) { domainName := fmt.Sprintf("%s.notadomain.com", acctest.RandString(10)) log1 := gofastly.HealthCheck{ - Version: "1", + Version: 1, Name: "example-healthcheck1", Host: "example1.com", Path: "/test1.txt", @@ -32,7 +32,7 @@ func TestAccFastlyServiceV1_healthcheck_basic(t *testing.T) { } log2 := gofastly.HealthCheck{ - Version: "1", + Version: 1, Name: "example-healthcheck2", Host: "example2.com", Path: "/test2.txt", @@ -88,7 +88,7 @@ func testAccCheckFastlyServiceV1HealthCheckAttributes(service *gofastly.ServiceD }) if err != nil { - return fmt.Errorf("[ERR] Error looking up Healthcheck for (%s), version (%s): %s", service.Name, service.ActiveVersion.Number, err) + return fmt.Errorf("[ERR] Error looking up Healthcheck for (%s), version (%v): %s", service.Name, service.ActiveVersion.Number, err) } if len(healthcheckList) != len(healthchecks) { diff --git a/builtin/providers/fastly/resource_fastly_service_v1_papertrail_test.go b/builtin/providers/fastly/resource_fastly_service_v1_papertrail_test.go index 69500f258..2e2fcac3d 100644 --- a/builtin/providers/fastly/resource_fastly_service_v1_papertrail_test.go +++ b/builtin/providers/fastly/resource_fastly_service_v1_papertrail_test.go @@ -17,7 +17,7 @@ func TestAccFastlyServiceV1_papertrail_basic(t *testing.T) { domainName1 := fmt.Sprintf("%s.notadomain.com", acctest.RandString(10)) log1 := gofastly.Papertrail{ - Version: "1", + Version: 1, Name: "papertrailtesting", Address: "test1.papertrailapp.com", Port: uint(3600), @@ -26,7 +26,7 @@ func TestAccFastlyServiceV1_papertrail_basic(t *testing.T) { } log2 := gofastly.Papertrail{ - Version: "1", + Version: 1, Name: "papertrailtesting2", Address: "test2.papertrailapp.com", Port: uint(8080), @@ -75,7 +75,7 @@ func testAccCheckFastlyServiceV1PapertrailAttributes(service *gofastly.ServiceDe }) if err != nil { - return fmt.Errorf("[ERR] Error looking up Papertrail for (%s), version (%s): %s", service.Name, service.ActiveVersion.Number, err) + return fmt.Errorf("[ERR] Error looking up Papertrail for (%s), version (%v): %s", service.Name, service.ActiveVersion.Number, err) } if len(papertrailList) != len(papertrails) { diff --git a/builtin/providers/fastly/resource_fastly_service_v1_request_setting_test.go b/builtin/providers/fastly/resource_fastly_service_v1_request_setting_test.go index 3c095c5c7..72d1c3e81 100644 --- a/builtin/providers/fastly/resource_fastly_service_v1_request_setting_test.go +++ b/builtin/providers/fastly/resource_fastly_service_v1_request_setting_test.go @@ -56,7 +56,7 @@ func testAccCheckFastlyServiceV1RequestSettingsAttributes(service *gofastly.Serv }) if err != nil { - return fmt.Errorf("[ERR] Error looking up Request Setting for (%s), version (%s): %s", service.Name, service.ActiveVersion.Number, err) + return fmt.Errorf("[ERR] Error looking up Request Setting for (%s), version (%v): %s", service.Name, service.ActiveVersion.Number, err) } if len(rqList) != len(rqs) { diff --git a/builtin/providers/fastly/resource_fastly_service_v1_response_object_test.go b/builtin/providers/fastly/resource_fastly_service_v1_response_object_test.go index 330cde8d8..e4a2e02b2 100644 --- a/builtin/providers/fastly/resource_fastly_service_v1_response_object_test.go +++ b/builtin/providers/fastly/resource_fastly_service_v1_response_object_test.go @@ -17,7 +17,7 @@ func TestAccFastlyServiceV1_response_object_basic(t *testing.T) { domainName1 := fmt.Sprintf("%s.notadomain.com", acctest.RandString(10)) log1 := gofastly.ResponseObject{ - Version: "1", + Version: 1, Name: "responseObjecttesting", Status: 200, Response: "OK", @@ -28,7 +28,7 @@ func TestAccFastlyServiceV1_response_object_basic(t *testing.T) { } log2 := gofastly.ResponseObject{ - Version: "1", + Version: 1, Name: "responseObjecttesting2", Status: 404, Response: "Not Found", @@ -80,7 +80,7 @@ func testAccCheckFastlyServiceV1ResponseObjectAttributes(service *gofastly.Servi }) if err != nil { - return fmt.Errorf("[ERR] Error looking up Response Object for (%s), version (%s): %s", service.Name, service.ActiveVersion.Number, err) + return fmt.Errorf("[ERR] Error looking up Response Object for (%s), version (%v): %s", service.Name, service.ActiveVersion.Number, err) } if len(responseObjectList) != len(responseObjects) { diff --git a/builtin/providers/fastly/resource_fastly_service_v1_s3logging_test.go b/builtin/providers/fastly/resource_fastly_service_v1_s3logging_test.go index 68a91983f..651eceac3 100644 --- a/builtin/providers/fastly/resource_fastly_service_v1_s3logging_test.go +++ b/builtin/providers/fastly/resource_fastly_service_v1_s3logging_test.go @@ -18,7 +18,7 @@ func TestAccFastlyServiceV1_s3logging_basic(t *testing.T) { domainName1 := fmt.Sprintf("%s.notadomain.com", acctest.RandString(10)) log1 := gofastly.S3{ - Version: "1", + Version: 1, Name: "somebucketlog", BucketName: "fastlytestlogging", Domain: "s3-us-west-2.amazonaws.com", @@ -33,7 +33,7 @@ func TestAccFastlyServiceV1_s3logging_basic(t *testing.T) { } log2 := gofastly.S3{ - Version: "1", + Version: 1, Name: "someotherbucketlog", BucketName: "fastlytestlogging2", Domain: "s3-us-west-2.amazonaws.com", @@ -89,7 +89,7 @@ func TestAccFastlyServiceV1_s3logging_s3_env(t *testing.T) { defer resetEnv() log3 := gofastly.S3{ - Version: "1", + Version: 1, Name: "somebucketlog", BucketName: "fastlytestlogging", Domain: "s3-us-west-2.amazonaws.com", @@ -128,7 +128,7 @@ func TestAccFastlyServiceV1_s3logging_formatVersion(t *testing.T) { domainName1 := fmt.Sprintf("%s.notadomain.com", acctest.RandString(10)) log1 := gofastly.S3{ - Version: "1", + Version: 1, Name: "somebucketlog", BucketName: "fastlytestlogging", Domain: "s3-us-west-2.amazonaws.com", @@ -171,7 +171,7 @@ func testAccCheckFastlyServiceV1S3LoggingAttributes(service *gofastly.ServiceDet }) if err != nil { - return fmt.Errorf("[ERR] Error looking up S3 Logging for (%s), version (%s): %s", service.Name, service.ActiveVersion.Number, err) + return fmt.Errorf("[ERR] Error looking up S3 Logging for (%s), version (%v): %s", service.Name, service.ActiveVersion.Number, err) } if len(s3List) != len(s3s) { diff --git a/builtin/providers/fastly/resource_fastly_service_v1_sumologic_test.go b/builtin/providers/fastly/resource_fastly_service_v1_sumologic_test.go new file mode 100644 index 000000000..ca7aabae9 --- /dev/null +++ b/builtin/providers/fastly/resource_fastly_service_v1_sumologic_test.go @@ -0,0 +1,126 @@ +package fastly + +import ( + "fmt" + "reflect" + "testing" + + "github.com/hashicorp/terraform/helper/acctest" + "github.com/hashicorp/terraform/helper/resource" + "github.com/hashicorp/terraform/terraform" + gofastly "github.com/sethvargo/go-fastly" +) + +func TestResourceFastlyFlattenSumologic(t *testing.T) { + cases := []struct { + remote []*gofastly.Sumologic + local []map[string]interface{} + }{ + { + remote: []*gofastly.Sumologic{ + &gofastly.Sumologic{ + Name: "sumo collector", + URL: "https://sumologic.com/collector/1", + Format: "log format", + FormatVersion: 2, + MessageType: "classic", + ResponseCondition: "condition 1", + }, + }, + local: []map[string]interface{}{ + map[string]interface{}{ + "name": "sumo collector", + "url": "https://sumologic.com/collector/1", + "format": "log format", + "format_version": 2, + "message_type": "classic", + "response_condition": "condition 1", + }, + }, + }, + } + + for _, c := range cases { + out := flattenSumologics(c.remote) + if !reflect.DeepEqual(out, c.local) { + t.Fatalf("Error matching:\nexpected: %#v\ngot: %#v", c.local, out) + } + } +} + +func TestAccFastlyServiceV1_sumologic(t *testing.T) { + var service gofastly.ServiceDetail + name := fmt.Sprintf("tf-test-%s", acctest.RandString(10)) + sumologicName := fmt.Sprintf("sumologic %s", acctest.RandString(3)) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckServiceV1Destroy, + Steps: []resource.TestStep{ + resource.TestStep{ + Config: testAccServiceV1Config_sumologic(name, sumologicName), + Check: resource.ComposeTestCheckFunc( + testAccCheckServiceV1Exists("fastly_service_v1.foo", &service), + testAccCheckFastlyServiceV1Attributes_sumologic(&service, name, sumologicName), + ), + }, + }, + }) +} + +func testAccCheckFastlyServiceV1Attributes_sumologic(service *gofastly.ServiceDetail, name, sumologic string) resource.TestCheckFunc { + return func(s *terraform.State) error { + + if service.Name != name { + return fmt.Errorf("Bad name, expected (%s), got (%s)", name, service.Name) + } + + conn := testAccProvider.Meta().(*FastlyClient).conn + sumologicList, err := conn.ListSumologics(&gofastly.ListSumologicsInput{ + Service: service.ID, + Version: service.ActiveVersion.Number, + }) + + if err != nil { + return fmt.Errorf("[ERR] Error looking up Sumologics for (%s), version (%v): %s", service.Name, service.ActiveVersion.Number, err) + } + + if len(sumologicList) != 1 { + return fmt.Errorf("Sumologic missing, expected: 1, got: %d", len(sumologicList)) + } + + if sumologicList[0].Name != sumologic { + return fmt.Errorf("Sumologic name mismatch, expected: %s, got: %#v", sumologic, sumologicList[0].Name) + } + + return nil + } +} + +func testAccServiceV1Config_sumologic(name, sumologic string) string { + backendName := fmt.Sprintf("%s.aws.amazon.com", acctest.RandString(3)) + + return fmt.Sprintf(` +resource "fastly_service_v1" "foo" { + name = "%s" + + domain { + name = "test.notadomain.com" + comment = "tf-testing-domain" + } + + backend { + address = "%s" + name = "tf -test backend" + } + + sumologic { + name = "%s" + url = "https://sumologic.com/collector/1" + format_version = 2 + } + + force_destroy = true +}`, name, backendName, sumologic) +} diff --git a/builtin/providers/fastly/resource_fastly_service_v1_test.go b/builtin/providers/fastly/resource_fastly_service_v1_test.go index ba6ca5592..e4c853057 100644 --- a/builtin/providers/fastly/resource_fastly_service_v1_test.go +++ b/builtin/providers/fastly/resource_fastly_service_v1_test.go @@ -71,6 +71,7 @@ func TestResourceFastlyFlattenBackend(t *testing.T) { FirstByteTimeout: uint(15000), MaxConn: uint(200), RequestCondition: "", + HealthCheck: "", SSLCheckCert: true, SSLHostname: "", SSLCertHostname: "", @@ -91,6 +92,7 @@ func TestResourceFastlyFlattenBackend(t *testing.T) { "first_byte_timeout": 15000, "max_conn": 200, "request_condition": "", + "healthcheck": "", "ssl_check_cert": true, "ssl_hostname": "", "ssl_cert_hostname": "", @@ -173,7 +175,7 @@ func TestAccFastlyServiceV1_updateBackend(t *testing.T) { }, resource.TestStep{ - Config: testAccServiceV1Config_backend_update(name, backendName, backendName2), + Config: testAccServiceV1Config_backend_update(name, backendName, backendName2, 3400), Check: resource.ComposeTestCheckFunc( testAccCheckServiceV1Exists("fastly_service_v1.foo", &service), testAccCheckFastlyServiceV1Attributes_backends(&service, name, []string{backendName, backendName2}), @@ -303,7 +305,7 @@ func testAccCheckFastlyServiceV1Attributes(service *gofastly.ServiceDetail, name }) if err != nil { - return fmt.Errorf("[ERR] Error looking up Domains for (%s), version (%s): %s", service.Name, service.ActiveVersion.Number, err) + return fmt.Errorf("[ERR] Error looking up Domains for (%s), version (%v): %s", service.Name, service.ActiveVersion.Number, err) } expected := len(domains) @@ -337,7 +339,7 @@ func testAccCheckFastlyServiceV1Attributes_backends(service *gofastly.ServiceDet }) if err != nil { - return fmt.Errorf("[ERR] Error looking up Backends for (%s), version (%s): %s", service.Name, service.ActiveVersion.Number, err) + return fmt.Errorf("[ERR] Error looking up Backends for (%s), version (%v): %s", service.Name, service.ActiveVersion.Number, err) } expected := len(backendList) @@ -357,6 +359,52 @@ func testAccCheckFastlyServiceV1Attributes_backends(service *gofastly.ServiceDet } } +func TestAccFastlyServiceV1_defaultTTL(t *testing.T) { + var service gofastly.ServiceDetail + name := fmt.Sprintf("tf-test-%s", acctest.RandString(10)) + backendName := fmt.Sprintf("%s.aws.amazon.com", acctest.RandString(3)) + backendName2 := fmt.Sprintf("%s.aws.amazon.com", acctest.RandString(3)) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckServiceV1Destroy, + Steps: []resource.TestStep{ + resource.TestStep{ + Config: testAccServiceV1Config_backend(name, backendName), + Check: resource.ComposeTestCheckFunc( + testAccCheckServiceV1Exists("fastly_service_v1.foo", &service), + testAccCheckFastlyServiceV1Attributes_backends(&service, name, []string{backendName}), + ), + }, + + resource.TestStep{ + Config: testAccServiceV1Config_backend_update(name, backendName, backendName2, 3400), + Check: resource.ComposeTestCheckFunc( + testAccCheckServiceV1Exists("fastly_service_v1.foo", &service), + testAccCheckFastlyServiceV1Attributes_backends(&service, name, []string{backendName, backendName2}), + resource.TestCheckResourceAttr( + "fastly_service_v1.foo", "default_ttl", "3400"), + resource.TestCheckResourceAttr( + "fastly_service_v1.foo", "active_version", "2"), + ), + }, + // Now update the default_ttl to 0 and encounter the issue https://github.com/hashicorp/terraform/issues/12910 + resource.TestStep{ + Config: testAccServiceV1Config_backend_update(name, backendName, backendName2, 0), + Check: resource.ComposeTestCheckFunc( + testAccCheckServiceV1Exists("fastly_service_v1.foo", &service), + testAccCheckFastlyServiceV1Attributes_backends(&service, name, []string{backendName, backendName2}), + resource.TestCheckResourceAttr( + "fastly_service_v1.foo", "default_ttl", "0"), + resource.TestCheckResourceAttr( + "fastly_service_v1.foo", "active_version", "3"), + ), + }, + }, + }) +} + func testAccCheckServiceV1Destroy(s *terraform.State) error { for _, rs := range s.RootModule().Resources { if rs.Type != "fastly_service_v1" { @@ -441,12 +489,12 @@ resource "fastly_service_v1" "foo" { }`, name, backend) } -func testAccServiceV1Config_backend_update(name, backend, backend2 string) string { +func testAccServiceV1Config_backend_update(name, backend, backend2 string, ttl uint) string { return fmt.Sprintf(` resource "fastly_service_v1" "foo" { name = "%s" - default_ttl = 3400 + default_ttl = %d domain { name = "test.notadomain.com" @@ -464,5 +512,5 @@ resource "fastly_service_v1" "foo" { } force_destroy = true -}`, name, backend, backend2) +}`, name, ttl, backend, backend2) } diff --git a/builtin/providers/fastly/resource_fastly_service_v1_vcl_test.go b/builtin/providers/fastly/resource_fastly_service_v1_vcl_test.go index c95a0f2d0..621e6d1da 100644 --- a/builtin/providers/fastly/resource_fastly_service_v1_vcl_test.go +++ b/builtin/providers/fastly/resource_fastly_service_v1_vcl_test.go @@ -61,7 +61,7 @@ func testAccCheckFastlyServiceV1VCLAttributes(service *gofastly.ServiceDetail, n }) if err != nil { - return fmt.Errorf("[ERR] Error looking up VCL for (%s), version (%s): %s", service.Name, service.ActiveVersion.Number, err) + return fmt.Errorf("[ERR] Error looking up VCL for (%s), version (%v): %s", service.Name, service.ActiveVersion.Number, err) } if len(vclList) != vclCount { diff --git a/builtin/providers/fastly/validators.go b/builtin/providers/fastly/validators.go index 1f2fb22d4..1903d8daf 100644 --- a/builtin/providers/fastly/validators.go +++ b/builtin/providers/fastly/validators.go @@ -2,7 +2,7 @@ package fastly import "fmt" -func validateS3FormatVersion(v interface{}, k string) (ws []string, errors []error) { +func validateLoggingFormatVersion(v interface{}, k string) (ws []string, errors []error) { value := uint(v.(int)) validVersions := map[uint]struct{}{ 1: {}, @@ -15,3 +15,19 @@ func validateS3FormatVersion(v interface{}, k string) (ws []string, errors []err } return } + +func validateLoggingMessageType(v interface{}, k string) (ws []string, errors []error) { + value := v.(string) + validTypes := map[string]struct{}{ + "classic": {}, + "loggly": {}, + "logplex": {}, + "blank": {}, + } + + if _, ok := validTypes[value]; !ok { + errors = append(errors, fmt.Errorf( + "%q must be one of ['classic', 'loggly', 'logplex', 'blank']", k)) + } + return +} diff --git a/builtin/providers/fastly/validators_test.go b/builtin/providers/fastly/validators_test.go index d563c7f5d..9ec1a4e8e 100644 --- a/builtin/providers/fastly/validators_test.go +++ b/builtin/providers/fastly/validators_test.go @@ -2,13 +2,13 @@ package fastly import "testing" -func TestValidateS3FormatVersion(t *testing.T) { +func TestValidateLoggingFormatVersion(t *testing.T) { validVersions := []int{ 1, 2, } for _, v := range validVersions { - _, errors := validateS3FormatVersion(v, "format_version") + _, errors := validateLoggingFormatVersion(v, "format_version") if len(errors) != 0 { t.Fatalf("%q should be a valid format version: %q", v, errors) } @@ -21,9 +21,35 @@ func TestValidateS3FormatVersion(t *testing.T) { 5, } for _, v := range invalidVersions { - _, errors := validateS3FormatVersion(v, "format_version") + _, errors := validateLoggingFormatVersion(v, "format_version") if len(errors) != 1 { t.Fatalf("%q should not be a valid format version", v) } } } + +func TestValidateLoggingMessageType(t *testing.T) { + validTypes := []string{ + "classic", + "loggly", + "logplex", + "blank", + } + for _, v := range validTypes { + _, errors := validateLoggingMessageType(v, "message_type") + if len(errors) != 0 { + t.Fatalf("%q should be a valid message type: %q", v, errors) + } + } + + invalidTypes := []string{ + "invalid_type_1", + "invalid_type_2", + } + for _, v := range invalidTypes { + _, errors := validateLoggingMessageType(v, "message_type") + if len(errors) != 1 { + t.Fatalf("%q should not be a valid message type", v) + } + } +} diff --git a/builtin/providers/github/config.go b/builtin/providers/github/config.go index 8cd0f4ee7..8372d4aec 100644 --- a/builtin/providers/github/config.go +++ b/builtin/providers/github/config.go @@ -4,6 +4,7 @@ import ( "net/url" "github.com/google/go-github/github" + "github.com/hashicorp/terraform/helper/logging" "golang.org/x/oauth2" ) @@ -27,6 +28,8 @@ func (c *Config) Client() (interface{}, error) { ) tc := oauth2.NewClient(oauth2.NoContext, ts) + tc.Transport = logging.NewTransport("Github", tc.Transport) + org.client = github.NewClient(tc) if c.BaseURL != "" { u, err := url.Parse(c.BaseURL) @@ -35,5 +38,6 @@ func (c *Config) Client() (interface{}, error) { } org.client.BaseURL = u } + return &org, nil } diff --git a/builtin/providers/github/provider.go b/builtin/providers/github/provider.go index b3fd81d51..4b5e11107 100644 --- a/builtin/providers/github/provider.go +++ b/builtin/providers/github/provider.go @@ -41,6 +41,7 @@ func Provider() terraform.ResourceProvider { "github_organization_webhook": resourceGithubOrganizationWebhook(), "github_repository_collaborator": resourceGithubRepositoryCollaborator(), "github_issue_label": resourceGithubIssueLabel(), + "github_branch_protection": resourceGithubBranchProtection(), }, ConfigureFunc: providerConfigure, diff --git a/builtin/providers/github/provider_test.go b/builtin/providers/github/provider_test.go index b227d5271..79924badf 100644 --- a/builtin/providers/github/provider_test.go +++ b/builtin/providers/github/provider_test.go @@ -8,8 +8,6 @@ import ( "github.com/hashicorp/terraform/terraform" ) -const testRepo string = "test-repo" - var testUser string = os.Getenv("GITHUB_TEST_USER") var testCollaborator string = os.Getenv("GITHUB_TEST_COLLABORATOR") diff --git a/builtin/providers/github/resource_github_branch_protection.go b/builtin/providers/github/resource_github_branch_protection.go new file mode 100644 index 000000000..203283576 --- /dev/null +++ b/builtin/providers/github/resource_github_branch_protection.go @@ -0,0 +1,283 @@ +package github + +import ( + "context" + "errors" + "net/http" + + "github.com/google/go-github/github" + "github.com/hashicorp/terraform/helper/schema" +) + +func resourceGithubBranchProtection() *schema.Resource { + return &schema.Resource{ + Create: resourceGithubBranchProtectionCreate, + Read: resourceGithubBranchProtectionRead, + Update: resourceGithubBranchProtectionUpdate, + Delete: resourceGithubBranchProtectionDelete, + Importer: &schema.ResourceImporter{ + State: schema.ImportStatePassthrough, + }, + + Schema: map[string]*schema.Schema{ + "repository": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + "branch": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + "required_status_checks": { + Type: schema.TypeList, + Optional: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "include_admins": { + Type: schema.TypeBool, + Optional: true, + Default: false, + }, + "strict": { + Type: schema.TypeBool, + Optional: true, + Default: false, + }, + "contexts": { + Type: schema.TypeList, + Optional: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + }, + }, + }, + "required_pull_request_reviews": { + Type: schema.TypeList, + Optional: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "include_admins": { + Type: schema.TypeBool, + Optional: true, + Default: false, + }, + }, + }, + }, + "restrictions": { + Type: schema.TypeList, + Optional: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "users": { + Type: schema.TypeList, + Optional: true, + Elem: &schema.Schema{Type: schema.TypeString}, + }, + "teams": { + Type: schema.TypeList, + Optional: true, + Elem: &schema.Schema{Type: schema.TypeString}, + }, + }, + }, + }, + }, + } +} + +func resourceGithubBranchProtectionCreate(d *schema.ResourceData, meta interface{}) error { + client := meta.(*Organization).client + r := d.Get("repository").(string) + b := d.Get("branch").(string) + + protectionRequest, err := buildProtectionRequest(d) + if err != nil { + return err + } + + _, _, err = client.Repositories.UpdateBranchProtection(context.TODO(), meta.(*Organization).name, r, b, protectionRequest) + if err != nil { + return err + } + d.SetId(buildTwoPartID(&r, &b)) + + return resourceGithubBranchProtectionRead(d, meta) +} + +func resourceGithubBranchProtectionRead(d *schema.ResourceData, meta interface{}) error { + client := meta.(*Organization).client + r, b := parseTwoPartID(d.Id()) + + githubProtection, _, err := client.Repositories.GetBranchProtection(context.TODO(), meta.(*Organization).name, r, b) + if err != nil { + if err, ok := err.(*github.ErrorResponse); ok && err.Response.StatusCode == http.StatusNotFound { + d.SetId("") + return nil + } + + return err + } + + d.Set("repository", r) + d.Set("branch", b) + + rsc := githubProtection.RequiredStatusChecks + if rsc != nil { + d.Set("required_status_checks", []interface{}{ + map[string]interface{}{ + "include_admins": rsc.IncludeAdmins, + "strict": rsc.Strict, + "contexts": rsc.Contexts, + }, + }) + } else { + d.Set("required_status_checks", []interface{}{}) + } + + rprr := githubProtection.RequiredPullRequestReviews + if rprr != nil { + d.Set("required_pull_request_reviews", []interface{}{ + map[string]interface{}{ + "include_admins": rprr.IncludeAdmins, + }, + }) + } else { + d.Set("required_pull_request_reviews", []interface{}{}) + } + + restrictions := githubProtection.Restrictions + if restrictions != nil { + var userLogins []string + for _, u := range restrictions.Users { + if u.Login != nil { + userLogins = append(userLogins, *u.Login) + } + } + var teamSlugs []string + for _, t := range restrictions.Teams { + if t.Slug != nil { + teamSlugs = append(teamSlugs, *t.Slug) + } + } + + d.Set("restrictions", []interface{}{ + map[string]interface{}{ + "users": userLogins, + "teams": teamSlugs, + }, + }) + } else { + d.Set("restrictions", []interface{}{}) + } + + return nil +} + +func resourceGithubBranchProtectionUpdate(d *schema.ResourceData, meta interface{}) error { + client := meta.(*Organization).client + r, b := parseTwoPartID(d.Id()) + + protectionRequest, err := buildProtectionRequest(d) + if err != nil { + return err + } + + _, _, err = client.Repositories.UpdateBranchProtection(context.TODO(), meta.(*Organization).name, r, b, protectionRequest) + if err != nil { + return err + } + d.SetId(buildTwoPartID(&r, &b)) + + return resourceGithubBranchProtectionRead(d, meta) +} + +func resourceGithubBranchProtectionDelete(d *schema.ResourceData, meta interface{}) error { + client := meta.(*Organization).client + r, b := parseTwoPartID(d.Id()) + + _, err := client.Repositories.RemoveBranchProtection(context.TODO(), meta.(*Organization).name, r, b) + return err +} + +func buildProtectionRequest(d *schema.ResourceData) (*github.ProtectionRequest, error) { + protectionRequest := new(github.ProtectionRequest) + + if v, ok := d.GetOk("required_status_checks"); ok { + vL := v.([]interface{}) + if len(vL) > 1 { + return nil, errors.New("cannot specify required_status_checks more than one time") + } + + for _, v := range vL { + m := v.(map[string]interface{}) + + rsc := new(github.RequiredStatusChecks) + rsc.IncludeAdmins = m["include_admins"].(bool) + rsc.Strict = m["strict"].(bool) + + rsc.Contexts = []string{} + if contexts, ok := m["contexts"].([]interface{}); ok { + for _, c := range contexts { + rsc.Contexts = append(rsc.Contexts, c.(string)) + } + } + + protectionRequest.RequiredStatusChecks = rsc + } + } + + if v, ok := d.GetOk("required_pull_request_reviews"); ok { + vL := v.([]interface{}) + if len(vL) > 1 { + return nil, errors.New("cannot specify required_pull_request_reviews more than one time") + } + + for _, v := range vL { + m := v.(map[string]interface{}) + + rprr := new(github.RequiredPullRequestReviews) + rprr.IncludeAdmins = m["include_admins"].(bool) + + protectionRequest.RequiredPullRequestReviews = rprr + } + } + + if v, ok := d.GetOk("restrictions"); ok { + vL := v.([]interface{}) + if len(vL) > 1 { + return nil, errors.New("cannot specify restrictions more than one time") + } + + for _, v := range vL { + m := v.(map[string]interface{}) + + restrictions := new(github.BranchRestrictionsRequest) + + restrictions.Users = []string{} + if users, ok := m["users"].([]interface{}); ok { + for _, u := range users { + restrictions.Users = append(restrictions.Users, u.(string)) + } + } + + restrictions.Teams = []string{} + if teams, ok := m["teams"].([]interface{}); ok { + for _, t := range teams { + restrictions.Teams = append(restrictions.Teams, t.(string)) + } + } + + protectionRequest.Restrictions = restrictions + } + } + + return protectionRequest, nil +} diff --git a/builtin/providers/github/resource_github_branch_protection_test.go b/builtin/providers/github/resource_github_branch_protection_test.go new file mode 100644 index 000000000..89f4a7bff --- /dev/null +++ b/builtin/providers/github/resource_github_branch_protection_test.go @@ -0,0 +1,242 @@ +package github + +import ( + "context" + "fmt" + "reflect" + "testing" + + "github.com/google/go-github/github" + "github.com/hashicorp/terraform/helper/acctest" + "github.com/hashicorp/terraform/helper/resource" + "github.com/hashicorp/terraform/terraform" +) + +func TestAccGithubBranchProtection_basic(t *testing.T) { + var protection github.Protection + + rString := acctest.RandString(5) + repoName := fmt.Sprintf("tf-acc-test-branch-prot-%s", rString) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccGithubBranchProtectionDestroy, + Steps: []resource.TestStep{ + { + Config: testAccGithubBranchProtectionConfig(repoName), + Check: resource.ComposeTestCheckFunc( + testAccCheckGithubProtectedBranchExists("github_branch_protection.master", repoName+":master", &protection), + testAccCheckGithubBranchProtectionRequiredStatusChecks(&protection, true, true, []string{"github/foo"}), + testAccCheckGithubBranchProtectionRestrictions(&protection, []string{testUser}, []string{}), + resource.TestCheckResourceAttr("github_branch_protection.master", "repository", repoName), + resource.TestCheckResourceAttr("github_branch_protection.master", "branch", "master"), + resource.TestCheckResourceAttr("github_branch_protection.master", "required_status_checks.0.include_admins", "true"), + resource.TestCheckResourceAttr("github_branch_protection.master", "required_status_checks.0.strict", "true"), + resource.TestCheckResourceAttr("github_branch_protection.master", "required_status_checks.0.contexts.#", "1"), + resource.TestCheckResourceAttr("github_branch_protection.master", "required_status_checks.0.contexts.0", "github/foo"), + resource.TestCheckResourceAttr("github_branch_protection.master", "required_pull_request_reviews.0.include_admins", "true"), + resource.TestCheckResourceAttr("github_branch_protection.master", "restrictions.0.users.#", "1"), + resource.TestCheckResourceAttr("github_branch_protection.master", "restrictions.0.users.0", testUser), + resource.TestCheckResourceAttr("github_branch_protection.master", "restrictions.0.teams.#", "0"), + ), + }, + { + Config: testAccGithubBranchProtectionUpdateConfig(repoName), + Check: resource.ComposeTestCheckFunc( + testAccCheckGithubProtectedBranchExists("github_branch_protection.master", repoName+":master", &protection), + testAccCheckGithubBranchProtectionRequiredStatusChecks(&protection, false, false, []string{"github/bar"}), + testAccCheckGithubBranchProtectionNoRestrictionsExist(&protection), + resource.TestCheckResourceAttr("github_branch_protection.master", "repository", repoName), + resource.TestCheckResourceAttr("github_branch_protection.master", "branch", "master"), + resource.TestCheckResourceAttr("github_branch_protection.master", "required_status_checks.0.include_admins", "false"), + resource.TestCheckResourceAttr("github_branch_protection.master", "required_status_checks.0.strict", "false"), + resource.TestCheckResourceAttr("github_branch_protection.master", "required_status_checks.0.contexts.#", "1"), + resource.TestCheckResourceAttr("github_branch_protection.master", "required_status_checks.0.contexts.0", "github/bar"), + resource.TestCheckResourceAttr("github_branch_protection.master", "required_pull_request_reviews.#", "0"), + resource.TestCheckResourceAttr("github_branch_protection.master", "restrictions.#", "0"), + ), + }, + }, + }) +} + +func TestAccGithubBranchProtection_importBasic(t *testing.T) { + rString := acctest.RandString(5) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccGithubBranchProtectionDestroy, + Steps: []resource.TestStep{ + { + Config: testAccGithubBranchProtectionConfig(rString), + }, + { + ResourceName: "github_branch_protection.master", + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func testAccCheckGithubProtectedBranchExists(n, id string, protection *github.Protection) resource.TestCheckFunc { + return func(s *terraform.State) error { + rs, ok := s.RootModule().Resources[n] + if !ok { + return fmt.Errorf("Not Found: %s", n) + } + + if rs.Primary.ID != id { + return fmt.Errorf("Expected ID to be %v, got %v", id, rs.Primary.ID) + } + + conn := testAccProvider.Meta().(*Organization).client + o := testAccProvider.Meta().(*Organization).name + r, b := parseTwoPartID(rs.Primary.ID) + + githubProtection, _, err := conn.Repositories.GetBranchProtection(context.TODO(), o, r, b) + if err != nil { + return err + } + + *protection = *githubProtection + return nil + } +} + +func testAccCheckGithubBranchProtectionRequiredStatusChecks(protection *github.Protection, expectedIncludeAdmins bool, expectedStrict bool, expectedContexts []string) resource.TestCheckFunc { + return func(s *terraform.State) error { + rsc := protection.RequiredStatusChecks + if rsc == nil { + return fmt.Errorf("Expected RequiredStatusChecks to be present, but was nil") + } + + if rsc.IncludeAdmins != expectedIncludeAdmins { + return fmt.Errorf("Expected RequiredStatusChecks.IncludeAdmins to be %v, got %v", expectedIncludeAdmins, rsc.IncludeAdmins) + } + if rsc.Strict != expectedStrict { + return fmt.Errorf("Expected RequiredStatusChecks.Strict to be %v, got %v", expectedStrict, rsc.Strict) + } + + if !reflect.DeepEqual(rsc.Contexts, expectedContexts) { + return fmt.Errorf("Expected RequiredStatusChecks.Contexts to be %v, got %v", expectedContexts, rsc.Contexts) + } + + return nil + } +} + +func testAccCheckGithubBranchProtectionRestrictions(protection *github.Protection, expectedUserLogins []string, expectedTeamNames []string) resource.TestCheckFunc { + return func(s *terraform.State) error { + restrictions := protection.Restrictions + if restrictions == nil { + return fmt.Errorf("Expected Restrictions to be present, but was nil") + } + + userLogins := []string{} + for _, u := range restrictions.Users { + userLogins = append(userLogins, *u.Login) + } + if !reflect.DeepEqual(userLogins, expectedUserLogins) { + return fmt.Errorf("Expected Restrictions.Users to be %v, got %v", expectedUserLogins, userLogins) + } + + teamLogins := []string{} + for _, t := range restrictions.Teams { + teamLogins = append(teamLogins, *t.Name) + } + if !reflect.DeepEqual(teamLogins, expectedTeamNames) { + return fmt.Errorf("Expected Restrictions.Teams to be %v, got %v", expectedTeamNames, teamLogins) + } + + return nil + } +} + +func testAccCheckGithubBranchProtectionNoRestrictionsExist(protection *github.Protection) resource.TestCheckFunc { + return func(s *terraform.State) error { + if protection.Restrictions != nil { + return fmt.Errorf("Expected Restrictions to be nil, but was %v", protection.Restrictions) + } + + return nil + + } +} + +func testAccGithubBranchProtectionDestroy(s *terraform.State) error { + conn := testAccProvider.Meta().(*Organization).client + + for _, rs := range s.RootModule().Resources { + if rs.Type != "github_branch_protection" { + continue + } + + o := testAccProvider.Meta().(*Organization).name + r, b := parseTwoPartID(rs.Primary.ID) + protection, res, err := conn.Repositories.GetBranchProtection(context.TODO(), o, r, b) + + if err == nil { + if protection != nil { + return fmt.Errorf("Branch protection still exists") + } + } + if res.StatusCode != 404 { + return err + } + return nil + } + return nil +} + +func testAccGithubBranchProtectionConfig(repoName string) string { + return fmt.Sprintf(` +resource "github_repository" "test" { + name = "%s" + description = "Terraform Acceptance Test %s" + auto_init = true +} + +resource "github_branch_protection" "master" { + repository = "${github_repository.test.name}" + branch = "master" + + required_status_checks = { + include_admins = true + strict = true + contexts = ["github/foo"] + } + + required_pull_request_reviews { + include_admins = true + } + + restrictions { + users = ["%s"] + } +} +`, repoName, repoName, testUser) +} + +func testAccGithubBranchProtectionUpdateConfig(repoName string) string { + return fmt.Sprintf(` +resource "github_repository" "test" { + name = "%s" + description = "Terraform Acceptance Test %s" + auto_init = true +} + +resource "github_branch_protection" "master" { + repository = "${github_repository.test.name}" + branch = "master" + + required_status_checks = { + include_admins = false + strict = false + contexts = ["github/bar"] + } +} +`, repoName, repoName) +} diff --git a/builtin/providers/github/resource_github_issue_label.go b/builtin/providers/github/resource_github_issue_label.go index 0d89c0343..5a1f6eea4 100644 --- a/builtin/providers/github/resource_github_issue_label.go +++ b/builtin/providers/github/resource_github_issue_label.go @@ -10,9 +10,9 @@ import ( func resourceGithubIssueLabel() *schema.Resource { return &schema.Resource{ - Create: resourceGithubIssueLabelCreate, + Create: resourceGithubIssueLabelCreateOrUpdate, Read: resourceGithubIssueLabelRead, - Update: resourceGithubIssueLabelUpdate, + Update: resourceGithubIssueLabelCreateOrUpdate, Delete: resourceGithubIssueLabelDelete, Importer: &schema.ResourceImporter{ State: schema.ImportStatePassthrough, @@ -40,21 +40,54 @@ func resourceGithubIssueLabel() *schema.Resource { } } -func resourceGithubIssueLabelCreate(d *schema.ResourceData, meta interface{}) error { +// resourceGithubIssueLabelCreateOrUpdate idempotently creates or updates an +// issue label. Issue labels are keyed off of their "name", so pre-existing +// issue labels result in a 422 HTTP error if they exist outside of Terraform. +// Normally this would not be an issue, except new repositories are created with +// a "default" set of labels, and those labels easily conflict with custom ones. +// +// This function will first check if the label exists, and then issue an update, +// otherwise it will create. This is also advantageous in that we get to use the +// same function for two schema funcs. + +func resourceGithubIssueLabelCreateOrUpdate(d *schema.ResourceData, meta interface{}) error { client := meta.(*Organization).client + o := meta.(*Organization).name r := d.Get("repository").(string) n := d.Get("name").(string) c := d.Get("color").(string) - label := github.Label{ + + label := &github.Label{ Name: &n, Color: &c, } - log.Printf("[DEBUG] Creating label: %#v", label) - _, resp, err := client.Issues.CreateLabel(context.TODO(), meta.(*Organization).name, r, &label) - log.Printf("[DEBUG] Response from creating label: %s", *resp) - if err != nil { - return err + log.Printf("[DEBUG] Querying label existence %s/%s (%s)", o, r, n) + existing, _, _ := client.Issues.GetLabel(context.TODO(), o, r, n) + + if existing != nil { + log.Printf("[DEBUG] Updating label: %s/%s (%s: %s)", o, r, n, c) + + // Pull out the original name. If we already have a resource, this is the + // parsed ID. If not, it's the value given to the resource. + var oname string + if d.Id() == "" { + oname = n + } else { + _, oname = parseTwoPartID(d.Id()) + } + + _, _, err := client.Issues.EditLabel(context.TODO(), o, r, oname, label) + if err != nil { + return err + } + } else { + log.Printf("[DEBUG] Creating label: %s/%s (%s: %s)", o, r, n, c) + _, resp, err := client.Issues.CreateLabel(context.TODO(), o, r, label) + log.Printf("[DEBUG] Response from creating label: %s", *resp) + if err != nil { + return err + } } d.SetId(buildTwoPartID(&r, &n)) @@ -66,6 +99,7 @@ func resourceGithubIssueLabelRead(d *schema.ResourceData, meta interface{}) erro client := meta.(*Organization).client r, n := parseTwoPartID(d.Id()) + log.Printf("[DEBUG] Reading label: %s/%s", r, n) githubLabel, _, err := client.Issues.GetLabel(context.TODO(), meta.(*Organization).name, r, n) if err != nil { d.SetId("") @@ -80,31 +114,12 @@ func resourceGithubIssueLabelRead(d *schema.ResourceData, meta interface{}) erro return nil } -func resourceGithubIssueLabelUpdate(d *schema.ResourceData, meta interface{}) error { - client := meta.(*Organization).client - r := d.Get("repository").(string) - n := d.Get("name").(string) - c := d.Get("color").(string) - - _, originalName := parseTwoPartID(d.Id()) - _, _, err := client.Issues.EditLabel(context.TODO(), meta.(*Organization).name, r, originalName, &github.Label{ - Name: &n, - Color: &c, - }) - if err != nil { - return err - } - - d.SetId(buildTwoPartID(&r, &n)) - - return resourceGithubIssueLabelRead(d, meta) -} - func resourceGithubIssueLabelDelete(d *schema.ResourceData, meta interface{}) error { client := meta.(*Organization).client r := d.Get("repository").(string) n := d.Get("name").(string) + log.Printf("[DEBUG] Deleting label: %s/%s", r, n) _, err := client.Issues.DeleteLabel(context.TODO(), meta.(*Organization).name, r, n) return err } diff --git a/builtin/providers/github/resource_github_issue_label_test.go b/builtin/providers/github/resource_github_issue_label_test.go index d3b3a0597..a73a209e1 100644 --- a/builtin/providers/github/resource_github_issue_label_test.go +++ b/builtin/providers/github/resource_github_issue_label_test.go @@ -6,6 +6,7 @@ import ( "testing" "github.com/google/go-github/github" + "github.com/hashicorp/terraform/helper/acctest" "github.com/hashicorp/terraform/helper/resource" "github.com/hashicorp/terraform/terraform" ) @@ -13,20 +14,23 @@ import ( func TestAccGithubIssueLabel_basic(t *testing.T) { var label github.Label + rString := acctest.RandString(5) + repoName := fmt.Sprintf("tf-acc-test-branch-issue-label-%s", rString) + resource.Test(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, CheckDestroy: testAccGithubIssueLabelDestroy, Steps: []resource.TestStep{ { - Config: testAccGithubIssueLabelConfig, + Config: testAccGithubIssueLabelConfig(repoName), Check: resource.ComposeTestCheckFunc( testAccCheckGithubIssueLabelExists("github_issue_label.test", &label), testAccCheckGithubIssueLabelAttributes(&label, "foo", "000000"), ), }, { - Config: testAccGithubIssueLabelUpdateConfig, + Config: testAccGithubIssueLabelUpdateConfig(repoName), Check: resource.ComposeTestCheckFunc( testAccCheckGithubIssueLabelExists("github_issue_label.test", &label), testAccCheckGithubIssueLabelAttributes(&label, "bar", "FFFFFF"), @@ -36,14 +40,39 @@ func TestAccGithubIssueLabel_basic(t *testing.T) { }) } -func TestAccGithubIssueLabel_importBasic(t *testing.T) { +func TestAccGithubIssueLabel_existingLabel(t *testing.T) { + var label github.Label + + rString := acctest.RandString(5) + repoName := fmt.Sprintf("tf-acc-test-branch-issue-label-%s", rString) + resource.Test(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, CheckDestroy: testAccGithubIssueLabelDestroy, Steps: []resource.TestStep{ { - Config: testAccGithubIssueLabelConfig, + Config: testAccGitHubIssueLabelExistsConfig(repoName), + Check: resource.ComposeTestCheckFunc( + testAccCheckGithubIssueLabelExists("github_issue_label.test", &label), + testAccCheckGithubIssueLabelAttributes(&label, "enhancement", "FF00FF"), + ), + }, + }, + }) +} + +func TestAccGithubIssueLabel_importBasic(t *testing.T) { + rString := acctest.RandString(5) + repoName := fmt.Sprintf("tf-acc-test-branch-issue-label-%s", rString) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccGithubIssueLabelDestroy, + Steps: []resource.TestStep{ + { + Config: testAccGithubIssueLabelConfig(repoName), }, { ResourceName: "github_issue_label.test", @@ -119,18 +148,45 @@ func testAccGithubIssueLabelDestroy(s *terraform.State) error { return nil } -var testAccGithubIssueLabelConfig string = fmt.Sprintf(` +func testAccGithubIssueLabelConfig(repoName string) string { + return fmt.Sprintf(` +resource "github_repository" "test" { + name = "%s" +} + resource "github_issue_label" "test" { - repository = "%s" + repository = "${github_repository.test.name}" name = "foo" color = "000000" } -`, testRepo) +`, repoName) +} + +func testAccGithubIssueLabelUpdateConfig(repoName string) string { + return fmt.Sprintf(` +resource "github_repository" "test" { + name = "%s" +} -var testAccGithubIssueLabelUpdateConfig string = fmt.Sprintf(` resource "github_issue_label" "test" { - repository = "%s" + repository = "${github_repository.test.name}" name = "bar" color = "FFFFFF" } -`, testRepo) +`, repoName) +} + +func testAccGitHubIssueLabelExistsConfig(repoName string) string { + return fmt.Sprintf(` +// Create a repository which has the default labels +resource "github_repository" "test" { + name = "%s" +} + +resource "github_issue_label" "test" { + repository = "${github_repository.test.name}" + name = "enhancement" // Important! This is a pre-created label + color = "FF00FF" +} +`, repoName) +} diff --git a/builtin/providers/github/resource_github_repository_collaborator_test.go b/builtin/providers/github/resource_github_repository_collaborator_test.go index 065cadeab..c842bfe44 100644 --- a/builtin/providers/github/resource_github_repository_collaborator_test.go +++ b/builtin/providers/github/resource_github_repository_collaborator_test.go @@ -5,6 +5,7 @@ import ( "fmt" "testing" + "github.com/hashicorp/terraform/helper/acctest" "github.com/hashicorp/terraform/helper/resource" "github.com/hashicorp/terraform/terraform" ) @@ -12,13 +13,15 @@ import ( const expectedPermission string = "admin" func TestAccGithubRepositoryCollaborator_basic(t *testing.T) { + repoName := fmt.Sprintf("tf-acc-test-collab-%s", acctest.RandString(5)) + resource.Test(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, CheckDestroy: testAccCheckGithubRepositoryCollaboratorDestroy, Steps: []resource.TestStep{ { - Config: testAccGithubRepositoryCollaboratorConfig, + Config: testAccGithubRepositoryCollaboratorConfig(repoName), Check: resource.ComposeTestCheckFunc( testAccCheckGithubRepositoryCollaboratorExists("github_repository_collaborator.test_repo_collaborator"), testAccCheckGithubRepositoryCollaboratorPermission("github_repository_collaborator.test_repo_collaborator"), @@ -29,13 +32,15 @@ func TestAccGithubRepositoryCollaborator_basic(t *testing.T) { } func TestAccGithubRepositoryCollaborator_importBasic(t *testing.T) { + repoName := fmt.Sprintf("tf-acc-test-collab-%s", acctest.RandString(5)) + resource.Test(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, CheckDestroy: testAccCheckGithubRepositoryCollaboratorDestroy, Steps: []resource.TestStep{ { - Config: testAccGithubRepositoryCollaboratorConfig, + Config: testAccGithubRepositoryCollaboratorConfig(repoName), }, { ResourceName: "github_repository_collaborator.test_repo_collaborator", @@ -148,10 +153,16 @@ func testAccCheckGithubRepositoryCollaboratorPermission(n string) resource.TestC } } -var testAccGithubRepositoryCollaboratorConfig string = fmt.Sprintf(` +func testAccGithubRepositoryCollaboratorConfig(repoName string) string { + return fmt.Sprintf(` +resource "github_repository" "test" { + name = "%s" +} + resource "github_repository_collaborator" "test_repo_collaborator" { - repository = "%s" + repository = "${github_repository.test.name}" username = "%s" permission = "%s" } -`, testRepo, testCollaborator, expectedPermission) +`, repoName, testCollaborator, expectedPermission) +} diff --git a/builtin/providers/github/resource_github_team_repository_test.go b/builtin/providers/github/resource_github_team_repository_test.go index 9f1007a3d..a3721c819 100644 --- a/builtin/providers/github/resource_github_team_repository_test.go +++ b/builtin/providers/github/resource_github_team_repository_test.go @@ -13,7 +13,9 @@ import ( func TestAccGithubTeamRepository_basic(t *testing.T) { var repository github.Repository + randString := acctest.RandStringFromCharSet(10, acctest.CharSetAlphaNum) + repoName := fmt.Sprintf("tf-acc-test-team-%s", acctest.RandString(5)) resource.Test(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, @@ -21,14 +23,14 @@ func TestAccGithubTeamRepository_basic(t *testing.T) { CheckDestroy: testAccCheckGithubTeamRepositoryDestroy, Steps: []resource.TestStep{ { - Config: testAccGithubTeamRepositoryConfig(randString, testRepo), + Config: testAccGithubTeamRepositoryConfig(randString, repoName), Check: resource.ComposeTestCheckFunc( testAccCheckGithubTeamRepositoryExists("github_team_repository.test_team_test_repo", &repository), testAccCheckGithubTeamRepositoryRoleState("pull", &repository), ), }, { - Config: testAccGithubTeamRepositoryUpdateConfig(randString, testRepo), + Config: testAccGithubTeamRepositoryUpdateConfig(randString, repoName), Check: resource.ComposeTestCheckFunc( testAccCheckGithubTeamRepositoryExists("github_team_repository.test_team_test_repo", &repository), testAccCheckGithubTeamRepositoryRoleState("push", &repository), @@ -40,6 +42,7 @@ func TestAccGithubTeamRepository_basic(t *testing.T) { func TestAccGithubTeamRepository_importBasic(t *testing.T) { randString := acctest.RandStringFromCharSet(10, acctest.CharSetAlphaNum) + repoName := fmt.Sprintf("tf-acc-test-team-%s", acctest.RandString(5)) resource.Test(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, @@ -47,7 +50,7 @@ func TestAccGithubTeamRepository_importBasic(t *testing.T) { CheckDestroy: testAccCheckGithubTeamRepositoryDestroy, Steps: []resource.TestStep{ { - Config: testAccGithubTeamRepositoryConfig(randString, testRepo), + Config: testAccGithubTeamRepositoryConfig(randString, repoName), }, { ResourceName: "github_team_repository.test_team_test_repo", @@ -159,9 +162,13 @@ resource "github_team" "test_team" { description = "Terraform acc test group" } +resource "github_repository" "test" { + name = "%s" +} + resource "github_team_repository" "test_team_test_repo" { team_id = "${github_team.test_team.id}" - repository = "%s" + repository = "${github_repository.test.name}" permission = "pull" } `, randString, repoName) @@ -174,9 +181,13 @@ resource "github_team" "test_team" { description = "Terraform acc test group" } +resource "github_repository" "test" { + name = "%s" +} + resource "github_team_repository" "test_team_test_repo" { team_id = "${github_team.test_team.id}" - repository = "%s" + repository = "${github_repository.test.name}" permission = "push" } `, randString, repoName) diff --git a/builtin/providers/gitlab/config.go b/builtin/providers/gitlab/config.go new file mode 100644 index 000000000..288f7ba6a --- /dev/null +++ b/builtin/providers/gitlab/config.go @@ -0,0 +1,31 @@ +package gitlab + +import ( + "github.com/xanzy/go-gitlab" +) + +// Config is per-provider, specifies where to connect to gitlab +type Config struct { + Token string + BaseURL string +} + +// Client returns a *gitlab.Client to interact with the configured gitlab instance +func (c *Config) Client() (interface{}, error) { + client := gitlab.NewClient(nil, c.Token) + if c.BaseURL != "" { + err := client.SetBaseURL(c.BaseURL) + if err != nil { + // The BaseURL supplied wasn't valid, bail. + return nil, err + } + } + + // Test the credentials by checking we can get information about the authenticated user. + _, _, err := client.Users.CurrentUser() + if err != nil { + return nil, err + } + + return client, nil +} diff --git a/builtin/providers/gitlab/provider.go b/builtin/providers/gitlab/provider.go new file mode 100644 index 000000000..097dc39e1 --- /dev/null +++ b/builtin/providers/gitlab/provider.go @@ -0,0 +1,53 @@ +package gitlab + +import ( + "github.com/hashicorp/terraform/helper/schema" + "github.com/hashicorp/terraform/terraform" +) + +// Provider returns a terraform.ResourceProvider. +func Provider() terraform.ResourceProvider { + + // The actual provider + return &schema.Provider{ + Schema: map[string]*schema.Schema{ + "token": { + Type: schema.TypeString, + Required: true, + DefaultFunc: schema.EnvDefaultFunc("GITLAB_TOKEN", nil), + Description: descriptions["token"], + }, + "base_url": { + Type: schema.TypeString, + Optional: true, + DefaultFunc: schema.EnvDefaultFunc("GITLAB_BASE_URL", ""), + Description: descriptions["base_url"], + }, + }, + ResourcesMap: map[string]*schema.Resource{ + "gitlab_project": resourceGitlabProject(), + "gitlab_project_hook": resourceGitlabProjectHook(), + }, + + ConfigureFunc: providerConfigure, + } +} + +var descriptions map[string]string + +func init() { + descriptions = map[string]string{ + "token": "The OAuth token used to connect to GitLab.", + + "base_url": "The GitLab Base API URL", + } +} + +func providerConfigure(d *schema.ResourceData) (interface{}, error) { + config := Config{ + Token: d.Get("token").(string), + BaseURL: d.Get("base_url").(string), + } + + return config.Client() +} diff --git a/builtin/providers/gitlab/provider_test.go b/builtin/providers/gitlab/provider_test.go new file mode 100644 index 000000000..a28eddb8d --- /dev/null +++ b/builtin/providers/gitlab/provider_test.go @@ -0,0 +1,35 @@ +package gitlab + +import ( + "os" + "testing" + + "github.com/hashicorp/terraform/helper/schema" + "github.com/hashicorp/terraform/terraform" +) + +var testAccProviders map[string]terraform.ResourceProvider +var testAccProvider *schema.Provider + +func init() { + testAccProvider = Provider().(*schema.Provider) + testAccProviders = map[string]terraform.ResourceProvider{ + "gitlab": testAccProvider, + } +} + +func TestProvider(t *testing.T) { + if err := Provider().(*schema.Provider).InternalValidate(); err != nil { + t.Fatalf("err: %s", err) + } +} + +func TestProvider_impl(t *testing.T) { + var _ terraform.ResourceProvider = Provider() +} + +func testAccPreCheck(t *testing.T) { + if v := os.Getenv("GITLAB_TOKEN"); v == "" { + t.Fatal("GITLAB_TOKEN must be set for acceptance tests") + } +} diff --git a/builtin/providers/gitlab/resource_gitlab_project.go b/builtin/providers/gitlab/resource_gitlab_project.go new file mode 100644 index 000000000..e76c2b1ad --- /dev/null +++ b/builtin/providers/gitlab/resource_gitlab_project.go @@ -0,0 +1,192 @@ +package gitlab + +import ( + "fmt" + "log" + + "github.com/hashicorp/terraform/helper/schema" + "github.com/hashicorp/terraform/helper/validation" + gitlab "github.com/xanzy/go-gitlab" +) + +func resourceGitlabProject() *schema.Resource { + return &schema.Resource{ + Create: resourceGitlabProjectCreate, + Read: resourceGitlabProjectRead, + Update: resourceGitlabProjectUpdate, + Delete: resourceGitlabProjectDelete, + + Schema: map[string]*schema.Schema{ + "name": { + Type: schema.TypeString, + Required: true, + }, + "description": { + Type: schema.TypeString, + Optional: true, + }, + "default_branch": { + Type: schema.TypeString, + Optional: true, + }, + "issues_enabled": { + Type: schema.TypeBool, + Optional: true, + Default: true, + }, + "merge_requests_enabled": { + Type: schema.TypeBool, + Optional: true, + Default: true, + }, + "wiki_enabled": { + Type: schema.TypeBool, + Optional: true, + Default: true, + }, + "snippets_enabled": { + Type: schema.TypeBool, + Optional: true, + Default: true, + }, + "visibility_level": { + Type: schema.TypeString, + Optional: true, + ValidateFunc: validation.StringInSlice([]string{"private", "internal", "public"}, true), + Default: "private", + }, + + "ssh_url_to_repo": { + Type: schema.TypeString, + Computed: true, + }, + "http_url_to_repo": { + Type: schema.TypeString, + Computed: true, + }, + "web_url": { + Type: schema.TypeString, + Computed: true, + }, + }, + } +} + +func resourceGitlabProjectSetToState(d *schema.ResourceData, project *gitlab.Project) { + d.Set("name", project.Name) + d.Set("description", project.Description) + d.Set("default_branch", project.DefaultBranch) + d.Set("issues_enabled", project.IssuesEnabled) + d.Set("merge_requests_enabled", project.MergeRequestsEnabled) + d.Set("wiki_enabled", project.WikiEnabled) + d.Set("snippets_enabled", project.SnippetsEnabled) + d.Set("visibility_level", visibilityLevelToString(project.VisibilityLevel)) + + d.Set("ssh_url_to_repo", project.SSHURLToRepo) + d.Set("http_url_to_repo", project.HTTPURLToRepo) + d.Set("web_url", project.WebURL) +} + +func resourceGitlabProjectCreate(d *schema.ResourceData, meta interface{}) error { + client := meta.(*gitlab.Client) + options := &gitlab.CreateProjectOptions{ + Name: gitlab.String(d.Get("name").(string)), + IssuesEnabled: gitlab.Bool(d.Get("issues_enabled").(bool)), + MergeRequestsEnabled: gitlab.Bool(d.Get("merge_requests_enabled").(bool)), + WikiEnabled: gitlab.Bool(d.Get("wiki_enabled").(bool)), + SnippetsEnabled: gitlab.Bool(d.Get("snippets_enabled").(bool)), + } + + if v, ok := d.GetOk("description"); ok { + options.Description = gitlab.String(v.(string)) + } + + if v, ok := d.GetOk("visibility_level"); ok { + options.VisibilityLevel = stringToVisibilityLevel(v.(string)) + } + + log.Printf("[DEBUG] create gitlab project %q", options.Name) + + project, _, err := client.Projects.CreateProject(options) + if err != nil { + return err + } + + d.SetId(fmt.Sprintf("%d", project.ID)) + + return resourceGitlabProjectRead(d, meta) +} + +func resourceGitlabProjectRead(d *schema.ResourceData, meta interface{}) error { + client := meta.(*gitlab.Client) + log.Printf("[DEBUG] read gitlab project %s", d.Id()) + + project, response, err := client.Projects.GetProject(d.Id()) + if err != nil { + if response.StatusCode == 404 { + log.Printf("[WARN] removing project %s from state because it no longer exists in gitlab", d.Id()) + d.SetId("") + return nil + } + + return err + } + + resourceGitlabProjectSetToState(d, project) + return nil +} + +func resourceGitlabProjectUpdate(d *schema.ResourceData, meta interface{}) error { + client := meta.(*gitlab.Client) + + options := &gitlab.EditProjectOptions{} + + if d.HasChange("name") { + options.Name = gitlab.String(d.Get("name").(string)) + } + + if d.HasChange("description") { + options.Description = gitlab.String(d.Get("description").(string)) + } + + if d.HasChange("default_branch") { + options.DefaultBranch = gitlab.String(d.Get("description").(string)) + } + + if d.HasChange("visibility_level") { + options.VisibilityLevel = stringToVisibilityLevel(d.Get("visibility_level").(string)) + } + + if d.HasChange("issues_enabled") { + options.IssuesEnabled = gitlab.Bool(d.Get("issues_enabled").(bool)) + } + + if d.HasChange("merge_requests_enabled") { + options.MergeRequestsEnabled = gitlab.Bool(d.Get("merge_requests_enabled").(bool)) + } + + if d.HasChange("wiki_enabled") { + options.WikiEnabled = gitlab.Bool(d.Get("wiki_enabled").(bool)) + } + + if d.HasChange("snippets_enabled") { + options.SnippetsEnabled = gitlab.Bool(d.Get("snippets_enabled").(bool)) + } + + log.Printf("[DEBUG] update gitlab project %s", d.Id()) + + _, _, err := client.Projects.EditProject(d.Id(), options) + if err != nil { + return err + } + + return resourceGitlabProjectRead(d, meta) +} + +func resourceGitlabProjectDelete(d *schema.ResourceData, meta interface{}) error { + client := meta.(*gitlab.Client) + log.Printf("[DEBUG] Delete gitlab project %s", d.Id()) + + _, err := client.Projects.DeleteProject(d.Id()) + return err +} diff --git a/builtin/providers/gitlab/resource_gitlab_project_hook.go b/builtin/providers/gitlab/resource_gitlab_project_hook.go new file mode 100644 index 000000000..aa3d9a9ce --- /dev/null +++ b/builtin/providers/gitlab/resource_gitlab_project_hook.go @@ -0,0 +1,192 @@ +package gitlab + +import ( + "fmt" + "log" + "strconv" + + "github.com/hashicorp/terraform/helper/schema" + gitlab "github.com/xanzy/go-gitlab" +) + +func resourceGitlabProjectHook() *schema.Resource { + return &schema.Resource{ + Create: resourceGitlabProjectHookCreate, + Read: resourceGitlabProjectHookRead, + Update: resourceGitlabProjectHookUpdate, + Delete: resourceGitlabProjectHookDelete, + + Schema: map[string]*schema.Schema{ + "project": { + Type: schema.TypeString, + Required: true, + }, + "url": { + Type: schema.TypeString, + Required: true, + }, + "token": { + Type: schema.TypeString, + Optional: true, + Sensitive: true, + }, + "push_events": { + Type: schema.TypeBool, + Optional: true, + Default: true, + }, + "issues_events": { + Type: schema.TypeBool, + Optional: true, + Default: false, + }, + "merge_requests_events": { + Type: schema.TypeBool, + Optional: true, + Default: false, + }, + "tag_push_events": { + Type: schema.TypeBool, + Optional: true, + Default: false, + }, + "note_events": { + Type: schema.TypeBool, + Optional: true, + Default: false, + }, + "build_events": { + Type: schema.TypeBool, + Optional: true, + Default: false, + }, + "pipeline_events": { + Type: schema.TypeBool, + Optional: true, + Default: false, + }, + "wiki_page_events": { + Type: schema.TypeBool, + Optional: true, + Default: false, + }, + "enable_ssl_verification": { + Type: schema.TypeBool, + Optional: true, + Default: true, + }, + }, + } +} + +func resourceGitlabProjectHookCreate(d *schema.ResourceData, meta interface{}) error { + client := meta.(*gitlab.Client) + project := d.Get("project").(string) + options := &gitlab.AddProjectHookOptions{ + URL: gitlab.String(d.Get("url").(string)), + PushEvents: gitlab.Bool(d.Get("push_events").(bool)), + IssuesEvents: gitlab.Bool(d.Get("issues_events").(bool)), + MergeRequestsEvents: gitlab.Bool(d.Get("merge_requests_events").(bool)), + TagPushEvents: gitlab.Bool(d.Get("tag_push_events").(bool)), + NoteEvents: gitlab.Bool(d.Get("note_events").(bool)), + BuildEvents: gitlab.Bool(d.Get("build_events").(bool)), + PipelineEvents: gitlab.Bool(d.Get("pipeline_events").(bool)), + WikiPageEvents: gitlab.Bool(d.Get("wiki_page_events").(bool)), + EnableSSLVerification: gitlab.Bool(d.Get("enable_ssl_verification").(bool)), + } + + if v, ok := d.GetOk("token"); ok { + options.Token = gitlab.String(v.(string)) + } + + log.Printf("[DEBUG] create gitlab project hook %q", options.URL) + + hook, _, err := client.Projects.AddProjectHook(project, options) + if err != nil { + return err + } + + d.SetId(fmt.Sprintf("%d", hook.ID)) + + return resourceGitlabProjectHookRead(d, meta) +} + +func resourceGitlabProjectHookRead(d *schema.ResourceData, meta interface{}) error { + client := meta.(*gitlab.Client) + project := d.Get("project").(string) + hookId, err := strconv.Atoi(d.Id()) + if err != nil { + return err + } + log.Printf("[DEBUG] read gitlab project hook %s/%d", project, hookId) + + hook, response, err := client.Projects.GetProjectHook(project, hookId) + if err != nil { + if response.StatusCode == 404 { + log.Printf("[WARN] removing project hook %d from state because it no longer exists in gitlab", hookId) + d.SetId("") + return nil + } + + return err + } + + d.Set("url", hook.URL) + d.Set("push_events", hook.PushEvents) + d.Set("issues_events", hook.IssuesEvents) + d.Set("merge_requests_events", hook.MergeRequestsEvents) + d.Set("tag_push_events", hook.TagPushEvents) + d.Set("note_events", hook.NoteEvents) + d.Set("build_events", hook.BuildEvents) + d.Set("pipeline_events", hook.PipelineEvents) + d.Set("wiki_page_events", hook.WikiPageEvents) + d.Set("enable_ssl_verification", hook.EnableSSLVerification) + return nil +} + +func resourceGitlabProjectHookUpdate(d *schema.ResourceData, meta interface{}) error { + client := meta.(*gitlab.Client) + project := d.Get("project").(string) + hookId, err := strconv.Atoi(d.Id()) + if err != nil { + return err + } + options := &gitlab.EditProjectHookOptions{ + URL: gitlab.String(d.Get("url").(string)), + PushEvents: gitlab.Bool(d.Get("push_events").(bool)), + IssuesEvents: gitlab.Bool(d.Get("issues_events").(bool)), + MergeRequestsEvents: gitlab.Bool(d.Get("merge_requests_events").(bool)), + TagPushEvents: gitlab.Bool(d.Get("tag_push_events").(bool)), + NoteEvents: gitlab.Bool(d.Get("note_events").(bool)), + BuildEvents: gitlab.Bool(d.Get("build_events").(bool)), + PipelineEvents: gitlab.Bool(d.Get("pipeline_events").(bool)), + WikiPageEvents: gitlab.Bool(d.Get("wiki_page_events").(bool)), + EnableSSLVerification: gitlab.Bool(d.Get("enable_ssl_verification").(bool)), + } + + if d.HasChange("token") { + options.Token = gitlab.String(d.Get("token").(string)) + } + + log.Printf("[DEBUG] update gitlab project hook %s", d.Id()) + + _, _, err = client.Projects.EditProjectHook(project, hookId, options) + if err != nil { + return err + } + + return resourceGitlabProjectHookRead(d, meta) +} + +func resourceGitlabProjectHookDelete(d *schema.ResourceData, meta interface{}) error { + client := meta.(*gitlab.Client) + project := d.Get("project").(string) + hookId, err := strconv.Atoi(d.Id()) + if err != nil { + return err + } + log.Printf("[DEBUG] Delete gitlab project hook %s", d.Id()) + + _, err = client.Projects.DeleteProjectHook(project, hookId) + return err +} diff --git a/builtin/providers/gitlab/resource_gitlab_project_hook_test.go b/builtin/providers/gitlab/resource_gitlab_project_hook_test.go new file mode 100644 index 000000000..0d7d433d7 --- /dev/null +++ b/builtin/providers/gitlab/resource_gitlab_project_hook_test.go @@ -0,0 +1,220 @@ +package gitlab + +import ( + "fmt" + "strconv" + "testing" + + "github.com/hashicorp/terraform/helper/acctest" + "github.com/hashicorp/terraform/helper/resource" + "github.com/hashicorp/terraform/terraform" + "github.com/xanzy/go-gitlab" +) + +func TestAccGitlabProjectHook_basic(t *testing.T) { + var hook gitlab.ProjectHook + rInt := acctest.RandInt() + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckGitlabProjectHookDestroy, + Steps: []resource.TestStep{ + // Create a project and hook with default options + { + Config: testAccGitlabProjectHookConfig(rInt), + Check: resource.ComposeTestCheckFunc( + testAccCheckGitlabProjectHookExists("gitlab_project_hook.foo", &hook), + testAccCheckGitlabProjectHookAttributes(&hook, &testAccGitlabProjectHookExpectedAttributes{ + URL: fmt.Sprintf("https://example.com/hook-%d", rInt), + PushEvents: true, + EnableSSLVerification: true, + }), + ), + }, + // Update the project hook to toggle all the values to their inverse + { + Config: testAccGitlabProjectHookUpdateConfig(rInt), + Check: resource.ComposeTestCheckFunc( + testAccCheckGitlabProjectHookExists("gitlab_project_hook.foo", &hook), + testAccCheckGitlabProjectHookAttributes(&hook, &testAccGitlabProjectHookExpectedAttributes{ + URL: fmt.Sprintf("https://example.com/hook-%d", rInt), + PushEvents: false, + IssuesEvents: true, + MergeRequestsEvents: true, + TagPushEvents: true, + NoteEvents: true, + BuildEvents: true, + PipelineEvents: true, + WikiPageEvents: true, + EnableSSLVerification: false, + }), + ), + }, + // Update the project hook to toggle the options back + { + Config: testAccGitlabProjectHookConfig(rInt), + Check: resource.ComposeTestCheckFunc( + testAccCheckGitlabProjectHookExists("gitlab_project_hook.foo", &hook), + testAccCheckGitlabProjectHookAttributes(&hook, &testAccGitlabProjectHookExpectedAttributes{ + URL: fmt.Sprintf("https://example.com/hook-%d", rInt), + PushEvents: true, + EnableSSLVerification: true, + }), + ), + }, + }, + }) +} + +func testAccCheckGitlabProjectHookExists(n string, hook *gitlab.ProjectHook) resource.TestCheckFunc { + return func(s *terraform.State) error { + rs, ok := s.RootModule().Resources[n] + if !ok { + return fmt.Errorf("Not Found: %s", n) + } + + hookID, err := strconv.Atoi(rs.Primary.ID) + if err != nil { + return err + } + repoName := rs.Primary.Attributes["project"] + if repoName == "" { + return fmt.Errorf("No project ID is set") + } + conn := testAccProvider.Meta().(*gitlab.Client) + + gotHook, _, err := conn.Projects.GetProjectHook(repoName, hookID) + if err != nil { + return err + } + *hook = *gotHook + return nil + } +} + +type testAccGitlabProjectHookExpectedAttributes struct { + URL string + PushEvents bool + IssuesEvents bool + MergeRequestsEvents bool + TagPushEvents bool + NoteEvents bool + BuildEvents bool + PipelineEvents bool + WikiPageEvents bool + EnableSSLVerification bool +} + +func testAccCheckGitlabProjectHookAttributes(hook *gitlab.ProjectHook, want *testAccGitlabProjectHookExpectedAttributes) resource.TestCheckFunc { + return func(s *terraform.State) error { + if hook.URL != want.URL { + return fmt.Errorf("got url %q; want %q", hook.URL, want.URL) + } + + if hook.EnableSSLVerification != want.EnableSSLVerification { + return fmt.Errorf("got enable_ssl_verification %t; want %t", hook.EnableSSLVerification, want.EnableSSLVerification) + } + + if hook.PushEvents != want.PushEvents { + return fmt.Errorf("got push_events %t; want %t", hook.PushEvents, want.PushEvents) + } + + if hook.IssuesEvents != want.IssuesEvents { + return fmt.Errorf("got issues_events %t; want %t", hook.IssuesEvents, want.IssuesEvents) + } + + if hook.MergeRequestsEvents != want.MergeRequestsEvents { + return fmt.Errorf("got merge_requests_events %t; want %t", hook.MergeRequestsEvents, want.MergeRequestsEvents) + } + + if hook.TagPushEvents != want.TagPushEvents { + return fmt.Errorf("got tag_push_events %t; want %t", hook.TagPushEvents, want.TagPushEvents) + } + + if hook.NoteEvents != want.NoteEvents { + return fmt.Errorf("got note_events %t; want %t", hook.NoteEvents, want.NoteEvents) + } + + if hook.BuildEvents != want.BuildEvents { + return fmt.Errorf("got build_events %t; want %t", hook.BuildEvents, want.BuildEvents) + } + + if hook.PipelineEvents != want.PipelineEvents { + return fmt.Errorf("got pipeline_events %t; want %t", hook.PipelineEvents, want.PipelineEvents) + } + + if hook.WikiPageEvents != want.WikiPageEvents { + return fmt.Errorf("got wiki_page_events %t; want %t", hook.WikiPageEvents, want.WikiPageEvents) + } + + return nil + } +} + +func testAccCheckGitlabProjectHookDestroy(s *terraform.State) error { + conn := testAccProvider.Meta().(*gitlab.Client) + + for _, rs := range s.RootModule().Resources { + if rs.Type != "gitlab_project" { + continue + } + + gotRepo, resp, err := conn.Projects.GetProject(rs.Primary.ID) + if err == nil { + if gotRepo != nil && fmt.Sprintf("%d", gotRepo.ID) == rs.Primary.ID { + return fmt.Errorf("Repository still exists") + } + } + if resp.StatusCode != 404 { + return err + } + return nil + } + return nil +} + +func testAccGitlabProjectHookConfig(rInt int) string { + return fmt.Sprintf(` +resource "gitlab_project" "foo" { + name = "foo-%d" + description = "Terraform acceptance tests" + + # So that acceptance tests can be run in a gitlab organization + # with no billing + visibility_level = "public" +} + +resource "gitlab_project_hook" "foo" { + project = "${gitlab_project.foo.id}" + url = "https://example.com/hook-%d" +} + `, rInt, rInt) +} + +func testAccGitlabProjectHookUpdateConfig(rInt int) string { + return fmt.Sprintf(` +resource "gitlab_project" "foo" { + name = "foo-%d" + description = "Terraform acceptance tests" + + # So that acceptance tests can be run in a gitlab organization + # with no billing + visibility_level = "public" +} + +resource "gitlab_project_hook" "foo" { + project = "${gitlab_project.foo.id}" + url = "https://example.com/hook-%d" + enable_ssl_verification = false + push_events = false + issues_events = true + merge_requests_events = true + tag_push_events = true + note_events = true + build_events = true + pipeline_events = true + wiki_page_events = true +} + `, rInt, rInt) +} diff --git a/builtin/providers/gitlab/resource_gitlab_project_test.go b/builtin/providers/gitlab/resource_gitlab_project_test.go new file mode 100644 index 000000000..52083b0be --- /dev/null +++ b/builtin/providers/gitlab/resource_gitlab_project_test.go @@ -0,0 +1,191 @@ +package gitlab + +import ( + "fmt" + "testing" + + "github.com/hashicorp/terraform/helper/acctest" + "github.com/hashicorp/terraform/helper/resource" + "github.com/hashicorp/terraform/terraform" + "github.com/xanzy/go-gitlab" +) + +func TestAccGitlabProject_basic(t *testing.T) { + var project gitlab.Project + rInt := acctest.RandInt() + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckGitlabProjectDestroy, + Steps: []resource.TestStep{ + // Create a project with all the features on + { + Config: testAccGitlabProjectConfig(rInt), + Check: resource.ComposeTestCheckFunc( + testAccCheckGitlabProjectExists("gitlab_project.foo", &project), + testAccCheckGitlabProjectAttributes(&project, &testAccGitlabProjectExpectedAttributes{ + Name: fmt.Sprintf("foo-%d", rInt), + Description: "Terraform acceptance tests", + IssuesEnabled: true, + MergeRequestsEnabled: true, + WikiEnabled: true, + SnippetsEnabled: true, + VisibilityLevel: 20, + }), + ), + }, + // Update the project to turn the features off + { + Config: testAccGitlabProjectUpdateConfig(rInt), + Check: resource.ComposeTestCheckFunc( + testAccCheckGitlabProjectExists("gitlab_project.foo", &project), + testAccCheckGitlabProjectAttributes(&project, &testAccGitlabProjectExpectedAttributes{ + Name: fmt.Sprintf("foo-%d", rInt), + Description: "Terraform acceptance tests!", + VisibilityLevel: 20, + }), + ), + }, + //Update the project to turn the features on again + { + Config: testAccGitlabProjectConfig(rInt), + Check: resource.ComposeTestCheckFunc( + testAccCheckGitlabProjectExists("gitlab_project.foo", &project), + testAccCheckGitlabProjectAttributes(&project, &testAccGitlabProjectExpectedAttributes{ + Name: fmt.Sprintf("foo-%d", rInt), + Description: "Terraform acceptance tests", + IssuesEnabled: true, + MergeRequestsEnabled: true, + WikiEnabled: true, + SnippetsEnabled: true, + VisibilityLevel: 20, + }), + ), + }, + }, + }) +} + +func testAccCheckGitlabProjectExists(n string, project *gitlab.Project) resource.TestCheckFunc { + return func(s *terraform.State) error { + rs, ok := s.RootModule().Resources[n] + if !ok { + return fmt.Errorf("Not Found: %s", n) + } + + repoName := rs.Primary.ID + if repoName == "" { + return fmt.Errorf("No project ID is set") + } + conn := testAccProvider.Meta().(*gitlab.Client) + + gotProject, _, err := conn.Projects.GetProject(repoName) + if err != nil { + return err + } + *project = *gotProject + return nil + } +} + +type testAccGitlabProjectExpectedAttributes struct { + Name string + Description string + DefaultBranch string + IssuesEnabled bool + MergeRequestsEnabled bool + WikiEnabled bool + SnippetsEnabled bool + VisibilityLevel gitlab.VisibilityLevelValue +} + +func testAccCheckGitlabProjectAttributes(project *gitlab.Project, want *testAccGitlabProjectExpectedAttributes) resource.TestCheckFunc { + return func(s *terraform.State) error { + if project.Name != want.Name { + return fmt.Errorf("got repo %q; want %q", project.Name, want.Name) + } + if project.Description != want.Description { + return fmt.Errorf("got description %q; want %q", project.Description, want.Description) + } + + if project.DefaultBranch != want.DefaultBranch { + return fmt.Errorf("got default_branch %q; want %q", project.DefaultBranch, want.DefaultBranch) + } + + if project.IssuesEnabled != want.IssuesEnabled { + return fmt.Errorf("got issues_enabled %t; want %t", project.IssuesEnabled, want.IssuesEnabled) + } + + if project.MergeRequestsEnabled != want.MergeRequestsEnabled { + return fmt.Errorf("got merge_requests_enabled %t; want %t", project.MergeRequestsEnabled, want.MergeRequestsEnabled) + } + + if project.WikiEnabled != want.WikiEnabled { + return fmt.Errorf("got wiki_enabled %t; want %t", project.WikiEnabled, want.WikiEnabled) + } + + if project.SnippetsEnabled != want.SnippetsEnabled { + return fmt.Errorf("got snippets_enabled %t; want %t", project.SnippetsEnabled, want.SnippetsEnabled) + } + + if project.VisibilityLevel != want.VisibilityLevel { + return fmt.Errorf("got default branch %q; want %q", project.VisibilityLevel, want.VisibilityLevel) + } + + return nil + } +} + +func testAccCheckGitlabProjectDestroy(s *terraform.State) error { + conn := testAccProvider.Meta().(*gitlab.Client) + + for _, rs := range s.RootModule().Resources { + if rs.Type != "gitlab_project" { + continue + } + + gotRepo, resp, err := conn.Projects.GetProject(rs.Primary.ID) + if err == nil { + if gotRepo != nil && fmt.Sprintf("%d", gotRepo.ID) == rs.Primary.ID { + return fmt.Errorf("Repository still exists") + } + } + if resp.StatusCode != 404 { + return err + } + return nil + } + return nil +} + +func testAccGitlabProjectConfig(rInt int) string { + return fmt.Sprintf(` +resource "gitlab_project" "foo" { + name = "foo-%d" + description = "Terraform acceptance tests" + + # So that acceptance tests can be run in a gitlab organization + # with no billing + visibility_level = "public" +} + `, rInt) +} + +func testAccGitlabProjectUpdateConfig(rInt int) string { + return fmt.Sprintf(` +resource "gitlab_project" "foo" { + name = "foo-%d" + description = "Terraform acceptance tests!" + + # So that acceptance tests can be run in a gitlab organization + # with no billing + visibility_level = "public" + + issues_enabled = false + merge_requests_enabled = false + wiki_enabled = false + snippets_enabled = false +} + `, rInt) +} diff --git a/builtin/providers/gitlab/util.go b/builtin/providers/gitlab/util.go new file mode 100644 index 000000000..942e30852 --- /dev/null +++ b/builtin/providers/gitlab/util.go @@ -0,0 +1,54 @@ +package gitlab + +import ( + "fmt" + + "github.com/hashicorp/terraform/helper/schema" + gitlab "github.com/xanzy/go-gitlab" +) + +// copied from ../github/util.go +func validateValueFunc(values []string) schema.SchemaValidateFunc { + return func(v interface{}, k string) (we []string, errors []error) { + value := v.(string) + valid := false + for _, role := range values { + if value == role { + valid = true + break + } + } + + if !valid { + errors = append(errors, fmt.Errorf("%s is an invalid value for argument %s", value, k)) + } + return + } +} + +func stringToVisibilityLevel(s string) *gitlab.VisibilityLevelValue { + lookup := map[string]gitlab.VisibilityLevelValue{ + "private": gitlab.PrivateVisibility, + "internal": gitlab.InternalVisibility, + "public": gitlab.PublicVisibility, + } + + value, ok := lookup[s] + if !ok { + return nil + } + return &value +} + +func visibilityLevelToString(v gitlab.VisibilityLevelValue) *string { + lookup := map[gitlab.VisibilityLevelValue]string{ + gitlab.PrivateVisibility: "private", + gitlab.InternalVisibility: "internal", + gitlab.PublicVisibility: "public", + } + value, ok := lookup[v] + if !ok { + return nil + } + return &value +} diff --git a/builtin/providers/gitlab/util_test.go b/builtin/providers/gitlab/util_test.go new file mode 100644 index 000000000..465eec73c --- /dev/null +++ b/builtin/providers/gitlab/util_test.go @@ -0,0 +1,65 @@ +package gitlab + +import ( + "testing" + + "github.com/xanzy/go-gitlab" +) + +func TestGitlab_validation(t *testing.T) { + cases := []struct { + Value string + ErrCount int + }{ + { + Value: "invalid", + ErrCount: 1, + }, + { + Value: "valid_one", + ErrCount: 0, + }, + { + Value: "valid_two", + ErrCount: 0, + }, + } + + validationFunc := validateValueFunc([]string{"valid_one", "valid_two"}) + + for _, tc := range cases { + _, errors := validationFunc(tc.Value, "test_arg") + + if len(errors) != tc.ErrCount { + t.Fatalf("Expected 1 validation error") + } + } +} + +func TestGitlab_visbilityHelpers(t *testing.T) { + cases := []struct { + String string + Level gitlab.VisibilityLevelValue + }{ + { + String: "private", + Level: gitlab.PrivateVisibility, + }, + { + String: "public", + Level: gitlab.PublicVisibility, + }, + } + + for _, tc := range cases { + level := stringToVisibilityLevel(tc.String) + if level == nil || *level != tc.Level { + t.Fatalf("got %v expected %v", level, tc.Level) + } + + sv := visibilityLevelToString(tc.Level) + if sv == nil || *sv != tc.String { + t.Fatalf("got %v expected %v", sv, tc.String) + } + } +} diff --git a/builtin/providers/google/config.go b/builtin/providers/google/config.go index 37ac2db85..716296442 100644 --- a/builtin/providers/google/config.go +++ b/builtin/providers/google/config.go @@ -8,11 +8,13 @@ import ( "runtime" "strings" + "github.com/hashicorp/terraform/helper/logging" "github.com/hashicorp/terraform/helper/pathorcontents" "github.com/hashicorp/terraform/terraform" "golang.org/x/oauth2" "golang.org/x/oauth2/google" "golang.org/x/oauth2/jwt" + "google.golang.org/api/bigquery/v2" "google.golang.org/api/cloudbilling/v1" "google.golang.org/api/cloudresourcemanager/v1" "google.golang.org/api/compute/v1" @@ -42,6 +44,7 @@ type Config struct { clientSqlAdmin *sqladmin.Service clientIAM *iam.Service clientServiceMan *servicemanagement.APIService + clientBigQuery *bigquery.Service } func (c *Config) loadAndValidate() error { @@ -93,6 +96,8 @@ func (c *Config) loadAndValidate() error { } } + client.Transport = logging.NewTransport("Google", client.Transport) + versionString := terraform.VersionString() userAgent := fmt.Sprintf( "(%s %s) Terraform/%s", runtime.GOOS, runtime.GOARCH, versionString) @@ -169,6 +174,13 @@ func (c *Config) loadAndValidate() error { } c.clientBilling.UserAgent = userAgent + log.Printf("[INFO] Instantiating Google Cloud BigQuery Client...") + c.clientBigQuery, err = bigquery.New(client) + if err != nil { + return err + } + c.clientBigQuery.UserAgent = userAgent + return nil } diff --git a/builtin/providers/google/data_source_google_compute_network.go b/builtin/providers/google/data_source_google_compute_network.go new file mode 100644 index 000000000..b22d2b257 --- /dev/null +++ b/builtin/providers/google/data_source_google_compute_network.go @@ -0,0 +1,73 @@ +package google + +import ( + "fmt" + + "github.com/hashicorp/terraform/helper/schema" + "google.golang.org/api/googleapi" +) + +func dataSourceGoogleComputeNetwork() *schema.Resource { + return &schema.Resource{ + Read: dataSourceGoogleComputeNetworkRead, + + Schema: map[string]*schema.Schema{ + "name": &schema.Schema{ + Type: schema.TypeString, + Required: true, + }, + + "description": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + }, + + "gateway_ipv4": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + }, + + "self_link": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + }, + + "project": &schema.Schema{ + Type: schema.TypeString, + Optional: true, + }, + + "subnetworks_self_links": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{Type: schema.TypeString}, + }, + }, + } +} + +func dataSourceGoogleComputeNetworkRead(d *schema.ResourceData, meta interface{}) error { + config := meta.(*Config) + + project, err := getProject(d, config) + if err != nil { + return err + } + network, err := config.clientCompute.Networks.Get( + project, d.Get("name").(string)).Do() + if err != nil { + if gerr, ok := err.(*googleapi.Error); ok && gerr.Code == 404 { + // The resource doesn't exist anymore + + return fmt.Errorf("Network Not Found : %s", d.Get("name")) + } + + return fmt.Errorf("Error reading network: %s", err) + } + d.Set("gateway_ipv4", network.GatewayIPv4) + d.Set("self_link", network.SelfLink) + d.Set("description", network.Description) + d.Set("subnetworks_self_links", network.Subnetworks) + d.SetId(network.Name) + return nil +} diff --git a/builtin/providers/google/data_source_google_compute_network_test.go b/builtin/providers/google/data_source_google_compute_network_test.go new file mode 100644 index 000000000..fe0aac8fa --- /dev/null +++ b/builtin/providers/google/data_source_google_compute_network_test.go @@ -0,0 +1,73 @@ +package google + +import ( + "fmt" + "testing" + + "github.com/hashicorp/terraform/helper/acctest" + "github.com/hashicorp/terraform/helper/resource" + "github.com/hashicorp/terraform/terraform" +) + +func TestAccDataSourceGoogleNetwork(t *testing.T) { + networkName := fmt.Sprintf("tf-test-%s", acctest.RandString(10)) + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + Steps: []resource.TestStep{ + resource.TestStep{ + Config: testAccDataSourceGoogleNetworkConfig(networkName), + Check: resource.ComposeTestCheckFunc( + testAccDataSourceGoogleNetworkCheck("data.google_compute_network.my_network", "google_compute_network.foobar"), + ), + }, + }, + }) +} + +func testAccDataSourceGoogleNetworkCheck(data_source_name string, resource_name string) resource.TestCheckFunc { + return func(s *terraform.State) error { + ds, ok := s.RootModule().Resources[data_source_name] + if !ok { + return fmt.Errorf("root module has no resource called %s", data_source_name) + } + + rs, ok := s.RootModule().Resources[resource_name] + if !ok { + return fmt.Errorf("can't find %s in state", resource_name) + } + + ds_attr := ds.Primary.Attributes + rs_attr := rs.Primary.Attributes + network_attrs_to_test := []string{ + "id", + "self_link", + "name", + "description", + } + + for _, attr_to_check := range network_attrs_to_test { + if ds_attr[attr_to_check] != rs_attr[attr_to_check] { + return fmt.Errorf( + "%s is %s; want %s", + attr_to_check, + ds_attr[attr_to_check], + rs_attr[attr_to_check], + ) + } + } + return nil + } +} + +func testAccDataSourceGoogleNetworkConfig(name string) string { + return fmt.Sprintf(` +resource "google_compute_network" "foobar" { + name = "%s" + description = "my-description" +} + +data "google_compute_network" "my_network" { + name = "${google_compute_network.foobar.name}" +}`, name) +} diff --git a/builtin/providers/google/data_source_google_compute_subnetwork.go b/builtin/providers/google/data_source_google_compute_subnetwork.go new file mode 100644 index 000000000..bff489ba3 --- /dev/null +++ b/builtin/providers/google/data_source_google_compute_subnetwork.go @@ -0,0 +1,87 @@ +package google + +import ( + "fmt" + + "github.com/hashicorp/terraform/helper/schema" + "google.golang.org/api/googleapi" +) + +func dataSourceGoogleComputeSubnetwork() *schema.Resource { + return &schema.Resource{ + Read: dataSourceGoogleComputeSubnetworkRead, + + Schema: map[string]*schema.Schema{ + "name": &schema.Schema{ + Type: schema.TypeString, + Required: true, + }, + + "description": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + }, + "self_link": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + }, + "ip_cidr_range": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + }, + "network": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + }, + "gateway_address": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + }, + "region": &schema.Schema{ + Type: schema.TypeString, + Optional: true, + }, + + "project": &schema.Schema{ + Type: schema.TypeString, + Optional: true, + }, + }, + } +} + +func dataSourceGoogleComputeSubnetworkRead(d *schema.ResourceData, meta interface{}) error { + config := meta.(*Config) + + project, err := getProject(d, config) + if err != nil { + return err + } + region, err := getRegion(d, config) + if err != nil { + return err + } + + subnetwork, err := config.clientCompute.Subnetworks.Get( + project, region, d.Get("name").(string)).Do() + if err != nil { + if gerr, ok := err.(*googleapi.Error); ok && gerr.Code == 404 { + // The resource doesn't exist anymore + + return fmt.Errorf("Subnetwork Not Found") + } + + return fmt.Errorf("Error reading Subnetwork: %s", err) + } + + d.Set("ip_cidr_range", subnetwork.IpCidrRange) + d.Set("self_link", subnetwork.SelfLink) + d.Set("description", subnetwork.Description) + d.Set("gateway_address", subnetwork.GatewayAddress) + d.Set("network", subnetwork.Network) + + //Subnet id creation is defined in resource_compute_subnetwork.go + subnetwork.Region = region + d.SetId(createSubnetID(subnetwork)) + return nil +} diff --git a/builtin/providers/google/data_source_google_compute_subnetwork_test.go b/builtin/providers/google/data_source_google_compute_subnetwork_test.go new file mode 100644 index 000000000..f3d8516da --- /dev/null +++ b/builtin/providers/google/data_source_google_compute_subnetwork_test.go @@ -0,0 +1,81 @@ +package google + +import ( + "fmt" + "testing" + + "github.com/hashicorp/terraform/helper/resource" + "github.com/hashicorp/terraform/terraform" +) + +func TestAccDataSourceGoogleSubnetwork(t *testing.T) { + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + Steps: []resource.TestStep{ + resource.TestStep{ + Config: TestAccDataSourceGoogleSubnetworkConfig, + Check: resource.ComposeTestCheckFunc( + testAccDataSourceGoogleSubnetworkCheck("data.google_compute_subnetwork.my_subnetwork", "google_compute_subnetwork.foobar"), + ), + }, + }, + }) +} + +func testAccDataSourceGoogleSubnetworkCheck(data_source_name string, resource_name string) resource.TestCheckFunc { + return func(s *terraform.State) error { + ds, ok := s.RootModule().Resources[data_source_name] + if !ok { + return fmt.Errorf("root module has no resource called %s", data_source_name) + } + + rs, ok := s.RootModule().Resources[resource_name] + if !ok { + return fmt.Errorf("can't find %s in state", resource_name) + } + + ds_attr := ds.Primary.Attributes + rs_attr := rs.Primary.Attributes + + subnetwork_attrs_to_test := []string{ + "id", + "self_link", + "name", + "description", + "ip_cidr_range", + "network", + } + + for _, attr_to_check := range subnetwork_attrs_to_test { + if ds_attr[attr_to_check] != rs_attr[attr_to_check] { + return fmt.Errorf( + "%s is %s; want %s", + attr_to_check, + ds_attr[attr_to_check], + rs_attr[attr_to_check], + ) + } + } + + return nil + } +} + +var TestAccDataSourceGoogleSubnetworkConfig = ` + +resource "google_compute_network" "foobar" { + name = "network-test" + description = "my-description" +} +resource "google_compute_subnetwork" "foobar" { + name = "subnetwork-test" + description = "my-description" + ip_cidr_range = "10.0.0.0/24" + network = "${google_compute_network.foobar.self_link}" +} + +data "google_compute_subnetwork" "my_subnetwork" { + name = "${google_compute_subnetwork.foobar.name}" +} +` diff --git a/builtin/providers/google/data_source_google_container_engine_versions.go b/builtin/providers/google/data_source_google_container_engine_versions.go new file mode 100644 index 000000000..3eaf8043a --- /dev/null +++ b/builtin/providers/google/data_source_google_container_engine_versions.go @@ -0,0 +1,67 @@ +package google + +import ( + "fmt" + "time" + + "github.com/hashicorp/terraform/helper/schema" +) + +func dataSourceGoogleContainerEngineVersions() *schema.Resource { + return &schema.Resource{ + Read: dataSourceGoogleContainerEngineVersionsRead, + Schema: map[string]*schema.Schema{ + "project": { + Type: schema.TypeString, + Optional: true, + }, + "zone": { + Type: schema.TypeString, + Required: true, + }, + "latest_master_version": { + Type: schema.TypeString, + Computed: true, + }, + "latest_node_version": { + Type: schema.TypeString, + Computed: true, + }, + "valid_master_versions": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{Type: schema.TypeString}, + }, + "valid_node_versions": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{Type: schema.TypeString}, + }, + }, + } +} + +func dataSourceGoogleContainerEngineVersionsRead(d *schema.ResourceData, meta interface{}) error { + config := meta.(*Config) + + project, err := getProject(d, config) + if err != nil { + return err + } + + zone := d.Get("zone").(string) + + resp, err := config.clientContainer.Projects.Zones.GetServerconfig(project, zone).Do() + if err != nil { + return fmt.Errorf("Error retrieving available container cluster versions: %s", err.Error()) + } + + d.Set("valid_master_versions", resp.ValidMasterVersions) + d.Set("valid_node_versions", resp.ValidNodeVersions) + d.Set("latest_master_version", resp.ValidMasterVersions[0]) + d.Set("latest_node_version", resp.ValidNodeVersions[0]) + + d.SetId(time.Now().UTC().String()) + + return nil +} diff --git a/builtin/providers/google/data_source_google_container_engine_versions_test.go b/builtin/providers/google/data_source_google_container_engine_versions_test.go new file mode 100644 index 000000000..baf880943 --- /dev/null +++ b/builtin/providers/google/data_source_google_container_engine_versions_test.go @@ -0,0 +1,97 @@ +package google + +import ( + "errors" + "fmt" + "strconv" + "testing" + + "github.com/hashicorp/terraform/helper/resource" + "github.com/hashicorp/terraform/terraform" +) + +func TestAccGoogleContainerEngineVersions_basic(t *testing.T) { + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + Steps: []resource.TestStep{ + { + Config: testAccCheckGoogleContainerEngineVersionsConfig, + Check: resource.ComposeTestCheckFunc( + testAccCheckGoogleContainerEngineVersionsMeta("data.google_container_engine_versions.versions"), + ), + }, + }, + }) +} + +func testAccCheckGoogleContainerEngineVersionsMeta(n string) resource.TestCheckFunc { + return func(s *terraform.State) error { + rs, ok := s.RootModule().Resources[n] + if !ok { + return fmt.Errorf("Can't find versions data source: %s", n) + } + + if rs.Primary.ID == "" { + return errors.New("versions data source ID not set.") + } + + nodeCount, ok := rs.Primary.Attributes["valid_node_versions.#"] + if !ok { + return errors.New("can't find 'valid_node_versions' attribute") + } + + noOfNodes, err := strconv.Atoi(nodeCount) + if err != nil { + return errors.New("failed to read number of valid node versions") + } + if noOfNodes < 2 { + return fmt.Errorf("expected at least 2 valid node versions, received %d, this is most likely a bug", + noOfNodes) + } + + for i := 0; i < noOfNodes; i++ { + idx := "valid_node_versions." + strconv.Itoa(i) + v, ok := rs.Primary.Attributes[idx] + if !ok { + return fmt.Errorf("valid node versions list is corrupt (%q not found), this is definitely a bug", idx) + } + if len(v) < 1 { + return fmt.Errorf("Empty node version (%q), this is definitely a bug", idx) + } + } + + masterCount, ok := rs.Primary.Attributes["valid_master_versions.#"] + if !ok { + return errors.New("can't find 'valid_master_versions' attribute") + } + + noOfMasters, err := strconv.Atoi(masterCount) + if err != nil { + return errors.New("failed to read number of valid master versions") + } + if noOfMasters < 2 { + return fmt.Errorf("expected at least 2 valid master versions, received %d, this is most likely a bug", + noOfMasters) + } + + for i := 0; i < noOfMasters; i++ { + idx := "valid_master_versions." + strconv.Itoa(i) + v, ok := rs.Primary.Attributes[idx] + if !ok { + return fmt.Errorf("valid master versions list is corrupt (%q not found), this is definitely a bug", idx) + } + if len(v) < 1 { + return fmt.Errorf("Empty master version (%q), this is definitely a bug", idx) + } + } + + return nil + } +} + +var testAccCheckGoogleContainerEngineVersionsConfig = ` +data "google_container_engine_versions" "versions" { + zone = "us-central1-b" +} +` diff --git a/builtin/providers/google/import_bigquery_dataset_test.go b/builtin/providers/google/import_bigquery_dataset_test.go new file mode 100644 index 000000000..32f2682d4 --- /dev/null +++ b/builtin/providers/google/import_bigquery_dataset_test.go @@ -0,0 +1,31 @@ +package google + +import ( + "fmt" + "testing" + + "github.com/hashicorp/terraform/helper/acctest" + "github.com/hashicorp/terraform/helper/resource" +) + +func TestAccBigQueryDataset_importBasic(t *testing.T) { + resourceName := "google_bigquery_dataset.test" + datasetID := fmt.Sprintf("tf_test_%s", acctest.RandString(10)) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckBigQueryDatasetDestroy, + Steps: []resource.TestStep{ + { + Config: testAccBigQueryDataset(datasetID), + }, + + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} diff --git a/builtin/providers/google/import_bigquery_table_test.go b/builtin/providers/google/import_bigquery_table_test.go new file mode 100644 index 000000000..7fa359a4c --- /dev/null +++ b/builtin/providers/google/import_bigquery_table_test.go @@ -0,0 +1,32 @@ +package google + +import ( + "fmt" + "testing" + + "github.com/hashicorp/terraform/helper/acctest" + "github.com/hashicorp/terraform/helper/resource" +) + +func TestAccBigQueryTable_importBasic(t *testing.T) { + resourceName := "google_bigquery_table.test" + datasetID := fmt.Sprintf("tf_test_%s", acctest.RandString(10)) + tableID := fmt.Sprintf("tf_test_%s", acctest.RandString(10)) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckBigQueryTableDestroy, + Steps: []resource.TestStep{ + { + Config: testAccBigQueryTable(datasetID, tableID), + }, + + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} diff --git a/builtin/providers/google/import_compute_address_test.go b/builtin/providers/google/import_compute_address_test.go new file mode 100644 index 000000000..db579f4c0 --- /dev/null +++ b/builtin/providers/google/import_compute_address_test.go @@ -0,0 +1,28 @@ +package google + +import ( + "testing" + + "github.com/hashicorp/terraform/helper/resource" +) + +func TestAccComputeAddress_importBasic(t *testing.T) { + resourceName := "google_compute_address.foobar" + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckComputeAddressDestroy, + Steps: []resource.TestStep{ + resource.TestStep{ + Config: testAccComputeAddress_basic, + }, + + resource.TestStep{ + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} diff --git a/builtin/providers/google/import_compute_global_address_test.go b/builtin/providers/google/import_compute_global_address_test.go new file mode 100644 index 000000000..73e495644 --- /dev/null +++ b/builtin/providers/google/import_compute_global_address_test.go @@ -0,0 +1,28 @@ +package google + +import ( + "testing" + + "github.com/hashicorp/terraform/helper/resource" +) + +func TestAccComputeGlobalAddress_importBasic(t *testing.T) { + resourceName := "google_compute_global_address.foobar" + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckComputeGlobalAddressDestroy, + Steps: []resource.TestStep{ + resource.TestStep{ + Config: testAccComputeGlobalAddress_basic, + }, + + resource.TestStep{ + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} diff --git a/builtin/providers/google/import_compute_network_test.go b/builtin/providers/google/import_compute_network_test.go new file mode 100644 index 000000000..8e6ab769b --- /dev/null +++ b/builtin/providers/google/import_compute_network_test.go @@ -0,0 +1,65 @@ +package google + +import ( + "testing" + + "github.com/hashicorp/terraform/helper/resource" +) + +func TestAccComputeNetwork_importBasic(t *testing.T) { + resourceName := "google_compute_network.foobar" + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckComputeNetworkDestroy, + Steps: []resource.TestStep{ + { + Config: testAccComputeNetwork_basic, + }, { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + //ImportStateVerifyIgnore: []string{"ipv4_range", "name"}, + }, + }, + }) +} + +func TestAccComputeNetwork_importAuto_subnet(t *testing.T) { + resourceName := "google_compute_network.bar" + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckComputeNetworkDestroy, + Steps: []resource.TestStep{ + { + Config: testAccComputeNetwork_auto_subnet, + }, { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func TestAccComputeNetwork_importCustom_subnet(t *testing.T) { + resourceName := "google_compute_network.baz" + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckComputeNetworkDestroy, + Steps: []resource.TestStep{ + { + Config: testAccComputeNetwork_custom_subnet, + }, { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} diff --git a/builtin/providers/google/import_compute_route_test.go b/builtin/providers/google/import_compute_route_test.go new file mode 100644 index 000000000..a4bfb9893 --- /dev/null +++ b/builtin/providers/google/import_compute_route_test.go @@ -0,0 +1,47 @@ +package google + +import ( + "testing" + + "github.com/hashicorp/terraform/helper/resource" +) + +func TestAccComputeRoute_importBasic(t *testing.T) { + resourceName := "google_compute_network.foobar" + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckComputeRouteDestroy, + Steps: []resource.TestStep{ + { + Config: testAccComputeRoute_basic, + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func TestAccComputeRoute_importDefaultInternetGateway(t *testing.T) { + resourceName := "google_compute_network.foobar" + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckComputeRouteDestroy, + Steps: []resource.TestStep{ + { + Config: testAccComputeRoute_defaultInternetGateway, + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} diff --git a/builtin/providers/google/import_dns_managed_zone_test.go b/builtin/providers/google/import_dns_managed_zone_test.go new file mode 100644 index 000000000..751663516 --- /dev/null +++ b/builtin/providers/google/import_dns_managed_zone_test.go @@ -0,0 +1,28 @@ +package google + +import ( + "testing" + + "github.com/hashicorp/terraform/helper/resource" +) + +func TestAccDnsManagedZone_importBasic(t *testing.T) { + resourceName := "google_dns_managed_zone.foobar" + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckDnsManagedZoneDestroy, + Steps: []resource.TestStep{ + resource.TestStep{ + Config: testAccDnsManagedZone_basic, + }, + + resource.TestStep{ + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} diff --git a/builtin/providers/google/provider.go b/builtin/providers/google/provider.go index 7562609c3..557450729 100644 --- a/builtin/providers/google/provider.go +++ b/builtin/providers/google/provider.go @@ -3,6 +3,7 @@ package google import ( "encoding/json" "fmt" + "log" "strings" "github.com/hashicorp/terraform/helper/schema" @@ -48,15 +49,22 @@ func Provider() terraform.ResourceProvider { }, DataSourcesMap: map[string]*schema.Resource{ - "google_iam_policy": dataSourceGoogleIamPolicy(), - "google_compute_zones": dataSourceGoogleComputeZones(), + "google_compute_network": dataSourceGoogleComputeNetwork(), + "google_compute_subnetwork": dataSourceGoogleComputeSubnetwork(), + "google_compute_zones": dataSourceGoogleComputeZones(), + "google_container_engine_versions": dataSourceGoogleContainerEngineVersions(), + "google_iam_policy": dataSourceGoogleIamPolicy(), }, ResourcesMap: map[string]*schema.Resource{ + "google_bigquery_dataset": resourceBigQueryDataset(), + "google_bigquery_table": resourceBigQueryTable(), "google_compute_autoscaler": resourceComputeAutoscaler(), "google_compute_address": resourceComputeAddress(), + "google_compute_backend_bucket": resourceComputeBackendBucket(), "google_compute_backend_service": resourceComputeBackendService(), "google_compute_disk": resourceComputeDisk(), + "google_compute_snapshot": resourceComputeSnapshot(), "google_compute_firewall": resourceComputeFirewall(), "google_compute_forwarding_rule": resourceComputeForwardingRule(), "google_compute_global_address": resourceComputeGlobalAddress(), @@ -246,3 +254,15 @@ func getNetworkNameFromSelfLink(network string) (string, error) { return network, nil } + +func handleNotFoundError(err error, d *schema.ResourceData, resource string) error { + if gerr, ok := err.(*googleapi.Error); ok && gerr.Code == 404 { + log.Printf("[WARN] Removing %s because it's gone", resource) + // The resource doesn't exist anymore + d.SetId("") + + return nil + } + + return fmt.Errorf("Error reading %s: %s", resource, err) +} diff --git a/builtin/providers/google/resource_bigquery_dataset.go b/builtin/providers/google/resource_bigquery_dataset.go new file mode 100644 index 000000000..8080b8dbc --- /dev/null +++ b/builtin/providers/google/resource_bigquery_dataset.go @@ -0,0 +1,276 @@ +package google + +import ( + "fmt" + "log" + "regexp" + "strings" + + "github.com/hashicorp/terraform/helper/schema" + "github.com/hashicorp/terraform/helper/validation" + "google.golang.org/api/bigquery/v2" +) + +func resourceBigQueryDataset() *schema.Resource { + return &schema.Resource{ + Create: resourceBigQueryDatasetCreate, + Read: resourceBigQueryDatasetRead, + Update: resourceBigQueryDatasetUpdate, + Delete: resourceBigQueryDatasetDelete, + Importer: &schema.ResourceImporter{ + State: schema.ImportStatePassthrough, + }, + Schema: map[string]*schema.Schema{ + // DatasetId: [Required] A unique ID for this dataset, without the + // project name. The ID must contain only letters (a-z, A-Z), numbers + // (0-9), or underscores (_). The maximum length is 1,024 characters. + "dataset_id": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + ValidateFunc: func(v interface{}, k string) (ws []string, errors []error) { + value := v.(string) + if !regexp.MustCompile(`^[0-9A-Za-z_]+$`).MatchString(value) { + errors = append(errors, fmt.Errorf( + "%q must contain only letters (a-z, A-Z), numbers (0-9), or underscores (_)", k)) + } + + if len(value) > 1024 { + errors = append(errors, fmt.Errorf( + "%q cannot be greater than 1,024 characters", k)) + } + + return + }, + }, + + // ProjectId: [Optional] The ID of the project containing this dataset. + "project": { + Type: schema.TypeString, + Optional: true, + ForceNew: true, + }, + + // FriendlyName: [Optional] A descriptive name for the dataset. + "friendly_name": { + Type: schema.TypeString, + Optional: true, + }, + + // Description: [Optional] A user-friendly description of the dataset. + "description": { + Type: schema.TypeString, + Optional: true, + }, + + // Location: [Experimental] The geographic location where the dataset + // should reside. Possible values include EU and US. The default value + // is US. + "location": { + Type: schema.TypeString, + Optional: true, + ForceNew: true, + Default: "US", + ValidateFunc: validation.StringInSlice([]string{"US", "EU"}, false), + }, + + // DefaultTableExpirationMs: [Optional] The default lifetime of all + // tables in the dataset, in milliseconds. The minimum value is 3600000 + // milliseconds (one hour). Once this property is set, all newly-created + // tables in the dataset will have an expirationTime property set to the + // creation time plus the value in this property, and changing the value + // will only affect new tables, not existing ones. When the + // expirationTime for a given table is reached, that table will be + // deleted automatically. If a table's expirationTime is modified or + // removed before the table expires, or if you provide an explicit + // expirationTime when creating a table, that value takes precedence + // over the default expiration time indicated by this property. + "default_table_expiration_ms": { + Type: schema.TypeInt, + Optional: true, + ValidateFunc: func(v interface{}, k string) (ws []string, errors []error) { + value := v.(int) + if value < 3600000 { + errors = append(errors, fmt.Errorf("%q cannot be shorter than 3600000 milliseconds (one hour)", k)) + } + + return + }, + }, + + // Labels: [Experimental] The labels associated with this dataset. You + // can use these to organize and group your datasets. You can set this + // property when inserting or updating a dataset. + "labels": &schema.Schema{ + Type: schema.TypeMap, + Optional: true, + Elem: schema.TypeString, + }, + + // SelfLink: [Output-only] A URL that can be used to access the resource + // again. You can use this URL in Get or Update requests to the + // resource. + "self_link": { + Type: schema.TypeString, + Computed: true, + }, + + // Etag: [Output-only] A hash of the resource. + "etag": { + Type: schema.TypeString, + Computed: true, + }, + + // CreationTime: [Output-only] The time when this dataset was created, + // in milliseconds since the epoch. + "creation_time": { + Type: schema.TypeInt, + Computed: true, + }, + + // LastModifiedTime: [Output-only] The date when this dataset or any of + // its tables was last modified, in milliseconds since the epoch. + "last_modified_time": { + Type: schema.TypeInt, + Computed: true, + }, + }, + } +} + +func resourceDataset(d *schema.ResourceData, meta interface{}) (*bigquery.Dataset, error) { + config := meta.(*Config) + + project, err := getProject(d, config) + if err != nil { + return nil, err + } + + dataset := &bigquery.Dataset{ + DatasetReference: &bigquery.DatasetReference{ + DatasetId: d.Get("dataset_id").(string), + ProjectId: project, + }, + } + + if v, ok := d.GetOk("friendly_name"); ok { + dataset.FriendlyName = v.(string) + } + + if v, ok := d.GetOk("description"); ok { + dataset.Description = v.(string) + } + + if v, ok := d.GetOk("location"); ok { + dataset.Location = v.(string) + } + + if v, ok := d.GetOk("default_table_expiration_ms"); ok { + dataset.DefaultTableExpirationMs = int64(v.(int)) + } + + if v, ok := d.GetOk("labels"); ok { + labels := map[string]string{} + + for k, v := range v.(map[string]interface{}) { + labels[k] = v.(string) + } + + dataset.Labels = labels + } + + return dataset, nil +} + +func resourceBigQueryDatasetCreate(d *schema.ResourceData, meta interface{}) error { + config := meta.(*Config) + + project, err := getProject(d, config) + if err != nil { + return err + } + + dataset, err := resourceDataset(d, meta) + if err != nil { + return err + } + + log.Printf("[INFO] Creating BigQuery dataset: %s", dataset.DatasetReference.DatasetId) + + res, err := config.clientBigQuery.Datasets.Insert(project, dataset).Do() + if err != nil { + return err + } + + log.Printf("[INFO] BigQuery dataset %s has been created", res.Id) + + d.SetId(res.Id) + + return resourceBigQueryDatasetRead(d, meta) +} + +func resourceBigQueryDatasetParseID(id string) (string, string) { + // projectID, datasetID + parts := strings.Split(id, ":") + return parts[0], parts[1] +} + +func resourceBigQueryDatasetRead(d *schema.ResourceData, meta interface{}) error { + config := meta.(*Config) + + log.Printf("[INFO] Reading BigQuery dataset: %s", d.Id()) + + projectID, datasetID := resourceBigQueryDatasetParseID(d.Id()) + + res, err := config.clientBigQuery.Datasets.Get(projectID, datasetID).Do() + if err != nil { + return handleNotFoundError(err, d, fmt.Sprintf("BigQuery dataset %q", datasetID)) + } + + d.Set("etag", res.Etag) + d.Set("labels", res.Labels) + d.Set("location", res.Location) + d.Set("self_link", res.SelfLink) + d.Set("description", res.Description) + d.Set("friendly_name", res.FriendlyName) + d.Set("creation_time", res.CreationTime) + d.Set("last_modified_time", res.LastModifiedTime) + d.Set("dataset_id", res.DatasetReference.DatasetId) + d.Set("default_table_expiration_ms", res.DefaultTableExpirationMs) + + return nil +} + +func resourceBigQueryDatasetUpdate(d *schema.ResourceData, meta interface{}) error { + config := meta.(*Config) + + dataset, err := resourceDataset(d, meta) + if err != nil { + return err + } + + log.Printf("[INFO] Updating BigQuery dataset: %s", d.Id()) + + projectID, datasetID := resourceBigQueryDatasetParseID(d.Id()) + + if _, err = config.clientBigQuery.Datasets.Update(projectID, datasetID, dataset).Do(); err != nil { + return err + } + + return resourceBigQueryDatasetRead(d, meta) +} + +func resourceBigQueryDatasetDelete(d *schema.ResourceData, meta interface{}) error { + config := meta.(*Config) + + log.Printf("[INFO] Deleting BigQuery dataset: %s", d.Id()) + + projectID, datasetID := resourceBigQueryDatasetParseID(d.Id()) + + if err := config.clientBigQuery.Datasets.Delete(projectID, datasetID).Do(); err != nil { + return err + } + + d.SetId("") + return nil +} diff --git a/builtin/providers/google/resource_bigquery_dataset_test.go b/builtin/providers/google/resource_bigquery_dataset_test.go new file mode 100644 index 000000000..e1032ce91 --- /dev/null +++ b/builtin/providers/google/resource_bigquery_dataset_test.go @@ -0,0 +1,112 @@ +package google + +import ( + "fmt" + "testing" + + "github.com/hashicorp/terraform/helper/acctest" + "github.com/hashicorp/terraform/helper/resource" + "github.com/hashicorp/terraform/terraform" +) + +func TestAccBigQueryDataset_basic(t *testing.T) { + datasetID := fmt.Sprintf("tf_test_%s", acctest.RandString(10)) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckBigQueryDatasetDestroy, + Steps: []resource.TestStep{ + { + Config: testAccBigQueryDataset(datasetID), + Check: resource.ComposeTestCheckFunc( + testAccCheckBigQueryDatasetExists( + "google_bigquery_dataset.test"), + ), + }, + + { + Config: testAccBigQueryDatasetUpdated(datasetID), + Check: resource.ComposeTestCheckFunc( + testAccCheckBigQueryDatasetExists( + "google_bigquery_dataset.test"), + ), + }, + }, + }) +} + +func testAccCheckBigQueryDatasetDestroy(s *terraform.State) error { + config := testAccProvider.Meta().(*Config) + + for _, rs := range s.RootModule().Resources { + if rs.Type != "google_bigquery_dataset" { + continue + } + + _, err := config.clientBigQuery.Datasets.Get(config.Project, rs.Primary.Attributes["dataset_id"]).Do() + if err == nil { + return fmt.Errorf("Dataset still exists") + } + } + + return nil +} + +func testAccCheckBigQueryDatasetExists(n string) resource.TestCheckFunc { + return func(s *terraform.State) error { + rs, ok := s.RootModule().Resources[n] + if !ok { + return fmt.Errorf("Not found: %s", n) + } + + if rs.Primary.ID == "" { + return fmt.Errorf("No ID is set") + } + + config := testAccProvider.Meta().(*Config) + + found, err := config.clientBigQuery.Datasets.Get(config.Project, rs.Primary.Attributes["dataset_id"]).Do() + if err != nil { + return err + } + + if found.Id != rs.Primary.ID { + return fmt.Errorf("Dataset not found") + } + + return nil + } +} + +func testAccBigQueryDataset(datasetID string) string { + return fmt.Sprintf(` +resource "google_bigquery_dataset" "test" { + dataset_id = "%s" + friendly_name = "foo" + description = "This is a foo description" + location = "EU" + default_table_expiration_ms = 3600000 + + labels { + env = "foo" + default_table_expiration_ms = 3600000 + } +}`, datasetID) +} + +func testAccBigQueryDatasetUpdated(datasetID string) string { + return fmt.Sprintf(` +resource "google_bigquery_dataset" "test" { + dataset_id = "%s" + friendly_name = "bar" + description = "This is a bar description" + location = "EU" + default_table_expiration_ms = 7200000 + + labels { + env = "bar" + default_table_expiration_ms = 7200000 + } +}`, datasetID) +} diff --git a/builtin/providers/google/resource_bigquery_table.go b/builtin/providers/google/resource_bigquery_table.go new file mode 100644 index 000000000..298152a86 --- /dev/null +++ b/builtin/providers/google/resource_bigquery_table.go @@ -0,0 +1,396 @@ +package google + +import ( + "encoding/json" + "fmt" + "log" + "strings" + + "github.com/hashicorp/terraform/helper/schema" + "github.com/hashicorp/terraform/helper/structure" + "github.com/hashicorp/terraform/helper/validation" + "google.golang.org/api/bigquery/v2" +) + +func resourceBigQueryTable() *schema.Resource { + return &schema.Resource{ + Create: resourceBigQueryTableCreate, + Read: resourceBigQueryTableRead, + Delete: resourceBigQueryTableDelete, + Update: resourceBigQueryTableUpdate, + Importer: &schema.ResourceImporter{ + State: schema.ImportStatePassthrough, + }, + Schema: map[string]*schema.Schema{ + // TableId: [Required] The ID of the table. The ID must contain only + // letters (a-z, A-Z), numbers (0-9), or underscores (_). The maximum + // length is 1,024 characters. + "table_id": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + + // DatasetId: [Required] The ID of the dataset containing this table. + "dataset_id": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + + // ProjectId: [Required] The ID of the project containing this table. + "project": { + Type: schema.TypeString, + Optional: true, + ForceNew: true, + }, + + // Description: [Optional] A user-friendly description of this table. + "description": { + Type: schema.TypeString, + Optional: true, + }, + + // ExpirationTime: [Optional] The time when this table expires, in + // milliseconds since the epoch. If not present, the table will persist + // indefinitely. Expired tables will be deleted and their storage + // reclaimed. + "expiration_time": { + Type: schema.TypeInt, + Optional: true, + Computed: true, + }, + + // FriendlyName: [Optional] A descriptive name for this table. + "friendly_name": { + Type: schema.TypeString, + Optional: true, + }, + + // Labels: [Experimental] The labels associated with this table. You can + // use these to organize and group your tables. Label keys and values + // can be no longer than 63 characters, can only contain lowercase + // letters, numeric characters, underscores and dashes. International + // characters are allowed. Label values are optional. Label keys must + // start with a letter and each label in the list must have a different + // key. + "labels": &schema.Schema{ + Type: schema.TypeMap, + Optional: true, + Elem: schema.TypeString, + }, + + // Schema: [Optional] Describes the schema of this table. + "schema": { + Type: schema.TypeString, + Optional: true, + Computed: true, + ValidateFunc: validation.ValidateJsonString, + StateFunc: func(v interface{}) string { + json, _ := structure.NormalizeJsonString(v) + return json + }, + }, + + // TimePartitioning: [Experimental] If specified, configures time-based + // partitioning for this table. + "time_partitioning": &schema.Schema{ + Type: schema.TypeList, + Optional: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + // ExpirationMs: [Optional] Number of milliseconds for which to keep the + // storage for a partition. + "expiration_ms": { + Type: schema.TypeInt, + Optional: true, + }, + + // Type: [Required] The only type supported is DAY, which will generate + // one partition per day based on data loading time. + "type": { + Type: schema.TypeString, + Required: true, + ValidateFunc: validation.StringInSlice([]string{"DAY"}, false), + }, + }, + }, + }, + + // CreationTime: [Output-only] The time when this table was created, in + // milliseconds since the epoch. + "creation_time": { + Type: schema.TypeInt, + Computed: true, + }, + + // Etag: [Output-only] A hash of this resource. + "etag": { + Type: schema.TypeString, + Computed: true, + }, + + // LastModifiedTime: [Output-only] The time when this table was last + // modified, in milliseconds since the epoch. + "last_modified_time": { + Type: schema.TypeInt, + Computed: true, + }, + + // Location: [Output-only] The geographic location where the table + // resides. This value is inherited from the dataset. + "location": { + Type: schema.TypeString, + Computed: true, + }, + + // NumBytes: [Output-only] The size of this table in bytes, excluding + // any data in the streaming buffer. + "num_bytes": { + Type: schema.TypeInt, + Computed: true, + }, + + // NumLongTermBytes: [Output-only] The number of bytes in the table that + // are considered "long-term storage". + "num_long_term_bytes": { + Type: schema.TypeInt, + Computed: true, + }, + + // NumRows: [Output-only] The number of rows of data in this table, + // excluding any data in the streaming buffer. + "num_rows": { + Type: schema.TypeInt, + Computed: true, + }, + + // SelfLink: [Output-only] A URL that can be used to access this + // resource again. + "self_link": { + Type: schema.TypeString, + Computed: true, + }, + + // Type: [Output-only] Describes the table type. The following values + // are supported: TABLE: A normal BigQuery table. VIEW: A virtual table + // defined by a SQL query. EXTERNAL: A table that references data stored + // in an external storage system, such as Google Cloud Storage. The + // default value is TABLE. + "type": { + Type: schema.TypeString, + Computed: true, + }, + }, + } +} + +func resourceTable(d *schema.ResourceData, meta interface{}) (*bigquery.Table, error) { + config := meta.(*Config) + + project, err := getProject(d, config) + if err != nil { + return nil, err + } + + table := &bigquery.Table{ + TableReference: &bigquery.TableReference{ + DatasetId: d.Get("dataset_id").(string), + TableId: d.Get("table_id").(string), + ProjectId: project, + }, + } + + if v, ok := d.GetOk("description"); ok { + table.Description = v.(string) + } + + if v, ok := d.GetOk("expiration_time"); ok { + table.ExpirationTime = v.(int64) + } + + if v, ok := d.GetOk("friendly_name"); ok { + table.FriendlyName = v.(string) + } + + if v, ok := d.GetOk("labels"); ok { + labels := map[string]string{} + + for k, v := range v.(map[string]interface{}) { + labels[k] = v.(string) + } + + table.Labels = labels + } + + if v, ok := d.GetOk("schema"); ok { + schema, err := expandSchema(v) + if err != nil { + return nil, err + } + + table.Schema = schema + } + + if v, ok := d.GetOk("time_partitioning"); ok { + table.TimePartitioning = expandTimePartitioning(v) + } + + return table, nil +} + +func resourceBigQueryTableCreate(d *schema.ResourceData, meta interface{}) error { + config := meta.(*Config) + + project, err := getProject(d, config) + if err != nil { + return err + } + + table, err := resourceTable(d, meta) + if err != nil { + return err + } + + datasetID := d.Get("dataset_id").(string) + + log.Printf("[INFO] Creating BigQuery table: %s", table.TableReference.TableId) + + res, err := config.clientBigQuery.Tables.Insert(project, datasetID, table).Do() + if err != nil { + return err + } + + log.Printf("[INFO] BigQuery table %s has been created", res.Id) + + d.SetId(fmt.Sprintf("%s:%s.%s", res.TableReference.ProjectId, res.TableReference.DatasetId, res.TableReference.TableId)) + + return resourceBigQueryTableRead(d, meta) +} + +func resourceBigQueryTableParseID(id string) (string, string, string) { + parts := strings.FieldsFunc(id, func(r rune) bool { return r == ':' || r == '.' }) + return parts[0], parts[1], parts[2] // projectID, datasetID, tableID +} + +func resourceBigQueryTableRead(d *schema.ResourceData, meta interface{}) error { + config := meta.(*Config) + + log.Printf("[INFO] Reading BigQuery table: %s", d.Id()) + + projectID, datasetID, tableID := resourceBigQueryTableParseID(d.Id()) + + res, err := config.clientBigQuery.Tables.Get(projectID, datasetID, tableID).Do() + if err != nil { + return handleNotFoundError(err, d, fmt.Sprintf("BigQuery table %q", tableID)) + } + + d.Set("description", res.Description) + d.Set("expiration_time", res.ExpirationTime) + d.Set("friendly_name", res.FriendlyName) + d.Set("labels", res.Labels) + d.Set("creation_time", res.CreationTime) + d.Set("etag", res.Etag) + d.Set("last_modified_time", res.LastModifiedTime) + d.Set("location", res.Location) + d.Set("num_bytes", res.NumBytes) + d.Set("table_id", res.TableReference.TableId) + d.Set("dataset_id", res.TableReference.DatasetId) + d.Set("num_long_term_bytes", res.NumLongTermBytes) + d.Set("num_rows", res.NumRows) + d.Set("self_link", res.SelfLink) + d.Set("type", res.Type) + + if res.TimePartitioning != nil { + if err := d.Set("time_partitioning", flattenTimePartitioning(res.TimePartitioning)); err != nil { + return err + } + } + + if res.Schema != nil { + schema, err := flattenSchema(res.Schema) + if err != nil { + return err + } + + d.Set("schema", schema) + } + + return nil +} + +func resourceBigQueryTableUpdate(d *schema.ResourceData, meta interface{}) error { + config := meta.(*Config) + + table, err := resourceTable(d, meta) + if err != nil { + return err + } + + log.Printf("[INFO] Updating BigQuery table: %s", d.Id()) + + projectID, datasetID, tableID := resourceBigQueryTableParseID(d.Id()) + + if _, err = config.clientBigQuery.Tables.Update(projectID, datasetID, tableID, table).Do(); err != nil { + return err + } + + return resourceBigQueryTableRead(d, meta) +} + +func resourceBigQueryTableDelete(d *schema.ResourceData, meta interface{}) error { + config := meta.(*Config) + + log.Printf("[INFO] Deleting BigQuery table: %s", d.Id()) + + projectID, datasetID, tableID := resourceBigQueryTableParseID(d.Id()) + + if err := config.clientBigQuery.Tables.Delete(projectID, datasetID, tableID).Do(); err != nil { + return err + } + + d.SetId("") + + return nil +} + +func expandSchema(raw interface{}) (*bigquery.TableSchema, error) { + var fields []*bigquery.TableFieldSchema + + if err := json.Unmarshal([]byte(raw.(string)), &fields); err != nil { + return nil, err + } + + return &bigquery.TableSchema{Fields: fields}, nil +} + +func flattenSchema(tableSchema *bigquery.TableSchema) (string, error) { + schema, err := json.Marshal(tableSchema.Fields) + if err != nil { + return "", err + } + + return string(schema), nil +} + +func expandTimePartitioning(configured interface{}) *bigquery.TimePartitioning { + raw := configured.([]interface{})[0].(map[string]interface{}) + tp := &bigquery.TimePartitioning{Type: raw["type"].(string)} + + if v, ok := raw["expiration_ms"]; ok { + tp.ExpirationMs = int64(v.(int)) + } + + return tp +} + +func flattenTimePartitioning(tp *bigquery.TimePartitioning) []map[string]interface{} { + result := map[string]interface{}{"type": tp.Type} + + if tp.ExpirationMs != 0 { + result["expiration_ms"] = tp.ExpirationMs + } + + return []map[string]interface{}{result} +} diff --git a/builtin/providers/google/resource_bigquery_table_test.go b/builtin/providers/google/resource_bigquery_table_test.go new file mode 100644 index 000000000..f01b7e0f4 --- /dev/null +++ b/builtin/providers/google/resource_bigquery_table_test.go @@ -0,0 +1,174 @@ +package google + +import ( + "fmt" + "testing" + + "github.com/hashicorp/terraform/helper/acctest" + "github.com/hashicorp/terraform/helper/resource" + "github.com/hashicorp/terraform/terraform" +) + +func TestAccBigQueryTable_Basic(t *testing.T) { + datasetID := fmt.Sprintf("tf_test_%s", acctest.RandString(10)) + tableID := fmt.Sprintf("tf_test_%s", acctest.RandString(10)) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckBigQueryTableDestroy, + Steps: []resource.TestStep{ + { + Config: testAccBigQueryTable(datasetID, tableID), + Check: resource.ComposeTestCheckFunc( + testAccBigQueryTableExists( + "google_bigquery_table.test"), + ), + }, + + { + Config: testAccBigQueryTableUpdated(datasetID, tableID), + Check: resource.ComposeTestCheckFunc( + testAccBigQueryTableExists( + "google_bigquery_table.test"), + ), + }, + }, + }) +} + +func testAccCheckBigQueryTableDestroy(s *terraform.State) error { + for _, rs := range s.RootModule().Resources { + if rs.Type != "google_bigquery_table" { + continue + } + + config := testAccProvider.Meta().(*Config) + _, err := config.clientBigQuery.Tables.Get(config.Project, rs.Primary.Attributes["dataset_id"], rs.Primary.Attributes["name"]).Do() + if err == nil { + return fmt.Errorf("Table still present") + } + } + + return nil +} + +func testAccBigQueryTableExists(n string) resource.TestCheckFunc { + return func(s *terraform.State) error { + rs, ok := s.RootModule().Resources[n] + if !ok { + return fmt.Errorf("Not found: %s", n) + } + + if rs.Primary.ID == "" { + return fmt.Errorf("No ID is set") + } + config := testAccProvider.Meta().(*Config) + _, err := config.clientBigQuery.Tables.Get(config.Project, rs.Primary.Attributes["dataset_id"], rs.Primary.Attributes["name"]).Do() + if err != nil { + return fmt.Errorf("BigQuery Table not present") + } + + return nil + } +} + +func testAccBigQueryTable(datasetID, tableID string) string { + return fmt.Sprintf(` +resource "google_bigquery_dataset" "test" { + dataset_id = "%s" +} + +resource "google_bigquery_table" "test" { + table_id = "%s" + dataset_id = "${google_bigquery_dataset.test.dataset_id}" + + time_partitioning { + type = "DAY" + } + + schema = < 0 { - return fmt.Errorf("Error, metadata items still exist") + for _, rs := range s.RootModule().Resources { + if rs.Type != "google_compute_project_metadata" { + continue + } + + project, err := config.clientCompute.Projects.Get(rs.Primary.ID).Do() + if err == nil && len(project.CommonInstanceMetadata.Items) > 0 { + return fmt.Errorf("Error, metadata items still exist in %s", rs.Primary.ID) + } } return nil } -func testAccCheckComputeProjectExists(n string, project *compute.Project) resource.TestCheckFunc { +func testAccCheckComputeProjectExists(n, projectID string, project *compute.Project) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[n] if !ok { @@ -126,8 +161,7 @@ func testAccCheckComputeProjectExists(n string, project *compute.Project) resour config := testAccProvider.Meta().(*Config) - found, err := config.clientCompute.Projects.Get( - config.Project).Do() + found, err := config.clientCompute.Projects.Get(projectID).Do() if err != nil { return err } @@ -142,10 +176,10 @@ func testAccCheckComputeProjectExists(n string, project *compute.Project) resour } } -func testAccCheckComputeProjectMetadataContains(project *compute.Project, key string, value string) resource.TestCheckFunc { +func testAccCheckComputeProjectMetadataContains(projectID, key, value string) resource.TestCheckFunc { return func(s *terraform.State) error { config := testAccProvider.Meta().(*Config) - project, err := config.clientCompute.Projects.Get(config.Project).Do() + project, err := config.clientCompute.Projects.Get(projectID).Do() if err != nil { return fmt.Errorf("Error, failed to load project service for %s: %s", config.Project, err) } @@ -161,14 +195,14 @@ func testAccCheckComputeProjectMetadataContains(project *compute.Project, key st } } - return fmt.Errorf("Error, key %s not present", key) + return fmt.Errorf("Error, key %s not present in %s", key, project.SelfLink) } } -func testAccCheckComputeProjectMetadataSize(project *compute.Project, size int) resource.TestCheckFunc { +func testAccCheckComputeProjectMetadataSize(projectID string, size int) resource.TestCheckFunc { return func(s *terraform.State) error { config := testAccProvider.Meta().(*Config) - project, err := config.clientCompute.Projects.Get(config.Project).Do() + project, err := config.clientCompute.Projects.Get(projectID).Do() if err != nil { return fmt.Errorf("Error, failed to load project service for %s: %s", config.Project, err) } @@ -182,36 +216,100 @@ func testAccCheckComputeProjectMetadataSize(project *compute.Project, size int) } } -const testAccComputeProject_basic0_metadata = ` -resource "google_compute_project_metadata" "fizzbuzz" { - metadata { - banana = "orange" - sofa = "darwinism" - } -}` +func testAccComputeProject_basic0_metadata(projectID, name, org, billing string) string { + return fmt.Sprintf(` +resource "google_project" "project" { + project_id = "%s" + name = "%s" + org_id = "%s" + billing_account = "%s" +} -const testAccComputeProject_basic1_metadata = ` -resource "google_compute_project_metadata" "fizzbuzz" { - metadata { - kiwi = "papaya" - finches = "darwinism" - } -}` +resource "google_project_services" "services" { + project = "${google_project.project.project_id}" + services = ["compute-component.googleapis.com"] +} -const testAccComputeProject_modify0_metadata = ` resource "google_compute_project_metadata" "fizzbuzz" { - metadata { - paper = "pen" - genghis_khan = "french bread" - happy = "smiling" - } -}` + project = "${google_project.project.project_id}" + metadata { + banana = "orange" + sofa = "darwinism" + } + depends_on = ["google_project_services.services"] +}`, projectID, name, org, billing) +} + +func testAccComputeProject_basic1_metadata(projectID, name, org, billing string) string { + return fmt.Sprintf(` +resource "google_project" "project" { + project_id = "%s" + name = "%s" + org_id = "%s" + billing_account = "%s" +} + +resource "google_project_services" "services" { + project = "${google_project.project.project_id}" + services = ["compute-component.googleapis.com"] +} -const testAccComputeProject_modify1_metadata = ` resource "google_compute_project_metadata" "fizzbuzz" { - metadata { - paper = "pen" - paris = "french bread" - happy = "laughing" - } -}` + project = "${google_project.project.project_id}" + metadata { + kiwi = "papaya" + finches = "darwinism" + } + depends_on = ["google_project_services.services"] +}`, projectID, name, org, billing) +} + +func testAccComputeProject_modify0_metadata(projectID, name, org, billing string) string { + return fmt.Sprintf(` +resource "google_project" "project" { + project_id = "%s" + name = "%s" + org_id = "%s" + billing_account = "%s" +} + +resource "google_project_services" "services" { + project = "${google_project.project.project_id}" + services = ["compute-component.googleapis.com"] +} + +resource "google_compute_project_metadata" "fizzbuzz" { + project = "${google_project.project.project_id}" + metadata { + paper = "pen" + genghis_khan = "french bread" + happy = "smiling" + } + depends_on = ["google_project_services.services"] +}`, projectID, name, org, billing) +} + +func testAccComputeProject_modify1_metadata(projectID, name, org, billing string) string { + return fmt.Sprintf(` +resource "google_project" "project" { + project_id = "%s" + name = "%s" + org_id = "%s" + billing_account = "%s" +} + +resource "google_project_services" "services" { + project = "${google_project.project.project_id}" + services = ["compute-component.googleapis.com"] +} + +resource "google_compute_project_metadata" "fizzbuzz" { + project = "${google_project.project.project_id}" + metadata { + paper = "pen" + paris = "french bread" + happy = "laughing" + } + depends_on = ["google_project_services.services"] +}`, projectID, name, org, billing) +} diff --git a/builtin/providers/google/resource_compute_region_backend_service.go b/builtin/providers/google/resource_compute_region_backend_service.go index 8fd3950f7..682cd0fab 100644 --- a/builtin/providers/google/resource_compute_region_backend_service.go +++ b/builtin/providers/google/resource_compute_region_backend_service.go @@ -9,7 +9,6 @@ import ( "github.com/hashicorp/terraform/helper/hashcode" "github.com/hashicorp/terraform/helper/schema" "google.golang.org/api/compute/v1" - "google.golang.org/api/googleapi" ) func resourceComputeRegionBackendService() *schema.Resource { @@ -189,15 +188,7 @@ func resourceComputeRegionBackendServiceRead(d *schema.ResourceData, meta interf service, err := config.clientCompute.RegionBackendServices.Get( project, region, d.Id()).Do() if err != nil { - if gerr, ok := err.(*googleapi.Error); ok && gerr.Code == 404 { - // The resource doesn't exist anymore - log.Printf("[WARN] Removing Backend Service %q because it's gone", d.Get("name").(string)) - d.SetId("") - - return nil - } - - return fmt.Errorf("Error reading service: %s", err) + return handleNotFoundError(err, d, fmt.Sprintf("Region Backend Service %q", d.Get("name").(string))) } d.Set("description", service.Description) diff --git a/builtin/providers/google/resource_compute_route.go b/builtin/providers/google/resource_compute_route.go index ac5760f96..90b5a2e8b 100644 --- a/builtin/providers/google/resource_compute_route.go +++ b/builtin/providers/google/resource_compute_route.go @@ -6,7 +6,6 @@ import ( "github.com/hashicorp/terraform/helper/schema" "google.golang.org/api/compute/v1" - "google.golang.org/api/googleapi" ) func resourceComputeRoute() *schema.Resource { @@ -14,6 +13,9 @@ func resourceComputeRoute() *schema.Resource { Create: resourceComputeRouteCreate, Read: resourceComputeRouteRead, Delete: resourceComputeRouteDelete, + Importer: &schema.ResourceImporter{ + State: schema.ImportStatePassthrough, + }, Schema: map[string]*schema.Schema{ "dest_range": &schema.Schema{ @@ -189,15 +191,7 @@ func resourceComputeRouteRead(d *schema.ResourceData, meta interface{}) error { route, err := config.clientCompute.Routes.Get( project, d.Id()).Do() if err != nil { - if gerr, ok := err.(*googleapi.Error); ok && gerr.Code == 404 { - log.Printf("[WARN] Removing Route %q because it's gone", d.Get("name").(string)) - // The resource doesn't exist anymore - d.SetId("") - - return nil - } - - return fmt.Errorf("Error reading route: %#v", err) + return handleNotFoundError(err, d, fmt.Sprintf("Route %q", d.Get("name").(string))) } d.Set("next_hop_network", route.NextHopNetwork) diff --git a/builtin/providers/google/resource_compute_snapshot.go b/builtin/providers/google/resource_compute_snapshot.go new file mode 100644 index 000000000..794d98904 --- /dev/null +++ b/builtin/providers/google/resource_compute_snapshot.go @@ -0,0 +1,202 @@ +package google + +import ( + "fmt" + "log" + + "github.com/hashicorp/terraform/helper/schema" + "google.golang.org/api/compute/v1" + "google.golang.org/api/googleapi" +) + +func resourceComputeSnapshot() *schema.Resource { + return &schema.Resource{ + Create: resourceComputeSnapshotCreate, + Read: resourceComputeSnapshotRead, + Delete: resourceComputeSnapshotDelete, + Exists: resourceComputeSnapshotExists, + + Schema: map[string]*schema.Schema{ + "name": &schema.Schema{ + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + + "zone": &schema.Schema{ + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + + "snapshot_encryption_key_raw": &schema.Schema{ + Type: schema.TypeString, + Optional: true, + ForceNew: true, + Sensitive: true, + }, + + "snapshot_encryption_key_sha256": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + }, + + "source_disk_encryption_key_raw": &schema.Schema{ + Type: schema.TypeString, + Optional: true, + ForceNew: true, + Sensitive: true, + }, + + "source_disk_encryption_key_sha256": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + }, + + "source_disk": &schema.Schema{ + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + + "source_disk_link": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + }, + + "project": &schema.Schema{ + Type: schema.TypeString, + Optional: true, + ForceNew: true, + }, + + "self_link": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + }, + }, + } +} + +func resourceComputeSnapshotCreate(d *schema.ResourceData, meta interface{}) error { + config := meta.(*Config) + + project, err := getProject(d, config) + if err != nil { + return err + } + + // Build the snapshot parameter + snapshot := &compute.Snapshot{ + Name: d.Get("name").(string), + } + + source_disk := d.Get("source_disk").(string) + + if v, ok := d.GetOk("snapshot_encryption_key_raw"); ok { + snapshot.SnapshotEncryptionKey = &compute.CustomerEncryptionKey{} + snapshot.SnapshotEncryptionKey.RawKey = v.(string) + } + + if v, ok := d.GetOk("source_disk_encryption_key_raw"); ok { + snapshot.SourceDiskEncryptionKey = &compute.CustomerEncryptionKey{} + snapshot.SourceDiskEncryptionKey.RawKey = v.(string) + } + + op, err := config.clientCompute.Disks.CreateSnapshot( + project, d.Get("zone").(string), source_disk, snapshot).Do() + if err != nil { + return fmt.Errorf("Error creating snapshot: %s", err) + } + + // It probably maybe worked, so store the ID now + d.SetId(snapshot.Name) + + err = computeOperationWaitZone(config, op, project, d.Get("zone").(string), "Creating Snapshot") + if err != nil { + return err + } + return resourceComputeSnapshotRead(d, meta) +} + +func resourceComputeSnapshotRead(d *schema.ResourceData, meta interface{}) error { + config := meta.(*Config) + + project, err := getProject(d, config) + if err != nil { + return err + } + + snapshot, err := config.clientCompute.Snapshots.Get( + project, d.Id()).Do() + if err != nil { + return handleNotFoundError(err, d, fmt.Sprintf("Snapshot %q", d.Get("name").(string))) + } + + d.Set("self_link", snapshot.SelfLink) + d.Set("source_disk_link", snapshot.SourceDisk) + d.Set("name", snapshot.Name) + + if snapshot.SnapshotEncryptionKey != nil && snapshot.SnapshotEncryptionKey.Sha256 != "" { + d.Set("snapshot_encryption_key_sha256", snapshot.SnapshotEncryptionKey.Sha256) + } + + if snapshot.SourceDiskEncryptionKey != nil && snapshot.SourceDiskEncryptionKey.Sha256 != "" { + d.Set("source_disk_encryption_key_sha256", snapshot.SourceDiskEncryptionKey.Sha256) + } + + return nil +} + +func resourceComputeSnapshotDelete(d *schema.ResourceData, meta interface{}) error { + config := meta.(*Config) + + project, err := getProject(d, config) + if err != nil { + return err + } + + // Delete the snapshot + op, err := config.clientCompute.Snapshots.Delete( + project, d.Id()).Do() + if err != nil { + if gerr, ok := err.(*googleapi.Error); ok && gerr.Code == 404 { + log.Printf("[WARN] Removing Snapshot %q because it's gone", d.Get("name").(string)) + // The resource doesn't exist anymore + d.SetId("") + return nil + } + return fmt.Errorf("Error deleting snapshot: %s", err) + } + + err = computeOperationWaitGlobal(config, op, project, "Deleting Snapshot") + if err != nil { + return err + } + + d.SetId("") + return nil +} + +func resourceComputeSnapshotExists(d *schema.ResourceData, meta interface{}) (bool, error) { + config := meta.(*Config) + + project, err := getProject(d, config) + if err != nil { + return false, err + } + + _, err = config.clientCompute.Snapshots.Get( + project, d.Id()).Do() + if err != nil { + if gerr, ok := err.(*googleapi.Error); ok && gerr.Code == 404 { + log.Printf("[WARN] Removing Snapshot %q because it's gone", d.Get("name").(string)) + // The resource doesn't exist anymore + d.SetId("") + + return false, err + } + return true, err + } + return true, nil +} diff --git a/builtin/providers/google/resource_compute_snapshot_test.go b/builtin/providers/google/resource_compute_snapshot_test.go new file mode 100644 index 000000000..2a29f940d --- /dev/null +++ b/builtin/providers/google/resource_compute_snapshot_test.go @@ -0,0 +1,183 @@ +package google + +import ( + "fmt" + "testing" + + "github.com/hashicorp/terraform/helper/acctest" + "github.com/hashicorp/terraform/helper/resource" + "github.com/hashicorp/terraform/terraform" + "google.golang.org/api/compute/v1" + "google.golang.org/api/googleapi" +) + +func TestAccComputeSnapshot_basic(t *testing.T) { + snapshotName := fmt.Sprintf("tf-test-%s", acctest.RandString(10)) + var snapshot compute.Snapshot + diskName := fmt.Sprintf("tf-test-%s", acctest.RandString(10)) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckComputeSnapshotDestroy, + Steps: []resource.TestStep{ + resource.TestStep{ + Config: testAccComputeSnapshot_basic(snapshotName, diskName), + Check: resource.ComposeTestCheckFunc( + testAccCheckComputeSnapshotExists( + "google_compute_snapshot.foobar", &snapshot), + ), + }, + }, + }) +} + +func TestAccComputeSnapshot_encryption(t *testing.T) { + snapshotName := fmt.Sprintf("tf-test-%s", acctest.RandString(10)) + diskName := fmt.Sprintf("tf-test-%s", acctest.RandString(10)) + var snapshot compute.Snapshot + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckComputeSnapshotDestroy, + Steps: []resource.TestStep{ + resource.TestStep{ + Config: testAccComputeSnapshot_encryption(snapshotName, diskName), + Check: resource.ComposeTestCheckFunc( + testAccCheckComputeSnapshotExists( + "google_compute_snapshot.foobar", &snapshot), + ), + }, + }, + }) +} + +func testAccCheckComputeSnapshotDestroy(s *terraform.State) error { + config := testAccProvider.Meta().(*Config) + + for _, rs := range s.RootModule().Resources { + if rs.Type != "google_compute_snapshot" { + continue + } + + _, err := config.clientCompute.Snapshots.Get( + config.Project, rs.Primary.ID).Do() + if err != nil { + if gerr, ok := err.(*googleapi.Error); ok && gerr.Code == 404 { + return nil + } else if ok { + return fmt.Errorf("Error while requesting Google Cloud Plateform: http code error : %d, http message error: %s", gerr.Code, gerr.Message) + } + return fmt.Errorf("Error while requesting Google Cloud Plateform") + } + return fmt.Errorf("Snapshot still exists") + } + + return nil +} + +func testAccCheckComputeSnapshotExists(n string, snapshot *compute.Snapshot) resource.TestCheckFunc { + return func(s *terraform.State) error { + rs, ok := s.RootModule().Resources[n] + if !ok { + return fmt.Errorf("Not found: %s", n) + } + + if rs.Primary.ID == "" { + return fmt.Errorf("No ID is set") + } + + config := testAccProvider.Meta().(*Config) + + found, err := config.clientCompute.Snapshots.Get( + config.Project, rs.Primary.ID).Do() + if err != nil { + return err + } + + if found.Name != rs.Primary.ID { + return fmt.Errorf("Snapshot %s not found", n) + } + + attr := rs.Primary.Attributes["snapshot_encryption_key_sha256"] + if found.SnapshotEncryptionKey != nil && found.SnapshotEncryptionKey.Sha256 != attr { + return fmt.Errorf("Snapshot %s has mismatched encryption key (Sha256).\nTF State: %+v.\nGCP State: %+v", + n, attr, found.SnapshotEncryptionKey.Sha256) + } else if found.SnapshotEncryptionKey == nil && attr != "" { + return fmt.Errorf("Snapshot %s has mismatched encryption key.\nTF State: %+v.\nGCP State: %+v", + n, attr, found.SnapshotEncryptionKey) + } + + attr = rs.Primary.Attributes["source_disk_encryption_key_sha256"] + if found.SourceDiskEncryptionKey != nil && found.SourceDiskEncryptionKey.Sha256 != attr { + return fmt.Errorf("Snapshot %s has mismatched source disk encryption key (Sha256).\nTF State: %+v.\nGCP State: %+v", + n, attr, found.SourceDiskEncryptionKey.Sha256) + } else if found.SourceDiskEncryptionKey == nil && attr != "" { + return fmt.Errorf("Snapshot %s has mismatched source disk encryption key.\nTF State: %+v.\nGCP State: %+v", + n, attr, found.SourceDiskEncryptionKey) + } + + attr = rs.Primary.Attributes["source_disk_link"] + if found.SourceDisk != attr { + return fmt.Errorf("Snapshot %s has mismatched source disk link.\nTF State: %+v.\nGCP State: %+v", + n, attr, found.SourceDisk) + } + + foundDisk, errDisk := config.clientCompute.Disks.Get( + config.Project, rs.Primary.Attributes["zone"], rs.Primary.Attributes["source_disk"]).Do() + if errDisk != nil { + return errDisk + } + if foundDisk.SelfLink != attr { + return fmt.Errorf("Snapshot %s has mismatched source disk\nTF State: %+v.\nGCP State: %+v", + n, attr, foundDisk.SelfLink) + } + + attr = rs.Primary.Attributes["self_link"] + if found.SelfLink != attr { + return fmt.Errorf("Snapshot %s has mismatched self link.\nTF State: %+v.\nGCP State: %+v", + n, attr, found.SelfLink) + } + + *snapshot = *found + + return nil + } +} + +func testAccComputeSnapshot_basic(snapshotName string, diskName string) string { + return fmt.Sprintf(` +resource "google_compute_disk" "foobar" { + name = "%s" + image = "debian-8-jessie-v20160921" + size = 10 + type = "pd-ssd" + zone = "us-central1-a" +} + +resource "google_compute_snapshot" "foobar" { + name = "%s" + source_disk = "${google_compute_disk.foobar.name}" + zone = "us-central1-a" +}`, diskName, snapshotName) +} + +func testAccComputeSnapshot_encryption(snapshotName string, diskName string) string { + return fmt.Sprintf(` +resource "google_compute_disk" "foobar" { + name = "%s" + image = "debian-8-jessie-v20160921" + size = 10 + type = "pd-ssd" + zone = "us-central1-a" + disk_encryption_key_raw = "SGVsbG8gZnJvbSBHb29nbGUgQ2xvdWQgUGxhdGZvcm0=" +} +resource "google_compute_snapshot" "foobar" { + name = "%s" + source_disk = "${google_compute_disk.foobar.name}" + zone = "us-central1-a" + source_disk_encryption_key_raw = "SGVsbG8gZnJvbSBHb29nbGUgQ2xvdWQgUGxhdGZvcm0=" + snapshot_encryption_key_raw = "SGVsbG8gZnJvbSBHb29nbGUgQ2xvdWQgUGxhdGZvcm0=" +}`, diskName, snapshotName) +} diff --git a/builtin/providers/google/resource_compute_ssl_certificate.go b/builtin/providers/google/resource_compute_ssl_certificate.go index ea37e141f..5b64ebbf7 100644 --- a/builtin/providers/google/resource_compute_ssl_certificate.go +++ b/builtin/providers/google/resource_compute_ssl_certificate.go @@ -2,13 +2,11 @@ package google import ( "fmt" - "log" "strconv" "github.com/hashicorp/terraform/helper/resource" "github.com/hashicorp/terraform/helper/schema" "google.golang.org/api/compute/v1" - "google.golang.org/api/googleapi" ) func resourceComputeSslCertificate() *schema.Resource { @@ -144,15 +142,7 @@ func resourceComputeSslCertificateRead(d *schema.ResourceData, meta interface{}) cert, err := config.clientCompute.SslCertificates.Get( project, d.Id()).Do() if err != nil { - if gerr, ok := err.(*googleapi.Error); ok && gerr.Code == 404 { - log.Printf("[WARN] Removing SSL Certificate %q because it's gone", d.Get("name").(string)) - // The resource doesn't exist anymore - d.SetId("") - - return nil - } - - return fmt.Errorf("Error reading ssl certificate: %s", err) + return handleNotFoundError(err, d, fmt.Sprintf("SSL Certificate %q", d.Get("name").(string))) } d.Set("self_link", cert.SelfLink) diff --git a/builtin/providers/google/resource_compute_subnetwork.go b/builtin/providers/google/resource_compute_subnetwork.go index 94c7a9dd8..53f0c0dae 100644 --- a/builtin/providers/google/resource_compute_subnetwork.go +++ b/builtin/providers/google/resource_compute_subnetwork.go @@ -8,7 +8,6 @@ import ( "github.com/hashicorp/terraform/helper/schema" "google.golang.org/api/compute/v1" - "google.golang.org/api/googleapi" ) func resourceComputeSubnetwork() *schema.Resource { @@ -146,15 +145,7 @@ func resourceComputeSubnetworkRead(d *schema.ResourceData, meta interface{}) err subnetwork, err := config.clientCompute.Subnetworks.Get( project, region, name).Do() if err != nil { - if gerr, ok := err.(*googleapi.Error); ok && gerr.Code == 404 { - log.Printf("[WARN] Removing Subnetwork %q because it's gone", name) - // The resource doesn't exist anymore - d.SetId("") - - return nil - } - - return fmt.Errorf("Error reading subnetwork: %s", err) + return handleNotFoundError(err, d, fmt.Sprintf("Subnetwork %q", name)) } d.Set("gateway_address", subnetwork.GatewayAddress) diff --git a/builtin/providers/google/resource_compute_target_http_proxy.go b/builtin/providers/google/resource_compute_target_http_proxy.go index 72c68eb51..602c38b7c 100644 --- a/builtin/providers/google/resource_compute_target_http_proxy.go +++ b/builtin/providers/google/resource_compute_target_http_proxy.go @@ -7,7 +7,6 @@ import ( "github.com/hashicorp/terraform/helper/schema" "google.golang.org/api/compute/v1" - "google.golang.org/api/googleapi" ) func resourceComputeTargetHttpProxy() *schema.Resource { @@ -131,15 +130,7 @@ func resourceComputeTargetHttpProxyRead(d *schema.ResourceData, meta interface{} proxy, err := config.clientCompute.TargetHttpProxies.Get( project, d.Id()).Do() if err != nil { - if gerr, ok := err.(*googleapi.Error); ok && gerr.Code == 404 { - log.Printf("[WARN] Removing Target HTTP Proxy %q because it's gone", d.Get("name").(string)) - // The resource doesn't exist anymore - d.SetId("") - - return nil - } - - return fmt.Errorf("Error reading TargetHttpProxy: %s", err) + return handleNotFoundError(err, d, fmt.Sprintf("Target HTTP Proxy %q", d.Get("name").(string))) } d.Set("self_link", proxy.SelfLink) diff --git a/builtin/providers/google/resource_compute_target_https_proxy.go b/builtin/providers/google/resource_compute_target_https_proxy.go index 5e8bf58c2..7ba080e4c 100644 --- a/builtin/providers/google/resource_compute_target_https_proxy.go +++ b/builtin/providers/google/resource_compute_target_https_proxy.go @@ -7,7 +7,6 @@ import ( "github.com/hashicorp/terraform/helper/schema" "google.golang.org/api/compute/v1" - "google.golang.org/api/googleapi" ) func resourceComputeTargetHttpsProxy() *schema.Resource { @@ -206,15 +205,7 @@ func resourceComputeTargetHttpsProxyRead(d *schema.ResourceData, meta interface{ proxy, err := config.clientCompute.TargetHttpsProxies.Get( project, d.Id()).Do() if err != nil { - if gerr, ok := err.(*googleapi.Error); ok && gerr.Code == 404 { - log.Printf("[WARN] Removing Target HTTPS Proxy %q because it's gone", d.Get("name").(string)) - // The resource doesn't exist anymore - d.SetId("") - - return nil - } - - return fmt.Errorf("Error reading TargetHttpsProxy: %s", err) + return handleNotFoundError(err, d, fmt.Sprintf("Target HTTPS proxy %q", d.Get("name").(string))) } _certs := d.Get("ssl_certificates").([]interface{}) diff --git a/builtin/providers/google/resource_compute_target_pool.go b/builtin/providers/google/resource_compute_target_pool.go index 1680be90f..3a40c151d 100644 --- a/builtin/providers/google/resource_compute_target_pool.go +++ b/builtin/providers/google/resource_compute_target_pool.go @@ -7,7 +7,6 @@ import ( "github.com/hashicorp/terraform/helper/schema" "google.golang.org/api/compute/v1" - "google.golang.org/api/googleapi" ) func resourceComputeTargetPool() *schema.Resource { @@ -391,15 +390,7 @@ func resourceComputeTargetPoolRead(d *schema.ResourceData, meta interface{}) err tpool, err := config.clientCompute.TargetPools.Get( project, region, d.Id()).Do() if err != nil { - if gerr, ok := err.(*googleapi.Error); ok && gerr.Code == 404 { - log.Printf("[WARN] Removing Target Pool %q because it's gone", d.Get("name").(string)) - // The resource doesn't exist anymore - d.SetId("") - - return nil - } - - return fmt.Errorf("Error reading TargetPool: %s", err) + return handleNotFoundError(err, d, fmt.Sprintf("Target Pool %q", d.Get("name").(string))) } regionUrl := strings.Split(tpool.Region, "/") diff --git a/builtin/providers/google/resource_compute_url_map.go b/builtin/providers/google/resource_compute_url_map.go index 56c19ddc3..3c5740e06 100644 --- a/builtin/providers/google/resource_compute_url_map.go +++ b/builtin/providers/google/resource_compute_url_map.go @@ -2,12 +2,10 @@ package google import ( "fmt" - "log" "strconv" "github.com/hashicorp/terraform/helper/schema" "google.golang.org/api/compute/v1" - "google.golang.org/api/googleapi" ) func resourceComputeUrlMap() *schema.Resource { @@ -312,15 +310,7 @@ func resourceComputeUrlMapRead(d *schema.ResourceData, meta interface{}) error { urlMap, err := config.clientCompute.UrlMaps.Get(project, name).Do() if err != nil { - if gerr, ok := err.(*googleapi.Error); ok && gerr.Code == 404 { - log.Printf("[WARN] Removing URL Map %q because it's gone", d.Get("name").(string)) - // The resource doesn't exist anymore - d.SetId("") - - return nil - } - - return fmt.Errorf("Error, failed to get Url Map %s: %s", name, err) + return handleNotFoundError(err, d, fmt.Sprintf("URL Map %q", d.Get("name").(string))) } d.SetId(name) diff --git a/builtin/providers/google/resource_compute_vpn_gateway.go b/builtin/providers/google/resource_compute_vpn_gateway.go index fe716198d..5b23eaa49 100644 --- a/builtin/providers/google/resource_compute_vpn_gateway.go +++ b/builtin/providers/google/resource_compute_vpn_gateway.go @@ -2,12 +2,10 @@ package google import ( "fmt" - "log" "github.com/hashicorp/terraform/helper/schema" "google.golang.org/api/compute/v1" - "google.golang.org/api/googleapi" ) func resourceComputeVpnGateway() *schema.Resource { @@ -119,15 +117,7 @@ func resourceComputeVpnGatewayRead(d *schema.ResourceData, meta interface{}) err vpnGateway, err := vpnGatewaysService.Get(project, region, name).Do() if err != nil { - if gerr, ok := err.(*googleapi.Error); ok && gerr.Code == 404 { - log.Printf("[WARN] Removing VPN Gateway %q because it's gone", d.Get("name").(string)) - // The resource doesn't exist anymore - d.SetId("") - - return nil - } - - return fmt.Errorf("Error Reading VPN Gateway %s: %s", name, err) + return handleNotFoundError(err, d, fmt.Sprintf("VPN Gateway %q", d.Get("name").(string))) } d.Set("self_link", vpnGateway.SelfLink) diff --git a/builtin/providers/google/resource_compute_vpn_tunnel.go b/builtin/providers/google/resource_compute_vpn_tunnel.go index 42f477d92..a5120c991 100644 --- a/builtin/providers/google/resource_compute_vpn_tunnel.go +++ b/builtin/providers/google/resource_compute_vpn_tunnel.go @@ -3,13 +3,11 @@ package google import ( "bytes" "fmt" - "log" "net" "github.com/hashicorp/terraform/helper/schema" "google.golang.org/api/compute/v1" - "google.golang.org/api/googleapi" ) func resourceComputeVpnTunnel() *schema.Resource { @@ -189,15 +187,7 @@ func resourceComputeVpnTunnelRead(d *schema.ResourceData, meta interface{}) erro vpnTunnel, err := vpnTunnelsService.Get(project, region, name).Do() if err != nil { - if gerr, ok := err.(*googleapi.Error); ok && gerr.Code == 404 { - log.Printf("[WARN] Removing VPN Tunnel %q because it's gone", d.Get("name").(string)) - // The resource doesn't exist anymore - d.SetId("") - - return nil - } - - return fmt.Errorf("Error Reading VPN Tunnel %s: %s", name, err) + return handleNotFoundError(err, d, fmt.Sprintf("VPN Tunnel %q", d.Get("name").(string))) } localTrafficSelectors := []string{} diff --git a/builtin/providers/google/resource_container_cluster.go b/builtin/providers/google/resource_container_cluster.go index 203a990b8..91c994826 100644 --- a/builtin/providers/google/resource_container_cluster.go +++ b/builtin/providers/google/resource_container_cluster.go @@ -6,9 +6,9 @@ import ( "net" "regexp" + "github.com/hashicorp/terraform/helper/resource" "github.com/hashicorp/terraform/helper/schema" "google.golang.org/api/container/v1" - "google.golang.org/api/googleapi" ) var ( @@ -23,12 +23,6 @@ func resourceContainerCluster() *schema.Resource { Delete: resourceContainerClusterDelete, Schema: map[string]*schema.Schema{ - "initial_node_count": &schema.Schema{ - Type: schema.TypeInt, - Required: true, - ForceNew: true, - }, - "master_auth": &schema.Schema{ Type: schema.TypeList, Required: true, @@ -40,17 +34,19 @@ func resourceContainerCluster() *schema.Resource { Computed: true, }, "client_key": &schema.Schema{ - Type: schema.TypeString, - Computed: true, + Type: schema.TypeString, + Computed: true, + Sensitive: true, }, "cluster_ca_certificate": &schema.Schema{ Type: schema.TypeString, Computed: true, }, "password": &schema.Schema{ - Type: schema.TypeString, - Required: true, - ForceNew: true, + Type: schema.TypeString, + Required: true, + ForceNew: true, + Sensitive: true, }, "username": &schema.Schema{ Type: schema.TypeString, @@ -94,6 +90,12 @@ func resourceContainerCluster() *schema.Resource { ForceNew: true, }, + "initial_node_count": &schema.Schema{ + Type: schema.TypeInt, + Optional: true, + ForceNew: true, + }, + "additional_zones": &schema.Schema{ Type: schema.TypeList, Optional: true, @@ -290,6 +292,36 @@ func resourceContainerCluster() *schema.Resource { Computed: true, }, + "node_pool": &schema.Schema{ + Type: schema.TypeList, + Optional: true, + Computed: true, + ForceNew: true, // TODO(danawillow): Add ability to add/remove nodePools + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "initial_node_count": &schema.Schema{ + Type: schema.TypeInt, + Required: true, + ForceNew: true, + }, + + "name": &schema.Schema{ + Type: schema.TypeString, + Optional: true, + Computed: true, + ConflictsWith: []string{"node_pool.name_prefix"}, + ForceNew: true, + }, + + "name_prefix": &schema.Schema{ + Type: schema.TypeString, + Optional: true, + ForceNew: true, + }, + }, + }, + }, + "project": &schema.Schema{ Type: schema.TypeString, Optional: true, @@ -375,14 +407,14 @@ func resourceContainerClusterCreate(d *schema.ResourceData, meta interface{}) er addonsConfig := v.([]interface{})[0].(map[string]interface{}) cluster.AddonsConfig = &container.AddonsConfig{} - if v, ok := addonsConfig["http_load_balancing"]; ok { + if v, ok := addonsConfig["http_load_balancing"]; ok && len(v.([]interface{})) > 0 { addon := v.([]interface{})[0].(map[string]interface{}) cluster.AddonsConfig.HttpLoadBalancing = &container.HttpLoadBalancing{ Disabled: addon["disabled"].(bool), } } - if v, ok := addonsConfig["horizontal_pod_autoscaling"]; ok { + if v, ok := addonsConfig["horizontal_pod_autoscaling"]; ok && len(v.([]interface{})) > 0 { addon := v.([]interface{})[0].(map[string]interface{}) cluster.AddonsConfig.HorizontalPodAutoscaling = &container.HorizontalPodAutoscaling{ Disabled: addon["disabled"].(bool), @@ -437,6 +469,33 @@ func resourceContainerClusterCreate(d *schema.ResourceData, meta interface{}) er } } + nodePoolsCount := d.Get("node_pool.#").(int) + if nodePoolsCount > 0 { + nodePools := make([]*container.NodePool, 0, nodePoolsCount) + for i := 0; i < nodePoolsCount; i++ { + prefix := fmt.Sprintf("node_pool.%d", i) + + nodeCount := d.Get(prefix + ".initial_node_count").(int) + + var name string + if v, ok := d.GetOk(prefix + ".name"); ok { + name = v.(string) + } else if v, ok := d.GetOk(prefix + ".name_prefix"); ok { + name = resource.PrefixedUniqueId(v.(string)) + } else { + name = resource.UniqueId() + } + + nodePool := &container.NodePool{ + Name: name, + InitialNodeCount: int64(nodeCount), + } + + nodePools = append(nodePools, nodePool) + } + cluster.NodePools = nodePools + } + req := &container.CreateClusterRequest{ Cluster: cluster, } @@ -475,15 +534,7 @@ func resourceContainerClusterRead(d *schema.ResourceData, meta interface{}) erro cluster, err := config.clientContainer.Projects.Zones.Clusters.Get( project, zoneName, d.Get("name").(string)).Do() if err != nil { - if gerr, ok := err.(*googleapi.Error); ok && gerr.Code == 404 { - log.Printf("[WARN] Removing Container Cluster %q because it's gone", d.Get("name").(string)) - // The resource doesn't exist anymore - d.SetId("") - - return nil - } - - return err + return handleNotFoundError(err, d, fmt.Sprintf("Container Cluster %q", d.Get("name").(string))) } d.Set("name", cluster.Name) @@ -521,6 +572,7 @@ func resourceContainerClusterRead(d *schema.ResourceData, meta interface{}) erro d.Set("network", d.Get("network").(string)) d.Set("subnetwork", cluster.Subnetwork) d.Set("node_config", flattenClusterNodeConfig(cluster.NodeConfig)) + d.Set("node_pool", flattenClusterNodePools(d, cluster.NodePools)) if igUrls, err := getInstanceGroupUrlsFromManagerUrls(config, cluster.InstanceGroupUrls); err != nil { return err @@ -639,3 +691,20 @@ func flattenClusterNodeConfig(c *container.NodeConfig) []map[string]interface{} return config } + +func flattenClusterNodePools(d *schema.ResourceData, c []*container.NodePool) []map[string]interface{} { + count := len(c) + + nodePools := make([]map[string]interface{}, 0, count) + + for i, np := range c { + nodePool := map[string]interface{}{ + "name": np.Name, + "name_prefix": d.Get(fmt.Sprintf("node_pool.%d.name_prefix", i)), + "initial_node_count": np.InitialNodeCount, + } + nodePools = append(nodePools, nodePool) + } + + return nodePools +} diff --git a/builtin/providers/google/resource_container_cluster_test.go b/builtin/providers/google/resource_container_cluster_test.go index f0723dcb1..549803f55 100644 --- a/builtin/providers/google/resource_container_cluster_test.go +++ b/builtin/providers/google/resource_container_cluster_test.go @@ -132,6 +132,57 @@ func TestAccContainerCluster_backend(t *testing.T) { }) } +func TestAccContainerCluster_withNodePoolBasic(t *testing.T) { + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckContainerClusterDestroy, + Steps: []resource.TestStep{ + resource.TestStep{ + Config: testAccContainerCluster_withNodePoolBasic, + Check: resource.ComposeTestCheckFunc( + testAccCheckContainerCluster( + "google_container_cluster.with_node_pool"), + ), + }, + }, + }) +} + +func TestAccContainerCluster_withNodePoolNamePrefix(t *testing.T) { + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckContainerClusterDestroy, + Steps: []resource.TestStep{ + resource.TestStep{ + Config: testAccContainerCluster_withNodePoolNamePrefix, + Check: resource.ComposeTestCheckFunc( + testAccCheckContainerCluster( + "google_container_cluster.with_node_pool_name_prefix"), + ), + }, + }, + }) +} + +func TestAccContainerCluster_withNodePoolMultiple(t *testing.T) { + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckContainerClusterDestroy, + Steps: []resource.TestStep{ + resource.TestStep{ + Config: testAccContainerCluster_withNodePoolMultiple, + Check: resource.ComposeTestCheckFunc( + testAccCheckContainerCluster( + "google_container_cluster.with_node_pool_multiple"), + ), + }, + }, + }) +} + func testAccCheckContainerClusterDestroy(s *terraform.State) error { config := testAccProvider.Meta().(*Config) @@ -222,6 +273,13 @@ func testAccCheckContainerCluster(n string) resource.TestCheckFunc { } } + for i, np := range cluster.NodePools { + prefix := fmt.Sprintf("node_pool.%d.", i) + clusterTests = append(clusterTests, + clusterTestField{prefix + "name", np.Name}, + clusterTestField{prefix + "initial_node_count", strconv.FormatInt(np.InitialNodeCount, 10)}) + } + for _, attrs := range clusterTests { if c := checkMatch(attributes, attrs.tf_attr, attrs.gcp_attr); c != "" { return fmt.Errorf(c) @@ -342,10 +400,14 @@ resource "google_container_cluster" "with_additional_zones" { }`, acctest.RandString(10)) var testAccContainerCluster_withVersion = fmt.Sprintf(` +data "google_container_engine_versions" "central1a" { + zone = "us-central1-a" +} + resource "google_container_cluster" "with_version" { name = "cluster-test-%s" zone = "us-central1-a" - node_version = "1.5.2" + node_version = "${data.google_container_engine_versions.central1a.latest_node_version}" initial_node_count = 1 master_auth { @@ -478,3 +540,56 @@ resource "google_container_cluster" "primary" { } } `, acctest.RandString(10), acctest.RandString(10), acctest.RandString(10)) + +var testAccContainerCluster_withNodePoolBasic = fmt.Sprintf(` +resource "google_container_cluster" "with_node_pool" { + name = "tf-cluster-nodepool-test-%s" + zone = "us-central1-a" + + master_auth { + username = "mr.yoda" + password = "adoy.rm" + } + + node_pool { + name = "tf-cluster-nodepool-test-%s" + initial_node_count = 2 + } +}`, acctest.RandString(10), acctest.RandString(10)) + +var testAccContainerCluster_withNodePoolNamePrefix = fmt.Sprintf(` +resource "google_container_cluster" "with_node_pool_name_prefix" { + name = "tf-cluster-nodepool-test-%s" + zone = "us-central1-a" + + master_auth { + username = "mr.yoda" + password = "adoy.rm" + } + + node_pool { + name_prefix = "tf-np-test" + initial_node_count = 2 + } +}`, acctest.RandString(10)) + +var testAccContainerCluster_withNodePoolMultiple = fmt.Sprintf(` +resource "google_container_cluster" "with_node_pool_multiple" { + name = "tf-cluster-nodepool-test-%s" + zone = "us-central1-a" + + master_auth { + username = "mr.yoda" + password = "adoy.rm" + } + + node_pool { + name = "tf-cluster-nodepool-test-%s" + initial_node_count = 2 + } + + node_pool { + name = "tf-cluster-nodepool-test-%s" + initial_node_count = 3 + } +}`, acctest.RandString(10), acctest.RandString(10), acctest.RandString(10)) diff --git a/builtin/providers/google/resource_dns_managed_zone.go b/builtin/providers/google/resource_dns_managed_zone.go index 8181e278b..a934460c0 100644 --- a/builtin/providers/google/resource_dns_managed_zone.go +++ b/builtin/providers/google/resource_dns_managed_zone.go @@ -6,7 +6,6 @@ import ( "github.com/hashicorp/terraform/helper/schema" "google.golang.org/api/dns/v1" - "google.golang.org/api/googleapi" ) func resourceDnsManagedZone() *schema.Resource { @@ -14,7 +13,9 @@ func resourceDnsManagedZone() *schema.Resource { Create: resourceDnsManagedZoneCreate, Read: resourceDnsManagedZoneRead, Delete: resourceDnsManagedZoneDelete, - + Importer: &schema.ResourceImporter{ + State: schema.ImportStatePassthrough, + }, Schema: map[string]*schema.Schema{ "dns_name": &schema.Schema{ Type: schema.TypeString, @@ -97,18 +98,13 @@ func resourceDnsManagedZoneRead(d *schema.ResourceData, meta interface{}) error zone, err := config.clientDns.ManagedZones.Get( project, d.Id()).Do() if err != nil { - if gerr, ok := err.(*googleapi.Error); ok && gerr.Code == 404 { - log.Printf("[WARN] Removing DNS Managed Zone %q because it's gone", d.Get("name").(string)) - // The resource doesn't exist anymore - d.SetId("") - - return nil - } - - return fmt.Errorf("Error reading DNS ManagedZone: %#v", err) + return handleNotFoundError(err, d, fmt.Sprintf("DNS Managed Zone %q", d.Get("name").(string))) } d.Set("name_servers", zone.NameServers) + d.Set("name", zone.Name) + d.Set("dns_name", zone.DnsName) + d.Set("description", zone.Description) return nil } diff --git a/builtin/providers/google/resource_dns_record_set.go b/builtin/providers/google/resource_dns_record_set.go index 49a56d9b1..0f322bd86 100644 --- a/builtin/providers/google/resource_dns_record_set.go +++ b/builtin/providers/google/resource_dns_record_set.go @@ -6,7 +6,6 @@ import ( "github.com/hashicorp/terraform/helper/schema" "google.golang.org/api/dns/v1" - "google.golang.org/api/googleapi" ) func resourceDnsRecordSet() *schema.Resource { @@ -117,15 +116,7 @@ func resourceDnsRecordSetRead(d *schema.ResourceData, meta interface{}) error { resp, err := config.clientDns.ResourceRecordSets.List( project, zone).Name(name).Type(dnsType).Do() if err != nil { - if gerr, ok := err.(*googleapi.Error); ok && gerr.Code == 404 { - log.Printf("[WARN] Removing DNS Record Set %q because it's gone", d.Get("name").(string)) - // The resource doesn't exist anymore - d.SetId("") - - return nil - } - - return fmt.Errorf("Error reading DNS RecordSet: %#v", err) + return handleNotFoundError(err, d, fmt.Sprintf("DNS Record Set %q", d.Get("name").(string))) } if len(resp.Rrsets) == 0 { // The resource doesn't exist anymore diff --git a/builtin/providers/google/resource_google_project.go b/builtin/providers/google/resource_google_project.go index 9b947a66c..4e71d0d46 100644 --- a/builtin/providers/google/resource_google_project.go +++ b/builtin/providers/google/resource_google_project.go @@ -105,6 +105,8 @@ func resourceGoogleProjectCreate(d *schema.ResourceData, meta interface{}) error // Wait for the operation to complete waitErr := resourceManagerOperationWait(config, op, "project to create") if waitErr != nil { + // The resource wasn't actually created + d.SetId("") return waitErr } @@ -134,10 +136,7 @@ func resourceGoogleProjectRead(d *schema.ResourceData, meta interface{}) error { // Read the project p, err := config.clientResourceManager.Projects.Get(pid).Do() if err != nil { - if v, ok := err.(*googleapi.Error); ok && v.Code == http.StatusNotFound { - return fmt.Errorf("Project %q does not exist.", pid) - } - return fmt.Errorf("Error checking project %q: %s", pid, err) + return handleNotFoundError(err, d, fmt.Sprintf("Project %q", pid)) } d.Set("project_id", pid) diff --git a/builtin/providers/google/resource_google_project_services.go b/builtin/providers/google/resource_google_project_services.go index 84bcd95ad..3a9c66730 100644 --- a/builtin/providers/google/resource_google_project_services.go +++ b/builtin/providers/google/resource_google_project_services.go @@ -31,6 +31,14 @@ func resourceGoogleProjectServices() *schema.Resource { } } +// These services can only be enabled as a side-effect of enabling other services, +// so don't bother storing them in the config or using them for diffing. +var ignore = map[string]struct{}{ + "containeranalysis.googleapis.com": struct{}{}, + "dataproc-control.googleapis.com": struct{}{}, + "source.googleapis.com": struct{}{}, +} + func resourceGoogleProjectServicesCreate(d *schema.ResourceData, meta interface{}) error { config := meta.(*Config) pid := d.Get("project").(string) @@ -155,12 +163,19 @@ func getConfigServices(d *schema.ResourceData) (services []string) { func getApiServices(pid string, config *Config) ([]string, error) { apiServices := make([]string, 0) // Get services from the API - svcResp, err := config.clientServiceMan.Services.List().ConsumerId("project:" + pid).Do() - if err != nil { - return apiServices, err - } - for _, v := range svcResp.Services { - apiServices = append(apiServices, v.ServiceName) + token := "" + for paginate := true; paginate; { + svcResp, err := config.clientServiceMan.Services.List().ConsumerId("project:" + pid).PageToken(token).Do() + if err != nil { + return apiServices, err + } + for _, v := range svcResp.Services { + if _, ok := ignore[v.ServiceName]; !ok { + apiServices = append(apiServices, v.ServiceName) + } + } + token = svcResp.NextPageToken + paginate = token != "" } return apiServices, nil } diff --git a/builtin/providers/google/resource_google_project_services_test.go b/builtin/providers/google/resource_google_project_services_test.go index dff073b28..e8af051cd 100644 --- a/builtin/providers/google/resource_google_project_services_test.go +++ b/builtin/providers/google/resource_google_project_services_test.go @@ -4,6 +4,7 @@ import ( "bytes" "fmt" "log" + "os" "reflect" "sort" "testing" @@ -123,6 +124,103 @@ func TestAccGoogleProjectServices_authoritative2(t *testing.T) { }) } +// Test that services that can't be enabled on their own (such as dataproc-control.googleapis.com) +// don't end up causing diffs when they are enabled as a side-effect of a different service's +// enablement. +func TestAccGoogleProjectServices_ignoreUnenablableServices(t *testing.T) { + skipIfEnvNotSet(t, + []string{ + "GOOGLE_ORG", + "GOOGLE_BILLING_ACCOUNT", + }..., + ) + + billingId := os.Getenv("GOOGLE_BILLING_ACCOUNT") + pid := "terraform-" + acctest.RandString(10) + services := []string{ + "dataproc.googleapis.com", + // The following services are enabled as a side-effect of dataproc's enablement + "storage-component.googleapis.com", + "deploymentmanager.googleapis.com", + "replicapool.googleapis.com", + "replicapoolupdater.googleapis.com", + "resourceviews.googleapis.com", + "compute-component.googleapis.com", + "container.googleapis.com", + "containerregistry.googleapis.com", + "storage-api.googleapis.com", + "pubsub.googleapis.com", + } + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + Steps: []resource.TestStep{ + resource.TestStep{ + Config: testAccGoogleProjectAssociateServicesBasic_withBilling(services, pid, pname, org, billingId), + Check: resource.ComposeTestCheckFunc( + testProjectServicesMatch(services, pid), + ), + }, + }, + }) +} + +func TestAccGoogleProjectServices_manyServices(t *testing.T) { + skipIfEnvNotSet(t, + []string{ + "GOOGLE_ORG", + "GOOGLE_BILLING_ACCOUNT", + }..., + ) + + billingId := os.Getenv("GOOGLE_BILLING_ACCOUNT") + pid := "terraform-" + acctest.RandString(10) + services := []string{ + "bigquery-json.googleapis.com", + "cloudbuild.googleapis.com", + "cloudfunctions.googleapis.com", + "cloudresourcemanager.googleapis.com", + "cloudtrace.googleapis.com", + "compute-component.googleapis.com", + "container.googleapis.com", + "containerregistry.googleapis.com", + "dataflow.googleapis.com", + "dataproc.googleapis.com", + "deploymentmanager.googleapis.com", + "dns.googleapis.com", + "endpoints.googleapis.com", + "iam.googleapis.com", + "logging.googleapis.com", + "ml.googleapis.com", + "monitoring.googleapis.com", + "pubsub.googleapis.com", + "replicapool.googleapis.com", + "replicapoolupdater.googleapis.com", + "resourceviews.googleapis.com", + "runtimeconfig.googleapis.com", + "servicecontrol.googleapis.com", + "servicemanagement.googleapis.com", + "sourcerepo.googleapis.com", + "spanner.googleapis.com", + "storage-api.googleapis.com", + "storage-component.googleapis.com", + } + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + Steps: []resource.TestStep{ + resource.TestStep{ + Config: testAccGoogleProjectAssociateServicesBasic_withBilling(services, pid, pname, org, billingId), + Check: resource.ComposeTestCheckFunc( + testProjectServicesMatch(services, pid), + ), + }, + }, + }) +} + func testAccGoogleProjectAssociateServicesBasic(services []string, pid, name, org string) string { return fmt.Sprintf(` resource "google_project" "acceptance" { @@ -137,6 +235,21 @@ resource "google_project_services" "acceptance" { `, pid, name, org, testStringsToString(services)) } +func testAccGoogleProjectAssociateServicesBasic_withBilling(services []string, pid, name, org, billing string) string { + return fmt.Sprintf(` +resource "google_project" "acceptance" { + project_id = "%s" + name = "%s" + org_id = "%s" + billing_account = "%s" +} +resource "google_project_services" "acceptance" { + project = "${google_project.acceptance.project_id}" + services = [%s] +} +`, pid, name, org, billing, testStringsToString(services)) +} + func testProjectServicesMatch(services []string, pid string) resource.TestCheckFunc { return func(s *terraform.State) error { config := testAccProvider.Meta().(*Config) diff --git a/builtin/providers/google/resource_google_service_account.go b/builtin/providers/google/resource_google_service_account.go index b97e602c7..6e3e6abe1 100644 --- a/builtin/providers/google/resource_google_service_account.go +++ b/builtin/providers/google/resource_google_service_account.go @@ -6,7 +6,6 @@ import ( "log" "github.com/hashicorp/terraform/helper/schema" - "google.golang.org/api/googleapi" "google.golang.org/api/iam/v1" ) @@ -116,15 +115,7 @@ func resourceGoogleServiceAccountRead(d *schema.ResourceData, meta interface{}) // Confirm the service account exists sa, err := config.clientIAM.Projects.ServiceAccounts.Get(d.Id()).Do() if err != nil { - if gerr, ok := err.(*googleapi.Error); ok && gerr.Code == 404 { - log.Printf("[WARN] Removing reference to service account %q because it no longer exists", d.Id()) - saName := d.Id() - // The resource doesn't exist anymore - d.SetId("") - - return fmt.Errorf("Error getting service account with name %q: %s", saName, err) - } - return fmt.Errorf("Error reading service account %q: %q", d.Id(), err) + return handleNotFoundError(err, d, fmt.Sprintf("Service Account %q", d.Id())) } d.Set("email", sa.Email) diff --git a/builtin/providers/google/resource_pubsub_subscription.go b/builtin/providers/google/resource_pubsub_subscription.go index 432d48ee2..04c0414b0 100644 --- a/builtin/providers/google/resource_pubsub_subscription.go +++ b/builtin/providers/google/resource_pubsub_subscription.go @@ -38,6 +38,11 @@ func resourcePubsubSubscription() *schema.Resource { ForceNew: true, }, + "path": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + }, + "push_config": &schema.Schema{ Type: schema.TypeList, Optional: true, @@ -113,6 +118,7 @@ func resourcePubsubSubscriptionCreate(d *schema.ResourceData, meta interface{}) } d.SetId(res.Name) + d.Set("path", name) return nil } @@ -124,7 +130,7 @@ func resourcePubsubSubscriptionRead(d *schema.ResourceData, meta interface{}) er call := config.clientPubsub.Projects.Subscriptions.Get(name) _, err := call.Do() if err != nil { - return err + return handleNotFoundError(err, d, fmt.Sprintf("Pubsub Subscription %q", name)) } return nil diff --git a/builtin/providers/google/resource_pubsub_subscription_test.go b/builtin/providers/google/resource_pubsub_subscription_test.go index 80dc0aa67..01230656f 100644 --- a/builtin/providers/google/resource_pubsub_subscription_test.go +++ b/builtin/providers/google/resource_pubsub_subscription_test.go @@ -16,11 +16,12 @@ func TestAccPubsubSubscriptionCreate(t *testing.T) { Providers: testAccProviders, CheckDestroy: testAccCheckPubsubSubscriptionDestroy, Steps: []resource.TestStep{ - resource.TestStep{ + { Config: testAccPubsubSubscription, Check: resource.ComposeTestCheckFunc( testAccPubsubSubscriptionExists( "google_pubsub_subscription.foobar_sub"), + resource.TestCheckResourceAttrSet("google_pubsub_subscription.foobar_sub", "path"), ), }, }, diff --git a/builtin/providers/google/resource_pubsub_topic.go b/builtin/providers/google/resource_pubsub_topic.go index 84932e4e9..ba78a6f74 100644 --- a/builtin/providers/google/resource_pubsub_topic.go +++ b/builtin/providers/google/resource_pubsub_topic.go @@ -58,7 +58,7 @@ func resourcePubsubTopicRead(d *schema.ResourceData, meta interface{}) error { call := config.clientPubsub.Projects.Topics.Get(name) _, err := call.Do() if err != nil { - return err + return handleNotFoundError(err, d, fmt.Sprintf("Pubsub Topic %q", name)) } return nil diff --git a/builtin/providers/google/resource_sql_database.go b/builtin/providers/google/resource_sql_database.go index c15e49ced..e8df24a70 100644 --- a/builtin/providers/google/resource_sql_database.go +++ b/builtin/providers/google/resource_sql_database.go @@ -2,11 +2,9 @@ package google import ( "fmt" - "log" "github.com/hashicorp/terraform/helper/schema" - "google.golang.org/api/googleapi" "google.golang.org/api/sqladmin/v1beta4" ) @@ -93,17 +91,7 @@ func resourceSqlDatabaseRead(d *schema.ResourceData, meta interface{}) error { database_name).Do() if err != nil { - if gerr, ok := err.(*googleapi.Error); ok && gerr.Code == 404 { - log.Printf("[WARN] Removing SQL Database %q because it's gone", d.Get("name").(string)) - // The resource doesn't exist anymore - d.SetId("") - - return nil - } - - return fmt.Errorf("Error, failed to get"+ - "database %s in instance %s: %s", database_name, - instance_name, err) + return handleNotFoundError(err, d, fmt.Sprintf("SQL Database %q in instance %q", database_name, instance_name)) } d.Set("self_link", db.SelfLink) diff --git a/builtin/providers/google/resource_sql_database_instance.go b/builtin/providers/google/resource_sql_database_instance.go index 2a1fa2f30..e946e6267 100644 --- a/builtin/providers/google/resource_sql_database_instance.go +++ b/builtin/providers/google/resource_sql_database_instance.go @@ -2,7 +2,6 @@ package google import ( "fmt" - "log" "strings" "github.com/hashicorp/terraform/helper/resource" @@ -610,16 +609,7 @@ func resourceSqlDatabaseInstanceRead(d *schema.ResourceData, meta interface{}) e d.Get("name").(string)).Do() if err != nil { - if gerr, ok := err.(*googleapi.Error); ok && gerr.Code == 404 { - log.Printf("[WARN] Removing SQL Database %q because it's gone", d.Get("name").(string)) - // The resource doesn't exist anymore - d.SetId("") - - return nil - } - - return fmt.Errorf("Error retrieving instance %s: %s", - d.Get("name").(string), err) + return handleNotFoundError(err, d, fmt.Sprintf("SQL Database Instance %q", d.Get("name").(string))) } _settingsList := d.Get("settings").([]interface{}) diff --git a/builtin/providers/google/resource_sql_user.go b/builtin/providers/google/resource_sql_user.go index 2aaf1bd7a..23daf461a 100644 --- a/builtin/providers/google/resource_sql_user.go +++ b/builtin/providers/google/resource_sql_user.go @@ -6,7 +6,6 @@ import ( "github.com/hashicorp/terraform/helper/schema" - "google.golang.org/api/googleapi" "google.golang.org/api/sqladmin/v1beta4" ) @@ -102,14 +101,7 @@ func resourceSqlUserRead(d *schema.ResourceData, meta interface{}) error { users, err := config.clientSqlAdmin.Users.List(project, instance).Do() if err != nil { - if gerr, ok := err.(*googleapi.Error); ok && gerr.Code == 404 { - log.Printf("[WARN] Removing SQL User %q because it's gone", d.Get("name").(string)) - d.SetId("") - - return nil - } - - return fmt.Errorf("Error, failed to get user %s in instance %s: %s", name, instance, err) + return handleNotFoundError(err, d, fmt.Sprintf("SQL User %q in instance %q", name, instance)) } found := false diff --git a/builtin/providers/google/resource_storage_bucket.go b/builtin/providers/google/resource_storage_bucket.go index afd2ad493..2640a1cc4 100644 --- a/builtin/providers/google/resource_storage_bucket.go +++ b/builtin/providers/google/resource_storage_bucket.go @@ -19,6 +19,9 @@ func resourceStorageBucket() *schema.Resource { Read: resourceStorageBucketRead, Update: resourceStorageBucketUpdate, Delete: resourceStorageBucketDelete, + Importer: &schema.ResourceImporter{ + State: resourceStorageBucketStateImporter, + }, Schema: map[string]*schema.Schema{ "name": &schema.Schema{ @@ -58,6 +61,11 @@ func resourceStorageBucket() *schema.Resource { Computed: true, }, + "url": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + }, + "storage_class": &schema.Schema{ Type: schema.TypeString, Optional: true, @@ -149,11 +157,8 @@ func resourceStorageBucketCreate(d *schema.ResourceData, meta interface{}) error log.Printf("[DEBUG] Created bucket %v at location %v\n\n", res.Name, res.SelfLink) - // Assign the bucket ID as the resource ID - d.Set("self_link", res.SelfLink) d.SetId(res.Id) - - return nil + return resourceStorageBucketRead(d, meta) } func resourceStorageBucketUpdate(d *schema.ResourceData, meta interface{}) error { @@ -215,23 +220,17 @@ func resourceStorageBucketRead(d *schema.ResourceData, meta interface{}) error { res, err := config.clientStorage.Buckets.Get(bucket).Do() if err != nil { - if gerr, ok := err.(*googleapi.Error); ok && gerr.Code == 404 { - log.Printf("[WARN] Removing Bucket %q because it's gone", d.Get("name").(string)) - // The resource doesn't exist anymore - d.SetId("") - - return nil - } - - return fmt.Errorf("Error reading bucket %s: %v", bucket, err) + return handleNotFoundError(err, d, fmt.Sprintf("Storage Bucket %q", d.Get("name").(string))) } log.Printf("[DEBUG] Read bucket %v at location %v\n\n", res.Name, res.SelfLink) // Update the bucket ID according to the resource ID d.Set("self_link", res.SelfLink) + d.Set("url", fmt.Sprintf("gs://%s", bucket)) + d.Set("storage_class", res.StorageClass) + d.Set("location", res.Location) d.SetId(res.Id) - return nil } @@ -291,3 +290,8 @@ func resourceStorageBucketDelete(d *schema.ResourceData, meta interface{}) error return nil } + +func resourceStorageBucketStateImporter(d *schema.ResourceData, meta interface{}) ([]*schema.ResourceData, error) { + d.Set("name", d.Id()) + return []*schema.ResourceData{d}, nil +} diff --git a/builtin/providers/google/resource_storage_bucket_acl.go b/builtin/providers/google/resource_storage_bucket_acl.go index aa996cb9f..428c1cecf 100644 --- a/builtin/providers/google/resource_storage_bucket_acl.go +++ b/builtin/providers/google/resource_storage_bucket_acl.go @@ -7,7 +7,6 @@ import ( "github.com/hashicorp/terraform/helper/schema" - "google.golang.org/api/googleapi" "google.golang.org/api/storage/v1" ) @@ -170,15 +169,7 @@ func resourceStorageBucketAclRead(d *schema.ResourceData, meta interface{}) erro res, err := config.clientStorage.BucketAccessControls.List(bucket).Do() if err != nil { - if gerr, ok := err.(*googleapi.Error); ok && gerr.Code == 404 { - log.Printf("[WARN] Removing Bucket ACL for bucket %q because it's gone", d.Get("bucket").(string)) - // The resource doesn't exist anymore - d.SetId("") - - return nil - } - - return err + return handleNotFoundError(err, d, fmt.Sprintf("Storage Bucket ACL for bucket %q", d.Get("bucket").(string))) } for _, v := range res.Items { diff --git a/builtin/providers/google/resource_storage_bucket_object.go b/builtin/providers/google/resource_storage_bucket_object.go index a129f73cf..bbf9c1f28 100644 --- a/builtin/providers/google/resource_storage_bucket_object.go +++ b/builtin/providers/google/resource_storage_bucket_object.go @@ -32,6 +32,37 @@ func resourceStorageBucketObject() *schema.Resource { ForceNew: true, }, + "cache_control": &schema.Schema{ + Type: schema.TypeString, + ForceNew: true, + Optional: true, + }, + + "content_disposition": &schema.Schema{ + Type: schema.TypeString, + ForceNew: true, + Optional: true, + }, + + "content_encoding": &schema.Schema{ + Type: schema.TypeString, + ForceNew: true, + Optional: true, + }, + + "content_language": &schema.Schema{ + Type: schema.TypeString, + ForceNew: true, + Optional: true, + }, + + "content_type": &schema.Schema{ + Type: schema.TypeString, + Optional: true, + ForceNew: true, + Computed: true, + }, + "content": &schema.Schema{ Type: schema.TypeString, Optional: true, @@ -62,6 +93,13 @@ func resourceStorageBucketObject() *schema.Resource { ForceNew: true, ConflictsWith: []string{"content"}, }, + + "storage_class": &schema.Schema{ + Type: schema.TypeString, + Optional: true, + ForceNew: true, + Computed: true, + }, }, } } @@ -92,6 +130,30 @@ func resourceStorageBucketObjectCreate(d *schema.ResourceData, meta interface{}) objectsService := storage.NewObjectsService(config.clientStorage) object := &storage.Object{Bucket: bucket} + if v, ok := d.GetOk("cache_control"); ok { + object.CacheControl = v.(string) + } + + if v, ok := d.GetOk("content_disposition"); ok { + object.ContentDisposition = v.(string) + } + + if v, ok := d.GetOk("content_encoding"); ok { + object.ContentEncoding = v.(string) + } + + if v, ok := d.GetOk("content_language"); ok { + object.ContentLanguage = v.(string) + } + + if v, ok := d.GetOk("content_type"); ok { + object.ContentType = v.(string) + } + + if v, ok := d.GetOk("storage_class"); ok { + object.StorageClass = v.(string) + } + insertCall := objectsService.Insert(bucket, object) insertCall.Name(name) insertCall.Media(media) @@ -120,19 +182,17 @@ func resourceStorageBucketObjectRead(d *schema.ResourceData, meta interface{}) e res, err := getCall.Do() if err != nil { - if gerr, ok := err.(*googleapi.Error); ok && gerr.Code == 404 { - log.Printf("[WARN] Removing Bucket Object %q because it's gone", d.Get("name").(string)) - // The resource doesn't exist anymore - d.SetId("") - - return nil - } - - return fmt.Errorf("Error retrieving contents of object %s: %s", name, err) + return handleNotFoundError(err, d, fmt.Sprintf("Storage Bucket Object %q", d.Get("name").(string))) } d.Set("md5hash", res.Md5Hash) d.Set("crc32c", res.Crc32c) + d.Set("cache_control", res.CacheControl) + d.Set("content_disposition", res.ContentDisposition) + d.Set("content_encoding", res.ContentEncoding) + d.Set("content_language", res.ContentLanguage) + d.Set("content_type", res.ContentType) + d.Set("storage_class", res.StorageClass) d.SetId(objectGetId(res)) @@ -151,6 +211,14 @@ func resourceStorageBucketObjectDelete(d *schema.ResourceData, meta interface{}) err := DeleteCall.Do() if err != nil { + if gerr, ok := err.(*googleapi.Error); ok && gerr.Code == 404 { + log.Printf("[WARN] Removing Bucket Object %q because it's gone", name) + // The resource doesn't exist anymore + d.SetId("") + + return nil + } + return fmt.Errorf("Error deleting contents of object %s: %s", name, err) } diff --git a/builtin/providers/google/resource_storage_bucket_object_test.go b/builtin/providers/google/resource_storage_bucket_object_test.go index 9ee0981e3..d3eff46db 100644 --- a/builtin/providers/google/resource_storage_bucket_object_test.go +++ b/builtin/providers/google/resource_storage_bucket_object_test.go @@ -64,7 +64,113 @@ func TestAccGoogleStorageObject_content(t *testing.T) { Steps: []resource.TestStep{ resource.TestStep{ Config: testGoogleStorageBucketsObjectContent(bucketName), - Check: testAccCheckGoogleStorageObject(bucketName, objectName, data_md5), + Check: resource.ComposeTestCheckFunc( + testAccCheckGoogleStorageObject(bucketName, objectName, data_md5), + resource.TestCheckResourceAttr( + "google_storage_bucket_object.object", "content_type", "text/plain; charset=utf-8"), + resource.TestCheckResourceAttr( + "google_storage_bucket_object.object", "storage_class", "STANDARD"), + ), + }, + }, + }) +} + +func TestAccGoogleStorageObject_withContentCharacteristics(t *testing.T) { + bucketName := testBucketName() + data := []byte(content) + h := md5.New() + h.Write(data) + data_md5 := base64.StdEncoding.EncodeToString(h.Sum(nil)) + ioutil.WriteFile(tf.Name(), data, 0644) + + disposition, encoding, language, content_type := "inline", "compress", "en", "binary/octet-stream" + resource.Test(t, resource.TestCase{ + PreCheck: func() { + if err != nil { + panic(err) + } + testAccPreCheck(t) + }, + Providers: testAccProviders, + CheckDestroy: testAccGoogleStorageObjectDestroy, + Steps: []resource.TestStep{ + resource.TestStep{ + Config: testGoogleStorageBucketsObject_optionalContentFields( + bucketName, disposition, encoding, language, content_type), + Check: resource.ComposeTestCheckFunc( + testAccCheckGoogleStorageObject(bucketName, objectName, data_md5), + resource.TestCheckResourceAttr( + "google_storage_bucket_object.object", "content_disposition", disposition), + resource.TestCheckResourceAttr( + "google_storage_bucket_object.object", "content_encoding", encoding), + resource.TestCheckResourceAttr( + "google_storage_bucket_object.object", "content_language", language), + resource.TestCheckResourceAttr( + "google_storage_bucket_object.object", "content_type", content_type), + ), + }, + }, + }) +} + +func TestAccGoogleStorageObject_cacheControl(t *testing.T) { + bucketName := testBucketName() + data := []byte(content) + h := md5.New() + h.Write(data) + data_md5 := base64.StdEncoding.EncodeToString(h.Sum(nil)) + ioutil.WriteFile(tf.Name(), data, 0644) + + cacheControl := "private" + resource.Test(t, resource.TestCase{ + PreCheck: func() { + if err != nil { + panic(err) + } + testAccPreCheck(t) + }, + Providers: testAccProviders, + CheckDestroy: testAccGoogleStorageObjectDestroy, + Steps: []resource.TestStep{ + resource.TestStep{ + Config: testGoogleStorageBucketsObject_cacheControl(bucketName, cacheControl), + Check: resource.ComposeTestCheckFunc( + testAccCheckGoogleStorageObject(bucketName, objectName, data_md5), + resource.TestCheckResourceAttr( + "google_storage_bucket_object.object", "cache_control", cacheControl), + ), + }, + }, + }) +} + +func TestAccGoogleStorageObject_storageClass(t *testing.T) { + bucketName := testBucketName() + data := []byte(content) + h := md5.New() + h.Write(data) + data_md5 := base64.StdEncoding.EncodeToString(h.Sum(nil)) + ioutil.WriteFile(tf.Name(), data, 0644) + + storageClass := "MULTI_REGIONAL" + resource.Test(t, resource.TestCase{ + PreCheck: func() { + if err != nil { + panic(err) + } + testAccPreCheck(t) + }, + Providers: testAccProviders, + CheckDestroy: testAccGoogleStorageObjectDestroy, + Steps: []resource.TestStep{ + resource.TestStep{ + Config: testGoogleStorageBucketsObject_storageClass(bucketName, storageClass), + Check: resource.ComposeTestCheckFunc( + testAccCheckGoogleStorageObject(bucketName, objectName, data_md5), + resource.TestCheckResourceAttr( + "google_storage_bucket_object.object", "storage_class", storageClass), + ), }, }, }) @@ -129,6 +235,7 @@ resource "google_storage_bucket_object" "object" { } `, bucketName, objectName, content) } + func testGoogleStorageBucketsObjectBasic(bucketName string) string { return fmt.Sprintf(` resource "google_storage_bucket" "bucket" { @@ -143,3 +250,52 @@ resource "google_storage_bucket_object" "object" { } `, bucketName, objectName, tf.Name()) } + +func testGoogleStorageBucketsObject_optionalContentFields( + bucketName, disposition, encoding, language, content_type string) string { + return fmt.Sprintf(` +resource "google_storage_bucket" "bucket" { + name = "%s" +} + +resource "google_storage_bucket_object" "object" { + name = "%s" + bucket = "${google_storage_bucket.bucket.name}" + content = "%s" + content_disposition = "%s" + content_encoding = "%s" + content_language = "%s" + content_type = "%s" +} +`, bucketName, objectName, content, disposition, encoding, language, content_type) +} + +func testGoogleStorageBucketsObject_cacheControl(bucketName, cacheControl string) string { + return fmt.Sprintf(` +resource "google_storage_bucket" "bucket" { + name = "%s" +} + +resource "google_storage_bucket_object" "object" { + name = "%s" + bucket = "${google_storage_bucket.bucket.name}" + source = "%s" + cache_control = "%s" +} +`, bucketName, objectName, tf.Name(), cacheControl) +} + +func testGoogleStorageBucketsObject_storageClass(bucketName string, storageClass string) string { + return fmt.Sprintf(` +resource "google_storage_bucket" "bucket" { + name = "%s" +} + +resource "google_storage_bucket_object" "object" { + name = "%s" + bucket = "${google_storage_bucket.bucket.name}" + content = "%s" + storage_class = "%s" +} +`, bucketName, objectName, content, storageClass) +} diff --git a/builtin/providers/google/resource_storage_bucket_test.go b/builtin/providers/google/resource_storage_bucket_test.go index 417164bec..b40cabded 100644 --- a/builtin/providers/google/resource_storage_bucket_test.go +++ b/builtin/providers/google/resource_storage_bucket_test.go @@ -86,14 +86,14 @@ func TestAccStorageStorageClass(t *testing.T) { ), }, { - Config: testGoogleStorageBucketsReaderStorageClass(bucketName, "REGIONAL", "us-central1"), + Config: testGoogleStorageBucketsReaderStorageClass(bucketName, "REGIONAL", "US-CENTRAL1"), Check: resource.ComposeTestCheckFunc( testAccCheckCloudStorageBucketExists( "google_storage_bucket.bucket", bucketName), resource.TestCheckResourceAttr( "google_storage_bucket.bucket", "storage_class", "REGIONAL"), resource.TestCheckResourceAttr( - "google_storage_bucket.bucket", "location", "us-central1"), + "google_storage_bucket.bucket", "location", "US-CENTRAL1"), ), }, }, @@ -136,6 +136,27 @@ func TestAccStorageBucketUpdate(t *testing.T) { }) } +func TestAccStorageBucketImport(t *testing.T) { + bucketName := fmt.Sprintf("tf-test-acl-bucket-%d", acctest.RandInt()) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccGoogleStorageDestroy, + Steps: []resource.TestStep{ + resource.TestStep{ + Config: testGoogleStorageBucketsReaderDefaults(bucketName), + }, + resource.TestStep{ + ResourceName: "google_storage_bucket.bucket", + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"force_destroy"}, + }, + }, + }) +} + func TestAccStorageForceDestroy(t *testing.T) { bucketName := fmt.Sprintf("tf-test-acl-bucket-%d", acctest.RandInt()) diff --git a/builtin/providers/google/resource_storage_object_acl.go b/builtin/providers/google/resource_storage_object_acl.go index 9795305b6..718260d98 100644 --- a/builtin/providers/google/resource_storage_object_acl.go +++ b/builtin/providers/google/resource_storage_object_acl.go @@ -6,7 +6,6 @@ import ( "github.com/hashicorp/terraform/helper/schema" - "google.golang.org/api/googleapi" "google.golang.org/api/storage/v1" ) @@ -138,15 +137,7 @@ func resourceStorageObjectAclRead(d *schema.ResourceData, meta interface{}) erro res, err := config.clientStorage.ObjectAccessControls.List(bucket, object).Do() if err != nil { - if gerr, ok := err.(*googleapi.Error); ok && gerr.Code == 404 { - log.Printf("[WARN] Removing Storage Object ACL for Bucket %q because it's gone", d.Get("bucket").(string)) - // The resource doesn't exist anymore - d.SetId("") - - return nil - } - - return err + return handleNotFoundError(err, d, fmt.Sprintf("Storage Object ACL for Bucket %q", d.Get("bucket").(string))) } for _, v := range res.Items { diff --git a/builtin/providers/heroku/import_heroku_app_test.go b/builtin/providers/heroku/import_heroku_app_test.go new file mode 100644 index 000000000..7ede51c67 --- /dev/null +++ b/builtin/providers/heroku/import_heroku_app_test.go @@ -0,0 +1,58 @@ +package heroku + +import ( + "fmt" + "os" + "testing" + + "github.com/hashicorp/terraform/helper/acctest" + "github.com/hashicorp/terraform/helper/resource" +) + +func TestAccHerokuApp_importBasic(t *testing.T) { + appName := fmt.Sprintf("tftest-%s", acctest.RandString(10)) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckHerokuAppDestroy, + Steps: []resource.TestStep{ + { + Config: testAccCheckHerokuAppConfig_basic(appName), + }, + { + ResourceName: "heroku_app.foobar", + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"config_vars"}, + }, + }, + }) +} + +func TestAccHerokuApp_importOrganization(t *testing.T) { + appName := fmt.Sprintf("tftest-%s", acctest.RandString(10)) + org := os.Getenv("HEROKU_ORGANIZATION") + + resource.Test(t, resource.TestCase{ + PreCheck: func() { + testAccPreCheck(t) + if org == "" { + t.Skip("HEROKU_ORGANIZATION is not set; skipping test.") + } + }, + Providers: testAccProviders, + CheckDestroy: testAccCheckHerokuAppDestroy, + Steps: []resource.TestStep{ + { + Config: testAccCheckHerokuAppConfig_organization(appName, org), + }, + { + ResourceName: "heroku_app.foobar", + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"config_vars"}, + }, + }, + }) +} diff --git a/builtin/providers/heroku/import_heroku_pipeline_test.go b/builtin/providers/heroku/import_heroku_pipeline_test.go new file mode 100644 index 000000000..bff20f44e --- /dev/null +++ b/builtin/providers/heroku/import_heroku_pipeline_test.go @@ -0,0 +1,30 @@ +package heroku + +import ( + "fmt" + "testing" + + "github.com/hashicorp/terraform/helper/acctest" + "github.com/hashicorp/terraform/helper/resource" +) + +func TestAccHerokuPipeline_importBasic(t *testing.T) { + pName := fmt.Sprintf("tftest-%s", acctest.RandString(10)) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckHerokuPipelineDestroy, + Steps: []resource.TestStep{ + { + Config: testAccCheckHerokuPipelineConfig_basic(pName), + }, + { + ResourceName: "heroku_pipeline.foobar", + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"config_vars"}, + }, + }, + }) +} diff --git a/builtin/providers/heroku/provider.go b/builtin/providers/heroku/provider.go index b6ea2bc98..fec57ca59 100644 --- a/builtin/providers/heroku/provider.go +++ b/builtin/providers/heroku/provider.go @@ -1,7 +1,9 @@ package heroku import ( + "fmt" "log" + "strings" "github.com/hashicorp/terraform/helper/schema" "github.com/hashicorp/terraform/terraform" @@ -25,11 +27,15 @@ func Provider() terraform.ResourceProvider { }, ResourcesMap: map[string]*schema.Resource{ - "heroku_app": resourceHerokuApp(), - "heroku_addon": resourceHerokuAddon(), - "heroku_domain": resourceHerokuDomain(), - "heroku_drain": resourceHerokuDrain(), - "heroku_cert": resourceHerokuCert(), + "heroku_addon": resourceHerokuAddon(), + "heroku_app": resourceHerokuApp(), + "heroku_app_feature": resourceHerokuAppFeature(), + "heroku_cert": resourceHerokuCert(), + "heroku_domain": resourceHerokuDomain(), + "heroku_drain": resourceHerokuDrain(), + "heroku_pipeline": resourceHerokuPipeline(), + "heroku_pipeline_coupling": resourceHerokuPipelineCoupling(), + "heroku_space": resourceHerokuSpace(), }, ConfigureFunc: providerConfigure, @@ -45,3 +51,12 @@ func providerConfigure(d *schema.ResourceData) (interface{}, error) { log.Println("[INFO] Initializing Heroku client") return config.Client() } + +func buildCompositeID(a, b string) string { + return fmt.Sprintf("%s:%s", a, b) +} + +func parseCompositeID(id string) (string, string) { + parts := strings.SplitN(id, ":", 2) + return parts[0], parts[1] +} diff --git a/builtin/providers/heroku/resource_heroku_addon.go b/builtin/providers/heroku/resource_heroku_addon.go index ca9123514..fe414165b 100644 --- a/builtin/providers/heroku/resource_heroku_addon.go +++ b/builtin/providers/heroku/resource_heroku_addon.go @@ -6,8 +6,10 @@ import ( "log" "strings" "sync" + "time" "github.com/cyberdelia/heroku-go/v3" + "github.com/hashicorp/terraform/helper/resource" "github.com/hashicorp/terraform/helper/schema" ) @@ -89,6 +91,20 @@ func resourceHerokuAddonCreate(d *schema.ResourceData, meta interface{}) error { d.SetId(a.ID) log.Printf("[INFO] Addon ID: %s", d.Id()) + // Wait for the Addon to be provisioned + log.Printf("[DEBUG] Waiting for Addon (%s) to be provisioned", d.Id()) + stateConf := &resource.StateChangeConf{ + Pending: []string{"provisioning"}, + Target: []string{"provisioned"}, + Refresh: AddOnStateRefreshFunc(client, app, d.Id()), + Timeout: 20 * time.Minute, + } + + if _, err := stateConf.WaitForState(); err != nil { + return fmt.Errorf("Error waiting for Addon (%s) to be provisioned: %s", d.Id(), err) + } + log.Printf("[INFO] Addon provisioned: %s", d.Id()) + return resourceHerokuAddonRead(d, meta) } @@ -167,3 +183,18 @@ func resourceHerokuAddonRetrieve(app string, id string, client *heroku.Service) return addon, nil } + +// AddOnStateRefreshFunc returns a resource.StateRefreshFunc that is used to +// watch an AddOn. +func AddOnStateRefreshFunc(client *heroku.Service, appID, addOnID string) resource.StateRefreshFunc { + return func() (interface{}, string, error) { + addon, err := client.AddOnInfo(context.TODO(), appID, addOnID) + if err != nil { + return nil, "", err + } + + // The type conversion here can be dropped when the vendored version of + // heroku-go is updated. + return (*heroku.AddOn)(addon), addon.State, nil + } +} diff --git a/builtin/providers/heroku/resource_heroku_app.go b/builtin/providers/heroku/resource_heroku_app.go index 20a6c9c0d..575f8f08b 100644 --- a/builtin/providers/heroku/resource_heroku_app.go +++ b/builtin/providers/heroku/resource_heroku_app.go @@ -16,6 +16,7 @@ import ( type herokuApplication struct { Name string Region string + Space string Stack string GitURL string WebURL string @@ -30,6 +31,7 @@ type application struct { App *herokuApplication // The heroku application Client *heroku.Service // Client to interact with the heroku API Vars map[string]string // The vars on the application + Buildpacks []string // The application's buildpack names or URLs Organization bool // is the application organization app } @@ -62,6 +64,9 @@ func (a *application) Update() error { a.App.Stack = app.Stack.Name a.App.GitURL = app.GitURL a.App.WebURL = app.WebURL + if app.Space != nil { + a.App.Space = app.Space.Name + } if app.Organization != nil { a.App.OrganizationName = app.Organization.Name } else { @@ -71,6 +76,11 @@ func (a *application) Update() error { } } + a.Buildpacks, err = retrieveBuildpacks(a.Id, a.Client) + if err != nil { + errs = append(errs, err) + } + a.Vars, err = retrieveConfigVars(a.Id, a.Client) if err != nil { errs = append(errs, err) @@ -90,12 +100,22 @@ func resourceHerokuApp() *schema.Resource { Update: resourceHerokuAppUpdate, Delete: resourceHerokuAppDelete, + Importer: &schema.ResourceImporter{ + State: resourceHerokuAppImport, + }, + Schema: map[string]*schema.Schema{ "name": { Type: schema.TypeString, Required: true, }, + "space": { + Type: schema.TypeString, + Optional: true, + ForceNew: true, + }, + "region": { Type: schema.TypeString, Required: true, @@ -109,6 +129,14 @@ func resourceHerokuApp() *schema.Resource { ForceNew: true, }, + "buildpacks": { + Type: schema.TypeList, + Optional: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + "config_vars": { Type: schema.TypeList, Optional: true, @@ -169,6 +197,24 @@ func isOrganizationApp(d *schema.ResourceData) bool { return len(v) > 0 && v[0] != nil } +func resourceHerokuAppImport(d *schema.ResourceData, m interface{}) ([]*schema.ResourceData, error) { + client := m.(*heroku.Service) + + app, err := client.AppInfo(context.TODO(), d.Id()) + if err != nil { + return nil, err + } + + // Flag organization apps by setting the organization name + if app.Organization != nil { + d.Set("organization", []map[string]interface{}{ + {"name": app.Organization.Name}, + }) + } + + return []*schema.ResourceData{d}, nil +} + func switchHerokuAppCreate(d *schema.ResourceData, meta interface{}) error { if isOrganizationApp(d) { return resourceHerokuOrgAppCreate(d, meta) @@ -208,11 +254,8 @@ func resourceHerokuAppCreate(d *schema.ResourceData, meta interface{}) error { d.SetId(a.Name) log.Printf("[INFO] App ID: %s", d.Id()) - if v, ok := d.GetOk("config_vars"); ok { - err = updateConfigVars(d.Id(), client, nil, v.([]interface{})) - if err != nil { - return err - } + if err := performAppPostCreateTasks(d, client); err != nil { + return err } return resourceHerokuAppRead(d, meta) @@ -257,6 +300,11 @@ func resourceHerokuOrgAppCreate(d *schema.ResourceData, meta interface{}) error log.Printf("[DEBUG] App region: %s", vs) opts.Region = &vs } + if v, ok := d.GetOk("space"); ok { + vs := v.(string) + log.Printf("[DEBUG] App space: %s", vs) + opts.Space = &vs + } if v, ok := d.GetOk("stack"); ok { vs := v.(string) log.Printf("[DEBUG] App stack: %s", vs) @@ -272,11 +320,8 @@ func resourceHerokuOrgAppCreate(d *schema.ResourceData, meta interface{}) error d.SetId(a.Name) log.Printf("[INFO] App ID: %s", d.Id()) - if v, ok := d.GetOk("config_vars"); ok { - err = updateConfigVars(d.Id(), client, nil, v.([]interface{})) - if err != nil { - return err - } + if err := performAppPostCreateTasks(d, client); err != nil { + return err } return resourceHerokuAppRead(d, meta) @@ -293,6 +338,9 @@ func resourceHerokuAppRead(d *schema.ResourceData, meta interface{}) error { } } + // Only track buildpacks when set in the configuration. + _, buildpacksConfigured := d.GetOk("buildpacks") + organizationApp := isOrganizationApp(d) // Only set the config_vars that we have set in the configuration. @@ -317,9 +365,14 @@ func resourceHerokuAppRead(d *schema.ResourceData, meta interface{}) error { d.Set("region", app.App.Region) d.Set("git_url", app.App.GitURL) d.Set("web_url", app.App.WebURL) + if buildpacksConfigured { + d.Set("buildpacks", app.Buildpacks) + } d.Set("config_vars", configVarsValue) d.Set("all_config_vars", app.Vars) if organizationApp { + d.Set("space", app.App.Space) + orgDetails := map[string]interface{}{ "name": app.App.OrganizationName, "locked": app.App.Locked, @@ -374,6 +427,13 @@ func resourceHerokuAppUpdate(d *schema.ResourceData, meta interface{}) error { } } + if d.HasChange("buildpacks") { + err := updateBuildpacks(d.Id(), client, d.Get("buildpacks").([]interface{})) + if err != nil { + return err + } + } + return resourceHerokuAppRead(d, meta) } @@ -402,6 +462,21 @@ func resourceHerokuAppRetrieve(id string, organization bool, client *heroku.Serv return &app, nil } +func retrieveBuildpacks(id string, client *heroku.Service) ([]string, error) { + results, err := client.BuildpackInstallationList(context.TODO(), id, nil) + + if err != nil { + return nil, err + } + + buildpacks := []string{} + for _, installation := range results { + buildpacks = append(buildpacks, installation.Buildpack.Name) + } + + return buildpacks, nil +} + func retrieveConfigVars(id string, client *heroku.Service) (map[string]string, error) { vars, err := client.ConfigVarInfoForApp(context.TODO(), id) @@ -450,3 +525,41 @@ func updateConfigVars( return nil } + +func updateBuildpacks(id string, client *heroku.Service, v []interface{}) error { + opts := heroku.BuildpackInstallationUpdateOpts{ + Updates: []struct { + Buildpack string `json:"buildpack" url:"buildpack,key"` + }{}} + + for _, buildpack := range v { + opts.Updates = append(opts.Updates, struct { + Buildpack string `json:"buildpack" url:"buildpack,key"` + }{ + Buildpack: buildpack.(string), + }) + } + + if _, err := client.BuildpackInstallationUpdate(context.TODO(), id, opts); err != nil { + return fmt.Errorf("Error updating buildpacks: %s", err) + } + + return nil +} + +// performAppPostCreateTasks performs post-create tasks common to both org and non-org apps. +func performAppPostCreateTasks(d *schema.ResourceData, client *heroku.Service) error { + if v, ok := d.GetOk("config_vars"); ok { + if err := updateConfigVars(d.Id(), client, nil, v.([]interface{})); err != nil { + return err + } + } + + if v, ok := d.GetOk("buildpacks"); ok { + if err := updateBuildpacks(d.Id(), client, v.([]interface{})); err != nil { + return err + } + } + + return nil +} diff --git a/builtin/providers/heroku/resource_heroku_app_feature.go b/builtin/providers/heroku/resource_heroku_app_feature.go new file mode 100644 index 000000000..9718fdc67 --- /dev/null +++ b/builtin/providers/heroku/resource_heroku_app_feature.go @@ -0,0 +1,101 @@ +package heroku + +import ( + "context" + "log" + + heroku "github.com/cyberdelia/heroku-go/v3" + "github.com/hashicorp/terraform/helper/schema" +) + +func resourceHerokuAppFeature() *schema.Resource { + return &schema.Resource{ + Create: resourceHerokuAppFeatureCreate, + Update: resourceHerokuAppFeatureUpdate, + Read: resourceHerokuAppFeatureRead, + Delete: resourceHerokuAppFeatureDelete, + + Schema: map[string]*schema.Schema{ + "app": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + + "name": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + + "enabled": { + Type: schema.TypeBool, + Optional: true, + Default: true, + }, + }, + } +} + +func resourceHerokuAppFeatureRead(d *schema.ResourceData, meta interface{}) error { + client := meta.(*heroku.Service) + + app, id := parseCompositeID(d.Id()) + + feature, err := client.AppFeatureInfo(context.TODO(), app, id) + if err != nil { + return err + } + + d.Set("app", app) + d.Set("name", feature.Name) + d.Set("enabled", feature.Enabled) + + return nil +} + +func resourceHerokuAppFeatureCreate(d *schema.ResourceData, meta interface{}) error { + client := meta.(*heroku.Service) + + app := d.Get("app").(string) + featureName := d.Get("name").(string) + enabled := d.Get("enabled").(bool) + + opts := heroku.AppFeatureUpdateOpts{Enabled: enabled} + + log.Printf("[DEBUG] Feature set configuration: %#v, %#v", featureName, opts) + + feature, err := client.AppFeatureUpdate(context.TODO(), app, featureName, opts) + if err != nil { + return err + } + + d.SetId(buildCompositeID(app, feature.ID)) + + return resourceHerokuAppFeatureRead(d, meta) +} + +func resourceHerokuAppFeatureUpdate(d *schema.ResourceData, meta interface{}) error { + if d.HasChange("enabled") { + return resourceHerokuAppFeatureCreate(d, meta) + } + + return resourceHerokuAppFeatureRead(d, meta) +} + +func resourceHerokuAppFeatureDelete(d *schema.ResourceData, meta interface{}) error { + client := meta.(*heroku.Service) + + app, id := parseCompositeID(d.Id()) + featureName := d.Get("name").(string) + + log.Printf("[INFO] Deleting app feature %s (%s) for app %s", featureName, id, app) + opts := heroku.AppFeatureUpdateOpts{Enabled: false} + _, err := client.AppFeatureUpdate(context.TODO(), app, id, opts) + if err != nil { + return err + } + + d.SetId("") + return nil +} diff --git a/builtin/providers/heroku/resource_heroku_app_feature_test.go b/builtin/providers/heroku/resource_heroku_app_feature_test.go new file mode 100644 index 000000000..870216ae9 --- /dev/null +++ b/builtin/providers/heroku/resource_heroku_app_feature_test.go @@ -0,0 +1,135 @@ +package heroku + +import ( + "context" + "fmt" + "testing" + + heroku "github.com/cyberdelia/heroku-go/v3" + "github.com/hashicorp/terraform/helper/acctest" + "github.com/hashicorp/terraform/helper/resource" + "github.com/hashicorp/terraform/terraform" +) + +func TestAccHerokuAppFeature(t *testing.T) { + var feature heroku.AppFeatureInfoResult + appName := fmt.Sprintf("tftest-%s", acctest.RandString(10)) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckHerokuFeatureDestroy, + Steps: []resource.TestStep{ + { + Config: testAccCheckHerokuFeature_basic(appName), + Check: resource.ComposeTestCheckFunc( + testAccCheckHerokuFeatureExists("heroku_app_feature.runtime_metrics", &feature), + testAccCheckHerokuFeatureEnabled(&feature, true), + resource.TestCheckResourceAttr( + "heroku_app_feature.runtime_metrics", "enabled", "true", + ), + ), + }, + { + Config: testAccCheckHerokuFeature_disabled(appName), + Check: resource.ComposeTestCheckFunc( + testAccCheckHerokuFeatureExists("heroku_app_feature.runtime_metrics", &feature), + testAccCheckHerokuFeatureEnabled(&feature, false), + resource.TestCheckResourceAttr( + "heroku_app_feature.runtime_metrics", "enabled", "false", + ), + ), + }, + }, + }) +} + +func testAccCheckHerokuFeatureDestroy(s *terraform.State) error { + client := testAccProvider.Meta().(*heroku.Service) + + for _, rs := range s.RootModule().Resources { + if rs.Type != "heroku_app_feature" { + continue + } + + _, err := client.AppFeatureInfo(context.TODO(), rs.Primary.Attributes["app"], rs.Primary.ID) + + if err == nil { + return fmt.Errorf("Feature still exists") + } + } + + return nil +} + +func testAccCheckHerokuFeatureExists(n string, feature *heroku.AppFeatureInfoResult) resource.TestCheckFunc { + return func(s *terraform.State) error { + rs, ok := s.RootModule().Resources[n] + + if !ok { + return fmt.Errorf("Not found: %s", n) + } + + if rs.Primary.ID == "" { + return fmt.Errorf("No feature ID is set") + } + + app, id := parseCompositeID(rs.Primary.ID) + if app != rs.Primary.Attributes["app"] { + return fmt.Errorf("Bad app: %s", app) + } + + client := testAccProvider.Meta().(*heroku.Service) + + foundFeature, err := client.AppFeatureInfo(context.TODO(), app, id) + if err != nil { + return err + } + + if foundFeature.ID != id { + return fmt.Errorf("Feature not found") + } + + *feature = *foundFeature + return nil + } +} + +func testAccCheckHerokuFeatureEnabled(feature *heroku.AppFeatureInfoResult, enabled bool) resource.TestCheckFunc { + return func(s *terraform.State) error { + if feature.Enabled != enabled { + return fmt.Errorf("Bad enabled: %v", feature.Enabled) + } + + return nil + } +} + +func testAccCheckHerokuFeature_basic(appName string) string { + return fmt.Sprintf(` +resource "heroku_app" "example" { + name = "%s" + region = "us" +} + +resource "heroku_app_feature" "runtime_metrics" { + app = "${heroku_app.example.name}" + name = "log-runtime-metrics" +} +`, appName) +} + +func testAccCheckHerokuFeature_disabled(appName string) string { + return fmt.Sprintf(` +resource "heroku_app" "example" { + name = "%s" + region = "us" +} + +resource "heroku_app_feature" "runtime_metrics" { + app = "${heroku_app.example.name}" + name = "log-runtime-metrics" + enabled = false +} +`, appName) +} diff --git a/builtin/providers/heroku/resource_heroku_app_test.go b/builtin/providers/heroku/resource_heroku_app_test.go index caeade8f2..5888271af 100644 --- a/builtin/providers/heroku/resource_heroku_app_test.go +++ b/builtin/providers/heroku/resource_heroku_app_test.go @@ -109,6 +109,75 @@ func TestAccHerokuApp_NukeVars(t *testing.T) { }) } +func TestAccHerokuApp_Buildpacks(t *testing.T) { + var app heroku.AppInfoResult + appName := fmt.Sprintf("tftest-%s", acctest.RandString(10)) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckHerokuAppDestroy, + Steps: []resource.TestStep{ + { + Config: testAccCheckHerokuAppConfig_go(appName), + Check: resource.ComposeTestCheckFunc( + testAccCheckHerokuAppExists("heroku_app.foobar", &app), + testAccCheckHerokuAppBuildpacks(appName, false), + resource.TestCheckResourceAttr("heroku_app.foobar", "buildpacks.0", "heroku/go"), + ), + }, + { + Config: testAccCheckHerokuAppConfig_multi(appName), + Check: resource.ComposeTestCheckFunc( + testAccCheckHerokuAppExists("heroku_app.foobar", &app), + testAccCheckHerokuAppBuildpacks(appName, true), + resource.TestCheckResourceAttr( + "heroku_app.foobar", "buildpacks.0", "https://github.com/heroku/heroku-buildpack-multi-procfile"), + resource.TestCheckResourceAttr("heroku_app.foobar", "buildpacks.1", "heroku/go"), + ), + }, + { + Config: testAccCheckHerokuAppConfig_no_vars(appName), + Check: resource.ComposeTestCheckFunc( + testAccCheckHerokuAppExists("heroku_app.foobar", &app), + testAccCheckHerokuAppNoBuildpacks(appName), + resource.TestCheckNoResourceAttr("heroku_app.foobar", "buildpacks.0"), + ), + }, + }, + }) +} + +func TestAccHerokuApp_ExternallySetBuildpacks(t *testing.T) { + var app heroku.AppInfoResult + appName := fmt.Sprintf("tftest-%s", acctest.RandString(10)) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckHerokuAppDestroy, + Steps: []resource.TestStep{ + { + Config: testAccCheckHerokuAppConfig_no_vars(appName), + Check: resource.ComposeTestCheckFunc( + testAccCheckHerokuAppExists("heroku_app.foobar", &app), + testAccCheckHerokuAppNoBuildpacks(appName), + resource.TestCheckNoResourceAttr("heroku_app.foobar", "buildpacks.0"), + ), + }, + { + PreConfig: testAccInstallUnconfiguredBuildpack(t, appName), + Config: testAccCheckHerokuAppConfig_no_vars(appName), + Check: resource.ComposeTestCheckFunc( + testAccCheckHerokuAppExists("heroku_app.foobar", &app), + testAccCheckHerokuAppBuildpacks(appName, false), + resource.TestCheckNoResourceAttr("heroku_app.foobar", "buildpacks.0"), + ), + }, + }, + }) +} + func TestAccHerokuApp_Organization(t *testing.T) { var app heroku.OrganizationApp appName := fmt.Sprintf("tftest-%s", acctest.RandString(10)) @@ -128,7 +197,37 @@ func TestAccHerokuApp_Organization(t *testing.T) { Config: testAccCheckHerokuAppConfig_organization(appName, org), Check: resource.ComposeTestCheckFunc( testAccCheckHerokuAppExistsOrg("heroku_app.foobar", &app), - testAccCheckHerokuAppAttributesOrg(&app, appName, org), + testAccCheckHerokuAppAttributesOrg(&app, appName, "", org), + ), + }, + }, + }) +} + +func TestAccHerokuApp_Space(t *testing.T) { + var app heroku.OrganizationApp + appName := fmt.Sprintf("tftest-%s", acctest.RandString(10)) + org := os.Getenv("HEROKU_ORGANIZATION") + space := os.Getenv("HEROKU_SPACE") + + resource.Test(t, resource.TestCase{ + PreCheck: func() { + testAccPreCheck(t) + if org == "" { + t.Skip("HEROKU_ORGANIZATION is not set; skipping test.") + } + if space == "" { + t.Skip("HEROKU_SPACE is not set; skipping test.") + } + }, + Providers: testAccProviders, + CheckDestroy: testAccCheckHerokuAppDestroy, + Steps: []resource.TestStep{ + { + Config: testAccCheckHerokuAppConfig_space(appName, space, org), + Check: resource.ComposeTestCheckFunc( + testAccCheckHerokuAppExistsOrg("heroku_app.foobar", &app), + testAccCheckHerokuAppAttributesOrg(&app, appName, space, org), ), }, }, @@ -230,14 +329,76 @@ func testAccCheckHerokuAppAttributesNoVars(app *heroku.AppInfoResult, appName st } } -func testAccCheckHerokuAppAttributesOrg(app *heroku.OrganizationApp, appName string, org string) resource.TestCheckFunc { +func testAccCheckHerokuAppBuildpacks(appName string, multi bool) resource.TestCheckFunc { return func(s *terraform.State) error { client := testAccProvider.Meta().(*heroku.Service) - if app.Region.Name != "us" { + results, err := client.BuildpackInstallationList(context.TODO(), appName, nil) + if err != nil { + return err + } + + buildpacks := []string{} + for _, installation := range results { + buildpacks = append(buildpacks, installation.Buildpack.Name) + } + + if multi { + herokuMulti := "https://github.com/heroku/heroku-buildpack-multi-procfile" + if len(buildpacks) != 2 || buildpacks[0] != herokuMulti || buildpacks[1] != "heroku/go" { + return fmt.Errorf("Bad buildpacks: %v", buildpacks) + } + + return nil + } + + if len(buildpacks) != 1 || buildpacks[0] != "heroku/go" { + return fmt.Errorf("Bad buildpacks: %v", buildpacks) + } + + return nil + } +} + +func testAccCheckHerokuAppNoBuildpacks(appName string) resource.TestCheckFunc { + return func(s *terraform.State) error { + client := testAccProvider.Meta().(*heroku.Service) + + results, err := client.BuildpackInstallationList(context.TODO(), appName, nil) + if err != nil { + return err + } + + buildpacks := []string{} + for _, installation := range results { + buildpacks = append(buildpacks, installation.Buildpack.Name) + } + + if len(buildpacks) != 0 { + return fmt.Errorf("Bad buildpacks: %v", buildpacks) + } + + return nil + } +} + +func testAccCheckHerokuAppAttributesOrg(app *heroku.OrganizationApp, appName, space, org string) resource.TestCheckFunc { + return func(s *terraform.State) error { + client := testAccProvider.Meta().(*heroku.Service) + + if app.Region.Name != "us" && app.Region.Name != "virginia" { return fmt.Errorf("Bad region: %s", app.Region.Name) } + var appSpace string + if app.Space != nil { + appSpace = app.Space.Name + } + + if appSpace != space { + return fmt.Errorf("Bad space: %s", appSpace) + } + if app.Stack.Name != "cedar-14" { return fmt.Errorf("Bad stack: %s", app.Stack.Name) } @@ -323,6 +484,25 @@ func testAccCheckHerokuAppExistsOrg(n string, app *heroku.OrganizationApp) resou } } +func testAccInstallUnconfiguredBuildpack(t *testing.T, appName string) func() { + return func() { + client := testAccProvider.Meta().(*heroku.Service) + + opts := heroku.BuildpackInstallationUpdateOpts{ + Updates: []struct { + Buildpack string `json:"buildpack" url:"buildpack,key"` + }{ + {Buildpack: "heroku/go"}, + }, + } + + _, err := client.BuildpackInstallationUpdate(context.TODO(), appName, opts) + if err != nil { + t.Fatalf("Error updating buildpacks: %s", err) + } + } +} + func testAccCheckHerokuAppConfig_basic(appName string) string { return fmt.Sprintf(` resource "heroku_app" "foobar" { @@ -335,6 +515,29 @@ resource "heroku_app" "foobar" { }`, appName) } +func testAccCheckHerokuAppConfig_go(appName string) string { + return fmt.Sprintf(` +resource "heroku_app" "foobar" { + name = "%s" + region = "us" + + buildpacks = ["heroku/go"] +}`, appName) +} + +func testAccCheckHerokuAppConfig_multi(appName string) string { + return fmt.Sprintf(` +resource "heroku_app" "foobar" { + name = "%s" + region = "us" + + buildpacks = [ + "https://github.com/heroku/heroku-buildpack-multi-procfile", + "heroku/go" + ] +}`, appName) +} + func testAccCheckHerokuAppConfig_updated(appName string) string { return fmt.Sprintf(` resource "heroku_app" "foobar" { @@ -371,3 +574,20 @@ resource "heroku_app" "foobar" { } }`, appName, org) } + +func testAccCheckHerokuAppConfig_space(appName, space, org string) string { + return fmt.Sprintf(` +resource "heroku_app" "foobar" { + name = "%s" + space = "%s" + region = "virginia" + + organization { + name = "%s" + } + + config_vars { + FOO = "bar" + } +}`, appName, space, org) +} diff --git a/builtin/providers/heroku/resource_heroku_cert.go b/builtin/providers/heroku/resource_heroku_cert.go index a6390e4e2..8b4d5eacb 100644 --- a/builtin/providers/heroku/resource_heroku_cert.go +++ b/builtin/providers/heroku/resource_heroku_cert.go @@ -88,22 +88,20 @@ func resourceHerokuCertUpdate(d *schema.ResourceData, meta interface{}) error { client := meta.(*heroku.Service) app := d.Get("app").(string) + preprocess := true + rollback := false + opts := heroku.SSLEndpointUpdateOpts{ + CertificateChain: heroku.String(d.Get("certificate_chain").(string)), + Preprocess: &preprocess, + PrivateKey: heroku.String(d.Get("private_key").(string)), + Rollback: &rollback} - if d.HasChange("certificate_chain") { - preprocess := true - rollback := false - ad, err := client.SSLEndpointUpdate( - context.TODO(), app, d.Id(), heroku.SSLEndpointUpdateOpts{ - CertificateChain: d.Get("certificate_chain").(*string), - Preprocess: &preprocess, - PrivateKey: d.Get("private_key").(*string), - Rollback: &rollback}) + if d.HasChange("certificate_chain") || d.HasChange("private_key") { + log.Printf("[DEBUG] SSL Certificate update configuration: %#v, %#v", app, opts) + _, err := client.SSLEndpointUpdate(context.TODO(), app, d.Id(), opts) if err != nil { - return err + return fmt.Errorf("Error updating SSL endpoint: %s", err) } - - // Store the new ID - d.SetId(ad.ID) } return resourceHerokuCertRead(d, meta) diff --git a/builtin/providers/heroku/resource_heroku_cert_test.go b/builtin/providers/heroku/resource_heroku_cert_test.go index e40fe4b03..91fbd111f 100644 --- a/builtin/providers/heroku/resource_heroku_cert_test.go +++ b/builtin/providers/heroku/resource_heroku_cert_test.go @@ -5,7 +5,10 @@ import ( "fmt" "io/ioutil" "os" + "regexp" + "strings" "testing" + "time" "github.com/cyberdelia/heroku-go/v3" "github.com/hashicorp/terraform/helper/acctest" @@ -13,31 +16,32 @@ import ( "github.com/hashicorp/terraform/terraform" ) -func TestAccHerokuCert_Basic(t *testing.T) { +// We break apart testing for EU and US because at present, Heroku deals with +// each a bit differently and the setup/teardown of separate tests seems to +// help them to perform more consistently. +// https://devcenter.heroku.com/articles/ssl-endpoint#add-certificate-and-intermediaries +// +// We also have a time.Sleep() set for the update step (step 2 of 2) in each +// region's tests. This is somewhat kludgy, but the Heroku API SSL Endpoint +// handles parts of the create and update requests asynchronously, and if you +// add a cert+key then immediately update it, and then delete it (end of test), +// there are scenarios where the operations get out of order. For now, sleeping +// on update seems to allow the test to run smoothly; in real life, this test +// case is definitely an extreme edge case. +func TestAccHerokuCert_EU(t *testing.T) { var endpoint heroku.SSLEndpointInfoResult - wd, _ := os.Getwd() - certificateChainFile := wd + "/test-fixtures/terraform.cert" - certificateChainBytes, _ := ioutil.ReadFile(certificateChainFile) - certificateChain := string(certificateChainBytes) appName := fmt.Sprintf("tftest-%s", acctest.RandString(10)) - testAccCheckHerokuCertConfig_basic := ` - resource "heroku_app" "foobar" { - name = "` + appName + `" - region = "eu" - } - resource "heroku_addon" "ssl" { - app = "${heroku_app.foobar.name}" - plan = "ssl:endpoint" - } + wd, _ := os.Getwd() + certFile := wd + "/test-fixtures/terraform.cert" + certFile2 := wd + "/test-fixtures/terraform2.cert" + keyFile := wd + "/test-fixtures/terraform.key" + keyFile2 := wd + "/test-fixtures/terraform2.key" - resource "heroku_cert" "ssl_certificate" { - app = "${heroku_app.foobar.name}" - depends_on = ["heroku_addon.ssl"] - certificate_chain="${file("` + certificateChainFile + `")}" - private_key="${file("` + wd + `/test-fixtures/terraform.key")}" - } - ` + certificateChainBytes, _ := ioutil.ReadFile(certFile) + certificateChain := string(certificateChainBytes) + certificateChain2Bytes, _ := ioutil.ReadFile(certFile2) + certificateChain2 := string(certificateChain2Bytes) resource.Test(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, @@ -45,7 +49,7 @@ func TestAccHerokuCert_Basic(t *testing.T) { CheckDestroy: testAccCheckHerokuCertDestroy, Steps: []resource.TestStep{ { - Config: testAccCheckHerokuCertConfig_basic, + Config: testAccCheckHerokuCertEUConfig(appName, certFile, keyFile), Check: resource.ComposeTestCheckFunc( testAccCheckHerokuCertExists("heroku_cert.ssl_certificate", &endpoint), testAccCheckHerokuCertificateChain(&endpoint, certificateChain), @@ -54,10 +58,112 @@ func TestAccHerokuCert_Basic(t *testing.T) { "cname", fmt.Sprintf("%s.herokuapp.com", appName)), ), }, + { + PreConfig: sleep(t, 15), + Config: testAccCheckHerokuCertEUConfig(appName, certFile2, keyFile2), + Check: resource.ComposeTestCheckFunc( + testAccCheckHerokuCertExists("heroku_cert.ssl_certificate", &endpoint), + testAccCheckHerokuCertificateChain(&endpoint, certificateChain2), + resource.TestCheckResourceAttr( + "heroku_cert.ssl_certificate", + "cname", fmt.Sprintf("%s.herokuapp.com", appName)), + ), + }, }, }) } +func TestAccHerokuCert_US(t *testing.T) { + var endpoint heroku.SSLEndpointInfoResult + appName := fmt.Sprintf("tftest-%s", acctest.RandString(10)) + + wd, _ := os.Getwd() + certFile := wd + "/test-fixtures/terraform.cert" + certFile2 := wd + "/test-fixtures/terraform2.cert" + keyFile := wd + "/test-fixtures/terraform.key" + keyFile2 := wd + "/test-fixtures/terraform2.key" + + certificateChainBytes, _ := ioutil.ReadFile(certFile) + certificateChain := string(certificateChainBytes) + certificateChain2Bytes, _ := ioutil.ReadFile(certFile2) + certificateChain2 := string(certificateChain2Bytes) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckHerokuCertDestroy, + Steps: []resource.TestStep{ + { + Config: testAccCheckHerokuCertUSConfig(appName, certFile2, keyFile2), + Check: resource.ComposeTestCheckFunc( + testAccCheckHerokuCertExists("heroku_cert.ssl_certificate", &endpoint), + testAccCheckHerokuCertificateChain(&endpoint, certificateChain2), + resource.TestMatchResourceAttr( + "heroku_cert.ssl_certificate", + "cname", regexp.MustCompile(`herokussl`)), + ), + }, + { + PreConfig: sleep(t, 15), + Config: testAccCheckHerokuCertUSConfig(appName, certFile, keyFile), + Check: resource.ComposeTestCheckFunc( + testAccCheckHerokuCertExists("heroku_cert.ssl_certificate", &endpoint), + testAccCheckHerokuCertificateChain(&endpoint, certificateChain), + resource.TestMatchResourceAttr( + "heroku_cert.ssl_certificate", + "cname", regexp.MustCompile(`herokussl`)), + ), + }, + }, + }) +} + +func testAccCheckHerokuCertEUConfig(appName, certFile, keyFile string) string { + return strings.TrimSpace(fmt.Sprintf(` +resource "heroku_app" "foobar" { + name = "%s" + region = "eu" +} + +resource "heroku_addon" "ssl" { + app = "${heroku_app.foobar.name}" + plan = "ssl:endpoint" +} + +resource "heroku_cert" "ssl_certificate" { + app = "${heroku_app.foobar.name}" + depends_on = ["heroku_addon.ssl"] + certificate_chain="${file("%s")}" + private_key="${file("%s")}" +}`, appName, certFile, keyFile)) +} + +func testAccCheckHerokuCertUSConfig(appName, certFile, keyFile string) string { + return strings.TrimSpace(fmt.Sprintf(` +resource "heroku_app" "foobar" { + name = "%s" + region = "us" +} + +resource "heroku_addon" "ssl" { + app = "${heroku_app.foobar.name}" + plan = "ssl:endpoint" +} + +resource "heroku_cert" "ssl_certificate" { + app = "${heroku_app.foobar.name}" + depends_on = ["heroku_addon.ssl"] + certificate_chain="${file("%s")}" + private_key="${file("%s")}" +}`, appName, certFile, keyFile)) +} + +func sleep(t *testing.T, amount time.Duration) func() { + return func() { + time.Sleep(amount * time.Second) + } +} + func testAccCheckHerokuCertDestroy(s *terraform.State) error { client := testAccProvider.Meta().(*heroku.Service) diff --git a/builtin/providers/heroku/resource_heroku_domain.go b/builtin/providers/heroku/resource_heroku_domain.go index da2a8ab17..1fb9bf128 100644 --- a/builtin/providers/heroku/resource_heroku_domain.go +++ b/builtin/providers/heroku/resource_heroku_domain.go @@ -51,7 +51,7 @@ func resourceHerokuDomainCreate(d *schema.ResourceData, meta interface{}) error d.SetId(do.ID) d.Set("hostname", do.Hostname) - d.Set("cname", fmt.Sprintf("%s.herokuapp.com", app)) + d.Set("cname", do.CName) log.Printf("[INFO] Domain ID: %s", d.Id()) return nil @@ -81,7 +81,7 @@ func resourceHerokuDomainRead(d *schema.ResourceData, meta interface{}) error { } d.Set("hostname", do.Hostname) - d.Set("cname", fmt.Sprintf("%s.herokuapp.com", app)) + d.Set("cname", do.CName) return nil } diff --git a/builtin/providers/heroku/resource_heroku_domain_test.go b/builtin/providers/heroku/resource_heroku_domain_test.go index 9e1abe862..7e5b01528 100644 --- a/builtin/providers/heroku/resource_heroku_domain_test.go +++ b/builtin/providers/heroku/resource_heroku_domain_test.go @@ -30,8 +30,7 @@ func TestAccHerokuDomain_Basic(t *testing.T) { resource.TestCheckResourceAttr( "heroku_domain.foobar", "app", appName), resource.TestCheckResourceAttr( - "heroku_domain.foobar", "cname", - fmt.Sprintf("%s.herokuapp.com", appName)), + "heroku_domain.foobar", "cname", "terraform.example.com.herokudns.com"), ), }, }, diff --git a/builtin/providers/heroku/resource_heroku_pipeline.go b/builtin/providers/heroku/resource_heroku_pipeline.go new file mode 100644 index 000000000..94b0959c4 --- /dev/null +++ b/builtin/providers/heroku/resource_heroku_pipeline.go @@ -0,0 +1,109 @@ +package heroku + +import ( + "context" + "fmt" + "log" + + "github.com/cyberdelia/heroku-go/v3" + "github.com/hashicorp/terraform/helper/schema" +) + +func resourceHerokuPipeline() *schema.Resource { + return &schema.Resource{ + Create: resourceHerokuPipelineCreate, + Update: resourceHerokuPipelineUpdate, + Read: resourceHerokuPipelineRead, + Delete: resourceHerokuPipelineDelete, + + Importer: &schema.ResourceImporter{ + State: resourceHerokuPipelineImport, + }, + + Schema: map[string]*schema.Schema{ + "name": { + Type: schema.TypeString, + Required: true, + }, + }, + } +} + +func resourceHerokuPipelineImport(d *schema.ResourceData, meta interface{}) ([]*schema.ResourceData, error) { + client := meta.(*heroku.Service) + + p, err := client.PipelineInfo(context.TODO(), d.Id()) + if err != nil { + return nil, err + } + + d.Set("name", p.Name) + + return []*schema.ResourceData{d}, nil +} + +func resourceHerokuPipelineCreate(d *schema.ResourceData, meta interface{}) error { + client := meta.(*heroku.Service) + + opts := heroku.PipelineCreateOpts{ + Name: d.Get("name").(string), + } + + log.Printf("[DEBUG] Pipeline create configuration: %#v", opts) + + p, err := client.PipelineCreate(context.TODO(), opts) + if err != nil { + return fmt.Errorf("Error creating pipeline: %s", err) + } + + d.SetId(p.ID) + d.Set("name", p.Name) + + log.Printf("[INFO] Pipeline ID: %s", d.Id()) + + return resourceHerokuPipelineUpdate(d, meta) +} + +func resourceHerokuPipelineUpdate(d *schema.ResourceData, meta interface{}) error { + client := meta.(*heroku.Service) + + if d.HasChange("name") { + name := d.Get("name").(string) + opts := heroku.PipelineUpdateOpts{ + Name: &name, + } + + _, err := client.PipelineUpdate(context.TODO(), d.Id(), opts) + if err != nil { + return err + } + } + + return resourceHerokuPipelineRead(d, meta) +} + +func resourceHerokuPipelineDelete(d *schema.ResourceData, meta interface{}) error { + client := meta.(*heroku.Service) + + log.Printf("[INFO] Deleting pipeline: %s", d.Id()) + + _, err := client.PipelineDelete(context.TODO(), d.Id()) + if err != nil { + return fmt.Errorf("Error deleting pipeline: %s", err) + } + + return nil +} + +func resourceHerokuPipelineRead(d *schema.ResourceData, meta interface{}) error { + client := meta.(*heroku.Service) + + p, err := client.PipelineInfo(context.TODO(), d.Id()) + if err != nil { + return fmt.Errorf("Error retrieving pipeline: %s", err) + } + + d.Set("name", p.Name) + + return nil +} diff --git a/builtin/providers/heroku/resource_heroku_pipeline_coupling.go b/builtin/providers/heroku/resource_heroku_pipeline_coupling.go new file mode 100644 index 000000000..90b70447a --- /dev/null +++ b/builtin/providers/heroku/resource_heroku_pipeline_coupling.go @@ -0,0 +1,89 @@ +package heroku + +import ( + "context" + "fmt" + "log" + + "github.com/cyberdelia/heroku-go/v3" + "github.com/hashicorp/terraform/helper/schema" +) + +func resourceHerokuPipelineCoupling() *schema.Resource { + return &schema.Resource{ + Create: resourceHerokuPipelineCouplingCreate, + Read: resourceHerokuPipelineCouplingRead, + Delete: resourceHerokuPipelineCouplingDelete, + + Schema: map[string]*schema.Schema{ + "app": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + "pipeline": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + ValidateFunc: validateUUID, + }, + "stage": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + ValidateFunc: validatePipelineStageName, + }, + }, + } +} + +func resourceHerokuPipelineCouplingCreate(d *schema.ResourceData, meta interface{}) error { + client := meta.(*heroku.Service) + + opts := heroku.PipelineCouplingCreateOpts{ + App: d.Get("app").(string), + Pipeline: d.Get("pipeline").(string), + Stage: d.Get("stage").(string), + } + + log.Printf("[DEBUG] PipelineCoupling create configuration: %#v", opts) + + p, err := client.PipelineCouplingCreate(context.TODO(), opts) + if err != nil { + return fmt.Errorf("Error creating pipeline: %s", err) + } + + d.SetId(p.ID) + + log.Printf("[INFO] PipelineCoupling ID: %s", d.Id()) + + return resourceHerokuPipelineCouplingRead(d, meta) +} + +func resourceHerokuPipelineCouplingDelete(d *schema.ResourceData, meta interface{}) error { + client := meta.(*heroku.Service) + + log.Printf("[INFO] Deleting pipeline: %s", d.Id()) + + _, err := client.PipelineCouplingDelete(context.TODO(), d.Id()) + if err != nil { + return fmt.Errorf("Error deleting pipeline: %s", err) + } + + return nil +} + +func resourceHerokuPipelineCouplingRead(d *schema.ResourceData, meta interface{}) error { + client := meta.(*heroku.Service) + + p, err := client.PipelineCouplingInfo(context.TODO(), d.Id()) + if err != nil { + return fmt.Errorf("Error retrieving pipeline: %s", err) + } + + d.Set("app", p.App) + d.Set("pipeline", p.Pipeline) + d.Set("stage", p.Stage) + + return nil +} diff --git a/builtin/providers/heroku/resource_heroku_pipeline_coupling_test.go b/builtin/providers/heroku/resource_heroku_pipeline_coupling_test.go new file mode 100644 index 000000000..6fd8b5195 --- /dev/null +++ b/builtin/providers/heroku/resource_heroku_pipeline_coupling_test.go @@ -0,0 +1,123 @@ +package heroku + +import ( + "context" + "fmt" + "testing" + + heroku "github.com/cyberdelia/heroku-go/v3" + "github.com/hashicorp/terraform/helper/acctest" + "github.com/hashicorp/terraform/helper/resource" + "github.com/hashicorp/terraform/terraform" +) + +func TestAccHerokuPipelineCoupling_Basic(t *testing.T) { + var coupling heroku.PipelineCouplingInfoResult + + appName := fmt.Sprintf("tftest-%s", acctest.RandString(10)) + pipelineName := fmt.Sprintf("tftest-%s", acctest.RandString(10)) + stageName := "development" + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckHerokuPipelineCouplingDestroy, + Steps: []resource.TestStep{ + { + Config: testAccCheckHerokuPipelineCouplingConfig_basic(appName, pipelineName, stageName), + Check: resource.ComposeTestCheckFunc( + testAccCheckHerokuPipelineCouplingExists("heroku_pipeline_coupling.default", &coupling), + testAccCheckHerokuPipelineCouplingAttributes( + &coupling, + "heroku_pipeline.default", + stageName, + ), + ), + }, + }, + }) +} + +func testAccCheckHerokuPipelineCouplingConfig_basic(appName, pipelineName, stageName string) string { + return fmt.Sprintf(` +resource "heroku_app" "default" { + name = "%s" + region = "us" +} + +resource "heroku_pipeline" "default" { + name = "%s" +} + +resource "heroku_pipeline_coupling" "default" { + app = "${heroku_app.default.id}" + pipeline = "${heroku_pipeline.default.id}" + stage = "%s" +} +`, appName, pipelineName, stageName) +} + +func testAccCheckHerokuPipelineCouplingExists(n string, pipeline *heroku.PipelineCouplingInfoResult) resource.TestCheckFunc { + return func(s *terraform.State) error { + rs, ok := s.RootModule().Resources[n] + + if !ok { + return fmt.Errorf("Not found: %s", n) + } + + if rs.Primary.ID == "" { + return fmt.Errorf("No coupling ID set") + } + + client := testAccProvider.Meta().(*heroku.Service) + + foundPipelineCoupling, err := client.PipelineCouplingInfo(context.TODO(), rs.Primary.ID) + if err != nil { + return err + } + + if foundPipelineCoupling.ID != rs.Primary.ID { + return fmt.Errorf("PipelineCoupling not found: %s != %s", foundPipelineCoupling.ID, rs.Primary.ID) + } + + *pipeline = *foundPipelineCoupling + + return nil + } +} + +func testAccCheckHerokuPipelineCouplingAttributes(coupling *heroku.PipelineCouplingInfoResult, pipelineResource, stageName string) resource.TestCheckFunc { + return func(s *terraform.State) error { + pipeline, ok := s.RootModule().Resources[pipelineResource] + if !ok { + return fmt.Errorf("Pipeline not found: %s", pipelineResource) + } + + if coupling.Pipeline.ID != pipeline.Primary.ID { + return fmt.Errorf("Bad pipeline ID: %v != %v", coupling.Pipeline.ID, pipeline.Primary.ID) + } + if coupling.Stage != stageName { + return fmt.Errorf("Bad stage: %s", coupling.Stage) + } + + return nil + } +} + +func testAccCheckHerokuPipelineCouplingDestroy(s *terraform.State) error { + client := testAccProvider.Meta().(*heroku.Service) + + for _, rs := range s.RootModule().Resources { + if rs.Type != "heroku_pipeline_coupling" { + continue + } + + _, err := client.PipelineCouplingInfo(context.TODO(), rs.Primary.ID) + + if err == nil { + return fmt.Errorf("PipelineCoupling still exists") + } + } + + return nil +} diff --git a/builtin/providers/heroku/resource_heroku_pipeline_test.go b/builtin/providers/heroku/resource_heroku_pipeline_test.go new file mode 100644 index 000000000..1c40e1403 --- /dev/null +++ b/builtin/providers/heroku/resource_heroku_pipeline_test.go @@ -0,0 +1,96 @@ +package heroku + +import ( + "context" + "fmt" + "testing" + + heroku "github.com/cyberdelia/heroku-go/v3" + "github.com/hashicorp/terraform/helper/acctest" + "github.com/hashicorp/terraform/helper/resource" + "github.com/hashicorp/terraform/terraform" +) + +func TestAccHerokuPipeline_Basic(t *testing.T) { + var pipeline heroku.PipelineInfoResult + pipelineName := fmt.Sprintf("tftest-%s", acctest.RandString(10)) + pipelineName2 := fmt.Sprintf("%s-2", pipelineName) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckHerokuPipelineDestroy, + Steps: []resource.TestStep{ + { + Config: testAccCheckHerokuPipelineConfig_basic(pipelineName), + Check: resource.ComposeTestCheckFunc( + testAccCheckHerokuPipelineExists("heroku_pipeline.foobar", &pipeline), + resource.TestCheckResourceAttr( + "heroku_pipeline.foobar", "name", pipelineName), + ), + }, + { + Config: testAccCheckHerokuPipelineConfig_basic(pipelineName2), + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttr( + "heroku_pipeline.foobar", "name", pipelineName2), + ), + }, + }, + }) +} + +func testAccCheckHerokuPipelineConfig_basic(pipelineName string) string { + return fmt.Sprintf(` +resource "heroku_pipeline" "foobar" { + name = "%s" +} +`, pipelineName) +} + +func testAccCheckHerokuPipelineExists(n string, pipeline *heroku.PipelineInfoResult) resource.TestCheckFunc { + return func(s *terraform.State) error { + rs, ok := s.RootModule().Resources[n] + + if !ok { + return fmt.Errorf("Not found: %s", n) + } + + if rs.Primary.ID == "" { + return fmt.Errorf("No pipeline name set") + } + + client := testAccProvider.Meta().(*heroku.Service) + + foundPipeline, err := client.PipelineInfo(context.TODO(), rs.Primary.ID) + if err != nil { + return err + } + + if foundPipeline.ID != rs.Primary.ID { + return fmt.Errorf("Pipeline not found") + } + + *pipeline = *foundPipeline + + return nil + } +} + +func testAccCheckHerokuPipelineDestroy(s *terraform.State) error { + client := testAccProvider.Meta().(*heroku.Service) + + for _, rs := range s.RootModule().Resources { + if rs.Type != "heroku_pipeline" { + continue + } + + _, err := client.PipelineInfo(context.TODO(), rs.Primary.ID) + + if err == nil { + return fmt.Errorf("Pipeline still exists") + } + } + + return nil +} diff --git a/builtin/providers/heroku/resource_heroku_space.go b/builtin/providers/heroku/resource_heroku_space.go new file mode 100644 index 000000000..fcabee429 --- /dev/null +++ b/builtin/providers/heroku/resource_heroku_space.go @@ -0,0 +1,144 @@ +package heroku + +import ( + "context" + "fmt" + "log" + "time" + + heroku "github.com/cyberdelia/heroku-go/v3" + "github.com/hashicorp/terraform/helper/resource" + "github.com/hashicorp/terraform/helper/schema" +) + +func resourceHerokuSpace() *schema.Resource { + return &schema.Resource{ + Create: resourceHerokuSpaceCreate, + Read: resourceHerokuSpaceRead, + Update: resourceHerokuSpaceUpdate, + Delete: resourceHerokuSpaceDelete, + + Schema: map[string]*schema.Schema{ + "name": { + Type: schema.TypeString, + Required: true, + }, + + "organization": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + + "region": { + Type: schema.TypeString, + Optional: true, + ForceNew: true, + }, + }, + } +} + +func resourceHerokuSpaceCreate(d *schema.ResourceData, meta interface{}) error { + client := meta.(*heroku.Service) + + opts := heroku.SpaceCreateOpts{} + opts.Name = d.Get("name").(string) + opts.Organization = d.Get("organization").(string) + + if v, ok := d.GetOk("region"); ok { + vs := v.(string) + opts.Region = &vs + } + + space, err := client.SpaceCreate(context.TODO(), opts) + if err != nil { + return err + } + + d.SetId(space.ID) + log.Printf("[INFO] Space ID: %s", d.Id()) + + // Wait for the Space to be allocated + log.Printf("[DEBUG] Waiting for Space (%s) to be allocated", d.Id()) + stateConf := &resource.StateChangeConf{ + Pending: []string{"allocating"}, + Target: []string{"allocated"}, + Refresh: SpaceStateRefreshFunc(client, d.Id()), + Timeout: 20 * time.Minute, + } + + if _, err := stateConf.WaitForState(); err != nil { + return fmt.Errorf("Error waiting for Space (%s) to become available: %s", d.Id(), err) + } + + return resourceHerokuSpaceRead(d, meta) +} + +func resourceHerokuSpaceRead(d *schema.ResourceData, meta interface{}) error { + client := meta.(*heroku.Service) + + spaceRaw, _, err := SpaceStateRefreshFunc(client, d.Id())() + if err != nil { + return err + } + space := spaceRaw.(*heroku.Space) + + setSpaceAttributes(d, space) + return nil +} + +func resourceHerokuSpaceUpdate(d *schema.ResourceData, meta interface{}) error { + client := meta.(*heroku.Service) + + if !d.HasChange("name") { + return nil + } + + name := d.Get("name").(string) + opts := heroku.SpaceUpdateOpts{Name: &name} + + space, err := client.SpaceUpdate(context.TODO(), d.Id(), opts) + if err != nil { + return err + } + + // The type conversion here can be dropped when the vendored version of + // heroku-go is updated. + setSpaceAttributes(d, (*heroku.Space)(space)) + return nil +} + +func setSpaceAttributes(d *schema.ResourceData, space *heroku.Space) { + d.Set("name", space.Name) + d.Set("organization", space.Organization.Name) + d.Set("region", space.Region.Name) +} + +func resourceHerokuSpaceDelete(d *schema.ResourceData, meta interface{}) error { + client := meta.(*heroku.Service) + + log.Printf("[INFO] Deleting space: %s", d.Id()) + _, err := client.SpaceDelete(context.TODO(), d.Id()) + if err != nil { + return err + } + + d.SetId("") + return nil +} + +// SpaceStateRefreshFunc returns a resource.StateRefreshFunc that is used to watch +// a Space. +func SpaceStateRefreshFunc(client *heroku.Service, id string) resource.StateRefreshFunc { + return func() (interface{}, string, error) { + space, err := client.SpaceInfo(context.TODO(), id) + if err != nil { + return nil, "", err + } + + // The type conversion here can be dropped when the vendored version of + // heroku-go is updated. + return (*heroku.Space)(space), space.State, nil + } +} diff --git a/builtin/providers/heroku/resource_heroku_space_test.go b/builtin/providers/heroku/resource_heroku_space_test.go new file mode 100644 index 000000000..72a2ed0c5 --- /dev/null +++ b/builtin/providers/heroku/resource_heroku_space_test.go @@ -0,0 +1,114 @@ +package heroku + +import ( + "context" + "fmt" + "os" + "testing" + + heroku "github.com/cyberdelia/heroku-go/v3" + "github.com/hashicorp/terraform/helper/acctest" + "github.com/hashicorp/terraform/helper/resource" + "github.com/hashicorp/terraform/terraform" +) + +func TestAccHerokuSpace_Basic(t *testing.T) { + var space heroku.SpaceInfoResult + spaceName := fmt.Sprintf("tftest-%s", acctest.RandString(10)) + spaceName2 := fmt.Sprintf("tftest-%s", acctest.RandString(10)) + org := os.Getenv("HEROKU_ORGANIZATION") + + resource.Test(t, resource.TestCase{ + PreCheck: func() { + testAccPreCheck(t) + if org == "" { + t.Skip("HEROKU_ORGANIZATION is not set; skipping test.") + } + }, + Providers: testAccProviders, + CheckDestroy: testAccCheckHerokuSpaceDestroy, + Steps: []resource.TestStep{ + { + Config: testAccCheckHerokuSpaceConfig_basic(spaceName, org), + Check: resource.ComposeTestCheckFunc( + testAccCheckHerokuSpaceExists("heroku_space.foobar", &space), + testAccCheckHerokuSpaceAttributes(&space, spaceName), + ), + }, + { + Config: testAccCheckHerokuSpaceConfig_basic(spaceName2, org), + Check: resource.ComposeTestCheckFunc( + testAccCheckHerokuSpaceExists("heroku_space.foobar", &space), + testAccCheckHerokuSpaceAttributes(&space, spaceName2), + ), + }, + }, + }) +} + +func testAccCheckHerokuSpaceConfig_basic(spaceName, orgName string) string { + return fmt.Sprintf(` +resource "heroku_space" "foobar" { + name = "%s" + organization = "%s" + region = "virginia" +} +`, spaceName, orgName) +} + +func testAccCheckHerokuSpaceExists(n string, space *heroku.SpaceInfoResult) resource.TestCheckFunc { + return func(s *terraform.State) error { + rs, ok := s.RootModule().Resources[n] + + if !ok { + return fmt.Errorf("Not found: %s", n) + } + + if rs.Primary.ID == "" { + return fmt.Errorf("No space name set") + } + + client := testAccProvider.Meta().(*heroku.Service) + + foundSpace, err := client.SpaceInfo(context.TODO(), rs.Primary.ID) + if err != nil { + return err + } + + if foundSpace.ID != rs.Primary.ID { + return fmt.Errorf("Space not found") + } + + *space = *foundSpace + + return nil + } +} + +func testAccCheckHerokuSpaceAttributes(space *heroku.SpaceInfoResult, spaceName string) resource.TestCheckFunc { + return func(s *terraform.State) error { + if space.Name != spaceName { + return fmt.Errorf("Bad name: %s", space.Name) + } + + return nil + } +} + +func testAccCheckHerokuSpaceDestroy(s *terraform.State) error { + client := testAccProvider.Meta().(*heroku.Service) + + for _, rs := range s.RootModule().Resources { + if rs.Type != "heroku_space" { + continue + } + + _, err := client.SpaceInfo(context.TODO(), rs.Primary.ID) + + if err == nil { + return fmt.Errorf("Space still exists") + } + } + + return nil +} diff --git a/builtin/providers/heroku/test-fixtures/terraform2.cert b/builtin/providers/heroku/test-fixtures/terraform2.cert new file mode 100644 index 000000000..41b7785ee --- /dev/null +++ b/builtin/providers/heroku/test-fixtures/terraform2.cert @@ -0,0 +1,29 @@ +-----BEGIN CERTIFICATE----- +MIIE5jCCAs6gAwIBAgIBATANBgkqhkiG9w0BAQsFADATMREwDwYDVQQDEwhDZXJ0 +QXV0aDAeFw0xNzA1MDUwMDI4NDhaFw0yNzA1MDUwMDI4NTVaMBMxETAPBgNVBAMT +CENlcnRBdXRoMIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEA3f07ApBL +Infz43y96n6iWtQgk4nVEMN2Qc5a4bGm7Ha/gnNGYnv87CGpd6VNBrd07zXlOGXo +5DCly3AxjmFaHw9wzKadXmU2P91tQ4S253tFN8lirMPe+2hS5RnAPw9NsvYsU0Iy +wp/+1a2OpDGtUv00fyU9tY8M1wQo/33xgTyc+8DdEDQ08/PjCKbA5vvpfra5fE+S +g0Gcw8j6Y/iXcnj6LrTvY7I9G3doyAUezGCpAqPErVCDj5nokdJ17zs0kWbr/e4z +o7yKvQOw7majlaX/R6v8tuYvEZ8fokXR7ecGeco86d7sH+OHafOkYQgf+forGMh6 +PSJ5z3WWnLKPvzGgvqoDemGfIyfeRHGTI+e8+4DrcvJGlLS0vBFCYxqXhlvmi6xf +u9G0/zKV/VbIeJS1hTus6sYIIRMzABNwYIGGIz4eBjnO1jakowsdxfgsBvpMwVB+ +yZ+yxv/L9DCVK/VW3VfxQoQ+IDRTokfU/6yKWeonYVtTH57upJ7tRKRy2pmFCJEo +c4T7IKg5ENfGhSkKHuN8CLoWdRREh2KTTijET0qUHCWPbOl9MgW6Y4Jf2qYkggGk +CTRDk7iGuLKT6tMqVrqcmA/AhBpgZKg5N+rIbwTfIHzGNql93bc1FX0KVh7LlV64 +9ZRR4mksrk26pDnLqAfiT15aRsIrYZYdbh0CAwEAAaNFMEMwDgYDVR0PAQH/BAQD +AgEGMBIGA1UdEwEB/wQIMAYBAf8CAQAwHQYDVR0OBBYEFDq5vNYjPHDUyIgkTKCX +9N27PvuiMA0GCSqGSIb3DQEBCwUAA4ICAQCW4RfKiHsFLOwDTTVkQzb0G2A9Ajeg +66lWSuNidntbr+w5595G0ae3qCumaVQSNWKtMAkdahzI+0J00YGWpnqS2rJIIgD+ +8I67EpQ6wi60EUMAECNl7vJvLH/IXt6IVY1wr3ci3G56aKVZIsnaoFi2vxnwHNz3 +uOkNcj0OO4Nosw8aThzsitiddu4BVk+8AFq0cylroQzWjoCrkKOyWMyKTcK6qnS7 +ayyCK02AQPhXFYxet7NVY5hgldto2BAsijBX1Xl6XR5QGSrIQw/2nkAywVSnAGip +Ofk/njzZH9FhUnEY1C5vB2SU310LIOq1evvF8nd7csnI7wdjfHQ3m70PO6p9DGK/ +W0tET8NtuW2JV38KSNMrYxF2Hs7Il92x8JVQu9LtjiKTcJLdnnAQl0OvHUAgAmU9 +BRHOsfWD4Cxiwes0OZHuOpoghh7HV1A+JS5e9qNCCEzarQe4H2Zv8JkeBFbIaEH/ +bcT3a2Rtt6cvDw9mSXSw7p85/810n8af4T1D3aeLFdoVrpeTZVUdyFygcuWo1U4D +JxaRAyJHvi4IJmwpjehn7DoFasNefPBVVFi28QCJXFHpe0DNm8MvI5fGhyZ2uW8t ++6PDgumsZLQT7jJNl9ubYV3U0Nsymvvwqx4LY2nql0agEzJ0F9ekoA50csoxe2ir +/DOgG1nKIc186A== +-----END CERTIFICATE----- diff --git a/builtin/providers/heroku/test-fixtures/terraform2.key b/builtin/providers/heroku/test-fixtures/terraform2.key new file mode 100644 index 000000000..c5fee3428 --- /dev/null +++ b/builtin/providers/heroku/test-fixtures/terraform2.key @@ -0,0 +1,51 @@ +-----BEGIN RSA PRIVATE KEY----- +MIIJKQIBAAKCAgEA3f07ApBLInfz43y96n6iWtQgk4nVEMN2Qc5a4bGm7Ha/gnNG +Ynv87CGpd6VNBrd07zXlOGXo5DCly3AxjmFaHw9wzKadXmU2P91tQ4S253tFN8li +rMPe+2hS5RnAPw9NsvYsU0Iywp/+1a2OpDGtUv00fyU9tY8M1wQo/33xgTyc+8Dd +EDQ08/PjCKbA5vvpfra5fE+Sg0Gcw8j6Y/iXcnj6LrTvY7I9G3doyAUezGCpAqPE +rVCDj5nokdJ17zs0kWbr/e4zo7yKvQOw7majlaX/R6v8tuYvEZ8fokXR7ecGeco8 +6d7sH+OHafOkYQgf+forGMh6PSJ5z3WWnLKPvzGgvqoDemGfIyfeRHGTI+e8+4Dr +cvJGlLS0vBFCYxqXhlvmi6xfu9G0/zKV/VbIeJS1hTus6sYIIRMzABNwYIGGIz4e +BjnO1jakowsdxfgsBvpMwVB+yZ+yxv/L9DCVK/VW3VfxQoQ+IDRTokfU/6yKWeon +YVtTH57upJ7tRKRy2pmFCJEoc4T7IKg5ENfGhSkKHuN8CLoWdRREh2KTTijET0qU +HCWPbOl9MgW6Y4Jf2qYkggGkCTRDk7iGuLKT6tMqVrqcmA/AhBpgZKg5N+rIbwTf +IHzGNql93bc1FX0KVh7LlV649ZRR4mksrk26pDnLqAfiT15aRsIrYZYdbh0CAwEA +AQKCAgAKdpIed9CiykablViaQefDIjZ63cdGKABd760G8Emu4ZX7PxW1NKTiOF/1 +fLwZsfH4CHFKbDtC7iwSX7JmRJ5r0l19t+i490pMTlKFGS9Jz9yeWYamIAFVlkA5 +/jG6hy0hX0sNjZQ46jOnvKt5f8HspHSh/Y5gDWMMi2ynRjdo4QOBNkD1L5DDYt5z +nPCAsqT5zQEHI/UC7MfHzqRGrAPvaFZadzrFVzRcJA+zRdKCzZeJwVBW3vGkhhuZ +K/NVGFRM+i3rZRvX/t4HNLJVOk9BkXZr2WZq9ISJbxednW7cqMP8X5TpbRFyG1ZZ +nxtDW4+uR6VaYLCqSwK0zZUQw7XUtbSSlxPG90dZyNkR5n3grK0wORro8zV/8BMg +qON/jxUJFLOxCBDT5jThjFm6mk9dkUF/uzubm7k5LdRP4v1J8LojEF1BrP5g8JEN +cOBwC2z10uwcSSdVPF7FMJ35EctIzFw+eA2qeYqCywTSd7J1AQ5vNcjc+2wiY2Ff +4qIDAvgaXV+g7JsmqaEFWTs4o5PwKZXp4qEU4hhZ1636vi9aGJPYcsZqWb5os/+j +OQFWGrk16gDyzC3J3Qh8cnVHQko7yrWbhMOXSAN5W/1npovhVeYOVUtCLRfog66b +ZrCmRkoFdRaQeRD3iYHu5dLye8g4k1PWB/+Uq17GjAWp12wenQKCAQEA9usfQVgt +4C2tRwsHUXaRihiY+MM7YlXDwh4qzDXQk8cfdGabR6MIvGPcpsDpxDidPHUuU0qy +NZC4y4rrZnFJaQ3YaD6lDlAuICyHqrQcYBYB7wB9gZy/Un34P8WnE93kTfDZRhd0 +7SF94lBW+cb2BjzcyUsYLf/0UVEt8kTWxP1T39fHyQEGxwJcbPvjRLZoYWkTnPZb +cx/hBk8gclVPUV0w9idNuWz4ittkEF3oEEtu+06pjP8DZ+lJ/Hn6hwJjN66oCXKH +9TLnvygJZjub8BKXRpbRJ989dQvGl7w+rlT/gyJvewjtn/GU6OEvFyaHh2Hgqy6y +ROM9nQgGIwtqWwKCAQEA5idim5tM6lYbR5oTeczqVTNE69gnzmQVMFML7Eb2Qnne +BFvpHuKouJksY514rSrXusirYRqhX5WU8exkn/h3T9LkRyLA3pUfBHxqcejMfuRG +MYIy9nIgiV9xEc73hZsi4xCWEgFfmS9WCB7Z46Zi3PayZg4Hrq7C69ez1drt6njQ +R09qCLUJD+DRTgEax08eZNYLeqcy20ofCGu2UZyyr3ZIS7wGLxNqzic26E24r2GG +K2KqiFH6isUS4EnthwV29EqvPcsq57A4s9Uva8xkORUhJCtY/7M1klUo/89HxVGp +OZ4+sxYqZCKcQJO8+i/4RPwF3QYZ/uh/gcZM2z9C5wKCAQAyjsQQkiiajV+8ezKd +aIS2XQD9dqQzJ1J07c5fj+lMSOpU4CmNSoGgaWYlsrxq1BjF50x7+4Bv3VkpPCGl +ES8x1oboGWOcgahgKB4DQuvIdNkigdww7NJz5p0tGaBzPezgVJ94bZcgcsoey8pz +TFzVvCKNCNZDnPP+rnuU7ql3HlPNMpaSvqYPm5knK5BGYn8O6v/8FKl28iEWNJ91 +KaibBVTgIf4VKI3fiLp9a2z34SoxRNMMrq6Y2Tiv/J3ihQehwB5iCNRzzV+MUXtT +NoNgbb4R0xGyc1BXJfkc2ouPEJJc3HEtJQ/avxF5eZo1yErZ2p2xD1erKUhVXe47 +wLufAoIBAQC853DBJXvBD0G+yFDZ9P4VRkp4hWdOuMjHbDJqEWiI8Xvv+fxilElF +krtjW9mz0GlW7uPzhKcVTDH/SzbgMlDDnOYvGPBTAPR/exrnOdu2/ug6NJJdwxi/ +iC3HHyf8anP9CR0T1DrCAZ9MdP4EIwocMQQGTdeyYdCtQNNjYRlMDTNuhFkUonq4 +pJ9GthNjqaXZv/GWD2vnn3PPNpFjdQkYiS4Xs1EkDHzqjjc7/qbqlFJKg+ZSk27f +vZebrjIeU7bqFe61+m7R0csIl58fjJhqXdRg2o9m+JGs9Ob86AYRh9As8Zym4zeS +DvJO8rP2aa8N+Alb+2kU14HoY3mrrsXbAoIBAQDK0jCxdc73h4u2B2zlX4eyHAy7 +oPpwhIjuuMVXbsR5MqlIOpD7QjqujnMTN0MSslV1GzwhfQO7cN6ijQQiWWiHzCKd +O6NqetPQnn19ddqFLWcrl/WzZdVTDeXyhAaFffy+x8dhPVUdPs/ZDXXAF43LFwly +2kSTWnfwZ5Yvi3K2SB/dO48I77qEUF370/wstdHviSttbI5HhtiRljCU6mwpms34 +4KdDCCxPleZ7Dl2m8v+FkdWkZomLi9wo/XzBo/z5RcI5gjt83OJ6pLBTcLDo7WOc +g2XM7rqQoQr8bilH+eMAZtEm/axwZHIcTTqsyt3Mp09KL65MB+581V5TnGSu +-----END RSA PRIVATE KEY----- diff --git a/builtin/providers/heroku/validators.go b/builtin/providers/heroku/validators.go new file mode 100644 index 000000000..0b3702247 --- /dev/null +++ b/builtin/providers/heroku/validators.go @@ -0,0 +1,38 @@ +package heroku + +import ( + "fmt" + "strings" + + "github.com/satori/uuid" +) + +func validatePipelineStageName(v interface{}, k string) (ws []string, errors []error) { + validPipelineStageNames := []string{ + "review", + "development", + "staging", + "production", + } + + for _, s := range validPipelineStageNames { + if v == s { + return + } + } + + err := fmt.Errorf( + "%s is an invalid pipeline stage, must be one of [%s]", + v, + strings.Join(validPipelineStageNames, ", "), + ) + errors = append(errors, err) + return +} + +func validateUUID(v interface{}, k string) (ws []string, errors []error) { + if _, err := uuid.FromString(v.(string)); err != nil { + errors = append(errors, fmt.Errorf("%q is an invalid UUID: %s", k, err)) + } + return +} diff --git a/builtin/providers/heroku/validators_test.go b/builtin/providers/heroku/validators_test.go new file mode 100644 index 000000000..6131be8bc --- /dev/null +++ b/builtin/providers/heroku/validators_test.go @@ -0,0 +1,53 @@ +package heroku + +import "testing" + +func TestPipelineStage(t *testing.T) { + valid := []string{ + "review", + "development", + "staging", + "production", + } + for _, v := range valid { + _, errors := validatePipelineStageName(v, "stage") + if len(errors) != 0 { + t.Fatalf("%q should be a valid stage: %q", v, errors) + } + } + + invalid := []string{ + "foobarbaz", + "another-stage", + "", + } + for _, v := range invalid { + _, errors := validatePipelineStageName(v, "stage") + if len(errors) == 0 { + t.Fatalf("%q should be an invalid stage", v) + } + } +} + +func TestValidateUUID(t *testing.T) { + valid := []string{ + "4812ccbc-2a2e-4c6c-bae4-a3d04ed51c0e", + } + for _, v := range valid { + _, errors := validateUUID(v, "id") + if len(errors) != 0 { + t.Fatalf("%q should be a valid UUID: %q", v, errors) + } + } + + invalid := []string{ + "foobarbaz", + "my-app-name", + } + for _, v := range invalid { + _, errors := validateUUID(v, "id") + if len(errors) == 0 { + t.Fatalf("%q should be an invalid UUID", v) + } + } +} diff --git a/builtin/providers/http/data_source.go b/builtin/providers/http/data_source.go new file mode 100644 index 000000000..221de4adf --- /dev/null +++ b/builtin/providers/http/data_source.go @@ -0,0 +1,104 @@ +package http + +import ( + "fmt" + "io/ioutil" + "net/http" + "regexp" + "time" + + "github.com/hashicorp/terraform/helper/schema" +) + +func dataSource() *schema.Resource { + return &schema.Resource{ + Read: dataSourceRead, + + Schema: map[string]*schema.Schema{ + "url": &schema.Schema{ + Type: schema.TypeString, + Required: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + + "request_headers": &schema.Schema{ + Type: schema.TypeMap, + Optional: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + + "body": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + }, + } +} + +func dataSourceRead(d *schema.ResourceData, meta interface{}) error { + + url := d.Get("url").(string) + headers := d.Get("request_headers").(map[string]interface{}) + + client := &http.Client{} + + req, err := http.NewRequest("GET", url, nil) + if err != nil { + return fmt.Errorf("Error creating request: %s", err) + } + + for name, value := range headers { + req.Header.Set(name, value.(string)) + } + + resp, err := client.Do(req) + if err != nil { + return fmt.Errorf("Error during making a request: %s", url) + } + + defer resp.Body.Close() + + if resp.StatusCode != 200 { + return fmt.Errorf("HTTP request error. Response code: %d", resp.StatusCode) + } + + contentType := resp.Header.Get("Content-Type") + if contentType == "" || isContentTypeAllowed(contentType) == false { + return fmt.Errorf("Content-Type is not a text type. Got: %s", contentType) + } + + bytes, err := ioutil.ReadAll(resp.Body) + if err != nil { + return fmt.Errorf("Error while reading response body. %s", err) + } + + d.Set("body", string(bytes)) + d.SetId(time.Now().UTC().String()) + + return nil +} + +// This is to prevent potential issues w/ binary files +// and generally unprintable characters +// See https://github.com/hashicorp/terraform/pull/3858#issuecomment-156856738 +func isContentTypeAllowed(contentType string) bool { + allowedContentTypes := []*regexp.Regexp{ + regexp.MustCompile("^text/.+"), + regexp.MustCompile("^application/json$"), + } + + for _, r := range allowedContentTypes { + if r.MatchString(contentType) { + return true + } + } + + return false +} diff --git a/builtin/providers/http/data_source_test.go b/builtin/providers/http/data_source_test.go new file mode 100644 index 000000000..8ad73ce36 --- /dev/null +++ b/builtin/providers/http/data_source_test.go @@ -0,0 +1,166 @@ +package http + +import ( + "fmt" + "net/http" + "net/http/httptest" + "regexp" + "testing" + + "github.com/hashicorp/terraform/helper/resource" + "github.com/hashicorp/terraform/terraform" +) + +type TestHttpMock struct { + server *httptest.Server +} + +const testDataSourceConfig_basic = ` +data "http" "http_test" { + url = "%s/meta_%d.txt" +} + +output "body" { + value = "${data.http.http_test.body}" +} +` + +func TestDataSource_http200(t *testing.T) { + testHttpMock := setUpMockHttpServer() + + defer testHttpMock.server.Close() + + resource.UnitTest(t, resource.TestCase{ + Providers: testProviders, + Steps: []resource.TestStep{ + resource.TestStep{ + Config: fmt.Sprintf(testDataSourceConfig_basic, testHttpMock.server.URL, 200), + Check: func(s *terraform.State) error { + _, ok := s.RootModule().Resources["data.http.http_test"] + if !ok { + return fmt.Errorf("missing data resource") + } + + outputs := s.RootModule().Outputs + + if outputs["body"].Value != "1.0.0" { + return fmt.Errorf( + `'body' output is %s; want '1.0.0'`, + outputs["body"].Value, + ) + } + + return nil + }, + }, + }, + }) +} + +func TestDataSource_http404(t *testing.T) { + testHttpMock := setUpMockHttpServer() + + defer testHttpMock.server.Close() + + resource.UnitTest(t, resource.TestCase{ + Providers: testProviders, + Steps: []resource.TestStep{ + resource.TestStep{ + Config: fmt.Sprintf(testDataSourceConfig_basic, testHttpMock.server.URL, 404), + ExpectError: regexp.MustCompile("HTTP request error. Response code: 404"), + }, + }, + }) +} + +const testDataSourceConfig_withHeaders = ` +data "http" "http_test" { + url = "%s/restricted/meta_%d.txt" + + request_headers = { + "Authorization" = "Zm9vOmJhcg==" + } +} + +output "body" { + value = "${data.http.http_test.body}" +} +` + +func TestDataSource_withHeaders200(t *testing.T) { + testHttpMock := setUpMockHttpServer() + + defer testHttpMock.server.Close() + + resource.UnitTest(t, resource.TestCase{ + Providers: testProviders, + Steps: []resource.TestStep{ + resource.TestStep{ + Config: fmt.Sprintf(testDataSourceConfig_withHeaders, testHttpMock.server.URL, 200), + Check: func(s *terraform.State) error { + _, ok := s.RootModule().Resources["data.http.http_test"] + if !ok { + return fmt.Errorf("missing data resource") + } + + outputs := s.RootModule().Outputs + + if outputs["body"].Value != "1.0.0" { + return fmt.Errorf( + `'body' output is %s; want '1.0.0'`, + outputs["body"].Value, + ) + } + + return nil + }, + }, + }, + }) +} + +const testDataSourceConfig_error = ` +data "http" "http_test" { + +} +` + +func TestDataSource_compileError(t *testing.T) { + resource.UnitTest(t, resource.TestCase{ + Providers: testProviders, + Steps: []resource.TestStep{ + resource.TestStep{ + Config: testDataSourceConfig_error, + ExpectError: regexp.MustCompile("required field is not set"), + }, + }, + }) +} + +func setUpMockHttpServer() *TestHttpMock { + Server := httptest.NewServer( + http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/meta_200.txt" { + w.WriteHeader(http.StatusOK) + w.Write([]byte("1.0.0")) + } else if r.URL.Path == "/restricted/meta_200.txt" { + if r.Header.Get("Authorization") == "Zm9vOmJhcg==" { + w.WriteHeader(http.StatusOK) + w.Write([]byte("1.0.0")) + } else { + w.WriteHeader(http.StatusForbidden) + } + } else if r.URL.Path == "/meta_404.txt" { + w.WriteHeader(http.StatusNotFound) + } else { + w.WriteHeader(http.StatusNotFound) + } + + w.Header().Add("Content-Type", "text/plain") + }), + ) + + return &TestHttpMock{ + server: Server, + } +} diff --git a/builtin/providers/http/provider.go b/builtin/providers/http/provider.go new file mode 100644 index 000000000..e11b68346 --- /dev/null +++ b/builtin/providers/http/provider.go @@ -0,0 +1,18 @@ +package http + +import ( + "github.com/hashicorp/terraform/helper/schema" + "github.com/hashicorp/terraform/terraform" +) + +func Provider() terraform.ResourceProvider { + return &schema.Provider{ + Schema: map[string]*schema.Schema{}, + + DataSourcesMap: map[string]*schema.Resource{ + "http": dataSource(), + }, + + ResourcesMap: map[string]*schema.Resource{}, + } +} diff --git a/builtin/providers/http/provider_test.go b/builtin/providers/http/provider_test.go new file mode 100644 index 000000000..dd21abd45 --- /dev/null +++ b/builtin/providers/http/provider_test.go @@ -0,0 +1,18 @@ +package http + +import ( + "testing" + + "github.com/hashicorp/terraform/helper/schema" + "github.com/hashicorp/terraform/terraform" +) + +var testProviders = map[string]terraform.ResourceProvider{ + "http": Provider(), +} + +func TestProvider(t *testing.T) { + if err := Provider().(*schema.Provider).InternalValidate(); err != nil { + t.Fatalf("err: %s", err) + } +} diff --git a/builtin/providers/ignition/provider.go b/builtin/providers/ignition/provider.go index 6ad832d03..81462e361 100644 --- a/builtin/providers/ignition/provider.go +++ b/builtin/providers/ignition/provider.go @@ -15,6 +15,21 @@ import ( "github.com/hashicorp/terraform/terraform" ) +// globalCache keeps the instances of the internal types of ignition generated +// by the different data resources with the goal to be reused by the +// ignition_config data resource. The key of the maps are a hash of the types +// calculated on the type serialized to JSON. +var globalCache = &cache{ + disks: make(map[string]*types.Disk, 0), + arrays: make(map[string]*types.Raid, 0), + filesystems: make(map[string]*types.Filesystem, 0), + files: make(map[string]*types.File, 0), + systemdUnits: make(map[string]*types.SystemdUnit, 0), + networkdUnits: make(map[string]*types.NetworkdUnit, 0), + users: make(map[string]*types.User, 0), + groups: make(map[string]*types.Group, 0), +} + func Provider() terraform.ResourceProvider { return &schema.Provider{ DataSourcesMap: map[string]*schema.Resource{ @@ -66,18 +81,6 @@ func Provider() terraform.ResourceProvider { resourceGroup(), ), }, - ConfigureFunc: func(*schema.ResourceData) (interface{}, error) { - return &cache{ - disks: make(map[string]*types.Disk, 0), - arrays: make(map[string]*types.Raid, 0), - filesystems: make(map[string]*types.Filesystem, 0), - files: make(map[string]*types.File, 0), - systemdUnits: make(map[string]*types.SystemdUnit, 0), - networkdUnits: make(map[string]*types.NetworkdUnit, 0), - users: make(map[string]*types.User, 0), - groups: make(map[string]*types.Group, 0), - }, nil - }, } } diff --git a/builtin/providers/ignition/resource_ignition_config.go b/builtin/providers/ignition/resource_ignition_config.go index 4df56f79c..c75e50afd 100644 --- a/builtin/providers/ignition/resource_ignition_config.go +++ b/builtin/providers/ignition/resource_ignition_config.go @@ -91,7 +91,7 @@ func resourceConfig() *schema.Resource { } func resourceIgnitionFileRead(d *schema.ResourceData, meta interface{}) error { - rendered, err := renderConfig(d, meta.(*cache)) + rendered, err := renderConfig(d, globalCache) if err != nil { return err } @@ -105,7 +105,7 @@ func resourceIgnitionFileRead(d *schema.ResourceData, meta interface{}) error { } func resourceIgnitionFileExists(d *schema.ResourceData, meta interface{}) (bool, error) { - rendered, err := renderConfig(d, meta.(*cache)) + rendered, err := renderConfig(d, globalCache) if err != nil { return false, err } diff --git a/builtin/providers/ignition/resource_ignition_disk.go b/builtin/providers/ignition/resource_ignition_disk.go index 3fa9b947a..8ef6c7e05 100644 --- a/builtin/providers/ignition/resource_ignition_disk.go +++ b/builtin/providers/ignition/resource_ignition_disk.go @@ -59,7 +59,7 @@ func resourceDisk() *schema.Resource { } func resourceDiskRead(d *schema.ResourceData, meta interface{}) error { - id, err := buildDisk(d, meta.(*cache)) + id, err := buildDisk(d, globalCache) if err != nil { return err } @@ -69,7 +69,7 @@ func resourceDiskRead(d *schema.ResourceData, meta interface{}) error { } func resourceDiskExists(d *schema.ResourceData, meta interface{}) (bool, error) { - id, err := buildDisk(d, meta.(*cache)) + id, err := buildDisk(d, globalCache) if err != nil { return false, err } diff --git a/builtin/providers/ignition/resource_ignition_file.go b/builtin/providers/ignition/resource_ignition_file.go index a6f34f2fa..0f73ea6ed 100644 --- a/builtin/providers/ignition/resource_ignition_file.go +++ b/builtin/providers/ignition/resource_ignition_file.go @@ -90,7 +90,7 @@ func resourceFile() *schema.Resource { } func resourceFileRead(d *schema.ResourceData, meta interface{}) error { - id, err := buildFile(d, meta.(*cache)) + id, err := buildFile(d, globalCache) if err != nil { return err } @@ -100,7 +100,7 @@ func resourceFileRead(d *schema.ResourceData, meta interface{}) error { } func resourceFileExists(d *schema.ResourceData, meta interface{}) (bool, error) { - id, err := buildFile(d, meta.(*cache)) + id, err := buildFile(d, globalCache) if err != nil { return false, err } diff --git a/builtin/providers/ignition/resource_ignition_filesystem.go b/builtin/providers/ignition/resource_ignition_filesystem.go index a26c3f700..ce858e80c 100644 --- a/builtin/providers/ignition/resource_ignition_filesystem.go +++ b/builtin/providers/ignition/resource_ignition_filesystem.go @@ -63,7 +63,7 @@ func resourceFilesystem() *schema.Resource { } func resourceFilesystemRead(d *schema.ResourceData, meta interface{}) error { - id, err := buildFilesystem(d, meta.(*cache)) + id, err := buildFilesystem(d, globalCache) if err != nil { return err } @@ -73,7 +73,7 @@ func resourceFilesystemRead(d *schema.ResourceData, meta interface{}) error { } func resourceFilesystemExists(d *schema.ResourceData, meta interface{}) (bool, error) { - id, err := buildFilesystem(d, meta.(*cache)) + id, err := buildFilesystem(d, globalCache) if err != nil { return false, err } diff --git a/builtin/providers/ignition/resource_ignition_group.go b/builtin/providers/ignition/resource_ignition_group.go index 29ebeecd9..125e97e73 100644 --- a/builtin/providers/ignition/resource_ignition_group.go +++ b/builtin/providers/ignition/resource_ignition_group.go @@ -30,7 +30,7 @@ func resourceGroup() *schema.Resource { } func resourceGroupRead(d *schema.ResourceData, meta interface{}) error { - id, err := buildGroup(d, meta.(*cache)) + id, err := buildGroup(d, globalCache) if err != nil { return err } @@ -40,7 +40,7 @@ func resourceGroupRead(d *schema.ResourceData, meta interface{}) error { } func resourceGroupExists(d *schema.ResourceData, meta interface{}) (bool, error) { - id, err := buildGroup(d, meta.(*cache)) + id, err := buildGroup(d, globalCache) if err != nil { return false, err } diff --git a/builtin/providers/ignition/resource_ignition_networkd_unit.go b/builtin/providers/ignition/resource_ignition_networkd_unit.go index e5d822570..9fd40ed51 100644 --- a/builtin/providers/ignition/resource_ignition_networkd_unit.go +++ b/builtin/providers/ignition/resource_ignition_networkd_unit.go @@ -25,7 +25,7 @@ func resourceNetworkdUnit() *schema.Resource { } func resourceNetworkdUnitRead(d *schema.ResourceData, meta interface{}) error { - id, err := buildNetworkdUnit(d, meta.(*cache)) + id, err := buildNetworkdUnit(d, globalCache) if err != nil { return err } @@ -40,7 +40,7 @@ func resourceNetworkdUnitDelete(d *schema.ResourceData, meta interface{}) error } func resourceNetworkdUnitExists(d *schema.ResourceData, meta interface{}) (bool, error) { - id, err := buildNetworkdUnit(d, meta.(*cache)) + id, err := buildNetworkdUnit(d, globalCache) if err != nil { return false, err } diff --git a/builtin/providers/ignition/resource_ignition_raid.go b/builtin/providers/ignition/resource_ignition_raid.go index 1c8b732ed..dab1a5f7c 100644 --- a/builtin/providers/ignition/resource_ignition_raid.go +++ b/builtin/providers/ignition/resource_ignition_raid.go @@ -36,7 +36,7 @@ func resourceRaid() *schema.Resource { } func resourceRaidRead(d *schema.ResourceData, meta interface{}) error { - id, err := buildRaid(d, meta.(*cache)) + id, err := buildRaid(d, globalCache) if err != nil { return err } @@ -46,7 +46,7 @@ func resourceRaidRead(d *schema.ResourceData, meta interface{}) error { } func resourceRaidExists(d *schema.ResourceData, meta interface{}) (bool, error) { - id, err := buildRaid(d, meta.(*cache)) + id, err := buildRaid(d, globalCache) if err != nil { return false, err } diff --git a/builtin/providers/ignition/resource_ignition_systemd_unit.go b/builtin/providers/ignition/resource_ignition_systemd_unit.go index 211380024..88fe9b206 100644 --- a/builtin/providers/ignition/resource_ignition_systemd_unit.go +++ b/builtin/providers/ignition/resource_ignition_systemd_unit.go @@ -55,7 +55,7 @@ func resourceSystemdUnit() *schema.Resource { } func resourceSystemdUnitRead(d *schema.ResourceData, meta interface{}) error { - id, err := buildSystemdUnit(d, meta.(*cache)) + id, err := buildSystemdUnit(d, globalCache) if err != nil { return err } @@ -65,7 +65,7 @@ func resourceSystemdUnitRead(d *schema.ResourceData, meta interface{}) error { } func resourceSystemdUnitExists(d *schema.ResourceData, meta interface{}) (bool, error) { - id, err := buildSystemdUnit(d, meta.(*cache)) + id, err := buildSystemdUnit(d, globalCache) if err != nil { return false, err } diff --git a/builtin/providers/ignition/resource_ignition_user.go b/builtin/providers/ignition/resource_ignition_user.go index dd4ccc153..183e6c8c1 100644 --- a/builtin/providers/ignition/resource_ignition_user.go +++ b/builtin/providers/ignition/resource_ignition_user.go @@ -79,7 +79,7 @@ func resourceUser() *schema.Resource { } func resourceUserRead(d *schema.ResourceData, meta interface{}) error { - id, err := buildUser(d, meta.(*cache)) + id, err := buildUser(d, globalCache) if err != nil { return err } @@ -89,7 +89,7 @@ func resourceUserRead(d *schema.ResourceData, meta interface{}) error { } func resourceUserExists(d *schema.ResourceData, meta interface{}) (bool, error) { - id, err := buildUser(d, meta.(*cache)) + id, err := buildUser(d, globalCache) if err != nil { return false, err } diff --git a/builtin/providers/kubernetes/provider.go b/builtin/providers/kubernetes/provider.go index 9d0d23cc3..5420572c4 100644 --- a/builtin/providers/kubernetes/provider.go +++ b/builtin/providers/kubernetes/provider.go @@ -66,6 +66,11 @@ func Provider() terraform.ResourceProvider { DefaultFunc: schema.EnvDefaultFunc("KUBE_CONFIG", "~/.kube/config"), Description: "Path to the kube config file, defaults to ~/.kube/config", }, + "config_context": { + Type: schema.TypeString, + Optional: true, + DefaultFunc: schema.EnvDefaultFunc("KUBE_CTX", ""), + }, "config_context_auth_info": { Type: schema.TypeString, Optional: true, @@ -81,8 +86,13 @@ func Provider() terraform.ResourceProvider { }, ResourcesMap: map[string]*schema.Resource{ - "kubernetes_config_map": resourceKubernetesConfigMap(), - "kubernetes_namespace": resourceKubernetesNamespace(), + "kubernetes_config_map": resourceKubernetesConfigMap(), + "kubernetes_limit_range": resourceKubernetesLimitRange(), + "kubernetes_namespace": resourceKubernetesNamespace(), + "kubernetes_persistent_volume": resourceKubernetesPersistentVolume(), + "kubernetes_persistent_volume_claim": resourceKubernetesPersistentVolumeClaim(), + "kubernetes_resource_quota": resourceKubernetesResourceQuota(), + "kubernetes_secret": resourceKubernetesSecret(), }, ConfigureFunc: providerConfigure, } @@ -140,22 +150,32 @@ func tryLoadingConfigFile(d *schema.ResourceData) (*restclient.Config, error) { loader := &clientcmd.ClientConfigLoadingRules{ ExplicitPath: path, } + overrides := &clientcmd.ConfigOverrides{} - ctxSuffix := "; no context" + ctxSuffix := "; default context" + + ctx, ctxOk := d.GetOk("config_context") authInfo, authInfoOk := d.GetOk("config_context_auth_info") cluster, clusterOk := d.GetOk("config_context_cluster") - if authInfoOk || clusterOk { + if ctxOk || authInfoOk || clusterOk { + ctxSuffix = "; overriden context" + if ctxOk { + overrides.CurrentContext = ctx.(string) + ctxSuffix += fmt.Sprintf("; config ctx: %s", overrides.CurrentContext) + log.Printf("[DEBUG] Using custom current context: %q", overrides.CurrentContext) + } + overrides.Context = clientcmdapi.Context{} if authInfoOk { overrides.Context.AuthInfo = authInfo.(string) + ctxSuffix += fmt.Sprintf("; auth_info: %s", overrides.Context.AuthInfo) } if clusterOk { overrides.Context.Cluster = cluster.(string) + ctxSuffix += fmt.Sprintf("; cluster: %s", overrides.Context.Cluster) } - ctxSuffix = fmt.Sprintf("; auth_info: %s, cluster: %s", - overrides.Context.AuthInfo, overrides.Context.Cluster) + log.Printf("[DEBUG] Using overidden context: %#v", overrides.Context) } - log.Printf("[DEBUG] Using override context: %#v", *overrides) cc := clientcmd.NewNonInteractiveDeferredLoadingClientConfig(loader, overrides) cfg, err := cc.ClientConfig() diff --git a/builtin/providers/kubernetes/resource_kubernetes_limit_range.go b/builtin/providers/kubernetes/resource_kubernetes_limit_range.go new file mode 100644 index 000000000..e6ca5adf4 --- /dev/null +++ b/builtin/providers/kubernetes/resource_kubernetes_limit_range.go @@ -0,0 +1,188 @@ +package kubernetes + +import ( + "fmt" + "log" + + "github.com/hashicorp/terraform/helper/schema" + pkgApi "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/errors" + api "k8s.io/kubernetes/pkg/api/v1" + kubernetes "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" +) + +func resourceKubernetesLimitRange() *schema.Resource { + return &schema.Resource{ + Create: resourceKubernetesLimitRangeCreate, + Read: resourceKubernetesLimitRangeRead, + Exists: resourceKubernetesLimitRangeExists, + Update: resourceKubernetesLimitRangeUpdate, + Delete: resourceKubernetesLimitRangeDelete, + Importer: &schema.ResourceImporter{ + State: schema.ImportStatePassthrough, + }, + + Schema: map[string]*schema.Schema{ + "metadata": namespacedMetadataSchema("limit range", true), + "spec": { + Type: schema.TypeList, + Description: "Spec defines the limits enforced. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#spec-and-status", + Optional: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "limit": { + Type: schema.TypeList, + Description: "Limits is the list of objects that are enforced.", + Optional: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "default": { + Type: schema.TypeMap, + Description: "Default resource requirement limit value by resource name if resource limit is omitted.", + Optional: true, + }, + "default_request": { + Type: schema.TypeMap, + Description: "The default resource requirement request value by resource name if resource request is omitted.", + Optional: true, + Computed: true, + }, + "max": { + Type: schema.TypeMap, + Description: "Max usage constraints on this kind by resource name.", + Optional: true, + }, + "max_limit_request_ratio": { + Type: schema.TypeMap, + Description: "The named resource must have a request and limit that are both non-zero where limit divided by request is less than or equal to the enumerated value; this represents the max burst for the named resource.", + Optional: true, + }, + "min": { + Type: schema.TypeMap, + Description: "Min usage constraints on this kind by resource name.", + Optional: true, + }, + "type": { + Type: schema.TypeString, + Description: "Type of resource that this limit applies to.", + Optional: true, + }, + }, + }, + }, + }, + }, + }, + }, + } +} + +func resourceKubernetesLimitRangeCreate(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*kubernetes.Clientset) + + metadata := expandMetadata(d.Get("metadata").([]interface{})) + spec, err := expandLimitRangeSpec(d.Get("spec").([]interface{}), d.IsNewResource()) + if err != nil { + return err + } + limitRange := api.LimitRange{ + ObjectMeta: metadata, + Spec: spec, + } + log.Printf("[INFO] Creating new limit range: %#v", limitRange) + out, err := conn.CoreV1().LimitRanges(metadata.Namespace).Create(&limitRange) + if err != nil { + return fmt.Errorf("Failed to create limit range: %s", err) + } + log.Printf("[INFO] Submitted new limit range: %#v", out) + d.SetId(buildId(out.ObjectMeta)) + + return resourceKubernetesLimitRangeRead(d, meta) +} + +func resourceKubernetesLimitRangeRead(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*kubernetes.Clientset) + + namespace, name := idParts(d.Id()) + log.Printf("[INFO] Reading limit range %s", name) + limitRange, err := conn.CoreV1().LimitRanges(namespace).Get(name) + if err != nil { + log.Printf("[DEBUG] Received error: %#v", err) + return err + } + log.Printf("[INFO] Received limit range: %#v", limitRange) + + err = d.Set("metadata", flattenMetadata(limitRange.ObjectMeta)) + if err != nil { + return err + } + err = d.Set("spec", flattenLimitRangeSpec(limitRange.Spec)) + if err != nil { + return err + } + + return nil +} + +func resourceKubernetesLimitRangeUpdate(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*kubernetes.Clientset) + + namespace, name := idParts(d.Id()) + + ops := patchMetadata("metadata.0.", "/metadata/", d) + if d.HasChange("spec") { + spec, err := expandLimitRangeSpec(d.Get("spec").([]interface{}), d.IsNewResource()) + if err != nil { + return err + } + ops = append(ops, &ReplaceOperation{ + Path: "/spec", + Value: spec, + }) + } + data, err := ops.MarshalJSON() + if err != nil { + return fmt.Errorf("Failed to marshal update operations: %s", err) + } + log.Printf("[INFO] Updating limit range %q: %v", name, string(data)) + out, err := conn.CoreV1().LimitRanges(namespace).Patch(name, pkgApi.JSONPatchType, data) + if err != nil { + return fmt.Errorf("Failed to update limit range: %s", err) + } + log.Printf("[INFO] Submitted updated limit range: %#v", out) + d.SetId(buildId(out.ObjectMeta)) + + return resourceKubernetesLimitRangeRead(d, meta) +} + +func resourceKubernetesLimitRangeDelete(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*kubernetes.Clientset) + + namespace, name := idParts(d.Id()) + log.Printf("[INFO] Deleting limit range: %#v", name) + err := conn.CoreV1().LimitRanges(namespace).Delete(name, &api.DeleteOptions{}) + if err != nil { + return err + } + + log.Printf("[INFO] Limit range %s deleted", name) + + d.SetId("") + return nil +} + +func resourceKubernetesLimitRangeExists(d *schema.ResourceData, meta interface{}) (bool, error) { + conn := meta.(*kubernetes.Clientset) + + namespace, name := idParts(d.Id()) + log.Printf("[INFO] Checking limit range %s", name) + _, err := conn.CoreV1().LimitRanges(namespace).Get(name) + if err != nil { + if statusErr, ok := err.(*errors.StatusError); ok && statusErr.ErrStatus.Code == 404 { + return false, nil + } + log.Printf("[DEBUG] Received error: %#v", err) + } + return true, err +} diff --git a/builtin/providers/kubernetes/resource_kubernetes_limit_range_test.go b/builtin/providers/kubernetes/resource_kubernetes_limit_range_test.go new file mode 100644 index 000000000..c8eaa705d --- /dev/null +++ b/builtin/providers/kubernetes/resource_kubernetes_limit_range_test.go @@ -0,0 +1,475 @@ +package kubernetes + +import ( + "fmt" + "testing" + + "github.com/hashicorp/terraform/helper/acctest" + "github.com/hashicorp/terraform/helper/resource" + "github.com/hashicorp/terraform/terraform" + api "k8s.io/kubernetes/pkg/api/v1" + kubernetes "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" +) + +func TestAccKubernetesLimitRange_basic(t *testing.T) { + var conf api.LimitRange + name := fmt.Sprintf("tf-acc-test-%s", acctest.RandString(10)) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + IDRefreshName: "kubernetes_limit_range.test", + Providers: testAccProviders, + CheckDestroy: testAccCheckKubernetesLimitRangeDestroy, + Steps: []resource.TestStep{ + { + Config: testAccKubernetesLimitRangeConfig_basic(name), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckKubernetesLimitRangeExists("kubernetes_limit_range.test", &conf), + resource.TestCheckResourceAttr("kubernetes_limit_range.test", "metadata.0.annotations.%", "1"), + resource.TestCheckResourceAttr("kubernetes_limit_range.test", "metadata.0.annotations.TestAnnotationOne", "one"), + testAccCheckMetaAnnotations(&conf.ObjectMeta, map[string]string{"TestAnnotationOne": "one"}), + resource.TestCheckResourceAttr("kubernetes_limit_range.test", "metadata.0.labels.%", "3"), + resource.TestCheckResourceAttr("kubernetes_limit_range.test", "metadata.0.labels.TestLabelOne", "one"), + resource.TestCheckResourceAttr("kubernetes_limit_range.test", "metadata.0.labels.TestLabelThree", "three"), + resource.TestCheckResourceAttr("kubernetes_limit_range.test", "metadata.0.labels.TestLabelFour", "four"), + testAccCheckMetaLabels(&conf.ObjectMeta, map[string]string{"TestLabelOne": "one", "TestLabelThree": "three", "TestLabelFour": "four"}), + resource.TestCheckResourceAttr("kubernetes_limit_range.test", "metadata.0.name", name), + resource.TestCheckResourceAttrSet("kubernetes_limit_range.test", "metadata.0.generation"), + resource.TestCheckResourceAttrSet("kubernetes_limit_range.test", "metadata.0.resource_version"), + resource.TestCheckResourceAttrSet("kubernetes_limit_range.test", "metadata.0.self_link"), + resource.TestCheckResourceAttrSet("kubernetes_limit_range.test", "metadata.0.uid"), + resource.TestCheckResourceAttr("kubernetes_limit_range.test", "spec.0.limit.#", "1"), + resource.TestCheckResourceAttr("kubernetes_limit_range.test", "spec.0.limit.0.default.%", "2"), + resource.TestCheckResourceAttr("kubernetes_limit_range.test", "spec.0.limit.0.default.cpu", "200m"), + resource.TestCheckResourceAttr("kubernetes_limit_range.test", "spec.0.limit.0.default.memory", "512M"), + resource.TestCheckResourceAttr("kubernetes_limit_range.test", "spec.0.limit.0.default_request.%", "2"), + resource.TestCheckResourceAttr("kubernetes_limit_range.test", "spec.0.limit.0.default_request.cpu", "100m"), + resource.TestCheckResourceAttr("kubernetes_limit_range.test", "spec.0.limit.0.default_request.memory", "256M"), + resource.TestCheckResourceAttr("kubernetes_limit_range.test", "spec.0.limit.0.type", "Container"), + ), + }, + { + Config: testAccKubernetesLimitRangeConfig_metaModified(name), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckKubernetesLimitRangeExists("kubernetes_limit_range.test", &conf), + resource.TestCheckResourceAttr("kubernetes_limit_range.test", "metadata.0.annotations.%", "2"), + resource.TestCheckResourceAttr("kubernetes_limit_range.test", "metadata.0.annotations.TestAnnotationOne", "one"), + resource.TestCheckResourceAttr("kubernetes_limit_range.test", "metadata.0.annotations.TestAnnotationTwo", "two"), + testAccCheckMetaAnnotations(&conf.ObjectMeta, map[string]string{"TestAnnotationOne": "one", "TestAnnotationTwo": "two"}), + resource.TestCheckResourceAttr("kubernetes_limit_range.test", "metadata.0.labels.%", "3"), + resource.TestCheckResourceAttr("kubernetes_limit_range.test", "metadata.0.labels.TestLabelOne", "one"), + resource.TestCheckResourceAttr("kubernetes_limit_range.test", "metadata.0.labels.TestLabelTwo", "two"), + resource.TestCheckResourceAttr("kubernetes_limit_range.test", "metadata.0.labels.TestLabelThree", "three"), + testAccCheckMetaLabels(&conf.ObjectMeta, map[string]string{"TestLabelOne": "one", "TestLabelTwo": "two", "TestLabelThree": "three"}), + resource.TestCheckResourceAttr("kubernetes_limit_range.test", "metadata.0.name", name), + resource.TestCheckResourceAttrSet("kubernetes_limit_range.test", "metadata.0.generation"), + resource.TestCheckResourceAttrSet("kubernetes_limit_range.test", "metadata.0.resource_version"), + resource.TestCheckResourceAttrSet("kubernetes_limit_range.test", "metadata.0.self_link"), + resource.TestCheckResourceAttrSet("kubernetes_limit_range.test", "metadata.0.uid"), + resource.TestCheckResourceAttr("kubernetes_limit_range.test", "spec.0.limit.#", "1"), + resource.TestCheckResourceAttr("kubernetes_limit_range.test", "spec.0.limit.0.default.%", "2"), + resource.TestCheckResourceAttr("kubernetes_limit_range.test", "spec.0.limit.0.default.cpu", "200m"), + resource.TestCheckResourceAttr("kubernetes_limit_range.test", "spec.0.limit.0.default.memory", "512M"), + resource.TestCheckResourceAttr("kubernetes_limit_range.test", "spec.0.limit.0.default_request.%", "2"), + resource.TestCheckResourceAttr("kubernetes_limit_range.test", "spec.0.limit.0.default_request.cpu", "100m"), + resource.TestCheckResourceAttr("kubernetes_limit_range.test", "spec.0.limit.0.default_request.memory", "256M"), + resource.TestCheckResourceAttr("kubernetes_limit_range.test", "spec.0.limit.0.type", "Container"), + ), + }, + { + Config: testAccKubernetesLimitRangeConfig_specModified(name), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckKubernetesLimitRangeExists("kubernetes_limit_range.test", &conf), + resource.TestCheckResourceAttr("kubernetes_limit_range.test", "metadata.0.annotations.%", "0"), + testAccCheckMetaAnnotations(&conf.ObjectMeta, map[string]string{}), + resource.TestCheckResourceAttr("kubernetes_limit_range.test", "metadata.0.labels.%", "0"), + testAccCheckMetaLabels(&conf.ObjectMeta, map[string]string{}), + resource.TestCheckResourceAttr("kubernetes_limit_range.test", "metadata.0.name", name), + resource.TestCheckResourceAttrSet("kubernetes_limit_range.test", "metadata.0.generation"), + resource.TestCheckResourceAttrSet("kubernetes_limit_range.test", "metadata.0.resource_version"), + resource.TestCheckResourceAttrSet("kubernetes_limit_range.test", "metadata.0.self_link"), + resource.TestCheckResourceAttrSet("kubernetes_limit_range.test", "metadata.0.uid"), + resource.TestCheckResourceAttr("kubernetes_limit_range.test", "spec.0.limit.#", "1"), + resource.TestCheckResourceAttr("kubernetes_limit_range.test", "spec.0.limit.0.default.%", "2"), + resource.TestCheckResourceAttr("kubernetes_limit_range.test", "spec.0.limit.0.default.cpu", "200m"), + resource.TestCheckResourceAttr("kubernetes_limit_range.test", "spec.0.limit.0.default.memory", "1024M"), + resource.TestCheckResourceAttr("kubernetes_limit_range.test", "spec.0.limit.0.default_request.%", "2"), + resource.TestCheckResourceAttr("kubernetes_limit_range.test", "spec.0.limit.0.default_request.cpu", "100m"), + resource.TestCheckResourceAttr("kubernetes_limit_range.test", "spec.0.limit.0.default_request.memory", "256M"), + resource.TestCheckResourceAttr("kubernetes_limit_range.test", "spec.0.limit.0.max.%", "1"), + resource.TestCheckResourceAttr("kubernetes_limit_range.test", "spec.0.limit.0.max.cpu", "500m"), + resource.TestCheckResourceAttr("kubernetes_limit_range.test", "spec.0.limit.0.min.%", "2"), + resource.TestCheckResourceAttr("kubernetes_limit_range.test", "spec.0.limit.0.min.cpu", "10m"), + resource.TestCheckResourceAttr("kubernetes_limit_range.test", "spec.0.limit.0.min.memory", "10M"), + resource.TestCheckResourceAttr("kubernetes_limit_range.test", "spec.0.limit.0.type", "Container"), + ), + }, + }, + }) +} + +func TestAccKubernetesLimitRange_generatedName(t *testing.T) { + var conf api.LimitRange + prefix := "tf-acc-test-" + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + IDRefreshName: "kubernetes_limit_range.test", + Providers: testAccProviders, + CheckDestroy: testAccCheckKubernetesLimitRangeDestroy, + Steps: []resource.TestStep{ + { + Config: testAccKubernetesLimitRangeConfig_generatedName(prefix), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckKubernetesLimitRangeExists("kubernetes_limit_range.test", &conf), + resource.TestCheckResourceAttr("kubernetes_limit_range.test", "metadata.0.annotations.%", "0"), + testAccCheckMetaAnnotations(&conf.ObjectMeta, map[string]string{}), + resource.TestCheckResourceAttr("kubernetes_limit_range.test", "metadata.0.labels.%", "0"), + testAccCheckMetaLabels(&conf.ObjectMeta, map[string]string{}), + resource.TestCheckResourceAttr("kubernetes_limit_range.test", "metadata.0.generate_name", prefix), + resource.TestCheckResourceAttrSet("kubernetes_limit_range.test", "metadata.0.generation"), + resource.TestCheckResourceAttrSet("kubernetes_limit_range.test", "metadata.0.resource_version"), + resource.TestCheckResourceAttrSet("kubernetes_limit_range.test", "metadata.0.self_link"), + resource.TestCheckResourceAttrSet("kubernetes_limit_range.test", "metadata.0.uid"), + resource.TestCheckResourceAttr("kubernetes_limit_range.test", "spec.0.limit.#", "1"), + resource.TestCheckResourceAttr("kubernetes_limit_range.test", "spec.0.limit.0.type", "Pod"), + ), + }, + }, + }) +} + +func TestAccKubernetesLimitRange_typeChange(t *testing.T) { + var conf api.LimitRange + name := fmt.Sprintf("tf-acc-test-%s", acctest.RandString(10)) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + IDRefreshName: "kubernetes_limit_range.test", + Providers: testAccProviders, + CheckDestroy: testAccCheckKubernetesLimitRangeDestroy, + Steps: []resource.TestStep{ + { + Config: testAccKubernetesLimitRangeConfig_typeChange(name), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckKubernetesLimitRangeExists("kubernetes_limit_range.test", &conf), + resource.TestCheckResourceAttr("kubernetes_limit_range.test", "metadata.0.annotations.%", "0"), + testAccCheckMetaAnnotations(&conf.ObjectMeta, map[string]string{}), + resource.TestCheckResourceAttr("kubernetes_limit_range.test", "metadata.0.labels.%", "0"), + testAccCheckMetaLabels(&conf.ObjectMeta, map[string]string{}), + resource.TestCheckResourceAttr("kubernetes_limit_range.test", "metadata.0.name", name), + resource.TestCheckResourceAttrSet("kubernetes_limit_range.test", "metadata.0.generation"), + resource.TestCheckResourceAttrSet("kubernetes_limit_range.test", "metadata.0.resource_version"), + resource.TestCheckResourceAttrSet("kubernetes_limit_range.test", "metadata.0.self_link"), + resource.TestCheckResourceAttrSet("kubernetes_limit_range.test", "metadata.0.uid"), + resource.TestCheckResourceAttr("kubernetes_limit_range.test", "spec.0.limit.#", "1"), + resource.TestCheckResourceAttr("kubernetes_limit_range.test", "spec.0.limit.0.default.%", "2"), + resource.TestCheckResourceAttr("kubernetes_limit_range.test", "spec.0.limit.0.default.cpu", "200m"), + resource.TestCheckResourceAttr("kubernetes_limit_range.test", "spec.0.limit.0.default.memory", "1024M"), + resource.TestCheckResourceAttr("kubernetes_limit_range.test", "spec.0.limit.0.type", "Container"), + ), + }, + { + Config: testAccKubernetesLimitRangeConfig_typeChangeModified(name), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckKubernetesLimitRangeExists("kubernetes_limit_range.test", &conf), + resource.TestCheckResourceAttr("kubernetes_limit_range.test", "metadata.0.annotations.%", "0"), + testAccCheckMetaAnnotations(&conf.ObjectMeta, map[string]string{}), + resource.TestCheckResourceAttr("kubernetes_limit_range.test", "metadata.0.labels.%", "0"), + testAccCheckMetaLabels(&conf.ObjectMeta, map[string]string{}), + resource.TestCheckResourceAttr("kubernetes_limit_range.test", "metadata.0.name", name), + resource.TestCheckResourceAttrSet("kubernetes_limit_range.test", "metadata.0.generation"), + resource.TestCheckResourceAttrSet("kubernetes_limit_range.test", "metadata.0.resource_version"), + resource.TestCheckResourceAttrSet("kubernetes_limit_range.test", "metadata.0.self_link"), + resource.TestCheckResourceAttrSet("kubernetes_limit_range.test", "metadata.0.uid"), + resource.TestCheckResourceAttr("kubernetes_limit_range.test", "spec.0.limit.#", "1"), + resource.TestCheckResourceAttr("kubernetes_limit_range.test", "spec.0.limit.0.min.%", "2"), + resource.TestCheckResourceAttr("kubernetes_limit_range.test", "spec.0.limit.0.min.cpu", "200m"), + resource.TestCheckResourceAttr("kubernetes_limit_range.test", "spec.0.limit.0.min.memory", "1024M"), + resource.TestCheckResourceAttr("kubernetes_limit_range.test", "spec.0.limit.0.type", "Pod"), + ), + }, + }, + }) +} + +func TestAccKubernetesLimitRange_multipleLimits(t *testing.T) { + var conf api.LimitRange + name := fmt.Sprintf("tf-acc-test-%s", acctest.RandString(10)) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + IDRefreshName: "kubernetes_limit_range.test", + Providers: testAccProviders, + CheckDestroy: testAccCheckKubernetesLimitRangeDestroy, + Steps: []resource.TestStep{ + { + Config: testAccKubernetesLimitRangeConfig_multipleLimits(name), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckKubernetesLimitRangeExists("kubernetes_limit_range.test", &conf), + resource.TestCheckResourceAttr("kubernetes_limit_range.test", "metadata.0.annotations.%", "0"), + testAccCheckMetaAnnotations(&conf.ObjectMeta, map[string]string{}), + resource.TestCheckResourceAttr("kubernetes_limit_range.test", "metadata.0.labels.%", "0"), + testAccCheckMetaLabels(&conf.ObjectMeta, map[string]string{}), + resource.TestCheckResourceAttr("kubernetes_limit_range.test", "metadata.0.name", name), + resource.TestCheckResourceAttrSet("kubernetes_limit_range.test", "metadata.0.generation"), + resource.TestCheckResourceAttrSet("kubernetes_limit_range.test", "metadata.0.resource_version"), + resource.TestCheckResourceAttrSet("kubernetes_limit_range.test", "metadata.0.self_link"), + resource.TestCheckResourceAttrSet("kubernetes_limit_range.test", "metadata.0.uid"), + resource.TestCheckResourceAttr("kubernetes_limit_range.test", "spec.0.limit.#", "3"), + resource.TestCheckResourceAttr("kubernetes_limit_range.test", "spec.0.limit.0.max.%", "2"), + resource.TestCheckResourceAttr("kubernetes_limit_range.test", "spec.0.limit.0.max.cpu", "200m"), + resource.TestCheckResourceAttr("kubernetes_limit_range.test", "spec.0.limit.0.max.memory", "1024M"), + resource.TestCheckResourceAttr("kubernetes_limit_range.test", "spec.0.limit.0.type", "Pod"), + resource.TestCheckResourceAttr("kubernetes_limit_range.test", "spec.0.limit.1.min.%", "1"), + resource.TestCheckResourceAttr("kubernetes_limit_range.test", "spec.0.limit.1.min.storage", "24M"), + resource.TestCheckResourceAttr("kubernetes_limit_range.test", "spec.0.limit.1.type", "PersistentVolumeClaim"), + resource.TestCheckResourceAttr("kubernetes_limit_range.test", "spec.0.limit.2.default.%", "2"), + resource.TestCheckResourceAttr("kubernetes_limit_range.test", "spec.0.limit.2.default.cpu", "50m"), + resource.TestCheckResourceAttr("kubernetes_limit_range.test", "spec.0.limit.2.default.memory", "24M"), + resource.TestCheckResourceAttr("kubernetes_limit_range.test", "spec.0.limit.2.type", "Container"), + ), + }, + }, + }) +} + +func TestAccKubernetesLimitRange_importBasic(t *testing.T) { + resourceName := "kubernetes_limit_range.test" + name := fmt.Sprintf("tf-acc-test-%s", acctest.RandString(10)) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckKubernetesLimitRangeDestroy, + Steps: []resource.TestStep{ + { + Config: testAccKubernetesLimitRangeConfig_basic(name), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func testAccCheckKubernetesLimitRangeDestroy(s *terraform.State) error { + conn := testAccProvider.Meta().(*kubernetes.Clientset) + + for _, rs := range s.RootModule().Resources { + if rs.Type != "kubernetes_limit_range" { + continue + } + namespace, name := idParts(rs.Primary.ID) + resp, err := conn.CoreV1().LimitRanges(namespace).Get(name) + if err == nil { + if resp.Namespace == namespace && resp.Name == name { + return fmt.Errorf("Limit Range still exists: %s", rs.Primary.ID) + } + } + } + + return nil +} + +func testAccCheckKubernetesLimitRangeExists(n string, obj *api.LimitRange) resource.TestCheckFunc { + return func(s *terraform.State) error { + rs, ok := s.RootModule().Resources[n] + if !ok { + return fmt.Errorf("Not found: %s", n) + } + + conn := testAccProvider.Meta().(*kubernetes.Clientset) + namespace, name := idParts(rs.Primary.ID) + out, err := conn.CoreV1().LimitRanges(namespace).Get(name) + if err != nil { + return err + } + + *obj = *out + return nil + } +} + +func testAccKubernetesLimitRangeConfig_basic(name string) string { + return fmt.Sprintf(` +resource "kubernetes_limit_range" "test" { + metadata { + annotations { + TestAnnotationOne = "one" + } + labels { + TestLabelOne = "one" + TestLabelThree = "three" + TestLabelFour = "four" + } + name = "%s" + } + spec { + limit { + type = "Container" + + default { + cpu = "200m" + memory = "512M" + } + + default_request { + cpu = "100m" + memory = "256M" + } + } + } +} +`, name) +} + +func testAccKubernetesLimitRangeConfig_metaModified(name string) string { + return fmt.Sprintf(` +resource "kubernetes_limit_range" "test" { + metadata { + annotations { + TestAnnotationOne = "one" + TestAnnotationTwo = "two" + } + labels { + TestLabelOne = "one" + TestLabelTwo = "two" + TestLabelThree = "three" + } + name = "%s" + } + spec { + limit { + type = "Container" + + default { + cpu = "200m" + memory = "512M" + } + + default_request { + cpu = "100m" + memory = "256M" + } + } + } +} +`, name) +} + +func testAccKubernetesLimitRangeConfig_specModified(name string) string { + return fmt.Sprintf(` +resource "kubernetes_limit_range" "test" { + metadata { + name = "%s" + } + spec { + limit { + type = "Container" + + default { + cpu = "200m" + memory = "1024M" + } + + max { + cpu = "500m" + } + + min { + cpu = "10m" + memory = "10M" + } + } + } +} +`, name) +} + +func testAccKubernetesLimitRangeConfig_generatedName(prefix string) string { + return fmt.Sprintf(` +resource "kubernetes_limit_range" "test" { + metadata { + generate_name = "%s" + } + spec { + limit { + type = "Pod" + } + } +} +`, prefix) +} + +func testAccKubernetesLimitRangeConfig_typeChange(name string) string { + return fmt.Sprintf(` +resource "kubernetes_limit_range" "test" { + metadata { + name = "%s" + } + spec { + limit { + type = "Container" + default { + cpu = "200m" + memory = "1024M" + } + } + } +} +`, name) +} + +func testAccKubernetesLimitRangeConfig_typeChangeModified(name string) string { + return fmt.Sprintf(` +resource "kubernetes_limit_range" "test" { + metadata { + name = "%s" + } + spec { + limit { + type = "Pod" + min { + cpu = "200m" + memory = "1024M" + } + } + } +} +`, name) +} + +func testAccKubernetesLimitRangeConfig_multipleLimits(name string) string { + return fmt.Sprintf(` +resource "kubernetes_limit_range" "test" { + metadata { + name = "%s" + } + spec { + limit { + type = "Pod" + max { + cpu = "200m" + memory = "1024M" + } + } + limit { + type = "PersistentVolumeClaim" + min { + storage = "24M" + } + } + limit { + type = "Container" + default { + cpu = "50m" + memory = "24M" + } + } + } +} +`, name) +} diff --git a/builtin/providers/kubernetes/resource_kubernetes_namespace.go b/builtin/providers/kubernetes/resource_kubernetes_namespace.go index 9e6160e51..0f1a7366e 100644 --- a/builtin/providers/kubernetes/resource_kubernetes_namespace.go +++ b/builtin/providers/kubernetes/resource_kubernetes_namespace.go @@ -7,6 +7,7 @@ import ( "github.com/hashicorp/terraform/helper/resource" "github.com/hashicorp/terraform/helper/schema" + pkgApi "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/errors" api "k8s.io/kubernetes/pkg/api/v1" kubernetes "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" @@ -24,7 +25,7 @@ func resourceKubernetesNamespace() *schema.Resource { }, Schema: map[string]*schema.Schema{ - "metadata": metadataSchema("namespace"), + "metadata": metadataSchema("namespace", true), }, } } @@ -69,15 +70,14 @@ func resourceKubernetesNamespaceRead(d *schema.ResourceData, meta interface{}) e func resourceKubernetesNamespaceUpdate(d *schema.ResourceData, meta interface{}) error { conn := meta.(*kubernetes.Clientset) - metadata := expandMetadata(d.Get("metadata").([]interface{})) - // This is necessary in case the name is generated - metadata.Name = d.Id() - - namespace := api.Namespace{ - ObjectMeta: metadata, + ops := patchMetadata("metadata.0.", "/metadata/", d) + data, err := ops.MarshalJSON() + if err != nil { + return fmt.Errorf("Failed to marshal update operations: %s", err) } - log.Printf("[INFO] Updating namespace: %#v", namespace) - out, err := conn.CoreV1().Namespaces().Update(&namespace) + + log.Printf("[INFO] Updating namespace: %s", ops) + out, err := conn.CoreV1().Namespaces().Patch(d.Id(), pkgApi.JSONPatchType, data) if err != nil { return err } diff --git a/builtin/providers/kubernetes/resource_kubernetes_persistent_volume.go b/builtin/providers/kubernetes/resource_kubernetes_persistent_volume.go new file mode 100644 index 000000000..8a74c9843 --- /dev/null +++ b/builtin/providers/kubernetes/resource_kubernetes_persistent_volume.go @@ -0,0 +1,195 @@ +package kubernetes + +import ( + "fmt" + "log" + "time" + + "github.com/hashicorp/terraform/helper/resource" + "github.com/hashicorp/terraform/helper/schema" + pkgApi "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/errors" + api "k8s.io/kubernetes/pkg/api/v1" + kubernetes "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" +) + +func resourceKubernetesPersistentVolume() *schema.Resource { + return &schema.Resource{ + Create: resourceKubernetesPersistentVolumeCreate, + Read: resourceKubernetesPersistentVolumeRead, + Exists: resourceKubernetesPersistentVolumeExists, + Update: resourceKubernetesPersistentVolumeUpdate, + Delete: resourceKubernetesPersistentVolumeDelete, + Importer: &schema.ResourceImporter{ + State: schema.ImportStatePassthrough, + }, + + Schema: map[string]*schema.Schema{ + "metadata": metadataSchema("persistent volume", false), + "spec": { + Type: schema.TypeList, + Description: "Spec of the persistent volume owned by the cluster", + Required: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "access_modes": { + Type: schema.TypeSet, + Description: "Contains all ways the volume can be mounted. More info: http://kubernetes.io/docs/user-guide/persistent-volumes#access-modes", + Required: true, + Elem: &schema.Schema{Type: schema.TypeString}, + Set: schema.HashString, + }, + "capacity": { + Type: schema.TypeMap, + Description: "A description of the persistent volume's resources and capacity. More info: http://kubernetes.io/docs/user-guide/persistent-volumes#capacity", + Required: true, + Elem: schema.TypeString, + ValidateFunc: validateResourceList, + }, + "persistent_volume_reclaim_policy": { + Type: schema.TypeString, + Description: "What happens to a persistent volume when released from its claim. Valid options are Retain (default) and Recycle. Recycling must be supported by the volume plugin underlying this persistent volume. More info: http://kubernetes.io/docs/user-guide/persistent-volumes#recycling-policy", + Optional: true, + Default: "Retain", + }, + "persistent_volume_source": { + Type: schema.TypeList, + Description: "The specification of a persistent volume.", + Required: true, + MaxItems: 1, + Elem: persistentVolumeSourceSchema(), + }, + }, + }, + }, + }, + } +} + +func resourceKubernetesPersistentVolumeCreate(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*kubernetes.Clientset) + + metadata := expandMetadata(d.Get("metadata").([]interface{})) + spec, err := expandPersistentVolumeSpec(d.Get("spec").([]interface{})) + if err != nil { + return err + } + volume := api.PersistentVolume{ + ObjectMeta: metadata, + Spec: spec, + } + + log.Printf("[INFO] Creating new persistent volume: %#v", volume) + out, err := conn.CoreV1().PersistentVolumes().Create(&volume) + if err != nil { + return err + } + log.Printf("[INFO] Submitted new persistent volume: %#v", out) + + stateConf := &resource.StateChangeConf{ + Target: []string{"Available", "Bound"}, + Pending: []string{"Pending"}, + Timeout: 5 * time.Minute, + Refresh: func() (interface{}, string, error) { + out, err := conn.CoreV1().PersistentVolumes().Get(metadata.Name) + if err != nil { + log.Printf("[ERROR] Received error: %#v", err) + return out, "Error", err + } + + statusPhase := fmt.Sprintf("%v", out.Status.Phase) + log.Printf("[DEBUG] Persistent volume %s status received: %#v", out.Name, statusPhase) + return out, statusPhase, nil + }, + } + _, err = stateConf.WaitForState() + if err != nil { + return err + } + log.Printf("[INFO] Persistent volume %s created", out.Name) + + d.SetId(out.Name) + + return resourceKubernetesPersistentVolumeRead(d, meta) +} + +func resourceKubernetesPersistentVolumeRead(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*kubernetes.Clientset) + + name := d.Id() + log.Printf("[INFO] Reading persistent volume %s", name) + volume, err := conn.CoreV1().PersistentVolumes().Get(name) + if err != nil { + log.Printf("[DEBUG] Received error: %#v", err) + return err + } + log.Printf("[INFO] Received persistent volume: %#v", volume) + err = d.Set("metadata", flattenMetadata(volume.ObjectMeta)) + if err != nil { + return err + } + err = d.Set("spec", flattenPersistentVolumeSpec(volume.Spec)) + if err != nil { + return err + } + + return nil +} + +func resourceKubernetesPersistentVolumeUpdate(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*kubernetes.Clientset) + + ops := patchMetadata("metadata.0.", "/metadata/", d) + if d.HasChange("spec") { + specOps, err := patchPersistentVolumeSpec("/spec", "spec", d) + if err != nil { + return err + } + ops = append(ops, specOps...) + } + data, err := ops.MarshalJSON() + if err != nil { + return fmt.Errorf("Failed to marshal update operations: %s", err) + } + + log.Printf("[INFO] Updating persistent volume %s: %s", d.Id(), ops) + out, err := conn.CoreV1().PersistentVolumes().Patch(d.Id(), pkgApi.JSONPatchType, data) + if err != nil { + return err + } + log.Printf("[INFO] Submitted updated persistent volume: %#v", out) + d.SetId(out.Name) + + return resourceKubernetesPersistentVolumeRead(d, meta) +} + +func resourceKubernetesPersistentVolumeDelete(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*kubernetes.Clientset) + + name := d.Id() + log.Printf("[INFO] Deleting persistent volume: %#v", name) + err := conn.CoreV1().PersistentVolumes().Delete(name, &api.DeleteOptions{}) + if err != nil { + return err + } + + log.Printf("[INFO] Persistent volume %s deleted", name) + + d.SetId("") + return nil +} + +func resourceKubernetesPersistentVolumeExists(d *schema.ResourceData, meta interface{}) (bool, error) { + conn := meta.(*kubernetes.Clientset) + + name := d.Id() + log.Printf("[INFO] Checking persistent volume %s", name) + _, err := conn.CoreV1().PersistentVolumes().Get(name) + if err != nil { + if statusErr, ok := err.(*errors.StatusError); ok && statusErr.ErrStatus.Code == 404 { + return false, nil + } + log.Printf("[DEBUG] Received error: %#v", err) + } + return true, err +} diff --git a/builtin/providers/kubernetes/resource_kubernetes_persistent_volume_claim.go b/builtin/providers/kubernetes/resource_kubernetes_persistent_volume_claim.go new file mode 100644 index 000000000..ca0150eaa --- /dev/null +++ b/builtin/providers/kubernetes/resource_kubernetes_persistent_volume_claim.go @@ -0,0 +1,266 @@ +package kubernetes + +import ( + "fmt" + "log" + "time" + + "github.com/hashicorp/terraform/helper/resource" + "github.com/hashicorp/terraform/helper/schema" + pkgApi "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/errors" + api "k8s.io/kubernetes/pkg/api/v1" + kubernetes "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" +) + +func resourceKubernetesPersistentVolumeClaim() *schema.Resource { + return &schema.Resource{ + Create: resourceKubernetesPersistentVolumeClaimCreate, + Read: resourceKubernetesPersistentVolumeClaimRead, + Exists: resourceKubernetesPersistentVolumeClaimExists, + Update: resourceKubernetesPersistentVolumeClaimUpdate, + Delete: resourceKubernetesPersistentVolumeClaimDelete, + Importer: &schema.ResourceImporter{ + State: func(d *schema.ResourceData, meta interface{}) ([]*schema.ResourceData, error) { + d.Set("wait_until_bound", true) + return []*schema.ResourceData{d}, nil + }, + }, + + Timeouts: &schema.ResourceTimeout{ + Create: schema.DefaultTimeout(5 * time.Minute), + }, + + Schema: map[string]*schema.Schema{ + "metadata": namespacedMetadataSchema("persistent volume claim", true), + "spec": { + Type: schema.TypeList, + Description: "Spec defines the desired characteristics of a volume requested by a pod author. More info: http://kubernetes.io/docs/user-guide/persistent-volumes#persistentvolumeclaims", + Required: true, + ForceNew: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "access_modes": { + Type: schema.TypeSet, + Description: "A set of the desired access modes the volume should have. More info: http://kubernetes.io/docs/user-guide/persistent-volumes#access-modes-1", + Required: true, + ForceNew: true, + Elem: &schema.Schema{Type: schema.TypeString}, + Set: schema.HashString, + }, + "resources": { + Type: schema.TypeList, + Description: "A list of the minimum resources the volume should have. More info: http://kubernetes.io/docs/user-guide/persistent-volumes#resources", + Required: true, + ForceNew: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "limits": { + Type: schema.TypeMap, + Description: "Map describing the maximum amount of compute resources allowed. More info: http://kubernetes.io/docs/user-guide/compute-resources/", + Optional: true, + ForceNew: true, + }, + "requests": { + Type: schema.TypeMap, + Description: "Map describing the minimum amount of compute resources required. If this is omitted for a container, it defaults to `limits` if that is explicitly specified, otherwise to an implementation-defined value. More info: http://kubernetes.io/docs/user-guide/compute-resources/", + Optional: true, + ForceNew: true, + }, + }, + }, + }, + "selector": { + Type: schema.TypeList, + Description: "A label query over volumes to consider for binding.", + Optional: true, + ForceNew: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "match_expressions": { + Type: schema.TypeList, + Description: "A list of label selector requirements. The requirements are ANDed.", + Optional: true, + ForceNew: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "key": { + Type: schema.TypeString, + Description: "The label key that the selector applies to.", + Optional: true, + ForceNew: true, + }, + "operator": { + Type: schema.TypeString, + Description: "A key's relationship to a set of values. Valid operators ard `In`, `NotIn`, `Exists` and `DoesNotExist`.", + Optional: true, + ForceNew: true, + }, + "values": { + Type: schema.TypeSet, + Description: "An array of string values. If the operator is `In` or `NotIn`, the values array must be non-empty. If the operator is `Exists` or `DoesNotExist`, the values array must be empty. This array is replaced during a strategic merge patch.", + Optional: true, + ForceNew: true, + Elem: &schema.Schema{Type: schema.TypeString}, + Set: schema.HashString, + }, + }, + }, + }, + "match_labels": { + Type: schema.TypeMap, + Description: "A map of {key,value} pairs. A single {key,value} in the matchLabels map is equivalent to an element of `match_expressions`, whose key field is \"key\", the operator is \"In\", and the values array contains only \"value\". The requirements are ANDed.", + Optional: true, + ForceNew: true, + }, + }, + }, + }, + "volume_name": { + Type: schema.TypeString, + Description: "The binding reference to the PersistentVolume backing this claim.", + Optional: true, + ForceNew: true, + Computed: true, + }, + }, + }, + }, + "wait_until_bound": { + Type: schema.TypeBool, + Description: "Whether to wait for the claim to reach `Bound` state (to find volume in which to claim the space)", + Optional: true, + Default: true, + }, + }, + } +} + +func resourceKubernetesPersistentVolumeClaimCreate(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*kubernetes.Clientset) + + metadata := expandMetadata(d.Get("metadata").([]interface{})) + spec, err := expandPersistentVolumeClaimSpec(d.Get("spec").([]interface{})) + if err != nil { + return err + } + + claim := api.PersistentVolumeClaim{ + ObjectMeta: metadata, + Spec: spec, + } + + log.Printf("[INFO] Creating new persistent volume claim: %#v", claim) + out, err := conn.CoreV1().PersistentVolumeClaims(metadata.Namespace).Create(&claim) + if err != nil { + return err + } + log.Printf("[INFO] Submitted new persistent volume claim: %#v", out) + + d.SetId(buildId(out.ObjectMeta)) + name := out.ObjectMeta.Name + + if d.Get("wait_until_bound").(bool) { + stateConf := &resource.StateChangeConf{ + Target: []string{"Bound"}, + Pending: []string{"Pending"}, + Timeout: d.Timeout(schema.TimeoutCreate), + Refresh: func() (interface{}, string, error) { + out, err := conn.CoreV1().PersistentVolumeClaims(metadata.Namespace).Get(name) + if err != nil { + log.Printf("[ERROR] Received error: %#v", err) + return out, "", err + } + + statusPhase := fmt.Sprintf("%v", out.Status.Phase) + log.Printf("[DEBUG] Persistent volume claim %s status received: %#v", out.Name, statusPhase) + return out, statusPhase, nil + }, + } + _, err = stateConf.WaitForState() + if err != nil { + return err + } + } + log.Printf("[INFO] Persistent volume claim %s created", out.Name) + + return resourceKubernetesPersistentVolumeClaimRead(d, meta) +} + +func resourceKubernetesPersistentVolumeClaimRead(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*kubernetes.Clientset) + + namespace, name := idParts(d.Id()) + log.Printf("[INFO] Reading persistent volume claim %s", name) + claim, err := conn.CoreV1().PersistentVolumeClaims(namespace).Get(name) + if err != nil { + log.Printf("[DEBUG] Received error: %#v", err) + return err + } + log.Printf("[INFO] Received persistent volume claim: %#v", claim) + err = d.Set("metadata", flattenMetadata(claim.ObjectMeta)) + if err != nil { + return err + } + err = d.Set("spec", flattenPersistentVolumeClaimSpec(claim.Spec)) + if err != nil { + return err + } + + return nil +} + +func resourceKubernetesPersistentVolumeClaimUpdate(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*kubernetes.Clientset) + namespace, name := idParts(d.Id()) + + ops := patchMetadata("metadata.0.", "/metadata/", d) + // The whole spec is ForceNew = nothing to update there + data, err := ops.MarshalJSON() + if err != nil { + return fmt.Errorf("Failed to marshal update operations: %s", err) + } + + log.Printf("[INFO] Updating persistent volume claim: %s", ops) + out, err := conn.CoreV1().PersistentVolumeClaims(namespace).Patch(name, pkgApi.JSONPatchType, data) + if err != nil { + return err + } + log.Printf("[INFO] Submitted updated persistent volume claim: %#v", out) + + return resourceKubernetesPersistentVolumeClaimRead(d, meta) +} + +func resourceKubernetesPersistentVolumeClaimDelete(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*kubernetes.Clientset) + + namespace, name := idParts(d.Id()) + log.Printf("[INFO] Deleting persistent volume claim: %#v", name) + err := conn.CoreV1().PersistentVolumeClaims(namespace).Delete(name, &api.DeleteOptions{}) + if err != nil { + return err + } + + log.Printf("[INFO] Persistent volume claim %s deleted", name) + + d.SetId("") + return nil +} + +func resourceKubernetesPersistentVolumeClaimExists(d *schema.ResourceData, meta interface{}) (bool, error) { + conn := meta.(*kubernetes.Clientset) + + namespace, name := idParts(d.Id()) + log.Printf("[INFO] Checking persistent volume claim %s", name) + _, err := conn.CoreV1().PersistentVolumeClaims(namespace).Get(name) + if err != nil { + if statusErr, ok := err.(*errors.StatusError); ok && statusErr.ErrStatus.Code == 404 { + return false, nil + } + log.Printf("[DEBUG] Received error: %#v", err) + } + return true, err +} diff --git a/builtin/providers/kubernetes/resource_kubernetes_persistent_volume_claim_test.go b/builtin/providers/kubernetes/resource_kubernetes_persistent_volume_claim_test.go new file mode 100644 index 000000000..2436212fa --- /dev/null +++ b/builtin/providers/kubernetes/resource_kubernetes_persistent_volume_claim_test.go @@ -0,0 +1,667 @@ +package kubernetes + +import ( + "fmt" + "testing" + + "github.com/hashicorp/terraform/helper/acctest" + "github.com/hashicorp/terraform/helper/resource" + "github.com/hashicorp/terraform/terraform" + api "k8s.io/kubernetes/pkg/api/v1" + kubernetes "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" +) + +func TestAccKubernetesPersistentVolumeClaim_basic(t *testing.T) { + var conf api.PersistentVolumeClaim + name := fmt.Sprintf("tf-acc-test-%s", acctest.RandString(10)) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + IDRefreshName: "kubernetes_persistent_volume_claim.test", + Providers: testAccProviders, + CheckDestroy: testAccCheckKubernetesPersistentVolumeClaimDestroy, + Steps: []resource.TestStep{ + { + Config: testAccKubernetesPersistentVolumeClaimConfig_basic(name), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckKubernetesPersistentVolumeClaimExists("kubernetes_persistent_volume_claim.test", &conf), + resource.TestCheckResourceAttr("kubernetes_persistent_volume_claim.test", "metadata.0.annotations.%", "1"), + resource.TestCheckResourceAttr("kubernetes_persistent_volume_claim.test", "metadata.0.annotations.TestAnnotationOne", "one"), + testAccCheckMetaAnnotations(&conf.ObjectMeta, map[string]string{"TestAnnotationOne": "one"}), + resource.TestCheckResourceAttr("kubernetes_persistent_volume_claim.test", "metadata.0.labels.%", "3"), + resource.TestCheckResourceAttr("kubernetes_persistent_volume_claim.test", "metadata.0.labels.TestLabelOne", "one"), + resource.TestCheckResourceAttr("kubernetes_persistent_volume_claim.test", "metadata.0.labels.TestLabelThree", "three"), + resource.TestCheckResourceAttr("kubernetes_persistent_volume_claim.test", "metadata.0.labels.TestLabelFour", "four"), + testAccCheckMetaLabels(&conf.ObjectMeta, map[string]string{"TestLabelOne": "one", "TestLabelThree": "three", "TestLabelFour": "four"}), + resource.TestCheckResourceAttr("kubernetes_persistent_volume_claim.test", "metadata.0.name", name), + resource.TestCheckResourceAttrSet("kubernetes_persistent_volume_claim.test", "metadata.0.generation"), + resource.TestCheckResourceAttrSet("kubernetes_persistent_volume_claim.test", "metadata.0.resource_version"), + resource.TestCheckResourceAttrSet("kubernetes_persistent_volume_claim.test", "metadata.0.self_link"), + resource.TestCheckResourceAttrSet("kubernetes_persistent_volume_claim.test", "metadata.0.uid"), + resource.TestCheckResourceAttr("kubernetes_persistent_volume_claim.test", "spec.0.access_modes.#", "1"), + resource.TestCheckResourceAttr("kubernetes_persistent_volume_claim.test", "spec.0.access_modes.1254135962", "ReadWriteMany"), + resource.TestCheckResourceAttr("kubernetes_persistent_volume_claim.test", "spec.0.resources.#", "1"), + resource.TestCheckResourceAttr("kubernetes_persistent_volume_claim.test", "spec.0.resources.0.requests.%", "1"), + resource.TestCheckResourceAttr("kubernetes_persistent_volume_claim.test", "spec.0.resources.0.requests.storage", "5Gi"), + ), + }, + { + Config: testAccKubernetesPersistentVolumeClaimConfig_metaModified(name), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckKubernetesPersistentVolumeClaimExists("kubernetes_persistent_volume_claim.test", &conf), + resource.TestCheckResourceAttr("kubernetes_persistent_volume_claim.test", "metadata.0.annotations.%", "2"), + resource.TestCheckResourceAttr("kubernetes_persistent_volume_claim.test", "metadata.0.annotations.TestAnnotationOne", "one"), + resource.TestCheckResourceAttr("kubernetes_persistent_volume_claim.test", "metadata.0.annotations.TestAnnotationTwo", "two"), + testAccCheckMetaAnnotations(&conf.ObjectMeta, map[string]string{"TestAnnotationOne": "one", "TestAnnotationTwo": "two"}), + resource.TestCheckResourceAttr("kubernetes_persistent_volume_claim.test", "metadata.0.labels.%", "3"), + resource.TestCheckResourceAttr("kubernetes_persistent_volume_claim.test", "metadata.0.labels.TestLabelOne", "one"), + resource.TestCheckResourceAttr("kubernetes_persistent_volume_claim.test", "metadata.0.labels.TestLabelTwo", "two"), + resource.TestCheckResourceAttr("kubernetes_persistent_volume_claim.test", "metadata.0.labels.TestLabelThree", "three"), + testAccCheckMetaLabels(&conf.ObjectMeta, map[string]string{"TestLabelOne": "one", "TestLabelTwo": "two", "TestLabelThree": "three"}), + resource.TestCheckResourceAttr("kubernetes_persistent_volume_claim.test", "metadata.0.name", name), + resource.TestCheckResourceAttrSet("kubernetes_persistent_volume_claim.test", "metadata.0.generation"), + resource.TestCheckResourceAttrSet("kubernetes_persistent_volume_claim.test", "metadata.0.resource_version"), + resource.TestCheckResourceAttrSet("kubernetes_persistent_volume_claim.test", "metadata.0.self_link"), + resource.TestCheckResourceAttrSet("kubernetes_persistent_volume_claim.test", "metadata.0.uid"), + resource.TestCheckResourceAttr("kubernetes_persistent_volume_claim.test", "spec.0.access_modes.#", "1"), + resource.TestCheckResourceAttr("kubernetes_persistent_volume_claim.test", "spec.0.access_modes.1254135962", "ReadWriteMany"), + resource.TestCheckResourceAttr("kubernetes_persistent_volume_claim.test", "spec.0.resources.#", "1"), + resource.TestCheckResourceAttr("kubernetes_persistent_volume_claim.test", "spec.0.resources.0.requests.%", "1"), + resource.TestCheckResourceAttr("kubernetes_persistent_volume_claim.test", "spec.0.resources.0.requests.storage", "5Gi"), + ), + }, + }, + }) +} + +func TestAccKubernetesPersistentVolumeClaim_importBasic(t *testing.T) { + resourceName := "kubernetes_persistent_volume_claim.test" + volumeName := fmt.Sprintf("tf-acc-test-%s", acctest.RandString(10)) + claimName := fmt.Sprintf("tf-acc-test-%s", acctest.RandString(10)) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckKubernetesPersistentVolumeClaimDestroy, + Steps: []resource.TestStep{ + { + Config: testAccKubernetesPersistentVolumeClaimConfig_import(volumeName, claimName), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func TestAccKubernetesPersistentVolumeClaim_volumeMatch(t *testing.T) { + var pvcConf api.PersistentVolumeClaim + var pvConf api.PersistentVolume + + claimName := fmt.Sprintf("tf-acc-test-%s", acctest.RandString(10)) + volumeName := fmt.Sprintf("tf-acc-test-%s", acctest.RandString(10)) + volumeNameModified := fmt.Sprintf("tf-acc-test-%s", acctest.RandString(10)) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + IDRefreshName: "kubernetes_persistent_volume_claim.test", + Providers: testAccProviders, + CheckDestroy: testAccCheckKubernetesPersistentVolumeClaimDestroy, + Steps: []resource.TestStep{ + { + Config: testAccKubernetesPersistentVolumeClaimConfig_volumeMatch(volumeName, claimName), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckKubernetesPersistentVolumeClaimExists("kubernetes_persistent_volume_claim.test", &pvcConf), + resource.TestCheckResourceAttr("kubernetes_persistent_volume_claim.test", "metadata.0.annotations.%", "0"), + testAccCheckMetaAnnotations(&pvcConf.ObjectMeta, map[string]string{"pv.kubernetes.io/bind-completed": "yes"}), + resource.TestCheckResourceAttr("kubernetes_persistent_volume_claim.test", "metadata.0.labels.%", "0"), + testAccCheckMetaLabels(&pvcConf.ObjectMeta, map[string]string{}), + resource.TestCheckResourceAttr("kubernetes_persistent_volume_claim.test", "metadata.0.name", claimName), + resource.TestCheckResourceAttrSet("kubernetes_persistent_volume_claim.test", "metadata.0.generation"), + resource.TestCheckResourceAttrSet("kubernetes_persistent_volume_claim.test", "metadata.0.resource_version"), + resource.TestCheckResourceAttrSet("kubernetes_persistent_volume_claim.test", "metadata.0.self_link"), + resource.TestCheckResourceAttrSet("kubernetes_persistent_volume_claim.test", "metadata.0.uid"), + resource.TestCheckResourceAttr("kubernetes_persistent_volume_claim.test", "spec.0.access_modes.#", "1"), + resource.TestCheckResourceAttr("kubernetes_persistent_volume_claim.test", "spec.0.access_modes.1254135962", "ReadWriteMany"), + resource.TestCheckResourceAttr("kubernetes_persistent_volume_claim.test", "spec.0.resources.#", "1"), + resource.TestCheckResourceAttr("kubernetes_persistent_volume_claim.test", "spec.0.resources.0.requests.%", "1"), + resource.TestCheckResourceAttr("kubernetes_persistent_volume_claim.test", "spec.0.resources.0.requests.storage", "5Gi"), + resource.TestCheckResourceAttr("kubernetes_persistent_volume_claim.test", "spec.0.volume_name", volumeName), + testAccCheckKubernetesPersistentVolumeExists("kubernetes_persistent_volume.test", &pvConf), + testAccCheckMetaAnnotations(&pvConf.ObjectMeta, map[string]string{"pv.kubernetes.io/bound-by-controller": "yes"}), + ), + }, + { + Config: testAccKubernetesPersistentVolumeClaimConfig_volumeMatch_modified(volumeNameModified, claimName), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckKubernetesPersistentVolumeClaimExists("kubernetes_persistent_volume_claim.test", &pvcConf), + resource.TestCheckResourceAttr("kubernetes_persistent_volume_claim.test", "metadata.0.annotations.%", "0"), + testAccCheckMetaAnnotations(&pvcConf.ObjectMeta, map[string]string{"pv.kubernetes.io/bind-completed": "yes"}), + resource.TestCheckResourceAttr("kubernetes_persistent_volume_claim.test", "metadata.0.labels.%", "0"), + testAccCheckMetaLabels(&pvcConf.ObjectMeta, map[string]string{}), + resource.TestCheckResourceAttr("kubernetes_persistent_volume_claim.test", "metadata.0.name", claimName), + resource.TestCheckResourceAttrSet("kubernetes_persistent_volume_claim.test", "metadata.0.generation"), + resource.TestCheckResourceAttrSet("kubernetes_persistent_volume_claim.test", "metadata.0.resource_version"), + resource.TestCheckResourceAttrSet("kubernetes_persistent_volume_claim.test", "metadata.0.self_link"), + resource.TestCheckResourceAttrSet("kubernetes_persistent_volume_claim.test", "metadata.0.uid"), + resource.TestCheckResourceAttr("kubernetes_persistent_volume_claim.test", "spec.0.access_modes.#", "1"), + resource.TestCheckResourceAttr("kubernetes_persistent_volume_claim.test", "spec.0.access_modes.1254135962", "ReadWriteMany"), + resource.TestCheckResourceAttr("kubernetes_persistent_volume_claim.test", "spec.0.resources.#", "1"), + resource.TestCheckResourceAttr("kubernetes_persistent_volume_claim.test", "spec.0.resources.0.requests.%", "1"), + resource.TestCheckResourceAttr("kubernetes_persistent_volume_claim.test", "spec.0.resources.0.requests.storage", "5Gi"), + resource.TestCheckResourceAttr("kubernetes_persistent_volume_claim.test", "spec.0.volume_name", volumeNameModified), + testAccCheckKubernetesPersistentVolumeExists("kubernetes_persistent_volume.test2", &pvConf), + testAccCheckMetaAnnotations(&pvConf.ObjectMeta, map[string]string{"pv.kubernetes.io/bound-by-controller": "yes"}), + ), + }, + }, + }) +} + +func TestAccKubernetesPersistentVolumeClaim_labelsMatch(t *testing.T) { + var conf api.PersistentVolumeClaim + claimName := fmt.Sprintf("tf-acc-test-%s", acctest.RandString(10)) + volumeName := fmt.Sprintf("tf-acc-test-%s", acctest.RandString(10)) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + IDRefreshName: "kubernetes_persistent_volume_claim.test", + Providers: testAccProviders, + CheckDestroy: testAccCheckKubernetesPersistentVolumeClaimDestroy, + Steps: []resource.TestStep{ + { + Config: testAccKubernetesPersistentVolumeClaimConfig_labelsMatch(volumeName, claimName), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckKubernetesPersistentVolumeClaimExists("kubernetes_persistent_volume_claim.test", &conf), + resource.TestCheckResourceAttr("kubernetes_persistent_volume_claim.test", "metadata.0.annotations.%", "0"), + testAccCheckMetaAnnotations(&conf.ObjectMeta, map[string]string{"pv.kubernetes.io/bind-completed": "yes", "pv.kubernetes.io/bound-by-controller": "yes"}), + resource.TestCheckResourceAttr("kubernetes_persistent_volume_claim.test", "metadata.0.labels.%", "0"), + testAccCheckMetaLabels(&conf.ObjectMeta, map[string]string{}), + resource.TestCheckResourceAttr("kubernetes_persistent_volume_claim.test", "metadata.0.name", claimName), + resource.TestCheckResourceAttrSet("kubernetes_persistent_volume_claim.test", "metadata.0.generation"), + resource.TestCheckResourceAttrSet("kubernetes_persistent_volume_claim.test", "metadata.0.resource_version"), + resource.TestCheckResourceAttrSet("kubernetes_persistent_volume_claim.test", "metadata.0.self_link"), + resource.TestCheckResourceAttrSet("kubernetes_persistent_volume_claim.test", "metadata.0.uid"), + resource.TestCheckResourceAttr("kubernetes_persistent_volume_claim.test", "spec.0.access_modes.#", "1"), + resource.TestCheckResourceAttr("kubernetes_persistent_volume_claim.test", "spec.0.access_modes.1254135962", "ReadWriteMany"), + resource.TestCheckResourceAttr("kubernetes_persistent_volume_claim.test", "spec.0.resources.#", "1"), + resource.TestCheckResourceAttr("kubernetes_persistent_volume_claim.test", "spec.0.resources.0.requests.%", "1"), + resource.TestCheckResourceAttr("kubernetes_persistent_volume_claim.test", "spec.0.resources.0.requests.storage", "5Gi"), + resource.TestCheckResourceAttr("kubernetes_persistent_volume_claim.test", "spec.0.selector.#", "1"), + resource.TestCheckResourceAttr("kubernetes_persistent_volume_claim.test", "spec.0.selector.0.match_labels.%", "1"), + resource.TestCheckResourceAttr("kubernetes_persistent_volume_claim.test", "spec.0.selector.0.match_labels.TfAccTestEnvironment", "blablah"), + ), + }, + }, + }) +} + +func TestAccKubernetesPersistentVolumeClaim_labelsMatchExpression(t *testing.T) { + var conf api.PersistentVolumeClaim + claimName := fmt.Sprintf("tf-acc-test-%s", acctest.RandString(10)) + volumeName := fmt.Sprintf("tf-acc-test-%s", acctest.RandString(10)) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + IDRefreshName: "kubernetes_persistent_volume_claim.test", + Providers: testAccProviders, + CheckDestroy: testAccCheckKubernetesPersistentVolumeClaimDestroy, + Steps: []resource.TestStep{ + { + Config: testAccKubernetesPersistentVolumeClaimConfig_labelsMatchExpression(volumeName, claimName), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckKubernetesPersistentVolumeClaimExists("kubernetes_persistent_volume_claim.test", &conf), + resource.TestCheckResourceAttr("kubernetes_persistent_volume_claim.test", "metadata.0.annotations.%", "0"), + testAccCheckMetaAnnotations(&conf.ObjectMeta, map[string]string{"pv.kubernetes.io/bind-completed": "yes", "pv.kubernetes.io/bound-by-controller": "yes"}), + resource.TestCheckResourceAttr("kubernetes_persistent_volume_claim.test", "metadata.0.labels.%", "0"), + testAccCheckMetaLabels(&conf.ObjectMeta, map[string]string{}), + resource.TestCheckResourceAttr("kubernetes_persistent_volume_claim.test", "metadata.0.name", claimName), + resource.TestCheckResourceAttrSet("kubernetes_persistent_volume_claim.test", "metadata.0.generation"), + resource.TestCheckResourceAttrSet("kubernetes_persistent_volume_claim.test", "metadata.0.resource_version"), + resource.TestCheckResourceAttrSet("kubernetes_persistent_volume_claim.test", "metadata.0.self_link"), + resource.TestCheckResourceAttrSet("kubernetes_persistent_volume_claim.test", "metadata.0.uid"), + resource.TestCheckResourceAttr("kubernetes_persistent_volume_claim.test", "spec.0.access_modes.#", "1"), + resource.TestCheckResourceAttr("kubernetes_persistent_volume_claim.test", "spec.0.access_modes.1254135962", "ReadWriteMany"), + resource.TestCheckResourceAttr("kubernetes_persistent_volume_claim.test", "spec.0.resources.#", "1"), + resource.TestCheckResourceAttr("kubernetes_persistent_volume_claim.test", "spec.0.resources.0.requests.%", "1"), + resource.TestCheckResourceAttr("kubernetes_persistent_volume_claim.test", "spec.0.resources.0.requests.storage", "5Gi"), + resource.TestCheckResourceAttr("kubernetes_persistent_volume_claim.test", "spec.0.selector.#", "1"), + resource.TestCheckResourceAttr("kubernetes_persistent_volume_claim.test", "spec.0.selector.0.match_expressions.#", "1"), + resource.TestCheckResourceAttr("kubernetes_persistent_volume_claim.test", "spec.0.selector.0.match_expressions.0.key", "TfAccTestEnvironment"), + resource.TestCheckResourceAttr("kubernetes_persistent_volume_claim.test", "spec.0.selector.0.match_expressions.0.operator", "In"), + resource.TestCheckResourceAttr("kubernetes_persistent_volume_claim.test", "spec.0.selector.0.match_expressions.0.values.#", "3"), + resource.TestCheckResourceAttr("kubernetes_persistent_volume_claim.test", "spec.0.selector.0.match_expressions.0.values.1187371253", "three"), + resource.TestCheckResourceAttr("kubernetes_persistent_volume_claim.test", "spec.0.selector.0.match_expressions.0.values.2053932785", "one"), + resource.TestCheckResourceAttr("kubernetes_persistent_volume_claim.test", "spec.0.selector.0.match_expressions.0.values.298486374", "two"), + ), + }, + }, + }) +} + +func TestAccKubernetesPersistentVolumeClaim_volumeUpdate(t *testing.T) { + var pvcConf api.PersistentVolumeClaim + var pvConf api.PersistentVolume + + claimName := fmt.Sprintf("tf-acc-test-%s", acctest.RandString(10)) + volumeName := fmt.Sprintf("tf-acc-test-%s", acctest.RandString(10)) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + IDRefreshName: "kubernetes_persistent_volume_claim.test", + Providers: testAccProviders, + CheckDestroy: testAccCheckKubernetesPersistentVolumeClaimDestroy, + Steps: []resource.TestStep{ + { + Config: testAccKubernetesPersistentVolumeClaimConfig_volumeUpdate(volumeName, claimName, "5Gi"), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckKubernetesPersistentVolumeClaimExists("kubernetes_persistent_volume_claim.test", &pvcConf), + resource.TestCheckResourceAttr("kubernetes_persistent_volume_claim.test", "metadata.0.annotations.%", "0"), + testAccCheckMetaAnnotations(&pvcConf.ObjectMeta, map[string]string{"pv.kubernetes.io/bind-completed": "yes"}), + resource.TestCheckResourceAttr("kubernetes_persistent_volume_claim.test", "metadata.0.labels.%", "0"), + testAccCheckMetaLabels(&pvcConf.ObjectMeta, map[string]string{}), + resource.TestCheckResourceAttr("kubernetes_persistent_volume_claim.test", "metadata.0.name", claimName), + resource.TestCheckResourceAttrSet("kubernetes_persistent_volume_claim.test", "metadata.0.generation"), + resource.TestCheckResourceAttrSet("kubernetes_persistent_volume_claim.test", "metadata.0.resource_version"), + resource.TestCheckResourceAttrSet("kubernetes_persistent_volume_claim.test", "metadata.0.self_link"), + resource.TestCheckResourceAttrSet("kubernetes_persistent_volume_claim.test", "metadata.0.uid"), + resource.TestCheckResourceAttr("kubernetes_persistent_volume_claim.test", "spec.0.access_modes.#", "1"), + resource.TestCheckResourceAttr("kubernetes_persistent_volume_claim.test", "spec.0.access_modes.1254135962", "ReadWriteMany"), + resource.TestCheckResourceAttr("kubernetes_persistent_volume_claim.test", "spec.0.resources.#", "1"), + resource.TestCheckResourceAttr("kubernetes_persistent_volume_claim.test", "spec.0.resources.0.requests.%", "1"), + resource.TestCheckResourceAttr("kubernetes_persistent_volume_claim.test", "spec.0.resources.0.requests.storage", "5Gi"), + resource.TestCheckResourceAttr("kubernetes_persistent_volume_claim.test", "spec.0.volume_name", volumeName), + testAccCheckKubernetesPersistentVolumeExists("kubernetes_persistent_volume.test", &pvConf), + testAccCheckMetaAnnotations(&pvConf.ObjectMeta, map[string]string{"pv.kubernetes.io/bound-by-controller": "yes"}), + testAccCheckClaimRef(&pvConf, &ObjectRefStatic{Namespace: "default", Name: claimName}), + ), + }, + { + Config: testAccKubernetesPersistentVolumeClaimConfig_volumeUpdate(volumeName, claimName, "10Gi"), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckKubernetesPersistentVolumeClaimExists("kubernetes_persistent_volume_claim.test", &pvcConf), + resource.TestCheckResourceAttr("kubernetes_persistent_volume_claim.test", "metadata.0.annotations.%", "0"), + testAccCheckMetaAnnotations(&pvcConf.ObjectMeta, map[string]string{"pv.kubernetes.io/bind-completed": "yes"}), + resource.TestCheckResourceAttr("kubernetes_persistent_volume_claim.test", "metadata.0.labels.%", "0"), + testAccCheckMetaLabels(&pvcConf.ObjectMeta, map[string]string{}), + resource.TestCheckResourceAttr("kubernetes_persistent_volume_claim.test", "metadata.0.name", claimName), + resource.TestCheckResourceAttrSet("kubernetes_persistent_volume_claim.test", "metadata.0.generation"), + resource.TestCheckResourceAttrSet("kubernetes_persistent_volume_claim.test", "metadata.0.resource_version"), + resource.TestCheckResourceAttrSet("kubernetes_persistent_volume_claim.test", "metadata.0.self_link"), + resource.TestCheckResourceAttrSet("kubernetes_persistent_volume_claim.test", "metadata.0.uid"), + resource.TestCheckResourceAttr("kubernetes_persistent_volume_claim.test", "spec.0.access_modes.#", "1"), + resource.TestCheckResourceAttr("kubernetes_persistent_volume_claim.test", "spec.0.access_modes.1254135962", "ReadWriteMany"), + resource.TestCheckResourceAttr("kubernetes_persistent_volume_claim.test", "spec.0.resources.#", "1"), + resource.TestCheckResourceAttr("kubernetes_persistent_volume_claim.test", "spec.0.resources.0.requests.%", "1"), + resource.TestCheckResourceAttr("kubernetes_persistent_volume_claim.test", "spec.0.resources.0.requests.storage", "5Gi"), + resource.TestCheckResourceAttr("kubernetes_persistent_volume_claim.test", "spec.0.volume_name", volumeName), + testAccCheckKubernetesPersistentVolumeExists("kubernetes_persistent_volume.test", &pvConf), + testAccCheckMetaAnnotations(&pvConf.ObjectMeta, map[string]string{"pv.kubernetes.io/bound-by-controller": "yes"}), + testAccCheckClaimRef(&pvConf, &ObjectRefStatic{Namespace: "default", Name: claimName}), + ), + }, + }, + }) +} + +func testAccCheckKubernetesPersistentVolumeClaimDestroy(s *terraform.State) error { + conn := testAccProvider.Meta().(*kubernetes.Clientset) + + for _, rs := range s.RootModule().Resources { + if rs.Type != "kubernetes_persistent_volume_claim" { + continue + } + namespace, name := idParts(rs.Primary.ID) + resp, err := conn.CoreV1().PersistentVolumeClaims(namespace).Get(name) + if err == nil { + if resp.Namespace == namespace && resp.Name == name { + return fmt.Errorf("Persistent Volume still exists: %s", rs.Primary.ID) + } + } + } + + return nil +} + +func testAccCheckKubernetesPersistentVolumeClaimExists(n string, obj *api.PersistentVolumeClaim) resource.TestCheckFunc { + return func(s *terraform.State) error { + rs, ok := s.RootModule().Resources[n] + if !ok { + return fmt.Errorf("Not found: %s", n) + } + + conn := testAccProvider.Meta().(*kubernetes.Clientset) + namespace, name := idParts(rs.Primary.ID) + out, err := conn.CoreV1().PersistentVolumeClaims(namespace).Get(name) + if err != nil { + return err + } + + *obj = *out + return nil + } +} + +func testAccCheckClaimRef(pv *api.PersistentVolume, expected *ObjectRefStatic) resource.TestCheckFunc { + return func(s *terraform.State) error { + or := pv.Spec.ClaimRef + if or == nil { + return fmt.Errorf("Expected ClaimRef to be not-nil, specifically %#v", *expected) + } + if or.Namespace != expected.Namespace { + return fmt.Errorf("Expected object reference %q, given: %q", expected.Namespace, or.Namespace) + } + if or.Name != expected.Name { + return fmt.Errorf("Expected object reference %q, given: %q", expected.Name, or.Name) + } + return nil + } +} + +type ObjectRefStatic struct { + Namespace string + Name string +} + +func testAccKubernetesPersistentVolumeClaimConfig_basic(name string) string { + return fmt.Sprintf(` +resource "kubernetes_persistent_volume_claim" "test" { + metadata { + annotations { + TestAnnotationOne = "one" + } + labels { + TestLabelOne = "one" + TestLabelThree = "three" + TestLabelFour = "four" + } + name = "%s" + } + spec { + access_modes = ["ReadWriteMany"] + resources { + requests { + storage = "5Gi" + } + } + selector { + match_expressions { + key = "environment" + operator = "In" + values = ["non-exists-12345"] + } + } + } + wait_until_bound = false +} +`, name) +} + +func testAccKubernetesPersistentVolumeClaimConfig_metaModified(name string) string { + return fmt.Sprintf(` +resource "kubernetes_persistent_volume_claim" "test" { + metadata { + annotations { + TestAnnotationOne = "one" + TestAnnotationTwo = "two" + } + labels { + TestLabelOne = "one" + TestLabelTwo = "two" + TestLabelThree = "three" + } + name = "%s" + } + spec { + access_modes = ["ReadWriteMany"] + resources { + requests { + storage = "5Gi" + } + } + selector { + match_expressions { + key = "environment" + operator = "In" + values = ["non-exists-12345"] + } + } + } + wait_until_bound = false +} +`, name) +} + +func testAccKubernetesPersistentVolumeClaimConfig_import(volumeName, claimName string) string { + return fmt.Sprintf(` +resource "kubernetes_persistent_volume" "test" { + metadata { + name = "%s" + } + spec { + capacity { + storage = "10Gi" + } + access_modes = ["ReadWriteMany"] + persistent_volume_source { + gce_persistent_disk { + pd_name = "test123" + } + } + } +} + +resource "kubernetes_persistent_volume_claim" "test" { + metadata { + name = "%s" + } + spec { + access_modes = ["ReadWriteMany"] + resources { + requests { + storage = "5Gi" + } + } + volume_name = "${kubernetes_persistent_volume.test.metadata.0.name}" + } +} +`, volumeName, claimName) +} + +func testAccKubernetesPersistentVolumeClaimConfig_volumeMatch(volumeName, claimName string) string { + return fmt.Sprintf(` +resource "kubernetes_persistent_volume" "test" { + metadata { + name = "%s" + } + spec { + capacity { + storage = "10Gi" + } + access_modes = ["ReadWriteMany"] + persistent_volume_source { + gce_persistent_disk { + pd_name = "test123" + } + } + } +} + +resource "kubernetes_persistent_volume_claim" "test" { + metadata { + name = "%s" + } + spec { + access_modes = ["ReadWriteMany"] + resources { + requests { + storage = "5Gi" + } + } + volume_name = "${kubernetes_persistent_volume.test.metadata.0.name}" + } +} +`, volumeName, claimName) +} + +func testAccKubernetesPersistentVolumeClaimConfig_volumeMatch_modified(volumeName, claimName string) string { + return fmt.Sprintf(` +resource "kubernetes_persistent_volume" "test2" { + metadata { + name = "%s" + } + spec { + capacity { + storage = "10Gi" + } + access_modes = ["ReadWriteMany"] + persistent_volume_source { + gce_persistent_disk { + pd_name = "test123" + } + } + } +} + +resource "kubernetes_persistent_volume_claim" "test" { + metadata { + name = "%s" + } + spec { + access_modes = ["ReadWriteMany"] + resources { + requests { + storage = "5Gi" + } + } + volume_name = "${kubernetes_persistent_volume.test2.metadata.0.name}" + } +} +`, volumeName, claimName) +} + +func testAccKubernetesPersistentVolumeClaimConfig_labelsMatch(volumeName, claimName string) string { + return fmt.Sprintf(` +resource "kubernetes_persistent_volume" "test" { + metadata { + labels { + TfAccTestEnvironment = "blablah" + } + name = "%s" + } + spec { + capacity { + storage = "10Gi" + } + access_modes = ["ReadWriteMany"] + persistent_volume_source { + gce_persistent_disk { + pd_name = "test123" + } + } + } +} + +resource "kubernetes_persistent_volume_claim" "test" { + metadata { + name = "%s" + } + spec { + access_modes = ["ReadWriteMany"] + resources { + requests { + storage = "5Gi" + } + } + selector { + match_labels { + TfAccTestEnvironment = "blablah" + } + } + } +} +`, volumeName, claimName) +} + +func testAccKubernetesPersistentVolumeClaimConfig_labelsMatchExpression(volumeName, claimName string) string { + return fmt.Sprintf(` +resource "kubernetes_persistent_volume" "test" { + metadata { + labels { + TfAccTestEnvironment = "two" + } + name = "%s" + } + spec { + capacity { + storage = "10Gi" + } + access_modes = ["ReadWriteMany"] + persistent_volume_source { + gce_persistent_disk { + pd_name = "test123" + } + } + } +} + +resource "kubernetes_persistent_volume_claim" "test" { + metadata { + name = "%s" + } + spec { + access_modes = ["ReadWriteMany"] + resources { + requests { + storage = "5Gi" + } + } + selector { + match_expressions { + key = "TfAccTestEnvironment" + operator = "In" + values = ["one", "three", "two"] + } + } + } +} +`, volumeName, claimName) +} + +func testAccKubernetesPersistentVolumeClaimConfig_volumeUpdate(volumeName, claimName, storage string) string { + return fmt.Sprintf(` +resource "kubernetes_persistent_volume" "test" { + metadata { + name = "%s" + } + spec { + capacity { + storage = "%s" + } + access_modes = ["ReadWriteMany"] + persistent_volume_source { + gce_persistent_disk { + pd_name = "test123" + } + } + } +} + +resource "kubernetes_persistent_volume_claim" "test" { + metadata { + name = "%s" + } + spec { + access_modes = ["ReadWriteMany"] + resources { + requests { + storage = "5Gi" + } + } + volume_name = "${kubernetes_persistent_volume.test.metadata.0.name}" + } +} +`, volumeName, storage, claimName) +} diff --git a/builtin/providers/kubernetes/resource_kubernetes_persistent_volume_test.go b/builtin/providers/kubernetes/resource_kubernetes_persistent_volume_test.go new file mode 100644 index 000000000..17fb4034c --- /dev/null +++ b/builtin/providers/kubernetes/resource_kubernetes_persistent_volume_test.go @@ -0,0 +1,368 @@ +package kubernetes + +import ( + "fmt" + "testing" + + "github.com/hashicorp/terraform/helper/acctest" + "github.com/hashicorp/terraform/helper/resource" + "github.com/hashicorp/terraform/terraform" + api "k8s.io/kubernetes/pkg/api/v1" + kubernetes "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" +) + +func TestAccKubernetesPersistentVolume_basic(t *testing.T) { + var conf api.PersistentVolume + randString := acctest.RandStringFromCharSet(10, acctest.CharSetAlphaNum) + name := fmt.Sprintf("tf-acc-test-%s", randString) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + IDRefreshName: "kubernetes_persistent_volume.test", + Providers: testAccProviders, + CheckDestroy: testAccCheckKubernetesPersistentVolumeDestroy, + Steps: []resource.TestStep{ + { + Config: testAccKubernetesPersistentVolumeConfig_basic(name), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckKubernetesPersistentVolumeExists("kubernetes_persistent_volume.test", &conf), + resource.TestCheckResourceAttr("kubernetes_persistent_volume.test", "metadata.0.annotations.%", "2"), + resource.TestCheckResourceAttr("kubernetes_persistent_volume.test", "metadata.0.annotations.TestAnnotationOne", "one"), + resource.TestCheckResourceAttr("kubernetes_persistent_volume.test", "metadata.0.annotations.TestAnnotationTwo", "two"), + testAccCheckMetaAnnotations(&conf.ObjectMeta, map[string]string{"TestAnnotationOne": "one", "TestAnnotationTwo": "two"}), + resource.TestCheckResourceAttr("kubernetes_persistent_volume.test", "metadata.0.labels.%", "3"), + resource.TestCheckResourceAttr("kubernetes_persistent_volume.test", "metadata.0.labels.TestLabelOne", "one"), + resource.TestCheckResourceAttr("kubernetes_persistent_volume.test", "metadata.0.labels.TestLabelTwo", "two"), + resource.TestCheckResourceAttr("kubernetes_persistent_volume.test", "metadata.0.labels.TestLabelThree", "three"), + testAccCheckMetaLabels(&conf.ObjectMeta, map[string]string{"TestLabelOne": "one", "TestLabelTwo": "two", "TestLabelThree": "three"}), + resource.TestCheckResourceAttr("kubernetes_persistent_volume.test", "metadata.0.name", name), + resource.TestCheckResourceAttrSet("kubernetes_persistent_volume.test", "metadata.0.generation"), + resource.TestCheckResourceAttrSet("kubernetes_persistent_volume.test", "metadata.0.resource_version"), + resource.TestCheckResourceAttrSet("kubernetes_persistent_volume.test", "metadata.0.self_link"), + resource.TestCheckResourceAttrSet("kubernetes_persistent_volume.test", "metadata.0.uid"), + resource.TestCheckResourceAttr("kubernetes_persistent_volume.test", "spec.0.capacity.%", "1"), + resource.TestCheckResourceAttr("kubernetes_persistent_volume.test", "spec.0.capacity.storage", "123Gi"), + resource.TestCheckResourceAttr("kubernetes_persistent_volume.test", "spec.0.access_modes.#", "1"), + resource.TestCheckResourceAttr("kubernetes_persistent_volume.test", "spec.0.access_modes.1254135962", "ReadWriteMany"), + resource.TestCheckResourceAttr("kubernetes_persistent_volume.test", "spec.0.persistent_volume_source.0.gce_persistent_disk.#", "1"), + resource.TestCheckResourceAttr("kubernetes_persistent_volume.test", "spec.0.persistent_volume_source.0.gce_persistent_disk.0.pd_name", "test123"), + ), + }, + { + Config: testAccKubernetesPersistentVolumeConfig_modified(name), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckKubernetesPersistentVolumeExists("kubernetes_persistent_volume.test", &conf), + resource.TestCheckResourceAttr("kubernetes_persistent_volume.test", "metadata.0.annotations.%", "2"), + resource.TestCheckResourceAttr("kubernetes_persistent_volume.test", "metadata.0.annotations.TestAnnotationOne", "one"), + resource.TestCheckResourceAttr("kubernetes_persistent_volume.test", "metadata.0.annotations.TestAnnotationTwo", "two"), + testAccCheckMetaAnnotations(&conf.ObjectMeta, map[string]string{"TestAnnotationOne": "one", "TestAnnotationTwo": "two"}), + resource.TestCheckResourceAttr("kubernetes_persistent_volume.test", "metadata.0.labels.%", "3"), + resource.TestCheckResourceAttr("kubernetes_persistent_volume.test", "metadata.0.labels.TestLabelOne", "one"), + resource.TestCheckResourceAttr("kubernetes_persistent_volume.test", "metadata.0.labels.TestLabelTwo", "two"), + resource.TestCheckResourceAttr("kubernetes_persistent_volume.test", "metadata.0.labels.TestLabelThree", "three"), + testAccCheckMetaLabels(&conf.ObjectMeta, map[string]string{"TestLabelOne": "one", "TestLabelTwo": "two", "TestLabelThree": "three"}), + resource.TestCheckResourceAttr("kubernetes_persistent_volume.test", "metadata.0.name", name), + resource.TestCheckResourceAttrSet("kubernetes_persistent_volume.test", "metadata.0.generation"), + resource.TestCheckResourceAttrSet("kubernetes_persistent_volume.test", "metadata.0.resource_version"), + resource.TestCheckResourceAttrSet("kubernetes_persistent_volume.test", "metadata.0.self_link"), + resource.TestCheckResourceAttrSet("kubernetes_persistent_volume.test", "metadata.0.uid"), + resource.TestCheckResourceAttr("kubernetes_persistent_volume.test", "spec.0.capacity.%", "1"), + resource.TestCheckResourceAttr("kubernetes_persistent_volume.test", "spec.0.capacity.storage", "42Mi"), + resource.TestCheckResourceAttr("kubernetes_persistent_volume.test", "spec.0.access_modes.#", "2"), + resource.TestCheckResourceAttr("kubernetes_persistent_volume.test", "spec.0.access_modes.1245328686", "ReadWriteOnce"), + resource.TestCheckResourceAttr("kubernetes_persistent_volume.test", "spec.0.access_modes.1254135962", "ReadWriteMany"), + resource.TestCheckResourceAttr("kubernetes_persistent_volume.test", "spec.0.persistent_volume_source.0.gce_persistent_disk.#", "1"), + resource.TestCheckResourceAttr("kubernetes_persistent_volume.test", "spec.0.persistent_volume_source.0.gce_persistent_disk.0.fs_type", "ntfs"), + resource.TestCheckResourceAttr("kubernetes_persistent_volume.test", "spec.0.persistent_volume_source.0.gce_persistent_disk.0.pd_name", "test123"), + resource.TestCheckResourceAttr("kubernetes_persistent_volume.test", "spec.0.persistent_volume_source.0.gce_persistent_disk.0.read_only", "true"), + ), + }, + }, + }) +} + +func TestAccKubernetesPersistentVolume_importBasic(t *testing.T) { + resourceName := "kubernetes_persistent_volume.test" + randString := acctest.RandStringFromCharSet(10, acctest.CharSetAlphaNum) + name := fmt.Sprintf("tf-acc-test-import-%s", randString) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckKubernetesPersistentVolumeDestroy, + Steps: []resource.TestStep{ + { + Config: testAccKubernetesPersistentVolumeConfig_basic(name), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func TestAccKubernetesPersistentVolume_volumeSource(t *testing.T) { + var conf api.PersistentVolume + randString := acctest.RandStringFromCharSet(10, acctest.CharSetAlphaNum) + name := fmt.Sprintf("tf-acc-test-%s", randString) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + IDRefreshName: "kubernetes_persistent_volume.test", + Providers: testAccProviders, + CheckDestroy: testAccCheckKubernetesPersistentVolumeDestroy, + Steps: []resource.TestStep{ + { + Config: testAccKubernetesPersistentVolumeConfig_volumeSource(name), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckKubernetesPersistentVolumeExists("kubernetes_persistent_volume.test", &conf), + resource.TestCheckResourceAttr("kubernetes_persistent_volume.test", "metadata.0.annotations.%", "0"), + testAccCheckMetaAnnotations(&conf.ObjectMeta, map[string]string{}), + resource.TestCheckResourceAttr("kubernetes_persistent_volume.test", "metadata.0.labels.%", "0"), + testAccCheckMetaLabels(&conf.ObjectMeta, map[string]string{}), + resource.TestCheckResourceAttr("kubernetes_persistent_volume.test", "metadata.0.name", name), + resource.TestCheckResourceAttrSet("kubernetes_persistent_volume.test", "metadata.0.generation"), + resource.TestCheckResourceAttrSet("kubernetes_persistent_volume.test", "metadata.0.resource_version"), + resource.TestCheckResourceAttrSet("kubernetes_persistent_volume.test", "metadata.0.self_link"), + resource.TestCheckResourceAttrSet("kubernetes_persistent_volume.test", "metadata.0.uid"), + resource.TestCheckResourceAttr("kubernetes_persistent_volume.test", "spec.0.capacity.%", "1"), + resource.TestCheckResourceAttr("kubernetes_persistent_volume.test", "spec.0.capacity.storage", "123Gi"), + resource.TestCheckResourceAttr("kubernetes_persistent_volume.test", "spec.0.access_modes.#", "1"), + resource.TestCheckResourceAttr("kubernetes_persistent_volume.test", "spec.0.access_modes.1254135962", "ReadWriteMany"), + resource.TestCheckResourceAttr("kubernetes_persistent_volume.test", "spec.0.persistent_volume_source.0.aws_elastic_block_store.#", "1"), + resource.TestCheckResourceAttr("kubernetes_persistent_volume.test", "spec.0.persistent_volume_source.0.aws_elastic_block_store.0.volume_id", "vol-12345678"), + resource.TestCheckResourceAttr("kubernetes_persistent_volume.test", "spec.0.persistent_volume_source.0.aws_elastic_block_store.0.fs_type", "ntfs"), + resource.TestCheckResourceAttr("kubernetes_persistent_volume.test", "spec.0.persistent_volume_source.0.aws_elastic_block_store.0.partition", "1"), + resource.TestCheckResourceAttr("kubernetes_persistent_volume.test", "spec.0.persistent_volume_source.0.aws_elastic_block_store.0.read_only", "true"), + ), + }, + { + Config: testAccKubernetesPersistentVolumeConfig_volumeSource_modified(name), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckKubernetesPersistentVolumeExists("kubernetes_persistent_volume.test", &conf), + resource.TestCheckResourceAttr("kubernetes_persistent_volume.test", "metadata.0.annotations.%", "0"), + testAccCheckMetaAnnotations(&conf.ObjectMeta, map[string]string{}), + resource.TestCheckResourceAttr("kubernetes_persistent_volume.test", "metadata.0.labels.%", "0"), + testAccCheckMetaLabels(&conf.ObjectMeta, map[string]string{}), + resource.TestCheckResourceAttr("kubernetes_persistent_volume.test", "metadata.0.name", name), + resource.TestCheckResourceAttrSet("kubernetes_persistent_volume.test", "metadata.0.generation"), + resource.TestCheckResourceAttrSet("kubernetes_persistent_volume.test", "metadata.0.resource_version"), + resource.TestCheckResourceAttrSet("kubernetes_persistent_volume.test", "metadata.0.self_link"), + resource.TestCheckResourceAttrSet("kubernetes_persistent_volume.test", "metadata.0.uid"), + resource.TestCheckResourceAttr("kubernetes_persistent_volume.test", "spec.0.capacity.%", "1"), + resource.TestCheckResourceAttr("kubernetes_persistent_volume.test", "spec.0.capacity.storage", "123Gi"), + resource.TestCheckResourceAttr("kubernetes_persistent_volume.test", "spec.0.access_modes.#", "1"), + resource.TestCheckResourceAttr("kubernetes_persistent_volume.test", "spec.0.access_modes.1254135962", "ReadWriteMany"), + resource.TestCheckResourceAttr("kubernetes_persistent_volume.test", "spec.0.persistent_volume_source.0.host_path.#", "1"), + resource.TestCheckResourceAttr("kubernetes_persistent_volume.test", "spec.0.persistent_volume_source.0.host_path.0.path", "/custom/testing/path"), + ), + }, + }, + }) +} + +func TestAccKubernetesPersistentVolume_cephFsSecretRef(t *testing.T) { + var conf api.PersistentVolume + randString := acctest.RandStringFromCharSet(10, acctest.CharSetAlphaNum) + name := fmt.Sprintf("tf-acc-test-%s", randString) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + IDRefreshName: "kubernetes_persistent_volume.test", + Providers: testAccProviders, + CheckDestroy: testAccCheckKubernetesPersistentVolumeDestroy, + Steps: []resource.TestStep{ + { + Config: testAccKubernetesPersistentVolumeConfig_cephFsSecretRef(name), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckKubernetesPersistentVolumeExists("kubernetes_persistent_volume.test", &conf), + resource.TestCheckResourceAttr("kubernetes_persistent_volume.test", "metadata.0.annotations.%", "0"), + testAccCheckMetaAnnotations(&conf.ObjectMeta, map[string]string{}), + resource.TestCheckResourceAttr("kubernetes_persistent_volume.test", "metadata.0.labels.%", "0"), + testAccCheckMetaLabels(&conf.ObjectMeta, map[string]string{}), + resource.TestCheckResourceAttr("kubernetes_persistent_volume.test", "metadata.0.name", name), + resource.TestCheckResourceAttrSet("kubernetes_persistent_volume.test", "metadata.0.generation"), + resource.TestCheckResourceAttrSet("kubernetes_persistent_volume.test", "metadata.0.resource_version"), + resource.TestCheckResourceAttrSet("kubernetes_persistent_volume.test", "metadata.0.self_link"), + resource.TestCheckResourceAttrSet("kubernetes_persistent_volume.test", "metadata.0.uid"), + resource.TestCheckResourceAttr("kubernetes_persistent_volume.test", "spec.0.capacity.%", "1"), + resource.TestCheckResourceAttr("kubernetes_persistent_volume.test", "spec.0.capacity.storage", "2Gi"), + resource.TestCheckResourceAttr("kubernetes_persistent_volume.test", "spec.0.access_modes.#", "1"), + resource.TestCheckResourceAttr("kubernetes_persistent_volume.test", "spec.0.access_modes.1254135962", "ReadWriteMany"), + resource.TestCheckResourceAttr("kubernetes_persistent_volume.test", "spec.0.persistent_volume_source.0.ceph_fs.#", "1"), + resource.TestCheckResourceAttr("kubernetes_persistent_volume.test", "spec.0.persistent_volume_source.0.ceph_fs.0.monitors.#", "2"), + resource.TestCheckResourceAttr("kubernetes_persistent_volume.test", "spec.0.persistent_volume_source.0.ceph_fs.0.monitors.2848821021", "10.16.154.78:6789"), + resource.TestCheckResourceAttr("kubernetes_persistent_volume.test", "spec.0.persistent_volume_source.0.ceph_fs.0.monitors.4263435410", "10.16.154.82:6789"), + resource.TestCheckResourceAttr("kubernetes_persistent_volume.test", "spec.0.persistent_volume_source.0.ceph_fs.0.secret_ref.#", "1"), + resource.TestCheckResourceAttr("kubernetes_persistent_volume.test", "spec.0.persistent_volume_source.0.ceph_fs.0.secret_ref.0.name", "ceph-secret"), + ), + }, + }, + }) +} + +func testAccCheckKubernetesPersistentVolumeDestroy(s *terraform.State) error { + conn := testAccProvider.Meta().(*kubernetes.Clientset) + + for _, rs := range s.RootModule().Resources { + if rs.Type != "kubernetes_persistent_volume" { + continue + } + name := rs.Primary.ID + resp, err := conn.CoreV1().PersistentVolumes().Get(name) + if err == nil { + if resp.Name == rs.Primary.ID { + return fmt.Errorf("Persistent Volume still exists: %s", rs.Primary.ID) + } + } + } + + return nil +} + +func testAccCheckKubernetesPersistentVolumeExists(n string, obj *api.PersistentVolume) resource.TestCheckFunc { + return func(s *terraform.State) error { + rs, ok := s.RootModule().Resources[n] + if !ok { + return fmt.Errorf("Not found: %s", n) + } + + conn := testAccProvider.Meta().(*kubernetes.Clientset) + name := rs.Primary.ID + out, err := conn.CoreV1().PersistentVolumes().Get(name) + if err != nil { + return err + } + + *obj = *out + return nil + } +} + +func testAccKubernetesPersistentVolumeConfig_basic(name string) string { + return fmt.Sprintf(` +resource "kubernetes_persistent_volume" "test" { + metadata { + annotations { + TestAnnotationOne = "one" + TestAnnotationTwo = "two" + } + labels { + TestLabelOne = "one" + TestLabelTwo = "two" + TestLabelThree = "three" + } + name = "%s" + } + spec { + capacity { + storage = "123Gi" + } + access_modes = ["ReadWriteMany"] + persistent_volume_source { + gce_persistent_disk { + pd_name = "test123" + } + } + } +}`, name) +} + +func testAccKubernetesPersistentVolumeConfig_modified(name string) string { + return fmt.Sprintf(` +resource "kubernetes_persistent_volume" "test" { + metadata { + annotations { + TestAnnotationOne = "one" + TestAnnotationTwo = "two" + } + labels { + TestLabelOne = "one" + TestLabelTwo = "two" + TestLabelThree = "three" + } + name = "%s" + } + spec { + capacity { + storage = "42Mi" + } + access_modes = ["ReadWriteMany", "ReadWriteOnce"] + persistent_volume_source { + gce_persistent_disk { + fs_type = "ntfs" + pd_name = "test123" + read_only = true + } + } + } +}`, name) +} + +func testAccKubernetesPersistentVolumeConfig_volumeSource(name string) string { + return fmt.Sprintf(` +resource "kubernetes_persistent_volume" "test" { + metadata { + name = "%s" + } + spec { + capacity { + storage = "123Gi" + } + access_modes = ["ReadWriteMany"] + persistent_volume_source { + aws_elastic_block_store { + volume_id = "vol-12345678" + fs_type = "ntfs" + partition = 1 + read_only = true + } + } + } +}`, name) +} + +func testAccKubernetesPersistentVolumeConfig_volumeSource_modified(name string) string { + return fmt.Sprintf(` +resource "kubernetes_persistent_volume" "test" { + metadata { + name = "%s" + } + spec { + capacity { + storage = "123Gi" + } + access_modes = ["ReadWriteMany"] + persistent_volume_source { + host_path { + path = "/custom/testing/path" + } + } + } +}`, name) +} + +func testAccKubernetesPersistentVolumeConfig_cephFsSecretRef(name string) string { + return fmt.Sprintf(` +resource "kubernetes_persistent_volume" "test" { + metadata { + name = "%s" + } + spec { + capacity { + storage = "2Gi" + } + access_modes = ["ReadWriteMany"] + persistent_volume_source { + ceph_fs { + monitors = ["10.16.154.78:6789", "10.16.154.82:6789"] + secret_ref { + name = "ceph-secret" + } + } + } + } +}`, name) +} diff --git a/builtin/providers/kubernetes/resource_kubernetes_resource_quota.go b/builtin/providers/kubernetes/resource_kubernetes_resource_quota.go new file mode 100644 index 000000000..758cf8f4f --- /dev/null +++ b/builtin/providers/kubernetes/resource_kubernetes_resource_quota.go @@ -0,0 +1,211 @@ +package kubernetes + +import ( + "fmt" + "log" + "time" + + "github.com/hashicorp/terraform/helper/resource" + "github.com/hashicorp/terraform/helper/schema" + pkgApi "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/errors" + api "k8s.io/kubernetes/pkg/api/v1" + kubernetes "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" +) + +func resourceKubernetesResourceQuota() *schema.Resource { + return &schema.Resource{ + Create: resourceKubernetesResourceQuotaCreate, + Read: resourceKubernetesResourceQuotaRead, + Exists: resourceKubernetesResourceQuotaExists, + Update: resourceKubernetesResourceQuotaUpdate, + Delete: resourceKubernetesResourceQuotaDelete, + Importer: &schema.ResourceImporter{ + State: schema.ImportStatePassthrough, + }, + + Schema: map[string]*schema.Schema{ + "metadata": namespacedMetadataSchema("resource quota", true), + "spec": { + Type: schema.TypeList, + Description: "Spec defines the desired quota. http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#spec-and-status", + Optional: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "hard": { + Type: schema.TypeMap, + Description: "The set of desired hard limits for each named resource. More info: http://releases.k8s.io/HEAD/docs/design/admission_control_resource_quota.md#admissioncontrol-plugin-resourcequota", + Optional: true, + Elem: schema.TypeString, + ValidateFunc: validateResourceList, + }, + "scopes": { + Type: schema.TypeSet, + Description: "A collection of filters that must match each object tracked by a quota. If not specified, the quota matches all objects.", + Optional: true, + ForceNew: true, + Elem: &schema.Schema{Type: schema.TypeString}, + Set: schema.HashString, + }, + }, + }, + }, + }, + } +} + +func resourceKubernetesResourceQuotaCreate(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*kubernetes.Clientset) + + metadata := expandMetadata(d.Get("metadata").([]interface{})) + spec, err := expandResourceQuotaSpec(d.Get("spec").([]interface{})) + if err != nil { + return err + } + resQuota := api.ResourceQuota{ + ObjectMeta: metadata, + Spec: spec, + } + log.Printf("[INFO] Creating new resource quota: %#v", resQuota) + out, err := conn.CoreV1().ResourceQuotas(metadata.Namespace).Create(&resQuota) + if err != nil { + return fmt.Errorf("Failed to create resource quota: %s", err) + } + log.Printf("[INFO] Submitted new resource quota: %#v", out) + d.SetId(buildId(out.ObjectMeta)) + + err = resource.Retry(1*time.Minute, func() *resource.RetryError { + quota, err := conn.CoreV1().ResourceQuotas(out.Namespace).Get(out.Name) + if err != nil { + return resource.NonRetryableError(err) + } + if resourceListEquals(spec.Hard, quota.Status.Hard) { + return nil + } + err = fmt.Errorf("Quotas don't match after creation.\nExpected: %#v\nGiven: %#v", + spec.Hard, quota.Status.Hard) + return resource.RetryableError(err) + }) + if err != nil { + return err + } + + return resourceKubernetesResourceQuotaRead(d, meta) +} + +func resourceKubernetesResourceQuotaRead(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*kubernetes.Clientset) + + namespace, name := idParts(d.Id()) + log.Printf("[INFO] Reading resource quota %s", name) + resQuota, err := conn.CoreV1().ResourceQuotas(namespace).Get(name) + if err != nil { + log.Printf("[DEBUG] Received error: %#v", err) + return err + } + log.Printf("[INFO] Received resource quota: %#v", resQuota) + + // This is to work around K8S bug + // See https://github.com/kubernetes/kubernetes/issues/44539 + if resQuota.ObjectMeta.GenerateName == "" { + if v, ok := d.GetOk("metadata.0.generate_name"); ok { + resQuota.ObjectMeta.GenerateName = v.(string) + } + } + + err = d.Set("metadata", flattenMetadata(resQuota.ObjectMeta)) + if err != nil { + return err + } + err = d.Set("spec", flattenResourceQuotaSpec(resQuota.Spec)) + if err != nil { + return err + } + + return nil +} + +func resourceKubernetesResourceQuotaUpdate(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*kubernetes.Clientset) + + namespace, name := idParts(d.Id()) + + ops := patchMetadata("metadata.0.", "/metadata/", d) + var spec api.ResourceQuotaSpec + waitForChangedSpec := false + if d.HasChange("spec") { + var err error + spec, err = expandResourceQuotaSpec(d.Get("spec").([]interface{})) + if err != nil { + return err + } + ops = append(ops, &ReplaceOperation{ + Path: "/spec", + Value: spec, + }) + waitForChangedSpec = true + } + data, err := ops.MarshalJSON() + if err != nil { + return fmt.Errorf("Failed to marshal update operations: %s", err) + } + log.Printf("[INFO] Updating resource quota %q: %v", name, string(data)) + out, err := conn.CoreV1().ResourceQuotas(namespace).Patch(name, pkgApi.JSONPatchType, data) + if err != nil { + return fmt.Errorf("Failed to update resource quota: %s", err) + } + log.Printf("[INFO] Submitted updated resource quota: %#v", out) + d.SetId(buildId(out.ObjectMeta)) + + if waitForChangedSpec { + err = resource.Retry(1*time.Minute, func() *resource.RetryError { + quota, err := conn.CoreV1().ResourceQuotas(namespace).Get(name) + if err != nil { + return resource.NonRetryableError(err) + } + if resourceListEquals(spec.Hard, quota.Status.Hard) { + return nil + } + err = fmt.Errorf("Quotas don't match after update.\nExpected: %#v\nGiven: %#v", + spec.Hard, quota.Status.Hard) + return resource.RetryableError(err) + }) + if err != nil { + return err + } + } + + return resourceKubernetesResourceQuotaRead(d, meta) +} + +func resourceKubernetesResourceQuotaDelete(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*kubernetes.Clientset) + + namespace, name := idParts(d.Id()) + log.Printf("[INFO] Deleting resource quota: %#v", name) + err := conn.CoreV1().ResourceQuotas(namespace).Delete(name, &api.DeleteOptions{}) + if err != nil { + return err + } + + log.Printf("[INFO] Resource quota %s deleted", name) + + d.SetId("") + return nil +} + +func resourceKubernetesResourceQuotaExists(d *schema.ResourceData, meta interface{}) (bool, error) { + conn := meta.(*kubernetes.Clientset) + + namespace, name := idParts(d.Id()) + log.Printf("[INFO] Checking resource quota %s", name) + _, err := conn.CoreV1().ResourceQuotas(namespace).Get(name) + if err != nil { + if statusErr, ok := err.(*errors.StatusError); ok && statusErr.ErrStatus.Code == 404 { + return false, nil + } + log.Printf("[DEBUG] Received error: %#v", err) + } + return true, err +} diff --git a/builtin/providers/kubernetes/resource_kubernetes_resource_quota_test.go b/builtin/providers/kubernetes/resource_kubernetes_resource_quota_test.go new file mode 100644 index 000000000..5935f7ea5 --- /dev/null +++ b/builtin/providers/kubernetes/resource_kubernetes_resource_quota_test.go @@ -0,0 +1,352 @@ +package kubernetes + +import ( + "fmt" + "testing" + + "github.com/hashicorp/terraform/helper/acctest" + "github.com/hashicorp/terraform/helper/resource" + "github.com/hashicorp/terraform/terraform" + api "k8s.io/kubernetes/pkg/api/v1" + kubernetes "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" +) + +func TestAccKubernetesResourceQuota_basic(t *testing.T) { + var conf api.ResourceQuota + name := fmt.Sprintf("tf-acc-test-%s", acctest.RandString(10)) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + IDRefreshName: "kubernetes_resource_quota.test", + Providers: testAccProviders, + CheckDestroy: testAccCheckKubernetesResourceQuotaDestroy, + Steps: []resource.TestStep{ + { + Config: testAccKubernetesResourceQuotaConfig_basic(name), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckKubernetesResourceQuotaExists("kubernetes_resource_quota.test", &conf), + resource.TestCheckResourceAttr("kubernetes_resource_quota.test", "metadata.0.annotations.%", "1"), + resource.TestCheckResourceAttr("kubernetes_resource_quota.test", "metadata.0.annotations.TestAnnotationOne", "one"), + testAccCheckMetaAnnotations(&conf.ObjectMeta, map[string]string{"TestAnnotationOne": "one"}), + resource.TestCheckResourceAttr("kubernetes_resource_quota.test", "metadata.0.labels.%", "3"), + resource.TestCheckResourceAttr("kubernetes_resource_quota.test", "metadata.0.labels.TestLabelOne", "one"), + resource.TestCheckResourceAttr("kubernetes_resource_quota.test", "metadata.0.labels.TestLabelThree", "three"), + resource.TestCheckResourceAttr("kubernetes_resource_quota.test", "metadata.0.labels.TestLabelFour", "four"), + testAccCheckMetaLabels(&conf.ObjectMeta, map[string]string{"TestLabelOne": "one", "TestLabelThree": "three", "TestLabelFour": "four"}), + resource.TestCheckResourceAttr("kubernetes_resource_quota.test", "metadata.0.name", name), + resource.TestCheckResourceAttrSet("kubernetes_resource_quota.test", "metadata.0.generation"), + resource.TestCheckResourceAttrSet("kubernetes_resource_quota.test", "metadata.0.resource_version"), + resource.TestCheckResourceAttrSet("kubernetes_resource_quota.test", "metadata.0.self_link"), + resource.TestCheckResourceAttrSet("kubernetes_resource_quota.test", "metadata.0.uid"), + resource.TestCheckResourceAttr("kubernetes_resource_quota.test", "spec.0.hard.%", "3"), + resource.TestCheckResourceAttr("kubernetes_resource_quota.test", "spec.0.hard.limits.cpu", "2"), + resource.TestCheckResourceAttr("kubernetes_resource_quota.test", "spec.0.hard.limits.memory", "2Gi"), + resource.TestCheckResourceAttr("kubernetes_resource_quota.test", "spec.0.hard.pods", "4"), + ), + }, + { + Config: testAccKubernetesResourceQuotaConfig_metaModified(name), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckKubernetesResourceQuotaExists("kubernetes_resource_quota.test", &conf), + resource.TestCheckResourceAttr("kubernetes_resource_quota.test", "metadata.0.annotations.%", "2"), + resource.TestCheckResourceAttr("kubernetes_resource_quota.test", "metadata.0.annotations.TestAnnotationOne", "one"), + resource.TestCheckResourceAttr("kubernetes_resource_quota.test", "metadata.0.annotations.TestAnnotationTwo", "two"), + testAccCheckMetaAnnotations(&conf.ObjectMeta, map[string]string{"TestAnnotationOne": "one", "TestAnnotationTwo": "two"}), + resource.TestCheckResourceAttr("kubernetes_resource_quota.test", "metadata.0.labels.%", "3"), + resource.TestCheckResourceAttr("kubernetes_resource_quota.test", "metadata.0.labels.TestLabelOne", "one"), + resource.TestCheckResourceAttr("kubernetes_resource_quota.test", "metadata.0.labels.TestLabelTwo", "two"), + resource.TestCheckResourceAttr("kubernetes_resource_quota.test", "metadata.0.labels.TestLabelThree", "three"), + testAccCheckMetaLabels(&conf.ObjectMeta, map[string]string{"TestLabelOne": "one", "TestLabelTwo": "two", "TestLabelThree": "three"}), + resource.TestCheckResourceAttr("kubernetes_resource_quota.test", "metadata.0.name", name), + resource.TestCheckResourceAttrSet("kubernetes_resource_quota.test", "metadata.0.generation"), + resource.TestCheckResourceAttrSet("kubernetes_resource_quota.test", "metadata.0.resource_version"), + resource.TestCheckResourceAttrSet("kubernetes_resource_quota.test", "metadata.0.self_link"), + resource.TestCheckResourceAttrSet("kubernetes_resource_quota.test", "metadata.0.uid"), + resource.TestCheckResourceAttr("kubernetes_resource_quota.test", "spec.0.hard.%", "3"), + resource.TestCheckResourceAttr("kubernetes_resource_quota.test", "spec.0.hard.limits.cpu", "2"), + resource.TestCheckResourceAttr("kubernetes_resource_quota.test", "spec.0.hard.limits.memory", "2Gi"), + resource.TestCheckResourceAttr("kubernetes_resource_quota.test", "spec.0.hard.pods", "4"), + ), + }, + { + Config: testAccKubernetesResourceQuotaConfig_specModified(name), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckKubernetesResourceQuotaExists("kubernetes_resource_quota.test", &conf), + resource.TestCheckResourceAttr("kubernetes_resource_quota.test", "metadata.0.annotations.%", "0"), + testAccCheckMetaAnnotations(&conf.ObjectMeta, map[string]string{}), + resource.TestCheckResourceAttr("kubernetes_resource_quota.test", "metadata.0.labels.%", "0"), + testAccCheckMetaLabels(&conf.ObjectMeta, map[string]string{}), + resource.TestCheckResourceAttr("kubernetes_resource_quota.test", "metadata.0.name", name), + resource.TestCheckResourceAttrSet("kubernetes_resource_quota.test", "metadata.0.generation"), + resource.TestCheckResourceAttrSet("kubernetes_resource_quota.test", "metadata.0.resource_version"), + resource.TestCheckResourceAttrSet("kubernetes_resource_quota.test", "metadata.0.self_link"), + resource.TestCheckResourceAttrSet("kubernetes_resource_quota.test", "metadata.0.uid"), + resource.TestCheckResourceAttr("kubernetes_resource_quota.test", "spec.0.hard.%", "4"), + resource.TestCheckResourceAttr("kubernetes_resource_quota.test", "spec.0.hard.limits.cpu", "4"), + resource.TestCheckResourceAttr("kubernetes_resource_quota.test", "spec.0.hard.requests.cpu", "1"), + resource.TestCheckResourceAttr("kubernetes_resource_quota.test", "spec.0.hard.limits.memory", "4Gi"), + resource.TestCheckResourceAttr("kubernetes_resource_quota.test", "spec.0.hard.pods", "10"), + ), + }, + }, + }) +} + +func TestAccKubernetesResourceQuota_generatedName(t *testing.T) { + var conf api.ResourceQuota + prefix := "tf-acc-test-" + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + IDRefreshName: "kubernetes_resource_quota.test", + Providers: testAccProviders, + CheckDestroy: testAccCheckKubernetesResourceQuotaDestroy, + Steps: []resource.TestStep{ + { + Config: testAccKubernetesResourceQuotaConfig_generatedName(prefix), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckKubernetesResourceQuotaExists("kubernetes_resource_quota.test", &conf), + resource.TestCheckResourceAttr("kubernetes_resource_quota.test", "metadata.0.annotations.%", "0"), + testAccCheckMetaAnnotations(&conf.ObjectMeta, map[string]string{}), + resource.TestCheckResourceAttr("kubernetes_resource_quota.test", "metadata.0.labels.%", "0"), + testAccCheckMetaLabels(&conf.ObjectMeta, map[string]string{}), + resource.TestCheckResourceAttr("kubernetes_resource_quota.test", "metadata.0.generate_name", prefix), + resource.TestCheckResourceAttrSet("kubernetes_resource_quota.test", "metadata.0.generation"), + resource.TestCheckResourceAttrSet("kubernetes_resource_quota.test", "metadata.0.resource_version"), + resource.TestCheckResourceAttrSet("kubernetes_resource_quota.test", "metadata.0.self_link"), + resource.TestCheckResourceAttrSet("kubernetes_resource_quota.test", "metadata.0.uid"), + resource.TestCheckResourceAttr("kubernetes_resource_quota.test", "spec.0.hard.%", "1"), + resource.TestCheckResourceAttr("kubernetes_resource_quota.test", "spec.0.hard.pods", "10"), + resource.TestCheckResourceAttr("kubernetes_resource_quota.test", "spec.0.scopes.#", "0"), + ), + }, + }, + }) +} + +func TestAccKubernetesResourceQuota_withScopes(t *testing.T) { + var conf api.ResourceQuota + name := fmt.Sprintf("tf-acc-test-%s", acctest.RandString(10)) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + IDRefreshName: "kubernetes_resource_quota.test", + Providers: testAccProviders, + CheckDestroy: testAccCheckKubernetesResourceQuotaDestroy, + Steps: []resource.TestStep{ + { + Config: testAccKubernetesResourceQuotaConfig_withScopes(name), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckKubernetesResourceQuotaExists("kubernetes_resource_quota.test", &conf), + resource.TestCheckResourceAttr("kubernetes_resource_quota.test", "metadata.0.annotations.%", "0"), + testAccCheckMetaAnnotations(&conf.ObjectMeta, map[string]string{}), + resource.TestCheckResourceAttr("kubernetes_resource_quota.test", "metadata.0.labels.%", "0"), + testAccCheckMetaLabels(&conf.ObjectMeta, map[string]string{}), + resource.TestCheckResourceAttr("kubernetes_resource_quota.test", "metadata.0.name", name), + resource.TestCheckResourceAttrSet("kubernetes_resource_quota.test", "metadata.0.generation"), + resource.TestCheckResourceAttrSet("kubernetes_resource_quota.test", "metadata.0.resource_version"), + resource.TestCheckResourceAttrSet("kubernetes_resource_quota.test", "metadata.0.self_link"), + resource.TestCheckResourceAttrSet("kubernetes_resource_quota.test", "metadata.0.uid"), + resource.TestCheckResourceAttr("kubernetes_resource_quota.test", "spec.0.hard.%", "1"), + resource.TestCheckResourceAttr("kubernetes_resource_quota.test", "spec.0.hard.pods", "10"), + resource.TestCheckResourceAttr("kubernetes_resource_quota.test", "spec.0.scopes.#", "1"), + resource.TestCheckResourceAttr("kubernetes_resource_quota.test", "spec.0.scopes.193563370", "BestEffort"), + ), + }, + { + Config: testAccKubernetesResourceQuotaConfig_withScopesModified(name), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckKubernetesResourceQuotaExists("kubernetes_resource_quota.test", &conf), + resource.TestCheckResourceAttr("kubernetes_resource_quota.test", "metadata.0.annotations.%", "0"), + testAccCheckMetaAnnotations(&conf.ObjectMeta, map[string]string{}), + resource.TestCheckResourceAttr("kubernetes_resource_quota.test", "metadata.0.labels.%", "0"), + testAccCheckMetaLabels(&conf.ObjectMeta, map[string]string{}), + resource.TestCheckResourceAttr("kubernetes_resource_quota.test", "metadata.0.name", name), + resource.TestCheckResourceAttrSet("kubernetes_resource_quota.test", "metadata.0.generation"), + resource.TestCheckResourceAttrSet("kubernetes_resource_quota.test", "metadata.0.resource_version"), + resource.TestCheckResourceAttrSet("kubernetes_resource_quota.test", "metadata.0.self_link"), + resource.TestCheckResourceAttrSet("kubernetes_resource_quota.test", "metadata.0.uid"), + resource.TestCheckResourceAttr("kubernetes_resource_quota.test", "spec.0.hard.%", "1"), + resource.TestCheckResourceAttr("kubernetes_resource_quota.test", "spec.0.hard.pods", "10"), + resource.TestCheckResourceAttr("kubernetes_resource_quota.test", "spec.0.scopes.#", "1"), + resource.TestCheckResourceAttr("kubernetes_resource_quota.test", "spec.0.scopes.3022121741", "NotBestEffort"), + ), + }, + }, + }) +} + +func TestAccKubernetesResourceQuota_importBasic(t *testing.T) { + resourceName := "kubernetes_resource_quota.test" + name := fmt.Sprintf("tf-acc-test-%s", acctest.RandString(10)) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckKubernetesResourceQuotaDestroy, + Steps: []resource.TestStep{ + { + Config: testAccKubernetesResourceQuotaConfig_basic(name), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func testAccCheckKubernetesResourceQuotaDestroy(s *terraform.State) error { + conn := testAccProvider.Meta().(*kubernetes.Clientset) + + for _, rs := range s.RootModule().Resources { + if rs.Type != "kubernetes_resource_quota" { + continue + } + namespace, name := idParts(rs.Primary.ID) + resp, err := conn.CoreV1().ResourceQuotas(namespace).Get(name) + if err == nil { + if resp.Namespace == namespace && resp.Name == name { + return fmt.Errorf("Resource Quota still exists: %s", rs.Primary.ID) + } + } + } + + return nil +} + +func testAccCheckKubernetesResourceQuotaExists(n string, obj *api.ResourceQuota) resource.TestCheckFunc { + return func(s *terraform.State) error { + rs, ok := s.RootModule().Resources[n] + if !ok { + return fmt.Errorf("Not found: %s", n) + } + + conn := testAccProvider.Meta().(*kubernetes.Clientset) + namespace, name := idParts(rs.Primary.ID) + out, err := conn.CoreV1().ResourceQuotas(namespace).Get(name) + if err != nil { + return err + } + + *obj = *out + return nil + } +} + +func testAccKubernetesResourceQuotaConfig_basic(name string) string { + return fmt.Sprintf(` +resource "kubernetes_resource_quota" "test" { + metadata { + annotations { + TestAnnotationOne = "one" + } + labels { + TestLabelOne = "one" + TestLabelThree = "three" + TestLabelFour = "four" + } + name = "%s" + } + spec { + hard { + "limits.cpu" = 2 + "limits.memory" = "2Gi" + pods = 4 + } + } +} +`, name) +} + +func testAccKubernetesResourceQuotaConfig_metaModified(name string) string { + return fmt.Sprintf(` +resource "kubernetes_resource_quota" "test" { + metadata { + annotations { + TestAnnotationOne = "one" + TestAnnotationTwo = "two" + } + labels { + TestLabelOne = "one" + TestLabelTwo = "two" + TestLabelThree = "three" + } + name = "%s" + } + spec { + hard { + "limits.cpu" = 2 + "limits.memory" = "2Gi" + pods = 4 + } + } +} +`, name) +} + +func testAccKubernetesResourceQuotaConfig_specModified(name string) string { + return fmt.Sprintf(` +resource "kubernetes_resource_quota" "test" { + metadata { + name = "%s" + } + spec { + hard { + "limits.cpu" = 4 + "requests.cpu" = 1 + "limits.memory" = "4Gi" + pods = 10 + } + } +} +`, name) +} + +func testAccKubernetesResourceQuotaConfig_generatedName(prefix string) string { + return fmt.Sprintf(` +resource "kubernetes_resource_quota" "test" { + metadata { + generate_name = "%s" + } + spec { + hard { + pods = 10 + } + } +} +`, prefix) +} + +func testAccKubernetesResourceQuotaConfig_withScopes(name string) string { + return fmt.Sprintf(` +resource "kubernetes_resource_quota" "test" { + metadata { + name = "%s" + } + spec { + hard { + pods = 10 + } + scopes = ["BestEffort"] + } +} +`, name) +} + +func testAccKubernetesResourceQuotaConfig_withScopesModified(name string) string { + return fmt.Sprintf(` +resource "kubernetes_resource_quota" "test" { + metadata { + name = "%s" + } + spec { + hard { + pods = 10 + } + scopes = ["NotBestEffort"] + } +} +`, name) +} diff --git a/builtin/providers/kubernetes/resource_kubernetes_secret.go b/builtin/providers/kubernetes/resource_kubernetes_secret.go new file mode 100644 index 000000000..0fe9a71ba --- /dev/null +++ b/builtin/providers/kubernetes/resource_kubernetes_secret.go @@ -0,0 +1,159 @@ +package kubernetes + +import ( + "log" + + "fmt" + "github.com/hashicorp/terraform/helper/schema" + pkgApi "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/errors" + api "k8s.io/kubernetes/pkg/api/v1" + kubernetes "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" +) + +func resourceKubernetesSecret() *schema.Resource { + return &schema.Resource{ + Create: resourceKubernetesSecretCreate, + Read: resourceKubernetesSecretRead, + Exists: resourceKubernetesSecretExists, + Update: resourceKubernetesSecretUpdate, + Delete: resourceKubernetesSecretDelete, + Importer: &schema.ResourceImporter{ + State: schema.ImportStatePassthrough, + }, + + Schema: map[string]*schema.Schema{ + "metadata": namespacedMetadataSchema("secret", true), + "data": { + Type: schema.TypeMap, + Description: "A map of the secret data.", + Optional: true, + Sensitive: true, + }, + "type": { + Type: schema.TypeString, + Description: "Type of secret", + Default: "Opaque", + Optional: true, + ForceNew: true, + }, + }, + } +} + +func resourceKubernetesSecretCreate(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*kubernetes.Clientset) + + metadata := expandMetadata(d.Get("metadata").([]interface{})) + secret := api.Secret{ + ObjectMeta: metadata, + StringData: expandStringMap(d.Get("data").(map[string]interface{})), + } + + if v, ok := d.GetOk("type"); ok { + secret.Type = api.SecretType(v.(string)) + } + + log.Printf("[INFO] Creating new secret: %#v", secret) + out, err := conn.CoreV1().Secrets(metadata.Namespace).Create(&secret) + if err != nil { + return err + } + + log.Printf("[INFO] Submitting new secret: %#v", out) + d.SetId(buildId(out.ObjectMeta)) + + return resourceKubernetesSecretRead(d, meta) +} + +func resourceKubernetesSecretRead(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*kubernetes.Clientset) + + namespace, name := idParts(d.Id()) + + log.Printf("[INFO] Reading secret %s", name) + secret, err := conn.CoreV1().Secrets(namespace).Get(name) + if err != nil { + return err + } + + log.Printf("[INFO] Received secret: %#v", secret) + err = d.Set("metadata", flattenMetadata(secret.ObjectMeta)) + if err != nil { + return err + } + + d.Set("data", byteMapToStringMap(secret.Data)) + d.Set("type", secret.Type) + + return nil +} + +func resourceKubernetesSecretUpdate(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*kubernetes.Clientset) + + namespace, name := idParts(d.Id()) + + ops := patchMetadata("metadata.0.", "/metadata/", d) + if d.HasChange("data") { + oldV, newV := d.GetChange("data") + + oldV = base64EncodeStringMap(oldV.(map[string]interface{})) + newV = base64EncodeStringMap(newV.(map[string]interface{})) + + diffOps := diffStringMap("/data/", oldV.(map[string]interface{}), newV.(map[string]interface{})) + + ops = append(ops, diffOps...) + } + + data, err := ops.MarshalJSON() + if err != nil { + return fmt.Errorf("Failed to marshal update operations: %s", err) + } + + log.Printf("[INFO] Updating secret %q: %v", name, data) + out, err := conn.CoreV1().Secrets(namespace).Patch(name, pkgApi.JSONPatchType, data) + if err != nil { + return fmt.Errorf("Failed to update secret: %s", err) + } + + log.Printf("[INFO] Submitting updated secret: %#v", out) + d.SetId(buildId(out.ObjectMeta)) + + return resourceKubernetesSecretRead(d, meta) +} + +func resourceKubernetesSecretDelete(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*kubernetes.Clientset) + + namespace, name := idParts(d.Id()) + + log.Printf("[INFO] Deleting secret: %q", name) + err := conn.CoreV1().Secrets(namespace).Delete(name, &api.DeleteOptions{}) + if err != nil { + return err + } + + log.Printf("[INFO] Secret %s deleted", name) + + d.SetId("") + + return nil +} + +func resourceKubernetesSecretExists(d *schema.ResourceData, meta interface{}) (bool, error) { + conn := meta.(*kubernetes.Clientset) + + namespace, name := idParts(d.Id()) + + log.Printf("[INFO] Checking secret %s", name) + _, err := conn.CoreV1().Secrets(namespace).Get(name) + if err != nil { + if statusErr, ok := err.(*errors.StatusError); ok && statusErr.ErrStatus.Code == 404 { + return false, nil + } + log.Printf("[DEBUG] Received error: %#v", err) + } + + return true, err +} diff --git a/builtin/providers/kubernetes/resource_kubernetes_secret_test.go b/builtin/providers/kubernetes/resource_kubernetes_secret_test.go new file mode 100644 index 000000000..0e9ef3123 --- /dev/null +++ b/builtin/providers/kubernetes/resource_kubernetes_secret_test.go @@ -0,0 +1,320 @@ +package kubernetes + +import ( + "fmt" + "reflect" + "regexp" + "testing" + + "github.com/hashicorp/terraform/helper/acctest" + "github.com/hashicorp/terraform/helper/resource" + "github.com/hashicorp/terraform/terraform" + api "k8s.io/kubernetes/pkg/api/v1" + kubernetes "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" +) + +func TestAccKubernetesSecret_basic(t *testing.T) { + var conf api.Secret + name := fmt.Sprintf("tf-acc-test-%s", acctest.RandStringFromCharSet(10, acctest.CharSetAlphaNum)) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + IDRefreshName: "kubernetes_secret.test", + Providers: testAccProviders, + CheckDestroy: testAccCheckKubernetesSecretDestroy, + Steps: []resource.TestStep{ + { + Config: testAccKubernetesSecretConfig_basic(name), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckKubernetesSecretExists("kubernetes_secret.test", &conf), + resource.TestCheckResourceAttr("kubernetes_secret.test", "metadata.0.annotations.%", "2"), + resource.TestCheckResourceAttr("kubernetes_secret.test", "metadata.0.annotations.TestAnnotationOne", "one"), + resource.TestCheckResourceAttr("kubernetes_secret.test", "metadata.0.annotations.TestAnnotationTwo", "two"), + testAccCheckMetaAnnotations(&conf.ObjectMeta, map[string]string{"TestAnnotationOne": "one", "TestAnnotationTwo": "two"}), + resource.TestCheckResourceAttr("kubernetes_secret.test", "metadata.0.labels.%", "3"), + resource.TestCheckResourceAttr("kubernetes_secret.test", "metadata.0.labels.TestLabelOne", "one"), + resource.TestCheckResourceAttr("kubernetes_secret.test", "metadata.0.labels.TestLabelTwo", "two"), + resource.TestCheckResourceAttr("kubernetes_secret.test", "metadata.0.labels.TestLabelThree", "three"), + testAccCheckMetaLabels(&conf.ObjectMeta, map[string]string{"TestLabelOne": "one", "TestLabelTwo": "two", "TestLabelThree": "three"}), + resource.TestCheckResourceAttr("kubernetes_secret.test", "metadata.0.name", name), + resource.TestCheckResourceAttrSet("kubernetes_secret.test", "metadata.0.generation"), + resource.TestCheckResourceAttrSet("kubernetes_secret.test", "metadata.0.resource_version"), + resource.TestCheckResourceAttrSet("kubernetes_secret.test", "metadata.0.self_link"), + resource.TestCheckResourceAttrSet("kubernetes_secret.test", "metadata.0.uid"), + resource.TestCheckResourceAttr("kubernetes_secret.test", "data.%", "2"), + resource.TestCheckResourceAttr("kubernetes_secret.test", "data.one", "first"), + resource.TestCheckResourceAttr("kubernetes_secret.test", "data.two", "second"), + resource.TestCheckResourceAttr("kubernetes_secret.test", "type", "Opaque"), + testAccCheckSecretData(&conf, map[string]string{"one": "first", "two": "second"}), + ), + }, + { + Config: testAccKubernetesSecretConfig_modified(name), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckKubernetesSecretExists("kubernetes_secret.test", &conf), + resource.TestCheckResourceAttr("kubernetes_secret.test", "metadata.0.annotations.%", "2"), + resource.TestCheckResourceAttr("kubernetes_secret.test", "metadata.0.annotations.TestAnnotationOne", "one"), + resource.TestCheckResourceAttr("kubernetes_secret.test", "metadata.0.annotations.Different", "1234"), + testAccCheckMetaAnnotations(&conf.ObjectMeta, map[string]string{"TestAnnotationOne": "one", "Different": "1234"}), + resource.TestCheckResourceAttr("kubernetes_secret.test", "metadata.0.labels.%", "2"), + resource.TestCheckResourceAttr("kubernetes_secret.test", "metadata.0.labels.TestLabelOne", "one"), + resource.TestCheckResourceAttr("kubernetes_secret.test", "metadata.0.labels.TestLabelThree", "three"), + testAccCheckMetaLabels(&conf.ObjectMeta, map[string]string{"TestLabelOne": "one", "TestLabelThree": "three"}), + resource.TestCheckResourceAttr("kubernetes_secret.test", "metadata.0.name", name), + resource.TestCheckResourceAttrSet("kubernetes_secret.test", "metadata.0.generation"), + resource.TestCheckResourceAttrSet("kubernetes_secret.test", "metadata.0.resource_version"), + resource.TestCheckResourceAttrSet("kubernetes_secret.test", "metadata.0.self_link"), + resource.TestCheckResourceAttrSet("kubernetes_secret.test", "metadata.0.uid"), + resource.TestCheckResourceAttr("kubernetes_secret.test", "data.%", "3"), + resource.TestCheckResourceAttr("kubernetes_secret.test", "data.one", "first"), + resource.TestCheckResourceAttr("kubernetes_secret.test", "data.two", "second"), + resource.TestCheckResourceAttr("kubernetes_secret.test", "data.nine", "ninth"), + resource.TestCheckResourceAttr("kubernetes_secret.test", "type", "Opaque"), + testAccCheckSecretData(&conf, map[string]string{"one": "first", "two": "second", "nine": "ninth"}), + ), + }, + { + Config: testAccKubernetesSecretConfig_noData(name), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckKubernetesSecretExists("kubernetes_secret.test", &conf), + resource.TestCheckResourceAttr("kubernetes_secret.test", "metadata.0.annotations.%", "0"), + testAccCheckMetaAnnotations(&conf.ObjectMeta, map[string]string{}), + resource.TestCheckResourceAttr("kubernetes_secret.test", "metadata.0.labels.%", "0"), + testAccCheckMetaLabels(&conf.ObjectMeta, map[string]string{}), + resource.TestCheckResourceAttr("kubernetes_secret.test", "metadata.0.name", name), + resource.TestCheckResourceAttrSet("kubernetes_secret.test", "metadata.0.generation"), + resource.TestCheckResourceAttrSet("kubernetes_secret.test", "metadata.0.resource_version"), + resource.TestCheckResourceAttrSet("kubernetes_secret.test", "metadata.0.self_link"), + resource.TestCheckResourceAttrSet("kubernetes_secret.test", "metadata.0.uid"), + resource.TestCheckResourceAttr("kubernetes_secret.test", "data.%", "0"), + testAccCheckSecretData(&conf, map[string]string{}), + ), + }, + { + Config: testAccKubernetesSecretConfig_typeSpecified(name), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckKubernetesSecretExists("kubernetes_secret.test", &conf), + resource.TestCheckResourceAttr("kubernetes_secret.test", "metadata.0.annotations.%", "0"), + testAccCheckMetaAnnotations(&conf.ObjectMeta, map[string]string{}), + resource.TestCheckResourceAttr("kubernetes_secret.test", "metadata.0.labels.%", "0"), + testAccCheckMetaLabels(&conf.ObjectMeta, map[string]string{}), + resource.TestCheckResourceAttr("kubernetes_secret.test", "metadata.0.name", name), + resource.TestCheckResourceAttrSet("kubernetes_secret.test", "metadata.0.generation"), + resource.TestCheckResourceAttrSet("kubernetes_secret.test", "metadata.0.resource_version"), + resource.TestCheckResourceAttrSet("kubernetes_secret.test", "metadata.0.self_link"), + resource.TestCheckResourceAttrSet("kubernetes_secret.test", "metadata.0.uid"), + resource.TestCheckResourceAttr("kubernetes_secret.test", "data.%", "2"), + resource.TestCheckResourceAttr("kubernetes_secret.test", "data.username", "admin"), + resource.TestCheckResourceAttr("kubernetes_secret.test", "data.password", "password"), + resource.TestCheckResourceAttr("kubernetes_secret.test", "type", "kubernetes.io/basic-auth"), + testAccCheckSecretData(&conf, map[string]string{"username": "admin", "password": "password"}), + ), + }, + }, + }) +} + +func TestAccKubernetesSecret_importBasic(t *testing.T) { + resourceName := "kubernetes_secret.test" + name := fmt.Sprintf("tf-acc-test-%s", acctest.RandStringFromCharSet(10, acctest.CharSetAlphaNum)) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckKubernetesSecretDestroy, + Steps: []resource.TestStep{ + { + Config: testAccKubernetesSecretConfig_basic(name), + }, + + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func TestAccKubernetesSecret_generatedName(t *testing.T) { + var conf api.Secret + prefix := "tf-acc-test-gen-" + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + IDRefreshName: "kubernetes_secret.test", + Providers: testAccProviders, + CheckDestroy: testAccCheckKubernetesSecretDestroy, + Steps: []resource.TestStep{ + { + Config: testAccKubernetesSecretConfig_generatedName(prefix), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckKubernetesSecretExists("kubernetes_secret.test", &conf), + resource.TestCheckResourceAttr("kubernetes_secret.test", "metadata.0.annotations.%", "0"), + testAccCheckMetaAnnotations(&conf.ObjectMeta, map[string]string{}), + resource.TestCheckResourceAttr("kubernetes_secret.test", "metadata.0.labels.%", "0"), + testAccCheckMetaLabels(&conf.ObjectMeta, map[string]string{}), + resource.TestCheckResourceAttr("kubernetes_secret.test", "metadata.0.generate_name", prefix), + resource.TestMatchResourceAttr("kubernetes_secret.test", "metadata.0.name", regexp.MustCompile("^"+prefix)), + resource.TestCheckResourceAttrSet("kubernetes_secret.test", "metadata.0.generation"), + resource.TestCheckResourceAttrSet("kubernetes_secret.test", "metadata.0.resource_version"), + resource.TestCheckResourceAttrSet("kubernetes_secret.test", "metadata.0.self_link"), + resource.TestCheckResourceAttrSet("kubernetes_secret.test", "metadata.0.uid"), + ), + }, + }, + }) +} + +func TestAccKubernetesSecret_importGeneratedName(t *testing.T) { + resourceName := "kubernetes_secret.test" + prefix := "tf-acc-test-gen-import-" + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckKubernetesSecretDestroy, + Steps: []resource.TestStep{ + { + Config: testAccKubernetesSecretConfig_generatedName(prefix), + }, + + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func testAccCheckSecretData(m *api.Secret, expected map[string]string) resource.TestCheckFunc { + return func(s *terraform.State) error { + if len(expected) == 0 && len(m.Data) == 0 { + return nil + } + if !reflect.DeepEqual(byteMapToStringMap(m.Data), expected) { + return fmt.Errorf("%s data don't match.\nExpected: %q\nGiven: %q", + m.Name, expected, m.Data) + } + return nil + } +} + +func testAccCheckKubernetesSecretDestroy(s *terraform.State) error { + conn := testAccProvider.Meta().(*kubernetes.Clientset) + + for _, rs := range s.RootModule().Resources { + if rs.Type != "kubernetes_secret" { + continue + } + namespace, name := idParts(rs.Primary.ID) + resp, err := conn.CoreV1().Secrets(namespace).Get(name) + if err == nil { + if resp.Name == rs.Primary.ID { + return fmt.Errorf("Secret still exists: %s", rs.Primary.ID) + } + } + } + + return nil +} + +func testAccCheckKubernetesSecretExists(n string, obj *api.Secret) resource.TestCheckFunc { + return func(s *terraform.State) error { + rs, ok := s.RootModule().Resources[n] + if !ok { + return fmt.Errorf("Not found: %s", n) + } + + conn := testAccProvider.Meta().(*kubernetes.Clientset) + namespace, name := idParts(rs.Primary.ID) + out, err := conn.CoreV1().Secrets(namespace).Get(name) + if err != nil { + return err + } + + *obj = *out + return nil + } +} + +func testAccKubernetesSecretConfig_basic(name string) string { + return fmt.Sprintf(` +resource "kubernetes_secret" "test" { + metadata { + annotations { + TestAnnotationOne = "one" + TestAnnotationTwo = "two" + } + labels { + TestLabelOne = "one" + TestLabelTwo = "two" + TestLabelThree = "three" + } + name = "%s" + } + data { + one = "first" + two = "second" + } +}`, name) +} + +func testAccKubernetesSecretConfig_modified(name string) string { + return fmt.Sprintf(` +resource "kubernetes_secret" "test" { + metadata { + annotations { + TestAnnotationOne = "one" + Different = "1234" + } + labels { + TestLabelOne = "one" + TestLabelThree = "three" + } + name = "%s" + } + data { + one = "first" + two = "second" + nine = "ninth" + } +}`, name) +} + +func testAccKubernetesSecretConfig_noData(name string) string { + return fmt.Sprintf(` +resource "kubernetes_secret" "test" { + metadata { + name = "%s" + } +}`, name) +} + +func testAccKubernetesSecretConfig_typeSpecified(name string) string { + return fmt.Sprintf(` +resource "kubernetes_secret" "test" { + metadata { + name = "%s" + } + data { + username = "admin" + password = "password" + } + type = "kubernetes.io/basic-auth" +}`, name) +} + +func testAccKubernetesSecretConfig_generatedName(prefix string) string { + return fmt.Sprintf(` +resource "kubernetes_secret" "test" { + metadata { + generate_name = "%s" + } + data { + one = "first" + two = "second" + } +}`, prefix) +} diff --git a/builtin/providers/kubernetes/schema_metadata.go b/builtin/providers/kubernetes/schema_metadata.go index 27644f83a..684acd6ae 100644 --- a/builtin/providers/kubernetes/schema_metadata.go +++ b/builtin/providers/kubernetes/schema_metadata.go @@ -26,13 +26,12 @@ func metadataFields(objectName string) map[string]*schema.Schema { ValidateFunc: validateLabels, }, "name": { - Type: schema.TypeString, - Description: fmt.Sprintf("Name of the %s, must be unique. Cannot be updated. More info: http://kubernetes.io/docs/user-guide/identifiers#names", objectName), - Optional: true, - ForceNew: true, - Computed: true, - ValidateFunc: validateName, - ConflictsWith: []string{"metadata.generate_name"}, + Type: schema.TypeString, + Description: fmt.Sprintf("Name of the %s, must be unique. Cannot be updated. More info: http://kubernetes.io/docs/user-guide/identifiers#names", objectName), + Optional: true, + ForceNew: true, + Computed: true, + ValidateFunc: validateName, }, "resource_version": { Type: schema.TypeString, @@ -52,15 +51,19 @@ func metadataFields(objectName string) map[string]*schema.Schema { } } -func metadataSchema(objectName string) *schema.Schema { +func metadataSchema(objectName string, generatableName bool) *schema.Schema { fields := metadataFields(objectName) - fields["generate_name"] = &schema.Schema{ - Type: schema.TypeString, - Description: "Prefix, used by the server, to generate a unique name ONLY IF the `name` field has not been provided. This value will also be combined with a unique suffix. Read more: https://github.com/kubernetes/community/blob/master/contributors/devel/api-conventions.md#idempotency", - Optional: true, - ForceNew: true, - ValidateFunc: validateGenerateName, - ConflictsWith: []string{"metadata.name"}, + + if generatableName { + fields["generate_name"] = &schema.Schema{ + Type: schema.TypeString, + Description: "Prefix, used by the server, to generate a unique name ONLY IF the `name` field has not been provided. This value will also be combined with a unique suffix. Read more: https://github.com/kubernetes/community/blob/master/contributors/devel/api-conventions.md#idempotency", + Optional: true, + ForceNew: true, + ValidateFunc: validateGenerateName, + ConflictsWith: []string{"metadata.name"}, + } + fields["name"].ConflictsWith = []string{"metadata.generate_name"} } return &schema.Schema{ @@ -92,6 +95,7 @@ func namespacedMetadataSchema(objectName string, generatableName bool) *schema.S ValidateFunc: validateGenerateName, ConflictsWith: []string{"metadata.name"}, } + fields["name"].ConflictsWith = []string{"metadata.generate_name"} } return &schema.Schema{ diff --git a/builtin/providers/kubernetes/schema_volume_source.go b/builtin/providers/kubernetes/schema_volume_source.go new file mode 100644 index 000000000..408a46850 --- /dev/null +++ b/builtin/providers/kubernetes/schema_volume_source.go @@ -0,0 +1,557 @@ +package kubernetes + +import ( + "github.com/hashicorp/terraform/helper/schema" +) + +func persistentVolumeSourceSchema() *schema.Resource { + volumeSources["host_path"] = &schema.Schema{ + Type: schema.TypeList, + Description: "Represents a directory on the host. Provisioned by a developer or tester. This is useful for single-node development and testing only! On-host storage is not supported in any way and WILL NOT WORK in a multi-node cluster. More info: http://kubernetes.io/docs/user-guide/volumes#hostpath", + Optional: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "path": { + Type: schema.TypeString, + Description: "Path of the directory on the host. More info: http://kubernetes.io/docs/user-guide/volumes#hostpath", + Optional: true, + }, + }, + }, + } + return &schema.Resource{ + Schema: volumeSources, + } +} + +// Common volume sources between Persistent Volumes and Pod Volumes +var volumeSources = map[string]*schema.Schema{ + "aws_elastic_block_store": { + Type: schema.TypeList, + Description: "Represents an AWS Disk resource that is attached to a kubelet's host machine and then exposed to the pod. More info: http://kubernetes.io/docs/user-guide/volumes#awselasticblockstore", + Optional: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "fs_type": { + Type: schema.TypeString, + Description: "Filesystem type of the volume that you want to mount. Tip: Ensure that the filesystem type is supported by the host operating system. Examples: \"ext4\", \"xfs\", \"ntfs\". Implicitly inferred to be \"ext4\" if unspecified. More info: http://kubernetes.io/docs/user-guide/volumes#awselasticblockstore", + Optional: true, + }, + "partition": { + Type: schema.TypeInt, + Description: "The partition in the volume that you want to mount. If omitted, the default is to mount by volume name. Examples: For volume /dev/sda1, you specify the partition as \"1\". Similarly, the volume partition for /dev/sda is \"0\" (or you can leave the property empty).", + Optional: true, + }, + "read_only": { + Type: schema.TypeBool, + Description: "Whether to set the read-only property in VolumeMounts to \"true\". If omitted, the default is \"false\". More info: http://kubernetes.io/docs/user-guide/volumes#awselasticblockstore", + Optional: true, + }, + "volume_id": { + Type: schema.TypeString, + Description: "Unique ID of the persistent disk resource in AWS (Amazon EBS volume). More info: http://kubernetes.io/docs/user-guide/volumes#awselasticblockstore", + Required: true, + }, + }, + }, + }, + "azure_disk": { + Type: schema.TypeList, + Description: "Represents an Azure Data Disk mount on the host and bind mount to the pod.", + Optional: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "caching_mode": { + Type: schema.TypeString, + Description: "Host Caching mode: None, Read Only, Read Write.", + Required: true, + }, + "data_disk_uri": { + Type: schema.TypeString, + Description: "The URI the data disk in the blob storage", + Required: true, + }, + "disk_name": { + Type: schema.TypeString, + Description: "The Name of the data disk in the blob storage", + Required: true, + }, + "fs_type": { + Type: schema.TypeString, + Description: "Filesystem type to mount. Must be a filesystem type supported by the host operating system. Ex. \"ext4\", \"xfs\", \"ntfs\". Implicitly inferred to be \"ext4\" if unspecified.", + Optional: true, + }, + "read_only": { + Type: schema.TypeBool, + Description: "Whether to force the read-only setting in VolumeMounts. Defaults to false (read/write).", + Optional: true, + Default: false, + }, + }, + }, + }, + "azure_file": { + Type: schema.TypeList, + Description: "Represents an Azure File Service mount on the host and bind mount to the pod.", + Optional: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "read_only": { + Type: schema.TypeBool, + Description: "Whether to force the read-only setting in VolumeMounts. Defaults to false (read/write).", + Optional: true, + }, + "secret_name": { + Type: schema.TypeString, + Description: "The name of secret that contains Azure Storage Account Name and Key", + Required: true, + }, + "share_name": { + Type: schema.TypeString, + Description: "Share Name", + Required: true, + }, + }, + }, + }, + "ceph_fs": { + Type: schema.TypeList, + Description: "Represents a Ceph FS mount on the host that shares a pod's lifetime", + Optional: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "monitors": { + Type: schema.TypeSet, + Description: "Monitors is a collection of Ceph monitors More info: http://releases.k8s.io/HEAD/examples/volumes/cephfs/README.md#how-to-use-it", + Required: true, + Elem: &schema.Schema{Type: schema.TypeString}, + Set: schema.HashString, + }, + "path": { + Type: schema.TypeString, + Description: "Used as the mounted root, rather than the full Ceph tree, default is /", + Optional: true, + }, + "read_only": { + Type: schema.TypeBool, + Description: "Whether to force the read-only setting in VolumeMounts. Defaults to `false` (read/write). More info: http://releases.k8s.io/HEAD/examples/volumes/cephfs/README.md#how-to-use-it", + Optional: true, + }, + "secret_file": { + Type: schema.TypeString, + Description: "The path to key ring for User, default is /etc/ceph/user.secret More info: http://releases.k8s.io/HEAD/examples/volumes/cephfs/README.md#how-to-use-it", + Optional: true, + }, + "secret_ref": { + Type: schema.TypeList, + Description: "Reference to the authentication secret for User, default is empty. More info: http://releases.k8s.io/HEAD/examples/volumes/cephfs/README.md#how-to-use-it", + Optional: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "name": { + Type: schema.TypeString, + Description: "Name of the referent. More info: http://kubernetes.io/docs/user-guide/identifiers#names", + Optional: true, + }, + }, + }, + }, + "user": { + Type: schema.TypeString, + Description: "User is the rados user name, default is admin. More info: http://releases.k8s.io/HEAD/examples/volumes/cephfs/README.md#how-to-use-it", + Optional: true, + }, + }, + }, + }, + "cinder": { + Type: schema.TypeList, + Description: "Represents a cinder volume attached and mounted on kubelets host machine. More info: http://releases.k8s.io/HEAD/examples/mysql-cinder-pd/README.md", + Optional: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "fs_type": { + Type: schema.TypeString, + Description: "Filesystem type to mount. Must be a filesystem type supported by the host operating system. Examples: \"ext4\", \"xfs\", \"ntfs\". Implicitly inferred to be \"ext4\" if unspecified. More info: http://releases.k8s.io/HEAD/examples/mysql-cinder-pd/README.md", + Optional: true, + }, + "read_only": { + Type: schema.TypeBool, + Description: "Whether to force the read-only setting in VolumeMounts. Defaults to false (read/write). More info: http://releases.k8s.io/HEAD/examples/mysql-cinder-pd/README.md", + Optional: true, + }, + "volume_id": { + Type: schema.TypeString, + Description: "Volume ID used to identify the volume in Cinder. More info: http://releases.k8s.io/HEAD/examples/mysql-cinder-pd/README.md", + Required: true, + }, + }, + }, + }, + "fc": { + Type: schema.TypeList, + Description: "Represents a Fibre Channel resource that is attached to a kubelet's host machine and then exposed to the pod.", + Optional: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "fs_type": { + Type: schema.TypeString, + Description: "Filesystem type to mount. Must be a filesystem type supported by the host operating system. Ex. \"ext4\", \"xfs\", \"ntfs\". Implicitly inferred to be \"ext4\" if unspecified.", + Optional: true, + }, + "lun": { + Type: schema.TypeInt, + Description: "FC target lun number", + Required: true, + }, + "read_only": { + Type: schema.TypeBool, + Description: "Whether to force the read-only setting in VolumeMounts. Defaults to false (read/write).", + Optional: true, + }, + "target_ww_ns": { + Type: schema.TypeSet, + Description: "FC target worldwide names (WWNs)", + Required: true, + Elem: &schema.Schema{Type: schema.TypeString}, + Set: schema.HashString, + }, + }, + }, + }, + "flex_volume": { + Type: schema.TypeList, + Description: "Represents a generic volume resource that is provisioned/attached using an exec based plugin. This is an alpha feature and may change in future.", + Optional: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "driver": { + Type: schema.TypeString, + Description: "Driver is the name of the driver to use for this volume.", + Required: true, + }, + "fs_type": { + Type: schema.TypeString, + Description: "Filesystem type to mount. Must be a filesystem type supported by the host operating system. Ex. \"ext4\", \"xfs\", \"ntfs\". The default filesystem depends on FlexVolume script.", + Optional: true, + }, + "options": { + Type: schema.TypeMap, + Description: "Extra command options if any.", + Optional: true, + }, + "read_only": { + Type: schema.TypeBool, + Description: "Whether to force the ReadOnly setting in VolumeMounts. Defaults to false (read/write).", + Optional: true, + }, + "secret_ref": { + Type: schema.TypeList, + Description: "Reference to the secret object containing sensitive information to pass to the plugin scripts. This may be empty if no secret object is specified. If the secret object contains more than one secret, all secrets are passed to the plugin scripts.", + Optional: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "name": { + Type: schema.TypeString, + Description: "Name of the referent. More info: http://kubernetes.io/docs/user-guide/identifiers#names", + Optional: true, + }, + }, + }, + }, + }, + }, + }, + "flocker": { + Type: schema.TypeList, + Description: "Represents a Flocker volume attached to a kubelet's host machine and exposed to the pod for its usage. This depends on the Flocker control service being running", + Optional: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "dataset_name": { + Type: schema.TypeString, + Description: "Name of the dataset stored as metadata -> name on the dataset for Flocker should be considered as deprecated", + Optional: true, + }, + "dataset_uuid": { + Type: schema.TypeString, + Description: "UUID of the dataset. This is unique identifier of a Flocker dataset", + Optional: true, + }, + }, + }, + }, + "gce_persistent_disk": { + Type: schema.TypeList, + Description: "Represents a GCE Disk resource that is attached to a kubelet's host machine and then exposed to the pod. Provisioned by an admin. More info: http://kubernetes.io/docs/user-guide/volumes#gcepersistentdisk", + Optional: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "fs_type": { + Type: schema.TypeString, + Description: "Filesystem type of the volume that you want to mount. Tip: Ensure that the filesystem type is supported by the host operating system. Examples: \"ext4\", \"xfs\", \"ntfs\". Implicitly inferred to be \"ext4\" if unspecified. More info: http://kubernetes.io/docs/user-guide/volumes#gcepersistentdisk", + Optional: true, + }, + "partition": { + Type: schema.TypeInt, + Description: "The partition in the volume that you want to mount. If omitted, the default is to mount by volume name. Examples: For volume /dev/sda1, you specify the partition as \"1\". Similarly, the volume partition for /dev/sda is \"0\" (or you can leave the property empty). More info: http://kubernetes.io/docs/user-guide/volumes#gcepersistentdisk", + Optional: true, + }, + "pd_name": { + Type: schema.TypeString, + Description: "Unique name of the PD resource in GCE. Used to identify the disk in GCE. More info: http://kubernetes.io/docs/user-guide/volumes#gcepersistentdisk", + Required: true, + }, + "read_only": { + Type: schema.TypeBool, + Description: "Whether to force the ReadOnly setting in VolumeMounts. Defaults to false. More info: http://kubernetes.io/docs/user-guide/volumes#gcepersistentdisk", + Optional: true, + }, + }, + }, + }, + "glusterfs": { + Type: schema.TypeList, + Description: "Represents a Glusterfs volume that is attached to a host and exposed to the pod. Provisioned by an admin. More info: http://releases.k8s.io/HEAD/examples/volumes/glusterfs/README.md", + Optional: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "endpoints_name": { + Type: schema.TypeString, + Description: "The endpoint name that details Glusterfs topology. More info: http://releases.k8s.io/HEAD/examples/volumes/glusterfs/README.md#create-a-pod", + Required: true, + }, + "path": { + Type: schema.TypeString, + Description: "The Glusterfs volume path. More info: http://releases.k8s.io/HEAD/examples/volumes/glusterfs/README.md#create-a-pod", + Required: true, + }, + "read_only": { + Type: schema.TypeBool, + Description: "Whether to force the Glusterfs volume to be mounted with read-only permissions. Defaults to false. More info: http://releases.k8s.io/HEAD/examples/volumes/glusterfs/README.md#create-a-pod", + Optional: true, + }, + }, + }, + }, + "iscsi": { + Type: schema.TypeList, + Description: "Represents an ISCSI Disk resource that is attached to a kubelet's host machine and then exposed to the pod. Provisioned by an admin.", + Optional: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "fs_type": { + Type: schema.TypeString, + Description: "Filesystem type of the volume that you want to mount. Tip: Ensure that the filesystem type is supported by the host operating system. Examples: \"ext4\", \"xfs\", \"ntfs\". Implicitly inferred to be \"ext4\" if unspecified. More info: http://kubernetes.io/docs/user-guide/volumes#iscsi", + Optional: true, + }, + "iqn": { + Type: schema.TypeString, + Description: "Target iSCSI Qualified Name.", + Required: true, + }, + "iscsi_interface": { + Type: schema.TypeString, + Description: "iSCSI interface name that uses an iSCSI transport. Defaults to 'default' (tcp).", + Optional: true, + Default: "default", + }, + "lun": { + Type: schema.TypeInt, + Description: "iSCSI target lun number.", + Optional: true, + }, + "read_only": { + Type: schema.TypeBool, + Description: "Whether to force the read-only setting in VolumeMounts. Defaults to false.", + Optional: true, + }, + "target_portal": { + Type: schema.TypeString, + Description: "iSCSI target portal. The portal is either an IP or ip_addr:port if the port is other than default (typically TCP ports 860 and 3260).", + Required: true, + }, + }, + }, + }, + "nfs": { + Type: schema.TypeList, + Description: "Represents an NFS mount on the host. Provisioned by an admin. More info: http://kubernetes.io/docs/user-guide/volumes#nfs", + Optional: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "path": { + Type: schema.TypeString, + Description: "Path that is exported by the NFS server. More info: http://kubernetes.io/docs/user-guide/volumes#nfs", + Required: true, + }, + "read_only": { + Type: schema.TypeBool, + Description: "Whether to force the NFS export to be mounted with read-only permissions. Defaults to false. More info: http://kubernetes.io/docs/user-guide/volumes#nfs", + Optional: true, + }, + "server": { + Type: schema.TypeString, + Description: "Server is the hostname or IP address of the NFS server. More info: http://kubernetes.io/docs/user-guide/volumes#nfs", + Required: true, + }, + }, + }, + }, + "photon_persistent_disk": { + Type: schema.TypeList, + Description: "Represents a PhotonController persistent disk attached and mounted on kubelets host machine", + Optional: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "fs_type": { + Type: schema.TypeString, + Description: "Filesystem type to mount. Must be a filesystem type supported by the host operating system. Ex. \"ext4\", \"xfs\", \"ntfs\". Implicitly inferred to be \"ext4\" if unspecified.", + Optional: true, + }, + "pd_id": { + Type: schema.TypeString, + Description: "ID that identifies Photon Controller persistent disk", + Required: true, + }, + }, + }, + }, + "quobyte": { + Type: schema.TypeList, + Description: "Quobyte represents a Quobyte mount on the host that shares a pod's lifetime", + Optional: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "group": { + Type: schema.TypeString, + Description: "Group to map volume access to Default is no group", + Optional: true, + }, + "read_only": { + Type: schema.TypeBool, + Description: "Whether to force the Quobyte volume to be mounted with read-only permissions. Defaults to false.", + Optional: true, + }, + "registry": { + Type: schema.TypeString, + Description: "Registry represents a single or multiple Quobyte Registry services specified as a string as host:port pair (multiple entries are separated with commas) which acts as the central registry for volumes", + Required: true, + }, + "user": { + Type: schema.TypeString, + Description: "User to map volume access to Defaults to serivceaccount user", + Optional: true, + }, + "volume": { + Type: schema.TypeString, + Description: "Volume is a string that references an already created Quobyte volume by name.", + Required: true, + }, + }, + }, + }, + "rbd": { + Type: schema.TypeList, + Description: "Represents a Rados Block Device mount on the host that shares a pod's lifetime. More info: http://releases.k8s.io/HEAD/examples/volumes/rbd/README.md", + Optional: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "ceph_monitors": { + Type: schema.TypeSet, + Description: "A collection of Ceph monitors. More info: http://releases.k8s.io/HEAD/examples/volumes/rbd/README.md#how-to-use-it", + Required: true, + Elem: &schema.Schema{Type: schema.TypeString}, + Set: schema.HashString, + }, + "fs_type": { + Type: schema.TypeString, + Description: "Filesystem type of the volume that you want to mount. Tip: Ensure that the filesystem type is supported by the host operating system. Examples: \"ext4\", \"xfs\", \"ntfs\". Implicitly inferred to be \"ext4\" if unspecified. More info: http://kubernetes.io/docs/user-guide/volumes#rbd", + Optional: true, + }, + "keyring": { + Type: schema.TypeString, + Description: "Keyring is the path to key ring for RBDUser. Default is /etc/ceph/keyring. More info: http://releases.k8s.io/HEAD/examples/volumes/rbd/README.md#how-to-use-it", + Optional: true, + Computed: true, + }, + "rados_user": { + Type: schema.TypeString, + Description: "The rados user name. Default is admin. More info: http://releases.k8s.io/HEAD/examples/volumes/rbd/README.md#how-to-use-it", + Optional: true, + Default: "admin", + }, + "rbd_image": { + Type: schema.TypeString, + Description: "The rados image name. More info: http://releases.k8s.io/HEAD/examples/volumes/rbd/README.md#how-to-use-it", + Required: true, + }, + "rbd_pool": { + Type: schema.TypeString, + Description: "The rados pool name. Default is rbd. More info: http://releases.k8s.io/HEAD/examples/volumes/rbd/README.md#how-to-use-it.", + Optional: true, + Default: "rbd", + }, + "read_only": { + Type: schema.TypeBool, + Description: "Whether to force the read-only setting in VolumeMounts. Defaults to false. More info: http://releases.k8s.io/HEAD/examples/volumes/rbd/README.md#how-to-use-it", + Optional: true, + Default: false, + }, + "secret_ref": { + Type: schema.TypeList, + Description: "Name of the authentication secret for RBDUser. If provided overrides keyring. Default is nil. More info: http://releases.k8s.io/HEAD/examples/volumes/rbd/README.md#how-to-use-it", + Optional: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "name": { + Type: schema.TypeString, + Description: "Name of the referent. More info: http://kubernetes.io/docs/user-guide/identifiers#names", + Optional: true, + }, + }, + }, + }, + }, + }, + }, + "vsphere_volume": { + Type: schema.TypeList, + Description: "Represents a vSphere volume attached and mounted on kubelets host machine", + Optional: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "fs_type": { + Type: schema.TypeString, + Description: "Filesystem type to mount. Must be a filesystem type supported by the host operating system. Ex. \"ext4\", \"xfs\", \"ntfs\". Implicitly inferred to be \"ext4\" if unspecified.", + Optional: true, + }, + "volume_path": { + Type: schema.TypeString, + Description: "Path that identifies vSphere volume vmdk", + Required: true, + }, + }, + }, + }, +} diff --git a/builtin/providers/kubernetes/structure_persistent_volume_claim.go b/builtin/providers/kubernetes/structure_persistent_volume_claim.go new file mode 100644 index 000000000..20fdbb0de --- /dev/null +++ b/builtin/providers/kubernetes/structure_persistent_volume_claim.go @@ -0,0 +1,134 @@ +package kubernetes + +import ( + "github.com/hashicorp/terraform/helper/schema" + "k8s.io/kubernetes/pkg/api/unversioned" + "k8s.io/kubernetes/pkg/api/v1" +) + +// Flatteners + +func flattenLabelSelector(in *unversioned.LabelSelector) []interface{} { + att := make(map[string]interface{}) + if len(in.MatchLabels) > 0 { + att["match_labels"] = in.MatchLabels + } + if len(in.MatchExpressions) > 0 { + att["match_expressions"] = flattenLabelSelectorRequirement(in.MatchExpressions) + } + return []interface{}{att} +} + +func flattenLabelSelectorRequirement(in []unversioned.LabelSelectorRequirement) []interface{} { + att := make([]interface{}, len(in), len(in)) + for i, n := range in { + m := make(map[string]interface{}) + m["key"] = n.Key + m["operator"] = n.Operator + m["values"] = newStringSet(schema.HashString, n.Values) + att[i] = m + } + return att +} + +func flattenPersistentVolumeClaimSpec(in v1.PersistentVolumeClaimSpec) []interface{} { + att := make(map[string]interface{}) + att["access_modes"] = flattenPersistentVolumeAccessModes(in.AccessModes) + att["resources"] = flattenResourceRequirements(in.Resources) + if in.Selector != nil { + att["selector"] = flattenLabelSelector(in.Selector) + } + if in.VolumeName != "" { + att["volume_name"] = in.VolumeName + } + return []interface{}{att} +} + +func flattenResourceRequirements(in v1.ResourceRequirements) []interface{} { + att := make(map[string]interface{}) + if len(in.Limits) > 0 { + att["limits"] = flattenResourceList(in.Limits) + } + if len(in.Requests) > 0 { + att["requests"] = flattenResourceList(in.Requests) + } + return []interface{}{att} +} + +// Expanders + +func expandLabelSelector(l []interface{}) *unversioned.LabelSelector { + if len(l) == 0 || l[0] == nil { + return &unversioned.LabelSelector{} + } + in := l[0].(map[string]interface{}) + obj := &unversioned.LabelSelector{} + if v, ok := in["match_labels"].(map[string]interface{}); ok && len(v) > 0 { + obj.MatchLabels = expandStringMap(v) + } + if v, ok := in["match_expressions"].([]interface{}); ok && len(v) > 0 { + obj.MatchExpressions = expandLabelSelectorRequirement(v) + } + return obj +} + +func expandLabelSelectorRequirement(l []interface{}) []unversioned.LabelSelectorRequirement { + if len(l) == 0 || l[0] == nil { + return []unversioned.LabelSelectorRequirement{} + } + obj := make([]unversioned.LabelSelectorRequirement, len(l), len(l)) + for i, n := range l { + in := n.(map[string]interface{}) + obj[i] = unversioned.LabelSelectorRequirement{ + Key: in["key"].(string), + Operator: unversioned.LabelSelectorOperator(in["operator"].(string)), + Values: sliceOfString(in["values"].(*schema.Set).List()), + } + } + return obj +} + +func expandPersistentVolumeClaimSpec(l []interface{}) (v1.PersistentVolumeClaimSpec, error) { + if len(l) == 0 || l[0] == nil { + return v1.PersistentVolumeClaimSpec{}, nil + } + in := l[0].(map[string]interface{}) + resourceRequirements, err := expandResourceRequirements(in["resources"].([]interface{})) + if err != nil { + return v1.PersistentVolumeClaimSpec{}, err + } + obj := v1.PersistentVolumeClaimSpec{ + AccessModes: expandPersistentVolumeAccessModes(in["access_modes"].(*schema.Set).List()), + Resources: resourceRequirements, + } + if v, ok := in["selector"].([]interface{}); ok && len(v) > 0 { + obj.Selector = expandLabelSelector(v) + } + if v, ok := in["volume_name"].(string); ok { + obj.VolumeName = v + } + return obj, nil +} + +func expandResourceRequirements(l []interface{}) (v1.ResourceRequirements, error) { + if len(l) == 0 || l[0] == nil { + return v1.ResourceRequirements{}, nil + } + in := l[0].(map[string]interface{}) + obj := v1.ResourceRequirements{} + if v, ok := in["limits"].(map[string]interface{}); ok && len(v) > 0 { + var err error + obj.Limits, err = expandMapToResourceList(v) + if err != nil { + return obj, err + } + } + if v, ok := in["requests"].(map[string]interface{}); ok && len(v) > 0 { + var err error + obj.Requests, err = expandMapToResourceList(v) + if err != nil { + return obj, err + } + } + return obj, nil +} diff --git a/builtin/providers/kubernetes/structure_persistent_volume_spec.go b/builtin/providers/kubernetes/structure_persistent_volume_spec.go new file mode 100644 index 000000000..f5463d2ac --- /dev/null +++ b/builtin/providers/kubernetes/structure_persistent_volume_spec.go @@ -0,0 +1,988 @@ +package kubernetes + +import ( + "k8s.io/kubernetes/pkg/api/v1" + + "github.com/hashicorp/terraform/helper/schema" +) + +// Flatteners + +func flattenAWSElasticBlockStoreVolumeSource(in *v1.AWSElasticBlockStoreVolumeSource) []interface{} { + att := make(map[string]interface{}) + att["volume_id"] = in.VolumeID + if in.FSType != "" { + att["fs_type"] = in.FSType + } + if in.Partition != 0 { + att["partition"] = in.Partition + } + if in.ReadOnly != false { + att["read_only"] = in.ReadOnly + } + return []interface{}{att} +} + +func flattenAzureDiskVolumeSource(in *v1.AzureDiskVolumeSource) []interface{} { + att := make(map[string]interface{}) + att["disk_name"] = in.DiskName + att["data_disk_uri"] = in.DataDiskURI + att["caching_mode"] = string(*in.CachingMode) + if in.FSType != nil { + att["fs_type"] = *in.FSType + } + if in.ReadOnly != nil { + att["read_only"] = *in.ReadOnly + } + return []interface{}{att} +} + +func flattenAzureFileVolumeSource(in *v1.AzureFileVolumeSource) []interface{} { + att := make(map[string]interface{}) + att["secret_name"] = in.SecretName + att["share_name"] = in.ShareName + if in.ReadOnly != false { + att["read_only"] = in.ReadOnly + } + return []interface{}{att} +} + +func flattenCephFSVolumeSource(in *v1.CephFSVolumeSource) []interface{} { + att := make(map[string]interface{}) + att["monitors"] = newStringSet(schema.HashString, in.Monitors) + if in.Path != "" { + att["path"] = in.Path + } + if in.User != "" { + att["user"] = in.User + } + if in.SecretFile != "" { + att["secret_file"] = in.SecretFile + } + if in.SecretRef != nil { + att["secret_ref"] = flattenLocalObjectReference(in.SecretRef) + } + if in.ReadOnly != false { + att["read_only"] = in.ReadOnly + } + return []interface{}{att} +} + +func flattenCinderVolumeSource(in *v1.CinderVolumeSource) []interface{} { + att := make(map[string]interface{}) + att["volume_id"] = in.VolumeID + if in.FSType != "" { + att["fs_type"] = in.FSType + } + if in.ReadOnly != false { + att["read_only"] = in.ReadOnly + } + return []interface{}{att} +} + +func flattenFCVolumeSource(in *v1.FCVolumeSource) []interface{} { + att := make(map[string]interface{}) + att["target_ww_ns"] = newStringSet(schema.HashString, in.TargetWWNs) + att["lun"] = *in.Lun + if in.FSType != "" { + att["fs_type"] = in.FSType + } + if in.ReadOnly != false { + att["read_only"] = in.ReadOnly + } + return []interface{}{att} +} + +func flattenFlexVolumeSource(in *v1.FlexVolumeSource) []interface{} { + att := make(map[string]interface{}) + att["driver"] = in.Driver + if in.FSType != "" { + att["fs_type"] = in.FSType + } + if in.SecretRef != nil { + att["secret_ref"] = flattenLocalObjectReference(in.SecretRef) + } + if in.ReadOnly != false { + att["read_only"] = in.ReadOnly + } + if len(in.Options) > 0 { + att["options"] = in.Options + } + return []interface{}{att} +} + +func flattenFlockerVolumeSource(in *v1.FlockerVolumeSource) []interface{} { + att := make(map[string]interface{}) + att["dataset_name"] = in.DatasetName + att["dataset_uuid"] = in.DatasetUUID + return []interface{}{att} +} + +func flattenGCEPersistentDiskVolumeSource(in *v1.GCEPersistentDiskVolumeSource) []interface{} { + att := make(map[string]interface{}) + att["pd_name"] = in.PDName + if in.FSType != "" { + att["fs_type"] = in.FSType + } + if in.Partition != 0 { + att["partition"] = in.Partition + } + if in.ReadOnly != false { + att["read_only"] = in.ReadOnly + } + return []interface{}{att} +} + +func flattenGlusterfsVolumeSource(in *v1.GlusterfsVolumeSource) []interface{} { + att := make(map[string]interface{}) + att["endpoints_name"] = in.EndpointsName + att["path"] = in.Path + if in.ReadOnly != false { + att["read_only"] = in.ReadOnly + } + return []interface{}{att} +} + +func flattenHostPathVolumeSource(in *v1.HostPathVolumeSource) []interface{} { + att := make(map[string]interface{}) + att["path"] = in.Path + return []interface{}{att} +} + +func flattenISCSIVolumeSource(in *v1.ISCSIVolumeSource) []interface{} { + att := make(map[string]interface{}) + if in.TargetPortal != "" { + att["target_portal"] = in.TargetPortal + } + if in.IQN != "" { + att["iqn"] = in.IQN + } + if in.Lun != 0 { + att["lun"] = in.Lun + } + if in.ISCSIInterface != "" { + att["iscsi_interface"] = in.ISCSIInterface + } + if in.FSType != "" { + att["fs_type"] = in.FSType + } + if in.ReadOnly != false { + att["read_only"] = in.ReadOnly + } + return []interface{}{att} +} + +func flattenLocalObjectReference(in *v1.LocalObjectReference) []interface{} { + att := make(map[string]interface{}) + if in.Name != "" { + att["name"] = in.Name + } + return []interface{}{att} +} + +func flattenNFSVolumeSource(in *v1.NFSVolumeSource) []interface{} { + att := make(map[string]interface{}) + att["server"] = in.Server + att["path"] = in.Path + if in.ReadOnly != false { + att["read_only"] = in.ReadOnly + } + return []interface{}{att} +} + +func flattenPersistentVolumeSource(in v1.PersistentVolumeSource) []interface{} { + att := make(map[string]interface{}) + if in.GCEPersistentDisk != nil { + att["gce_persistent_disk"] = flattenGCEPersistentDiskVolumeSource(in.GCEPersistentDisk) + } + if in.AWSElasticBlockStore != nil { + att["aws_elastic_block_store"] = flattenAWSElasticBlockStoreVolumeSource(in.AWSElasticBlockStore) + } + if in.HostPath != nil { + att["host_path"] = flattenHostPathVolumeSource(in.HostPath) + } + if in.Glusterfs != nil { + att["glusterfs"] = flattenGlusterfsVolumeSource(in.Glusterfs) + } + if in.NFS != nil { + att["nfs"] = flattenNFSVolumeSource(in.NFS) + } + if in.RBD != nil { + att["rbd"] = flattenRBDVolumeSource(in.RBD) + } + if in.ISCSI != nil { + att["iscsi"] = flattenISCSIVolumeSource(in.ISCSI) + } + if in.Cinder != nil { + att["cinder"] = flattenCinderVolumeSource(in.Cinder) + } + if in.CephFS != nil { + att["ceph_fs"] = flattenCephFSVolumeSource(in.CephFS) + } + if in.FC != nil { + att["fc"] = flattenFCVolumeSource(in.FC) + } + if in.Flocker != nil { + att["flocker"] = flattenFlockerVolumeSource(in.Flocker) + } + if in.FlexVolume != nil { + att["flex_volume"] = flattenFlexVolumeSource(in.FlexVolume) + } + if in.AzureFile != nil { + att["azure_file"] = flattenAzureFileVolumeSource(in.AzureFile) + } + if in.VsphereVolume != nil { + att["vsphere_volume"] = flattenVsphereVirtualDiskVolumeSource(in.VsphereVolume) + } + if in.Quobyte != nil { + att["quobyte"] = flattenQuobyteVolumeSource(in.Quobyte) + } + if in.AzureDisk != nil { + att["azure_disk"] = flattenAzureDiskVolumeSource(in.AzureDisk) + } + if in.PhotonPersistentDisk != nil { + att["photon_persistent_disk"] = flattenPhotonPersistentDiskVolumeSource(in.PhotonPersistentDisk) + } + return []interface{}{att} +} + +func flattenPersistentVolumeSpec(in v1.PersistentVolumeSpec) []interface{} { + att := make(map[string]interface{}) + if len(in.Capacity) > 0 { + att["capacity"] = flattenResourceList(in.Capacity) + } + + att["persistent_volume_source"] = flattenPersistentVolumeSource(in.PersistentVolumeSource) + if len(in.AccessModes) > 0 { + att["access_modes"] = flattenPersistentVolumeAccessModes(in.AccessModes) + } + if in.PersistentVolumeReclaimPolicy != "" { + att["persistent_volume_reclaim_policy"] = in.PersistentVolumeReclaimPolicy + } + return []interface{}{att} +} + +func flattenPhotonPersistentDiskVolumeSource(in *v1.PhotonPersistentDiskVolumeSource) []interface{} { + att := make(map[string]interface{}) + att["pd_id"] = in.PdID + if in.FSType != "" { + att["fs_type"] = in.FSType + } + return []interface{}{att} +} + +func flattenQuobyteVolumeSource(in *v1.QuobyteVolumeSource) []interface{} { + att := make(map[string]interface{}) + att["registry"] = in.Registry + att["volume"] = in.Volume + if in.ReadOnly != false { + att["read_only"] = in.ReadOnly + } + if in.User != "" { + att["user"] = in.User + } + if in.Group != "" { + att["group"] = in.Group + } + return []interface{}{att} +} + +func flattenRBDVolumeSource(in *v1.RBDVolumeSource) []interface{} { + att := make(map[string]interface{}) + att["ceph_monitors"] = newStringSet(schema.HashString, in.CephMonitors) + att["rbd_image"] = in.RBDImage + if in.FSType != "" { + att["fs_type"] = in.FSType + } + if in.RBDPool != "" { + att["rbd_pool"] = in.RBDPool + } + if in.RadosUser != "" { + att["rados_user"] = in.RadosUser + } + if in.Keyring != "" { + att["keyring"] = in.Keyring + } + if in.SecretRef != nil { + att["secret_ref"] = flattenLocalObjectReference(in.SecretRef) + } + if in.ReadOnly != false { + att["read_only"] = in.ReadOnly + } + return []interface{}{att} +} + +func flattenVsphereVirtualDiskVolumeSource(in *v1.VsphereVirtualDiskVolumeSource) []interface{} { + att := make(map[string]interface{}) + att["volume_path"] = in.VolumePath + if in.FSType != "" { + att["fs_type"] = in.FSType + } + return []interface{}{att} +} + +// Expanders + +func expandAWSElasticBlockStoreVolumeSource(l []interface{}) *v1.AWSElasticBlockStoreVolumeSource { + if len(l) == 0 || l[0] == nil { + return &v1.AWSElasticBlockStoreVolumeSource{} + } + in := l[0].(map[string]interface{}) + obj := &v1.AWSElasticBlockStoreVolumeSource{ + VolumeID: in["volume_id"].(string), + } + if v, ok := in["fs_type"].(string); ok { + obj.FSType = v + } + if v, ok := in["partition"].(int); ok { + obj.Partition = int32(v) + } + if v, ok := in["read_only"].(bool); ok { + obj.ReadOnly = v + } + return obj +} + +func expandAzureDiskVolumeSource(l []interface{}) *v1.AzureDiskVolumeSource { + if len(l) == 0 || l[0] == nil { + return &v1.AzureDiskVolumeSource{} + } + in := l[0].(map[string]interface{}) + cachingMode := v1.AzureDataDiskCachingMode(in["caching_mode"].(string)) + obj := &v1.AzureDiskVolumeSource{ + CachingMode: &cachingMode, + DiskName: in["disk_name"].(string), + DataDiskURI: in["data_disk_uri"].(string), + } + if v, ok := in["fs_type"].(string); ok { + obj.FSType = ptrToString(v) + } + if v, ok := in["read_only"].(bool); ok { + obj.ReadOnly = ptrToBool(v) + } + return obj +} + +func expandAzureFileVolumeSource(l []interface{}) *v1.AzureFileVolumeSource { + if len(l) == 0 || l[0] == nil { + return &v1.AzureFileVolumeSource{} + } + in := l[0].(map[string]interface{}) + obj := &v1.AzureFileVolumeSource{ + SecretName: in["secret_name"].(string), + ShareName: in["share_name"].(string), + } + if v, ok := in["read_only"].(bool); ok { + obj.ReadOnly = v + } + return obj +} + +func expandCephFSVolumeSource(l []interface{}) *v1.CephFSVolumeSource { + if len(l) == 0 || l[0] == nil { + return &v1.CephFSVolumeSource{} + } + in := l[0].(map[string]interface{}) + obj := &v1.CephFSVolumeSource{ + Monitors: sliceOfString(in["monitors"].(*schema.Set).List()), + } + if v, ok := in["path"].(string); ok { + obj.Path = v + } + if v, ok := in["user"].(string); ok { + obj.User = v + } + if v, ok := in["secret_file"].(string); ok { + obj.SecretFile = v + } + if v, ok := in["secret_ref"].([]interface{}); ok && len(v) > 0 { + obj.SecretRef = expandLocalObjectReference(v) + } + if v, ok := in["read_only"].(bool); ok { + obj.ReadOnly = v + } + return obj +} + +func expandCinderVolumeSource(l []interface{}) *v1.CinderVolumeSource { + if len(l) == 0 || l[0] == nil { + return &v1.CinderVolumeSource{} + } + in := l[0].(map[string]interface{}) + obj := &v1.CinderVolumeSource{ + VolumeID: in["volume_id"].(string), + } + if v, ok := in["fs_type"].(string); ok { + obj.FSType = v + } + if v, ok := in["read_only"].(bool); ok { + obj.ReadOnly = v + } + return obj +} + +func expandFCVolumeSource(l []interface{}) *v1.FCVolumeSource { + if len(l) == 0 || l[0] == nil { + return &v1.FCVolumeSource{} + } + in := l[0].(map[string]interface{}) + obj := &v1.FCVolumeSource{ + TargetWWNs: sliceOfString(in["target_ww_ns"].(*schema.Set).List()), + Lun: ptrToInt32(int32(in["lun"].(int))), + } + if v, ok := in["fs_type"].(string); ok { + obj.FSType = v + } + if v, ok := in["read_only"].(bool); ok { + obj.ReadOnly = v + } + return obj +} + +func expandFlexVolumeSource(l []interface{}) *v1.FlexVolumeSource { + if len(l) == 0 || l[0] == nil { + return &v1.FlexVolumeSource{} + } + in := l[0].(map[string]interface{}) + obj := &v1.FlexVolumeSource{ + Driver: in["driver"].(string), + } + if v, ok := in["fs_type"].(string); ok { + obj.FSType = v + } + if v, ok := in["secret_ref"].([]interface{}); ok && len(v) > 0 { + obj.SecretRef = expandLocalObjectReference(v) + } + if v, ok := in["read_only"].(bool); ok { + obj.ReadOnly = v + } + if v, ok := in["options"].(map[string]interface{}); ok && len(v) > 0 { + obj.Options = expandStringMap(v) + } + return obj +} + +func expandFlockerVolumeSource(l []interface{}) *v1.FlockerVolumeSource { + if len(l) == 0 || l[0] == nil { + return &v1.FlockerVolumeSource{} + } + in := l[0].(map[string]interface{}) + obj := &v1.FlockerVolumeSource{ + DatasetName: in["dataset_name"].(string), + DatasetUUID: in["dataset_uuid"].(string), + } + return obj +} + +func expandGCEPersistentDiskVolumeSource(l []interface{}) *v1.GCEPersistentDiskVolumeSource { + if len(l) == 0 || l[0] == nil { + return &v1.GCEPersistentDiskVolumeSource{} + } + in := l[0].(map[string]interface{}) + obj := &v1.GCEPersistentDiskVolumeSource{ + PDName: in["pd_name"].(string), + } + if v, ok := in["fs_type"].(string); ok { + obj.FSType = v + } + if v, ok := in["partition"].(int); ok { + obj.Partition = int32(v) + } + if v, ok := in["read_only"].(bool); ok { + obj.ReadOnly = v + } + return obj +} + +func expandGlusterfsVolumeSource(l []interface{}) *v1.GlusterfsVolumeSource { + if len(l) == 0 || l[0] == nil { + return &v1.GlusterfsVolumeSource{} + } + in := l[0].(map[string]interface{}) + obj := &v1.GlusterfsVolumeSource{ + EndpointsName: in["endpoints_name"].(string), + Path: in["path"].(string), + } + if v, ok := in["read_only"].(bool); ok { + obj.ReadOnly = v + } + return obj +} + +func expandHostPathVolumeSource(l []interface{}) *v1.HostPathVolumeSource { + if len(l) == 0 || l[0] == nil { + return &v1.HostPathVolumeSource{} + } + in := l[0].(map[string]interface{}) + obj := &v1.HostPathVolumeSource{ + Path: in["path"].(string), + } + return obj +} + +func expandISCSIVolumeSource(l []interface{}) *v1.ISCSIVolumeSource { + if len(l) == 0 || l[0] == nil { + return &v1.ISCSIVolumeSource{} + } + in := l[0].(map[string]interface{}) + obj := &v1.ISCSIVolumeSource{ + TargetPortal: in["target_portal"].(string), + IQN: in["iqn"].(string), + } + if v, ok := in["lun"].(int); ok { + obj.Lun = int32(v) + } + if v, ok := in["iscsi_interface"].(string); ok { + obj.ISCSIInterface = v + } + if v, ok := in["fs_type"].(string); ok { + obj.FSType = v + } + if v, ok := in["read_only"].(bool); ok { + obj.ReadOnly = v + } + return obj +} + +func expandLocalObjectReference(l []interface{}) *v1.LocalObjectReference { + if len(l) == 0 || l[0] == nil { + return &v1.LocalObjectReference{} + } + in := l[0].(map[string]interface{}) + obj := &v1.LocalObjectReference{} + if v, ok := in["name"].(string); ok { + obj.Name = v + } + return obj +} + +func expandNFSVolumeSource(l []interface{}) *v1.NFSVolumeSource { + if len(l) == 0 || l[0] == nil { + return &v1.NFSVolumeSource{} + } + in := l[0].(map[string]interface{}) + obj := &v1.NFSVolumeSource{ + Server: in["server"].(string), + Path: in["path"].(string), + } + if v, ok := in["read_only"].(bool); ok { + obj.ReadOnly = v + } + return obj +} + +func expandPersistentVolumeSource(l []interface{}) v1.PersistentVolumeSource { + if len(l) == 0 || l[0] == nil { + return v1.PersistentVolumeSource{} + } + in := l[0].(map[string]interface{}) + obj := v1.PersistentVolumeSource{} + if v, ok := in["gce_persistent_disk"].([]interface{}); ok && len(v) > 0 { + obj.GCEPersistentDisk = expandGCEPersistentDiskVolumeSource(v) + } + if v, ok := in["aws_elastic_block_store"].([]interface{}); ok && len(v) > 0 { + obj.AWSElasticBlockStore = expandAWSElasticBlockStoreVolumeSource(v) + } + if v, ok := in["host_path"].([]interface{}); ok && len(v) > 0 { + obj.HostPath = expandHostPathVolumeSource(v) + } + if v, ok := in["glusterfs"].([]interface{}); ok && len(v) > 0 { + obj.Glusterfs = expandGlusterfsVolumeSource(v) + } + if v, ok := in["nfs"].([]interface{}); ok && len(v) > 0 { + obj.NFS = expandNFSVolumeSource(v) + } + if v, ok := in["rbd"].([]interface{}); ok && len(v) > 0 { + obj.RBD = expandRBDVolumeSource(v) + } + if v, ok := in["iscsi"].([]interface{}); ok && len(v) > 0 { + obj.ISCSI = expandISCSIVolumeSource(v) + } + if v, ok := in["cinder"].([]interface{}); ok && len(v) > 0 { + obj.Cinder = expandCinderVolumeSource(v) + } + if v, ok := in["ceph_fs"].([]interface{}); ok && len(v) > 0 { + obj.CephFS = expandCephFSVolumeSource(v) + } + if v, ok := in["fc"].([]interface{}); ok && len(v) > 0 { + obj.FC = expandFCVolumeSource(v) + } + if v, ok := in["flocker"].([]interface{}); ok && len(v) > 0 { + obj.Flocker = expandFlockerVolumeSource(v) + } + if v, ok := in["flex_volume"].([]interface{}); ok && len(v) > 0 { + obj.FlexVolume = expandFlexVolumeSource(v) + } + if v, ok := in["azure_file"].([]interface{}); ok && len(v) > 0 { + obj.AzureFile = expandAzureFileVolumeSource(v) + } + if v, ok := in["vsphere_volume"].([]interface{}); ok && len(v) > 0 { + obj.VsphereVolume = expandVsphereVirtualDiskVolumeSource(v) + } + if v, ok := in["quobyte"].([]interface{}); ok && len(v) > 0 { + obj.Quobyte = expandQuobyteVolumeSource(v) + } + if v, ok := in["azure_disk"].([]interface{}); ok && len(v) > 0 { + obj.AzureDisk = expandAzureDiskVolumeSource(v) + } + if v, ok := in["photon_persistent_disk"].([]interface{}); ok && len(v) > 0 { + obj.PhotonPersistentDisk = expandPhotonPersistentDiskVolumeSource(v) + } + return obj +} + +func expandPersistentVolumeSpec(l []interface{}) (v1.PersistentVolumeSpec, error) { + if len(l) == 0 || l[0] == nil { + return v1.PersistentVolumeSpec{}, nil + } + in := l[0].(map[string]interface{}) + obj := v1.PersistentVolumeSpec{} + if v, ok := in["capacity"].(map[string]interface{}); ok && len(v) > 0 { + var err error + obj.Capacity, err = expandMapToResourceList(v) + if err != nil { + return obj, err + } + } + if v, ok := in["persistent_volume_source"].([]interface{}); ok && len(v) > 0 { + obj.PersistentVolumeSource = expandPersistentVolumeSource(v) + } + if v, ok := in["access_modes"].(*schema.Set); ok && v.Len() > 0 { + obj.AccessModes = expandPersistentVolumeAccessModes(v.List()) + } + if v, ok := in["persistent_volume_reclaim_policy"].(string); ok { + obj.PersistentVolumeReclaimPolicy = v1.PersistentVolumeReclaimPolicy(v) + } + return obj, nil +} + +func expandPhotonPersistentDiskVolumeSource(l []interface{}) *v1.PhotonPersistentDiskVolumeSource { + if len(l) == 0 || l[0] == nil { + return &v1.PhotonPersistentDiskVolumeSource{} + } + in := l[0].(map[string]interface{}) + obj := &v1.PhotonPersistentDiskVolumeSource{ + PdID: in["pd_id"].(string), + } + if v, ok := in["fs_type"].(string); ok { + obj.FSType = v + } + return obj +} + +func expandQuobyteVolumeSource(l []interface{}) *v1.QuobyteVolumeSource { + if len(l) == 0 || l[0] == nil { + return &v1.QuobyteVolumeSource{} + } + in := l[0].(map[string]interface{}) + obj := &v1.QuobyteVolumeSource{ + Registry: in["registry"].(string), + Volume: in["volume"].(string), + } + if v, ok := in["read_only"].(bool); ok { + obj.ReadOnly = v + } + if v, ok := in["user"].(string); ok { + obj.User = v + } + if v, ok := in["group"].(string); ok { + obj.Group = v + } + return obj +} + +func expandRBDVolumeSource(l []interface{}) *v1.RBDVolumeSource { + if len(l) == 0 || l[0] == nil { + return &v1.RBDVolumeSource{} + } + in := l[0].(map[string]interface{}) + obj := &v1.RBDVolumeSource{ + CephMonitors: expandStringSlice(in["ceph_monitors"].(*schema.Set).List()), + RBDImage: in["rbd_image"].(string), + } + if v, ok := in["fs_type"].(string); ok { + obj.FSType = v + } + if v, ok := in["rbd_pool"].(string); ok { + obj.RBDPool = v + } + if v, ok := in["rados_user"].(string); ok { + obj.RadosUser = v + } + if v, ok := in["keyring"].(string); ok { + obj.Keyring = v + } + if v, ok := in["secret_ref"].([]interface{}); ok && len(v) > 0 { + obj.SecretRef = expandLocalObjectReference(v) + } + if v, ok := in["read_only"].(bool); ok { + obj.ReadOnly = v + } + return obj +} + +func expandVsphereVirtualDiskVolumeSource(l []interface{}) *v1.VsphereVirtualDiskVolumeSource { + if len(l) == 0 || l[0] == nil { + return &v1.VsphereVirtualDiskVolumeSource{} + } + in := l[0].(map[string]interface{}) + obj := &v1.VsphereVirtualDiskVolumeSource{ + VolumePath: in["volume_path"].(string), + } + if v, ok := in["fs_type"].(string); ok { + obj.FSType = v + } + return obj +} + +func patchPersistentVolumeSpec(pathPrefix, prefix string, d *schema.ResourceData) (PatchOperations, error) { + ops := make([]PatchOperation, 0) + prefix += ".0." + + if d.HasChange(prefix + "capacity") { + v := d.Get(prefix + "capacity").(map[string]interface{}) + capacity, err := expandMapToResourceList(v) + if err != nil { + return ops, err + } + ops = append(ops, &ReplaceOperation{ + Path: pathPrefix + "/capacity", + Value: capacity, + }) + } + + if d.HasChange(prefix + "persistent_volume_source") { + ops = append(ops, patchPersistentVolumeSource( + pathPrefix, + prefix+"persistent_volume_source.0.", + d, + )...) + } + + if d.HasChange(prefix + "access_modes") { + v := d.Get(prefix + "access_modes").(*schema.Set) + ops = append(ops, &ReplaceOperation{ + Path: pathPrefix + "/accessModes", + Value: expandPersistentVolumeAccessModes(v.List()), + }) + } + if d.HasChange(prefix + "access_modes") { + v := d.Get(prefix + "persistent_volume_reclaim_policy").(string) + ops = append(ops, &ReplaceOperation{ + Path: pathPrefix + "/persistentVolumeReclaimPolicy", + Value: v1.PersistentVolumeReclaimPolicy(v), + }) + } + + return ops, nil +} + +func patchPersistentVolumeSource(pathPrefix, prefix string, d *schema.ResourceData) []PatchOperation { + ops := make([]PatchOperation, 0) + + if d.HasChange(prefix + "gce_persistent_disk") { + oldIn, newIn := d.GetChange(prefix + "gce_persistent_disk") + if v, ok := newIn.([]interface{}); ok && len(v) > 0 { + ops = append(ops, &ReplaceOperation{ + Path: pathPrefix + "/gcePersistentDisk", + Value: expandGCEPersistentDiskVolumeSource(v), + }) + } else if v, ok := oldIn.([]interface{}); ok && len(v) > 0 { + ops = append(ops, &RemoveOperation{Path: pathPrefix + "/gcePersistentDisk"}) + } + } + + if d.HasChange(prefix + "aws_elastic_block_store") { + oldIn, newIn := d.GetChange(prefix + "aws_elastic_block_store") + if v, ok := newIn.([]interface{}); ok && len(v) > 0 { + ops = append(ops, &ReplaceOperation{ + Path: pathPrefix + "/awsElasticBlockStore", + Value: expandAWSElasticBlockStoreVolumeSource(v), + }) + } else if v, ok := oldIn.([]interface{}); ok && len(v) > 0 { + ops = append(ops, &RemoveOperation{Path: pathPrefix + "/awsElasticBlockStore"}) + } + } + + if d.HasChange(prefix + "host_path") { + oldIn, newIn := d.GetChange(prefix + "host_path") + if v, ok := newIn.([]interface{}); ok && len(v) > 0 { + ops = append(ops, &ReplaceOperation{ + Path: pathPrefix + "/hostPath", + Value: expandHostPathVolumeSource(v), + }) + } else if v, ok := oldIn.([]interface{}); ok && len(v) > 0 { + ops = append(ops, &RemoveOperation{Path: pathPrefix + "/hostPath"}) + } + } + + if d.HasChange(prefix + "glusterfs") { + oldIn, newIn := d.GetChange(prefix + "glusterfs") + if v, ok := newIn.([]interface{}); ok && len(v) > 0 { + ops = append(ops, &ReplaceOperation{ + Path: pathPrefix + "/glusterfs", + Value: expandGlusterfsVolumeSource(v), + }) + } else if v, ok := oldIn.([]interface{}); ok && len(v) > 0 { + ops = append(ops, &RemoveOperation{Path: pathPrefix + "/glusterfs"}) + } + } + + if d.HasChange(prefix + "nfs") { + oldIn, newIn := d.GetChange(prefix + "nfs") + if v, ok := newIn.([]interface{}); ok && len(v) > 0 { + ops = append(ops, &ReplaceOperation{ + Path: pathPrefix + "/nfs", + Value: expandNFSVolumeSource(v), + }) + } else if v, ok := oldIn.([]interface{}); ok && len(v) > 0 { + ops = append(ops, &RemoveOperation{Path: pathPrefix + "/nfs"}) + } + } + + if d.HasChange(prefix + "rbd") { + oldIn, newIn := d.GetChange(prefix + "rbd") + if v, ok := newIn.([]interface{}); ok && len(v) > 0 { + ops = append(ops, &ReplaceOperation{ + Path: pathPrefix + "/rbd", + Value: expandRBDVolumeSource(v), + }) + } else if v, ok := oldIn.([]interface{}); ok && len(v) > 0 { + ops = append(ops, &RemoveOperation{Path: pathPrefix + "/rbd"}) + } + } + + if d.HasChange(prefix + "iscsi") { + oldIn, newIn := d.GetChange(prefix + "iscsi") + if v, ok := newIn.([]interface{}); ok && len(v) > 0 { + ops = append(ops, &ReplaceOperation{ + Path: pathPrefix + "/iscsi", + Value: expandISCSIVolumeSource(v), + }) + } else if v, ok := oldIn.([]interface{}); ok && len(v) > 0 { + ops = append(ops, &RemoveOperation{Path: pathPrefix + "/iscsi"}) + } + } + + if d.HasChange(prefix + "cinder") { + oldIn, newIn := d.GetChange(prefix + "cinder") + if v, ok := newIn.([]interface{}); ok && len(v) > 0 { + ops = append(ops, &ReplaceOperation{ + Path: pathPrefix + "/cinder", + Value: expandCinderVolumeSource(v), + }) + } else if v, ok := oldIn.([]interface{}); ok && len(v) > 0 { + ops = append(ops, &RemoveOperation{Path: pathPrefix + "/cinder"}) + } + } + + if d.HasChange(prefix + "ceph_fs") { + oldIn, newIn := d.GetChange(prefix + "ceph_fs") + if v, ok := newIn.([]interface{}); ok && len(v) > 0 { + ops = append(ops, &ReplaceOperation{ + Path: pathPrefix + "/cephfs", + Value: expandCephFSVolumeSource(v), + }) + } else if v, ok := oldIn.([]interface{}); ok && len(v) > 0 { + ops = append(ops, &RemoveOperation{Path: pathPrefix + "/cephfs"}) + } + } + + if d.HasChange(prefix + "fc") { + oldIn, newIn := d.GetChange(prefix + "fc") + if v, ok := newIn.([]interface{}); ok && len(v) > 0 { + ops = append(ops, &ReplaceOperation{ + Path: pathPrefix + "/fc", + Value: expandFCVolumeSource(v), + }) + } else if v, ok := oldIn.([]interface{}); ok && len(v) > 0 { + ops = append(ops, &RemoveOperation{Path: pathPrefix + "/fc"}) + } + } + + if d.HasChange(prefix + "flocker") { + oldIn, newIn := d.GetChange(prefix + "flocker") + if v, ok := newIn.([]interface{}); ok && len(v) > 0 { + ops = append(ops, &ReplaceOperation{ + Path: pathPrefix + "/flocker", + Value: expandFlockerVolumeSource(v), + }) + } else if v, ok := oldIn.([]interface{}); ok && len(v) > 0 { + ops = append(ops, &RemoveOperation{Path: pathPrefix + "/flocker"}) + } + } + + if d.HasChange(prefix + "flex_volume") { + oldIn, newIn := d.GetChange(prefix + "flex_volume") + if v, ok := newIn.([]interface{}); ok && len(v) > 0 { + ops = append(ops, &ReplaceOperation{ + Path: pathPrefix + "/flexVolume", + Value: expandFlexVolumeSource(v), + }) + } else if v, ok := oldIn.([]interface{}); ok && len(v) > 0 { + ops = append(ops, &RemoveOperation{Path: pathPrefix + "/flexVolume"}) + } + } + + if d.HasChange(prefix + "azure_file") { + oldIn, newIn := d.GetChange(prefix + "azure_file") + if v, ok := newIn.([]interface{}); ok && len(v) > 0 { + ops = append(ops, &ReplaceOperation{ + Path: pathPrefix + "/azureFile", + Value: expandAzureFileVolumeSource(v), + }) + } else if v, ok := oldIn.([]interface{}); ok && len(v) > 0 { + ops = append(ops, &RemoveOperation{Path: pathPrefix + "/azureFile"}) + } + } + + if d.HasChange(prefix + "vsphere_volume") { + oldIn, newIn := d.GetChange(prefix + "vsphere_volume") + if v, ok := newIn.([]interface{}); ok && len(v) > 0 { + ops = append(ops, &ReplaceOperation{ + Path: pathPrefix + "/vsphereVolume", + Value: expandVsphereVirtualDiskVolumeSource(v), + }) + } else if v, ok := oldIn.([]interface{}); ok && len(v) > 0 { + ops = append(ops, &RemoveOperation{Path: pathPrefix + "/vsphereVolume"}) + } + } + + if d.HasChange(prefix + "quobyte") { + oldIn, newIn := d.GetChange(prefix + "quobyte") + if v, ok := newIn.([]interface{}); ok && len(v) > 0 { + ops = append(ops, &ReplaceOperation{ + Path: pathPrefix + "/quobyte", + Value: expandQuobyteVolumeSource(v), + }) + } else if v, ok := oldIn.([]interface{}); ok && len(v) > 0 { + ops = append(ops, &RemoveOperation{Path: pathPrefix + "/quobyte"}) + } + } + + if d.HasChange(prefix + "azure_disk") { + oldIn, newIn := d.GetChange(prefix + "azure_disk") + if v, ok := newIn.([]interface{}); ok && len(v) > 0 { + ops = append(ops, &ReplaceOperation{ + Path: pathPrefix + "/azureDisk", + Value: expandAzureDiskVolumeSource(v), + }) + } else if v, ok := oldIn.([]interface{}); ok && len(v) > 0 { + ops = append(ops, &RemoveOperation{Path: pathPrefix + "/azureDisk"}) + } + } + + if d.HasChange(prefix + "photon_persistent_disk") { + oldIn, newIn := d.GetChange(prefix + "photon_persistent_disk") + if v, ok := newIn.([]interface{}); ok && len(v) > 0 { + ops = append(ops, &ReplaceOperation{ + Path: pathPrefix + "/photonPersistentDisk", + Value: expandPhotonPersistentDiskVolumeSource(v), + }) + } else if v, ok := oldIn.([]interface{}); ok && len(v) > 0 { + ops = append(ops, &RemoveOperation{Path: pathPrefix + "/photonPersistentDisk"}) + } + } + + return ops +} diff --git a/builtin/providers/kubernetes/structures.go b/builtin/providers/kubernetes/structures.go index 58bc49030..d02a9ea5d 100644 --- a/builtin/providers/kubernetes/structures.go +++ b/builtin/providers/kubernetes/structures.go @@ -5,7 +5,9 @@ import ( "net/url" "strings" + "encoding/base64" "github.com/hashicorp/terraform/helper/schema" + "k8s.io/kubernetes/pkg/api/resource" api "k8s.io/kubernetes/pkg/api/v1" ) @@ -64,10 +66,20 @@ func expandStringMap(m map[string]interface{}) map[string]string { return result } +func expandStringSlice(s []interface{}) []string { + result := make([]string, len(s), len(s)) + for k, v := range s { + result[k] = v.(string) + } + return result +} + func flattenMetadata(meta api.ObjectMeta) []map[string]interface{} { m := make(map[string]interface{}) m["annotations"] = filterAnnotations(meta.Annotations) - m["generate_name"] = meta.GenerateName + if meta.GenerateName != "" { + m["generate_name"] = meta.GenerateName + } m["labels"] = meta.Labels m["name"] = meta.Name m["resource_version"] = meta.ResourceVersion @@ -99,3 +111,265 @@ func isInternalAnnotationKey(annotationKey string) bool { return false } + +func byteMapToStringMap(m map[string][]byte) map[string]string { + result := make(map[string]string) + for k, v := range m { + result[k] = string(v) + } + return result +} + +func ptrToString(s string) *string { + return &s +} + +func ptrToInt(i int) *int { + return &i +} + +func ptrToBool(b bool) *bool { + return &b +} + +func ptrToInt32(i int32) *int32 { + return &i +} + +func sliceOfString(slice []interface{}) []string { + result := make([]string, len(slice), len(slice)) + for i, s := range slice { + result[i] = s.(string) + } + return result +} + +func base64EncodeStringMap(m map[string]interface{}) map[string]interface{} { + result := make(map[string]interface{}) + for k, v := range m { + value := v.(string) + result[k] = (base64.StdEncoding.EncodeToString([]byte(value))) + } + return result +} + +func flattenResourceList(l api.ResourceList) map[string]string { + m := make(map[string]string) + for k, v := range l { + m[string(k)] = v.String() + } + return m +} + +func expandMapToResourceList(m map[string]interface{}) (api.ResourceList, error) { + out := make(map[api.ResourceName]resource.Quantity) + for stringKey, origValue := range m { + key := api.ResourceName(stringKey) + var value resource.Quantity + + if v, ok := origValue.(int); ok { + q := resource.NewQuantity(int64(v), resource.DecimalExponent) + value = *q + } else if v, ok := origValue.(string); ok { + var err error + value, err = resource.ParseQuantity(v) + if err != nil { + return out, err + } + } else { + return out, fmt.Errorf("Unexpected value type: %#v", origValue) + } + + out[key] = value + } + return out, nil +} + +func flattenPersistentVolumeAccessModes(in []api.PersistentVolumeAccessMode) *schema.Set { + var out = make([]interface{}, len(in), len(in)) + for i, v := range in { + out[i] = string(v) + } + return schema.NewSet(schema.HashString, out) +} + +func expandPersistentVolumeAccessModes(s []interface{}) []api.PersistentVolumeAccessMode { + out := make([]api.PersistentVolumeAccessMode, len(s), len(s)) + for i, v := range s { + out[i] = api.PersistentVolumeAccessMode(v.(string)) + } + return out +} + +func flattenResourceQuotaSpec(in api.ResourceQuotaSpec) []interface{} { + out := make([]interface{}, 1) + + m := make(map[string]interface{}, 0) + m["hard"] = flattenResourceList(in.Hard) + m["scopes"] = flattenResourceQuotaScopes(in.Scopes) + + out[0] = m + return out +} + +func expandResourceQuotaSpec(s []interface{}) (api.ResourceQuotaSpec, error) { + out := api.ResourceQuotaSpec{} + if len(s) < 1 { + return out, nil + } + m := s[0].(map[string]interface{}) + + if v, ok := m["hard"]; ok { + list, err := expandMapToResourceList(v.(map[string]interface{})) + if err != nil { + return out, err + } + out.Hard = list + } + + if v, ok := m["scopes"]; ok { + out.Scopes = expandResourceQuotaScopes(v.(*schema.Set).List()) + } + + return out, nil +} + +func flattenResourceQuotaScopes(in []api.ResourceQuotaScope) *schema.Set { + out := make([]string, len(in), len(in)) + for i, scope := range in { + out[i] = string(scope) + } + return newStringSet(schema.HashString, out) +} + +func expandResourceQuotaScopes(s []interface{}) []api.ResourceQuotaScope { + out := make([]api.ResourceQuotaScope, len(s), len(s)) + for i, scope := range s { + out[i] = api.ResourceQuotaScope(scope.(string)) + } + return out +} + +func newStringSet(f schema.SchemaSetFunc, in []string) *schema.Set { + var out = make([]interface{}, len(in), len(in)) + for i, v := range in { + out[i] = v + } + return schema.NewSet(f, out) +} + +func resourceListEquals(x, y api.ResourceList) bool { + for k, v := range x { + yValue, ok := y[k] + if !ok { + return false + } + if v.Cmp(yValue) != 0 { + return false + } + } + for k, v := range y { + xValue, ok := x[k] + if !ok { + return false + } + if v.Cmp(xValue) != 0 { + return false + } + } + return true +} + +func expandLimitRangeSpec(s []interface{}, isNew bool) (api.LimitRangeSpec, error) { + out := api.LimitRangeSpec{} + if len(s) < 1 || s[0] == nil { + return out, nil + } + m := s[0].(map[string]interface{}) + + if limits, ok := m["limit"].([]interface{}); ok { + newLimits := make([]api.LimitRangeItem, len(limits), len(limits)) + + for i, l := range limits { + lrItem := api.LimitRangeItem{} + limit := l.(map[string]interface{}) + + if v, ok := limit["type"]; ok { + lrItem.Type = api.LimitType(v.(string)) + } + + // defaultRequest is forbidden for Pod limits, even though it's set & returned by API + // this is how we avoid sending it back + if v, ok := limit["default_request"]; ok { + drm := v.(map[string]interface{}) + if lrItem.Type == api.LimitTypePod && len(drm) > 0 { + if isNew { + return out, fmt.Errorf("limit.%d.default_request cannot be set for Pod limit", i) + } + } else { + el, err := expandMapToResourceList(drm) + if err != nil { + return out, err + } + lrItem.DefaultRequest = el + } + } + + if v, ok := limit["default"]; ok { + el, err := expandMapToResourceList(v.(map[string]interface{})) + if err != nil { + return out, err + } + lrItem.Default = el + } + if v, ok := limit["max"]; ok { + el, err := expandMapToResourceList(v.(map[string]interface{})) + if err != nil { + return out, err + } + lrItem.Max = el + } + if v, ok := limit["max_limit_request_ratio"]; ok { + el, err := expandMapToResourceList(v.(map[string]interface{})) + if err != nil { + return out, err + } + lrItem.MaxLimitRequestRatio = el + } + if v, ok := limit["min"]; ok { + el, err := expandMapToResourceList(v.(map[string]interface{})) + if err != nil { + return out, err + } + lrItem.Min = el + } + + newLimits[i] = lrItem + } + + out.Limits = newLimits + } + + return out, nil +} + +func flattenLimitRangeSpec(in api.LimitRangeSpec) []interface{} { + out := make([]interface{}, 1) + limits := make([]interface{}, len(in.Limits), len(in.Limits)) + + for i, l := range in.Limits { + m := make(map[string]interface{}, 0) + m["default"] = flattenResourceList(l.Default) + m["default_request"] = flattenResourceList(l.DefaultRequest) + m["max"] = flattenResourceList(l.Max) + m["max_limit_request_ratio"] = flattenResourceList(l.MaxLimitRequestRatio) + m["min"] = flattenResourceList(l.Min) + m["type"] = string(l.Type) + + limits[i] = m + } + out[0] = map[string]interface{}{ + "limit": limits, + } + return out +} diff --git a/builtin/providers/kubernetes/validators.go b/builtin/providers/kubernetes/validators.go index 22309a34e..4fe12328b 100644 --- a/builtin/providers/kubernetes/validators.go +++ b/builtin/providers/kubernetes/validators.go @@ -4,6 +4,7 @@ import ( "fmt" "strings" + "k8s.io/kubernetes/pkg/api/resource" apiValidation "k8s.io/kubernetes/pkg/api/validation" utilValidation "k8s.io/kubernetes/pkg/util/validation" ) @@ -58,3 +59,24 @@ func validateLabels(value interface{}, key string) (ws []string, es []error) { } return } + +func validateResourceList(value interface{}, key string) (ws []string, es []error) { + m := value.(map[string]interface{}) + for k, value := range m { + if _, ok := value.(int); ok { + continue + } + + if v, ok := value.(string); ok { + _, err := resource.ParseQuantity(v) + if err != nil { + es = append(es, fmt.Errorf("%s.%s (%q): %s", key, k, v, err)) + } + continue + } + + err := "Value can be either string or int" + es = append(es, fmt.Errorf("%s.%s (%#v): %s", key, k, value, err)) + } + return +} diff --git a/builtin/providers/local/provider.go b/builtin/providers/local/provider.go new file mode 100644 index 000000000..ee048c689 --- /dev/null +++ b/builtin/providers/local/provider.go @@ -0,0 +1,15 @@ +package local + +import ( + "github.com/hashicorp/terraform/helper/schema" + "github.com/hashicorp/terraform/terraform" +) + +func Provider() terraform.ResourceProvider { + return &schema.Provider{ + Schema: map[string]*schema.Schema{}, + ResourcesMap: map[string]*schema.Resource{ + "local_file": resourceLocalFile(), + }, + } +} diff --git a/builtin/providers/local/provider_test.go b/builtin/providers/local/provider_test.go new file mode 100644 index 000000000..7385ffe3a --- /dev/null +++ b/builtin/providers/local/provider_test.go @@ -0,0 +1,18 @@ +package local + +import ( + "testing" + + "github.com/hashicorp/terraform/helper/schema" + "github.com/hashicorp/terraform/terraform" +) + +var testProviders = map[string]terraform.ResourceProvider{ + "local": Provider(), +} + +func TestProvider(t *testing.T) { + if err := Provider().(*schema.Provider).InternalValidate(); err != nil { + t.Fatalf("err: %s", err) + } +} diff --git a/builtin/providers/local/resource_local_file.go b/builtin/providers/local/resource_local_file.go new file mode 100644 index 000000000..6f6da1b94 --- /dev/null +++ b/builtin/providers/local/resource_local_file.go @@ -0,0 +1,84 @@ +package local + +import ( + "crypto/sha1" + "encoding/hex" + "io/ioutil" + "os" + "path" + + "github.com/hashicorp/terraform/helper/schema" +) + +func resourceLocalFile() *schema.Resource { + return &schema.Resource{ + Create: resourceLocalFileCreate, + Read: resourceLocalFileRead, + Delete: resourceLocalFileDelete, + + Schema: map[string]*schema.Schema{ + "content": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + "filename": { + Type: schema.TypeString, + Description: "Path to the output file", + Required: true, + ForceNew: true, + }, + }, + } +} + +func resourceLocalFileRead(d *schema.ResourceData, _ interface{}) error { + // If the output file doesn't exist, mark the resource for creation. + outputPath := d.Get("filename").(string) + if _, err := os.Stat(outputPath); os.IsNotExist(err) { + d.SetId("") + return nil + } + + // Verify that the content of the destination file matches the content we + // expect. Otherwise, the file might have been modified externally and we + // must reconcile. + outputContent, err := ioutil.ReadFile(outputPath) + if err != nil { + return err + } + + outputChecksum := sha1.Sum([]byte(outputContent)) + if hex.EncodeToString(outputChecksum[:]) != d.Id() { + d.SetId("") + return nil + } + + return nil +} + +func resourceLocalFileCreate(d *schema.ResourceData, _ interface{}) error { + content := d.Get("content").(string) + destination := d.Get("filename").(string) + + destinationDir := path.Dir(destination) + if _, err := os.Stat(destinationDir); err != nil { + if err := os.MkdirAll(destinationDir, 0777); err != nil { + return err + } + } + + if err := ioutil.WriteFile(destination, []byte(content), 0777); err != nil { + return err + } + + checksum := sha1.Sum([]byte(content)) + d.SetId(hex.EncodeToString(checksum[:])) + + return nil +} + +func resourceLocalFileDelete(d *schema.ResourceData, _ interface{}) error { + os.Remove(d.Get("filename").(string)) + return nil +} diff --git a/builtin/providers/local/resource_local_file_test.go b/builtin/providers/local/resource_local_file_test.go new file mode 100644 index 000000000..33a44f0bb --- /dev/null +++ b/builtin/providers/local/resource_local_file_test.go @@ -0,0 +1,56 @@ +package local + +import ( + "errors" + "fmt" + "io/ioutil" + "os" + "testing" + + r "github.com/hashicorp/terraform/helper/resource" + "github.com/hashicorp/terraform/terraform" +) + +func TestLocalFile_Basic(t *testing.T) { + var cases = []struct { + path string + content string + config string + }{ + { + "local_file", + "This is some content", + `resource "local_file" "file" { + content = "This is some content" + filename = "local_file" + }`, + }, + } + + for _, tt := range cases { + r.UnitTest(t, r.TestCase{ + Providers: testProviders, + Steps: []r.TestStep{ + { + Config: tt.config, + Check: func(s *terraform.State) error { + content, err := ioutil.ReadFile(tt.path) + if err != nil { + return fmt.Errorf("config:\n%s\n,got: %s\n", tt.config, err) + } + if string(content) != tt.content { + return fmt.Errorf("config:\n%s\ngot:\n%s\nwant:\n%s\n", tt.config, content, tt.content) + } + return nil + }, + }, + }, + CheckDestroy: func(*terraform.State) error { + if _, err := os.Stat(tt.path); os.IsNotExist(err) { + return nil + } + return errors.New("local_file did not get destroyed") + }, + }) + } +} diff --git a/builtin/providers/logentries/resource_logentries_log.go b/builtin/providers/logentries/resource_logentries_log.go index f5db7ecfc..ca183d499 100644 --- a/builtin/providers/logentries/resource_logentries_log.go +++ b/builtin/providers/logentries/resource_logentries_log.go @@ -2,9 +2,12 @@ package logentries import ( "fmt" + "log" + "strconv" + "strings" + "github.com/hashicorp/terraform/helper/schema" logentries "github.com/logentries/le_goclient" - "strconv" ) func resourceLogentriesLog() *schema.Resource { @@ -16,25 +19,25 @@ func resourceLogentriesLog() *schema.Resource { Delete: resourceLogentriesLogDelete, Schema: map[string]*schema.Schema{ - "token": &schema.Schema{ + "token": { Type: schema.TypeString, Computed: true, ForceNew: true, }, - "logset_id": &schema.Schema{ + "logset_id": { Type: schema.TypeString, Required: true, ForceNew: true, }, - "name": &schema.Schema{ + "name": { Type: schema.TypeString, Required: true, }, - "filename": &schema.Schema{ + "filename": { Type: schema.TypeString, Optional: true, }, - "retention_period": &schema.Schema{ + "retention_period": { Type: schema.TypeString, Optional: true, Default: "ACCOUNT_DEFAULT", @@ -47,7 +50,7 @@ func resourceLogentriesLog() *schema.Resource { return }, }, - "source": &schema.Schema{ + "source": { Type: schema.TypeString, Optional: true, Default: "token", @@ -60,7 +63,7 @@ func resourceLogentriesLog() *schema.Resource { return }, }, - "type": &schema.Schema{ + "type": { Type: schema.TypeString, Default: "", Optional: true, @@ -100,6 +103,11 @@ func resourceLogentriesLogRead(d *schema.ResourceData, meta interface{}) error { Key: d.Id(), }) if err != nil { + if strings.Contains(err.Error(), "not found") { + log.Printf("Logentries Log Not Found - Refreshing from State") + d.SetId("") + return nil + } return err } diff --git a/builtin/providers/logentries/resource_logentries_logset.go b/builtin/providers/logentries/resource_logentries_logset.go index d12076953..3c5aac6d0 100644 --- a/builtin/providers/logentries/resource_logentries_logset.go +++ b/builtin/providers/logentries/resource_logentries_logset.go @@ -1,8 +1,11 @@ package logentries import ( + "log" + "strings" + "github.com/hashicorp/terraform/helper/schema" - "github.com/logentries/le_goclient" + logentries "github.com/logentries/le_goclient" ) func resourceLogentriesLogSet() *schema.Resource { @@ -49,6 +52,11 @@ func resourceLogentriesLogSetRead(d *schema.ResourceData, meta interface{}) erro Key: d.Id(), }) if err != nil { + if strings.Contains(err.Error(), "No such log set") { + log.Printf("Logentries LogSet Not Found - Refreshing from State") + d.SetId("") + return nil + } return err } diff --git a/builtin/providers/newrelic/resource_newrelic_alert_condition.go b/builtin/providers/newrelic/resource_newrelic_alert_condition.go index db8ba3c9c..1021d9af2 100644 --- a/builtin/providers/newrelic/resource_newrelic_alert_condition.go +++ b/builtin/providers/newrelic/resource_newrelic_alert_condition.go @@ -106,6 +106,10 @@ func resourceNewRelicAlertCondition() *schema.Resource { Type: schema.TypeString, Optional: true, }, + "condition_scope": { + Type: schema.TypeString, + Optional: true, + }, "term": { Type: schema.TypeList, Elem: &schema.Resource{ @@ -186,6 +190,7 @@ func buildAlertConditionStruct(d *schema.ResourceData) *newrelic.AlertCondition Metric: d.Get("metric").(string), Terms: terms, PolicyID: d.Get("policy_id").(int), + Scope: d.Get("condition_scope").(string), } if attr, ok := d.GetOk("runbook_url"); ok { @@ -226,6 +231,7 @@ func readAlertConditionStruct(condition *newrelic.AlertCondition, d *schema.Reso d.Set("type", condition.Type) d.Set("metric", condition.Metric) d.Set("runbook_url", condition.RunbookURL) + d.Set("condition_scope", condition.Scope) d.Set("user_defined_metric", condition.UserDefined.Metric) d.Set("user_defined_value_function", condition.UserDefined.ValueFunction) if err := d.Set("entities", entities); err != nil { diff --git a/builtin/providers/newrelic/resource_newrelic_alert_condition_test.go b/builtin/providers/newrelic/resource_newrelic_alert_condition_test.go index b9c608a83..a46938d82 100644 --- a/builtin/providers/newrelic/resource_newrelic_alert_condition_test.go +++ b/builtin/providers/newrelic/resource_newrelic_alert_condition_test.go @@ -29,8 +29,6 @@ func TestAccNewRelicAlertCondition_Basic(t *testing.T) { "newrelic_alert_condition.foo", "runbook_url", "https://foo.example.com"), resource.TestCheckResourceAttr( "newrelic_alert_condition.foo", "entities.#", "1"), - resource.TestCheckResourceAttr( - "newrelic_alert_condition.foo", "entities.0", "12345"), resource.TestCheckResourceAttr( "newrelic_alert_condition.foo", "term.#", "1"), resource.TestCheckResourceAttr( @@ -55,8 +53,6 @@ func TestAccNewRelicAlertCondition_Basic(t *testing.T) { "newrelic_alert_condition.foo", "runbook_url", "https://bar.example.com"), resource.TestCheckResourceAttr( "newrelic_alert_condition.foo", "entities.#", "1"), - resource.TestCheckResourceAttr( - "newrelic_alert_condition.foo", "entities.0", "67890"), resource.TestCheckResourceAttr( "newrelic_alert_condition.foo", "term.#", "1"), resource.TestCheckResourceAttr( @@ -136,6 +132,10 @@ func testAccCheckNewRelicAlertConditionExists(n string) resource.TestCheckFunc { func testAccCheckNewRelicAlertConditionConfig(rName string) string { return fmt.Sprintf(` +data "newrelic_application" "app" { + name = "%[2]s" +} + resource "newrelic_alert_policy" "foo" { name = "tf-test-%[1]s" } @@ -143,11 +143,12 @@ resource "newrelic_alert_policy" "foo" { resource "newrelic_alert_condition" "foo" { policy_id = "${newrelic_alert_policy.foo.id}" - name = "tf-test-%[1]s" - type = "apm_app_metric" - entities = ["12345"] - metric = "apdex" - runbook_url = "https://foo.example.com" + name = "tf-test-%[1]s" + type = "apm_app_metric" + entities = ["${data.newrelic_application.app.id}"] + metric = "apdex" + runbook_url = "https://foo.example.com" + condition_scope = "application" term { duration = 5 @@ -157,11 +158,15 @@ resource "newrelic_alert_condition" "foo" { time_function = "all" } } -`, rName) +`, rName, testAccExpectedApplicationName) } func testAccCheckNewRelicAlertConditionConfigUpdated(rName string) string { return fmt.Sprintf(` +data "newrelic_application" "app" { + name = "%[2]s" +} + resource "newrelic_alert_policy" "foo" { name = "tf-test-updated-%[1]s" } @@ -169,11 +174,12 @@ resource "newrelic_alert_policy" "foo" { resource "newrelic_alert_condition" "foo" { policy_id = "${newrelic_alert_policy.foo.id}" - name = "tf-test-updated-%[1]s" - type = "apm_app_metric" - entities = ["67890"] - metric = "apdex" - runbook_url = "https://bar.example.com" + name = "tf-test-updated-%[1]s" + type = "apm_app_metric" + entities = ["${data.newrelic_application.app.id}"] + metric = "apdex" + runbook_url = "https://bar.example.com" + condition_scope = "application" term { duration = 10 @@ -183,7 +189,7 @@ resource "newrelic_alert_condition" "foo" { time_function = "all" } } -`, rName) +`, rName, testAccExpectedApplicationName) } // TODO: const testAccCheckNewRelicAlertConditionConfigMulti = ` diff --git a/builtin/providers/nomad/provider.go b/builtin/providers/nomad/provider.go index d23c4ad97..61f8603bc 100644 --- a/builtin/providers/nomad/provider.go +++ b/builtin/providers/nomad/provider.go @@ -24,6 +24,24 @@ func Provider() terraform.ResourceProvider { DefaultFunc: schema.EnvDefaultFunc("NOMAD_REGION", ""), Description: "Region of the target Nomad agent.", }, + "ca_file": &schema.Schema{ + Type: schema.TypeString, + Optional: true, + DefaultFunc: schema.EnvDefaultFunc("NOMAD_CACERT", ""), + Description: "A path to a PEM-encoded certificate authority used to verify the remote agent's certificate.", + }, + "cert_file": &schema.Schema{ + Type: schema.TypeString, + Optional: true, + DefaultFunc: schema.EnvDefaultFunc("NOMAD_CLIENT_CERT", ""), + Description: "A path to a PEM-encoded certificate provided to the remote agent; requires use of key_file.", + }, + "key_file": &schema.Schema{ + Type: schema.TypeString, + Optional: true, + DefaultFunc: schema.EnvDefaultFunc("NOMAD_CLIENT_KEY", ""), + Description: "A path to a PEM-encoded private key, required if cert_file is specified.", + }, }, ConfigureFunc: providerConfigure, @@ -38,6 +56,9 @@ func providerConfigure(d *schema.ResourceData) (interface{}, error) { config := api.DefaultConfig() config.Address = d.Get("address").(string) config.Region = d.Get("region").(string) + config.TLSConfig.CACert = d.Get("ca_file").(string) + config.TLSConfig.ClientCert = d.Get("cert_file").(string) + config.TLSConfig.ClientKey = d.Get("key_file").(string) client, err := api.NewClient(config) if err != nil { diff --git a/builtin/providers/nomad/resource_job_test.go b/builtin/providers/nomad/resource_job_test.go index c43f5aa1f..7e71ce6b9 100644 --- a/builtin/providers/nomad/resource_job_test.go +++ b/builtin/providers/nomad/resource_job_test.go @@ -207,15 +207,17 @@ func testResourceJob_checkExists(s *terraform.State) error { func testResourceJob_checkDestroy(jobID string) r.TestCheckFunc { return func(*terraform.State) error { client := testProvider.Meta().(*api.Client) - _, _, err := client.Jobs().Info(jobID, nil) - if err != nil && strings.Contains(err.Error(), "404") { + job, _, err := client.Jobs().Info(jobID, nil) + // This should likely never happen, due to how nomad caches jobs + if err != nil && strings.Contains(err.Error(), "404") || job == nil { return nil } - if err == nil { - err = errors.New("not destroyed") + + if job.Status != "dead" { + return fmt.Errorf("Job %q has not been stopped. Status: %s", jobID, job.Status) } - return err + return nil } } @@ -284,9 +286,16 @@ func testResourceJob_updateCheck(s *terraform.State) error { { // Verify foo doesn't exist - _, _, err := client.Jobs().Info("foo", nil) - if err == nil { - return errors.New("reading foo success") + job, _, err := client.Jobs().Info("foo", nil) + if err != nil { + // Job could have already been purged from nomad server + if !strings.Contains(err.Error(), "(job not found)") { + return fmt.Errorf("error reading %q job: %s", "foo", err) + } + return nil + } + if job.Status != "dead" { + return fmt.Errorf("%q job is not dead. Status: %q", "foo", job.Status) } } diff --git a/builtin/providers/ns1/resource_record.go b/builtin/providers/ns1/resource_record.go index 88b1a96c9..add703c3a 100644 --- a/builtin/providers/ns1/resource_record.go +++ b/builtin/providers/ns1/resource_record.go @@ -236,7 +236,7 @@ func resourceDataToRecord(r *dns.Record, d *schema.ResourceData) error { var a *dns.Answer v := answer["answer"].(string) switch d.Get("type") { - case "TXT": + case "TXT", "SPF": a = dns.NewTXTAnswer(v) default: a = dns.NewAnswer(strings.Split(v, " ")) diff --git a/builtin/providers/ns1/resource_record_test.go b/builtin/providers/ns1/resource_record_test.go index e73a143cc..ec5075303 100644 --- a/builtin/providers/ns1/resource_record_test.go +++ b/builtin/providers/ns1/resource_record_test.go @@ -29,7 +29,7 @@ func TestAccRecord_basic(t *testing.T) { testAccCheckRecordUseClientSubnet(&record, true), testAccCheckRecordRegionName(&record, []string{"cal"}), // testAccCheckRecordAnswerMetaWeight(&record, 10), - testAccCheckRecordAnswerRdata(&record, "test1.terraform-record-test.io"), + testAccCheckRecordAnswerRdata(&record, 0, "test1.terraform-record-test.io"), ), }, }, @@ -52,7 +52,7 @@ func TestAccRecord_updated(t *testing.T) { testAccCheckRecordUseClientSubnet(&record, true), testAccCheckRecordRegionName(&record, []string{"cal"}), // testAccCheckRecordAnswerMetaWeight(&record, 10), - testAccCheckRecordAnswerRdata(&record, "test1.terraform-record-test.io"), + testAccCheckRecordAnswerRdata(&record, 0, "test1.terraform-record-test.io"), ), }, resource.TestStep{ @@ -64,7 +64,52 @@ func TestAccRecord_updated(t *testing.T) { testAccCheckRecordUseClientSubnet(&record, false), testAccCheckRecordRegionName(&record, []string{"ny", "wa"}), // testAccCheckRecordAnswerMetaWeight(&record, 5), - testAccCheckRecordAnswerRdata(&record, "test2.terraform-record-test.io"), + testAccCheckRecordAnswerRdata(&record, 0, "test2.terraform-record-test.io"), + ), + }, + }, + }) +} + +func TestAccRecord_SPF(t *testing.T) { + var record dns.Record + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckRecordDestroy, + Steps: []resource.TestStep{ + resource.TestStep{ + Config: testAccRecordSPF, + Check: resource.ComposeTestCheckFunc( + testAccCheckRecordExists("ns1_record.spf", &record), + testAccCheckRecordDomain(&record, "terraform-record-test.io"), + testAccCheckRecordTTL(&record, 86400), + testAccCheckRecordUseClientSubnet(&record, true), + testAccCheckRecordAnswerRdata(&record, 0, "v=DKIM1; k=rsa; p=XXXXXXXX"), + ), + }, + }, + }) +} + +func TestAccRecord_SRV(t *testing.T) { + var record dns.Record + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckRecordDestroy, + Steps: []resource.TestStep{ + resource.TestStep{ + Config: testAccRecordSRV, + Check: resource.ComposeTestCheckFunc( + testAccCheckRecordExists("ns1_record.srv", &record), + testAccCheckRecordDomain(&record, "_some-server._tcp.terraform-record-test.io"), + testAccCheckRecordTTL(&record, 86400), + testAccCheckRecordUseClientSubnet(&record, true), + testAccCheckRecordAnswerRdata(&record, 0, "10"), + testAccCheckRecordAnswerRdata(&record, 1, "0"), + testAccCheckRecordAnswerRdata(&record, 2, "2380"), + testAccCheckRecordAnswerRdata(&record, 3, "node-1.terraform-record-test.io"), ), }, }, @@ -185,12 +230,12 @@ func testAccCheckRecordAnswerMetaWeight(r *dns.Record, expected float64) resourc } } -func testAccCheckRecordAnswerRdata(r *dns.Record, expected string) resource.TestCheckFunc { +func testAccCheckRecordAnswerRdata(r *dns.Record, idx int, expected string) resource.TestCheckFunc { return func(s *terraform.State) error { recordAnswer := r.Answers[0] - recordAnswerString := recordAnswer.Rdata[0] + recordAnswerString := recordAnswer.Rdata[idx] if recordAnswerString != expected { - return fmt.Errorf("Answers[0].Rdata[0]: got: %#v want: %#v", recordAnswerString, expected) + return fmt.Errorf("Answers[0].Rdata[%d]: got: %#v want: %#v", idx, recordAnswerString, expected) } return nil } @@ -297,3 +342,37 @@ resource "ns1_zone" "test" { zone = "terraform-record-test.io" } ` + +const testAccRecordSPF = ` +resource "ns1_record" "spf" { + zone = "${ns1_zone.test.zone}" + domain = "${ns1_zone.test.zone}" + type = "SPF" + ttl = 86400 + use_client_subnet = "true" + answers = { + answer = "v=DKIM1; k=rsa; p=XXXXXXXX" + } +} + +resource "ns1_zone" "test" { + zone = "terraform-record-test.io" +} +` + +const testAccRecordSRV = ` +resource "ns1_record" "srv" { + zone = "${ns1_zone.test.zone}" + domain = "_some-server._tcp.${ns1_zone.test.zone}" + type = "SRV" + ttl = 86400 + use_client_subnet = "true" + answers { + answer = "10 0 2380 node-1.${ns1_zone.test.zone}" + } +} + +resource "ns1_zone" "test" { + zone = "terraform-record-test.io" +} +` diff --git a/builtin/providers/oneandone/config.go b/builtin/providers/oneandone/config.go new file mode 100644 index 000000000..1192c84e7 --- /dev/null +++ b/builtin/providers/oneandone/config.go @@ -0,0 +1,24 @@ +package oneandone + +import ( + "github.com/1and1/oneandone-cloudserver-sdk-go" +) + +type Config struct { + Token string + Retries int + Endpoint string + API *oneandone.API +} + +func (c *Config) Client() (*Config, error) { + token := oneandone.SetToken(c.Token) + + if len(c.Endpoint) > 0 { + c.API = oneandone.New(token, c.Endpoint) + } else { + c.API = oneandone.New(token, oneandone.BaseUrl) + } + + return c, nil +} diff --git a/builtin/providers/oneandone/provider.go b/builtin/providers/oneandone/provider.go new file mode 100644 index 000000000..8cc65f19b --- /dev/null +++ b/builtin/providers/oneandone/provider.go @@ -0,0 +1,56 @@ +package oneandone + +import ( + "github.com/1and1/oneandone-cloudserver-sdk-go" + "github.com/hashicorp/terraform/helper/schema" + "github.com/hashicorp/terraform/terraform" +) + +func Provider() terraform.ResourceProvider { + return &schema.Provider{ + Schema: map[string]*schema.Schema{ + "token": { + Type: schema.TypeString, + Required: true, + DefaultFunc: schema.EnvDefaultFunc("ONEANDONE_TOKEN", nil), + Description: "1&1 token for API operations.", + }, + "retries": { + Type: schema.TypeInt, + Optional: true, + Default: 50, + DefaultFunc: schema.EnvDefaultFunc("ONEANDONE_RETRIES", nil), + }, + "endpoint": { + Type: schema.TypeString, + Optional: true, + Default: oneandone.BaseUrl, + DefaultFunc: schema.EnvDefaultFunc("ONEANDONE_ENDPOINT", nil), + }, + }, + ResourcesMap: map[string]*schema.Resource{ + "oneandone_server": resourceOneandOneServer(), + "oneandone_firewall_policy": resourceOneandOneFirewallPolicy(), + "oneandone_private_network": resourceOneandOnePrivateNetwork(), + "oneandone_public_ip": resourceOneandOnePublicIp(), + "oneandone_shared_storage": resourceOneandOneSharedStorage(), + "oneandone_monitoring_policy": resourceOneandOneMonitoringPolicy(), + "oneandone_loadbalancer": resourceOneandOneLoadbalancer(), + "oneandone_vpn": resourceOneandOneVPN(), + }, + ConfigureFunc: providerConfigure, + } +} + +func providerConfigure(d *schema.ResourceData) (interface{}, error) { + var endpoint string + if d.Get("endpoint").(string) != oneandone.BaseUrl { + endpoint = d.Get("endpoint").(string) + } + config := Config{ + Token: d.Get("token").(string), + Retries: d.Get("retries").(int), + Endpoint: endpoint, + } + return config.Client() +} diff --git a/builtin/providers/oneandone/provider_test.go b/builtin/providers/oneandone/provider_test.go new file mode 100644 index 000000000..2057aac6d --- /dev/null +++ b/builtin/providers/oneandone/provider_test.go @@ -0,0 +1,36 @@ +package oneandone + +import ( + "os" + "testing" + + "github.com/hashicorp/terraform/helper/schema" + "github.com/hashicorp/terraform/terraform" +) + +// +var testAccProviders map[string]terraform.ResourceProvider +var testAccProvider *schema.Provider + +func init() { + testAccProvider = Provider().(*schema.Provider) + testAccProviders = map[string]terraform.ResourceProvider{ + "oneandone": testAccProvider, + } +} + +func TestProvider(t *testing.T) { + if err := Provider().(*schema.Provider).InternalValidate(); err != nil { + t.Fatalf("err: %s", err) + } +} + +func TestProvider_impl(t *testing.T) { + var _ terraform.ResourceProvider = Provider() +} + +func testAccPreCheck(t *testing.T) { + if v := os.Getenv("ONEANDONE_TOKEN"); v == "" { + t.Fatal("ONEANDONE_TOKEN must be set for acceptance tests") + } +} diff --git a/builtin/providers/oneandone/resource_oneandone_firewall_policy.go b/builtin/providers/oneandone/resource_oneandone_firewall_policy.go new file mode 100644 index 000000000..c62b63b5c --- /dev/null +++ b/builtin/providers/oneandone/resource_oneandone_firewall_policy.go @@ -0,0 +1,274 @@ +package oneandone + +import ( + "github.com/1and1/oneandone-cloudserver-sdk-go" + "github.com/hashicorp/terraform/helper/schema" + "github.com/hashicorp/terraform/helper/validation" + "strings" +) + +func resourceOneandOneFirewallPolicy() *schema.Resource { + return &schema.Resource{ + + Create: resourceOneandOneFirewallCreate, + Read: resourceOneandOneFirewallRead, + Update: resourceOneandOneFirewallUpdate, + Delete: resourceOneandOneFirewallDelete, + Schema: map[string]*schema.Schema{ + "name": { + Type: schema.TypeString, + Required: true, + }, + "description": { + Type: schema.TypeString, + Optional: true, + }, + "rules": { + Type: schema.TypeList, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "protocol": { + Type: schema.TypeString, + Required: true, + }, + "port_from": { + Type: schema.TypeInt, + Optional: true, + ValidateFunc: validation.IntBetween(1, 65535), + }, + "port_to": { + Type: schema.TypeInt, + Optional: true, + ValidateFunc: validation.IntBetween(1, 65535), + }, + "source_ip": { + Type: schema.TypeString, + Optional: true, + }, + "id": { + Type: schema.TypeString, + Computed: true, + }, + }, + }, + Required: true, + }, + }, + } +} + +func resourceOneandOneFirewallCreate(d *schema.ResourceData, meta interface{}) error { + config := meta.(*Config) + + req := oneandone.FirewallPolicyRequest{ + Name: d.Get("name").(string), + } + + if desc, ok := d.GetOk("description"); ok { + req.Description = desc.(string) + } + + req.Rules = getRules(d) + + fw_id, fw, err := config.API.CreateFirewallPolicy(&req) + if err != nil { + return err + } + + err = config.API.WaitForState(fw, "ACTIVE", 10, config.Retries) + if err != nil { + return err + } + + d.SetId(fw_id) + + if err != nil { + return err + } + + return resourceOneandOneFirewallRead(d, meta) +} + +func resourceOneandOneFirewallUpdate(d *schema.ResourceData, meta interface{}) error { + config := meta.(*Config) + if d.HasChange("name") || d.HasChange("description") { + fw, err := config.API.UpdateFirewallPolicy(d.Id(), d.Get("name").(string), d.Get("description").(string)) + if err != nil { + return err + } + err = config.API.WaitForState(fw, "ACTIVE", 10, config.Retries) + if err != nil { + return err + } + } + + if d.HasChange("rules") { + oldR, newR := d.GetChange("rules") + oldValues := oldR.([]interface{}) + newValues := newR.([]interface{}) + if len(oldValues) > len(newValues) { + diff := difference(oldValues, newValues) + for _, old := range diff { + o := old.(map[string]interface{}) + if o["id"] != nil { + old_id := o["id"].(string) + fw, err := config.API.DeleteFirewallPolicyRule(d.Id(), old_id) + if err != nil { + return err + } + + err = config.API.WaitForState(fw, "ACTIVE", 10, config.Retries) + if err != nil { + return err + } + } + } + } else { + var rules []oneandone.FirewallPolicyRule + + for _, raw := range newValues { + rl := raw.(map[string]interface{}) + + if rl["id"].(string) == "" { + rule := oneandone.FirewallPolicyRule{ + Protocol: rl["protocol"].(string), + } + + if rl["port_from"] != nil { + rule.PortFrom = oneandone.Int2Pointer(rl["port_from"].(int)) + } + if rl["port_to"] != nil { + rule.PortTo = oneandone.Int2Pointer(rl["port_to"].(int)) + } + + if rl["source_ip"] != nil { + rule.SourceIp = rl["source_ip"].(string) + } + + rules = append(rules, rule) + } + } + + if len(rules) > 0 { + fw, err := config.API.AddFirewallPolicyRules(d.Id(), rules) + if err != nil { + return err + } + + err = config.API.WaitForState(fw, "ACTIVE", 10, config.Retries) + } + } + } + + return resourceOneandOneFirewallRead(d, meta) +} + +func resourceOneandOneFirewallRead(d *schema.ResourceData, meta interface{}) error { + config := meta.(*Config) + + fw, err := config.API.GetFirewallPolicy(d.Id()) + if err != nil { + if strings.Contains(err.Error(), "404") { + d.SetId("") + return nil + } + return err + } + + d.Set("rules", readRules(d, fw.Rules)) + d.Set("description", fw.Description) + + return nil +} + +func resourceOneandOneFirewallDelete(d *schema.ResourceData, meta interface{}) error { + config := meta.(*Config) + + fp, err := config.API.DeleteFirewallPolicy(d.Id()) + if err != nil { + return err + } + + err = config.API.WaitUntilDeleted(fp) + if err != nil { + return err + } + + return nil +} + +func readRules(d *schema.ResourceData, rules []oneandone.FirewallPolicyRule) interface{} { + rawRules := d.Get("rules").([]interface{}) + counter := 0 + for _, rR := range rawRules { + if len(rules) > counter { + rawMap := rR.(map[string]interface{}) + rawMap["id"] = rules[counter].Id + if rules[counter].SourceIp != "0.0.0.0" { + rawMap["source_ip"] = rules[counter].SourceIp + } + } + counter++ + } + + return rawRules +} + +func getRules(d *schema.ResourceData) []oneandone.FirewallPolicyRule { + var rules []oneandone.FirewallPolicyRule + + if raw, ok := d.GetOk("rules"); ok { + rawRules := raw.([]interface{}) + + for _, raw := range rawRules { + rl := raw.(map[string]interface{}) + rule := oneandone.FirewallPolicyRule{ + Protocol: rl["protocol"].(string), + } + + if rl["port_from"] != nil { + rule.PortFrom = oneandone.Int2Pointer(rl["port_from"].(int)) + } + if rl["port_to"] != nil { + rule.PortTo = oneandone.Int2Pointer(rl["port_to"].(int)) + } + + if rl["source_ip"] != nil { + rule.SourceIp = rl["source_ip"].(string) + } + + rules = append(rules, rule) + } + } + return rules +} + +func difference(oldV, newV []interface{}) (toreturn []interface{}) { + var ( + lenMin int + longest []interface{} + ) + // Determine the shortest length and the longest slice + if len(oldV) < len(newV) { + lenMin = len(oldV) + longest = newV + } else { + lenMin = len(newV) + longest = oldV + } + // compare common indeces + for i := 0; i < lenMin; i++ { + if oldV[i] == nil || newV[i] == nil { + continue + } + if oldV[i].(map[string]interface{})["id"] != newV[i].(map[string]interface{})["id"] { + toreturn = append(toreturn, newV) //out += fmt.Sprintf("=>\t%s\t%s\n", oldV[i], newV[i]) + } + } + // add indeces not in common + for _, v := range longest[lenMin:] { + //out += fmt.Sprintf("=>\t%s\n", v) + toreturn = append(toreturn, v) + } + return toreturn +} diff --git a/builtin/providers/oneandone/resource_oneandone_firewall_policy_test.go b/builtin/providers/oneandone/resource_oneandone_firewall_policy_test.go new file mode 100644 index 000000000..146d63c3c --- /dev/null +++ b/builtin/providers/oneandone/resource_oneandone_firewall_policy_test.go @@ -0,0 +1,178 @@ +package oneandone + +import ( + "fmt" + "testing" + + "github.com/1and1/oneandone-cloudserver-sdk-go" + "github.com/hashicorp/terraform/helper/resource" + "github.com/hashicorp/terraform/terraform" + "os" + "time" +) + +func TestAccOneandoneFirewall_Basic(t *testing.T) { + var firewall oneandone.FirewallPolicy + + name := "test" + name_updated := "test1" + + resource.Test(t, resource.TestCase{ + PreCheck: func() { + testAccPreCheck(t) + }, + Providers: testAccProviders, + CheckDestroy: testAccCheckDOneandoneFirewallDestroyCheck, + Steps: []resource.TestStep{ + resource.TestStep{ + Config: fmt.Sprintf(testAccCheckOneandoneFirewall_basic, name), + + Check: resource.ComposeTestCheckFunc( + func(*terraform.State) error { + time.Sleep(10 * time.Second) + return nil + }, + testAccCheckOneandoneFirewallExists("oneandone_firewall_policy.fw", &firewall), + testAccCheckOneandoneFirewallAttributes("oneandone_firewall_policy.fw", name), + resource.TestCheckResourceAttr("oneandone_firewall_policy.fw", "name", name), + ), + }, + resource.TestStep{ + Config: fmt.Sprintf(testAccCheckOneandoneFirewall_update, name_updated), + + Check: resource.ComposeTestCheckFunc( + func(*terraform.State) error { + time.Sleep(10 * time.Second) + return nil + }, + testAccCheckOneandoneFirewallExists("oneandone_firewall_policy.fw", &firewall), + testAccCheckOneandoneFirewallAttributes("oneandone_firewall_policy.fw", name_updated), + resource.TestCheckResourceAttr("oneandone_firewall_policy.fw", "name", name_updated), + ), + }, + }, + }) +} + +func testAccCheckDOneandoneFirewallDestroyCheck(s *terraform.State) error { + for _, rs := range s.RootModule().Resources { + if rs.Type != "oneandone_firewall_policy.fw" { + continue + } + + api := oneandone.New(os.Getenv("ONEANDONE_TOKEN"), oneandone.BaseUrl) + + _, err := api.GetFirewallPolicy(rs.Primary.ID) + + if err == nil { + return fmt.Errorf("Firewall Policy still exists %s %s", rs.Primary.ID, err.Error()) + } + } + + return nil +} +func testAccCheckOneandoneFirewallAttributes(n string, reverse_dns string) resource.TestCheckFunc { + return func(s *terraform.State) error { + rs, ok := s.RootModule().Resources[n] + if !ok { + return fmt.Errorf("Not found: %s", n) + } + if rs.Primary.Attributes["name"] != reverse_dns { + return fmt.Errorf("Bad name: expected %s : found %s ", reverse_dns, rs.Primary.Attributes["name"]) + } + + return nil + } +} + +func testAccCheckOneandoneFirewallExists(n string, fw_p *oneandone.FirewallPolicy) resource.TestCheckFunc { + return func(s *terraform.State) error { + rs, ok := s.RootModule().Resources[n] + + if !ok { + return fmt.Errorf("Not found: %s", n) + } + + if rs.Primary.ID == "" { + return fmt.Errorf("No Record ID is set") + } + + api := oneandone.New(os.Getenv("ONEANDONE_TOKEN"), oneandone.BaseUrl) + + found_fw, err := api.GetFirewallPolicy(rs.Primary.ID) + + if err != nil { + return fmt.Errorf("Error occured while fetching Firewall Policy: %s", rs.Primary.ID) + } + if found_fw.Id != rs.Primary.ID { + return fmt.Errorf("Record not found") + } + fw_p = found_fw + + return nil + } +} + +const testAccCheckOneandoneFirewall_basic = ` +resource "oneandone_firewall_policy" "fw" { + name = "%s" + rules = [ + { + "protocol" = "TCP" + "port_from" = 80 + "port_to" = 80 + "source_ip" = "0.0.0.0" + }, + { + "protocol" = "ICMP" + "source_ip" = "0.0.0.0" + }, + { + "protocol" = "TCP" + "port_from" = 43 + "port_to" = 43 + "source_ip" = "0.0.0.0" + }, + { + "protocol" = "TCP" + "port_from" = 22 + "port_to" = 22 + "source_ip" = "0.0.0.0" + } + ] +}` + +const testAccCheckOneandoneFirewall_update = ` +resource "oneandone_firewall_policy" "fw" { + name = "%s" + rules = [ + { + "protocol" = "TCP" + "port_from" = 80 + "port_to" = 80 + "source_ip" = "0.0.0.0" + }, + { + "protocol" = "ICMP" + "source_ip" = "0.0.0.0" + }, + { + "protocol" = "TCP" + "port_from" = 43 + "port_to" = 43 + "source_ip" = "0.0.0.0" + }, + { + "protocol" = "TCP" + "port_from" = 22 + "port_to" = 22 + "source_ip" = "0.0.0.0" + }, + { + "protocol" = "TCP" + "port_from" = 88 + "port_to" = 88 + "source_ip" = "0.0.0.0" + }, + ] +}` diff --git a/builtin/providers/oneandone/resource_oneandone_loadbalancer.go b/builtin/providers/oneandone/resource_oneandone_loadbalancer.go new file mode 100644 index 000000000..627ec51df --- /dev/null +++ b/builtin/providers/oneandone/resource_oneandone_loadbalancer.go @@ -0,0 +1,370 @@ +package oneandone + +import ( + "fmt" + "github.com/1and1/oneandone-cloudserver-sdk-go" + "github.com/hashicorp/terraform/helper/schema" + "github.com/hashicorp/terraform/helper/validation" + "log" + "strings" +) + +func resourceOneandOneLoadbalancer() *schema.Resource { + return &schema.Resource{ + Create: resourceOneandOneLoadbalancerCreate, + Read: resourceOneandOneLoadbalancerRead, + Update: resourceOneandOneLoadbalancerUpdate, + Delete: resourceOneandOneLoadbalancerDelete, + Schema: map[string]*schema.Schema{ + + "name": { + Type: schema.TypeString, + Required: true, + }, + "description": { + Type: schema.TypeString, + Optional: true, + }, + "method": { + Type: schema.TypeString, + Required: true, + ValidateFunc: validateMethod, + }, + "datacenter": { + Type: schema.TypeString, + Optional: true, + }, + "persistence": { + Type: schema.TypeBool, + Optional: true, + }, + "persistence_time": { + Type: schema.TypeInt, + Optional: true, + }, + "health_check_test": { + Type: schema.TypeString, + Optional: true, + }, + "health_check_interval": { + Type: schema.TypeInt, + Optional: true, + }, + "health_check_path": { + Type: schema.TypeString, + Optional: true, + }, + "health_check_path_parser": { + Type: schema.TypeString, + Optional: true, + }, + "rules": { + Type: schema.TypeList, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "protocol": { + Type: schema.TypeString, + Required: true, + }, + "port_balancer": { + Type: schema.TypeInt, + Required: true, + ValidateFunc: validation.IntBetween(1, 65535), + }, + "port_server": { + Type: schema.TypeInt, + Required: true, + ValidateFunc: validation.IntBetween(1, 65535), + }, + "source_ip": { + Type: schema.TypeString, + Required: true, + }, + "id": { + Type: schema.TypeString, + Computed: true, + }, + }, + }, + Required: true, + }, + }, + } +} + +func resourceOneandOneLoadbalancerCreate(d *schema.ResourceData, meta interface{}) error { + config := meta.(*Config) + + req := oneandone.LoadBalancerRequest{ + Name: d.Get("name").(string), + Rules: getLBRules(d), + } + + if raw, ok := d.GetOk("description"); ok { + req.Description = raw.(string) + } + + if raw, ok := d.GetOk("datacenter"); ok { + dcs, err := config.API.ListDatacenters() + if err != nil { + return fmt.Errorf("An error occured while fetching list of datacenters %s", err) + } + + decenter := raw.(string) + for _, dc := range dcs { + if strings.ToLower(dc.CountryCode) == strings.ToLower(decenter) { + req.DatacenterId = dc.Id + break + } + } + } + + if raw, ok := d.GetOk("method"); ok { + req.Method = raw.(string) + } + + if raw, ok := d.GetOk("persistence"); ok { + req.Persistence = oneandone.Bool2Pointer(raw.(bool)) + } + if raw, ok := d.GetOk("persistence_time"); ok { + req.PersistenceTime = oneandone.Int2Pointer(raw.(int)) + } + + if raw, ok := d.GetOk("health_check_test"); ok { + req.HealthCheckTest = raw.(string) + } + if raw, ok := d.GetOk("health_check_interval"); ok { + req.HealthCheckInterval = oneandone.Int2Pointer(raw.(int)) + } + if raw, ok := d.GetOk("health_check_path"); ok { + req.HealthCheckPath = raw.(string) + } + if raw, ok := d.GetOk("health_check_path_parser"); ok { + req.HealthCheckPathParser = raw.(string) + } + + lb_id, lb, err := config.API.CreateLoadBalancer(&req) + if err != nil { + return err + } + + err = config.API.WaitForState(lb, "ACTIVE", 10, config.Retries) + if err != nil { + return err + } + + d.SetId(lb_id) + + return resourceOneandOneLoadbalancerRead(d, meta) +} + +func getLBRules(d *schema.ResourceData) []oneandone.LoadBalancerRule { + var rules []oneandone.LoadBalancerRule + + if raw, ok := d.GetOk("rules"); ok { + rawRules := raw.([]interface{}) + log.Println("[DEBUG] raw rules:", raw) + for _, raw := range rawRules { + rl := raw.(map[string]interface{}) + rule := oneandone.LoadBalancerRule{ + Protocol: rl["protocol"].(string), + } + + if rl["port_balancer"] != nil { + rule.PortBalancer = uint16(rl["port_balancer"].(int)) + } + if rl["port_server"] != nil { + rule.PortServer = uint16(rl["port_server"].(int)) + } + + if rl["source_ip"] != nil { + rule.Source = rl["source_ip"].(string) + } + + rules = append(rules, rule) + } + } + return rules +} + +func resourceOneandOneLoadbalancerUpdate(d *schema.ResourceData, meta interface{}) error { + config := meta.(*Config) + + if d.HasChange("name") || d.HasChange("description") || d.HasChange("method") || d.HasChange("persistence") || d.HasChange("persistence_time") || d.HasChange("health_check_test") || d.HasChange("health_check_interval") { + lb := oneandone.LoadBalancerRequest{} + if d.HasChange("name") { + _, n := d.GetChange("name") + lb.Name = n.(string) + } + if d.HasChange("description") { + _, n := d.GetChange("description") + lb.Description = n.(string) + } + if d.HasChange("method") { + _, n := d.GetChange("method") + lb.Method = (n.(string)) + } + if d.HasChange("persistence") { + _, n := d.GetChange("persistence") + lb.Persistence = oneandone.Bool2Pointer(n.(bool)) + } + if d.HasChange("persistence_time") { + _, n := d.GetChange("persistence_time") + lb.PersistenceTime = oneandone.Int2Pointer(n.(int)) + } + if d.HasChange("health_check_test") { + _, n := d.GetChange("health_check_test") + lb.HealthCheckTest = n.(string) + } + if d.HasChange("health_check_path") { + _, n := d.GetChange("health_check_path") + lb.HealthCheckPath = n.(string) + } + if d.HasChange("health_check_path_parser") { + _, n := d.GetChange("health_check_path_parser") + lb.HealthCheckPathParser = n.(string) + } + + ss, err := config.API.UpdateLoadBalancer(d.Id(), &lb) + + if err != nil { + return err + } + err = config.API.WaitForState(ss, "ACTIVE", 10, 30) + if err != nil { + return err + } + + } + + if d.HasChange("rules") { + oldR, newR := d.GetChange("rules") + oldValues := oldR.([]interface{}) + newValues := newR.([]interface{}) + if len(oldValues) > len(newValues) { + diff := difference(oldValues, newValues) + for _, old := range diff { + o := old.(map[string]interface{}) + if o["id"] != nil { + old_id := o["id"].(string) + fw, err := config.API.DeleteLoadBalancerRule(d.Id(), old_id) + if err != nil { + return err + } + + err = config.API.WaitForState(fw, "ACTIVE", 10, config.Retries) + if err != nil { + return err + } + } + } + } else { + var rules []oneandone.LoadBalancerRule + log.Println("[DEBUG] new values:", newValues) + + for _, raw := range newValues { + rl := raw.(map[string]interface{}) + log.Println("[DEBUG] rl:", rl) + + if rl["id"].(string) == "" { + rule := oneandone.LoadBalancerRule{ + Protocol: rl["protocol"].(string), + } + + rule.PortServer = uint16(rl["port_server"].(int)) + rule.PortBalancer = uint16(rl["port_balancer"].(int)) + + rule.Source = rl["source_ip"].(string) + + log.Println("[DEBUG] adding to list", rl["protocol"], rl["source_ip"], rl["port_balancer"], rl["port_server"]) + log.Println("[DEBUG] adding to list", rule) + + rules = append(rules, rule) + } + } + + log.Println("[DEBUG] new rules:", rules) + + if len(rules) > 0 { + fw, err := config.API.AddLoadBalancerRules(d.Id(), rules) + if err != nil { + return err + } + + err = config.API.WaitForState(fw, "ACTIVE", 10, config.Retries) + } + } + } + + return resourceOneandOneLoadbalancerRead(d, meta) +} + +func resourceOneandOneLoadbalancerRead(d *schema.ResourceData, meta interface{}) error { + config := meta.(*Config) + + ss, err := config.API.GetLoadBalancer(d.Id()) + if err != nil { + if strings.Contains(err.Error(), "404") { + d.SetId("") + return nil + } + return err + } + + d.Set("name", ss.Name) + d.Set("description", ss.Description) + d.Set("datacenter", ss.Datacenter.CountryCode) + d.Set("method", ss.Method) + d.Set("persistence", ss.Persistence) + d.Set("persistence_time", ss.PersistenceTime) + d.Set("health_check_test", ss.HealthCheckTest) + d.Set("health_check_interval", ss.HealthCheckInterval) + d.Set("rules", getLoadbalancerRules(ss.Rules)) + + return nil +} + +func getLoadbalancerRules(rules []oneandone.LoadBalancerRule) []map[string]interface{} { + raw := make([]map[string]interface{}, 0, len(rules)) + + for _, rule := range rules { + + toadd := map[string]interface{}{ + "id": rule.Id, + "port_balancer": rule.PortBalancer, + "port_server": rule.PortServer, + "protocol": rule.Protocol, + "source_ip": rule.Source, + } + + raw = append(raw, toadd) + } + + return raw + +} + +func resourceOneandOneLoadbalancerDelete(d *schema.ResourceData, meta interface{}) error { + config := meta.(*Config) + + lb, err := config.API.DeleteLoadBalancer(d.Id()) + if err != nil { + return err + } + err = config.API.WaitUntilDeleted(lb) + if err != nil { + return err + } + + return nil +} + +func validateMethod(v interface{}, k string) (ws []string, errors []error) { + value := v.(string) + + if value != "ROUND_ROBIN" && value != "LEAST_CONNECTIONS" { + errors = append(errors, fmt.Errorf("%q value sholud be either 'ROUND_ROBIN' or 'LEAST_CONNECTIONS' not %q", k, value)) + } + + return +} diff --git a/builtin/providers/oneandone/resource_oneandone_loadbalancer_test.go b/builtin/providers/oneandone/resource_oneandone_loadbalancer_test.go new file mode 100644 index 000000000..ecd0f9443 --- /dev/null +++ b/builtin/providers/oneandone/resource_oneandone_loadbalancer_test.go @@ -0,0 +1,156 @@ +package oneandone + +import ( + "fmt" + "testing" + + "github.com/1and1/oneandone-cloudserver-sdk-go" + "github.com/hashicorp/terraform/helper/resource" + "github.com/hashicorp/terraform/terraform" + "os" + "time" +) + +func TestAccOneandoneLoadbalancer_Basic(t *testing.T) { + var lb oneandone.LoadBalancer + + name := "test_loadbalancer" + name_updated := "test_loadbalancer_renamed" + + resource.Test(t, resource.TestCase{ + PreCheck: func() { + testAccPreCheck(t) + }, + Providers: testAccProviders, + CheckDestroy: testAccCheckDOneandoneLoadbalancerDestroyCheck, + Steps: []resource.TestStep{ + resource.TestStep{ + Config: fmt.Sprintf(testAccCheckOneandoneLoadbalancer_basic, name), + Check: resource.ComposeTestCheckFunc( + func(*terraform.State) error { + time.Sleep(10 * time.Second) + return nil + }, + testAccCheckOneandoneLoadbalancerExists("oneandone_loadbalancer.lb", &lb), + testAccCheckOneandoneLoadbalancerAttributes("oneandone_loadbalancer.lb", name), + resource.TestCheckResourceAttr("oneandone_loadbalancer.lb", "name", name), + ), + }, + resource.TestStep{ + Config: fmt.Sprintf(testAccCheckOneandoneLoadbalancer_update, name_updated), + Check: resource.ComposeTestCheckFunc( + func(*terraform.State) error { + time.Sleep(10 * time.Second) + return nil + }, + testAccCheckOneandoneLoadbalancerExists("oneandone_loadbalancer.lb", &lb), + testAccCheckOneandoneLoadbalancerAttributes("oneandone_loadbalancer.lb", name_updated), + resource.TestCheckResourceAttr("oneandone_loadbalancer.lb", "name", name_updated), + ), + }, + }, + }) +} + +func testAccCheckDOneandoneLoadbalancerDestroyCheck(s *terraform.State) error { + for _, rs := range s.RootModule().Resources { + if rs.Type != "oneandone_loadbalancer.lb" { + continue + } + + api := oneandone.New(os.Getenv("ONEANDONE_TOKEN"), oneandone.BaseUrl) + + _, err := api.GetLoadBalancer(rs.Primary.ID) + + if err == nil { + return fmt.Errorf("Loadbalancer still exists %s %s", rs.Primary.ID, err.Error()) + } + } + + return nil +} +func testAccCheckOneandoneLoadbalancerAttributes(n string, reverse_dns string) resource.TestCheckFunc { + return func(s *terraform.State) error { + rs, ok := s.RootModule().Resources[n] + if !ok { + return fmt.Errorf("Not found: %s", n) + } + if rs.Primary.Attributes["name"] != reverse_dns { + return fmt.Errorf("Bad name: expected %s : found %s ", reverse_dns, rs.Primary.Attributes["name"]) + } + + return nil + } +} + +func testAccCheckOneandoneLoadbalancerExists(n string, fw_p *oneandone.LoadBalancer) resource.TestCheckFunc { + return func(s *terraform.State) error { + rs, ok := s.RootModule().Resources[n] + + if !ok { + return fmt.Errorf("Not found: %s", n) + } + + if rs.Primary.ID == "" { + return fmt.Errorf("No Record ID is set") + } + + api := oneandone.New(os.Getenv("ONEANDONE_TOKEN"), oneandone.BaseUrl) + + found_fw, err := api.GetLoadBalancer(rs.Primary.ID) + + if err != nil { + return fmt.Errorf("Error occured while fetching Loadbalancer: %s", rs.Primary.ID) + } + if found_fw.Id != rs.Primary.ID { + return fmt.Errorf("Record not found") + } + fw_p = found_fw + + return nil + } +} + +const testAccCheckOneandoneLoadbalancer_basic = ` +resource "oneandone_loadbalancer" "lb" { + name = "%s" + method = "ROUND_ROBIN" + persistence = true + persistence_time = 60 + health_check_test = "TCP" + health_check_interval = 300 + datacenter = "US" + rules = [ + { + protocol = "TCP" + port_balancer = 8080 + port_server = 8089 + source_ip = "0.0.0.0" + }, + { + protocol = "TCP" + port_balancer = 9090 + port_server = 9099 + source_ip = "0.0.0.0" + } + ] +}` + +const testAccCheckOneandoneLoadbalancer_update = ` +resource "oneandone_loadbalancer" "lb" { + name = "%s" + method = "ROUND_ROBIN" + persistence = true + persistence_time = 60 + health_check_test = "TCP" + health_check_interval = 300 + datacenter = "US" + rules = [ + { + protocol = "TCP" + port_balancer = 8080 + port_server = 8089 + source_ip = "0.0.0.0" + } + ] +}` diff --git a/builtin/providers/oneandone/resource_oneandone_monitoring_policy.go b/builtin/providers/oneandone/resource_oneandone_monitoring_policy.go new file mode 100644 index 000000000..a6af20dfc --- /dev/null +++ b/builtin/providers/oneandone/resource_oneandone_monitoring_policy.go @@ -0,0 +1,706 @@ +package oneandone + +import ( + "github.com/1and1/oneandone-cloudserver-sdk-go" + "github.com/hashicorp/terraform/helper/schema" + "strings" +) + +func resourceOneandOneMonitoringPolicy() *schema.Resource { + return &schema.Resource{ + Create: resourceOneandOneMonitoringPolicyCreate, + Read: resourceOneandOneMonitoringPolicyRead, + Update: resourceOneandOneMonitoringPolicyUpdate, + Delete: resourceOneandOneMonitoringPolicyDelete, + Schema: map[string]*schema.Schema{ + "name": { + Type: schema.TypeString, + Required: true, + }, + "description": { + Type: schema.TypeString, + Optional: true, + }, + "email": { + Type: schema.TypeString, + Optional: true, + }, + "agent": { + Type: schema.TypeBool, + Required: true, + }, + "thresholds": { + Type: schema.TypeSet, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "cpu": { + Type: schema.TypeSet, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "warning": { + Type: schema.TypeSet, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "value": { + Type: schema.TypeInt, + Required: true, + }, + "alert": { + Type: schema.TypeBool, + Required: true, + }, + }, + }, + Required: true, + }, + "critical": { + Type: schema.TypeSet, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "value": { + Type: schema.TypeInt, + Required: true, + }, + "alert": { + Type: schema.TypeBool, + Required: true, + }, + }, + }, + Required: true, + }, + }, + }, + Required: true, + }, + "ram": { + Type: schema.TypeSet, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "warning": { + Type: schema.TypeSet, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "value": { + Type: schema.TypeInt, + Required: true, + }, + "alert": { + Type: schema.TypeBool, + Required: true, + }, + }, + }, + Required: true, + }, + "critical": { + Type: schema.TypeSet, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "value": { + Type: schema.TypeInt, + Required: true, + }, + "alert": { + Type: schema.TypeBool, + Required: true, + }, + }, + }, + Required: true, + }, + }, + }, + Required: true, + }, + "disk": { + Type: schema.TypeSet, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "warning": { + Type: schema.TypeSet, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "value": { + Type: schema.TypeInt, + Required: true, + }, + "alert": { + Type: schema.TypeBool, + Required: true, + }, + }, + }, + Required: true, + }, + "critical": { + Type: schema.TypeSet, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "value": { + Type: schema.TypeInt, + Required: true, + }, + "alert": { + Type: schema.TypeBool, + Required: true, + }, + }, + }, + Required: true, + }, + }, + }, + Required: true, + }, + "transfer": { + Type: schema.TypeSet, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "warning": { + Type: schema.TypeSet, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "value": { + Type: schema.TypeInt, + Required: true, + }, + "alert": { + Type: schema.TypeBool, + Required: true, + }, + }, + }, + Required: true, + }, + "critical": { + Type: schema.TypeSet, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "value": { + Type: schema.TypeInt, + Required: true, + }, + "alert": { + Type: schema.TypeBool, + Required: true, + }, + }, + }, + Required: true, + }, + }, + }, + Required: true, + }, + "internal_ping": { + Type: schema.TypeSet, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "warning": { + Type: schema.TypeSet, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "value": { + Type: schema.TypeInt, + Required: true, + }, + "alert": { + Type: schema.TypeBool, + Required: true, + }, + }, + }, + Required: true, + }, + "critical": { + Type: schema.TypeSet, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "value": { + Type: schema.TypeInt, + Required: true, + }, + "alert": { + Type: schema.TypeBool, + Required: true, + }, + }, + }, + Required: true, + }, + }, + }, + Required: true, + }, + }, + }, + Required: true, + }, + "ports": { + Type: schema.TypeList, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "email_notification": { + Type: schema.TypeBool, + Required: true, + }, + "port": { + Type: schema.TypeInt, + Required: true, + }, + "protocol": { + Type: schema.TypeString, + Optional: true, + }, + "alert_if": { + Type: schema.TypeString, + Optional: true, + }, + "id": { + Type: schema.TypeString, + Computed: true, + }, + }, + }, + Optional: true, + }, + "processes": { + Type: schema.TypeList, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + + "email_notification": { + Type: schema.TypeBool, + Required: true, + }, + "process": { + Type: schema.TypeString, + Required: true, + }, + "alert_if": { + Type: schema.TypeString, + Optional: true, + }, + "id": { + Type: schema.TypeString, + Computed: true, + }, + }, + }, + Optional: true, + }, + }, + } +} + +func resourceOneandOneMonitoringPolicyCreate(d *schema.ResourceData, meta interface{}) error { + config := meta.(*Config) + + mp_request := oneandone.MonitoringPolicy{ + Name: d.Get("name").(string), + Agent: d.Get("agent").(bool), + Thresholds: getThresholds(d.Get("thresholds")), + } + + if raw, ok := d.GetOk("ports"); ok { + mp_request.Ports = getPorts(raw) + } + + if raw, ok := d.GetOk("processes"); ok { + mp_request.Processes = getProcesses(raw) + } + + mp_id, mp, err := config.API.CreateMonitoringPolicy(&mp_request) + if err != nil { + return err + } + + err = config.API.WaitForState(mp, "ACTIVE", 30, config.Retries) + if err != nil { + return err + } + + d.SetId(mp_id) + + return resourceOneandOneMonitoringPolicyRead(d, meta) +} + +func resourceOneandOneMonitoringPolicyUpdate(d *schema.ResourceData, meta interface{}) error { + config := meta.(*Config) + + req := oneandone.MonitoringPolicy{} + if d.HasChange("name") { + _, n := d.GetChange("name") + req.Name = n.(string) + } + + if d.HasChange("description") { + _, n := d.GetChange("description") + req.Description = n.(string) + } + + if d.HasChange("email") { + _, n := d.GetChange("email") + req.Email = n.(string) + } + + if d.HasChange("agent") { + _, n := d.GetChange("agent") + req.Agent = n.(bool) + } + + if d.HasChange("thresholds") { + _, n := d.GetChange("thresholds") + req.Thresholds = getThresholds(n) + } + + mp, err := config.API.UpdateMonitoringPolicy(d.Id(), &req) + if err != nil { + return err + } + + err = config.API.WaitForState(mp, "ACTIVE", 30, config.Retries) + if err != nil { + return err + } + + if d.HasChange("ports") { + o, n := d.GetChange("ports") + oldValues := o.([]interface{}) + newValues := n.([]interface{}) + + if len(newValues) > len(oldValues) { + ports := getPorts(newValues) + + newports := []oneandone.MonitoringPort{} + + for _, p := range ports { + if p.Id == "" { + newports = append(newports, p) + } + } + + mp, err := config.API.AddMonitoringPolicyPorts(d.Id(), newports) + if err != nil { + return err + } + + err = config.API.WaitForState(mp, "ACTIVE", 30, config.Retries) + if err != nil { + return err + } + } else if len(oldValues) > len(newValues) { + diff := difference(oldValues, newValues) + ports := getPorts(diff) + + for _, port := range ports { + if port.Id == "" { + continue + } + + mp, err := config.API.DeleteMonitoringPolicyPort(d.Id(), port.Id) + if err != nil { + return err + } + + err = config.API.WaitForState(mp, "ACTIVE", 30, config.Retries) + if err != nil { + return err + } + } + } else if len(oldValues) == len(newValues) { + ports := getPorts(newValues) + + for _, port := range ports { + mp, err := config.API.ModifyMonitoringPolicyPort(d.Id(), port.Id, &port) + if err != nil { + return err + } + + err = config.API.WaitForState(mp, "ACTIVE", 30, config.Retries) + if err != nil { + return err + } + } + } + } + + if d.HasChange("processes") { + o, n := d.GetChange("processes") + oldValues := o.([]interface{}) + newValues := n.([]interface{}) + if len(newValues) > len(oldValues) { + processes := getProcesses(newValues) + + newprocesses := []oneandone.MonitoringProcess{} + + for _, p := range processes { + if p.Id == "" { + newprocesses = append(newprocesses, p) + } + } + + mp, err := config.API.AddMonitoringPolicyProcesses(d.Id(), newprocesses) + if err != nil { + return err + } + + err = config.API.WaitForState(mp, "ACTIVE", 30, config.Retries) + if err != nil { + return err + } + } else if len(oldValues) > len(newValues) { + diff := difference(oldValues, newValues) + processes := getProcesses(diff) + for _, process := range processes { + if process.Id == "" { + continue + } + + mp, err := config.API.DeleteMonitoringPolicyProcess(d.Id(), process.Id) + if err != nil { + return err + } + + err = config.API.WaitForState(mp, "ACTIVE", 30, config.Retries) + if err != nil { + return err + } + } + } else if len(oldValues) == len(newValues) { + processes := getProcesses(newValues) + + for _, process := range processes { + mp, err := config.API.ModifyMonitoringPolicyProcess(d.Id(), process.Id, &process) + if err != nil { + return err + } + + err = config.API.WaitForState(mp, "ACTIVE", 30, config.Retries) + if err != nil { + return err + } + } + } + } + + return resourceOneandOneMonitoringPolicyRead(d, meta) +} + +func resourceOneandOneMonitoringPolicyRead(d *schema.ResourceData, meta interface{}) error { + config := meta.(*Config) + + mp, err := config.API.GetMonitoringPolicy(d.Id()) + if err != nil { + if strings.Contains(err.Error(), "404") { + d.SetId("") + return nil + } + return err + } + + if len(mp.Servers) > 0 { + } + + if len(mp.Ports) > 0 { + pports := d.Get("ports").([]interface{}) + for i, raw_ports := range pports { + port := raw_ports.(map[string]interface{}) + port["id"] = mp.Ports[i].Id + } + d.Set("ports", pports) + } + + if len(mp.Processes) > 0 { + pprocesses := d.Get("processes").([]interface{}) + for i, raw_processes := range pprocesses { + process := raw_processes.(map[string]interface{}) + process["id"] = mp.Processes[i].Id + } + d.Set("processes", pprocesses) + } + + return nil +} + +func resourceOneandOneMonitoringPolicyDelete(d *schema.ResourceData, meta interface{}) error { + config := meta.(*Config) + + mp, err := config.API.DeleteMonitoringPolicy(d.Id()) + if err != nil { + return err + } + + err = config.API.WaitUntilDeleted(mp) + if err != nil { + return err + } + + return nil +} + +func getThresholds(d interface{}) *oneandone.MonitoringThreshold { + raw_thresholds := d.(*schema.Set).List() + + toReturn := &oneandone.MonitoringThreshold{} + + for _, thresholds := range raw_thresholds { + th_set := thresholds.(map[string]interface{}) + + //CPU + cpu_raw := th_set["cpu"].(*schema.Set) + toReturn.Cpu = &oneandone.MonitoringLevel{} + for _, c := range cpu_raw.List() { + int_k := c.(map[string]interface{}) + for _, w := range int_k["warning"].(*schema.Set).List() { + toReturn.Cpu.Warning = &oneandone.MonitoringValue{ + Value: w.(map[string]interface{})["value"].(int), + Alert: w.(map[string]interface{})["alert"].(bool), + } + } + + for _, c := range int_k["critical"].(*schema.Set).List() { + toReturn.Cpu.Critical = &oneandone.MonitoringValue{ + Value: c.(map[string]interface{})["value"].(int), + Alert: c.(map[string]interface{})["alert"].(bool), + } + } + } + //RAM + ram_raw := th_set["ram"].(*schema.Set) + toReturn.Ram = &oneandone.MonitoringLevel{} + for _, c := range ram_raw.List() { + int_k := c.(map[string]interface{}) + for _, w := range int_k["warning"].(*schema.Set).List() { + toReturn.Ram.Warning = &oneandone.MonitoringValue{ + Value: w.(map[string]interface{})["value"].(int), + Alert: w.(map[string]interface{})["alert"].(bool), + } + } + + for _, c := range int_k["critical"].(*schema.Set).List() { + toReturn.Ram.Critical = &oneandone.MonitoringValue{ + Value: c.(map[string]interface{})["value"].(int), + Alert: c.(map[string]interface{})["alert"].(bool), + } + } + } + + //DISK + disk_raw := th_set["disk"].(*schema.Set) + toReturn.Disk = &oneandone.MonitoringLevel{} + for _, c := range disk_raw.List() { + int_k := c.(map[string]interface{}) + for _, w := range int_k["warning"].(*schema.Set).List() { + toReturn.Disk.Warning = &oneandone.MonitoringValue{ + Value: w.(map[string]interface{})["value"].(int), + Alert: w.(map[string]interface{})["alert"].(bool), + } + } + + for _, c := range int_k["critical"].(*schema.Set).List() { + toReturn.Disk.Critical = &oneandone.MonitoringValue{ + Value: c.(map[string]interface{})["value"].(int), + Alert: c.(map[string]interface{})["alert"].(bool), + } + } + } + + //TRANSFER + transfer_raw := th_set["transfer"].(*schema.Set) + toReturn.Transfer = &oneandone.MonitoringLevel{} + for _, c := range transfer_raw.List() { + int_k := c.(map[string]interface{}) + for _, w := range int_k["warning"].(*schema.Set).List() { + toReturn.Transfer.Warning = &oneandone.MonitoringValue{ + Value: w.(map[string]interface{})["value"].(int), + Alert: w.(map[string]interface{})["alert"].(bool), + } + } + + for _, c := range int_k["critical"].(*schema.Set).List() { + toReturn.Transfer.Critical = &oneandone.MonitoringValue{ + Value: c.(map[string]interface{})["value"].(int), + Alert: c.(map[string]interface{})["alert"].(bool), + } + } + } + //internal ping + ping_raw := th_set["internal_ping"].(*schema.Set) + toReturn.InternalPing = &oneandone.MonitoringLevel{} + for _, c := range ping_raw.List() { + int_k := c.(map[string]interface{}) + for _, w := range int_k["warning"].(*schema.Set).List() { + toReturn.InternalPing.Warning = &oneandone.MonitoringValue{ + Value: w.(map[string]interface{})["value"].(int), + Alert: w.(map[string]interface{})["alert"].(bool), + } + } + + for _, c := range int_k["critical"].(*schema.Set).List() { + toReturn.InternalPing.Critical = &oneandone.MonitoringValue{ + Value: c.(map[string]interface{})["value"].(int), + Alert: c.(map[string]interface{})["alert"].(bool), + } + } + } + } + + return toReturn +} + +func getProcesses(d interface{}) []oneandone.MonitoringProcess { + toReturn := []oneandone.MonitoringProcess{} + + for _, raw := range d.([]interface{}) { + port := raw.(map[string]interface{}) + m_port := oneandone.MonitoringProcess{ + EmailNotification: port["email_notification"].(bool), + } + + if port["id"] != nil { + m_port.Id = port["id"].(string) + } + + if port["process"] != nil { + m_port.Process = port["process"].(string) + } + + if port["alert_if"] != nil { + m_port.AlertIf = port["alert_if"].(string) + } + + toReturn = append(toReturn, m_port) + } + + return toReturn +} + +func getPorts(d interface{}) []oneandone.MonitoringPort { + toReturn := []oneandone.MonitoringPort{} + + for _, raw := range d.([]interface{}) { + port := raw.(map[string]interface{}) + m_port := oneandone.MonitoringPort{ + EmailNotification: port["email_notification"].(bool), + Port: port["port"].(int), + } + + if port["id"] != nil { + m_port.Id = port["id"].(string) + } + + if port["protocol"] != nil { + m_port.Protocol = port["protocol"].(string) + } + + if port["alert_if"] != nil { + m_port.AlertIf = port["alert_if"].(string) + } + + toReturn = append(toReturn, m_port) + } + + return toReturn +} diff --git a/builtin/providers/oneandone/resource_oneandone_monitoring_policy_test.go b/builtin/providers/oneandone/resource_oneandone_monitoring_policy_test.go new file mode 100644 index 000000000..c6727ee21 --- /dev/null +++ b/builtin/providers/oneandone/resource_oneandone_monitoring_policy_test.go @@ -0,0 +1,212 @@ +package oneandone + +import ( + "fmt" + "testing" + + "github.com/1and1/oneandone-cloudserver-sdk-go" + "github.com/hashicorp/terraform/helper/resource" + "github.com/hashicorp/terraform/terraform" + "os" + "time" +) + +func TestAccOneandoneMonitoringPolicy_Basic(t *testing.T) { + var mp oneandone.MonitoringPolicy + + name := "test" + name_updated := "test1" + + resource.Test(t, resource.TestCase{ + PreCheck: func() { + testAccPreCheck(t) + }, + Providers: testAccProviders, + CheckDestroy: testAccCheckDOneandoneMonitoringPolicyDestroyCheck, + Steps: []resource.TestStep{ + resource.TestStep{ + Config: fmt.Sprintf(testAccCheckOneandoneMonitoringPolicy_basic, name), + Check: resource.ComposeTestCheckFunc( + func(*terraform.State) error { + time.Sleep(10 * time.Second) + return nil + }, + testAccCheckOneandoneMonitoringPolicyExists("oneandone_monitoring_policy.mp", &mp), + testAccCheckOneandoneMonitoringPolicyAttributes("oneandone_monitoring_policy.mp", name), + resource.TestCheckResourceAttr("oneandone_monitoring_policy.mp", "name", name), + ), + }, + resource.TestStep{ + Config: fmt.Sprintf(testAccCheckOneandoneMonitoringPolicy_basic, name_updated), + Check: resource.ComposeTestCheckFunc( + func(*terraform.State) error { + time.Sleep(10 * time.Second) + return nil + }, + testAccCheckOneandoneMonitoringPolicyExists("oneandone_monitoring_policy.mp", &mp), + testAccCheckOneandoneMonitoringPolicyAttributes("oneandone_monitoring_policy.mp", name_updated), + resource.TestCheckResourceAttr("oneandone_monitoring_policy.mp", "name", name_updated), + ), + }, + }, + }) +} + +func testAccCheckDOneandoneMonitoringPolicyDestroyCheck(s *terraform.State) error { + for _, rs := range s.RootModule().Resources { + if rs.Type != "oneandone_monitoring_policy.mp" { + continue + } + + api := oneandone.New(os.Getenv("ONEANDONE_TOKEN"), oneandone.BaseUrl) + + _, err := api.GetMonitoringPolicy(rs.Primary.ID) + + if err == nil { + return fmt.Errorf("MonitoringPolicy still exists %s %s", rs.Primary.ID, err.Error()) + } + } + + return nil +} +func testAccCheckOneandoneMonitoringPolicyAttributes(n string, reverse_dns string) resource.TestCheckFunc { + return func(s *terraform.State) error { + rs, ok := s.RootModule().Resources[n] + if !ok { + return fmt.Errorf("Not found: %s", n) + } + if rs.Primary.Attributes["name"] != reverse_dns { + return fmt.Errorf("Bad name: expected %s : found %s ", reverse_dns, rs.Primary.Attributes["name"]) + } + + return nil + } +} + +func testAccCheckOneandoneMonitoringPolicyExists(n string, fw_p *oneandone.MonitoringPolicy) resource.TestCheckFunc { + return func(s *terraform.State) error { + rs, ok := s.RootModule().Resources[n] + + if !ok { + return fmt.Errorf("Not found: %s", n) + } + + if rs.Primary.ID == "" { + return fmt.Errorf("No Record ID is set") + } + + api := oneandone.New(os.Getenv("ONEANDONE_TOKEN"), oneandone.BaseUrl) + + found_fw, err := api.GetMonitoringPolicy(rs.Primary.ID) + + if err != nil { + return fmt.Errorf("Error occured while fetching MonitoringPolicy: %s", rs.Primary.ID) + } + if found_fw.Id != rs.Primary.ID { + return fmt.Errorf("Record not found") + } + fw_p = found_fw + + return nil + } +} + +const testAccCheckOneandoneMonitoringPolicy_basic = ` +resource "oneandone_monitoring_policy" "mp" { + name = "%s" + agent = true + email = "email@address.com" + thresholds = { + cpu = { + warning = { + value = 50, + alert = false + } + critical = { + value = 66, + alert = false + } + } + ram = { + warning = { + value = 70, + alert = true + } + critical = { + value = 80, + alert = true + } + }, + ram = { + warning = { + value = 85, + alert = true + } + critical = { + value = 95, + alert = true + } + }, + disk = { + warning = { + value = 84, + alert = true + } + critical = { + value = 94, + alert = true + } + }, + transfer = { + warning = { + value = 1000, + alert = true + } + critical = { + value = 2000, + alert = true + } + }, + internal_ping = { + warning = { + value = 3000, + alert = true + } + critical = { + value = 4000, + alert = true + } + } + } + ports = [ + { + email_notification = true + port = 443 + protocol = "TCP" + alert_if = "NOT_RESPONDING" + }, + { + email_notification = false + port = 80 + protocol = "TCP" + alert_if = "NOT_RESPONDING" + }, + { + email_notification = true + port = 21 + protocol = "TCP" + alert_if = "NOT_RESPONDING" + } + ] + processes = [ + { + email_notification = false + process = "httpdeamon" + alert_if = "RUNNING" + }, + { + process = "iexplorer", + alert_if = "NOT_RUNNING" + email_notification = true + }] +}` diff --git a/builtin/providers/oneandone/resource_oneandone_private_network.go b/builtin/providers/oneandone/resource_oneandone_private_network.go new file mode 100644 index 000000000..f9a4fc9e3 --- /dev/null +++ b/builtin/providers/oneandone/resource_oneandone_private_network.go @@ -0,0 +1,291 @@ +package oneandone + +import ( + "fmt" + "github.com/1and1/oneandone-cloudserver-sdk-go" + "github.com/hashicorp/terraform/helper/schema" + "strings" +) + +func resourceOneandOnePrivateNetwork() *schema.Resource { + return &schema.Resource{ + + Create: resourceOneandOnePrivateNetworkCreate, + Read: resourceOneandOnePrivateNetworkRead, + Update: resourceOneandOnePrivateNetworkUpdate, + Delete: resourceOneandOnePrivateNetworkDelete, + Schema: map[string]*schema.Schema{ + "name": { + Type: schema.TypeString, + Required: true, + }, + "description": { + Type: schema.TypeString, + Optional: true, + }, + "datacenter": { + Type: schema.TypeString, + Optional: true, + }, + "network_address": { + Type: schema.TypeString, + Optional: true, + }, + "subnet_mask": { + Type: schema.TypeString, + Optional: true, + }, + "server_ids": { + Type: schema.TypeSet, + Elem: &schema.Schema{Type: schema.TypeString}, + Optional: true, + }, + }, + } +} + +func resourceOneandOnePrivateNetworkCreate(d *schema.ResourceData, meta interface{}) error { + config := meta.(*Config) + + req := oneandone.PrivateNetworkRequest{ + Name: d.Get("name").(string), + } + + if raw, ok := d.GetOk("description"); ok { + req.Description = raw.(string) + } + + if raw, ok := d.GetOk("network_address"); ok { + req.NetworkAddress = raw.(string) + } + + if raw, ok := d.GetOk("subnet_mask"); ok { + req.SubnetMask = raw.(string) + } + + if raw, ok := d.GetOk("datacenter"); ok { + dcs, err := config.API.ListDatacenters() + + if err != nil { + return fmt.Errorf("An error occured while fetching list of datacenters %s", err) + + } + + decenter := raw.(string) + for _, dc := range dcs { + if strings.ToLower(dc.CountryCode) == strings.ToLower(decenter) { + req.DatacenterId = dc.Id + break + } + } + } + + prn_id, prn, err := config.API.CreatePrivateNetwork(&req) + if err != nil { + return err + } + err = config.API.WaitForState(prn, "ACTIVE", 30, config.Retries) + + if err != nil { + return err + } + + d.SetId(prn_id) + + var ids []string + if raw, ok := d.GetOk("server_ids"); ok { + + rawIps := raw.(*schema.Set).List() + + for _, raw := range rawIps { + ids = append(ids, raw.(string)) + server, err := config.API.ShutdownServer(raw.(string), false) + if err != nil { + return err + } + err = config.API.WaitForState(server, "POWERED_OFF", 10, config.Retries) + if err != nil { + return err + } + + } + } + + prn, err = config.API.AttachPrivateNetworkServers(d.Id(), ids) + if err != nil { + return err + } + + err = config.API.WaitForState(prn, "ACTIVE", 30, config.Retries) + if err != nil { + return err + } + + for _, id := range ids { + server, err := config.API.StartServer(id) + if err != nil { + return err + } + + err = config.API.WaitForState(server, "POWERED_ON", 10, config.Retries) + if err != nil { + return err + } + } + + return resourceOneandOnePrivateNetworkRead(d, meta) +} + +func resourceOneandOnePrivateNetworkUpdate(d *schema.ResourceData, meta interface{}) error { + config := meta.(*Config) + if d.HasChange("name") || d.HasChange("description") || d.HasChange("network_address") || d.HasChange("subnet_mask") { + pnset := oneandone.PrivateNetworkRequest{} + + pnset.Name = d.Get("name").(string) + + pnset.Description = d.Get("description").(string) + pnset.NetworkAddress = d.Get("network_address").(string) + pnset.SubnetMask = d.Get("subnet_mask").(string) + + prn, err := config.API.UpdatePrivateNetwork(d.Id(), &pnset) + + if err != nil { + return err + } + + err = config.API.WaitForState(prn, "ACTIVE", 30, config.Retries) + if err != nil { + return err + } + } + + if d.HasChange("server_ids") { + o, n := d.GetChange("server_ids") + + newValues := n.(*schema.Set).List() + oldValues := o.(*schema.Set).List() + + var ids []string + for _, newV := range oldValues { + ids = append(ids, newV.(string)) + } + for _, id := range ids { + server, err := config.API.ShutdownServer(id, false) + if err != nil { + return err + } + err = config.API.WaitForState(server, "POWERED_OFF", 10, config.Retries) + if err != nil { + return err + } + + _, err = config.API.RemoveServerPrivateNetwork(id, d.Id()) + if err != nil { + return err + } + + prn, _ := config.API.GetPrivateNetwork(d.Id()) + + err = config.API.WaitForState(prn, "ACTIVE", 10, config.Retries) + if err != nil { + return err + } + + } + + var newids []string + + for _, newV := range newValues { + newids = append(newids, newV.(string)) + } + pn, err := config.API.AttachPrivateNetworkServers(d.Id(), newids) + + if err != nil { + return err + } + err = config.API.WaitForState(pn, "ACTIVE", 30, config.Retries) + if err != nil { + return err + } + + for _, id := range newids { + server, err := config.API.StartServer(id) + if err != nil { + return err + } + + err = config.API.WaitForState(server, "POWERED_ON", 10, config.Retries) + if err != nil { + return err + } + } + } + + return resourceOneandOnePrivateNetworkRead(d, meta) +} + +func resourceOneandOnePrivateNetworkRead(d *schema.ResourceData, meta interface{}) error { + config := meta.(*Config) + + pn, err := config.API.GetPrivateNetwork(d.Id()) + if err != nil { + if strings.Contains(err.Error(), "404") { + d.SetId("") + return nil + } + return err + } + + d.Set("name", pn.Name) + d.Set("description", pn.Description) + d.Set("network_address", pn.NetworkAddress) + d.Set("subnet_mask", pn.SubnetMask) + d.Set("datacenter", pn.Datacenter.CountryCode) + + var toAdd []string + for _, s := range pn.Servers { + toAdd = append(toAdd, s.Id) + } + d.Set("server_ids", toAdd) + return nil +} + +func resourceOneandOnePrivateNetworkDelete(d *schema.ResourceData, meta interface{}) error { + config := meta.(*Config) + + pn, err := config.API.GetPrivateNetwork(d.Id()) + + for _, server := range pn.Servers { + srv, err := config.API.ShutdownServer(server.Id, false) + if err != nil { + return err + } + err = config.API.WaitForState(srv, "POWERED_OFF", 10, config.Retries) + if err != nil { + return err + } + } + + pn, err = config.API.DeletePrivateNetwork(d.Id()) + if err != nil { + return err + } + + err = config.API.WaitUntilDeleted(pn) + if err != nil { + return err + } + + for _, server := range pn.Servers { + srv, err := config.API.StartServer(server.Id) + if err != nil { + return err + } + err = config.API.WaitForState(srv, "POWERED_ON", 10, config.Retries) + if err != nil { + return err + } + } + + return nil +} diff --git a/builtin/providers/oneandone/resource_oneandone_private_network_test.go b/builtin/providers/oneandone/resource_oneandone_private_network_test.go new file mode 100644 index 000000000..e91da76f2 --- /dev/null +++ b/builtin/providers/oneandone/resource_oneandone_private_network_test.go @@ -0,0 +1,160 @@ +package oneandone + +import ( + "fmt" + "testing" + + "github.com/1and1/oneandone-cloudserver-sdk-go" + "github.com/hashicorp/terraform/helper/resource" + "github.com/hashicorp/terraform/terraform" + "os" + "time" +) + +func TestAccOneandonePrivateNetwork_Basic(t *testing.T) { + var net oneandone.PrivateNetwork + + name := "test" + name_updated := "test1" + + resource.Test(t, resource.TestCase{ + PreCheck: func() { + testAccPreCheck(t) + }, + Providers: testAccProviders, + CheckDestroy: testAccCheckOneandonePrivateNetworkDestroyCheck, + Steps: []resource.TestStep{ + resource.TestStep{ + Config: fmt.Sprintf(testAccCheckOneandonePrivateNetwork_basic, name), + Check: resource.ComposeTestCheckFunc( + func(*terraform.State) error { + time.Sleep(10 * time.Second) + return nil + }, + testAccCheckOneandonePrivateNetworkExists("oneandone_private_network.pn", &net), + testAccCheckOneandonePrivateNetworkAttributes("oneandone_private_network.pn", name), + resource.TestCheckResourceAttr("oneandone_private_network.pn", "name", name), + ), + }, + resource.TestStep{ + Config: fmt.Sprintf(testAccCheckOneandonePrivateNetwork_basic, name_updated), + Check: resource.ComposeTestCheckFunc( + func(*terraform.State) error { + time.Sleep(10 * time.Second) + return nil + }, + testAccCheckOneandonePrivateNetworkExists("oneandone_private_network.pn", &net), + testAccCheckOneandonePrivateNetworkAttributes("oneandone_private_network.pn", name_updated), + resource.TestCheckResourceAttr("oneandone_private_network.pn", "name", name_updated), + ), + }, + }, + }) +} + +func testAccCheckOneandonePrivateNetworkDestroyCheck(s *terraform.State) error { + for _, rs := range s.RootModule().Resources { + if rs.Type != "oneandone_private_network" { + continue + } + + api := oneandone.New(os.Getenv("ONEANDONE_TOKEN"), oneandone.BaseUrl) + + _, err := api.GetPrivateNetwork(rs.Primary.ID) + + if err == nil { + return fmt.Errorf("PrivateNetwork still exists %s %s", rs.Primary.ID, err.Error()) + } + } + + return nil +} +func testAccCheckOneandonePrivateNetworkAttributes(n string, reverse_dns string) resource.TestCheckFunc { + return func(s *terraform.State) error { + rs, ok := s.RootModule().Resources[n] + if !ok { + return fmt.Errorf("Not found: %s", n) + } + if rs.Primary.Attributes["name"] != reverse_dns { + return fmt.Errorf("Bad name: expected %s : found %s ", reverse_dns, rs.Primary.Attributes["name"]) + } + + return nil + } +} + +func testAccCheckOneandonePrivateNetworkExists(n string, server *oneandone.PrivateNetwork) resource.TestCheckFunc { + return func(s *terraform.State) error { + rs, ok := s.RootModule().Resources[n] + + if !ok { + return fmt.Errorf("Not found: %s", n) + } + + if rs.Primary.ID == "" { + return fmt.Errorf("No Record ID is set") + } + + api := oneandone.New(os.Getenv("ONEANDONE_TOKEN"), oneandone.BaseUrl) + + found_server, err := api.GetPrivateNetwork(rs.Primary.ID) + + if err != nil { + return fmt.Errorf("Error occured while fetching PrivateNetwork: %s", rs.Primary.ID) + } + if found_server.Id != rs.Primary.ID { + return fmt.Errorf("Record not found") + } + server = found_server + + return nil + } +} + +const testAccCheckOneandonePrivateNetwork_basic = ` +resource "oneandone_server" "server1" { + name = "server_private_net_01" + description = "ttt" + image = "CoreOS_Stable_64std" + datacenter = "US" + vcores = 1 + cores_per_processor = 1 + ram = 2 + password = "Kv40kd8PQb" + hdds = [ + { + disk_size = 60 + is_main = true + } + ] +} + +resource "oneandone_server" "server2" { + name = "server_private_net_02" + description = "ttt" + image = "CoreOS_Stable_64std" + datacenter = "US" + vcores = 1 + cores_per_processor = 1 + ram = 2 + password = "${oneandone_server.server1.password}" + hdds = [ + { + disk_size = 60 + is_main = true + } + ] +} + +resource "oneandone_private_network" "pn" { + name = "%s", + description = "new private net" + datacenter = "US" + network_address = "192.168.7.0" + subnet_mask = "255.255.255.0" + server_ids = [ + "${oneandone_server.server1.id}", + "${oneandone_server.server2.id}" + ] +} +` diff --git a/builtin/providers/oneandone/resource_oneandone_public_ip.go b/builtin/providers/oneandone/resource_oneandone_public_ip.go new file mode 100644 index 000000000..2c1bec240 --- /dev/null +++ b/builtin/providers/oneandone/resource_oneandone_public_ip.go @@ -0,0 +1,133 @@ +package oneandone + +import ( + "fmt" + "github.com/hashicorp/terraform/helper/schema" + "strings" +) + +func resourceOneandOnePublicIp() *schema.Resource { + return &schema.Resource{ + + Create: resourceOneandOnePublicIpCreate, + Read: resourceOneandOnePublicIpRead, + Update: resourceOneandOnePublicIpUpdate, + Delete: resourceOneandOnePublicIpDelete, + Schema: map[string]*schema.Schema{ + "ip_type": { //IPV4 or IPV6 + Type: schema.TypeString, + Required: true, + }, + "reverse_dns": { + Type: schema.TypeString, + Optional: true, + }, + "datacenter": { + Type: schema.TypeString, + Optional: true, + }, + "ip_address": { + Type: schema.TypeString, + Computed: true, + }, + }, + } +} + +func resourceOneandOnePublicIpCreate(d *schema.ResourceData, meta interface{}) error { + config := meta.(*Config) + + var reverse_dns string + var datacenter_id string + + if raw, ok := d.GetOk("reverse_dns"); ok { + reverse_dns = raw.(string) + } + + if raw, ok := d.GetOk("datacenter"); ok { + dcs, err := config.API.ListDatacenters() + + if err != nil { + return fmt.Errorf("An error occured while fetching list of datacenters %s", err) + + } + + decenter := raw.(string) + for _, dc := range dcs { + if strings.ToLower(dc.CountryCode) == strings.ToLower(decenter) { + datacenter_id = dc.Id + break + } + } + + } + + ip_id, ip, err := config.API.CreatePublicIp(d.Get("ip_type").(string), reverse_dns, datacenter_id) + if err != nil { + return err + } + + err = config.API.WaitForState(ip, "ACTIVE", 10, config.Retries) + if err != nil { + return err + } + d.SetId(ip_id) + + return resourceOneandOnePublicIpRead(d, meta) +} + +func resourceOneandOnePublicIpRead(d *schema.ResourceData, meta interface{}) error { + config := meta.(*Config) + + ip, err := config.API.GetPublicIp(d.Id()) + if err != nil { + if strings.Contains(err.Error(), "404") { + d.SetId("") + return nil + } + return err + } + + d.Set("ip_address", ip.IpAddress) + d.Set("revers_dns", ip.ReverseDns) + d.Set("datacenter", ip.Datacenter.CountryCode) + d.Set("ip_type", ip.Type) + + return nil +} + +func resourceOneandOnePublicIpUpdate(d *schema.ResourceData, meta interface{}) error { + config := meta.(*Config) + + if d.HasChange("reverse_dns") { + _, n := d.GetChange("reverse_dns") + ip, err := config.API.UpdatePublicIp(d.Id(), n.(string)) + if err != nil { + return err + } + + err = config.API.WaitForState(ip, "ACTIVE", 10, config.Retries) + if err != nil { + return err + } + } + + return resourceOneandOnePublicIpRead(d, meta) +} + +func resourceOneandOnePublicIpDelete(d *schema.ResourceData, meta interface{}) error { + config := meta.(*Config) + + ip, err := config.API.DeletePublicIp(d.Id()) + if err != nil { + return err + } + + err = config.API.WaitUntilDeleted(ip) + if err != nil { + + return err + } + + return nil +} diff --git a/builtin/providers/oneandone/resource_oneandone_public_ip_test.go b/builtin/providers/oneandone/resource_oneandone_public_ip_test.go new file mode 100644 index 000000000..c797dc666 --- /dev/null +++ b/builtin/providers/oneandone/resource_oneandone_public_ip_test.go @@ -0,0 +1,119 @@ +package oneandone + +import ( + "fmt" + "testing" + + "github.com/1and1/oneandone-cloudserver-sdk-go" + "github.com/hashicorp/terraform/helper/resource" + "github.com/hashicorp/terraform/terraform" + "os" + "time" +) + +func TestAccOneandonePublicIp_Basic(t *testing.T) { + var public_ip oneandone.PublicIp + + reverse_dns := "example.de" + reverse_dns_updated := "example.ba" + + resource.Test(t, resource.TestCase{ + PreCheck: func() { + testAccPreCheck(t) + }, + Providers: testAccProviders, + CheckDestroy: testAccCheckDOneandonePublicIpDestroyCheck, + Steps: []resource.TestStep{ + resource.TestStep{ + Config: fmt.Sprintf(testAccCheckOneandonePublicIp_basic, reverse_dns), + Check: resource.ComposeTestCheckFunc( + func(*terraform.State) error { + time.Sleep(10 * time.Second) + return nil + }, + testAccCheckOneandonePublicIpExists("oneandone_public_ip.ip", &public_ip), + testAccCheckOneandonePublicIpAttributes("oneandone_public_ip.ip", reverse_dns), + resource.TestCheckResourceAttr("oneandone_public_ip.ip", "reverse_dns", reverse_dns), + ), + }, + resource.TestStep{ + Config: fmt.Sprintf(testAccCheckOneandonePublicIp_basic, reverse_dns_updated), + Check: resource.ComposeTestCheckFunc( + func(*terraform.State) error { + time.Sleep(10 * time.Second) + return nil + }, + testAccCheckOneandonePublicIpExists("oneandone_public_ip.ip", &public_ip), + testAccCheckOneandonePublicIpAttributes("oneandone_public_ip.ip", reverse_dns_updated), + resource.TestCheckResourceAttr("oneandone_public_ip.ip", "reverse_dns", reverse_dns_updated), + ), + }, + }, + }) +} + +func testAccCheckDOneandonePublicIpDestroyCheck(s *terraform.State) error { + for _, rs := range s.RootModule().Resources { + if rs.Type != "oneandone_public_ip" { + continue + } + + api := oneandone.New(os.Getenv("ONEANDONE_TOKEN"), oneandone.BaseUrl) + + _, err := api.GetPublicIp(rs.Primary.ID) + + if err == nil { + return fmt.Errorf("Public IP still exists %s %s", rs.Primary.ID, err.Error()) + } + } + + return nil +} +func testAccCheckOneandonePublicIpAttributes(n string, reverse_dns string) resource.TestCheckFunc { + return func(s *terraform.State) error { + rs, ok := s.RootModule().Resources[n] + if !ok { + return fmt.Errorf("Not found: %s", n) + } + if rs.Primary.Attributes["reverse_dns"] != reverse_dns { + return fmt.Errorf("Bad name: expected %s : found %s ", reverse_dns, rs.Primary.Attributes["name"]) + } + + return nil + } +} + +func testAccCheckOneandonePublicIpExists(n string, public_ip *oneandone.PublicIp) resource.TestCheckFunc { + return func(s *terraform.State) error { + rs, ok := s.RootModule().Resources[n] + + if !ok { + return fmt.Errorf("Not found: %s", n) + } + + if rs.Primary.ID == "" { + return fmt.Errorf("No Record ID is set") + } + + api := oneandone.New(os.Getenv("ONEANDONE_TOKEN"), oneandone.BaseUrl) + + found_public_ip, err := api.GetPublicIp(rs.Primary.ID) + + if err != nil { + return fmt.Errorf("Error occured while fetching public IP: %s", rs.Primary.ID) + } + if found_public_ip.Id != rs.Primary.ID { + return fmt.Errorf("Record not found") + } + public_ip = found_public_ip + + return nil + } +} + +const testAccCheckOneandonePublicIp_basic = ` +resource "oneandone_public_ip" "ip" { + "ip_type" = "IPV4" + "reverse_dns" = "%s" + "datacenter" = "GB" +}` diff --git a/builtin/providers/oneandone/resource_oneandone_server.go b/builtin/providers/oneandone/resource_oneandone_server.go new file mode 100644 index 000000000..930aba41a --- /dev/null +++ b/builtin/providers/oneandone/resource_oneandone_server.go @@ -0,0 +1,562 @@ +package oneandone + +import ( + "crypto/x509" + "encoding/pem" + "fmt" + "github.com/1and1/oneandone-cloudserver-sdk-go" + "github.com/hashicorp/terraform/helper/schema" + "golang.org/x/crypto/ssh" + "io/ioutil" + "log" + "strings" + + "errors" +) + +func resourceOneandOneServer() *schema.Resource { + return &schema.Resource{ + Create: resourceOneandOneServerCreate, + Read: resourceOneandOneServerRead, + Update: resourceOneandOneServerUpdate, + Delete: resourceOneandOneServerDelete, + Schema: map[string]*schema.Schema{ + "name": { + Type: schema.TypeString, + Required: true, + }, + "description": { + Type: schema.TypeString, + Optional: true, + }, + "image": { + Type: schema.TypeString, + Required: true, + }, + "vcores": { + Type: schema.TypeInt, + Required: true, + }, + "cores_per_processor": { + Type: schema.TypeInt, + Required: true, + }, + "ram": { + Type: schema.TypeFloat, + Required: true, + }, + "ssh_key_path": { + Type: schema.TypeString, + Optional: true, + }, + "password": { + Type: schema.TypeString, + Optional: true, + Sensitive: true, + }, + "datacenter": { + Type: schema.TypeString, + Optional: true, + }, + "ip": { + Type: schema.TypeString, + Optional: true, + }, + "ips": { + Type: schema.TypeList, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "id": { + Type: schema.TypeString, + Computed: true, + }, + "ip": { + Type: schema.TypeString, + Computed: true, + }, + "firewall_policy_id": { + Type: schema.TypeString, + Optional: true, + }, + }, + }, + Computed: true, + }, + "hdds": { + Type: schema.TypeList, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "id": { + Type: schema.TypeString, + Computed: true, + }, + "disk_size": { + Type: schema.TypeInt, + Required: true, + }, + "is_main": { + Type: schema.TypeBool, + Optional: true, + }, + }, + }, + Required: true, + }, + "firewall_policy_id": { + Type: schema.TypeString, + Optional: true, + }, + "monitoring_policy_id": { + Type: schema.TypeString, + Optional: true, + }, + "loadbalancer_id": { + Type: schema.TypeString, + Optional: true, + }, + }, + } +} + +func resourceOneandOneServerCreate(d *schema.ResourceData, meta interface{}) error { + config := meta.(*Config) + + saps, _ := config.API.ListServerAppliances() + + var sa oneandone.ServerAppliance + for _, a := range saps { + + if a.Type == "IMAGE" && strings.Contains(strings.ToLower(a.Name), strings.ToLower(d.Get("image").(string))) { + sa = a + break + } + } + + var hdds []oneandone.Hdd + if raw, ok := d.GetOk("hdds"); ok { + rawhdds := raw.([]interface{}) + + var istheremain bool + for _, raw := range rawhdds { + hd := raw.(map[string]interface{}) + hdd := oneandone.Hdd{ + Size: hd["disk_size"].(int), + IsMain: hd["is_main"].(bool), + } + + if hdd.IsMain { + if hdd.Size < sa.MinHddSize { + return fmt.Errorf(fmt.Sprintf("Minimum required disk size %d", sa.MinHddSize)) + } + istheremain = true + } + + hdds = append(hdds, hdd) + } + + if !istheremain { + return fmt.Errorf("At least one HDD has to be %s", "`is_main`") + } + } + + req := oneandone.ServerRequest{ + Name: d.Get("name").(string), + Description: d.Get("description").(string), + ApplianceId: sa.Id, + PowerOn: true, + Hardware: oneandone.Hardware{ + Vcores: d.Get("vcores").(int), + CoresPerProcessor: d.Get("cores_per_processor").(int), + Ram: float32(d.Get("ram").(float64)), + Hdds: hdds, + }, + } + + if raw, ok := d.GetOk("ip"); ok { + + new_ip := raw.(string) + + ips, err := config.API.ListPublicIps() + if err != nil { + return err + } + + for _, ip := range ips { + if ip.IpAddress == new_ip { + req.IpId = ip.Id + break + } + } + + log.Println("[DEBUG] req.IP", req.IpId) + } + + if raw, ok := d.GetOk("datacenter"); ok { + + dcs, err := config.API.ListDatacenters() + + if err != nil { + return fmt.Errorf("An error occured while fetching list of datacenters %s", err) + + } + + decenter := raw.(string) + for _, dc := range dcs { + if strings.ToLower(dc.CountryCode) == strings.ToLower(decenter) { + req.DatacenterId = dc.Id + break + } + } + } + + if fwp_id, ok := d.GetOk("firewall_policy_id"); ok { + req.FirewallPolicyId = fwp_id.(string) + } + + if mp_id, ok := d.GetOk("monitoring_policy_id"); ok { + req.MonitoringPolicyId = mp_id.(string) + } + + if mp_id, ok := d.GetOk("loadbalancer_id"); ok { + req.LoadBalancerId = mp_id.(string) + } + + var privateKey string + if raw, ok := d.GetOk("ssh_key_path"); ok { + rawpath := raw.(string) + + priv, publicKey, err := getSshKey(rawpath) + privateKey = priv + if err != nil { + return err + } + + req.SSHKey = publicKey + } + + var password string + if raw, ok := d.GetOk("password"); ok { + req.Password = raw.(string) + password = req.Password + } + + server_id, server, err := config.API.CreateServer(&req) + if err != nil { + return err + } + + err = config.API.WaitForState(server, "POWERED_ON", 10, config.Retries) + + d.SetId(server_id) + server, err = config.API.GetServer(d.Id()) + if err != nil { + return err + } + + if password == "" { + password = server.FirstPassword + } + d.SetConnInfo(map[string]string{ + "type": "ssh", + "host": server.Ips[0].Ip, + "password": password, + "private_key": privateKey, + }) + + return resourceOneandOneServerRead(d, meta) +} + +func resourceOneandOneServerRead(d *schema.ResourceData, meta interface{}) error { + config := meta.(*Config) + + server, err := config.API.GetServer(d.Id()) + + if err != nil { + if strings.Contains(err.Error(), "404") { + d.SetId("") + return nil + } + return err + } + + d.Set("name", server.Name) + d.Set("datacenter", server.Datacenter.CountryCode) + + d.Set("hdds", readHdds(server.Hardware)) + + d.Set("ips", readIps(server.Ips)) + + if len(server.FirstPassword) > 0 { + d.Set("password", server.FirstPassword) + } + + return nil +} + +func resourceOneandOneServerUpdate(d *schema.ResourceData, meta interface{}) error { + config := meta.(*Config) + + if d.HasChange("name") || d.HasChange("description") { + _, name := d.GetChange("name") + _, description := d.GetChange("description") + server, err := config.API.RenameServer(d.Id(), name.(string), description.(string)) + if err != nil { + return err + } + + err = config.API.WaitForState(server, "POWERED_ON", 10, config.Retries) + + } + + if d.HasChange("hdds") { + oldV, newV := d.GetChange("hdds") + newValues := newV.([]interface{}) + oldValues := oldV.([]interface{}) + + if len(oldValues) > len(newValues) { + diff := difference(oldValues, newValues) + for _, old := range diff { + o := old.(map[string]interface{}) + old_id := o["id"].(string) + server, err := config.API.DeleteServerHdd(d.Id(), old_id) + if err != nil { + return err + } + + err = config.API.WaitForState(server, "POWERED_ON", 10, config.Retries) + if err != nil { + return err + } + } + } else { + for _, newHdd := range newValues { + n := newHdd.(map[string]interface{}) + //old := oldHdd.(map[string]interface{}) + + if n["id"].(string) == "" { + hdds := oneandone.ServerHdds{ + Hdds: []oneandone.Hdd{ + { + Size: n["disk_size"].(int), + IsMain: n["is_main"].(bool), + }, + }, + } + + server, err := config.API.AddServerHdds(d.Id(), &hdds) + + if err != nil { + return err + } + err = config.API.WaitForState(server, "POWERED_ON", 10, config.Retries) + if err != nil { + return err + } + } else { + id := n["id"].(string) + isMain := n["is_main"].(bool) + + if id != "" && !isMain { + log.Println("[DEBUG] Resizing existing HDD") + config.API.ResizeServerHdd(d.Id(), id, n["disk_size"].(int)) + } + } + + } + } + } + + if d.HasChange("monitoring_policy_id") { + o, n := d.GetChange("monitoring_policy_id") + + if n == nil { + mp, err := config.API.RemoveMonitoringPolicyServer(o.(string), d.Id()) + + if err != nil { + return err + } + + err = config.API.WaitForState(mp, "ACTIVE", 30, config.Retries) + if err != nil { + return err + } + } else { + mp, err := config.API.AttachMonitoringPolicyServers(n.(string), []string{d.Id()}) + if err != nil { + return err + } + + err = config.API.WaitForState(mp, "ACTIVE", 30, config.Retries) + if err != nil { + return err + } + } + } + + if d.HasChange("loadbalancer_id") { + o, n := d.GetChange("loadbalancer_id") + server, err := config.API.GetServer(d.Id()) + if err != nil { + return err + } + + if n == nil || n.(string) == "" { + log.Println("[DEBUG] Removing") + log.Println("[DEBUG] IPS:", server.Ips) + + for _, ip := range server.Ips { + mp, err := config.API.DeleteLoadBalancerServerIp(o.(string), ip.Id) + + if err != nil { + return err + } + + err = config.API.WaitForState(mp, "ACTIVE", 30, config.Retries) + if err != nil { + return err + } + } + } else { + log.Println("[DEBUG] Adding") + ip_ids := []string{} + for _, ip := range server.Ips { + ip_ids = append(ip_ids, ip.Id) + } + mp, err := config.API.AddLoadBalancerServerIps(n.(string), ip_ids) + if err != nil { + return err + } + + err = config.API.WaitForState(mp, "ACTIVE", 30, config.Retries) + if err != nil { + return err + } + + } + } + + if d.HasChange("firewall_policy_id") { + server, err := config.API.GetServer(d.Id()) + if err != nil { + return err + } + + o, n := d.GetChange("firewall_policy_id") + if n == nil { + for _, ip := range server.Ips { + mp, err := config.API.DeleteFirewallPolicyServerIp(o.(string), ip.Id) + if err != nil { + return err + } + + err = config.API.WaitForState(mp, "ACTIVE", 30, config.Retries) + if err != nil { + return err + } + } + } else { + ip_ids := []string{} + for _, ip := range server.Ips { + ip_ids = append(ip_ids, ip.Id) + } + + mp, err := config.API.AddFirewallPolicyServerIps(n.(string), ip_ids) + if err != nil { + return err + } + + err = config.API.WaitForState(mp, "ACTIVE", 30, config.Retries) + if err != nil { + return err + } + } + } + + return resourceOneandOneServerRead(d, meta) +} + +func resourceOneandOneServerDelete(d *schema.ResourceData, meta interface{}) error { + config := meta.(*Config) + + _, ok := d.GetOk("ip") + + server, err := config.API.DeleteServer(d.Id(), ok) + if err != nil { + return err + } + + err = config.API.WaitUntilDeleted(server) + + if err != nil { + log.Println("[DEBUG] ************ ERROR While waiting ************") + return err + } + return nil +} + +func readHdds(hardware *oneandone.Hardware) []map[string]interface{} { + hdds := make([]map[string]interface{}, 0, len(hardware.Hdds)) + + for _, hd := range hardware.Hdds { + hdds = append(hdds, map[string]interface{}{ + "id": hd.Id, + "disk_size": hd.Size, + "is_main": hd.IsMain, + }) + } + + return hdds +} + +func readIps(ips []oneandone.ServerIp) []map[string]interface{} { + raw := make([]map[string]interface{}, 0, len(ips)) + for _, ip := range ips { + + toadd := map[string]interface{}{ + "ip": ip.Ip, + "id": ip.Id, + } + + if ip.Firewall != nil { + toadd["firewall_policy_id"] = ip.Firewall.Id + } + raw = append(raw, toadd) + } + + return raw +} + +func getSshKey(path string) (privatekey string, publickey string, err error) { + pemBytes, err := ioutil.ReadFile(path) + + if err != nil { + return "", "", err + } + + block, _ := pem.Decode(pemBytes) + + if block == nil { + return "", "", errors.New("File " + path + " contains nothing") + } + + priv, err := x509.ParsePKCS1PrivateKey(block.Bytes) + + if err != nil { + return "", "", err + } + + priv_blk := pem.Block{ + Type: "RSA PRIVATE KEY", + Headers: nil, + Bytes: x509.MarshalPKCS1PrivateKey(priv), + } + + pub, err := ssh.NewPublicKey(&priv.PublicKey) + if err != nil { + return "", "", err + } + publickey = string(ssh.MarshalAuthorizedKey(pub)) + privatekey = string(pem.EncodeToMemory(&priv_blk)) + + return privatekey, publickey, nil +} diff --git a/builtin/providers/oneandone/resource_oneandone_server_test.go b/builtin/providers/oneandone/resource_oneandone_server_test.go new file mode 100644 index 000000000..ed643abfa --- /dev/null +++ b/builtin/providers/oneandone/resource_oneandone_server_test.go @@ -0,0 +1,130 @@ +package oneandone + +import ( + "fmt" + "testing" + + "github.com/1and1/oneandone-cloudserver-sdk-go" + "github.com/hashicorp/terraform/helper/resource" + "github.com/hashicorp/terraform/terraform" + "os" + "time" +) + +func TestAccOneandoneServer_Basic(t *testing.T) { + var server oneandone.Server + + name := "test_server" + name_updated := "test_server_renamed" + + resource.Test(t, resource.TestCase{ + PreCheck: func() { + testAccPreCheck(t) + }, + Providers: testAccProviders, + CheckDestroy: testAccCheckDOneandoneServerDestroyCheck, + Steps: []resource.TestStep{ + resource.TestStep{ + Config: fmt.Sprintf(testAccCheckOneandoneServer_basic, name, name), + Check: resource.ComposeTestCheckFunc( + func(*terraform.State) error { + time.Sleep(10 * time.Second) + return nil + }, + testAccCheckOneandoneServerExists("oneandone_server.server", &server), + testAccCheckOneandoneServerAttributes("oneandone_server.server", name), + resource.TestCheckResourceAttr("oneandone_server.server", "name", name), + ), + }, + resource.TestStep{ + Config: fmt.Sprintf(testAccCheckOneandoneServer_basic, name_updated, name_updated), + Check: resource.ComposeTestCheckFunc( + func(*terraform.State) error { + time.Sleep(10 * time.Second) + return nil + }, + testAccCheckOneandoneServerExists("oneandone_server.server", &server), + testAccCheckOneandoneServerAttributes("oneandone_server.server", name_updated), + resource.TestCheckResourceAttr("oneandone_server.server", "name", name_updated), + ), + }, + }, + }) +} + +func testAccCheckDOneandoneServerDestroyCheck(s *terraform.State) error { + for _, rs := range s.RootModule().Resources { + if rs.Type != "oneandone_server" { + continue + } + + api := oneandone.New(os.Getenv("ONEANDONE_TOKEN"), oneandone.BaseUrl) + + _, err := api.GetServer(rs.Primary.ID) + + if err == nil { + return fmt.Errorf("Server still exists %s %s", rs.Primary.ID, err.Error()) + } + } + + return nil +} +func testAccCheckOneandoneServerAttributes(n string, reverse_dns string) resource.TestCheckFunc { + return func(s *terraform.State) error { + rs, ok := s.RootModule().Resources[n] + if !ok { + return fmt.Errorf("Not found: %s", n) + } + if rs.Primary.Attributes["name"] != reverse_dns { + return fmt.Errorf("Bad name: expected %s : found %s ", reverse_dns, rs.Primary.Attributes["name"]) + } + + return nil + } +} + +func testAccCheckOneandoneServerExists(n string, server *oneandone.Server) resource.TestCheckFunc { + return func(s *terraform.State) error { + rs, ok := s.RootModule().Resources[n] + + if !ok { + return fmt.Errorf("Not found: %s", n) + } + + if rs.Primary.ID == "" { + return fmt.Errorf("No Record ID is set") + } + + api := oneandone.New(os.Getenv("ONEANDONE_TOKEN"), oneandone.BaseUrl) + + found_server, err := api.GetServer(rs.Primary.ID) + + if err != nil { + return fmt.Errorf("Error occured while fetching Server: %s", rs.Primary.ID) + } + if found_server.Id != rs.Primary.ID { + return fmt.Errorf("Record not found") + } + server = found_server + + return nil + } +} + +const testAccCheckOneandoneServer_basic = ` +resource "oneandone_server" "server" { + name = "%s" + description = "%s" + image = "ubuntu" + datacenter = "GB" + vcores = 1 + cores_per_processor = 1 + ram = 2 + password = "Kv40kd8PQb" + hdds = [ + { + disk_size = 20 + is_main = true + } + ] +}` diff --git a/builtin/providers/oneandone/resource_oneandone_vpn.go b/builtin/providers/oneandone/resource_oneandone_vpn.go new file mode 100644 index 000000000..865c3361a --- /dev/null +++ b/builtin/providers/oneandone/resource_oneandone_vpn.go @@ -0,0 +1,217 @@ +package oneandone + +import ( + "crypto/md5" + "encoding/base64" + "fmt" + "github.com/1and1/oneandone-cloudserver-sdk-go" + "github.com/hashicorp/terraform/helper/schema" + "io" + "os" + fp "path/filepath" + "strings" +) + +func resourceOneandOneVPN() *schema.Resource { + return &schema.Resource{ + Create: resourceOneandOneVPNCreate, + Read: resourceOneandOneVPNRead, + Update: resourceOneandOneVPNUpdate, + Delete: resourceOneandOneVPNDelete, + Schema: map[string]*schema.Schema{ + + "name": { + Type: schema.TypeString, + Required: true, + }, + "description": { + Type: schema.TypeString, + Optional: true, + }, + "download_path": { + Type: schema.TypeString, + Computed: true, + }, + "datacenter": { + Type: schema.TypeString, + Optional: true, + }, + "file_name": { + Type: schema.TypeString, + Computed: true, + }, + }, + } +} + +func resourceOneandOneVPNCreate(d *schema.ResourceData, meta interface{}) error { + config := meta.(*Config) + + var datacenter string + + if raw, ok := d.GetOk("datacenter"); ok { + dcs, err := config.API.ListDatacenters() + if err != nil { + return fmt.Errorf("An error occured while fetching list of datacenters %s", err) + } + + decenter := raw.(string) + for _, dc := range dcs { + if strings.ToLower(dc.CountryCode) == strings.ToLower(decenter) { + datacenter = dc.Id + break + } + } + } + + var description string + if raw, ok := d.GetOk("description"); ok { + description = raw.(string) + } + + vpn_id, vpn, err := config.API.CreateVPN(d.Get("name").(string), description, datacenter) + if err != nil { + return err + } + + err = config.API.WaitForState(vpn, "ACTIVE", 10, config.Retries) + if err != nil { + return err + } + + d.SetId(vpn_id) + + return resourceOneandOneVPNRead(d, meta) +} + +func resourceOneandOneVPNUpdate(d *schema.ResourceData, meta interface{}) error { + config := meta.(*Config) + + if d.HasChange("name") || d.HasChange("description") { + + vpn, err := config.API.ModifyVPN(d.Id(), d.Get("name").(string), d.Get("description").(string)) + if err != nil { + return err + } + + err = config.API.WaitForState(vpn, "ACTIVE", 10, config.Retries) + if err != nil { + return err + } + } + + return resourceOneandOneVPNRead(d, meta) +} + +func resourceOneandOneVPNRead(d *schema.ResourceData, meta interface{}) error { + config := meta.(*Config) + + vpn, err := config.API.GetVPN(d.Id()) + + base64_str, err := config.API.GetVPNConfigFile(d.Id()) + if err != nil { + if strings.Contains(err.Error(), "404") { + d.SetId("") + return nil + } + return err + } + + var download_path string + if raw, ok := d.GetOk("download_path"); ok { + download_path = raw.(string) + } + + path, fileName, err := writeCofnig(vpn, download_path, base64_str) + if err != nil { + return err + } + + d.Set("name", vpn.Name) + d.Set("description", vpn.Description) + d.Set("download_path", path) + d.Set("file_name", fileName) + d.Set("datacenter", vpn.Datacenter.CountryCode) + + return nil +} + +func writeCofnig(vpn *oneandone.VPN, path, base64config string) (string, string, error) { + data, err := base64.StdEncoding.DecodeString(base64config) + if err != nil { + return "", "", err + } + + var fileName string + if vpn.CloudPanelId != "" { + fileName = vpn.CloudPanelId + ".zip" + } else { + fileName = "vpn_" + fmt.Sprintf("%x", md5.Sum(data)) + ".zip" + } + + if path == "" { + path, err = os.Getwd() + if err != nil { + return "", "", err + } + } + + if !fp.IsAbs(path) { + path, err = fp.Abs(path) + if err != nil { + return "", "", err + } + } + + _, err = os.Stat(path) + if err != nil { + if os.IsNotExist(err) { + // make all dirs + os.MkdirAll(path, 0666) + } else { + return "", "", err + } + } + + fpath := fp.Join(path, fileName) + + f, err := os.OpenFile(fpath, os.O_CREATE|os.O_WRONLY, 0666) + defer f.Close() + + if err != nil { + return "", "", err + } + + n, err := f.Write(data) + if err == nil && n < len(data) { + err = io.ErrShortWrite + } + + if err != nil { + return "", "", err + } + + return path, fileName, nil + +} + +func resourceOneandOneVPNDelete(d *schema.ResourceData, meta interface{}) error { + config := meta.(*Config) + + vpn, err := config.API.DeleteVPN(d.Id()) + if err != nil { + return err + } + + err = config.API.WaitUntilDeleted(vpn) + if err != nil { + return err + } + + fullPath := fp.Join(d.Get("download_path").(string), d.Get("file_name").(string)) + if _, err := os.Stat(fullPath); !os.IsNotExist(err) { + os.Remove(fullPath) + } + + return nil +} diff --git a/builtin/providers/oneandone/resource_oneandone_vpn_test.go b/builtin/providers/oneandone/resource_oneandone_vpn_test.go new file mode 100644 index 000000000..94e84bb61 --- /dev/null +++ b/builtin/providers/oneandone/resource_oneandone_vpn_test.go @@ -0,0 +1,119 @@ +package oneandone + +import ( + "fmt" + "testing" + + "github.com/1and1/oneandone-cloudserver-sdk-go" + "github.com/hashicorp/terraform/helper/resource" + "github.com/hashicorp/terraform/terraform" + "os" + "time" +) + +func TestAccOneandoneVpn_Basic(t *testing.T) { + var server oneandone.VPN + + name := "test" + name_updated := "test1" + + resource.Test(t, resource.TestCase{ + PreCheck: func() { + testAccPreCheck(t) + }, + Providers: testAccProviders, + CheckDestroy: testAccCheckDOneandoneVPNDestroyCheck, + Steps: []resource.TestStep{ + resource.TestStep{ + Config: fmt.Sprintf(testAccCheckOneandoneVPN_basic, name), + Check: resource.ComposeTestCheckFunc( + func(*terraform.State) error { + time.Sleep(10 * time.Second) + return nil + }, + testAccCheckOneandoneVPNExists("oneandone_vpn.vpn", &server), + testAccCheckOneandoneVPNAttributes("oneandone_vpn.vpn", name), + resource.TestCheckResourceAttr("oneandone_vpn.vpn", "name", name), + ), + }, + resource.TestStep{ + Config: fmt.Sprintf(testAccCheckOneandoneVPN_basic, name_updated), + Check: resource.ComposeTestCheckFunc( + func(*terraform.State) error { + time.Sleep(10 * time.Second) + return nil + }, + testAccCheckOneandoneVPNExists("oneandone_vpn.vpn", &server), + testAccCheckOneandoneVPNAttributes("oneandone_vpn.vpn", name_updated), + resource.TestCheckResourceAttr("oneandone_vpn.vpn", "name", name_updated), + ), + }, + }, + }) +} + +func testAccCheckDOneandoneVPNDestroyCheck(s *terraform.State) error { + for _, rs := range s.RootModule().Resources { + if rs.Type != "oneandone_server" { + continue + } + + api := oneandone.New(os.Getenv("ONEANDONE_TOKEN"), oneandone.BaseUrl) + + _, err := api.GetVPN(rs.Primary.ID) + + if err == nil { + return fmt.Errorf("VPN still exists %s %s", rs.Primary.ID, err.Error()) + } + } + + return nil +} +func testAccCheckOneandoneVPNAttributes(n string, reverse_dns string) resource.TestCheckFunc { + return func(s *terraform.State) error { + rs, ok := s.RootModule().Resources[n] + if !ok { + return fmt.Errorf("Not found: %s", n) + } + if rs.Primary.Attributes["name"] != reverse_dns { + return fmt.Errorf("Bad name: expected %s : found %s ", reverse_dns, rs.Primary.Attributes["name"]) + } + + return nil + } +} + +func testAccCheckOneandoneVPNExists(n string, server *oneandone.VPN) resource.TestCheckFunc { + return func(s *terraform.State) error { + rs, ok := s.RootModule().Resources[n] + + if !ok { + return fmt.Errorf("Not found: %s", n) + } + + if rs.Primary.ID == "" { + return fmt.Errorf("No Record ID is set") + } + + api := oneandone.New(os.Getenv("ONEANDONE_TOKEN"), oneandone.BaseUrl) + + found_server, err := api.GetVPN(rs.Primary.ID) + + if err != nil { + return fmt.Errorf("Error occured while fetching VPN: %s", rs.Primary.ID) + } + if found_server.Id != rs.Primary.ID { + return fmt.Errorf("Record not found") + } + server = found_server + + return nil + } +} + +const testAccCheckOneandoneVPN_basic = ` +resource "oneandone_vpn" "vpn" { + datacenter = "GB" + name = "%s" + description = "ttest descr" +}` diff --git a/builtin/providers/oneandone/resources_oneandone_shared_storage.go b/builtin/providers/oneandone/resources_oneandone_shared_storage.go new file mode 100644 index 000000000..f690e0cf6 --- /dev/null +++ b/builtin/providers/oneandone/resources_oneandone_shared_storage.go @@ -0,0 +1,256 @@ +package oneandone + +import ( + "fmt" + "github.com/1and1/oneandone-cloudserver-sdk-go" + "github.com/hashicorp/terraform/helper/schema" + "strings" +) + +func resourceOneandOneSharedStorage() *schema.Resource { + return &schema.Resource{ + Create: resourceOneandOneSharedStorageCreate, + Read: resourceOneandOneSharedStorageRead, + Update: resourceOneandOneSharedStorageUpdate, + Delete: resourceOneandOneSharedStorageDelete, + Schema: map[string]*schema.Schema{ + "name": { + Type: schema.TypeString, + Required: true, + }, + "description": { + Type: schema.TypeString, + Optional: true, + }, + "size": { + Type: schema.TypeInt, + Required: true, + }, + "datacenter": { + Type: schema.TypeString, + Required: true, + }, + "storage_servers": { + Type: schema.TypeList, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "id": { + Type: schema.TypeString, + Required: true, + }, + "rights": { + Type: schema.TypeString, + Required: true, + }, + }, + }, + Optional: true, + }, + }, + } +} + +func resourceOneandOneSharedStorageCreate(d *schema.ResourceData, meta interface{}) error { + config := meta.(*Config) + + req := oneandone.SharedStorageRequest{ + Name: d.Get("name").(string), + Size: oneandone.Int2Pointer(d.Get("size").(int)), + } + + if raw, ok := d.GetOk("description"); ok { + req.Description = raw.(string) + + } + + if raw, ok := d.GetOk("datacenter"); ok { + dcs, err := config.API.ListDatacenters() + + if err != nil { + return fmt.Errorf("An error occured while fetching list of datacenters %s", err) + + } + + decenter := raw.(string) + for _, dc := range dcs { + if strings.ToLower(dc.CountryCode) == strings.ToLower(decenter) { + req.DatacenterId = dc.Id + break + } + } + } + + ss_id, ss, err := config.API.CreateSharedStorage(&req) + if err != nil { + return err + } + + err = config.API.WaitForState(ss, "ACTIVE", 10, config.Retries) + if err != nil { + return err + } + d.SetId(ss_id) + + if raw, ok := d.GetOk("storage_servers"); ok { + + storage_servers := []oneandone.SharedStorageServer{} + + rawRights := raw.([]interface{}) + for _, raws_ss := range rawRights { + ss := raws_ss.(map[string]interface{}) + storage_server := oneandone.SharedStorageServer{ + Id: ss["id"].(string), + Rights: ss["rights"].(string), + } + storage_servers = append(storage_servers, storage_server) + } + + ss, err := config.API.AddSharedStorageServers(ss_id, storage_servers) + + if err != nil { + return err + } + + err = config.API.WaitForState(ss, "ACTIVE", 10, 30) + if err != nil { + return err + } + } + + return resourceOneandOneSharedStorageRead(d, meta) +} + +func resourceOneandOneSharedStorageUpdate(d *schema.ResourceData, meta interface{}) error { + config := meta.(*Config) + + if d.HasChange("name") || d.HasChange("description") || d.HasChange("size") { + ssu := oneandone.SharedStorageRequest{} + if d.HasChange("name") { + _, n := d.GetChange("name") + ssu.Name = n.(string) + } + if d.HasChange("description") { + _, n := d.GetChange("description") + ssu.Description = n.(string) + } + if d.HasChange("size") { + _, n := d.GetChange("size") + ssu.Size = oneandone.Int2Pointer(n.(int)) + } + + ss, err := config.API.UpdateSharedStorage(d.Id(), &ssu) + + if err != nil { + return err + } + err = config.API.WaitForState(ss, "ACTIVE", 10, 30) + if err != nil { + return err + } + + } + + if d.HasChange("storage_servers") { + + o, n := d.GetChange("storage_servers") + + oldV := o.([]interface{}) + + for _, old := range oldV { + ol := old.(map[string]interface{}) + + ss, err := config.API.DeleteSharedStorageServer(d.Id(), ol["id"].(string)) + if err != nil { + return err + } + + err = config.API.WaitForState(ss, "ACTIVE", 10, config.Retries) + + if err != nil { + return err + } + + } + + newV := n.([]interface{}) + + ids := []oneandone.SharedStorageServer{} + for _, newValue := range newV { + nn := newValue.(map[string]interface{}) + ids = append(ids, oneandone.SharedStorageServer{ + Id: nn["id"].(string), + Rights: nn["rights"].(string), + }) + } + + if len(ids) > 0 { + ss, err := config.API.AddSharedStorageServers(d.Id(), ids) + if err != nil { + return err + } + + err = config.API.WaitForState(ss, "ACTIVE", 10, config.Retries) + + if err != nil { + return err + } + } + + //DeleteSharedStorageServer + + } + + return resourceOneandOneSharedStorageRead(d, meta) +} + +func resourceOneandOneSharedStorageRead(d *schema.ResourceData, meta interface{}) error { + config := meta.(*Config) + + ss, err := config.API.GetSharedStorage(d.Id()) + if err != nil { + if strings.Contains(err.Error(), "404") { + d.SetId("") + return nil + } + return err + } + + d.Set("name", ss.Name) + d.Set("description", ss.Description) + d.Set("size", ss.Size) + d.Set("datacenter", ss.Datacenter.CountryCode) + d.Set("storage_servers", getStorageServers(ss.Servers)) + + return nil +} + +func getStorageServers(servers []oneandone.SharedStorageServer) []map[string]interface{} { + raw := make([]map[string]interface{}, 0, len(servers)) + + for _, server := range servers { + + toadd := map[string]interface{}{ + "id": server.Id, + "rights": server.Rights, + } + + raw = append(raw, toadd) + } + + return raw + +} +func resourceOneandOneSharedStorageDelete(d *schema.ResourceData, meta interface{}) error { + config := meta.(*Config) + + ss, err := config.API.DeleteSharedStorage(d.Id()) + if err != nil { + return err + } + err = config.API.WaitUntilDeleted(ss) + if err != nil { + return err + } + + return nil +} diff --git a/builtin/providers/oneandone/resources_oneandone_shared_storage_test.go b/builtin/providers/oneandone/resources_oneandone_shared_storage_test.go new file mode 100644 index 000000000..dcc07302a --- /dev/null +++ b/builtin/providers/oneandone/resources_oneandone_shared_storage_test.go @@ -0,0 +1,120 @@ +package oneandone + +import ( + "fmt" + "testing" + + "github.com/1and1/oneandone-cloudserver-sdk-go" + "github.com/hashicorp/terraform/helper/resource" + "github.com/hashicorp/terraform/terraform" + "os" + "time" +) + +func TestAccOneandoneSharedStorage_Basic(t *testing.T) { + var storage oneandone.SharedStorage + + name := "test_storage" + name_updated := "test1" + + resource.Test(t, resource.TestCase{ + PreCheck: func() { + testAccPreCheck(t) + }, + Providers: testAccProviders, + CheckDestroy: testAccCheckDOneandoneSharedStorageDestroyCheck, + Steps: []resource.TestStep{ + resource.TestStep{ + Config: fmt.Sprintf(testAccCheckOneandoneSharedStorage_basic, name), + Check: resource.ComposeTestCheckFunc( + func(*terraform.State) error { + time.Sleep(10 * time.Second) + return nil + }, + testAccCheckOneandoneSharedStorageExists("oneandone_shared_storage.storage", &storage), + testAccCheckOneandoneSharedStorageAttributes("oneandone_shared_storage.storage", name), + resource.TestCheckResourceAttr("oneandone_shared_storage.storage", "name", name), + ), + }, + resource.TestStep{ + Config: fmt.Sprintf(testAccCheckOneandoneSharedStorage_basic, name_updated), + Check: resource.ComposeTestCheckFunc( + func(*terraform.State) error { + time.Sleep(10 * time.Second) + return nil + }, + testAccCheckOneandoneSharedStorageExists("oneandone_shared_storage.storage", &storage), + testAccCheckOneandoneSharedStorageAttributes("oneandone_shared_storage.storage", name_updated), + resource.TestCheckResourceAttr("oneandone_shared_storage.storage", "name", name_updated), + ), + }, + }, + }) +} + +func testAccCheckDOneandoneSharedStorageDestroyCheck(s *terraform.State) error { + for _, rs := range s.RootModule().Resources { + if rs.Type != "oneandone_shared_storage" { + continue + } + + api := oneandone.New(os.Getenv("ONEANDONE_TOKEN"), oneandone.BaseUrl) + + _, err := api.GetVPN(rs.Primary.ID) + + if err == nil { + return fmt.Errorf("VPN still exists %s %s", rs.Primary.ID, err.Error()) + } + } + + return nil +} +func testAccCheckOneandoneSharedStorageAttributes(n string, reverse_dns string) resource.TestCheckFunc { + return func(s *terraform.State) error { + rs, ok := s.RootModule().Resources[n] + if !ok { + return fmt.Errorf("Not found: %s", n) + } + if rs.Primary.Attributes["name"] != reverse_dns { + return fmt.Errorf("Bad name: expected %s : found %s ", reverse_dns, rs.Primary.Attributes["name"]) + } + + return nil + } +} + +func testAccCheckOneandoneSharedStorageExists(n string, storage *oneandone.SharedStorage) resource.TestCheckFunc { + return func(s *terraform.State) error { + rs, ok := s.RootModule().Resources[n] + + if !ok { + return fmt.Errorf("Not found: %s", n) + } + + if rs.Primary.ID == "" { + return fmt.Errorf("No Record ID is set") + } + + api := oneandone.New(os.Getenv("ONEANDONE_TOKEN"), oneandone.BaseUrl) + + found_storage, err := api.GetSharedStorage(rs.Primary.ID) + + if err != nil { + return fmt.Errorf("Error occured while fetching SharedStorage: %s", rs.Primary.ID) + } + if found_storage.Id != rs.Primary.ID { + return fmt.Errorf("Record not found") + } + storage = found_storage + + return nil + } +} + +const testAccCheckOneandoneSharedStorage_basic = ` +resource "oneandone_shared_storage" "storage" { + name = "%s" + description = "ttt" + size = 50 + datacenter = "GB" +}` diff --git a/builtin/providers/openstack/config.go b/builtin/providers/openstack/config.go index 651b66783..0c6cb8995 100644 --- a/builtin/providers/openstack/config.go +++ b/builtin/providers/openstack/config.go @@ -113,8 +113,8 @@ func (c *Config) loadAndValidate() error { transport := &http.Transport{Proxy: http.ProxyFromEnvironment, TLSClientConfig: config} client.HTTPClient = http.Client{ Transport: &LogRoundTripper{ - rt: transport, - osDebug: osDebug, + Rt: transport, + OsDebug: osDebug, }, } diff --git a/builtin/providers/openstack/import_openstack_blockstorage_volume_v1_test.go b/builtin/providers/openstack/import_openstack_blockstorage_volume_v1_test.go index 411bdefa9..4a7e08401 100644 --- a/builtin/providers/openstack/import_openstack_blockstorage_volume_v1_test.go +++ b/builtin/providers/openstack/import_openstack_blockstorage_volume_v1_test.go @@ -6,7 +6,7 @@ import ( "github.com/hashicorp/terraform/helper/resource" ) -func TestAccOpenStackBlockStorageV1Volume_importBasic(t *testing.T) { +func TestAccBlockStorageV1Volume_importBasic(t *testing.T) { resourceName := "openstack_blockstorage_volume_v1.volume_1" resource.Test(t, resource.TestCase{ diff --git a/builtin/providers/openstack/import_openstack_blockstorage_volume_v2_test.go b/builtin/providers/openstack/import_openstack_blockstorage_volume_v2_test.go index c30485b6e..1f5365274 100644 --- a/builtin/providers/openstack/import_openstack_blockstorage_volume_v2_test.go +++ b/builtin/providers/openstack/import_openstack_blockstorage_volume_v2_test.go @@ -6,7 +6,7 @@ import ( "github.com/hashicorp/terraform/helper/resource" ) -func TestAccOpenStackBlockStorageV2Volume_importBasic(t *testing.T) { +func TestAccBlockStorageV2Volume_importBasic(t *testing.T) { resourceName := "openstack_blockstorage_volume_v2.volume_1" resource.Test(t, resource.TestCase{ diff --git a/builtin/providers/openstack/import_openstack_compute_floatingip_associate_v2_test.go b/builtin/providers/openstack/import_openstack_compute_floatingip_associate_v2_test.go index d2bad3a00..8bada4947 100644 --- a/builtin/providers/openstack/import_openstack_compute_floatingip_associate_v2_test.go +++ b/builtin/providers/openstack/import_openstack_compute_floatingip_associate_v2_test.go @@ -6,7 +6,7 @@ import ( "github.com/hashicorp/terraform/helper/resource" ) -func TestAccOpenStackComputeV2FloatingIPAssociate_importBasic(t *testing.T) { +func TestAccComputeV2FloatingIPAssociate_importBasic(t *testing.T) { resourceName := "openstack_compute_floatingip_associate_v2.fip_1" resource.Test(t, resource.TestCase{ diff --git a/builtin/providers/openstack/import_openstack_compute_keypair_v2_test.go b/builtin/providers/openstack/import_openstack_compute_keypair_v2_test.go index be5e26109..89e094463 100644 --- a/builtin/providers/openstack/import_openstack_compute_keypair_v2_test.go +++ b/builtin/providers/openstack/import_openstack_compute_keypair_v2_test.go @@ -6,8 +6,8 @@ import ( "github.com/hashicorp/terraform/helper/resource" ) -func TestAccOpenStackComputeV2Keypair_importBasic(t *testing.T) { - resourceName := "openstack_compute_keypair_v2.foo" +func TestAccComputeV2Keypair_importBasic(t *testing.T) { + resourceName := "openstack_compute_keypair_v2.kp_1" resource.Test(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, diff --git a/builtin/providers/openstack/import_openstack_fw_firewall_v1_test.go b/builtin/providers/openstack/import_openstack_fw_firewall_v1_test.go index d1b456e1f..c7ea21930 100644 --- a/builtin/providers/openstack/import_openstack_fw_firewall_v1_test.go +++ b/builtin/providers/openstack/import_openstack_fw_firewall_v1_test.go @@ -6,7 +6,7 @@ import ( "github.com/hashicorp/terraform/helper/resource" ) -func TestAccOpenStackFWFirewallV1_importBasic(t *testing.T) { +func TestAccFWFirewallV1_importBasic(t *testing.T) { resourceName := "openstack_fw_firewall_v1.fw_1" resource.Test(t, resource.TestCase{ diff --git a/builtin/providers/openstack/import_openstack_fw_policy_v1_test.go b/builtin/providers/openstack/import_openstack_fw_policy_v1_test.go index ec52a866c..6b9d9f25c 100644 --- a/builtin/providers/openstack/import_openstack_fw_policy_v1_test.go +++ b/builtin/providers/openstack/import_openstack_fw_policy_v1_test.go @@ -6,7 +6,7 @@ import ( "github.com/hashicorp/terraform/helper/resource" ) -func TestAccOpenStackFWPolicyV1_importBasic(t *testing.T) { +func TestAccFWPolicyV1_importBasic(t *testing.T) { resourceName := "openstack_fw_policy_v1.policy_1" resource.Test(t, resource.TestCase{ diff --git a/builtin/providers/openstack/import_openstack_fw_rule_v1_test.go b/builtin/providers/openstack/import_openstack_fw_rule_v1_test.go index 6b3ee0b07..c586d1085 100644 --- a/builtin/providers/openstack/import_openstack_fw_rule_v1_test.go +++ b/builtin/providers/openstack/import_openstack_fw_rule_v1_test.go @@ -6,7 +6,7 @@ import ( "github.com/hashicorp/terraform/helper/resource" ) -func TestAccOpenStackFWRuleV1_importBasic(t *testing.T) { +func TestAccFWRuleV1_importBasic(t *testing.T) { resourceName := "openstack_fw_rule_v1.rule_1" resource.Test(t, resource.TestCase{ diff --git a/builtin/providers/openstack/import_openstack_lb_member_v1_test.go b/builtin/providers/openstack/import_openstack_lb_member_v1_test.go index 8fda19063..514244048 100644 --- a/builtin/providers/openstack/import_openstack_lb_member_v1_test.go +++ b/builtin/providers/openstack/import_openstack_lb_member_v1_test.go @@ -6,7 +6,7 @@ import ( "github.com/hashicorp/terraform/helper/resource" ) -func TestAccOpenStackLBMemberV1_importBasic(t *testing.T) { +func TestAccLBV1Member_importBasic(t *testing.T) { resourceName := "openstack_lb_member_v1.member_1" resource.Test(t, resource.TestCase{ diff --git a/builtin/providers/openstack/import_openstack_lb_monitor_v1_test.go b/builtin/providers/openstack/import_openstack_lb_monitor_v1_test.go index 2609f7135..a27295a77 100644 --- a/builtin/providers/openstack/import_openstack_lb_monitor_v1_test.go +++ b/builtin/providers/openstack/import_openstack_lb_monitor_v1_test.go @@ -6,7 +6,7 @@ import ( "github.com/hashicorp/terraform/helper/resource" ) -func TestAccOpenStackLBMonitorV1_importBasic(t *testing.T) { +func TestAccLBV1Monitor_importBasic(t *testing.T) { resourceName := "openstack_lb_monitor_v1.monitor_1" resource.Test(t, resource.TestCase{ diff --git a/builtin/providers/openstack/import_openstack_lb_pool_v1_test.go b/builtin/providers/openstack/import_openstack_lb_pool_v1_test.go index f2d1b90af..14369f636 100644 --- a/builtin/providers/openstack/import_openstack_lb_pool_v1_test.go +++ b/builtin/providers/openstack/import_openstack_lb_pool_v1_test.go @@ -6,7 +6,7 @@ import ( "github.com/hashicorp/terraform/helper/resource" ) -func TestAccOpenStackLBPoolV1_importBasic(t *testing.T) { +func TestAccLBV1Pool_importBasic(t *testing.T) { resourceName := "openstack_lb_pool_v1.pool_1" resource.Test(t, resource.TestCase{ diff --git a/builtin/providers/openstack/import_openstack_lb_vip_v1_test.go b/builtin/providers/openstack/import_openstack_lb_vip_v1_test.go index 030399ed5..f5e5fa075 100644 --- a/builtin/providers/openstack/import_openstack_lb_vip_v1_test.go +++ b/builtin/providers/openstack/import_openstack_lb_vip_v1_test.go @@ -6,7 +6,7 @@ import ( "github.com/hashicorp/terraform/helper/resource" ) -func TestAccOpenStackLBVIPV1_importBasic(t *testing.T) { +func TestAccLBV1VIP_importBasic(t *testing.T) { resourceName := "openstack_lb_vip_v1.vip_1" resource.Test(t, resource.TestCase{ diff --git a/builtin/providers/openstack/import_openstack_networking_floatingip_v2_test.go b/builtin/providers/openstack/import_openstack_networking_floatingip_v2_test.go index f8bfeab15..9b792c661 100644 --- a/builtin/providers/openstack/import_openstack_networking_floatingip_v2_test.go +++ b/builtin/providers/openstack/import_openstack_networking_floatingip_v2_test.go @@ -6,8 +6,8 @@ import ( "github.com/hashicorp/terraform/helper/resource" ) -func TestAccOpenStackNetworkingFloatingIPV2_importBasic(t *testing.T) { - resourceName := "openstack_networking_floatingip_v2.foo" +func TestAccNetworkingV2FloatingIP_importBasic(t *testing.T) { + resourceName := "openstack_networking_floatingip_v2.fip_1" resource.Test(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, diff --git a/builtin/providers/openstack/import_openstack_networking_network_v2_test.go b/builtin/providers/openstack/import_openstack_networking_network_v2_test.go index 8f5137338..638c49295 100644 --- a/builtin/providers/openstack/import_openstack_networking_network_v2_test.go +++ b/builtin/providers/openstack/import_openstack_networking_network_v2_test.go @@ -6,8 +6,8 @@ import ( "github.com/hashicorp/terraform/helper/resource" ) -func TestAccOpenStackNetworkingNetworkV2_importBasic(t *testing.T) { - resourceName := "openstack_networking_network_v2.foo" +func TestAccNetworkingV2Network_importBasic(t *testing.T) { + resourceName := "openstack_networking_network_v2.network_1" resource.Test(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, diff --git a/builtin/providers/openstack/import_openstack_networking_port_v2_test.go b/builtin/providers/openstack/import_openstack_networking_port_v2_test.go index 2119183c1..562e3e0cd 100644 --- a/builtin/providers/openstack/import_openstack_networking_port_v2_test.go +++ b/builtin/providers/openstack/import_openstack_networking_port_v2_test.go @@ -6,8 +6,8 @@ import ( "github.com/hashicorp/terraform/helper/resource" ) -func TestAccOpenStackNetworkingPortV2_importBasic(t *testing.T) { - resourceName := "openstack_networking_port_v2.foo" +func TestAccNetworkingV2Port_importBasic(t *testing.T) { + resourceName := "openstack_networking_port_v2.port_1" resource.Test(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, @@ -22,6 +22,9 @@ func TestAccOpenStackNetworkingPortV2_importBasic(t *testing.T) { ResourceName: resourceName, ImportState: true, ImportStateVerify: true, + ImportStateVerifyIgnore: []string{ + "fixed_ip", + }, }, }, }) diff --git a/builtin/providers/openstack/import_openstack_networking_secgroup_rule_v2_test.go b/builtin/providers/openstack/import_openstack_networking_secgroup_rule_v2_test.go index 74d36c9aa..c48ef687a 100644 --- a/builtin/providers/openstack/import_openstack_networking_secgroup_rule_v2_test.go +++ b/builtin/providers/openstack/import_openstack_networking_secgroup_rule_v2_test.go @@ -6,8 +6,8 @@ import ( "github.com/hashicorp/terraform/helper/resource" ) -func TestAccOpenStackNetworkingSecGroupRuleV2_importBasic(t *testing.T) { - resourceName := "openstack_networking_secgroup_rule_v2.sr_foo" +func TestAccNetworkingV2SecGroupRule_importBasic(t *testing.T) { + resourceName := "openstack_networking_secgroup_rule_v2.secgroup_rule_1" resource.Test(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, diff --git a/builtin/providers/openstack/import_openstack_networking_secgroup_v2_test.go b/builtin/providers/openstack/import_openstack_networking_secgroup_v2_test.go index 035be2657..3913b174f 100644 --- a/builtin/providers/openstack/import_openstack_networking_secgroup_v2_test.go +++ b/builtin/providers/openstack/import_openstack_networking_secgroup_v2_test.go @@ -6,8 +6,8 @@ import ( "github.com/hashicorp/terraform/helper/resource" ) -func TestAccOpenStackNetworkingSecGroupV2_importBasic(t *testing.T) { - resourceName := "openstack_networking_secgroup_v2.foo" +func TestAccNetworkingV2SecGroup_importBasic(t *testing.T) { + resourceName := "openstack_networking_secgroup_v2.secgroup_1" resource.Test(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, diff --git a/builtin/providers/openstack/import_openstack_networking_subnet_v2_test.go b/builtin/providers/openstack/import_openstack_networking_subnet_v2_test.go index ce7a8c0b3..fa2d5eea9 100644 --- a/builtin/providers/openstack/import_openstack_networking_subnet_v2_test.go +++ b/builtin/providers/openstack/import_openstack_networking_subnet_v2_test.go @@ -6,7 +6,7 @@ import ( "github.com/hashicorp/terraform/helper/resource" ) -func TestAccOpenStackNetworkingSubnetV2_importBasic(t *testing.T) { +func TestAccNetworkingV2Subnet_importBasic(t *testing.T) { resourceName := "openstack_networking_subnet_v2.subnet_1" resource.Test(t, resource.TestCase{ diff --git a/builtin/providers/openstack/resource_openstack_compute_floatingip_associate_v2.go b/builtin/providers/openstack/resource_openstack_compute_floatingip_associate_v2.go index f3e0f5631..963e191d6 100644 --- a/builtin/providers/openstack/resource_openstack_compute_floatingip_associate_v2.go +++ b/builtin/providers/openstack/resource_openstack_compute_floatingip_associate_v2.go @@ -5,7 +5,10 @@ import ( "log" "strings" + "github.com/gophercloud/gophercloud" "github.com/gophercloud/gophercloud/openstack/compute/v2/extensions/floatingips" + "github.com/gophercloud/gophercloud/openstack/compute/v2/servers" + nfloatingips "github.com/gophercloud/gophercloud/openstack/networking/v2/extensions/layer3/floatingips" "github.com/hashicorp/terraform/helper/schema" ) @@ -79,12 +82,67 @@ func resourceComputeFloatingIPAssociateV2Create(d *schema.ResourceData, meta int } func resourceComputeFloatingIPAssociateV2Read(d *schema.ResourceData, meta interface{}) error { + config := meta.(*Config) + computeClient, err := config.computeV2Client(GetRegion(d)) + if err != nil { + return fmt.Errorf("Error creating OpenStack compute client: %s", err) + } + // Obtain relevant info from parsing the ID floatingIP, instanceId, fixedIP, err := parseComputeFloatingIPAssociateId(d.Id()) if err != nil { return err } + // Now check and see whether the floating IP still exists. + // First try to do this by querying the Network API. + networkEnabled := true + networkClient, err := config.networkingV2Client(GetRegion(d)) + if err != nil { + networkEnabled = false + } + + var exists bool + if networkEnabled { + log.Printf("[DEBUG] Checking for Floating IP existence via Network API") + exists, err = resourceComputeFloatingIPAssociateV2NetworkExists(networkClient, floatingIP) + } else { + log.Printf("[DEBUG] Checking for Floating IP existence via Compute API") + exists, err = resourceComputeFloatingIPAssociateV2ComputeExists(computeClient, floatingIP) + } + + if err != nil { + return err + } + + if !exists { + d.SetId("") + } + + // Next, see if the instance still exists + instance, err := servers.Get(computeClient, instanceId).Extract() + if err != nil { + if CheckDeleted(d, err, "instance") == nil { + return nil + } + } + + // Finally, check and see if the floating ip is still associated with the instance. + var associated bool + for _, networkAddresses := range instance.Addresses { + for _, element := range networkAddresses.([]interface{}) { + address := element.(map[string]interface{}) + if address["OS-EXT-IPS:type"] == "floating" && address["addr"] == floatingIP { + associated = true + } + } + } + + if !associated { + d.SetId("") + } + + // Set the attributes pulled from the composed resource ID d.Set("floating_ip", floatingIP) d.Set("instance_id", instanceId) d.Set("fixed_ip", fixedIP) @@ -110,7 +168,7 @@ func resourceComputeFloatingIPAssociateV2Delete(d *schema.ResourceData, meta int err = floatingips.DisassociateInstance(computeClient, instanceId, disassociateOpts).ExtractErr() if err != nil { - return fmt.Errorf("Error disassociating floating IP: %s", err) + return CheckDeleted(d, err, "floating ip association") } return nil @@ -128,3 +186,49 @@ func parseComputeFloatingIPAssociateId(id string) (string, string, string, error return floatingIP, instanceId, fixedIP, nil } + +func resourceComputeFloatingIPAssociateV2NetworkExists(networkClient *gophercloud.ServiceClient, floatingIP string) (bool, error) { + listOpts := nfloatingips.ListOpts{ + FloatingIP: floatingIP, + } + allPages, err := nfloatingips.List(networkClient, listOpts).AllPages() + if err != nil { + return false, err + } + + allFips, err := nfloatingips.ExtractFloatingIPs(allPages) + if err != nil { + return false, err + } + + if len(allFips) > 1 { + return false, fmt.Errorf("There was a problem retrieving the floating IP") + } + + if len(allFips) == 0 { + return false, nil + } + + return true, nil +} + +func resourceComputeFloatingIPAssociateV2ComputeExists(computeClient *gophercloud.ServiceClient, floatingIP string) (bool, error) { + // If the Network API isn't available, fall back to the deprecated Compute API. + allPages, err := floatingips.List(computeClient).AllPages() + if err != nil { + return false, err + } + + allFips, err := floatingips.ExtractFloatingIPs(allPages) + if err != nil { + return false, err + } + + for _, f := range allFips { + if f.IP == floatingIP { + return true, nil + } + } + + return false, nil +} diff --git a/builtin/providers/openstack/resource_openstack_compute_instance_v2.go b/builtin/providers/openstack/resource_openstack_compute_instance_v2.go index 5a60b55c5..028b6fb57 100644 --- a/builtin/providers/openstack/resource_openstack_compute_instance_v2.go +++ b/builtin/providers/openstack/resource_openstack_compute_instance_v2.go @@ -919,7 +919,7 @@ func resourceComputeInstanceV2Delete(d *schema.ResourceData, meta interface{}) e stateConf := &resource.StateChangeConf{ Pending: []string{"ACTIVE", "SHUTOFF"}, - Target: []string{"DELETED"}, + Target: []string{"DELETED", "SOFT_DELETED"}, Refresh: ServerV2StateRefreshFunc(computeClient, d.Id()), Timeout: d.Timeout(schema.TimeoutDelete), Delay: 10 * time.Second, diff --git a/builtin/providers/openstack/resource_openstack_compute_instance_v2_test.go b/builtin/providers/openstack/resource_openstack_compute_instance_v2_test.go index cf43ee4bb..affc17d6f 100644 --- a/builtin/providers/openstack/resource_openstack_compute_instance_v2_test.go +++ b/builtin/providers/openstack/resource_openstack_compute_instance_v2_test.go @@ -678,9 +678,11 @@ func testAccCheckComputeV2InstanceDestroy(s *terraform.State) error { continue } - _, err := servers.Get(computeClient, rs.Primary.ID).Extract() + server, err := servers.Get(computeClient, rs.Primary.ID).Extract() if err == nil { - return fmt.Errorf("Instance still exists") + if server.Status != "SOFT_DELETED" { + return fmt.Errorf("Instance still exists") + } } } diff --git a/builtin/providers/openstack/resource_openstack_compute_servergroup_v2.go b/builtin/providers/openstack/resource_openstack_compute_servergroup_v2.go index 5616ef9a9..70b31eec6 100644 --- a/builtin/providers/openstack/resource_openstack_compute_servergroup_v2.go +++ b/builtin/providers/openstack/resource_openstack_compute_servergroup_v2.go @@ -41,6 +41,11 @@ func resourceComputeServerGroupV2() *schema.Resource { Computed: true, Elem: &schema.Schema{Type: schema.TypeString}, }, + "value_specs": &schema.Schema{ + Type: schema.TypeMap, + Optional: true, + ForceNew: true, + }, }, } } @@ -52,10 +57,14 @@ func resourceComputeServerGroupV2Create(d *schema.ResourceData, meta interface{} return fmt.Errorf("Error creating OpenStack compute client: %s", err) } - createOpts := &servergroups.CreateOpts{ - Name: d.Get("name").(string), - Policies: resourceServerGroupPoliciesV2(d), + createOpts := ServerGroupCreateOpts{ + servergroups.CreateOpts{ + Name: d.Get("name").(string), + Policies: resourceServerGroupPoliciesV2(d), + }, + MapValueSpecs(d), } + log.Printf("[DEBUG] Create Options: %#v", createOpts) newSG, err := servergroups.Create(computeClient, createOpts).Extract() if err != nil { diff --git a/builtin/providers/openstack/resource_openstack_compute_volume_attach_v2.go b/builtin/providers/openstack/resource_openstack_compute_volume_attach_v2.go index 1eb8506e6..4fa6cb812 100644 --- a/builtin/providers/openstack/resource_openstack_compute_volume_attach_v2.go +++ b/builtin/providers/openstack/resource_openstack_compute_volume_attach_v2.go @@ -121,7 +121,7 @@ func resourceComputeVolumeAttachV2Read(d *schema.ResourceData, meta interface{}) attachment, err := volumeattach.Get(computeClient, instanceId, attachmentId).Extract() if err != nil { - return err + return CheckDeleted(d, err, "compute_volume_attach") } log.Printf("[DEBUG] Retrieved volume attachment: %#v", attachment) diff --git a/builtin/providers/openstack/resource_openstack_networking_port_v2.go b/builtin/providers/openstack/resource_openstack_networking_port_v2.go index 508ebc813..4be432935 100644 --- a/builtin/providers/openstack/resource_openstack_networking_port_v2.go +++ b/builtin/providers/openstack/resource_openstack_networking_port_v2.go @@ -236,7 +236,14 @@ func resourceNetworkingPortV2Update(d *schema.ResourceData, meta interface{}) er return fmt.Errorf("Error creating OpenStack networking client: %s", err) } - var updateOpts ports.UpdateOpts + // security_group_ids and allowed_address_pairs are able to send empty arrays + // to denote the removal of each. But their default zero-value is translated + // to "null", which has been reported to cause problems in vendor-modified + // OpenStack clouds. Therefore, we must set them in each request update. + updateOpts := ports.UpdateOpts{ + AllowedAddressPairs: resourceAllowedAddressPairsV2(d), + SecurityGroups: resourcePortSecurityGroupsV2(d), + } if d.HasChange("name") { updateOpts.Name = d.Get("name").(string) @@ -250,10 +257,6 @@ func resourceNetworkingPortV2Update(d *schema.ResourceData, meta interface{}) er updateOpts.DeviceOwner = d.Get("device_owner").(string) } - if d.HasChange("security_group_ids") { - updateOpts.SecurityGroups = resourcePortSecurityGroupsV2(d) - } - if d.HasChange("device_id") { updateOpts.DeviceID = d.Get("device_id").(string) } @@ -262,10 +265,6 @@ func resourceNetworkingPortV2Update(d *schema.ResourceData, meta interface{}) er updateOpts.FixedIPs = resourcePortFixedIpsV2(d) } - if d.HasChange("allowed_address_pairs") { - updateOpts.AllowedAddressPairs = resourceAllowedAddressPairsV2(d) - } - log.Printf("[DEBUG] Updating Port %s with options: %+v", d.Id(), updateOpts) _, err = ports.Update(networkingClient, d.Id(), updateOpts).Extract() @@ -332,10 +331,6 @@ func resourceAllowedAddressPairsV2(d *schema.ResourceData) []ports.AddressPair { // ports.AddressPair rawPairs := d.Get("allowed_address_pairs").(*schema.Set).List() - if len(rawPairs) == 0 { - return nil - } - pairs := make([]ports.AddressPair, len(rawPairs)) for i, raw := range rawPairs { rawMap := raw.(map[string]interface{}) diff --git a/builtin/providers/openstack/resource_openstack_networking_port_v2_test.go b/builtin/providers/openstack/resource_openstack_networking_port_v2_test.go index 28e08bebd..a9d7281af 100644 --- a/builtin/providers/openstack/resource_openstack_networking_port_v2_test.go +++ b/builtin/providers/openstack/resource_openstack_networking_port_v2_test.go @@ -7,6 +7,7 @@ import ( "github.com/hashicorp/terraform/helper/resource" "github.com/hashicorp/terraform/terraform" + "github.com/gophercloud/gophercloud/openstack/networking/v2/extensions/security/groups" "github.com/gophercloud/gophercloud/openstack/networking/v2/networks" "github.com/gophercloud/gophercloud/openstack/networking/v2/ports" "github.com/gophercloud/gophercloud/openstack/networking/v2/subnets" @@ -168,6 +169,54 @@ func TestAccNetworkingV2Port_fixedIPs(t *testing.T) { }) } +func TestAccNetworkingV2Port_updateSecurityGroups(t *testing.T) { + var network networks.Network + var port ports.Port + var security_group groups.SecGroup + var subnet subnets.Subnet + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckNetworkingV2PortDestroy, + Steps: []resource.TestStep{ + resource.TestStep{ + Config: testAccNetworkingV2Port_updateSecurityGroups_1, + Check: resource.ComposeTestCheckFunc( + testAccCheckNetworkingV2SubnetExists("openstack_networking_subnet_v2.subnet_1", &subnet), + testAccCheckNetworkingV2NetworkExists("openstack_networking_network_v2.network_1", &network), + testAccCheckNetworkingV2PortExists("openstack_networking_port_v2.port_1", &port), + testAccCheckNetworkingV2SecGroupExists( + "openstack_networking_secgroup_v2.secgroup_1", &security_group), + testAccCheckNetworkingV2PortCountSecurityGroups(&port, 1), + ), + }, + resource.TestStep{ + Config: testAccNetworkingV2Port_updateSecurityGroups_2, + Check: resource.ComposeTestCheckFunc( + testAccCheckNetworkingV2SubnetExists("openstack_networking_subnet_v2.subnet_1", &subnet), + testAccCheckNetworkingV2NetworkExists("openstack_networking_network_v2.network_1", &network), + testAccCheckNetworkingV2PortExists("openstack_networking_port_v2.port_1", &port), + testAccCheckNetworkingV2SecGroupExists( + "openstack_networking_secgroup_v2.secgroup_1", &security_group), + testAccCheckNetworkingV2PortCountSecurityGroups(&port, 1), + ), + }, + resource.TestStep{ + Config: testAccNetworkingV2Port_updateSecurityGroups_3, + Check: resource.ComposeTestCheckFunc( + testAccCheckNetworkingV2SubnetExists("openstack_networking_subnet_v2.subnet_1", &subnet), + testAccCheckNetworkingV2NetworkExists("openstack_networking_network_v2.network_1", &network), + testAccCheckNetworkingV2PortExists("openstack_networking_port_v2.port_1", &port), + testAccCheckNetworkingV2SecGroupExists( + "openstack_networking_secgroup_v2.secgroup_1", &security_group), + testAccCheckNetworkingV2PortCountSecurityGroups(&port, 0), + ), + }, + }, + }) +} + func testAccCheckNetworkingV2PortDestroy(s *terraform.State) error { config := testAccProvider.Meta().(*Config) networkingClient, err := config.networkingV2Client(OS_REGION_NAME) @@ -231,6 +280,16 @@ func testAccCheckNetworkingV2PortCountFixedIPs(port *ports.Port, expected int) r } } +func testAccCheckNetworkingV2PortCountSecurityGroups(port *ports.Port, expected int) resource.TestCheckFunc { + return func(s *terraform.State) error { + if len(port.SecurityGroups) != expected { + return fmt.Errorf("Expected %d Security Groups, got %d", expected, len(port.SecurityGroups)) + } + + return nil + } +} + const testAccNetworkingV2Port_basic = ` resource "openstack_networking_network_v2" "network_1" { name = "network_1" @@ -472,3 +531,95 @@ resource "openstack_networking_port_v2" "port_1" { } } ` + +const testAccNetworkingV2Port_updateSecurityGroups_1 = ` +resource "openstack_networking_network_v2" "network_1" { + name = "network_1" + admin_state_up = "true" +} + +resource "openstack_networking_subnet_v2" "subnet_1" { + name = "subnet_1" + cidr = "192.168.199.0/24" + ip_version = 4 + network_id = "${openstack_networking_network_v2.network_1.id}" +} + +resource "openstack_networking_secgroup_v2" "secgroup_1" { + name = "security_group" + description = "terraform security group acceptance test" +} + +resource "openstack_networking_port_v2" "port_1" { + name = "port_1" + admin_state_up = "true" + network_id = "${openstack_networking_network_v2.network_1.id}" + + fixed_ip { + subnet_id = "${openstack_networking_subnet_v2.subnet_1.id}" + ip_address = "192.168.199.23" + } +} +` + +const testAccNetworkingV2Port_updateSecurityGroups_2 = ` +resource "openstack_networking_network_v2" "network_1" { + name = "network_1" + admin_state_up = "true" +} + +resource "openstack_networking_subnet_v2" "subnet_1" { + name = "subnet_1" + cidr = "192.168.199.0/24" + ip_version = 4 + network_id = "${openstack_networking_network_v2.network_1.id}" +} + +resource "openstack_networking_secgroup_v2" "secgroup_1" { + name = "security_group" + description = "terraform security group acceptance test" +} + +resource "openstack_networking_port_v2" "port_1" { + name = "port_1" + admin_state_up = "true" + network_id = "${openstack_networking_network_v2.network_1.id}" + security_group_ids = ["${openstack_networking_secgroup_v2.secgroup_1.id}"] + + fixed_ip { + subnet_id = "${openstack_networking_subnet_v2.subnet_1.id}" + ip_address = "192.168.199.23" + } +} +` + +const testAccNetworkingV2Port_updateSecurityGroups_3 = ` +resource "openstack_networking_network_v2" "network_1" { + name = "network_1" + admin_state_up = "true" +} + +resource "openstack_networking_subnet_v2" "subnet_1" { + name = "subnet_1" + cidr = "192.168.199.0/24" + ip_version = 4 + network_id = "${openstack_networking_network_v2.network_1.id}" +} + +resource "openstack_networking_secgroup_v2" "secgroup_1" { + name = "security_group" + description = "terraform security group acceptance test" +} + +resource "openstack_networking_port_v2" "port_1" { + name = "port_1" + admin_state_up = "true" + network_id = "${openstack_networking_network_v2.network_1.id}" + security_group_ids = [] + + fixed_ip { + subnet_id = "${openstack_networking_subnet_v2.subnet_1.id}" + ip_address = "192.168.199.23" + } +} +` diff --git a/builtin/providers/openstack/resource_openstack_networking_secgroup_rule_v2.go b/builtin/providers/openstack/resource_openstack_networking_secgroup_rule_v2.go index 39a675967..2a6075ab5 100644 --- a/builtin/providers/openstack/resource_openstack_networking_secgroup_rule_v2.go +++ b/builtin/providers/openstack/resource_openstack_networking_secgroup_rule_v2.go @@ -236,6 +236,42 @@ func resourceNetworkingSecGroupRuleV2DetermineProtocol(v string) rules.RuleProto protocol = rules.ProtocolUDP case "icmp": protocol = rules.ProtocolICMP + case "ah": + protocol = rules.ProtocolAH + case "dccp": + protocol = rules.ProtocolDCCP + case "egp": + protocol = rules.ProtocolEGP + case "esp": + protocol = rules.ProtocolESP + case "gre": + protocol = rules.ProtocolGRE + case "igmp": + protocol = rules.ProtocolIGMP + case "ipv6-encap": + protocol = rules.ProtocolIPv6Encap + case "ipv6-frag": + protocol = rules.ProtocolIPv6Frag + case "ipv6-icmp": + protocol = rules.ProtocolIPv6ICMP + case "ipv6-nonxt": + protocol = rules.ProtocolIPv6NoNxt + case "ipv6-opts": + protocol = rules.ProtocolIPv6Opts + case "ipv6-route": + protocol = rules.ProtocolIPv6Route + case "ospf": + protocol = rules.ProtocolOSPF + case "pgm": + protocol = rules.ProtocolPGM + case "rsvp": + protocol = rules.ProtocolRSVP + case "sctp": + protocol = rules.ProtocolSCTP + case "udplite": + protocol = rules.ProtocolUDPLite + case "vrrp": + protocol = rules.ProtocolVRRP } return protocol diff --git a/builtin/providers/openstack/resource_openstack_networking_secgroup_rule_v2_test.go b/builtin/providers/openstack/resource_openstack_networking_secgroup_rule_v2_test.go index 7dd62e60b..e9bc6834e 100644 --- a/builtin/providers/openstack/resource_openstack_networking_secgroup_rule_v2_test.go +++ b/builtin/providers/openstack/resource_openstack_networking_secgroup_rule_v2_test.go @@ -85,6 +85,115 @@ func TestAccNetworkingV2SecGroupRule_timeout(t *testing.T) { }) } +func TestAccNetworkingV2SecGroupRule_protocols(t *testing.T) { + var secgroup_1 groups.SecGroup + var secgroup_rule_ah rules.SecGroupRule + var secgroup_rule_dccp rules.SecGroupRule + var secgroup_rule_egp rules.SecGroupRule + var secgroup_rule_esp rules.SecGroupRule + var secgroup_rule_gre rules.SecGroupRule + var secgroup_rule_igmp rules.SecGroupRule + var secgroup_rule_ipv6_encap rules.SecGroupRule + var secgroup_rule_ipv6_frag rules.SecGroupRule + var secgroup_rule_ipv6_icmp rules.SecGroupRule + var secgroup_rule_ipv6_nonxt rules.SecGroupRule + var secgroup_rule_ipv6_opts rules.SecGroupRule + var secgroup_rule_ipv6_route rules.SecGroupRule + var secgroup_rule_ospf rules.SecGroupRule + var secgroup_rule_pgm rules.SecGroupRule + var secgroup_rule_rsvp rules.SecGroupRule + var secgroup_rule_sctp rules.SecGroupRule + var secgroup_rule_udplite rules.SecGroupRule + var secgroup_rule_vrrp rules.SecGroupRule + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckNetworkingV2SecGroupRuleDestroy, + Steps: []resource.TestStep{ + resource.TestStep{ + Config: testAccNetworkingV2SecGroupRule_protocols, + Check: resource.ComposeTestCheckFunc( + testAccCheckNetworkingV2SecGroupExists( + "openstack_networking_secgroup_v2.secgroup_1", &secgroup_1), + testAccCheckNetworkingV2SecGroupRuleExists( + "openstack_networking_secgroup_rule_v2.secgroup_rule_ah", &secgroup_rule_ah), + testAccCheckNetworkingV2SecGroupRuleExists( + "openstack_networking_secgroup_rule_v2.secgroup_rule_dccp", &secgroup_rule_dccp), + testAccCheckNetworkingV2SecGroupRuleExists( + "openstack_networking_secgroup_rule_v2.secgroup_rule_egp", &secgroup_rule_egp), + testAccCheckNetworkingV2SecGroupRuleExists( + "openstack_networking_secgroup_rule_v2.secgroup_rule_esp", &secgroup_rule_esp), + testAccCheckNetworkingV2SecGroupRuleExists( + "openstack_networking_secgroup_rule_v2.secgroup_rule_gre", &secgroup_rule_gre), + testAccCheckNetworkingV2SecGroupRuleExists( + "openstack_networking_secgroup_rule_v2.secgroup_rule_igmp", &secgroup_rule_igmp), + testAccCheckNetworkingV2SecGroupRuleExists( + "openstack_networking_secgroup_rule_v2.secgroup_rule_ipv6_encap", &secgroup_rule_ipv6_encap), + testAccCheckNetworkingV2SecGroupRuleExists( + "openstack_networking_secgroup_rule_v2.secgroup_rule_ipv6_frag", &secgroup_rule_ipv6_frag), + testAccCheckNetworkingV2SecGroupRuleExists( + "openstack_networking_secgroup_rule_v2.secgroup_rule_ipv6_icmp", &secgroup_rule_ipv6_icmp), + testAccCheckNetworkingV2SecGroupRuleExists( + "openstack_networking_secgroup_rule_v2.secgroup_rule_ipv6_nonxt", &secgroup_rule_ipv6_nonxt), + testAccCheckNetworkingV2SecGroupRuleExists( + "openstack_networking_secgroup_rule_v2.secgroup_rule_ipv6_opts", &secgroup_rule_ipv6_opts), + testAccCheckNetworkingV2SecGroupRuleExists( + "openstack_networking_secgroup_rule_v2.secgroup_rule_ipv6_route", &secgroup_rule_ipv6_route), + testAccCheckNetworkingV2SecGroupRuleExists( + "openstack_networking_secgroup_rule_v2.secgroup_rule_ospf", &secgroup_rule_ospf), + testAccCheckNetworkingV2SecGroupRuleExists( + "openstack_networking_secgroup_rule_v2.secgroup_rule_pgm", &secgroup_rule_pgm), + testAccCheckNetworkingV2SecGroupRuleExists( + "openstack_networking_secgroup_rule_v2.secgroup_rule_rsvp", &secgroup_rule_rsvp), + testAccCheckNetworkingV2SecGroupRuleExists( + "openstack_networking_secgroup_rule_v2.secgroup_rule_sctp", &secgroup_rule_sctp), + testAccCheckNetworkingV2SecGroupRuleExists( + "openstack_networking_secgroup_rule_v2.secgroup_rule_udplite", &secgroup_rule_udplite), + testAccCheckNetworkingV2SecGroupRuleExists( + "openstack_networking_secgroup_rule_v2.secgroup_rule_vrrp", &secgroup_rule_vrrp), + resource.TestCheckResourceAttr( + "openstack_networking_secgroup_rule_v2.secgroup_rule_ah", "protocol", "ah"), + resource.TestCheckResourceAttr( + "openstack_networking_secgroup_rule_v2.secgroup_rule_dccp", "protocol", "dccp"), + resource.TestCheckResourceAttr( + "openstack_networking_secgroup_rule_v2.secgroup_rule_egp", "protocol", "egp"), + resource.TestCheckResourceAttr( + "openstack_networking_secgroup_rule_v2.secgroup_rule_esp", "protocol", "esp"), + resource.TestCheckResourceAttr( + "openstack_networking_secgroup_rule_v2.secgroup_rule_gre", "protocol", "gre"), + resource.TestCheckResourceAttr( + "openstack_networking_secgroup_rule_v2.secgroup_rule_igmp", "protocol", "igmp"), + resource.TestCheckResourceAttr( + "openstack_networking_secgroup_rule_v2.secgroup_rule_ipv6_encap", "protocol", "ipv6-encap"), + resource.TestCheckResourceAttr( + "openstack_networking_secgroup_rule_v2.secgroup_rule_ipv6_frag", "protocol", "ipv6-frag"), + resource.TestCheckResourceAttr( + "openstack_networking_secgroup_rule_v2.secgroup_rule_ipv6_icmp", "protocol", "ipv6-icmp"), + resource.TestCheckResourceAttr( + "openstack_networking_secgroup_rule_v2.secgroup_rule_ipv6_nonxt", "protocol", "ipv6-nonxt"), + resource.TestCheckResourceAttr( + "openstack_networking_secgroup_rule_v2.secgroup_rule_ipv6_opts", "protocol", "ipv6-opts"), + resource.TestCheckResourceAttr( + "openstack_networking_secgroup_rule_v2.secgroup_rule_ipv6_route", "protocol", "ipv6-route"), + resource.TestCheckResourceAttr( + "openstack_networking_secgroup_rule_v2.secgroup_rule_ospf", "protocol", "ospf"), + resource.TestCheckResourceAttr( + "openstack_networking_secgroup_rule_v2.secgroup_rule_pgm", "protocol", "pgm"), + resource.TestCheckResourceAttr( + "openstack_networking_secgroup_rule_v2.secgroup_rule_rsvp", "protocol", "rsvp"), + resource.TestCheckResourceAttr( + "openstack_networking_secgroup_rule_v2.secgroup_rule_sctp", "protocol", "sctp"), + resource.TestCheckResourceAttr( + "openstack_networking_secgroup_rule_v2.secgroup_rule_udplite", "protocol", "udplite"), + resource.TestCheckResourceAttr( + "openstack_networking_secgroup_rule_v2.secgroup_rule_vrrp", "protocol", "vrrp"), + ), + }, + }, + }) +} + func testAccCheckNetworkingV2SecGroupRuleDestroy(s *terraform.State) error { config := testAccProvider.Meta().(*Config) networkingClient, err := config.networkingV2Client(OS_REGION_NAME) @@ -226,3 +335,154 @@ resource "openstack_networking_secgroup_rule_v2" "secgroup_rule_2" { } } ` + +const testAccNetworkingV2SecGroupRule_protocols = ` +resource "openstack_networking_secgroup_v2" "secgroup_1" { + name = "secgroup_1" + description = "terraform security group rule acceptance test" +} + +resource "openstack_networking_secgroup_rule_v2" "secgroup_rule_ah" { + direction = "ingress" + ethertype = "IPv4" + protocol = "ah" + remote_ip_prefix = "0.0.0.0/0" + security_group_id = "${openstack_networking_secgroup_v2.secgroup_1.id}" +} + +resource "openstack_networking_secgroup_rule_v2" "secgroup_rule_dccp" { + direction = "ingress" + ethertype = "IPv4" + protocol = "dccp" + remote_ip_prefix = "0.0.0.0/0" + security_group_id = "${openstack_networking_secgroup_v2.secgroup_1.id}" +} + +resource "openstack_networking_secgroup_rule_v2" "secgroup_rule_egp" { + direction = "ingress" + ethertype = "IPv4" + protocol = "egp" + remote_ip_prefix = "0.0.0.0/0" + security_group_id = "${openstack_networking_secgroup_v2.secgroup_1.id}" +} + +resource "openstack_networking_secgroup_rule_v2" "secgroup_rule_esp" { + direction = "ingress" + ethertype = "IPv4" + protocol = "esp" + remote_ip_prefix = "0.0.0.0/0" + security_group_id = "${openstack_networking_secgroup_v2.secgroup_1.id}" +} + +resource "openstack_networking_secgroup_rule_v2" "secgroup_rule_gre" { + direction = "ingress" + ethertype = "IPv4" + protocol = "gre" + remote_ip_prefix = "0.0.0.0/0" + security_group_id = "${openstack_networking_secgroup_v2.secgroup_1.id}" +} + +resource "openstack_networking_secgroup_rule_v2" "secgroup_rule_igmp" { + direction = "ingress" + ethertype = "IPv4" + protocol = "igmp" + remote_ip_prefix = "0.0.0.0/0" + security_group_id = "${openstack_networking_secgroup_v2.secgroup_1.id}" +} + +resource "openstack_networking_secgroup_rule_v2" "secgroup_rule_ipv6_encap" { + direction = "ingress" + ethertype = "IPv6" + protocol = "ipv6-encap" + remote_ip_prefix = "::/0" + security_group_id = "${openstack_networking_secgroup_v2.secgroup_1.id}" +} + +resource "openstack_networking_secgroup_rule_v2" "secgroup_rule_ipv6_frag" { + direction = "ingress" + ethertype = "IPv6" + protocol = "ipv6-frag" + remote_ip_prefix = "::/0" + security_group_id = "${openstack_networking_secgroup_v2.secgroup_1.id}" +} + +resource "openstack_networking_secgroup_rule_v2" "secgroup_rule_ipv6_icmp" { + direction = "ingress" + ethertype = "IPv6" + protocol = "ipv6-icmp" + remote_ip_prefix = "::/0" + security_group_id = "${openstack_networking_secgroup_v2.secgroup_1.id}" +} + +resource "openstack_networking_secgroup_rule_v2" "secgroup_rule_ipv6_nonxt" { + direction = "ingress" + ethertype = "IPv6" + protocol = "ipv6-nonxt" + remote_ip_prefix = "::/0" + security_group_id = "${openstack_networking_secgroup_v2.secgroup_1.id}" +} + +resource "openstack_networking_secgroup_rule_v2" "secgroup_rule_ipv6_opts" { + direction = "ingress" + ethertype = "IPv6" + protocol = "ipv6-opts" + remote_ip_prefix = "::/0" + security_group_id = "${openstack_networking_secgroup_v2.secgroup_1.id}" +} + +resource "openstack_networking_secgroup_rule_v2" "secgroup_rule_ipv6_route" { + direction = "ingress" + ethertype = "IPv6" + protocol = "ipv6-route" + remote_ip_prefix = "::/0" + security_group_id = "${openstack_networking_secgroup_v2.secgroup_1.id}" +} + +resource "openstack_networking_secgroup_rule_v2" "secgroup_rule_ospf" { + direction = "ingress" + ethertype = "IPv4" + protocol = "ospf" + remote_ip_prefix = "0.0.0.0/0" + security_group_id = "${openstack_networking_secgroup_v2.secgroup_1.id}" +} + +resource "openstack_networking_secgroup_rule_v2" "secgroup_rule_pgm" { + direction = "ingress" + ethertype = "IPv4" + protocol = "pgm" + remote_ip_prefix = "0.0.0.0/0" + security_group_id = "${openstack_networking_secgroup_v2.secgroup_1.id}" +} + +resource "openstack_networking_secgroup_rule_v2" "secgroup_rule_rsvp" { + direction = "ingress" + ethertype = "IPv4" + protocol = "rsvp" + remote_ip_prefix = "0.0.0.0/0" + security_group_id = "${openstack_networking_secgroup_v2.secgroup_1.id}" +} + +resource "openstack_networking_secgroup_rule_v2" "secgroup_rule_sctp" { + direction = "ingress" + ethertype = "IPv4" + protocol = "sctp" + remote_ip_prefix = "0.0.0.0/0" + security_group_id = "${openstack_networking_secgroup_v2.secgroup_1.id}" +} + +resource "openstack_networking_secgroup_rule_v2" "secgroup_rule_udplite" { + direction = "ingress" + ethertype = "IPv4" + protocol = "udplite" + remote_ip_prefix = "0.0.0.0/0" + security_group_id = "${openstack_networking_secgroup_v2.secgroup_1.id}" +} + +resource "openstack_networking_secgroup_rule_v2" "secgroup_rule_vrrp" { + direction = "ingress" + ethertype = "IPv4" + protocol = "vrrp" + remote_ip_prefix = "0.0.0.0/0" + security_group_id = "${openstack_networking_secgroup_v2.secgroup_1.id}" +} +` diff --git a/builtin/providers/openstack/resource_openstack_networking_secgroup_v2.go b/builtin/providers/openstack/resource_openstack_networking_secgroup_v2.go index f76d24c57..8dad6fad8 100644 --- a/builtin/providers/openstack/resource_openstack_networking_secgroup_v2.go +++ b/builtin/providers/openstack/resource_openstack_networking_secgroup_v2.go @@ -167,6 +167,11 @@ func waitForSecGroupDelete(networkingClient *gophercloud.ServiceClient, secGroup log.Printf("[DEBUG] Successfully deleted OpenStack Neutron Security Group %s", secGroupId) return r, "DELETED", nil } + if errCode, ok := err.(gophercloud.ErrUnexpectedResponseCode); ok { + if errCode.Actual == 409 { + return r, "ACTIVE", nil + } + } return r, "ACTIVE", err } diff --git a/builtin/providers/openstack/types.go b/builtin/providers/openstack/types.go index e2d19304c..c6c6a268a 100644 --- a/builtin/providers/openstack/types.go +++ b/builtin/providers/openstack/types.go @@ -10,6 +10,7 @@ import ( "strings" "github.com/gophercloud/gophercloud/openstack/compute/v2/extensions/keypairs" + "github.com/gophercloud/gophercloud/openstack/compute/v2/extensions/servergroups" "github.com/gophercloud/gophercloud/openstack/networking/v2/extensions/fwaas/firewalls" "github.com/gophercloud/gophercloud/openstack/networking/v2/extensions/fwaas/policies" "github.com/gophercloud/gophercloud/openstack/networking/v2/extensions/fwaas/rules" @@ -23,8 +24,8 @@ import ( // LogRoundTripper satisfies the http.RoundTripper interface and is used to // customize the default http client RoundTripper to allow for logging. type LogRoundTripper struct { - rt http.RoundTripper - osDebug bool + Rt http.RoundTripper + OsDebug bool } // RoundTrip performs a round-trip HTTP request and logs relevant information about it. @@ -36,36 +37,36 @@ func (lrt *LogRoundTripper) RoundTrip(request *http.Request) (*http.Response, er }() // for future reference, this is how to access the Transport struct: - //tlsconfig := lrt.rt.(*http.Transport).TLSClientConfig + //tlsconfig := lrt.Rt.(*http.Transport).TLSClientConfig var err error - if lrt.osDebug { + if lrt.OsDebug { log.Printf("[DEBUG] OpenStack Request URL: %s %s", request.Method, request.URL) if request.Body != nil { - request.Body, err = lrt.logRequestBody(request.Body, request.Header) + request.Body, err = lrt.logRequest(request.Body, request.Header) if err != nil { return nil, err } } } - response, err := lrt.rt.RoundTrip(request) + response, err := lrt.Rt.RoundTrip(request) if response == nil { return nil, err } - if lrt.osDebug { - response.Body, err = lrt.logResponseBody(response.Body, response.Header) + if lrt.OsDebug { + response.Body, err = lrt.logResponse(response.Body, response.Header) } return response, err } -// logRequestBody will log the HTTP Request body. +// logRequest will log the HTTP Request details. // If the body is JSON, it will attempt to be pretty-formatted. -func (lrt *LogRoundTripper) logRequestBody(original io.ReadCloser, headers http.Header) (io.ReadCloser, error) { +func (lrt *LogRoundTripper) logRequest(original io.ReadCloser, headers http.Header) (io.ReadCloser, error) { defer original.Close() var bs bytes.Buffer @@ -74,20 +75,25 @@ func (lrt *LogRoundTripper) logRequestBody(original io.ReadCloser, headers http. return nil, err } + log.Printf("[DEBUG] Openstack Request headers:\n%s", strings.Join(RedactHeaders(headers), "\n")) + + // Handle request contentType contentType := headers.Get("Content-Type") if strings.HasPrefix(contentType, "application/json") { debugInfo := lrt.formatJSON(bs.Bytes()) - log.Printf("[DEBUG] OpenStack Request Options: %s", debugInfo) + log.Printf("[DEBUG] OpenStack Request Body: %s", debugInfo) } else { - log.Printf("[DEBUG] OpenStack Request Options: %s", bs.String()) + log.Printf("[DEBUG] OpenStack Request Body: %s", bs.String()) } return ioutil.NopCloser(strings.NewReader(bs.String())), nil } -// logResponseBody will log the HTTP Response body. +// logResponse will log the HTTP Response details. // If the body is JSON, it will attempt to be pretty-formatted. -func (lrt *LogRoundTripper) logResponseBody(original io.ReadCloser, headers http.Header) (io.ReadCloser, error) { +func (lrt *LogRoundTripper) logResponse(original io.ReadCloser, headers http.Header) (io.ReadCloser, error) { + log.Printf("[DEBUG] Openstack Response headers:\n%s", strings.Join(RedactHeaders(headers), "\n")) + contentType := headers.Get("Content-Type") if strings.HasPrefix(contentType, "application/json") { var bs bytes.Buffer @@ -250,6 +256,18 @@ func (opts RuleCreateOpts) ToRuleCreateMap() (map[string]interface{}, error) { return b, nil } +// ServerGroupCreateOpts represents the attributes used when creating a new router. +type ServerGroupCreateOpts struct { + servergroups.CreateOpts + ValueSpecs map[string]string `json:"value_specs,omitempty"` +} + +// ToServerGroupCreateMap casts a CreateOpts struct to a map. +// It overrides routers.ToServerGroupCreateMap to add the ValueSpecs field. +func (opts ServerGroupCreateOpts) ToServerGroupCreateMap() (map[string]interface{}, error) { + return BuildRequest(opts, "server_group") +} + // SubnetCreateOpts represents the attributes used when creating a new subnet. type SubnetCreateOpts struct { subnets.CreateOpts diff --git a/builtin/providers/openstack/util.go b/builtin/providers/openstack/util.go index 70fb8914f..eb5ccdf09 100644 --- a/builtin/providers/openstack/util.go +++ b/builtin/providers/openstack/util.go @@ -2,8 +2,10 @@ package openstack import ( "fmt" + "net/http" "os" + "github.com/Unknwon/com" "github.com/gophercloud/gophercloud" "github.com/hashicorp/terraform/helper/schema" ) @@ -58,3 +60,23 @@ func MapValueSpecs(d *schema.ResourceData) map[string]string { } return m } + +// List of headers that need to be redacted +var REDACT_HEADERS = []string{"x-auth-token", "x-auth-key", "x-service-token", + "x-storage-token", "x-account-meta-temp-url-key", "x-account-meta-temp-url-key-2", + "x-container-meta-temp-url-key", "x-container-meta-temp-url-key-2", "set-cookie", + "x-subject-token"} + +// RedactHeaders processes a headers object, returning a redacted list +func RedactHeaders(headers http.Header) (processedHeaders []string) { + for name, header := range headers { + for _, v := range header { + if com.IsSliceContainsStr(REDACT_HEADERS, name) { + processedHeaders = append(processedHeaders, fmt.Sprintf("%v: %v", name, "***")) + } else { + processedHeaders = append(processedHeaders, fmt.Sprintf("%v: %v", name, v)) + } + } + } + return +} diff --git a/builtin/providers/ovh/config.go b/builtin/providers/ovh/config.go new file mode 100644 index 000000000..95fbfe768 --- /dev/null +++ b/builtin/providers/ovh/config.go @@ -0,0 +1,67 @@ +package ovh + +import ( + "fmt" + "log" + + "github.com/ovh/go-ovh/ovh" +) + +type Config struct { + Endpoint string + ApplicationKey string + ApplicationSecret string + ConsumerKey string + OVHClient *ovh.Client +} + +/* type used to verify client access to ovh api + */ +type PartialMe struct { + Firstname string `json:"firstname"` +} + +func clientDefault(c *Config) (*ovh.Client, error) { + client, err := ovh.NewClient( + c.Endpoint, + c.ApplicationKey, + c.ApplicationSecret, + c.ConsumerKey, + ) + if err != nil { + return nil, err + } + return client, nil +} + +func (c *Config) loadAndValidate() error { + validEndpoint := false + + ovhEndpoints := [2]string{ovh.OvhEU, ovh.OvhCA} + + for _, e := range ovhEndpoints { + if ovh.Endpoints[c.Endpoint] == e { + validEndpoint = true + } + } + + if !validEndpoint { + return fmt.Errorf("%s must be one of %#v endpoints\n", c.Endpoint, ovh.Endpoints) + } + + targetClient, err := clientDefault(c) + if err != nil { + return fmt.Errorf("Error getting ovh client: %q\n", err) + } + + var me PartialMe + err = targetClient.Get("/me", &me) + if err != nil { + return fmt.Errorf("OVH client seems to be misconfigured: %q\n", err) + } + + log.Printf("[DEBUG] Logged in on OVH API as %s!", me.Firstname) + c.OVHClient = targetClient + + return nil +} diff --git a/builtin/providers/ovh/data_source_ovh_publiccloud_region.go b/builtin/providers/ovh/data_source_ovh_publiccloud_region.go new file mode 100644 index 000000000..9f324b94a --- /dev/null +++ b/builtin/providers/ovh/data_source_ovh_publiccloud_region.go @@ -0,0 +1,99 @@ +package ovh + +import ( + "fmt" + "log" + + "github.com/hashicorp/terraform/helper/hashcode" + "github.com/hashicorp/terraform/helper/schema" +) + +func dataSourcePublicCloudRegion() *schema.Resource { + return &schema.Resource{ + Read: dataSourcePublicCloudRegionRead, + Schema: map[string]*schema.Schema{ + "project_id": &schema.Schema{ + Type: schema.TypeString, + Required: true, + ForceNew: true, + DefaultFunc: schema.EnvDefaultFunc("OVH_PROJECT_ID", nil), + }, + "name": &schema.Schema{ + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + "services": &schema.Schema{ + Type: schema.TypeSet, + Set: publicCloudServiceHash, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "name": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + }, + + "status": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + }, + }, + }, + }, + + "continentCode": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + }, + + "datacenterLocation": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + }, + }, + } +} + +func dataSourcePublicCloudRegionRead(d *schema.ResourceData, meta interface{}) error { + config := meta.(*Config) + projectId := d.Get("project_id").(string) + name := d.Get("name").(string) + + log.Printf("[DEBUG] Will read public cloud region %s for project: %s", name, projectId) + d.Partial(true) + + response := &PublicCloudRegionResponse{} + endpoint := fmt.Sprintf("/cloud/project/%s/region/%s", projectId, name) + err := config.OVHClient.Get(endpoint, response) + + if err != nil { + return fmt.Errorf("Error calling %s:\n\t %q", endpoint, err) + } + + d.Set("datacenterLocation", response.DatacenterLocation) + d.Set("continentCode", response.ContinentCode) + + services := &schema.Set{ + F: publicCloudServiceHash, + } + for i := range response.Services { + service := map[string]interface{}{ + "name": response.Services[i].Name, + "status": response.Services[i].Status, + } + services.Add(service) + } + + d.Set("services", services) + + d.Partial(false) + d.SetId(fmt.Sprintf("%s_%s", projectId, name)) + + return nil +} + +func publicCloudServiceHash(v interface{}) int { + r := v.(map[string]interface{}) + return hashcode.String(r["name"].(string)) +} diff --git a/builtin/providers/ovh/data_source_ovh_publiccloud_region_test.go b/builtin/providers/ovh/data_source_ovh_publiccloud_region_test.go new file mode 100644 index 000000000..963b21211 --- /dev/null +++ b/builtin/providers/ovh/data_source_ovh_publiccloud_region_test.go @@ -0,0 +1,55 @@ +package ovh + +import ( + "fmt" + "os" + "testing" + + "github.com/hashicorp/terraform/helper/resource" + "github.com/hashicorp/terraform/terraform" +) + +func TestAccPublicCloudRegionDataSource_basic(t *testing.T) { + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + Steps: []resource.TestStep{ + resource.TestStep{ + Config: testAccPublicCloudRegionDatasourceConfig, + Check: resource.ComposeTestCheckFunc( + testAccPublicCloudRegionDatasource("data.ovh_publiccloud_region.region_attr.0"), + testAccPublicCloudRegionDatasource("data.ovh_publiccloud_region.region_attr.1"), + testAccPublicCloudRegionDatasource("data.ovh_publiccloud_region.region_attr.2"), + ), + }, + }, + }) +} + +func testAccPublicCloudRegionDatasource(n string) resource.TestCheckFunc { + return func(s *terraform.State) error { + rs, ok := s.RootModule().Resources[n] + + if !ok { + return fmt.Errorf("Can't find regions data source: %s", n) + } + + if rs.Primary.ID == "" { + return fmt.Errorf("Cannot find region attributes for project %s and region %s", rs.Primary.Attributes["project_id"], rs.Primary.Attributes["region"]) + } + + return nil + } +} + +var testAccPublicCloudRegionDatasourceConfig = fmt.Sprintf(` +data "ovh_publiccloud_regions" "regions" { + project_id = "%s" +} + +data "ovh_publiccloud_region" "region_attr" { + count = 3 + project_id = "${data.ovh_publiccloud_regions.regions.project_id}" + name = "${element(data.ovh_publiccloud_regions.regions.names, count.index)}" +} +`, os.Getenv("OVH_PUBLIC_CLOUD")) diff --git a/builtin/providers/ovh/data_source_ovh_publiccloud_regions.go b/builtin/providers/ovh/data_source_ovh_publiccloud_regions.go new file mode 100644 index 000000000..726ad3e35 --- /dev/null +++ b/builtin/providers/ovh/data_source_ovh_publiccloud_regions.go @@ -0,0 +1,51 @@ +package ovh + +import ( + "fmt" + "log" + + "github.com/hashicorp/terraform/helper/schema" +) + +func dataSourcePublicCloudRegions() *schema.Resource { + return &schema.Resource{ + Read: dataSourcePublicCloudRegionsRead, + Schema: map[string]*schema.Schema{ + "project_id": &schema.Schema{ + Type: schema.TypeString, + Required: true, + ForceNew: true, + DefaultFunc: schema.EnvDefaultFunc("OVH_PROJECT_ID", nil), + }, + "names": &schema.Schema{ + Type: schema.TypeSet, + Computed: true, + Elem: &schema.Schema{Type: schema.TypeString}, + Set: schema.HashString, + }, + }, + } +} + +func dataSourcePublicCloudRegionsRead(d *schema.ResourceData, meta interface{}) error { + config := meta.(*Config) + projectId := d.Get("project_id").(string) + + log.Printf("[DEBUG] Will read public cloud regions for project: %s", projectId) + d.Partial(true) + + endpoint := fmt.Sprintf("/cloud/project/%s/region", projectId) + names := make([]string, 0) + err := config.OVHClient.Get(endpoint, &names) + + if err != nil { + return fmt.Errorf("Error calling %s:\n\t %q", endpoint, err) + } + + d.Set("names", names) + d.Partial(false) + d.SetId(projectId) + + log.Printf("[DEBUG] Read Public Cloud Regions %s", names) + return nil +} diff --git a/builtin/providers/ovh/data_source_ovh_publiccloud_regions_test.go b/builtin/providers/ovh/data_source_ovh_publiccloud_regions_test.go new file mode 100644 index 000000000..5030bcd35 --- /dev/null +++ b/builtin/providers/ovh/data_source_ovh_publiccloud_regions_test.go @@ -0,0 +1,47 @@ +package ovh + +import ( + "fmt" + "os" + "testing" + + "github.com/hashicorp/terraform/helper/resource" + "github.com/hashicorp/terraform/terraform" +) + +func TestAccPublicCloudRegionsDataSource_basic(t *testing.T) { + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + Steps: []resource.TestStep{ + resource.TestStep{ + Config: testAccPublicCloudRegionsDatasourceConfig, + Check: resource.ComposeTestCheckFunc( + testAccPublicCloudRegionsDatasource("data.ovh_publiccloud_regions.regions"), + ), + }, + }, + }) +} + +func testAccPublicCloudRegionsDatasource(n string) resource.TestCheckFunc { + return func(s *terraform.State) error { + rs, ok := s.RootModule().Resources[n] + + if !ok { + return fmt.Errorf("Can't find regions data source: %s", n) + } + + if rs.Primary.ID == "" { + return fmt.Errorf("Cannot find regions for project %s", rs.Primary.Attributes["project_id"]) + } + + return nil + } +} + +var testAccPublicCloudRegionsDatasourceConfig = fmt.Sprintf(` +data "ovh_publiccloud_regions" "regions" { + project_id = "%s" +} +`, os.Getenv("OVH_PUBLIC_CLOUD")) diff --git a/builtin/providers/ovh/provider.go b/builtin/providers/ovh/provider.go new file mode 100644 index 000000000..5260a917f --- /dev/null +++ b/builtin/providers/ovh/provider.go @@ -0,0 +1,80 @@ +package ovh + +import ( + "github.com/hashicorp/terraform/helper/schema" + "github.com/hashicorp/terraform/terraform" +) + +// Provider returns a schema.Provider for OVH. +func Provider() terraform.ResourceProvider { + return &schema.Provider{ + Schema: map[string]*schema.Schema{ + "endpoint": &schema.Schema{ + Type: schema.TypeString, + Required: true, + DefaultFunc: schema.EnvDefaultFunc("OVH_ENDPOINT", nil), + Description: descriptions["endpoint"], + }, + "application_key": &schema.Schema{ + Type: schema.TypeString, + Required: true, + DefaultFunc: schema.EnvDefaultFunc("OVH_APPLICATION_KEY", ""), + Description: descriptions["application_key"], + }, + "application_secret": &schema.Schema{ + Type: schema.TypeString, + Required: true, + DefaultFunc: schema.EnvDefaultFunc("OVH_APPLICATION_SECRET", ""), + Description: descriptions["application_secret"], + }, + "consumer_key": &schema.Schema{ + Type: schema.TypeString, + Required: true, + DefaultFunc: schema.EnvDefaultFunc("OVH_CONSUMER_KEY", ""), + Description: descriptions["consumer_key"], + }, + }, + + DataSourcesMap: map[string]*schema.Resource{ + "ovh_publiccloud_region": dataSourcePublicCloudRegion(), + "ovh_publiccloud_regions": dataSourcePublicCloudRegions(), + }, + + ResourcesMap: map[string]*schema.Resource{ + "ovh_publiccloud_private_network": resourcePublicCloudPrivateNetwork(), + "ovh_publiccloud_private_network_subnet": resourcePublicCloudPrivateNetworkSubnet(), + "ovh_publiccloud_user": resourcePublicCloudUser(), + "ovh_vrack_publiccloud_attachment": resourceVRackPublicCloudAttachment(), + }, + + ConfigureFunc: configureProvider, + } +} + +var descriptions map[string]string + +func init() { + descriptions = map[string]string{ + "endpoint": "The OVH API endpoint to target (ex: \"ovh-eu\").", + + "application_key": "The OVH API Application Key.", + + "application_secret": "The OVH API Application Secret.", + "consumer_key": "The OVH API Consumer key.", + } +} + +func configureProvider(d *schema.ResourceData) (interface{}, error) { + config := Config{ + Endpoint: d.Get("endpoint").(string), + ApplicationKey: d.Get("application_key").(string), + ApplicationSecret: d.Get("application_secret").(string), + ConsumerKey: d.Get("consumer_key").(string), + } + + if err := config.loadAndValidate(); err != nil { + return nil, err + } + + return &config, nil +} diff --git a/builtin/providers/ovh/provider_test.go b/builtin/providers/ovh/provider_test.go new file mode 100644 index 000000000..e2f9adda8 --- /dev/null +++ b/builtin/providers/ovh/provider_test.go @@ -0,0 +1,119 @@ +package ovh + +import ( + "fmt" + "log" + "os" + "testing" + + "github.com/hashicorp/terraform/helper/schema" + "github.com/hashicorp/terraform/terraform" + + "github.com/ovh/go-ovh/ovh" +) + +var testAccProviders map[string]terraform.ResourceProvider +var testAccProvider *schema.Provider +var testAccOVHClient *ovh.Client + +func init() { + log.SetOutput(os.Stdout) + testAccProvider = Provider().(*schema.Provider) + testAccProviders = map[string]terraform.ResourceProvider{ + "ovh": testAccProvider, + } +} + +func TestProvider(t *testing.T) { + if err := Provider().(*schema.Provider).InternalValidate(); err != nil { + t.Fatalf("err: %s", err) + } +} + +func TestProvider_impl(t *testing.T) { + var _ terraform.ResourceProvider = Provider() +} + +func testAccPreCheck(t *testing.T) { + v := os.Getenv("OVH_ENDPOINT") + if v == "" { + t.Fatal("OVH_ENDPOINT must be set for acceptance tests") + } + + v = os.Getenv("OVH_APPLICATION_KEY") + if v == "" { + t.Fatal("OVH_APPLICATION_KEY must be set for acceptance tests") + } + + v = os.Getenv("OVH_APPLICATION_SECRET") + if v == "" { + t.Fatal("OVH_APPLICATION_SECRET must be set for acceptance tests") + } + + v = os.Getenv("OVH_CONSUMER_KEY") + if v == "" { + t.Fatal("OVH_CONSUMER_KEY must be set for acceptance tests") + } + + v = os.Getenv("OVH_VRACK") + if v == "" { + t.Fatal("OVH_VRACK must be set for acceptance tests") + } + + v = os.Getenv("OVH_PUBLIC_CLOUD") + if v == "" { + t.Fatal("OVH_PUBLIC_CLOUD must be set for acceptance tests") + } + + if testAccOVHClient == nil { + config := Config{ + Endpoint: os.Getenv("OVH_ENDPOINT"), + ApplicationKey: os.Getenv("OVH_APPLICATION_KEY"), + ApplicationSecret: os.Getenv("OVH_APPLICATION_SECRET"), + ConsumerKey: os.Getenv("OVH_CONSUMER_KEY"), + } + + if err := config.loadAndValidate(); err != nil { + t.Fatalf("couln't load OVH Client: %s", err) + } else { + testAccOVHClient = config.OVHClient + } + } +} + +func testAccCheckVRackExists(t *testing.T) { + type vrackResponse struct { + Name string `json:"name"` + Description string `json:"description"` + } + + r := vrackResponse{} + + endpoint := fmt.Sprintf("/vrack/%s", os.Getenv("OVH_VRACK")) + + err := testAccOVHClient.Get(endpoint, &r) + if err != nil { + t.Fatalf("Error: %q\n", err) + } + t.Logf("Read VRack %s -> name:'%s', desc:'%s' ", endpoint, r.Name, r.Description) + +} + +func testAccCheckPublicCloudExists(t *testing.T) { + type cloudProjectResponse struct { + ID string `json:"project_id"` + Status string `json:"status"` + Description string `json:"description"` + } + + r := cloudProjectResponse{} + + endpoint := fmt.Sprintf("/cloud/project/%s", os.Getenv("OVH_PUBLIC_CLOUD")) + + err := testAccOVHClient.Get(endpoint, &r) + if err != nil { + t.Fatalf("Error: %q\n", err) + } + t.Logf("Read Cloud Project %s -> status: '%s', desc: '%s'", endpoint, r.Status, r.Description) + +} diff --git a/builtin/providers/ovh/resource_ovh_publiccloud_private_network.go b/builtin/providers/ovh/resource_ovh_publiccloud_private_network.go new file mode 100644 index 000000000..9044acf22 --- /dev/null +++ b/builtin/providers/ovh/resource_ovh_publiccloud_private_network.go @@ -0,0 +1,297 @@ +package ovh + +import ( + "fmt" + "log" + "time" + + "github.com/hashicorp/terraform/helper/resource" + "github.com/hashicorp/terraform/helper/schema" + + "github.com/ovh/go-ovh/ovh" +) + +func resourcePublicCloudPrivateNetwork() *schema.Resource { + return &schema.Resource{ + Create: resourcePublicCloudPrivateNetworkCreate, + Read: resourcePublicCloudPrivateNetworkRead, + Update: resourcePublicCloudPrivateNetworkUpdate, + Delete: resourcePublicCloudPrivateNetworkDelete, + Importer: &schema.ResourceImporter{ + State: func(d *schema.ResourceData, meta interface{}) ([]*schema.ResourceData, error) { + return []*schema.ResourceData{d}, nil + }, + }, + + Schema: map[string]*schema.Schema{ + "project_id": &schema.Schema{ + Type: schema.TypeString, + Required: true, + ForceNew: true, + DefaultFunc: schema.EnvDefaultFunc("OVH_PROJECT_ID", nil), + }, + "name": &schema.Schema{ + Type: schema.TypeString, + Required: true, + ForceNew: false, + }, + "vlan_id": &schema.Schema{ + Type: schema.TypeInt, + Optional: true, + ForceNew: true, + Default: 0, + }, + "regions": &schema.Schema{ + Type: schema.TypeSet, + Optional: true, + Computed: true, + ForceNew: true, + Elem: &schema.Schema{Type: schema.TypeString}, + Set: schema.HashString, + }, + + "regions_status": &schema.Schema{ + Type: schema.TypeSet, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "status": &schema.Schema{ + Type: schema.TypeString, + Required: true, + }, + + "region": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + }, + }, + }, + }, + "status": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + }, + "type": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + }, + }, + } +} + +func resourcePublicCloudPrivateNetworkCreate(d *schema.ResourceData, meta interface{}) error { + config := meta.(*Config) + + projectId := d.Get("project_id").(string) + params := &PublicCloudPrivateNetworkCreateOpts{ + ProjectId: d.Get("project_id").(string), + VlanId: d.Get("vlan_id").(int), + Name: d.Get("name").(string), + Regions: regionsOptsFromSchema(d), + } + + r := &PublicCloudPrivateNetworkResponse{} + + log.Printf("[DEBUG] Will create public cloud private network: %s", params) + + endpoint := fmt.Sprintf("/cloud/project/%s/network/private", params.ProjectId) + + err := config.OVHClient.Post(endpoint, params, r) + if err != nil { + return fmt.Errorf("calling %s with params %s:\n\t %q", endpoint, params, err) + } + + log.Printf("[DEBUG] Waiting for Private Network %s:", r) + + stateConf := &resource.StateChangeConf{ + Pending: []string{"BUILDING"}, + Target: []string{"ACTIVE"}, + Refresh: waitForPublicCloudPrivateNetworkActive(config.OVHClient, projectId, r.Id), + Timeout: 10 * time.Minute, + Delay: 10 * time.Second, + MinTimeout: 3 * time.Second, + } + + _, err = stateConf.WaitForState() + if err != nil { + return fmt.Errorf("waiting for private network (%s): %s", params, err) + } + log.Printf("[DEBUG] Created Private Network %s", r) + + //set id + d.SetId(r.Id) + + return nil +} + +func resourcePublicCloudPrivateNetworkRead(d *schema.ResourceData, meta interface{}) error { + config := meta.(*Config) + + projectId := d.Get("project_id").(string) + + r := &PublicCloudPrivateNetworkResponse{} + + log.Printf("[DEBUG] Will read public cloud private network for project: %s, id: %s", projectId, d.Id()) + + endpoint := fmt.Sprintf("/cloud/project/%s/network/private/%s", projectId, d.Id()) + + d.Partial(true) + err := config.OVHClient.Get(endpoint, r) + if err != nil { + return fmt.Errorf("Error calling %s:\n\t %q", endpoint, err) + } + + err = readPublicCloudPrivateNetwork(config, d, r) + if err != nil { + return err + } + d.Partial(false) + + log.Printf("[DEBUG] Read Public Cloud Private Network %s", r) + return nil +} + +func resourcePublicCloudPrivateNetworkUpdate(d *schema.ResourceData, meta interface{}) error { + config := meta.(*Config) + + projectId := d.Get("project_id").(string) + params := &PublicCloudPrivateNetworkUpdateOpts{ + Name: d.Get("name").(string), + } + + log.Printf("[DEBUG] Will update public cloud private network: %s", params) + + endpoint := fmt.Sprintf("/cloud/project/%s/network/private/%s", projectId, d.Id()) + + err := config.OVHClient.Put(endpoint, params, nil) + if err != nil { + return fmt.Errorf("calling %s with params %s:\n\t %q", endpoint, params, err) + } + + log.Printf("[DEBUG] Updated Public cloud %s Private Network %s:", projectId, d.Id()) + + return resourcePublicCloudPrivateNetworkRead(d, meta) +} + +func resourcePublicCloudPrivateNetworkDelete(d *schema.ResourceData, meta interface{}) error { + config := meta.(*Config) + + projectId := d.Get("project_id").(string) + id := d.Id() + + log.Printf("[DEBUG] Will delete public cloud private network for project: %s, id: %s", projectId, id) + + endpoint := fmt.Sprintf("/cloud/project/%s/network/private/%s", projectId, id) + + err := config.OVHClient.Delete(endpoint, nil) + if err != nil { + return fmt.Errorf("calling %s:\n\t %q", endpoint, err) + } + + stateConf := &resource.StateChangeConf{ + Pending: []string{"DELETING"}, + Target: []string{"DELETED"}, + Refresh: waitForPublicCloudPrivateNetworkDelete(config.OVHClient, projectId, id), + Timeout: 10 * time.Minute, + Delay: 10 * time.Second, + MinTimeout: 3 * time.Second, + } + + _, err = stateConf.WaitForState() + if err != nil { + return fmt.Errorf("deleting for private network (%s): %s", id, err) + } + + d.SetId("") + + log.Printf("[DEBUG] Deleted Public Cloud %s Private Network %s", projectId, id) + return nil +} + +func regionsOptsFromSchema(d *schema.ResourceData) []string { + var regions []string + if v := d.Get("regions"); v != nil { + rs := v.(*schema.Set).List() + if len(rs) > 0 { + for _, v := range v.(*schema.Set).List() { + regions = append(regions, v.(string)) + } + } + } + return regions +} + +func readPublicCloudPrivateNetwork(config *Config, d *schema.ResourceData, r *PublicCloudPrivateNetworkResponse) error { + d.Set("name", r.Name) + d.Set("status", r.Status) + d.Set("type", r.Type) + d.Set("vlan_id", r.Vlanid) + + regions_status := make([]map[string]interface{}, 0) + regions := make([]string, 0) + + for i := range r.Regions { + region := make(map[string]interface{}) + region["region"] = r.Regions[i].Region + region["status"] = r.Regions[i].Status + regions_status = append(regions_status, region) + regions = append(regions, fmt.Sprintf(r.Regions[i].Region)) + } + d.Set("regions_status", regions_status) + d.Set("regions", regions) + + d.SetId(r.Id) + return nil +} + +func publicCloudPrivateNetworkExists(projectId, id string, c *ovh.Client) error { + r := &PublicCloudPrivateNetworkResponse{} + + log.Printf("[DEBUG] Will read public cloud private network for project: %s, id: %s", projectId, id) + + endpoint := fmt.Sprintf("/cloud/project/%s/network/private/%s", projectId, id) + + err := c.Get(endpoint, r) + if err != nil { + return fmt.Errorf("calling %s:\n\t %q", endpoint, err) + } + log.Printf("[DEBUG] Read public cloud private network: %s", r) + + return nil +} + +// AttachmentStateRefreshFunc returns a resource.StateRefreshFunc that is used to watch +// an Attachment Task. +func waitForPublicCloudPrivateNetworkActive(c *ovh.Client, projectId, PublicCloudPrivateNetworkId string) resource.StateRefreshFunc { + return func() (interface{}, string, error) { + r := &PublicCloudPrivateNetworkResponse{} + endpoint := fmt.Sprintf("/cloud/project/%s/network/private/%s", projectId, PublicCloudPrivateNetworkId) + err := c.Get(endpoint, r) + if err != nil { + return r, "", err + } + + log.Printf("[DEBUG] Pending Private Network: %s", r) + return r, r.Status, nil + } +} + +// AttachmentStateRefreshFunc returns a resource.StateRefreshFunc that is used to watch +// an Attachment Task. +func waitForPublicCloudPrivateNetworkDelete(c *ovh.Client, projectId, PublicCloudPrivateNetworkId string) resource.StateRefreshFunc { + return func() (interface{}, string, error) { + r := &PublicCloudPrivateNetworkResponse{} + endpoint := fmt.Sprintf("/cloud/project/%s/network/private/%s", projectId, PublicCloudPrivateNetworkId) + err := c.Get(endpoint, r) + if err != nil { + if err.(*ovh.APIError).Code == 404 { + log.Printf("[DEBUG] private network id %s on project %s deleted", PublicCloudPrivateNetworkId, projectId) + return r, "DELETED", nil + } else { + return r, "", err + } + } + log.Printf("[DEBUG] Pending Private Network: %s", r) + return r, r.Status, nil + } +} diff --git a/builtin/providers/ovh/resource_ovh_publiccloud_private_network_subnet.go b/builtin/providers/ovh/resource_ovh_publiccloud_private_network_subnet.go new file mode 100644 index 000000000..de8d4204c --- /dev/null +++ b/builtin/providers/ovh/resource_ovh_publiccloud_private_network_subnet.go @@ -0,0 +1,281 @@ +package ovh + +import ( + "fmt" + "log" + + "github.com/hashicorp/terraform/helper/schema" + + "net" + + "github.com/ovh/go-ovh/ovh" +) + +func resourcePublicCloudPrivateNetworkSubnet() *schema.Resource { + return &schema.Resource{ + Create: resourcePublicCloudPrivateNetworkSubnetCreate, + Read: resourcePublicCloudPrivateNetworkSubnetRead, + Delete: resourcePublicCloudPrivateNetworkSubnetDelete, + Importer: &schema.ResourceImporter{ + State: func(d *schema.ResourceData, meta interface{}) ([]*schema.ResourceData, error) { + return []*schema.ResourceData{d}, nil + }, + }, + + Schema: map[string]*schema.Schema{ + "project_id": &schema.Schema{ + Type: schema.TypeString, + Required: true, + ForceNew: true, + DefaultFunc: schema.EnvDefaultFunc("OVH_PROJECT_ID", ""), + }, + "network_id": &schema.Schema{ + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + "dhcp": &schema.Schema{ + Type: schema.TypeBool, + Optional: true, + ForceNew: true, + Default: false, + }, + "start": &schema.Schema{ + Type: schema.TypeString, + Required: true, + ForceNew: true, + ValidateFunc: resourcePubliccloudPrivateNetworkSubnetValidateIP, + }, + "end": &schema.Schema{ + Type: schema.TypeString, + Required: true, + ForceNew: true, + ValidateFunc: resourcePubliccloudPrivateNetworkSubnetValidateIP, + }, + "network": &schema.Schema{ + Type: schema.TypeString, + Required: true, + ForceNew: true, + ValidateFunc: resourcePubliccloudPrivateNetworkSubnetValidateNetwork, + }, + "region": &schema.Schema{ + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + "no_gateway": &schema.Schema{ + Type: schema.TypeBool, + Optional: true, + ForceNew: true, + Default: false, + }, + "gateway_ip": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + }, + + "cidr": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + }, + + "ip_pools": &schema.Schema{ + Type: schema.TypeSet, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "network": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + }, + "region": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + }, + "dhcp": &schema.Schema{ + Type: schema.TypeBool, + Computed: true, + }, + "end": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + }, + "start": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + }, + }, + }, + }, + }, + } +} + +func resourcePublicCloudPrivateNetworkSubnetCreate(d *schema.ResourceData, meta interface{}) error { + config := meta.(*Config) + + projectId := d.Get("project_id").(string) + networkId := d.Get("network_id").(string) + + params := &PublicCloudPrivateNetworksCreateOpts{ + ProjectId: projectId, + NetworkId: networkId, + Dhcp: d.Get("dhcp").(bool), + NoGateway: d.Get("no_gateway").(bool), + Start: d.Get("start").(string), + End: d.Get("end").(string), + Network: d.Get("network").(string), + Region: d.Get("region").(string), + } + + r := &PublicCloudPrivateNetworksResponse{} + + log.Printf("[DEBUG] Will create public cloud private network subnet: %s", params) + + endpoint := fmt.Sprintf("/cloud/project/%s/network/private/%s/subnet", projectId, networkId) + + err := config.OVHClient.Post(endpoint, params, r) + if err != nil { + return fmt.Errorf("calling %s with params %s:\n\t %q", endpoint, params, err) + } + + log.Printf("[DEBUG] Created Private Network Subnet %s", r) + + //set id + d.SetId(r.Id) + + return nil +} + +func resourcePublicCloudPrivateNetworkSubnetRead(d *schema.ResourceData, meta interface{}) error { + config := meta.(*Config) + + projectId := d.Get("project_id").(string) + networkId := d.Get("network_id").(string) + + r := []*PublicCloudPrivateNetworksResponse{} + + log.Printf("[DEBUG] Will read public cloud private network subnet for project: %s, network: %s, id: %s", projectId, networkId, d.Id()) + + endpoint := fmt.Sprintf("/cloud/project/%s/network/private/%s/subnet", projectId, networkId) + + err := config.OVHClient.Get(endpoint, &r) + if err != nil { + return fmt.Errorf("calling %s:\n\t %q", endpoint, err) + } + + err = readPublicCloudPrivateNetworkSubnet(d, r) + if err != nil { + return err + } + + log.Printf("[DEBUG] Read Public Cloud Private Network %v", r) + return nil +} + +func resourcePublicCloudPrivateNetworkSubnetDelete(d *schema.ResourceData, meta interface{}) error { + config := meta.(*Config) + + projectId := d.Get("project_id").(string) + networkId := d.Get("network_id").(string) + id := d.Id() + + log.Printf("[DEBUG] Will delete public cloud private network subnet for project: %s, network: %s, id: %s", projectId, networkId, id) + + endpoint := fmt.Sprintf("/cloud/project/%s/network/private/%s/subnet/%s", projectId, id, id) + + err := config.OVHClient.Delete(endpoint, nil) + if err != nil { + return fmt.Errorf("calling %s:\n\t %q", endpoint, err) + } + + d.SetId("") + + log.Printf("[DEBUG] Deleted Public Cloud %s Private Network %s Subnet %s", projectId, networkId, id) + return nil +} + +func publicCloudPrivateNetworkSubnetExists(projectId, networkId, id string, c *ovh.Client) error { + r := []*PublicCloudPrivateNetworksResponse{} + + log.Printf("[DEBUG] Will read public cloud private network subnet for project: %s, network: %s, id: %s", projectId, networkId, id) + + endpoint := fmt.Sprintf("/cloud/project/%s/network/private/%s/subnet", projectId, networkId) + + err := c.Get(endpoint, &r) + if err != nil { + return fmt.Errorf("calling %s:\n\t %q", endpoint, err) + } + + s := findPublicCloudPrivateNetworkSubnet(r, id) + if s == nil { + return fmt.Errorf("Subnet %s doesn't exists for project %s and network %s", id, projectId, networkId) + } + + return nil +} + +func findPublicCloudPrivateNetworkSubnet(rs []*PublicCloudPrivateNetworksResponse, id string) *PublicCloudPrivateNetworksResponse { + for i := range rs { + if rs[i].Id == id { + return rs[i] + } + } + + return nil +} + +func readPublicCloudPrivateNetworkSubnet(d *schema.ResourceData, rs []*PublicCloudPrivateNetworksResponse) error { + r := findPublicCloudPrivateNetworkSubnet(rs, d.Id()) + if r == nil { + return fmt.Errorf("%s subnet not found", d.Id()) + } + + d.Set("gateway_ip", r.GatewayIp) + d.Set("cidr", r.Cidr) + + ippools := make([]map[string]interface{}, 0) + for i := range r.IPPools { + ippool := make(map[string]interface{}) + ippool["network"] = r.IPPools[i].Network + ippool["region"] = r.IPPools[i].Region + ippool["dhcp"] = r.IPPools[i].Dhcp + ippool["start"] = r.IPPools[i].Start + ippool["end"] = r.IPPools[i].End + ippools = append(ippools, ippool) + } + + d.Set("network", ippools[0]["network"]) + d.Set("region", ippools[0]["region"]) + d.Set("dhcp", ippools[0]["dhcp"]) + d.Set("start", ippools[0]["start"]) + d.Set("end", ippools[0]["end"]) + d.Set("ip_pools", ippools) + + if r.GatewayIp == "" { + d.Set("no_gateway", true) + } else { + d.Set("no_gateway", false) + } + + d.SetId(r.Id) + return nil +} + +func resourcePubliccloudPrivateNetworkSubnetValidateIP(v interface{}, k string) (ws []string, errors []error) { + value := v.(string) + ip := net.ParseIP(value) + if ip == nil { + errors = append(errors, fmt.Errorf("%q must be a valid IP", k)) + } + return +} + +func resourcePubliccloudPrivateNetworkSubnetValidateNetwork(v interface{}, k string) (ws []string, errors []error) { + value := v.(string) + _, _, err := net.ParseCIDR(value) + if err != nil { + errors = append(errors, fmt.Errorf("%q is not a valid network value: %#v", k, err)) + } + return +} diff --git a/builtin/providers/ovh/resource_ovh_publiccloud_private_network_subnet_test.go b/builtin/providers/ovh/resource_ovh_publiccloud_private_network_subnet_test.go new file mode 100644 index 000000000..25c7d1164 --- /dev/null +++ b/builtin/providers/ovh/resource_ovh_publiccloud_private_network_subnet_test.go @@ -0,0 +1,120 @@ +package ovh + +import ( + "fmt" + "os" + "testing" + + "github.com/hashicorp/terraform/helper/resource" + "github.com/hashicorp/terraform/terraform" +) + +var testAccPublicCloudPrivateNetworkSubnetConfig = fmt.Sprintf(` +resource "ovh_vrack_publiccloud_attachment" "attach" { + vrack_id = "%s" + project_id = "%s" +} + +data "ovh_publiccloud_regions" "regions" { + project_id = "${ovh_vrack_publiccloud_attachment.attach.project_id}" +} + +data "ovh_publiccloud_region" "region_attr" { + count = 2 + project_id = "${data.ovh_publiccloud_regions.regions.project_id}" + name = "${element(data.ovh_publiccloud_regions.regions.names, count.index)}" +} + +resource "ovh_publiccloud_private_network" "network" { + project_id = "${ovh_vrack_publiccloud_attachment.attach.project_id}" + vlan_id = 0 + name = "terraform_testacc_private_net" + regions = ["${data.ovh_publiccloud_regions.regions.names}"] +} + +resource "ovh_publiccloud_private_network_subnet" "subnet" { + project_id = "${ovh_publiccloud_private_network.network.project_id}" + network_id = "${ovh_publiccloud_private_network.network.id}" + region = "${element(data.ovh_publiccloud_regions.regions.names, 0)}" + start = "192.168.168.100" + end = "192.168.168.200" + network = "192.168.168.0/24" + dhcp = true + no_gateway = false +} +`, os.Getenv("OVH_VRACK"), os.Getenv("OVH_PUBLIC_CLOUD")) + +func TestAccPublicCloudPrivateNetworkSubnet_basic(t *testing.T) { + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccCheckPublicCloudPrivateNetworkSubnetPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckPublicCloudPrivateNetworkSubnetDestroy, + Steps: []resource.TestStep{ + resource.TestStep{ + Config: testAccPublicCloudPrivateNetworkSubnetConfig, + Check: resource.ComposeTestCheckFunc( + testAccCheckVRackPublicCloudAttachmentExists("ovh_vrack_publiccloud_attachment.attach", t), + testAccCheckPublicCloudPrivateNetworkExists("ovh_publiccloud_private_network.network", t), + testAccCheckPublicCloudPrivateNetworkSubnetExists("ovh_publiccloud_private_network_subnet.subnet", t), + ), + }, + }, + }) +} + +func testAccCheckPublicCloudPrivateNetworkSubnetPreCheck(t *testing.T) { + testAccPreCheck(t) + testAccCheckPublicCloudExists(t) +} + +func testAccCheckPublicCloudPrivateNetworkSubnetExists(n string, t *testing.T) resource.TestCheckFunc { + return func(s *terraform.State) error { + config := testAccProvider.Meta().(*Config) + + rs, ok := s.RootModule().Resources[n] + if !ok { + return fmt.Errorf("Not found: %s", n) + } + + if rs.Primary.ID == "" { + return fmt.Errorf("No ID is set") + } + + if rs.Primary.Attributes["project_id"] == "" { + return fmt.Errorf("No Project ID is set") + } + + if rs.Primary.Attributes["network_id"] == "" { + return fmt.Errorf("No Network ID is set") + } + + return publicCloudPrivateNetworkSubnetExists( + rs.Primary.Attributes["project_id"], + rs.Primary.Attributes["network_id"], + rs.Primary.ID, + config.OVHClient, + ) + } +} + +func testAccCheckPublicCloudPrivateNetworkSubnetDestroy(s *terraform.State) error { + config := testAccProvider.Meta().(*Config) + for _, rs := range s.RootModule().Resources { + if rs.Type != "ovh_publiccloud_private_network_subnet" { + continue + } + + err := publicCloudPrivateNetworkSubnetExists( + rs.Primary.Attributes["project_id"], + rs.Primary.Attributes["network_id"], + rs.Primary.ID, + config.OVHClient, + ) + + if err == nil { + return fmt.Errorf("VRack > Public Cloud Private Network Subnet still exists") + } + + } + return nil +} diff --git a/builtin/providers/ovh/resource_ovh_publiccloud_private_network_test.go b/builtin/providers/ovh/resource_ovh_publiccloud_private_network_test.go new file mode 100644 index 000000000..6cc1a91b6 --- /dev/null +++ b/builtin/providers/ovh/resource_ovh_publiccloud_private_network_test.go @@ -0,0 +1,93 @@ +package ovh + +import ( + "fmt" + "os" + "testing" + + "github.com/hashicorp/terraform/helper/resource" + "github.com/hashicorp/terraform/terraform" +) + +var testAccPublicCloudPrivateNetworkConfig = fmt.Sprintf(` +resource "ovh_vrack_publiccloud_attachment" "attach" { + vrack_id = "%s" + project_id = "%s" +} + +data "ovh_publiccloud_regions" "regions" { + project_id = "${ovh_vrack_publiccloud_attachment.attach.project_id}" +} + +data "ovh_publiccloud_region" "region_attr" { + count = 2 + project_id = "${data.ovh_publiccloud_regions.regions.project_id}" + name = "${element(data.ovh_publiccloud_regions.regions.names, count.index)}" +} + +resource "ovh_publiccloud_private_network" "network" { + project_id = "${ovh_vrack_publiccloud_attachment.attach.project_id}" + vlan_id = 0 + name = "terraform_testacc_private_net" + regions = ["${data.ovh_publiccloud_regions.regions.names}"] +} +`, os.Getenv("OVH_VRACK"), os.Getenv("OVH_PUBLIC_CLOUD")) + +func TestAccPublicCloudPrivateNetwork_basic(t *testing.T) { + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccCheckPublicCloudPrivateNetworkPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckPublicCloudPrivateNetworkDestroy, + Steps: []resource.TestStep{ + resource.TestStep{ + Config: testAccPublicCloudPrivateNetworkConfig, + Check: resource.ComposeTestCheckFunc( + testAccCheckVRackPublicCloudAttachmentExists("ovh_vrack_publiccloud_attachment.attach", t), + testAccCheckPublicCloudPrivateNetworkExists("ovh_publiccloud_private_network.network", t), + ), + }, + }, + }) +} + +func testAccCheckPublicCloudPrivateNetworkPreCheck(t *testing.T) { + testAccPreCheck(t) + testAccCheckPublicCloudExists(t) +} + +func testAccCheckPublicCloudPrivateNetworkExists(n string, t *testing.T) resource.TestCheckFunc { + return func(s *terraform.State) error { + config := testAccProvider.Meta().(*Config) + + rs, ok := s.RootModule().Resources[n] + if !ok { + return fmt.Errorf("Not found: %s", n) + } + + if rs.Primary.ID == "" { + return fmt.Errorf("No ID is set") + } + + if rs.Primary.Attributes["project_id"] == "" { + return fmt.Errorf("No Project ID is set") + } + + return publicCloudPrivateNetworkExists(rs.Primary.Attributes["project_id"], rs.Primary.ID, config.OVHClient) + } +} + +func testAccCheckPublicCloudPrivateNetworkDestroy(s *terraform.State) error { + config := testAccProvider.Meta().(*Config) + for _, rs := range s.RootModule().Resources { + if rs.Type != "ovh_publiccloud_private_network" { + continue + } + + err := publicCloudPrivateNetworkExists(rs.Primary.Attributes["project_id"], rs.Primary.ID, config.OVHClient) + if err == nil { + return fmt.Errorf("VRack > Public Cloud Private Network still exists") + } + + } + return nil +} diff --git a/builtin/providers/ovh/resource_ovh_publiccloud_user.go b/builtin/providers/ovh/resource_ovh_publiccloud_user.go new file mode 100644 index 000000000..73824cccb --- /dev/null +++ b/builtin/providers/ovh/resource_ovh_publiccloud_user.go @@ -0,0 +1,289 @@ +package ovh + +import ( + "fmt" + "log" + "regexp" + "strconv" + "time" + + "github.com/hashicorp/terraform/helper/resource" + "github.com/hashicorp/terraform/helper/schema" + + "github.com/ovh/go-ovh/ovh" +) + +func resourcePublicCloudUser() *schema.Resource { + return &schema.Resource{ + Create: resourcePublicCloudUserCreate, + Read: resourcePublicCloudUserRead, + Delete: resourcePublicCloudUserDelete, + + Importer: &schema.ResourceImporter{ + State: func(d *schema.ResourceData, meta interface{}) ([]*schema.ResourceData, error) { + return []*schema.ResourceData{d}, nil + }, + }, + + Schema: map[string]*schema.Schema{ + "project_id": &schema.Schema{ + Type: schema.TypeString, + Required: true, + ForceNew: true, + DefaultFunc: schema.EnvDefaultFunc("OVH_PROJECT_ID", nil), + }, + "description": &schema.Schema{ + Type: schema.TypeString, + Optional: true, + ForceNew: true, + }, + "username": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + }, + "password": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Sensitive: true, + }, + "status": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + }, + "creation_date": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + }, + "openstack_rc": &schema.Schema{ + Type: schema.TypeMap, + Optional: true, + Computed: true, + }, + }, + } +} + +func resourcePublicCloudUserCreate(d *schema.ResourceData, meta interface{}) error { + config := meta.(*Config) + + projectId := d.Get("project_id").(string) + params := &PublicCloudUserCreateOpts{ + ProjectId: projectId, + Description: d.Get("description").(string), + } + + r := &PublicCloudUserResponse{} + + log.Printf("[DEBUG] Will create public cloud user: %s", params) + + // Resource is partial because we will also compute Openstack RC & creds + d.Partial(true) + + endpoint := fmt.Sprintf("/cloud/project/%s/user", params.ProjectId) + + err := config.OVHClient.Post(endpoint, params, r) + if err != nil { + return fmt.Errorf("calling Post %s with params %s:\n\t %q", endpoint, params, err) + } + + log.Printf("[DEBUG] Waiting for User %s:", r) + + stateConf := &resource.StateChangeConf{ + Pending: []string{"creating"}, + Target: []string{"ok"}, + Refresh: waitForPublicCloudUserActive(config.OVHClient, projectId, strconv.Itoa(r.Id)), + Timeout: 10 * time.Minute, + Delay: 10 * time.Second, + MinTimeout: 3 * time.Second, + } + + _, err = stateConf.WaitForState() + if err != nil { + return fmt.Errorf("waiting for user (%s): %s", params, err) + } + log.Printf("[DEBUG] Created User %s", r) + + readPublicCloudUser(d, r, true) + + openstackrc := make(map[string]string) + err = publicCloudUserGetOpenstackRC(projectId, d.Id(), config.OVHClient, openstackrc) + if err != nil { + return fmt.Errorf("Creating openstack creds for user %s: %s", d.Id(), err) + } + + d.Set("openstack_rc", &openstackrc) + + d.Partial(false) + + return nil +} + +func resourcePublicCloudUserRead(d *schema.ResourceData, meta interface{}) error { + config := meta.(*Config) + + projectId := d.Get("project_id").(string) + + d.Partial(true) + r := &PublicCloudUserResponse{} + + log.Printf("[DEBUG] Will read public cloud user %s from project: %s", d.Id(), projectId) + + endpoint := fmt.Sprintf("/cloud/project/%s/user/%s", projectId, d.Id()) + + err := config.OVHClient.Get(endpoint, r) + if err != nil { + return fmt.Errorf("calling Get %s:\n\t %q", endpoint, err) + } + + readPublicCloudUser(d, r, false) + + openstackrc := make(map[string]string) + err = publicCloudUserGetOpenstackRC(projectId, d.Id(), config.OVHClient, openstackrc) + if err != nil { + return fmt.Errorf("Reading openstack creds for user %s: %s", d.Id(), err) + } + + d.Set("openstack_rc", &openstackrc) + d.Partial(false) + log.Printf("[DEBUG] Read Public Cloud User %s", r) + return nil +} + +func resourcePublicCloudUserDelete(d *schema.ResourceData, meta interface{}) error { + config := meta.(*Config) + + projectId := d.Get("project_id").(string) + id := d.Id() + + log.Printf("[DEBUG] Will delete public cloud user %s from project: %s", id, projectId) + + endpoint := fmt.Sprintf("/cloud/project/%s/user/%s", projectId, id) + + err := config.OVHClient.Delete(endpoint, nil) + if err != nil { + return fmt.Errorf("calling Delete %s:\n\t %q", endpoint, err) + } + + log.Printf("[DEBUG] Deleting Public Cloud User %s from project %s:", id, projectId) + + stateConf := &resource.StateChangeConf{ + Pending: []string{"deleting"}, + Target: []string{"deleted"}, + Refresh: waitForPublicCloudUserDelete(config.OVHClient, projectId, id), + Timeout: 10 * time.Minute, + Delay: 10 * time.Second, + MinTimeout: 3 * time.Second, + } + + _, err = stateConf.WaitForState() + if err != nil { + return fmt.Errorf("Deleting Public Cloud user %s from project %s", id, projectId) + } + log.Printf("[DEBUG] Deleted Public Cloud User %s from project %s", id, projectId) + + d.SetId("") + + return nil +} + +func publicCloudUserExists(projectId, id string, c *ovh.Client) error { + r := &PublicCloudUserResponse{} + + log.Printf("[DEBUG] Will read public cloud user for project: %s, id: %s", projectId, id) + + endpoint := fmt.Sprintf("/cloud/project/%s/user/%s", projectId, id) + + err := c.Get(endpoint, r) + if err != nil { + return fmt.Errorf("calling Get %s:\n\t %q", endpoint, err) + } + log.Printf("[DEBUG] Read public cloud user: %s", r) + + return nil +} + +var publicCloudUserOSTenantName = regexp.MustCompile("export OS_TENANT_NAME=\"?([[:alnum:]]+)\"?") +var publicCloudUserOSTenantId = regexp.MustCompile("export OS_TENANT_ID=\"??([[:alnum:]]+)\"??") +var publicCloudUserOSAuthURL = regexp.MustCompile("export OS_AUTH_URL=\"??([[:^space:]]+)\"??") +var publicCloudUserOSUsername = regexp.MustCompile("export OS_USERNAME=\"?([[:alnum:]]+)\"?") + +func publicCloudUserGetOpenstackRC(projectId, id string, c *ovh.Client, rc map[string]string) error { + log.Printf("[DEBUG] Will read public cloud user openstack rc for project: %s, id: %s", projectId, id) + + endpoint := fmt.Sprintf("/cloud/project/%s/user/%s/openrc?region=to_be_overriden", projectId, id) + + r := &PublicCloudUserOpenstackRC{} + + err := c.Get(endpoint, r) + if err != nil { + return fmt.Errorf("calling Get %s:\n\t %q", endpoint, err) + } + + authURL := publicCloudUserOSAuthURL.FindStringSubmatch(r.Content) + if authURL == nil { + return fmt.Errorf("couln't extract OS_AUTH_URL from content: \n\t%s", r.Content) + } + tenantName := publicCloudUserOSTenantName.FindStringSubmatch(r.Content) + if tenantName == nil { + return fmt.Errorf("couln't extract OS_TENANT_NAME from content: \n\t%s", r.Content) + } + tenantId := publicCloudUserOSTenantId.FindStringSubmatch(r.Content) + if tenantId == nil { + return fmt.Errorf("couln't extract OS_TENANT_ID from content: \n\t%s", r.Content) + } + username := publicCloudUserOSUsername.FindStringSubmatch(r.Content) + if username == nil { + return fmt.Errorf("couln't extract OS_USERNAME from content: \n\t%s", r.Content) + } + + rc["OS_AUTH_URL"] = authURL[1] + rc["OS_TENANT_ID"] = tenantId[1] + rc["OS_TENANT_NAME"] = tenantName[1] + rc["OS_USERNAME"] = username[1] + + return nil +} + +func readPublicCloudUser(d *schema.ResourceData, r *PublicCloudUserResponse, setPassword bool) { + d.Set("description", r.Description) + d.Set("status", r.Status) + d.Set("creation_date", r.CreationDate) + d.Set("username", r.Username) + if setPassword { + d.Set("password", r.Password) + } + d.SetId(strconv.Itoa(r.Id)) +} + +func waitForPublicCloudUserActive(c *ovh.Client, projectId, PublicCloudUserId string) resource.StateRefreshFunc { + return func() (interface{}, string, error) { + r := &PublicCloudUserResponse{} + endpoint := fmt.Sprintf("/cloud/project/%s/user/%s", projectId, PublicCloudUserId) + err := c.Get(endpoint, r) + if err != nil { + return r, "", err + } + + log.Printf("[DEBUG] Pending User: %s", r) + return r, r.Status, nil + } +} + +func waitForPublicCloudUserDelete(c *ovh.Client, projectId, PublicCloudUserId string) resource.StateRefreshFunc { + return func() (interface{}, string, error) { + r := &PublicCloudUserResponse{} + endpoint := fmt.Sprintf("/cloud/project/%s/user/%s", projectId, PublicCloudUserId) + err := c.Get(endpoint, r) + if err != nil { + if err.(*ovh.APIError).Code == 404 { + log.Printf("[DEBUG] user id %s on project %s deleted", PublicCloudUserId, projectId) + return r, "deleted", nil + } else { + return r, "", err + } + } + + log.Printf("[DEBUG] Pending User: %s", r) + return r, r.Status, nil + } +} diff --git a/builtin/providers/ovh/resource_ovh_publiccloud_user_test.go b/builtin/providers/ovh/resource_ovh_publiccloud_user_test.go new file mode 100644 index 000000000..3edac47d2 --- /dev/null +++ b/builtin/providers/ovh/resource_ovh_publiccloud_user_test.go @@ -0,0 +1,107 @@ +package ovh + +import ( + "fmt" + "os" + "testing" + + "github.com/hashicorp/terraform/helper/resource" + "github.com/hashicorp/terraform/terraform" +) + +var testAccPublicCloudUserConfig = fmt.Sprintf(` +resource "ovh_publiccloud_user" "user" { + project_id = "%s" + description = "my user for acceptance tests" +} +`, os.Getenv("OVH_PUBLIC_CLOUD")) + +func TestAccPublicCloudUser_basic(t *testing.T) { + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccCheckPublicCloudUserPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckPublicCloudUserDestroy, + Steps: []resource.TestStep{ + resource.TestStep{ + Config: testAccPublicCloudUserConfig, + Check: resource.ComposeTestCheckFunc( + testAccCheckPublicCloudUserExists("ovh_publiccloud_user.user", t), + testAccCheckPublicCloudUserOpenRC("ovh_publiccloud_user.user", t), + ), + }, + }, + }) +} + +func testAccCheckPublicCloudUserPreCheck(t *testing.T) { + testAccPreCheck(t) + testAccCheckPublicCloudExists(t) +} + +func testAccCheckPublicCloudUserExists(n string, t *testing.T) resource.TestCheckFunc { + return func(s *terraform.State) error { + config := testAccProvider.Meta().(*Config) + + rs, ok := s.RootModule().Resources[n] + if !ok { + return fmt.Errorf("Not found: %s", n) + } + + if rs.Primary.ID == "" { + return fmt.Errorf("No ID is set") + } + + if rs.Primary.Attributes["project_id"] == "" { + return fmt.Errorf("No Project ID is set") + } + + return publicCloudUserExists(rs.Primary.Attributes["project_id"], rs.Primary.ID, config.OVHClient) + } +} + +func testAccCheckPublicCloudUserOpenRC(n string, t *testing.T) resource.TestCheckFunc { + return func(s *terraform.State) error { + rs, ok := s.RootModule().Resources[n] + if !ok { + return fmt.Errorf("Not found: %s", n) + } + + if rs.Primary.ID == "" { + return fmt.Errorf("No ID is set") + } + + if rs.Primary.Attributes["openstack_rc.OS_AUTH_URL"] == "" { + return fmt.Errorf("No openstack_rc.OS_AUTH_URL is set") + } + + if rs.Primary.Attributes["openstack_rc.OS_TENANT_ID"] == "" { + return fmt.Errorf("No openstack_rc.OS_TENANT_ID is set") + } + + if rs.Primary.Attributes["openstack_rc.OS_TENANT_NAME"] == "" { + return fmt.Errorf("No openstack_rc.OS_TENANT_NAME is set") + } + + if rs.Primary.Attributes["openstack_rc.OS_USERNAME"] == "" { + return fmt.Errorf("No openstack_rc.OS_USERNAME is set") + } + + return nil + } +} + +func testAccCheckPublicCloudUserDestroy(s *terraform.State) error { + config := testAccProvider.Meta().(*Config) + for _, rs := range s.RootModule().Resources { + if rs.Type != "ovh_publiccloud_user" { + continue + } + + err := publicCloudUserExists(rs.Primary.Attributes["project_id"], rs.Primary.ID, config.OVHClient) + if err == nil { + return fmt.Errorf("VRack > Public Cloud User still exists") + } + + } + return nil +} diff --git a/builtin/providers/ovh/resource_ovh_vrack_publiccloud_attachment.go b/builtin/providers/ovh/resource_ovh_vrack_publiccloud_attachment.go new file mode 100644 index 000000000..8ea1db8b4 --- /dev/null +++ b/builtin/providers/ovh/resource_ovh_vrack_publiccloud_attachment.go @@ -0,0 +1,172 @@ +package ovh + +import ( + "fmt" + "log" + "time" + + "github.com/hashicorp/terraform/helper/resource" + "github.com/hashicorp/terraform/helper/schema" + "github.com/ovh/go-ovh/ovh" +) + +func resourceVRackPublicCloudAttachment() *schema.Resource { + return &schema.Resource{ + Create: resourceVRackPublicCloudAttachmentCreate, + Read: resourceVRackPublicCloudAttachmentRead, + Delete: resourceVRackPublicCloudAttachmentDelete, + + Schema: map[string]*schema.Schema{ + "vrack_id": &schema.Schema{ + Type: schema.TypeString, + Required: true, + ForceNew: true, + DefaultFunc: schema.EnvDefaultFunc("OVH_VRACK_ID", ""), + }, + "project_id": &schema.Schema{ + Type: schema.TypeString, + Required: true, + ForceNew: true, + DefaultFunc: schema.EnvDefaultFunc("OVH_PROJECT_ID", ""), + }, + }, + } +} + +func resourceVRackPublicCloudAttachmentCreate(d *schema.ResourceData, meta interface{}) error { + config := meta.(*Config) + + vrackId := d.Get("vrack_id").(string) + projectId := d.Get("project_id").(string) + + if err := vrackPublicCloudAttachmentExists(vrackId, projectId, config.OVHClient); err == nil { + //set id + d.SetId(fmt.Sprintf("vrack_%s-cloudproject_%s-attach", vrackId, projectId)) + return nil + } + + params := &VRackAttachOpts{Project: projectId} + r := VRackAttachTaskResponse{} + + log.Printf("[DEBUG] Will Attach VRack %s -> PublicCloud %s", vrackId, params.Project) + endpoint := fmt.Sprintf("/vrack/%s/cloudProject", vrackId) + + err := config.OVHClient.Post(endpoint, params, &r) + if err != nil { + return fmt.Errorf("Error calling %s with params %s:\n\t %q", endpoint, params, err) + } + + log.Printf("[DEBUG] Waiting for Attachement Task id %d: VRack %s -> PublicCloud %s", r.Id, vrackId, params.Project) + + stateConf := &resource.StateChangeConf{ + Pending: []string{"init", "todo", "doing"}, + Target: []string{"completed"}, + Refresh: waitForVRackTaskCompleted(config.OVHClient, vrackId, r.Id), + Timeout: 10 * time.Minute, + Delay: 10 * time.Second, + MinTimeout: 3 * time.Second, + } + + _, err = stateConf.WaitForState() + if err != nil { + return fmt.Errorf("Error waiting for vrack (%s) to attach to public cloud (%s): %s", vrackId, params.Project, err) + } + log.Printf("[DEBUG] Created Attachement Task id %d: VRack %s -> PublicCloud %s", r.Id, vrackId, params.Project) + + //set id + d.SetId(fmt.Sprintf("vrack_%s-cloudproject_%s-attach", vrackId, params.Project)) + + return nil +} + +func resourceVRackPublicCloudAttachmentRead(d *schema.ResourceData, meta interface{}) error { + config := meta.(*Config) + + vrackId := d.Get("vrack_id").(string) + params := &VRackAttachOpts{Project: d.Get("project_id").(string)} + r := VRackAttachTaskResponse{} + endpoint := fmt.Sprintf("/vrack/%s/cloudProject/%s", vrackId, params.Project) + + err := config.OVHClient.Get(endpoint, &r) + if err != nil { + return err + } + log.Printf("[DEBUG] Read VRack %s -> PublicCloud %s", vrackId, params.Project) + + return nil +} + +func resourceVRackPublicCloudAttachmentDelete(d *schema.ResourceData, meta interface{}) error { + config := meta.(*Config) + + vrackId := d.Get("vrack_id").(string) + params := &VRackAttachOpts{Project: d.Get("project_id").(string)} + + r := VRackAttachTaskResponse{} + endpoint := fmt.Sprintf("/vrack/%s/cloudProject/%s", vrackId, params.Project) + + err := config.OVHClient.Delete(endpoint, &r) + if err != nil { + return err + } + + log.Printf("[DEBUG] Waiting for Attachment Deletion Task id %d: VRack %s -> PublicCloud %s", r.Id, vrackId, params.Project) + + stateConf := &resource.StateChangeConf{ + Pending: []string{"init", "todo", "doing"}, + Target: []string{"completed"}, + Refresh: waitForVRackTaskCompleted(config.OVHClient, vrackId, r.Id), + Timeout: 10 * time.Minute, + Delay: 10 * time.Second, + MinTimeout: 3 * time.Second, + } + + _, err = stateConf.WaitForState() + if err != nil { + return fmt.Errorf("Error waiting for vrack (%s) to attach to public cloud (%s): %s", vrackId, params.Project, err) + } + log.Printf("[DEBUG] Removed Attachement id %d: VRack %s -> PublicCloud %s", r.Id, vrackId, params.Project) + + d.SetId("") + return nil +} + +func vrackPublicCloudAttachmentExists(vrackId, projectId string, c *ovh.Client) error { + type attachResponse struct { + VRack string `json:"vrack"` + Project string `json:"project"` + } + + r := attachResponse{} + + endpoint := fmt.Sprintf("/vrack/%s/cloudProject/%s", vrackId, projectId) + + err := c.Get(endpoint, &r) + if err != nil { + return fmt.Errorf("Error while querying %s: %q\n", endpoint, err) + } + log.Printf("[DEBUG] Read Attachment %s -> VRack:%s, Cloud Project: %s", endpoint, r.VRack, r.Project) + + return nil +} + +// AttachmentStateRefreshFunc returns a resource.StateRefreshFunc that is used to watch +// an Attachment Task. +func waitForVRackTaskCompleted(c *ovh.Client, serviceName string, taskId int) resource.StateRefreshFunc { + return func() (interface{}, string, error) { + r := VRackAttachTaskResponse{} + endpoint := fmt.Sprintf("/vrack/%s/task/%d", serviceName, taskId) + err := c.Get(endpoint, &r) + if err != nil { + if err.(*ovh.APIError).Code == 404 { + log.Printf("[DEBUG] Task id %d on VRack %s completed", taskId, serviceName) + return taskId, "completed", nil + } else { + return taskId, "", err + } + } + + log.Printf("[DEBUG] Pending Task id %d on VRack %s status: %s", r.Id, serviceName, r.Status) + return taskId, r.Status, nil + } +} diff --git a/builtin/providers/ovh/resource_ovh_vrack_publiccloud_attachment_test.go b/builtin/providers/ovh/resource_ovh_vrack_publiccloud_attachment_test.go new file mode 100644 index 000000000..ed687086d --- /dev/null +++ b/builtin/providers/ovh/resource_ovh_vrack_publiccloud_attachment_test.go @@ -0,0 +1,76 @@ +package ovh + +import ( + "fmt" + "os" + "testing" + + "github.com/hashicorp/terraform/helper/resource" + "github.com/hashicorp/terraform/terraform" +) + +var testAccVRackPublicCloudAttachmentConfig = fmt.Sprintf(` +resource "ovh_vrack_publiccloud_attachment" "attach" { + vrack_id = "%s" + project_id = "%s" +} +`, os.Getenv("OVH_VRACK"), os.Getenv("OVH_PUBLIC_CLOUD")) + +func TestAccVRackPublicCloudAttachment_basic(t *testing.T) { + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccCheckVRackPublicCloudAttachmentPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckVRackPublicCloudAttachmentDestroy, + Steps: []resource.TestStep{ + resource.TestStep{ + Config: testAccVRackPublicCloudAttachmentConfig, + Check: resource.ComposeTestCheckFunc( + testAccCheckVRackPublicCloudAttachmentExists("ovh_vrack_publiccloud_attachment.attach", t), + ), + }, + }, + }) +} + +func testAccCheckVRackPublicCloudAttachmentPreCheck(t *testing.T) { + testAccPreCheck(t) + testAccCheckVRackExists(t) + testAccCheckPublicCloudExists(t) +} + +func testAccCheckVRackPublicCloudAttachmentExists(n string, t *testing.T) resource.TestCheckFunc { + return func(s *terraform.State) error { + config := testAccProvider.Meta().(*Config) + + rs, ok := s.RootModule().Resources[n] + if !ok { + return fmt.Errorf("Not found: %s", n) + } + + if rs.Primary.Attributes["vrack_id"] == "" { + return fmt.Errorf("No VRack ID is set") + } + + if rs.Primary.Attributes["project_id"] == "" { + return fmt.Errorf("No Project ID is set") + } + + return vrackPublicCloudAttachmentExists(rs.Primary.Attributes["vrack_id"], rs.Primary.Attributes["project_id"], config.OVHClient) + } +} + +func testAccCheckVRackPublicCloudAttachmentDestroy(s *terraform.State) error { + config := testAccProvider.Meta().(*Config) + for _, rs := range s.RootModule().Resources { + if rs.Type != "ovh_vrack_publiccloud_attachment" { + continue + } + + err := vrackPublicCloudAttachmentExists(rs.Primary.Attributes["vrack_id"], rs.Primary.Attributes["project_id"], config.OVHClient) + if err == nil { + return fmt.Errorf("VRack > Public Cloud Attachment still exists") + } + + } + return nil +} diff --git a/builtin/providers/ovh/types.go b/builtin/providers/ovh/types.go new file mode 100644 index 000000000..7141323c0 --- /dev/null +++ b/builtin/providers/ovh/types.go @@ -0,0 +1,154 @@ +package ovh + +import ( + "fmt" + "time" +) + +// Opts +type PublicCloudPrivateNetworkCreateOpts struct { + ProjectId string `json:"serviceName"` + VlanId int `json:"vlanId"` + Name string `json:"name"` + Regions []string `json:"regions"` +} + +func (p *PublicCloudPrivateNetworkCreateOpts) String() string { + return fmt.Sprintf("projectId: %s, vlanId:%d, name: %s, regions: %s", p.ProjectId, p.VlanId, p.Name, p.Regions) +} + +// Opts +type PublicCloudPrivateNetworkUpdateOpts struct { + Name string `json:"name"` +} + +type PublicCloudPrivateNetworkRegion struct { + Status string `json:"status"` + Region string `json:"region"` +} + +func (p *PublicCloudPrivateNetworkRegion) String() string { + return fmt.Sprintf("Status:%s, Region: %s", p.Status, p.Region) +} + +type PublicCloudPrivateNetworkResponse struct { + Id string `json:"id"` + Status string `json:"status"` + Vlanid int `json:"vlanId"` + Name string `json:"name"` + Type string `json:"type"` + Regions []*PublicCloudPrivateNetworkRegion `json:"regions"` +} + +func (p *PublicCloudPrivateNetworkResponse) String() string { + return fmt.Sprintf("Id: %s, Status: %s, Name: %s, Vlanid: %d, Type: %s, Regions: %s", p.Id, p.Status, p.Name, p.Vlanid, p.Type, p.Regions) +} + +// Opts +type PublicCloudPrivateNetworksCreateOpts struct { + ProjectId string `json:"serviceName"` + NetworkId string `json:"networkId"` + Dhcp bool `json:"dhcp"` + NoGateway bool `json:"noGateway"` + Start string `json:"start"` + End string `json:"end"` + Network string `json:"network"` + Region string `json:"region"` +} + +func (p *PublicCloudPrivateNetworksCreateOpts) String() string { + return fmt.Sprintf("PCPNSCreateOpts[projectId: %s, networkId:%s, dchp: %v, noGateway: %v, network: %s, start: %s, end: %s, region: %s]", + p.ProjectId, p.NetworkId, p.Dhcp, p.NoGateway, p.Network, p.Start, p.End, p.Region) +} + +type IPPool struct { + Network string `json:"network"` + Region string `json:"region"` + Dhcp bool `json:"dhcp"` + Start string `json:"start"` + End string `json:"end"` +} + +func (p *IPPool) String() string { + return fmt.Sprintf("IPPool[Network: %s, Region: %s, Dhcp: %v, Start: %s, End: %s]", p.Network, p.Region, p.Dhcp, p.Start, p.End) +} + +type PublicCloudPrivateNetworksResponse struct { + Id string `json:"id"` + GatewayIp string `json:"gatewayIp"` + Cidr string `json:"cidr"` + IPPools []*IPPool `json:"ipPools"` +} + +func (p *PublicCloudPrivateNetworksResponse) String() string { + return fmt.Sprintf("PCPNSResponse[Id: %s, GatewayIp: %s, Cidr: %s, IPPools: %s]", p.Id, p.GatewayIp, p.Cidr, p.IPPools) +} + +// Opts +type PublicCloudUserCreateOpts struct { + ProjectId string `json:"serviceName"` + Description string `json:"description"` +} + +func (p *PublicCloudUserCreateOpts) String() string { + return fmt.Sprintf("UserOpts[projectId: %s, description:%s]", p.ProjectId, p.Description) +} + +type PublicCloudUserResponse struct { + Id int `json:"id"` + Username string `json:"username"` + Status string `json:"status"` + Description string `json:"description"` + Password string `json:"password"` + CreationDate string `json:"creationDate"` +} + +func (p *PublicCloudUserResponse) String() string { + return fmt.Sprintf("UserResponse[Id: %v, Username: %s, Status: %s, Description: %s, CreationDate: %s]", p.Id, p.Username, p.Status, p.Description, p.CreationDate) +} + +type PublicCloudUserOpenstackRC struct { + Content string `json:"content"` +} + +// Opts +type VRackAttachOpts struct { + Project string `json:"project"` +} + +// Task Opts +type TaskOpts struct { + ServiceName string `json:"serviceName"` + TaskId string `json:"taskId"` +} + +type VRackAttachTaskResponse struct { + Id int `json:"id"` + Function string `json:"function"` + TargetDomain string `json:"targetDomain"` + Status string `json:"status"` + ServiceName string `json:"serviceName"` + OrderId int `json:"orderId"` + LastUpdate time.Time `json:"lastUpdate"` + TodoDate time.Time `json:"TodoDate"` +} + +type PublicCloudRegionResponse struct { + ContinentCode string `json:"continentCode"` + DatacenterLocation string `json:"datacenterLocation"` + Name string `json:"name"` + Services []PublicCloudServiceStatusResponse `json:"services"` +} + +func (r *PublicCloudRegionResponse) String() string { + return fmt.Sprintf("Region: %s, Services: %s", r.Name, r.Services) +} + +type PublicCloudServiceStatusResponse struct { + Status string `json:"status"` + Name string `json:"name"` +} + +func (s *PublicCloudServiceStatusResponse) String() string { + return fmt.Sprintf("%s: %s", s.Name, s.Status) +} diff --git a/builtin/providers/pagerduty/data_source_pagerduty_escalation_policy_test.go b/builtin/providers/pagerduty/data_source_pagerduty_escalation_policy_test.go index 929c72303..cd93e5c71 100644 --- a/builtin/providers/pagerduty/data_source_pagerduty_escalation_policy_test.go +++ b/builtin/providers/pagerduty/data_source_pagerduty_escalation_policy_test.go @@ -10,13 +10,16 @@ import ( ) func TestAccDataSourcePagerDutyEscalationPolicy_Basic(t *testing.T) { - rName := acctest.RandString(5) + username := fmt.Sprintf("tf-%s", acctest.RandString(5)) + email := fmt.Sprintf("%s@foo.com", username) + escalationPolicy := fmt.Sprintf("tf-%s", acctest.RandString(5)) + resource.Test(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, Steps: []resource.TestStep{ - resource.TestStep{ - Config: testAccDataSourcePagerDutyEscalationPolicyConfig(rName), + { + Config: testAccDataSourcePagerDutyEscalationPolicyConfig(username, email, escalationPolicy), Check: resource.ComposeTestCheckFunc( testAccDataSourcePagerDutyEscalationPolicy("pagerduty_escalation_policy.test", "data.pagerduty_escalation_policy.by_name"), ), @@ -50,15 +53,15 @@ func testAccDataSourcePagerDutyEscalationPolicy(src, n string) resource.TestChec } } -func testAccDataSourcePagerDutyEscalationPolicyConfig(rName string) string { +func testAccDataSourcePagerDutyEscalationPolicyConfig(username, email, escalationPolicy string) string { return fmt.Sprintf(` resource "pagerduty_user" "test" { - name = "TF User %[1]s" - email = "tf.%[1]s@example.com" + name = "%s" + email = "%s" } resource "pagerduty_escalation_policy" "test" { - name = "TF Escalation Policy %[1]v" + name = "%s" num_loops = 2 rule { @@ -74,5 +77,5 @@ resource "pagerduty_escalation_policy" "test" { data "pagerduty_escalation_policy" "by_name" { name = "${pagerduty_escalation_policy.test.name}" } -`, rName) +`, username, email, escalationPolicy) } diff --git a/builtin/providers/pagerduty/data_source_pagerduty_schedule_test.go b/builtin/providers/pagerduty/data_source_pagerduty_schedule_test.go index a3a7075f5..93338595a 100644 --- a/builtin/providers/pagerduty/data_source_pagerduty_schedule_test.go +++ b/builtin/providers/pagerduty/data_source_pagerduty_schedule_test.go @@ -10,13 +10,16 @@ import ( ) func TestAccDataSourcePagerDutySchedule_Basic(t *testing.T) { - rName := acctest.RandString(5) + username := fmt.Sprintf("tf-%s", acctest.RandString(5)) + email := fmt.Sprintf("%s@foo.com", username) + schedule := fmt.Sprintf("tf-%s", acctest.RandString(5)) + resource.Test(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, Steps: []resource.TestStep{ - resource.TestStep{ - Config: testAccDataSourcePagerDutyScheduleConfig(rName), + { + Config: testAccDataSourcePagerDutyScheduleConfig(username, email, schedule), Check: resource.ComposeTestCheckFunc( testAccDataSourcePagerDutySchedule("pagerduty_schedule.test", "data.pagerduty_schedule.by_name"), ), @@ -50,15 +53,15 @@ func testAccDataSourcePagerDutySchedule(src, n string) resource.TestCheckFunc { } } -func testAccDataSourcePagerDutyScheduleConfig(rName string) string { +func testAccDataSourcePagerDutyScheduleConfig(username, email, schedule string) string { return fmt.Sprintf(` resource "pagerduty_user" "test" { - name = "TF User %[1]s" - email = "tf.%[1]s@example.com" + name = "%s" + email = "%s" } resource "pagerduty_schedule" "test" { - name = "TF Schedule %[1]s" + name = "%s" time_zone = "America/New_York" @@ -81,5 +84,5 @@ resource "pagerduty_schedule" "test" { data "pagerduty_schedule" "by_name" { name = "${pagerduty_schedule.test.name}" } -`, rName) +`, username, email, schedule) } diff --git a/builtin/providers/pagerduty/data_source_pagerduty_user_test.go b/builtin/providers/pagerduty/data_source_pagerduty_user_test.go index e2ab336f0..2c09d9231 100644 --- a/builtin/providers/pagerduty/data_source_pagerduty_user_test.go +++ b/builtin/providers/pagerduty/data_source_pagerduty_user_test.go @@ -10,13 +10,15 @@ import ( ) func TestAccDataSourcePagerDutyUser_Basic(t *testing.T) { - rName := acctest.RandString(5) + username := fmt.Sprintf("tf-%s", acctest.RandString(5)) + email := fmt.Sprintf("%s@foo.com", username) + resource.Test(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, Steps: []resource.TestStep{ - resource.TestStep{ - Config: testAccDataSourcePagerDutyUserConfig(rName), + { + Config: testAccDataSourcePagerDutyUserConfig(username, email), Check: resource.ComposeTestCheckFunc( testAccDataSourcePagerDutyUser("pagerduty_user.test", "data.pagerduty_user.by_email"), ), @@ -50,15 +52,15 @@ func testAccDataSourcePagerDutyUser(src, n string) resource.TestCheckFunc { } } -func testAccDataSourcePagerDutyUserConfig(rName string) string { +func testAccDataSourcePagerDutyUserConfig(username, email string) string { return fmt.Sprintf(` resource "pagerduty_user" "test" { - name = "TF User %[1]s" - email = "tf.%[1]s@example.com" + name = "%s" + email = "%s" } data "pagerduty_user" "by_email" { email = "${pagerduty_user.test.email}" } -`, rName) +`, username, email) } diff --git a/builtin/providers/pagerduty/import_pagerduty_escalation_policy_test.go b/builtin/providers/pagerduty/import_pagerduty_escalation_policy_test.go index d71e50a19..5feb94fc9 100644 --- a/builtin/providers/pagerduty/import_pagerduty_escalation_policy_test.go +++ b/builtin/providers/pagerduty/import_pagerduty_escalation_policy_test.go @@ -1,25 +1,29 @@ package pagerduty import ( + "fmt" "testing" + "github.com/hashicorp/terraform/helper/acctest" "github.com/hashicorp/terraform/helper/resource" ) func TestAccPagerDutyEscalationPolicy_import(t *testing.T) { - resourceName := "pagerduty_escalation_policy.foo" + username := fmt.Sprintf("tf-%s", acctest.RandString(5)) + email := fmt.Sprintf("%s@foo.com", username) + escalationPolicy := fmt.Sprintf("tf-%s", acctest.RandString(5)) resource.Test(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, CheckDestroy: testAccCheckPagerDutyEscalationPolicyDestroy, Steps: []resource.TestStep{ - resource.TestStep{ - Config: testAccCheckPagerDutyEscalationPolicyConfig, + { + Config: testAccCheckPagerDutyEscalationPolicyConfig(username, email, escalationPolicy), }, - resource.TestStep{ - ResourceName: resourceName, + { + ResourceName: "pagerduty_escalation_policy.foo", ImportState: true, ImportStateVerify: true, }, diff --git a/builtin/providers/pagerduty/import_pagerduty_schedule_test.go b/builtin/providers/pagerduty/import_pagerduty_schedule_test.go index 41e06f7d3..3cc0db866 100644 --- a/builtin/providers/pagerduty/import_pagerduty_schedule_test.go +++ b/builtin/providers/pagerduty/import_pagerduty_schedule_test.go @@ -1,25 +1,29 @@ package pagerduty import ( + "fmt" "testing" + "github.com/hashicorp/terraform/helper/acctest" "github.com/hashicorp/terraform/helper/resource" ) func TestAccPagerDutySchedule_import(t *testing.T) { - resourceName := "pagerduty_schedule.foo" + username := fmt.Sprintf("tf-%s", acctest.RandString(5)) + email := fmt.Sprintf("%s@foo.com", username) + schedule := fmt.Sprintf("tf-%s", acctest.RandString(5)) resource.Test(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, CheckDestroy: testAccCheckPagerDutyUserDestroy, Steps: []resource.TestStep{ - resource.TestStep{ - Config: testAccCheckPagerDutyScheduleConfig, + { + Config: testAccCheckPagerDutyScheduleConfig(username, email, schedule), }, - resource.TestStep{ - ResourceName: resourceName, + { + ResourceName: "pagerduty_schedule.foo", ImportState: true, ImportStateVerify: true, }, diff --git a/builtin/providers/pagerduty/import_pagerduty_service_integration_test.go b/builtin/providers/pagerduty/import_pagerduty_service_integration_test.go index 38c3a060b..9b0ccfdcf 100644 --- a/builtin/providers/pagerduty/import_pagerduty_service_integration_test.go +++ b/builtin/providers/pagerduty/import_pagerduty_service_integration_test.go @@ -1,25 +1,31 @@ package pagerduty import ( + "fmt" "testing" + "github.com/hashicorp/terraform/helper/acctest" "github.com/hashicorp/terraform/helper/resource" ) func TestAccPagerDutyServiceIntegration_import(t *testing.T) { - resourceName := "pagerduty_service_integration.foo" + username := fmt.Sprintf("tf-%s", acctest.RandString(5)) + email := fmt.Sprintf("%s@foo.com", username) + escalationPolicy := fmt.Sprintf("tf-%s", acctest.RandString(5)) + service := fmt.Sprintf("tf-%s", acctest.RandString(5)) + serviceIntegration := fmt.Sprintf("tf-%s", acctest.RandString(5)) resource.Test(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, CheckDestroy: testAccCheckPagerDutyServiceIntegrationDestroy, Steps: []resource.TestStep{ - resource.TestStep{ - Config: testAccCheckPagerDutyServiceIntegrationConfig, + { + Config: testAccCheckPagerDutyServiceIntegrationConfig(username, email, escalationPolicy, service, serviceIntegration), }, - resource.TestStep{ - ResourceName: resourceName, + { + ResourceName: "pagerduty_service_integration.foo", ImportState: true, ImportStateVerify: true, }, diff --git a/builtin/providers/pagerduty/import_pagerduty_service_test.go b/builtin/providers/pagerduty/import_pagerduty_service_test.go index 28259c74b..516411a7f 100644 --- a/builtin/providers/pagerduty/import_pagerduty_service_test.go +++ b/builtin/providers/pagerduty/import_pagerduty_service_test.go @@ -1,25 +1,30 @@ package pagerduty import ( + "fmt" "testing" + "github.com/hashicorp/terraform/helper/acctest" "github.com/hashicorp/terraform/helper/resource" ) func TestAccPagerDutyService_import(t *testing.T) { - resourceName := "pagerduty_service.foo" + username := fmt.Sprintf("tf-%s", acctest.RandString(5)) + email := fmt.Sprintf("%s@foo.com", username) + escalationPolicy := fmt.Sprintf("tf-%s", acctest.RandString(5)) + service := fmt.Sprintf("tf-%s", acctest.RandString(5)) resource.Test(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, CheckDestroy: testAccCheckPagerDutyServiceDestroy, Steps: []resource.TestStep{ - resource.TestStep{ - Config: testAccCheckPagerDutyServiceConfig, + { + Config: testAccCheckPagerDutyServiceConfig(username, email, escalationPolicy, service), }, - resource.TestStep{ - ResourceName: resourceName, + { + ResourceName: "pagerduty_service.foo", ImportState: true, ImportStateVerify: true, }, @@ -28,19 +33,22 @@ func TestAccPagerDutyService_import(t *testing.T) { } func TestAccPagerDutyServiceWithIncidentUrgency_import(t *testing.T) { - resourceName := "pagerduty_service.foo" + username := fmt.Sprintf("tf-%s", acctest.RandString(5)) + email := fmt.Sprintf("%s@foo.com", username) + escalationPolicy := fmt.Sprintf("tf-%s", acctest.RandString(5)) + service := fmt.Sprintf("tf-%s", acctest.RandString(5)) resource.Test(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, CheckDestroy: testAccCheckPagerDutyServiceDestroy, Steps: []resource.TestStep{ - resource.TestStep{ - Config: testAccCheckPagerDutyServiceWithIncidentUrgencyRulesConfig, + { + Config: testAccCheckPagerDutyServiceWithIncidentUrgencyRulesConfig(username, email, escalationPolicy, service), }, - resource.TestStep{ - ResourceName: resourceName, + { + ResourceName: "pagerduty_service.foo", ImportState: true, ImportStateVerify: true, }, diff --git a/builtin/providers/pagerduty/import_pagerduty_team_test.go b/builtin/providers/pagerduty/import_pagerduty_team_test.go index 5017167a3..51a22f91c 100644 --- a/builtin/providers/pagerduty/import_pagerduty_team_test.go +++ b/builtin/providers/pagerduty/import_pagerduty_team_test.go @@ -1,25 +1,27 @@ package pagerduty import ( + "fmt" "testing" + "github.com/hashicorp/terraform/helper/acctest" "github.com/hashicorp/terraform/helper/resource" ) func TestAccPagerDutyTeam_import(t *testing.T) { - resourceName := "pagerduty_team.foo" + team := fmt.Sprintf("tf-%s", acctest.RandString(5)) resource.Test(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, CheckDestroy: testAccCheckPagerDutyTeamDestroy, Steps: []resource.TestStep{ - resource.TestStep{ - Config: testAccCheckPagerDutyTeamConfig, + { + Config: testAccCheckPagerDutyTeamConfig(team), }, - resource.TestStep{ - ResourceName: resourceName, + { + ResourceName: "pagerduty_team.foo", ImportState: true, ImportStateVerify: true, }, diff --git a/builtin/providers/pagerduty/import_pagerduty_user_test.go b/builtin/providers/pagerduty/import_pagerduty_user_test.go index 82d7cc99b..6f130401a 100644 --- a/builtin/providers/pagerduty/import_pagerduty_user_test.go +++ b/builtin/providers/pagerduty/import_pagerduty_user_test.go @@ -1,25 +1,28 @@ package pagerduty import ( + "fmt" "testing" + "github.com/hashicorp/terraform/helper/acctest" "github.com/hashicorp/terraform/helper/resource" ) func TestAccPagerDutyUser_import(t *testing.T) { - resourceName := "pagerduty_user.foo" + username := fmt.Sprintf("tf-%s", acctest.RandString(5)) + email := fmt.Sprintf("%s@foo.com", username) resource.Test(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, CheckDestroy: testAccCheckPagerDutyUserDestroy, Steps: []resource.TestStep{ - resource.TestStep{ - Config: testAccCheckPagerDutyUserConfig, + { + Config: testAccCheckPagerDutyUserConfig(username, email), }, - resource.TestStep{ - ResourceName: resourceName, + { + ResourceName: "pagerduty_user.foo", ImportState: true, ImportStateVerify: true, }, diff --git a/builtin/providers/pagerduty/provider_test.go b/builtin/providers/pagerduty/provider_test.go index b72ccae69..906c4e5c8 100644 --- a/builtin/providers/pagerduty/provider_test.go +++ b/builtin/providers/pagerduty/provider_test.go @@ -29,6 +29,10 @@ func TestProviderImpl(t *testing.T) { } func testAccPreCheck(t *testing.T) { + if v := os.Getenv("PAGERDUTY_PARALLEL"); v != "" { + t.Parallel() + } + if v := os.Getenv("PAGERDUTY_TOKEN"); v == "" { t.Fatal("PAGERDUTY_TOKEN must be set for acceptance tests") } diff --git a/builtin/providers/pagerduty/resource_pagerduty_addon_test.go b/builtin/providers/pagerduty/resource_pagerduty_addon_test.go index c6cee5dcb..639153b1e 100644 --- a/builtin/providers/pagerduty/resource_pagerduty_addon_test.go +++ b/builtin/providers/pagerduty/resource_pagerduty_addon_test.go @@ -5,32 +5,36 @@ import ( "testing" "github.com/PagerDuty/go-pagerduty" + "github.com/hashicorp/terraform/helper/acctest" "github.com/hashicorp/terraform/helper/resource" "github.com/hashicorp/terraform/terraform" ) func TestAccPagerDutyAddon_Basic(t *testing.T) { + addon := fmt.Sprintf("tf-%s", acctest.RandString(5)) + addonUpdated := fmt.Sprintf("tf-%s", acctest.RandString(5)) + resource.Test(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, CheckDestroy: testAccCheckPagerDutyAddonDestroy, Steps: []resource.TestStep{ - resource.TestStep{ - Config: testAccCheckPagerDutyAddonConfig, + { + Config: testAccCheckPagerDutyAddonConfig(addon), Check: resource.ComposeTestCheckFunc( testAccCheckPagerDutyAddonExists("pagerduty_addon.foo"), resource.TestCheckResourceAttr( - "pagerduty_addon.foo", "name", "Foo status page"), + "pagerduty_addon.foo", "name", addon), resource.TestCheckResourceAttr( "pagerduty_addon.foo", "src", "https://intranet.foo.com/status"), ), }, - resource.TestStep{ - Config: testAccCheckPagerDutyAddonConfigUpdated, + { + Config: testAccCheckPagerDutyAddonConfigUpdated(addonUpdated), Check: resource.ComposeTestCheckFunc( testAccCheckPagerDutyAddonExists("pagerduty_addon.foo"), resource.TestCheckResourceAttr( - "pagerduty_addon.foo", "name", "Bar status page"), + "pagerduty_addon.foo", "name", addonUpdated), resource.TestCheckResourceAttr( "pagerduty_addon.foo", "src", "https://intranet.bar.com/status"), ), @@ -80,16 +84,20 @@ func testAccCheckPagerDutyAddonExists(n string) resource.TestCheckFunc { } } -const testAccCheckPagerDutyAddonConfig = ` +func testAccCheckPagerDutyAddonConfig(addon string) string { + return fmt.Sprintf(` resource "pagerduty_addon" "foo" { - name = "Foo status page" + name = "%s" src = "https://intranet.foo.com/status" } -` +`, addon) +} -const testAccCheckPagerDutyAddonConfigUpdated = ` +func testAccCheckPagerDutyAddonConfigUpdated(addon string) string { + return fmt.Sprintf(` resource "pagerduty_addon" "foo" { - name = "Bar status page" + name = "%s" src = "https://intranet.bar.com/status" } -` +`, addon) +} diff --git a/builtin/providers/pagerduty/resource_pagerduty_escalation_policy_test.go b/builtin/providers/pagerduty/resource_pagerduty_escalation_policy_test.go index 2ca484105..c70d95809 100644 --- a/builtin/providers/pagerduty/resource_pagerduty_escalation_policy_test.go +++ b/builtin/providers/pagerduty/resource_pagerduty_escalation_policy_test.go @@ -5,22 +5,28 @@ import ( "testing" "github.com/PagerDuty/go-pagerduty" + "github.com/hashicorp/terraform/helper/acctest" "github.com/hashicorp/terraform/helper/resource" "github.com/hashicorp/terraform/terraform" ) func TestAccPagerDutyEscalationPolicy_Basic(t *testing.T) { + username := fmt.Sprintf("tf-%s", acctest.RandString(5)) + email := fmt.Sprintf("%s@foo.com", username) + escalationPolicy := fmt.Sprintf("tf-%s", acctest.RandString(5)) + escalationPolicyUpdated := fmt.Sprintf("tf-%s", acctest.RandString(5)) + resource.Test(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, CheckDestroy: testAccCheckPagerDutyEscalationPolicyDestroy, Steps: []resource.TestStep{ - resource.TestStep{ - Config: testAccCheckPagerDutyEscalationPolicyConfig, + { + Config: testAccCheckPagerDutyEscalationPolicyConfig(username, email, escalationPolicy), Check: resource.ComposeTestCheckFunc( testAccCheckPagerDutyEscalationPolicyExists("pagerduty_escalation_policy.foo"), resource.TestCheckResourceAttr( - "pagerduty_escalation_policy.foo", "name", "foo"), + "pagerduty_escalation_policy.foo", "name", escalationPolicy), resource.TestCheckResourceAttr( "pagerduty_escalation_policy.foo", "description", "foo"), resource.TestCheckResourceAttr( @@ -31,12 +37,13 @@ func TestAccPagerDutyEscalationPolicy_Basic(t *testing.T) { "pagerduty_escalation_policy.foo", "rule.0.escalation_delay_in_minutes", "10"), ), }, - resource.TestStep{ - Config: testAccCheckPagerDutyEscalationPolicyConfigUpdated, + + { + Config: testAccCheckPagerDutyEscalationPolicyConfigUpdated(username, email, escalationPolicyUpdated), Check: resource.ComposeTestCheckFunc( testAccCheckPagerDutyEscalationPolicyExists("pagerduty_escalation_policy.foo"), resource.TestCheckResourceAttr( - "pagerduty_escalation_policy.foo", "name", "bar"), + "pagerduty_escalation_policy.foo", "name", escalationPolicyUpdated), resource.TestCheckResourceAttr( "pagerduty_escalation_policy.foo", "description", "bar"), resource.TestCheckResourceAttr( @@ -54,17 +61,23 @@ func TestAccPagerDutyEscalationPolicy_Basic(t *testing.T) { } func TestAccPagerDutyEscalationPolicyWithTeams_Basic(t *testing.T) { + username := fmt.Sprintf("tf-%s", acctest.RandString(5)) + email := fmt.Sprintf("%s@foo.com", username) + team := fmt.Sprintf("tf-%s", acctest.RandString(5)) + escalationPolicy := fmt.Sprintf("tf-%s", acctest.RandString(5)) + escalationPolicyUpdated := fmt.Sprintf("tf-%s", acctest.RandString(5)) + resource.Test(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, CheckDestroy: testAccCheckPagerDutyEscalationPolicyDestroy, Steps: []resource.TestStep{ - resource.TestStep{ - Config: testAccCheckPagerDutyEscalationPolicyWithTeamsConfig, + { + Config: testAccCheckPagerDutyEscalationPolicyWithTeamsConfig(username, email, team, escalationPolicy), Check: resource.ComposeTestCheckFunc( testAccCheckPagerDutyEscalationPolicyExists("pagerduty_escalation_policy.foo"), resource.TestCheckResourceAttr( - "pagerduty_escalation_policy.foo", "name", "foo"), + "pagerduty_escalation_policy.foo", "name", escalationPolicy), resource.TestCheckResourceAttr( "pagerduty_escalation_policy.foo", "description", "foo"), resource.TestCheckResourceAttr( @@ -77,12 +90,12 @@ func TestAccPagerDutyEscalationPolicyWithTeams_Basic(t *testing.T) { "pagerduty_escalation_policy.foo", "teams.#", "1"), ), }, - resource.TestStep{ - Config: testAccCheckPagerDutyEscalationPolicyWithTeamsConfigUpdated, + { + Config: testAccCheckPagerDutyEscalationPolicyWithTeamsConfigUpdated(username, email, team, escalationPolicyUpdated), Check: resource.ComposeTestCheckFunc( testAccCheckPagerDutyEscalationPolicyExists("pagerduty_escalation_policy.foo"), resource.TestCheckResourceAttr( - "pagerduty_escalation_policy.foo", "name", "bar"), + "pagerduty_escalation_policy.foo", "name", escalationPolicyUpdated), resource.TestCheckResourceAttr( "pagerduty_escalation_policy.foo", "description", "bar"), resource.TestCheckResourceAttr( @@ -143,10 +156,11 @@ func testAccCheckPagerDutyEscalationPolicyExists(n string) resource.TestCheckFun } } -const testAccCheckPagerDutyEscalationPolicyConfig = ` +func testAccCheckPagerDutyEscalationPolicyConfig(name, email, escalationPolicy string) string { + return fmt.Sprintf(` resource "pagerduty_user" "foo" { - name = "foo" - email = "foo@bar.com" + name = "%s" + email = "%s" color = "green" role = "user" job_title = "foo" @@ -154,7 +168,7 @@ resource "pagerduty_user" "foo" { } resource "pagerduty_escalation_policy" "foo" { - name = "foo" + name = "%s" description = "foo" num_loops = 1 @@ -167,12 +181,14 @@ resource "pagerduty_escalation_policy" "foo" { } } } -` +`, name, email, escalationPolicy) +} -const testAccCheckPagerDutyEscalationPolicyConfigUpdated = ` +func testAccCheckPagerDutyEscalationPolicyConfigUpdated(name, email, escalationPolicy string) string { + return fmt.Sprintf(` resource "pagerduty_user" "foo" { - name = "foo" - email = "foo@bar.com" + name = "%s" + email = "%s" color = "green" role = "user" job_title = "foo" @@ -180,7 +196,7 @@ resource "pagerduty_user" "foo" { } resource "pagerduty_escalation_policy" "foo" { - name = "bar" + name = "%s" description = "bar" num_loops = 2 @@ -202,12 +218,14 @@ resource "pagerduty_escalation_policy" "foo" { } } } -` +`, name, email, escalationPolicy) +} -const testAccCheckPagerDutyEscalationPolicyWithTeamsConfig = ` +func testAccCheckPagerDutyEscalationPolicyWithTeamsConfig(name, email, team, escalationPolicy string) string { + return fmt.Sprintf(` resource "pagerduty_user" "foo" { - name = "foo" - email = "foo@bar.com" + name = "%s" + email = "%s" color = "green" role = "user" job_title = "foo" @@ -215,12 +233,12 @@ resource "pagerduty_user" "foo" { } resource "pagerduty_team" "foo" { - name = "foo" + name = "%s" description = "foo" } resource "pagerduty_escalation_policy" "foo" { - name = "foo" + name = "%s" description = "foo" num_loops = 1 teams = ["${pagerduty_team.foo.id}"] @@ -234,12 +252,14 @@ resource "pagerduty_escalation_policy" "foo" { } } } -` +`, name, email, team, escalationPolicy) +} -const testAccCheckPagerDutyEscalationPolicyWithTeamsConfigUpdated = ` +func testAccCheckPagerDutyEscalationPolicyWithTeamsConfigUpdated(name, email, team, escalationPolicy string) string { + return fmt.Sprintf(` resource "pagerduty_user" "foo" { - name = "foo" - email = "foo@bar.com" + name = "%s" + email = "%s" color = "green" role = "user" job_title = "foo" @@ -247,12 +267,12 @@ resource "pagerduty_user" "foo" { } resource "pagerduty_team" "foo" { - name = "foo" + name = "%s" description = "foo" } resource "pagerduty_escalation_policy" "foo" { - name = "bar" + name = "%s" description = "bar" num_loops = 2 @@ -274,4 +294,5 @@ resource "pagerduty_escalation_policy" "foo" { } } } -` +`, name, email, team, escalationPolicy) +} diff --git a/builtin/providers/pagerduty/resource_pagerduty_schedule_test.go b/builtin/providers/pagerduty/resource_pagerduty_schedule_test.go index a4989efcd..09eb9f604 100644 --- a/builtin/providers/pagerduty/resource_pagerduty_schedule_test.go +++ b/builtin/providers/pagerduty/resource_pagerduty_schedule_test.go @@ -5,22 +5,28 @@ import ( "testing" "github.com/PagerDuty/go-pagerduty" + "github.com/hashicorp/terraform/helper/acctest" "github.com/hashicorp/terraform/helper/resource" "github.com/hashicorp/terraform/terraform" ) func TestAccPagerDutySchedule_Basic(t *testing.T) { + username := fmt.Sprintf("tf-%s", acctest.RandString(5)) + email := fmt.Sprintf("%s@foo.com", username) + schedule := fmt.Sprintf("tf-%s", acctest.RandString(5)) + scheduleUpdated := fmt.Sprintf("tf-%s", acctest.RandString(5)) + resource.Test(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, CheckDestroy: testAccCheckPagerDutyScheduleDestroy, Steps: []resource.TestStep{ - resource.TestStep{ - Config: testAccCheckPagerDutyScheduleConfig, + { + Config: testAccCheckPagerDutyScheduleConfig(username, email, schedule), Check: resource.ComposeTestCheckFunc( testAccCheckPagerDutyScheduleExists("pagerduty_schedule.foo"), resource.TestCheckResourceAttr( - "pagerduty_schedule.foo", "name", "foo"), + "pagerduty_schedule.foo", "name", schedule), resource.TestCheckResourceAttr( "pagerduty_schedule.foo", "description", "foo"), resource.TestCheckResourceAttr( @@ -31,12 +37,12 @@ func TestAccPagerDutySchedule_Basic(t *testing.T) { "pagerduty_schedule.foo", "layer.0.name", "foo"), ), }, - resource.TestStep{ - Config: testAccCheckPagerDutyScheduleConfigUpdated, + { + Config: testAccCheckPagerDutyScheduleConfigUpdated(username, email, scheduleUpdated), Check: resource.ComposeTestCheckFunc( testAccCheckPagerDutyScheduleExists("pagerduty_schedule.foo"), resource.TestCheckResourceAttr( - "pagerduty_schedule.foo", "name", "bar"), + "pagerduty_schedule.foo", "name", scheduleUpdated), resource.TestCheckResourceAttr( "pagerduty_schedule.foo", "description", "Managed by Terraform"), resource.TestCheckResourceAttr( @@ -52,17 +58,22 @@ func TestAccPagerDutySchedule_Basic(t *testing.T) { } func TestAccPagerDutySchedule_BasicWeek(t *testing.T) { + username := fmt.Sprintf("tf-%s", acctest.RandString(5)) + email := fmt.Sprintf("%s@foo.com", username) + schedule := fmt.Sprintf("tf-%s", acctest.RandString(5)) + scheduleUpdated := fmt.Sprintf("tf-%s", acctest.RandString(5)) + resource.Test(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, CheckDestroy: testAccCheckPagerDutyScheduleDestroy, Steps: []resource.TestStep{ - resource.TestStep{ - Config: testAccCheckPagerDutyScheduleConfigWeek, + { + Config: testAccCheckPagerDutyScheduleConfigWeek(username, email, schedule), Check: resource.ComposeTestCheckFunc( testAccCheckPagerDutyScheduleExists("pagerduty_schedule.foo"), resource.TestCheckResourceAttr( - "pagerduty_schedule.foo", "name", "foo"), + "pagerduty_schedule.foo", "name", schedule), resource.TestCheckResourceAttr( "pagerduty_schedule.foo", "description", "foo"), resource.TestCheckResourceAttr( @@ -75,12 +86,12 @@ func TestAccPagerDutySchedule_BasicWeek(t *testing.T) { "pagerduty_schedule.foo", "layer.0.restriction.0.start_day_of_week", "1"), ), }, - resource.TestStep{ - Config: testAccCheckPagerDutyScheduleConfigWeekUpdated, + { + Config: testAccCheckPagerDutyScheduleConfigWeekUpdated(username, email, scheduleUpdated), Check: resource.ComposeTestCheckFunc( testAccCheckPagerDutyScheduleExists("pagerduty_schedule.foo"), resource.TestCheckResourceAttr( - "pagerduty_schedule.foo", "name", "bar"), + "pagerduty_schedule.foo", "name", scheduleUpdated), resource.TestCheckResourceAttr( "pagerduty_schedule.foo", "description", "Managed by Terraform"), resource.TestCheckResourceAttr( @@ -98,17 +109,21 @@ func TestAccPagerDutySchedule_BasicWeek(t *testing.T) { } func TestAccPagerDutySchedule_Multi(t *testing.T) { + username := fmt.Sprintf("tf-%s", acctest.RandString(5)) + email := fmt.Sprintf("%s@foo.com", username) + schedule := fmt.Sprintf("tf-%s", acctest.RandString(5)) + resource.Test(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, CheckDestroy: testAccCheckPagerDutyScheduleDestroy, Steps: []resource.TestStep{ - resource.TestStep{ - Config: testAccCheckPagerDutyScheduleConfigMulti, + { + Config: testAccCheckPagerDutyScheduleConfigMulti(username, email, schedule), Check: resource.ComposeTestCheckFunc( testAccCheckPagerDutyScheduleExists("pagerduty_schedule.foo"), resource.TestCheckResourceAttr( - "pagerduty_schedule.foo", "name", "foo"), + "pagerduty_schedule.foo", "name", schedule), resource.TestCheckResourceAttr( "pagerduty_schedule.foo", "description", "foo"), resource.TestCheckResourceAttr( @@ -215,14 +230,15 @@ func testAccCheckPagerDutyScheduleExists(n string) resource.TestCheckFunc { } } -const testAccCheckPagerDutyScheduleConfig = ` +func testAccCheckPagerDutyScheduleConfig(username, email, schedule string) string { + return fmt.Sprintf(` resource "pagerduty_user" "foo" { - name = "foo" - email = "foo@bar.com" + name = "%s" + email = "%s" } resource "pagerduty_schedule" "foo" { - name = "foo" + name = "%s" time_zone = "Europe/Berlin" description = "foo" @@ -241,16 +257,18 @@ resource "pagerduty_schedule" "foo" { } } } -` +`, username, email, schedule) +} -const testAccCheckPagerDutyScheduleConfigUpdated = ` +func testAccCheckPagerDutyScheduleConfigUpdated(username, email, schedule string) string { + return fmt.Sprintf(` resource "pagerduty_user" "foo" { - name = "foo" - email = "foo@bar.com" + name = "%s" + email = "%s" } resource "pagerduty_schedule" "foo" { - name = "bar" + name = "%s" time_zone = "America/New_York" @@ -268,16 +286,18 @@ resource "pagerduty_schedule" "foo" { } } } -` +`, username, email, schedule) +} -const testAccCheckPagerDutyScheduleConfigWeek = ` +func testAccCheckPagerDutyScheduleConfigWeek(username, email, schedule string) string { + return fmt.Sprintf(` resource "pagerduty_user" "foo" { - name = "foo" - email = "foo@bar.com" + name = "%s" + email = "%s" } resource "pagerduty_schedule" "foo" { - name = "foo" + name = "%s" time_zone = "Europe/Berlin" description = "foo" @@ -297,16 +317,18 @@ resource "pagerduty_schedule" "foo" { } } } -` +`, username, email, schedule) +} -const testAccCheckPagerDutyScheduleConfigWeekUpdated = ` +func testAccCheckPagerDutyScheduleConfigWeekUpdated(username, email, schedule string) string { + return fmt.Sprintf(` resource "pagerduty_user" "foo" { - name = "foo" - email = "foo@bar.com" + name = "%s" + email = "%s" } resource "pagerduty_schedule" "foo" { - name = "bar" + name = "%s" time_zone = "America/New_York" @@ -325,16 +347,18 @@ resource "pagerduty_schedule" "foo" { } } } -` +`, username, email, schedule) +} -const testAccCheckPagerDutyScheduleConfigMulti = ` +func testAccCheckPagerDutyScheduleConfigMulti(username, email, schedule string) string { + return fmt.Sprintf(` resource "pagerduty_user" "foo" { - name = "foo" - email = "foo@bar.com" + name = "%s" + email = "%s" } resource "pagerduty_schedule" "foo" { - name = "foo" + name = "%s" time_zone = "America/New_York" description = "foo" @@ -383,4 +407,5 @@ resource "pagerduty_schedule" "foo" { } } } -` +`, username, email, schedule) +} diff --git a/builtin/providers/pagerduty/resource_pagerduty_service_integration_test.go b/builtin/providers/pagerduty/resource_pagerduty_service_integration_test.go index eb58dd480..0aa451fc4 100644 --- a/builtin/providers/pagerduty/resource_pagerduty_service_integration_test.go +++ b/builtin/providers/pagerduty/resource_pagerduty_service_integration_test.go @@ -5,34 +5,42 @@ import ( "testing" "github.com/PagerDuty/go-pagerduty" + "github.com/hashicorp/terraform/helper/acctest" "github.com/hashicorp/terraform/helper/resource" "github.com/hashicorp/terraform/terraform" ) func TestAccPagerDutyServiceIntegration_Basic(t *testing.T) { + username := fmt.Sprintf("tf-%s", acctest.RandString(5)) + email := fmt.Sprintf("%s@foo.com", username) + escalationPolicy := fmt.Sprintf("tf-%s", acctest.RandString(5)) + service := fmt.Sprintf("tf-%s", acctest.RandString(5)) + serviceIntegration := fmt.Sprintf("tf-%s", acctest.RandString(5)) + serviceIntegrationUpdated := fmt.Sprintf("tf-%s", acctest.RandString(5)) + resource.Test(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, CheckDestroy: testAccCheckPagerDutyServiceIntegrationDestroy, Steps: []resource.TestStep{ - resource.TestStep{ - Config: testAccCheckPagerDutyServiceIntegrationConfig, + { + Config: testAccCheckPagerDutyServiceIntegrationConfig(username, email, escalationPolicy, service, serviceIntegration), Check: resource.ComposeTestCheckFunc( testAccCheckPagerDutyServiceIntegrationExists("pagerduty_service_integration.foo"), resource.TestCheckResourceAttr( - "pagerduty_service_integration.foo", "name", "foo"), + "pagerduty_service_integration.foo", "name", serviceIntegration), resource.TestCheckResourceAttr( "pagerduty_service_integration.foo", "type", "generic_events_api_inbound_integration"), resource.TestCheckResourceAttr( "pagerduty_service_integration.foo", "vendor", "PAM4FGS"), ), }, - resource.TestStep{ - Config: testAccCheckPagerDutyServiceIntegrationConfigUpdated, + { + Config: testAccCheckPagerDutyServiceIntegrationConfigUpdated(username, email, escalationPolicy, service, serviceIntegrationUpdated), Check: resource.ComposeTestCheckFunc( testAccCheckPagerDutyServiceIntegrationExists("pagerduty_service_integration.foo"), resource.TestCheckResourceAttr( - "pagerduty_service_integration.foo", "name", "bar"), + "pagerduty_service_integration.foo", "name", serviceIntegrationUpdated), resource.TestCheckResourceAttr( "pagerduty_service_integration.foo", "type", "generic_events_api_inbound_integration"), resource.TestCheckResourceAttr( @@ -44,27 +52,34 @@ func TestAccPagerDutyServiceIntegration_Basic(t *testing.T) { } func TestAccPagerDutyServiceIntegrationGeneric_Basic(t *testing.T) { + username := fmt.Sprintf("tf-%s", acctest.RandString(5)) + email := fmt.Sprintf("%s@foo.com", username) + escalationPolicy := fmt.Sprintf("tf-%s", acctest.RandString(5)) + service := fmt.Sprintf("tf-%s", acctest.RandString(5)) + serviceIntegration := fmt.Sprintf("tf-%s", acctest.RandString(5)) + serviceIntegrationUpdated := fmt.Sprintf("tf-%s", acctest.RandString(5)) + resource.Test(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, CheckDestroy: testAccCheckPagerDutyServiceIntegrationDestroy, Steps: []resource.TestStep{ - resource.TestStep{ - Config: testAccCheckPagerDutyServiceIntegrationGenericConfig, + { + Config: testAccCheckPagerDutyServiceIntegrationGenericConfig(username, email, escalationPolicy, service, serviceIntegration), Check: resource.ComposeTestCheckFunc( testAccCheckPagerDutyServiceIntegrationExists("pagerduty_service_integration.foo"), resource.TestCheckResourceAttr( - "pagerduty_service_integration.foo", "name", "foo"), + "pagerduty_service_integration.foo", "name", serviceIntegration), resource.TestCheckResourceAttr( "pagerduty_service_integration.foo", "type", "generic_events_api_inbound_integration"), ), }, - resource.TestStep{ - Config: testAccCheckPagerDutyServiceIntegrationGenericConfigUpdated, + { + Config: testAccCheckPagerDutyServiceIntegrationGenericConfigUpdated(username, email, escalationPolicy, service, serviceIntegrationUpdated), Check: resource.ComposeTestCheckFunc( testAccCheckPagerDutyServiceIntegrationExists("pagerduty_service_integration.foo"), resource.TestCheckResourceAttr( - "pagerduty_service_integration.foo", "name", "bar"), + "pagerduty_service_integration.foo", "name", serviceIntegrationUpdated), resource.TestCheckResourceAttr( "pagerduty_service_integration.foo", "type", "generic_events_api_inbound_integration"), ), @@ -120,14 +135,15 @@ func testAccCheckPagerDutyServiceIntegrationExists(n string) resource.TestCheckF } } -const testAccCheckPagerDutyServiceIntegrationConfig = ` +func testAccCheckPagerDutyServiceIntegrationConfig(username, email, escalationPolicy, service, serviceIntegration string) string { + return fmt.Sprintf(` resource "pagerduty_user" "foo" { - name = "foo" - email = "foo@bar.com" + name = "%s" + email = "%s" } resource "pagerduty_escalation_policy" "foo" { - name = "foo" + name = "%s" description = "foo" num_loops = 1 @@ -142,7 +158,7 @@ resource "pagerduty_escalation_policy" "foo" { } resource "pagerduty_service" "foo" { - name = "foo" + name = "%s" description = "foo" auto_resolve_timeout = 1800 acknowledgement_timeout = 1800 @@ -159,16 +175,18 @@ data "pagerduty_vendor" "datadog" { } resource "pagerduty_service_integration" "foo" { - name = "foo" + name = "%s" service = "${pagerduty_service.foo.id}" vendor = "${data.pagerduty_vendor.datadog.id}" } -` +`, username, email, escalationPolicy, service, serviceIntegration) +} -const testAccCheckPagerDutyServiceIntegrationConfigUpdated = ` +func testAccCheckPagerDutyServiceIntegrationConfigUpdated(username, email, escalationPolicy, service, serviceIntegration string) string { + return fmt.Sprintf(` resource "pagerduty_user" "foo" { - name = "foo" - email = "foo@bar.com" + name = "%s" + email = "%s" color = "green" role = "user" job_title = "foo" @@ -176,7 +194,7 @@ resource "pagerduty_user" "foo" { } resource "pagerduty_escalation_policy" "foo" { - name = "bar" + name = "%s" description = "bar" num_loops = 2 @@ -191,7 +209,7 @@ resource "pagerduty_escalation_policy" "foo" { } resource "pagerduty_service" "foo" { - name = "bar" + name = "%s" description = "bar" auto_resolve_timeout = 3600 acknowledgement_timeout = 3600 @@ -208,20 +226,22 @@ data "pagerduty_vendor" "datadog" { } resource "pagerduty_service_integration" "foo" { - name = "bar" + name = "%s" service = "${pagerduty_service.foo.id}" vendor = "${data.pagerduty_vendor.datadog.id}" } -` +`, username, email, escalationPolicy, service, serviceIntegration) +} -const testAccCheckPagerDutyServiceIntegrationGenericConfig = ` +func testAccCheckPagerDutyServiceIntegrationGenericConfig(username, email, escalationPolicy, service, serviceIntegration string) string { + return fmt.Sprintf(` resource "pagerduty_user" "foo" { - name = "foo" - email = "foo@bar.com" + name = "%s" + email = "%s" } resource "pagerduty_escalation_policy" "foo" { - name = "foo" + name = "%s" description = "foo" num_loops = 1 @@ -236,7 +256,7 @@ resource "pagerduty_escalation_policy" "foo" { } resource "pagerduty_service" "foo" { - name = "foo" + name = "%s" description = "foo" auto_resolve_timeout = 1800 acknowledgement_timeout = 1800 @@ -249,16 +269,18 @@ resource "pagerduty_service" "foo" { } resource "pagerduty_service_integration" "foo" { - name = "foo" + name = "%s" service = "${pagerduty_service.foo.id}" type = "generic_events_api_inbound_integration" } -` +`, username, email, escalationPolicy, service, serviceIntegration) +} -const testAccCheckPagerDutyServiceIntegrationGenericConfigUpdated = ` +func testAccCheckPagerDutyServiceIntegrationGenericConfigUpdated(username, email, escalationPolicy, service, serviceIntegration string) string { + return fmt.Sprintf(` resource "pagerduty_user" "foo" { - name = "foo" - email = "foo@bar.com" + name = "%s" + email = "%s" color = "green" role = "user" job_title = "foo" @@ -266,7 +288,7 @@ resource "pagerduty_user" "foo" { } resource "pagerduty_escalation_policy" "foo" { - name = "bar" + name = "%s" description = "bar" num_loops = 2 @@ -281,7 +303,7 @@ resource "pagerduty_escalation_policy" "foo" { } resource "pagerduty_service" "foo" { - name = "bar" + name = "%s" description = "bar" auto_resolve_timeout = 3600 acknowledgement_timeout = 3600 @@ -294,8 +316,9 @@ resource "pagerduty_service" "foo" { } resource "pagerduty_service_integration" "foo" { - name = "bar" + name = "%s" service = "${pagerduty_service.foo.id}" type = "generic_events_api_inbound_integration" } -` +`, username, email, escalationPolicy, service, serviceIntegration) +} diff --git a/builtin/providers/pagerduty/resource_pagerduty_service_test.go b/builtin/providers/pagerduty/resource_pagerduty_service_test.go index afd2c59c1..b169b1b0f 100644 --- a/builtin/providers/pagerduty/resource_pagerduty_service_test.go +++ b/builtin/providers/pagerduty/resource_pagerduty_service_test.go @@ -5,22 +5,29 @@ import ( "testing" "github.com/PagerDuty/go-pagerduty" + "github.com/hashicorp/terraform/helper/acctest" "github.com/hashicorp/terraform/helper/resource" "github.com/hashicorp/terraform/terraform" ) func TestAccPagerDutyService_Basic(t *testing.T) { + username := fmt.Sprintf("tf-%s", acctest.RandString(5)) + email := fmt.Sprintf("%s@foo.com", username) + escalationPolicy := fmt.Sprintf("tf-%s", acctest.RandString(5)) + service := fmt.Sprintf("tf-%s", acctest.RandString(5)) + serviceUpdated := fmt.Sprintf("tf-%s", acctest.RandString(5)) + resource.Test(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, CheckDestroy: testAccCheckPagerDutyServiceDestroy, Steps: []resource.TestStep{ - resource.TestStep{ - Config: testAccCheckPagerDutyServiceConfig, + { + Config: testAccCheckPagerDutyServiceConfig(username, email, escalationPolicy, service), Check: resource.ComposeTestCheckFunc( testAccCheckPagerDutyServiceExists("pagerduty_service.foo"), resource.TestCheckResourceAttr( - "pagerduty_service.foo", "name", "foo"), + "pagerduty_service.foo", "name", service), resource.TestCheckResourceAttr( "pagerduty_service.foo", "description", "foo"), resource.TestCheckResourceAttr( @@ -35,12 +42,12 @@ func TestAccPagerDutyService_Basic(t *testing.T) { "pagerduty_service.foo", "incident_urgency_rule.0.type", "constant"), ), }, - resource.TestStep{ - Config: testAccCheckPagerDutyServiceConfigUpdated, + { + Config: testAccCheckPagerDutyServiceConfigUpdated(username, email, escalationPolicy, serviceUpdated), Check: resource.ComposeTestCheckFunc( testAccCheckPagerDutyServiceExists("pagerduty_service.foo"), resource.TestCheckResourceAttr( - "pagerduty_service.foo", "name", "bar"), + "pagerduty_service.foo", "name", serviceUpdated), resource.TestCheckResourceAttr( "pagerduty_service.foo", "description", "bar"), resource.TestCheckResourceAttr( @@ -60,17 +67,23 @@ func TestAccPagerDutyService_Basic(t *testing.T) { } func TestAccPagerDutyService_BasicWithIncidentUrgencyRules(t *testing.T) { + username := fmt.Sprintf("tf-%s", acctest.RandString(5)) + email := fmt.Sprintf("%s@foo.com", username) + escalationPolicy := fmt.Sprintf("tf-%s", acctest.RandString(5)) + service := fmt.Sprintf("tf-%s", acctest.RandString(5)) + serviceUpdated := fmt.Sprintf("tf-%s", acctest.RandString(5)) + resource.Test(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, CheckDestroy: testAccCheckPagerDutyServiceDestroy, Steps: []resource.TestStep{ - resource.TestStep{ - Config: testAccCheckPagerDutyServiceWithIncidentUrgencyRulesConfig, + { + Config: testAccCheckPagerDutyServiceWithIncidentUrgencyRulesConfig(username, email, escalationPolicy, service), Check: resource.ComposeTestCheckFunc( testAccCheckPagerDutyServiceExists("pagerduty_service.foo"), resource.TestCheckResourceAttr( - "pagerduty_service.foo", "name", "foo"), + "pagerduty_service.foo", "name", service), resource.TestCheckResourceAttr( "pagerduty_service.foo", "description", "foo"), resource.TestCheckResourceAttr( @@ -127,12 +140,12 @@ func TestAccPagerDutyService_BasicWithIncidentUrgencyRules(t *testing.T) { "pagerduty_service.foo", "support_hours.0.type", "fixed_time_per_day"), ), }, - resource.TestStep{ - Config: testAccCheckPagerDutyServiceWithIncidentUrgencyRulesConfigUpdated, + { + Config: testAccCheckPagerDutyServiceWithIncidentUrgencyRulesConfigUpdated(username, email, escalationPolicy, serviceUpdated), Check: resource.ComposeTestCheckFunc( testAccCheckPagerDutyServiceExists("pagerduty_service.foo"), resource.TestCheckResourceAttr( - "pagerduty_service.foo", "name", "bar"), + "pagerduty_service.foo", "name", serviceUpdated), resource.TestCheckResourceAttr( "pagerduty_service.foo", "description", "bar bar bar"), resource.TestCheckResourceAttr( @@ -194,17 +207,23 @@ func TestAccPagerDutyService_BasicWithIncidentUrgencyRules(t *testing.T) { } func TestAccPagerDutyService_FromBasicToCustomIncidentUrgencyRules(t *testing.T) { + username := fmt.Sprintf("tf-%s", acctest.RandString(5)) + email := fmt.Sprintf("%s@foo.com", username) + escalationPolicy := fmt.Sprintf("tf-%s", acctest.RandString(5)) + service := fmt.Sprintf("tf-%s", acctest.RandString(5)) + serviceUpdated := fmt.Sprintf("tf-%s", acctest.RandString(5)) + resource.Test(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, CheckDestroy: testAccCheckPagerDutyServiceDestroy, Steps: []resource.TestStep{ - resource.TestStep{ - Config: testAccCheckPagerDutyServiceConfig, + { + Config: testAccCheckPagerDutyServiceConfig(username, email, escalationPolicy, service), Check: resource.ComposeTestCheckFunc( testAccCheckPagerDutyServiceExists("pagerduty_service.foo"), resource.TestCheckResourceAttr( - "pagerduty_service.foo", "name", "foo"), + "pagerduty_service.foo", "name", service), resource.TestCheckResourceAttr( "pagerduty_service.foo", "description", "foo"), resource.TestCheckResourceAttr( @@ -219,12 +238,12 @@ func TestAccPagerDutyService_FromBasicToCustomIncidentUrgencyRules(t *testing.T) "pagerduty_service.foo", "incident_urgency_rule.0.type", "constant"), ), }, - resource.TestStep{ - Config: testAccCheckPagerDutyServiceWithIncidentUrgencyRulesConfigUpdated, + { + Config: testAccCheckPagerDutyServiceWithIncidentUrgencyRulesConfigUpdated(username, email, escalationPolicy, serviceUpdated), Check: resource.ComposeTestCheckFunc( testAccCheckPagerDutyServiceExists("pagerduty_service.foo"), resource.TestCheckResourceAttr( - "pagerduty_service.foo", "name", "bar"), + "pagerduty_service.foo", "name", serviceUpdated), resource.TestCheckResourceAttr( "pagerduty_service.foo", "description", "bar bar bar"), resource.TestCheckResourceAttr( @@ -328,10 +347,11 @@ func testAccCheckPagerDutyServiceExists(n string) resource.TestCheckFunc { } } -const testAccCheckPagerDutyServiceConfig = ` +func testAccCheckPagerDutyServiceConfig(username, email, escalationPolicy, service string) string { + return fmt.Sprintf(` resource "pagerduty_user" "foo" { - name = "foo" - email = "foo@example.com" + name = "%s" + email = "%s" color = "green" role = "user" job_title = "foo" @@ -339,7 +359,7 @@ resource "pagerduty_user" "foo" { } resource "pagerduty_escalation_policy" "foo" { - name = "bar" + name = "%s" description = "bar" num_loops = 2 rule { @@ -352,7 +372,7 @@ resource "pagerduty_escalation_policy" "foo" { } resource "pagerduty_service" "foo" { - name = "foo" + name = "%s" description = "foo" auto_resolve_timeout = 1800 acknowledgement_timeout = 1800 @@ -362,12 +382,14 @@ resource "pagerduty_service" "foo" { urgency = "high" } } -` +`, username, email, escalationPolicy, service) +} -const testAccCheckPagerDutyServiceConfigUpdated = ` +func testAccCheckPagerDutyServiceConfigUpdated(username, email, escalationPolicy, service string) string { + return fmt.Sprintf(` resource "pagerduty_user" "foo" { - name = "foo" - email = "foo@example.com" + name = "%s" + email = "%s" color = "green" role = "user" job_title = "foo" @@ -375,7 +397,7 @@ resource "pagerduty_user" "foo" { } resource "pagerduty_escalation_policy" "foo" { - name = "bar" + name = "%s" description = "bar" num_loops = 2 @@ -389,7 +411,7 @@ resource "pagerduty_escalation_policy" "foo" { } resource "pagerduty_service" "foo" { - name = "bar" + name = "%s" description = "bar" auto_resolve_timeout = 3600 acknowledgement_timeout = 3600 @@ -400,12 +422,14 @@ resource "pagerduty_service" "foo" { urgency = "high" } } -` +`, username, email, escalationPolicy, service) +} -const testAccCheckPagerDutyServiceWithIncidentUrgencyRulesConfig = ` +func testAccCheckPagerDutyServiceWithIncidentUrgencyRulesConfig(username, email, escalationPolicy, service string) string { + return fmt.Sprintf(` resource "pagerduty_user" "foo" { - name = "foo" - email = "foo@example.com" + name = "%s" + email = "%s" color = "green" role = "user" job_title = "foo" @@ -413,7 +437,7 @@ resource "pagerduty_user" "foo" { } resource "pagerduty_escalation_policy" "foo" { - name = "bar" + name = "%s" description = "bar" num_loops = 2 @@ -427,7 +451,7 @@ resource "pagerduty_escalation_policy" "foo" { } resource "pagerduty_service" "foo" { - name = "foo" + name = "%s" description = "foo" auto_resolve_timeout = 1800 acknowledgement_timeout = 1800 @@ -463,12 +487,14 @@ resource "pagerduty_service" "foo" { } } } -` +`, username, email, escalationPolicy, service) +} -const testAccCheckPagerDutyServiceWithIncidentUrgencyRulesConfigUpdated = ` +func testAccCheckPagerDutyServiceWithIncidentUrgencyRulesConfigUpdated(username, email, escalationPolicy, service string) string { + return fmt.Sprintf(` resource "pagerduty_user" "foo" { - name = "foo" - email = "foo@example.com" + name = "%s" + email = "%s" color = "green" role = "user" job_title = "foo" @@ -476,7 +502,7 @@ const testAccCheckPagerDutyServiceWithIncidentUrgencyRulesConfigUpdated = ` } resource "pagerduty_escalation_policy" "foo" { - name = "bar" + name = "%s" description = "bar" num_loops = 2 @@ -490,12 +516,12 @@ resource "pagerduty_escalation_policy" "foo" { } resource "pagerduty_service" "foo" { - name = "bar" + name = "%s" description = "bar bar bar" auto_resolve_timeout = 3600 acknowledgement_timeout = 3600 escalation_policy = "${pagerduty_escalation_policy.foo.id}" - + incident_urgency_rule { type = "use_support_hours" during_support_hours { @@ -525,4 +551,5 @@ resource "pagerduty_service" "foo" { } } } -` +`, username, email, escalationPolicy, service) +} diff --git a/builtin/providers/pagerduty/resource_pagerduty_team_test.go b/builtin/providers/pagerduty/resource_pagerduty_team_test.go index 369440ee9..1695a158b 100644 --- a/builtin/providers/pagerduty/resource_pagerduty_team_test.go +++ b/builtin/providers/pagerduty/resource_pagerduty_team_test.go @@ -5,32 +5,36 @@ import ( "testing" "github.com/PagerDuty/go-pagerduty" + "github.com/hashicorp/terraform/helper/acctest" "github.com/hashicorp/terraform/helper/resource" "github.com/hashicorp/terraform/terraform" ) func TestAccPagerDutyTeam_Basic(t *testing.T) { + team := fmt.Sprintf("tf-%s", acctest.RandString(5)) + teamUpdated := fmt.Sprintf("tf-%s", acctest.RandString(5)) + resource.Test(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, CheckDestroy: testAccCheckPagerDutyTeamDestroy, Steps: []resource.TestStep{ - resource.TestStep{ - Config: testAccCheckPagerDutyTeamConfig, + { + Config: testAccCheckPagerDutyTeamConfig(team), Check: resource.ComposeTestCheckFunc( testAccCheckPagerDutyTeamExists("pagerduty_team.foo"), resource.TestCheckResourceAttr( - "pagerduty_team.foo", "name", "foo"), + "pagerduty_team.foo", "name", team), resource.TestCheckResourceAttr( "pagerduty_team.foo", "description", "foo"), ), }, - resource.TestStep{ - Config: testAccCheckPagerDutyTeamConfigUpdated, + { + Config: testAccCheckPagerDutyTeamConfigUpdated(teamUpdated), Check: resource.ComposeTestCheckFunc( testAccCheckPagerDutyTeamExists("pagerduty_team.foo"), resource.TestCheckResourceAttr( - "pagerduty_team.foo", "name", "bar"), + "pagerduty_team.foo", "name", teamUpdated), resource.TestCheckResourceAttr( "pagerduty_team.foo", "description", "bar"), ), @@ -68,16 +72,18 @@ func testAccCheckPagerDutyTeamExists(n string) resource.TestCheckFunc { } } -const testAccCheckPagerDutyTeamConfig = ` +func testAccCheckPagerDutyTeamConfig(team string) string { + return fmt.Sprintf(` resource "pagerduty_team" "foo" { - name = "foo" + name = "%s" description = "foo" +}`, team) } -` -const testAccCheckPagerDutyTeamConfigUpdated = ` +func testAccCheckPagerDutyTeamConfigUpdated(team string) string { + return fmt.Sprintf(` resource "pagerduty_team" "foo" { - name = "bar" + name = "%s" description = "bar" +}`, team) } -` diff --git a/builtin/providers/pagerduty/resource_pagerduty_user_test.go b/builtin/providers/pagerduty/resource_pagerduty_user_test.go index 5df51f3c2..bdb1d22e4 100644 --- a/builtin/providers/pagerduty/resource_pagerduty_user_test.go +++ b/builtin/providers/pagerduty/resource_pagerduty_user_test.go @@ -5,24 +5,30 @@ import ( "testing" "github.com/PagerDuty/go-pagerduty" + "github.com/hashicorp/terraform/helper/acctest" "github.com/hashicorp/terraform/helper/resource" "github.com/hashicorp/terraform/terraform" ) func TestAccPagerDutyUser_Basic(t *testing.T) { + username := fmt.Sprintf("tf-%s", acctest.RandString(5)) + usernameUpdated := fmt.Sprintf("tf-%s", acctest.RandString(5)) + email := fmt.Sprintf("%s@foo.com", username) + emailUpdated := fmt.Sprintf("%s@foo.com", usernameUpdated) + resource.Test(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, CheckDestroy: testAccCheckPagerDutyUserDestroy, Steps: []resource.TestStep{ - resource.TestStep{ - Config: testAccCheckPagerDutyUserConfig, + { + Config: testAccCheckPagerDutyUserConfig(username, email), Check: resource.ComposeTestCheckFunc( testAccCheckPagerDutyUserExists("pagerduty_user.foo"), resource.TestCheckResourceAttr( - "pagerduty_user.foo", "name", "foo"), + "pagerduty_user.foo", "name", username), resource.TestCheckResourceAttr( - "pagerduty_user.foo", "email", "foo@bar.com"), + "pagerduty_user.foo", "email", email), resource.TestCheckResourceAttr( "pagerduty_user.foo", "color", "green"), resource.TestCheckResourceAttr( @@ -33,14 +39,14 @@ func TestAccPagerDutyUser_Basic(t *testing.T) { "pagerduty_user.foo", "description", "foo"), ), }, - resource.TestStep{ - Config: testAccCheckPagerDutyUserConfigUpdated, + { + Config: testAccCheckPagerDutyUserConfigUpdated(usernameUpdated, emailUpdated), Check: resource.ComposeTestCheckFunc( testAccCheckPagerDutyUserExists("pagerduty_user.foo"), resource.TestCheckResourceAttr( - "pagerduty_user.foo", "name", "bar"), + "pagerduty_user.foo", "name", usernameUpdated), resource.TestCheckResourceAttr( - "pagerduty_user.foo", "email", "bar@foo.com"), + "pagerduty_user.foo", "email", emailUpdated), resource.TestCheckResourceAttr( "pagerduty_user.foo", "color", "red"), resource.TestCheckResourceAttr( @@ -56,43 +62,48 @@ func TestAccPagerDutyUser_Basic(t *testing.T) { } func TestAccPagerDutyUserWithTeams_Basic(t *testing.T) { + username := fmt.Sprintf("tf-%s", acctest.RandString(5)) + email := fmt.Sprintf("%s@foo.com", username) + team1 := fmt.Sprintf("tf-%s", acctest.RandString(5)) + team2 := fmt.Sprintf("tf-%s", acctest.RandString(5)) + resource.Test(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, CheckDestroy: testAccCheckPagerDutyUserDestroy, Steps: []resource.TestStep{ - resource.TestStep{ - Config: testAccCheckPagerDutyUserWithTeamsConfig, + { + Config: testAccCheckPagerDutyUserWithTeamsConfig(team1, username, email), Check: resource.ComposeTestCheckFunc( testAccCheckPagerDutyUserExists("pagerduty_user.foo"), resource.TestCheckResourceAttr( - "pagerduty_user.foo", "name", "foo"), + "pagerduty_user.foo", "name", username), resource.TestCheckResourceAttr( - "pagerduty_user.foo", "email", "foo@bar.com"), + "pagerduty_user.foo", "email", email), resource.TestCheckResourceAttr( "pagerduty_user.foo", "teams.#", "1"), ), }, - resource.TestStep{ - Config: testAccCheckPagerDutyUserWithTeamsConfigUpdated, + { + Config: testAccCheckPagerDutyUserWithTeamsConfigUpdated(team1, team2, username, email), Check: resource.ComposeTestCheckFunc( testAccCheckPagerDutyUserExists("pagerduty_user.foo"), resource.TestCheckResourceAttr( - "pagerduty_user.foo", "name", "foo"), + "pagerduty_user.foo", "name", username), resource.TestCheckResourceAttr( - "pagerduty_user.foo", "email", "foo@bar.com"), + "pagerduty_user.foo", "email", email), resource.TestCheckResourceAttr( "pagerduty_user.foo", "teams.#", "2"), ), }, - resource.TestStep{ - Config: testAccCheckPagerDutyUserWithNoTeamsConfig, + { + Config: testAccCheckPagerDutyUserWithNoTeamsConfig(team1, team2, username, email), Check: resource.ComposeTestCheckFunc( testAccCheckPagerDutyUserExists("pagerduty_user.foo"), resource.TestCheckResourceAttr( - "pagerduty_user.foo", "name", "foo"), + "pagerduty_user.foo", "name", username), resource.TestCheckResourceAttr( - "pagerduty_user.foo", "email", "foo@bar.com"), + "pagerduty_user.foo", "email", email), resource.TestCheckResourceAttr( "pagerduty_user.foo", "teams.#", "0"), ), @@ -145,66 +156,75 @@ func testAccCheckPagerDutyUserExists(n string) resource.TestCheckFunc { } } -const testAccCheckPagerDutyUserConfig = ` +func testAccCheckPagerDutyUserConfig(username, email string) string { + return fmt.Sprintf(` resource "pagerduty_user" "foo" { - name = "foo" - email = "foo@bar.com" + name = "%s" + email = "%s" color = "green" role = "user" job_title = "foo" description = "foo" +}`, username, email) } -` -const testAccCheckPagerDutyUserConfigUpdated = ` +func testAccCheckPagerDutyUserConfigUpdated(username, email string) string { + return fmt.Sprintf(` resource "pagerduty_user" "foo" { - name = "bar" - email = "bar@foo.com" + name = "%s" + email = "%s" color = "red" role = "team_responder" job_title = "bar" description = "bar" +}`, username, email) } -` -const testAccCheckPagerDutyUserWithTeamsConfig = ` +func testAccCheckPagerDutyUserWithTeamsConfig(team, username, email string) string { + return fmt.Sprintf(` resource "pagerduty_team" "foo" { - name = "Foo team" + name = "%s" } resource "pagerduty_user" "foo" { - name = "foo" - email = "foo@bar.com" + name = "%s" + email = "%s" teams = ["${pagerduty_team.foo.id}"] } -` -const testAccCheckPagerDutyUserWithTeamsConfigUpdated = ` +`, team, username, email) +} + +func testAccCheckPagerDutyUserWithTeamsConfigUpdated(team1, team2, username, email string) string { + return fmt.Sprintf(` resource "pagerduty_team" "foo" { - name = "Foo team" + name = "%s" } resource "pagerduty_team" "bar" { - name = "Bar team" + name = "%s" } resource "pagerduty_user" "foo" { - name = "foo" - email = "foo@bar.com" + name = "%s" + email = "%s" teams = ["${pagerduty_team.foo.id}", "${pagerduty_team.bar.id}"] } -` +`, team1, team2, username, email) +} -const testAccCheckPagerDutyUserWithNoTeamsConfig = ` +func testAccCheckPagerDutyUserWithNoTeamsConfig(team1, team2, username, email string) string { + return fmt.Sprintf(` resource "pagerduty_team" "foo" { - name = "Foo team" + name = "%s" } resource "pagerduty_team" "bar" { - name = "Bar team" + name = "%s" } resource "pagerduty_user" "foo" { - name = "foo" - email = "foo@bar.com" + name = "%s" + email = "%s" +} +`, team1, team2, username, email) } -` diff --git a/builtin/providers/postgresql/resource_postgresql_database.go b/builtin/providers/postgresql/resource_postgresql_database.go index d236b02d7..66f59fca1 100644 --- a/builtin/providers/postgresql/resource_postgresql_database.go +++ b/builtin/providers/postgresql/resource_postgresql_database.go @@ -122,6 +122,12 @@ func resourcePostgreSQLDatabaseCreate(d *schema.ResourceData, meta interface{}) b := bytes.NewBufferString("CREATE DATABASE ") fmt.Fprint(b, pq.QuoteIdentifier(dbName)) + //needed in order to set the owner of the db if the connection user is not a superuser + err = grantRoleMembership(conn, d.Get(dbOwnerAttr).(string), c.username) + if err != nil { + return errwrap.Wrapf(fmt.Sprintf("Error granting role membership on database %s: {{err}}", dbName), err) + } + // Handle each option individually and stream results into the query // buffer. @@ -464,3 +470,18 @@ func doSetDBIsTemplate(conn *sql.DB, dbName string, isTemplate bool) error { return nil } + +func grantRoleMembership(conn *sql.DB, dbOwner string, connUsername string) error { + if dbOwner != "" && dbOwner != connUsername { + query := fmt.Sprintf("GRANT %s TO %s", pq.QuoteIdentifier(dbOwner), pq.QuoteIdentifier(connUsername)) + _, err := conn.Query(query) + if err != nil { + // is already member or role + if strings.Contains(err.Error(), "duplicate key value violates unique constraint") { + return nil + } + return errwrap.Wrapf("Error granting membership: {{err}}", err) + } + } + return nil +} diff --git a/builtin/providers/profitbricks/data_source_image_test.go b/builtin/providers/profitbricks/data_source_image_test.go index 3efe6d325..3f8f151a4 100644 --- a/builtin/providers/profitbricks/data_source_image_test.go +++ b/builtin/providers/profitbricks/data_source_image_test.go @@ -17,7 +17,7 @@ func TestAccDataSourceImage_basic(t *testing.T) { Config: testAccDataSourceProfitBricksImage_basic, Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr("data.profitbricks_image.img", "location", "us/las"), - resource.TestCheckResourceAttr("data.profitbricks_image.img", "name", "Ubuntu-16.04-LTS-server-2017-02-01"), + resource.TestCheckResourceAttr("data.profitbricks_image.img", "name", "Ubuntu-16.04-LTS-server-2017-05-01"), resource.TestCheckResourceAttr("data.profitbricks_image.img", "type", "HDD"), ), }, diff --git a/builtin/providers/profitbricks/resource_profitbricks_ipblock.go b/builtin/providers/profitbricks/resource_profitbricks_ipblock.go index e11f60d10..ff6658acc 100644 --- a/builtin/providers/profitbricks/resource_profitbricks_ipblock.go +++ b/builtin/providers/profitbricks/resource_profitbricks_ipblock.go @@ -26,7 +26,8 @@ func resourceProfitBricksIPBlock() *schema.Resource { ForceNew: true, }, "ips": { - Type: schema.TypeString, + Type: schema.TypeList, + Elem: &schema.Schema{Type: schema.TypeString}, Computed: true, }, }, @@ -68,7 +69,7 @@ func resourceProfitBricksIPBlockRead(d *schema.ResourceData, meta interface{}) e log.Printf("[INFO] IPS: %s", strings.Join(ipblock.Properties.Ips, ",")) - d.Set("ips", strings.Join(ipblock.Properties.Ips, ",")) + d.Set("ips", ipblock.Properties.Ips) d.Set("location", ipblock.Properties.Location) d.Set("size", ipblock.Properties.Size) diff --git a/builtin/providers/profitbricks/resource_profitbricks_server.go b/builtin/providers/profitbricks/resource_profitbricks_server.go index bfcd1678a..c617f691d 100644 --- a/builtin/providers/profitbricks/resource_profitbricks_server.go +++ b/builtin/providers/profitbricks/resource_profitbricks_server.go @@ -254,34 +254,38 @@ func resourceProfitBricksServerCreate(d *schema.ResourceData, meta interface{}) var sshkey_path []interface{} var image, licenceType, availabilityZone string - if !IsValidUUID(rawMap["image_name"].(string)) { - if rawMap["image_name"] != nil { - image = getImageId(d.Get("datacenter_id").(string), rawMap["image_name"].(string), rawMap["disk_type"].(string)) - if image == "" { - dc := profitbricks.GetDatacenter(d.Get("datacenter_id").(string)) - return fmt.Errorf("Image '%s' doesn't exist. in location %s", rawMap["image_name"], dc.Properties.Location) - - } - } - } else { - image = rawMap["image_name"].(string) - } - - if rawMap["licence_type"] != nil { - licenceType = rawMap["licence_type"].(string) - } - if rawMap["image_password"] != nil { imagePassword = rawMap["image_password"].(string) } if rawMap["ssh_key_path"] != nil { sshkey_path = rawMap["ssh_key_path"].([]interface{}) } - if rawMap["image_name"] != nil { + + image_name := rawMap["image_name"].(string) + if !IsValidUUID(image_name) { if imagePassword == "" && len(sshkey_path) == 0 { - return fmt.Errorf("Either 'image_password' or 'ssh_key_path' must be provided.") + return fmt.Errorf("Either 'image_password' or 'sshkey' must be provided.") + } + image = getImageId(d.Get("datacenter_id").(string), image_name, rawMap["disk_type"].(string)) + } else { + img := profitbricks.GetImage(image_name) + if img.StatusCode > 299 { + return fmt.Errorf("Error fetching image: %s", img.Response) + } + if img.Properties.Public == true { + if imagePassword == "" && len(sshkey_path) == 0 { + return fmt.Errorf("Either 'image_password' or 'sshkey' must be provided.") + } + image = image_name + } else { + image = image_name } } + + if rawMap["licence_type"] != nil { + licenceType = rawMap["licence_type"].(string) + } + var publicKeys []string if len(sshkey_path) != 0 { for _, path := range sshkey_path { diff --git a/builtin/providers/profitbricks/resource_profitbricks_volume.go b/builtin/providers/profitbricks/resource_profitbricks_volume.go index 8fca17854..46d8ff47d 100644 --- a/builtin/providers/profitbricks/resource_profitbricks_volume.go +++ b/builtin/providers/profitbricks/resource_profitbricks_volume.go @@ -77,12 +77,6 @@ func resourceProfitBricksVolumeCreate(d *schema.ResourceData, meta interface{}) ssh_keypath = d.Get("ssh_key_path").([]interface{}) image_name := d.Get("image_name").(string) - if image_name != "" { - if imagePassword == "" && len(ssh_keypath) == 0 { - return fmt.Errorf("Either 'image_password' or 'sshkey' must be provided.") - } - } - licenceType := d.Get("licence_type").(string) if image_name == "" && licenceType == "" { @@ -102,10 +96,26 @@ func resourceProfitBricksVolumeCreate(d *schema.ResourceData, meta interface{}) } var image string - if !IsValidUUID(image_name) { - image = getImageId(d.Get("datacenter_id").(string), image_name, d.Get("disk_type").(string)) - } else { - image = image_name + if image_name != "" { + if !IsValidUUID(image_name) { + if imagePassword == "" && len(ssh_keypath) == 0 { + return fmt.Errorf("Either 'image_password' or 'sshkey' must be provided.") + } + image = getImageId(d.Get("datacenter_id").(string), image_name, d.Get("disk_type").(string)) + } else { + img := profitbricks.GetImage(image_name) + if img.StatusCode > 299 { + return fmt.Errorf("Error fetching image: %s", img.Response) + } + if img.Properties.Public == true { + if imagePassword == "" && len(ssh_keypath) == 0 { + return fmt.Errorf("Either 'image_password' or 'sshkey' must be provided.") + } + image = image_name + } else { + image = image_name + } + } } volume := profitbricks.Volume{ diff --git a/builtin/providers/rabbitmq/acceptance_env/deploy.sh b/builtin/providers/rabbitmq/acceptance_env/deploy.sh index 037750866..9e8c01d0b 100644 --- a/builtin/providers/rabbitmq/acceptance_env/deploy.sh +++ b/builtin/providers/rabbitmq/acceptance_env/deploy.sh @@ -11,10 +11,10 @@ sudo rabbitmq-plugins enable rabbitmq_management sudo wget -O /usr/local/bin/gimme https://raw.githubusercontent.com/travis-ci/gimme/master/gimme sudo chmod +x /usr/local/bin/gimme -gimme 1.6 >> .bashrc +gimme 1.8 >> .bashrc mkdir ~/go -eval "$(/usr/local/bin/gimme 1.6)" +eval "$(/usr/local/bin/gimme 1.8)" echo 'export GOPATH=$HOME/go' >> .bashrc export GOPATH=$HOME/go @@ -24,3 +24,9 @@ source .bashrc go get -u github.com/kardianos/govendor go get github.com/hashicorp/terraform + +cat < ~/rabbitmqrc +export RABBITMQ_ENDPOINT="http://127.0.0.1:15672" +export RABBITMQ_USERNAME="guest" +export RABBITMQ_PASSWORD="guest" +EOF diff --git a/builtin/providers/rabbitmq/resource_binding_test.go b/builtin/providers/rabbitmq/resource_binding_test.go index 8b710f98c..ccd9d646c 100644 --- a/builtin/providers/rabbitmq/resource_binding_test.go +++ b/builtin/providers/rabbitmq/resource_binding_test.go @@ -11,7 +11,7 @@ import ( "github.com/hashicorp/terraform/terraform" ) -func TestAccBinding(t *testing.T) { +func TestAccBinding_basic(t *testing.T) { var bindingInfo rabbithole.BindingInfo resource.Test(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, @@ -28,6 +28,23 @@ func TestAccBinding(t *testing.T) { }) } +func TestAccBinding_propertiesKey(t *testing.T) { + var bindingInfo rabbithole.BindingInfo + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccBindingCheckDestroy(bindingInfo), + Steps: []resource.TestStep{ + resource.TestStep{ + Config: testAccBindingConfig_propertiesKey, + Check: testAccBindingCheck( + "rabbitmq_binding.test", &bindingInfo, + ), + }, + }, + }) +} + func testAccBindingCheck(rn string, bindingInfo *rabbithole.BindingInfo) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[rn] @@ -119,3 +136,47 @@ resource "rabbitmq_binding" "test" { routing_key = "#" properties_key = "%23" }` + +const testAccBindingConfig_propertiesKey = ` +resource "rabbitmq_vhost" "test" { + name = "test" +} + +resource "rabbitmq_permissions" "guest" { + user = "guest" + vhost = "${rabbitmq_vhost.test.name}" + permissions { + configure = ".*" + write = ".*" + read = ".*" + } +} + +resource "rabbitmq_exchange" "test" { + name = "Test" + vhost = "${rabbitmq_permissions.guest.vhost}" + settings { + type = "topic" + durable = true + auto_delete = false + } +} + +resource "rabbitmq_queue" "test" { + name = "Test.Queue" + vhost = "${rabbitmq_permissions.guest.vhost}" + settings { + durable = true + auto_delete = false + } +} + +resource "rabbitmq_binding" "test" { + source = "${rabbitmq_exchange.test.name}" + vhost = "${rabbitmq_vhost.test.name}" + destination = "${rabbitmq_queue.test.name}" + destination_type = "queue" + routing_key = "ANYTHING.#" + properties_key = "ANYTHING.%23" +} +` diff --git a/builtin/providers/rabbitmq/resource_user.go b/builtin/providers/rabbitmq/resource_user.go index 2177182ef..e67e60e99 100644 --- a/builtin/providers/rabbitmq/resource_user.go +++ b/builtin/providers/rabbitmq/resource_user.go @@ -35,7 +35,7 @@ func resourceUser() *schema.Resource { "tags": &schema.Schema{ Type: schema.TypeList, - Required: true, + Optional: true, Elem: &schema.Schema{Type: schema.TypeString}, }, }, @@ -49,13 +49,17 @@ func CreateUser(d *schema.ResourceData, meta interface{}) error { var tagList []string for _, v := range d.Get("tags").([]interface{}) { - tagList = append(tagList, v.(string)) + if v, ok := v.(string); ok { + tagList = append(tagList, v) + } } - tags := strings.Join(tagList, ",") userSettings := rabbithole.UserSettings{ Password: d.Get("password").(string), - Tags: tags, + } + + if len(tagList) > 0 { + userSettings.Tags = strings.Join(tagList, ",") } log.Printf("[DEBUG] RabbitMQ: Attempting to create user %s", name) @@ -87,8 +91,10 @@ func ReadUser(d *schema.ResourceData, meta interface{}) error { d.Set("name", user.Name) - tags := strings.Split(user.Tags, ",") - d.Set("tags", tags) + if len(user.Tags) > 0 { + tags := strings.Split(user.Tags, ",") + d.Set("tags", tags) + } return nil } @@ -124,12 +130,14 @@ func UpdateUser(d *schema.ResourceData, meta interface{}) error { var tagList []string for _, v := range newTags.([]interface{}) { - tagList = append(tagList, v.(string)) + if v, ok := v.(string); ok { + tagList = append(tagList, v) + } } - tags := strings.Join(tagList, ",") - userSettings := rabbithole.UserSettings{ - Tags: tags, + userSettings := rabbithole.UserSettings{} + if len(tagList) > 0 { + userSettings.Tags = strings.Join(tagList, ",") } log.Printf("[DEBUG] RabbitMQ: Attempting to update tags for %s", name) diff --git a/builtin/providers/rabbitmq/resource_user_test.go b/builtin/providers/rabbitmq/resource_user_test.go index 6876134bf..35a3ccd12 100644 --- a/builtin/providers/rabbitmq/resource_user_test.go +++ b/builtin/providers/rabbitmq/resource_user_test.go @@ -2,6 +2,7 @@ package rabbitmq import ( "fmt" + "strings" "testing" "github.com/michaelklishin/rabbit-hole" @@ -10,7 +11,7 @@ import ( "github.com/hashicorp/terraform/terraform" ) -func TestAccUser(t *testing.T) { +func TestAccUser_basic(t *testing.T) { var user string resource.Test(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, @@ -33,6 +34,63 @@ func TestAccUser(t *testing.T) { }) } +func TestAccUser_emptyTag(t *testing.T) { + var user string + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccUserCheckDestroy(user), + Steps: []resource.TestStep{ + resource.TestStep{ + Config: testAccUserConfig_emptyTag_1, + Check: resource.ComposeTestCheckFunc( + testAccUserCheck("rabbitmq_user.test", &user), + testAccUserCheckTagCount(&user, 0), + ), + }, + resource.TestStep{ + Config: testAccUserConfig_emptyTag_2, + Check: resource.ComposeTestCheckFunc( + testAccUserCheck("rabbitmq_user.test", &user), + testAccUserCheckTagCount(&user, 1), + ), + }, + resource.TestStep{ + Config: testAccUserConfig_emptyTag_1, + Check: resource.ComposeTestCheckFunc( + testAccUserCheck("rabbitmq_user.test", &user), + testAccUserCheckTagCount(&user, 0), + ), + }, + }, + }) +} + +func TestAccUser_noTags(t *testing.T) { + var user string + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccUserCheckDestroy(user), + Steps: []resource.TestStep{ + resource.TestStep{ + Config: testAccUserConfig_noTags_1, + Check: resource.ComposeTestCheckFunc( + testAccUserCheck("rabbitmq_user.test", &user), + testAccUserCheckTagCount(&user, 0), + ), + }, + resource.TestStep{ + Config: testAccUserConfig_noTags_2, + Check: resource.ComposeTestCheckFunc( + testAccUserCheck("rabbitmq_user.test", &user), + testAccUserCheckTagCount(&user, 1), + ), + }, + }, + }) +} + func testAccUserCheck(rn string, name *string) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[rn] @@ -61,6 +119,29 @@ func testAccUserCheck(rn string, name *string) resource.TestCheckFunc { } } +func testAccUserCheckTagCount(name *string, tagCount int) resource.TestCheckFunc { + return func(s *terraform.State) error { + rmqc := testAccProvider.Meta().(*rabbithole.Client) + user, err := rmqc.GetUser(*name) + if err != nil { + return fmt.Errorf("Error retrieving user: %s", err) + } + + var tagList []string + for _, v := range strings.Split(user.Tags, ",") { + if v != "" { + tagList = append(tagList, v) + } + } + + if len(tagList) != tagCount { + return fmt.Errorf("Expected %d tags, user has %d", tagCount, len(tagList)) + } + + return nil + } +} + func testAccUserCheckDestroy(name string) resource.TestCheckFunc { return func(s *terraform.State) error { rmqc := testAccProvider.Meta().(*rabbithole.Client) @@ -92,3 +173,30 @@ resource "rabbitmq_user" "test" { password = "foobarry" tags = ["management"] }` + +const testAccUserConfig_emptyTag_1 = ` +resource "rabbitmq_user" "test" { + name = "mctest" + password = "foobar" + tags = [""] +}` + +const testAccUserConfig_emptyTag_2 = ` +resource "rabbitmq_user" "test" { + name = "mctest" + password = "foobar" + tags = ["administrator"] +}` + +const testAccUserConfig_noTags_1 = ` +resource "rabbitmq_user" "test" { + name = "mctest" + password = "foobar" +}` + +const testAccUserConfig_noTags_2 = ` +resource "rabbitmq_user" "test" { + name = "mctest" + password = "foobar" + tags = ["administrator"] +}` diff --git a/builtin/providers/rancher/resource_rancher_stack.go b/builtin/providers/rancher/resource_rancher_stack.go index e8a1b1052..c928cd1f2 100644 --- a/builtin/providers/rancher/resource_rancher_stack.go +++ b/builtin/providers/rancher/resource_rancher_stack.go @@ -76,14 +76,12 @@ func resourceRancherStack() *schema.Resource { Optional: true, }, "rendered_docker_compose": { - Type: schema.TypeString, - Computed: true, - DiffSuppressFunc: suppressComposeDiff, + Type: schema.TypeString, + Computed: true, }, "rendered_rancher_compose": { - Type: schema.TypeString, - Computed: true, - DiffSuppressFunc: suppressComposeDiff, + Type: schema.TypeString, + Computed: true, }, }, } diff --git a/builtin/providers/rundeck/resource_job.go b/builtin/providers/rundeck/resource_job.go index e3a35b062..7fecbcf41 100644 --- a/builtin/providers/rundeck/resource_job.go +++ b/builtin/providers/rundeck/resource_job.go @@ -183,6 +183,10 @@ func resourceRundeckJob() *schema.Resource { Required: true, Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ + "description": &schema.Schema{ + Type: schema.TypeString, + Optional: true, + }, "shell_command": &schema.Schema{ Type: schema.TypeString, Optional: true, @@ -364,6 +368,7 @@ func jobFromResourceData(d *schema.ResourceData) (*rundeck.JobDetail, error) { for _, commandI := range commandConfigs { commandMap := commandI.(map[string]interface{}) command := rundeck.JobCommand{ + Description: commandMap["description"].(string), ShellCommand: commandMap["shell_command"].(string), Script: commandMap["inline_script"].(string), ScriptFile: commandMap["script_file"].(string), @@ -552,6 +557,7 @@ func jobToResourceData(job *rundeck.JobDetail, d *schema.ResourceData) error { d.Set("command_ordering_strategy", job.CommandSequence.OrderingStrategy) for _, command := range job.CommandSequence.Commands { commandConfigI := map[string]interface{}{ + "description": command.Description, "shell_command": command.ShellCommand, "inline_script": command.Script, "script_file": command.ScriptFile, diff --git a/builtin/providers/rundeck/resource_job_test.go b/builtin/providers/rundeck/resource_job_test.go index 182f4a3cf..2bcf6f0e1 100644 --- a/builtin/providers/rundeck/resource_job_test.go +++ b/builtin/providers/rundeck/resource_job_test.go @@ -5,7 +5,6 @@ import ( "testing" "github.com/apparentlymart/go-rundeck-api/rundeck" - "github.com/hashicorp/terraform/helper/resource" "github.com/hashicorp/terraform/terraform" ) @@ -26,6 +25,9 @@ func TestAccJob_basic(t *testing.T) { if expected := "basic-job"; job.Name != expected { return fmt.Errorf("wrong name; expected %v, got %v", expected, job.Name) } + if expected := "Prints Hello World"; job.CommandSequence.Commands[0].Description != expected { + return fmt.Errorf("failed to set command description; expected %v, got %v", expected, job.CommandSequence.Commands[0].Description) + } return nil }, ), @@ -98,6 +100,7 @@ resource "rundeck_job" "test" { default_value = "bar" } command { + description = "Prints Hello World" shell_command = "echo Hello World" } } diff --git a/builtin/providers/scaleway/data_source_scaleway_bootscript.go b/builtin/providers/scaleway/data_source_scaleway_bootscript.go index 63232bfda..cc3b6419c 100644 --- a/builtin/providers/scaleway/data_source_scaleway_bootscript.go +++ b/builtin/providers/scaleway/data_source_scaleway_bootscript.go @@ -13,43 +13,43 @@ func dataSourceScalewayBootscript() *schema.Resource { Read: dataSourceScalewayBootscriptRead, Schema: map[string]*schema.Schema{ - "name": &schema.Schema{ + "name": { Type: schema.TypeString, Optional: true, ForceNew: true, }, - "name_filter": &schema.Schema{ + "name_filter": { Type: schema.TypeString, Optional: true, ForceNew: true, }, - "architecture": &schema.Schema{ + "architecture": { Type: schema.TypeString, Computed: true, Optional: true, }, // Computed values. - "organization": &schema.Schema{ + "organization": { Type: schema.TypeString, Computed: true, }, - "public": &schema.Schema{ + "public": { Type: schema.TypeBool, Computed: true, }, - "boot_cmd_args": &schema.Schema{ + "boot_cmd_args": { Type: schema.TypeString, Computed: true, }, - "dtb": &schema.Schema{ + "dtb": { Type: schema.TypeString, Computed: true, }, - "initrd": &schema.Schema{ + "initrd": { Type: schema.TypeString, Computed: true, }, - "kernel": &schema.Schema{ + "kernel": { Type: schema.TypeString, Computed: true, }, diff --git a/builtin/providers/scaleway/data_source_scaleway_image.go b/builtin/providers/scaleway/data_source_scaleway_image.go index 85e915177..fa79e2c60 100644 --- a/builtin/providers/scaleway/data_source_scaleway_image.go +++ b/builtin/providers/scaleway/data_source_scaleway_image.go @@ -12,32 +12,32 @@ func dataSourceScalewayImage() *schema.Resource { Read: dataSourceScalewayImageRead, Schema: map[string]*schema.Schema{ - "name": &schema.Schema{ + "name": { Type: schema.TypeString, Optional: true, ForceNew: true, Computed: true, }, - "name_filter": &schema.Schema{ + "name_filter": { Type: schema.TypeString, Optional: true, ForceNew: true, }, - "architecture": &schema.Schema{ + "architecture": { Type: schema.TypeString, Required: true, ForceNew: true, }, // Computed values. - "organization": &schema.Schema{ + "organization": { Type: schema.TypeString, Computed: true, }, - "public": &schema.Schema{ + "public": { Type: schema.TypeBool, Computed: true, }, - "creation_date": &schema.Schema{ + "creation_date": { Type: schema.TypeString, Computed: true, }, diff --git a/builtin/providers/scaleway/resource_scaleway_ip.go b/builtin/providers/scaleway/resource_scaleway_ip.go index f388fe4e2..ef9aa9bd9 100644 --- a/builtin/providers/scaleway/resource_scaleway_ip.go +++ b/builtin/providers/scaleway/resource_scaleway_ip.go @@ -18,11 +18,12 @@ func resourceScalewayIP() *schema.Resource { }, Schema: map[string]*schema.Schema{ - "server": &schema.Schema{ + "server": { Type: schema.TypeString, Optional: true, + Computed: true, }, - "ip": &schema.Schema{ + "ip": { Type: schema.TypeString, Computed: true, }, diff --git a/builtin/providers/scaleway/resource_scaleway_security_group.go b/builtin/providers/scaleway/resource_scaleway_security_group.go index e2c44b676..0f850d8ac 100644 --- a/builtin/providers/scaleway/resource_scaleway_security_group.go +++ b/builtin/providers/scaleway/resource_scaleway_security_group.go @@ -19,11 +19,11 @@ func resourceScalewaySecurityGroup() *schema.Resource { }, Schema: map[string]*schema.Schema{ - "name": &schema.Schema{ + "name": { Type: schema.TypeString, Required: true, }, - "description": &schema.Schema{ + "description": { Type: schema.TypeString, Required: true, }, diff --git a/builtin/providers/scaleway/resource_scaleway_security_group_rule.go b/builtin/providers/scaleway/resource_scaleway_security_group_rule.go index 4359052b5..240bc62a8 100644 --- a/builtin/providers/scaleway/resource_scaleway_security_group_rule.go +++ b/builtin/providers/scaleway/resource_scaleway_security_group_rule.go @@ -15,11 +15,11 @@ func resourceScalewaySecurityGroupRule() *schema.Resource { Update: resourceScalewaySecurityGroupRuleUpdate, Delete: resourceScalewaySecurityGroupRuleDelete, Schema: map[string]*schema.Schema{ - "security_group": &schema.Schema{ + "security_group": { Type: schema.TypeString, Required: true, }, - "action": &schema.Schema{ + "action": { Type: schema.TypeString, Required: true, ValidateFunc: func(v interface{}, k string) (ws []string, errors []error) { @@ -30,7 +30,7 @@ func resourceScalewaySecurityGroupRule() *schema.Resource { return }, }, - "direction": &schema.Schema{ + "direction": { Type: schema.TypeString, Required: true, ValidateFunc: func(v interface{}, k string) (ws []string, errors []error) { @@ -41,11 +41,11 @@ func resourceScalewaySecurityGroupRule() *schema.Resource { return }, }, - "ip_range": &schema.Schema{ + "ip_range": { Type: schema.TypeString, Required: true, }, - "protocol": &schema.Schema{ + "protocol": { Type: schema.TypeString, Required: true, ValidateFunc: func(v interface{}, k string) (ws []string, errors []error) { @@ -56,7 +56,7 @@ func resourceScalewaySecurityGroupRule() *schema.Resource { return }, }, - "port": &schema.Schema{ + "port": { Type: schema.TypeInt, Optional: true, }, diff --git a/builtin/providers/scaleway/resource_scaleway_server.go b/builtin/providers/scaleway/resource_scaleway_server.go index 1d27c76ea..e91dd75e4 100644 --- a/builtin/providers/scaleway/resource_scaleway_server.go +++ b/builtin/providers/scaleway/resource_scaleway_server.go @@ -19,45 +19,36 @@ func resourceScalewayServer() *schema.Resource { }, Schema: map[string]*schema.Schema{ - "name": &schema.Schema{ + "name": { Type: schema.TypeString, Required: true, }, - "image": &schema.Schema{ + "image": { Type: schema.TypeString, Required: true, ForceNew: true, }, - "type": &schema.Schema{ + "type": { Type: schema.TypeString, Required: true, ForceNew: true, }, - "bootscript": &schema.Schema{ + "bootscript": { Type: schema.TypeString, Optional: true, }, - "tags": &schema.Schema{ + "tags": { Type: schema.TypeList, Elem: &schema.Schema{ Type: schema.TypeString, }, Optional: true, }, - "enable_ipv6": &schema.Schema{ - Type: schema.TypeBool, - Optional: true, - Default: false, - }, - "dynamic_ip_required": &schema.Schema{ - Type: schema.TypeBool, - Optional: true, - }, - "security_group": &schema.Schema{ + "security_group": { Type: schema.TypeString, Optional: true, }, - "volume": &schema.Schema{ + "volume": { Type: schema.TypeList, Optional: true, ForceNew: true, @@ -68,36 +59,46 @@ func resourceScalewayServer() *schema.Resource { Required: true, ValidateFunc: validateVolumeSize, }, - "type": &schema.Schema{ + "type": { Type: schema.TypeString, Required: true, ValidateFunc: validateVolumeType, }, - "volume_id": &schema.Schema{ + "volume_id": { Type: schema.TypeString, Computed: true, }, }, }, }, - "private_ip": &schema.Schema{ + "enable_ipv6": { + Type: schema.TypeBool, + Optional: true, + Default: false, + }, + "dynamic_ip_required": { + Type: schema.TypeBool, + Optional: true, + }, + "private_ip": { Type: schema.TypeString, Computed: true, }, - "public_ip": &schema.Schema{ - Type: schema.TypeString, - Computed: true, - }, - "public_ipv6": &schema.Schema{ - Type: schema.TypeString, - Computed: true, - }, - "state": &schema.Schema{ + "public_ip": { Type: schema.TypeString, Optional: true, Computed: true, }, - "state_detail": &schema.Schema{ + "public_ipv6": { + Type: schema.TypeString, + Computed: true, + }, + "state": { + Type: schema.TypeString, + Optional: true, + Computed: true, + }, + "state_detail": { Type: schema.TypeString, Computed: true, }, @@ -168,6 +169,22 @@ func resourceScalewayServerCreate(d *schema.ResourceData, m interface{}) error { } err = waitForServerState(scaleway, id, "running") + + if v, ok := d.GetOk("public_ip"); ok { + if ips, err := scaleway.GetIPS(); err != nil { + return err + } else { + for _, ip := range ips.IPS { + if ip.Address == v.(string) { + log.Printf("[DEBUG] Attaching IP %q to server %q\n", ip.ID, d.Id()) + if err := scaleway.AttachIP(ip.ID, d.Id()); err != nil { + return err + } + break + } + } + } + } } if err != nil { @@ -257,6 +274,34 @@ func resourceScalewayServerUpdate(d *schema.ResourceData, m interface{}) error { return fmt.Errorf("Failed patching scaleway server: %q", err) } + if d.HasChange("public_ip") { + ips, err := scaleway.GetIPS() + if err != nil { + return err + } + if v, ok := d.GetOk("public_ip"); ok { + for _, ip := range ips.IPS { + if ip.Address == v.(string) { + log.Printf("[DEBUG] Attaching IP %q to server %q\n", ip.ID, d.Id()) + if err := scaleway.AttachIP(ip.ID, d.Id()); err != nil { + return err + } + break + } + } + } else { + for _, ip := range ips.IPS { + if ip.Server != nil && ip.Server.Identifier == d.Id() { + log.Printf("[DEBUG] Detaching IP %q to server %q\n", ip.ID, d.Id()) + if err := scaleway.DetachIP(ip.ID); err != nil { + return err + } + break + } + } + } + } + return resourceScalewayServerRead(d, m) } diff --git a/builtin/providers/scaleway/resource_scaleway_server_test.go b/builtin/providers/scaleway/resource_scaleway_server_test.go index 9b41bc786..468ec32c0 100644 --- a/builtin/providers/scaleway/resource_scaleway_server_test.go +++ b/builtin/providers/scaleway/resource_scaleway_server_test.go @@ -27,6 +27,35 @@ func TestAccScalewayServer_Basic(t *testing.T) { "scaleway_server.base", "tags.0", "terraform-test"), ), }, + resource.TestStep{ + Config: testAccCheckScalewayServerConfig_IPAttachment, + Check: resource.ComposeTestCheckFunc( + testAccCheckScalewayServerIPAttachmentAttributes("scaleway_ip.base", "scaleway_server.base"), + ), + }, + resource.TestStep{ + Config: testAccCheckScalewayServerConfig_IPDetachment, + Check: resource.ComposeTestCheckFunc( + testAccCheckScalewayServerIPDetachmentAttributes("scaleway_server.base"), + ), + }, + }, + }) +} + +func TestAccScalewayServer_ExistingIP(t *testing.T) { + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckScalewayServerDestroy, + Steps: []resource.TestStep{ + resource.TestStep{ + Config: testAccCheckScalewayServerConfig_IPAttachment, + Check: resource.ComposeTestCheckFunc( + testAccCheckScalewayServerExists("scaleway_server.base"), + testAccCheckScalewayServerIPAttachmentAttributes("scaleway_ip.base", "scaleway_server.base"), + ), + }, }, }) } @@ -106,6 +135,52 @@ func testAccCheckScalewayServerDestroy(s *terraform.State) error { return nil } +func testAccCheckScalewayServerIPAttachmentAttributes(ipName, serverName string) resource.TestCheckFunc { + return func(s *terraform.State) error { + ip, ok := s.RootModule().Resources[ipName] + if !ok { + return fmt.Errorf("Unknown scaleway_ip resource: %s", ipName) + } + + server, ok := s.RootModule().Resources[serverName] + if !ok { + return fmt.Errorf("Unknown scaleway_server resource: %s", serverName) + } + + client := testAccProvider.Meta().(*Client).scaleway + + res, err := client.GetIP(ip.Primary.ID) + if err != nil { + return err + } + if res.IP.Server == nil || res.IP.Server.Identifier != server.Primary.ID { + return fmt.Errorf("IP %q is not attached to server %q", ip.Primary.ID, server.Primary.ID) + } + + return nil + } +} + +func testAccCheckScalewayServerIPDetachmentAttributes(n string) resource.TestCheckFunc { + return func(s *terraform.State) error { + rs, ok := s.RootModule().Resources[n] + if !ok { + return fmt.Errorf("Unknown resource: %s", n) + } + + client := testAccProvider.Meta().(*Client).scaleway + server, err := client.GetServer(rs.Primary.ID) + if err != nil { + return err + } + + if server.PublicAddress.Identifier != "" { + return fmt.Errorf("Expected server to have no public IP but got %q", server.PublicAddress.Identifier) + } + return nil + } +} + func testAccCheckScalewayServerAttributes(n string) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[n] @@ -194,6 +269,27 @@ resource "scaleway_server" "base" { tags = [ "terraform-test" ] }`, armImageIdentifier) +var testAccCheckScalewayServerConfig_IPAttachment = fmt.Sprintf(` +resource "scaleway_ip" "base" {} + +resource "scaleway_server" "base" { + name = "test" + # ubuntu 14.04 + image = "%s" + type = "C1" + tags = [ "terraform-test" ] + public_ip = "${scaleway_ip.base.ip}" +}`, armImageIdentifier) + +var testAccCheckScalewayServerConfig_IPDetachment = fmt.Sprintf(` +resource "scaleway_server" "base" { + name = "test" + # ubuntu 14.04 + image = "%s" + type = "C1" + tags = [ "terraform-test" ] +}`, armImageIdentifier) + var testAccCheckScalewayServerVolumeConfig = fmt.Sprintf(` resource "scaleway_server" "base" { name = "test" diff --git a/builtin/providers/scaleway/resource_scaleway_volume.go b/builtin/providers/scaleway/resource_scaleway_volume.go index e36cf15c9..c9cac0f25 100644 --- a/builtin/providers/scaleway/resource_scaleway_volume.go +++ b/builtin/providers/scaleway/resource_scaleway_volume.go @@ -21,21 +21,21 @@ func resourceScalewayVolume() *schema.Resource { }, Schema: map[string]*schema.Schema{ - "name": &schema.Schema{ + "name": { Type: schema.TypeString, Required: true, }, - "size_in_gb": &schema.Schema{ + "size_in_gb": { Type: schema.TypeInt, Required: true, ValidateFunc: validateVolumeSize, }, - "type": &schema.Schema{ + "type": { Type: schema.TypeString, Required: true, ValidateFunc: validateVolumeType, }, - "server": &schema.Schema{ + "server": { Type: schema.TypeString, Computed: true, }, diff --git a/builtin/providers/scaleway/resource_scaleway_volume_attachment.go b/builtin/providers/scaleway/resource_scaleway_volume_attachment.go index 532586c66..74cc4eebd 100644 --- a/builtin/providers/scaleway/resource_scaleway_volume_attachment.go +++ b/builtin/providers/scaleway/resource_scaleway_volume_attachment.go @@ -16,12 +16,12 @@ func resourceScalewayVolumeAttachment() *schema.Resource { Read: resourceScalewayVolumeAttachmentRead, Delete: resourceScalewayVolumeAttachmentDelete, Schema: map[string]*schema.Schema{ - "server": &schema.Schema{ + "server": { Type: schema.TypeString, Required: true, ForceNew: true, }, - "volume": &schema.Schema{ + "volume": { Type: schema.TypeString, Required: true, ForceNew: true, diff --git a/builtin/providers/statuscake/resource_statuscaketest.go b/builtin/providers/statuscake/resource_statuscaketest.go index 4912758d4..101ee8358 100644 --- a/builtin/providers/statuscake/resource_statuscaketest.go +++ b/builtin/providers/statuscake/resource_statuscaketest.go @@ -70,6 +70,12 @@ func resourceStatusCakeTest() *schema.Resource { Type: schema.TypeInt, Optional: true, }, + + "trigger_rate": { + Type: schema.TypeInt, + Optional: true, + Default: 5, + }, }, } } @@ -87,6 +93,7 @@ func CreateTest(d *schema.ResourceData, meta interface{}) error { ContactID: d.Get("contact_id").(int), Confirmation: d.Get("confirmations").(int), Port: d.Get("port").(int), + TriggerRate: d.Get("trigger_rate").(int), } log.Printf("[DEBUG] Creating new StatusCake Test: %s", d.Get("website_name").(string)) @@ -151,6 +158,7 @@ func ReadTest(d *schema.ResourceData, meta interface{}) error { d.Set("contact_id", testResp.ContactID) d.Set("confirmations", testResp.Confirmation) d.Set("port", testResp.Port) + d.Set("trigger_rate", testResp.TriggerRate) return nil } @@ -193,6 +201,9 @@ func getStatusCakeTestInput(d *schema.ResourceData) *statuscake.Test { if v, ok := d.GetOk("port"); ok { test.Port = v.(int) } + if v, ok := d.GetOk("trigger_rate"); ok { + test.TriggerRate = v.(int) + } defaultStatusCodes := "204, 205, 206, 303, 400, 401, 403, 404, 405, 406, " + "408, 410, 413, 444, 429, 494, 495, 496, 499, 500, 501, 502, 503, " + diff --git a/builtin/providers/statuscake/resource_statuscaketest_test.go b/builtin/providers/statuscake/resource_statuscaketest_test.go index d38dc1c33..f07fcc55a 100644 --- a/builtin/providers/statuscake/resource_statuscaketest_test.go +++ b/builtin/providers/statuscake/resource_statuscaketest_test.go @@ -73,6 +73,7 @@ func TestAccStatusCake_withUpdate(t *testing.T) { resource.TestCheckResourceAttr("statuscake_test.google", "timeout", "40"), resource.TestCheckResourceAttr("statuscake_test.google", "contact_id", "0"), resource.TestCheckResourceAttr("statuscake_test.google", "confirmations", "0"), + resource.TestCheckResourceAttr("statuscake_test.google", "trigger_rate", "20"), ), }, }, @@ -139,6 +140,8 @@ func testAccTestCheckAttributes(rn string, test *statuscake.Test) resource.TestC err = check(key, value, strconv.Itoa(test.ContactID)) case "confirmations": err = check(key, value, strconv.Itoa(test.Confirmation)) + case "trigger_rate": + err = check(key, value, strconv.Itoa(test.TriggerRate)) } if err != nil { @@ -170,6 +173,7 @@ resource "statuscake_test" "google" { timeout = 10 contact_id = 43402 confirmations = 1 + trigger_rate = 10 } ` @@ -180,6 +184,7 @@ resource "statuscake_test" "google" { test_type = "HTTP" check_rate = 500 paused = true + trigger_rate = 20 } ` diff --git a/builtin/providers/template/datasource_cloudinit_config.go b/builtin/providers/template/datasource_cloudinit_config.go index edbe0d13e..8a24c329a 100644 --- a/builtin/providers/template/datasource_cloudinit_config.go +++ b/builtin/providers/template/datasource_cloudinit_config.go @@ -19,41 +19,41 @@ func dataSourceCloudinitConfig() *schema.Resource { Read: dataSourceCloudinitConfigRead, Schema: map[string]*schema.Schema{ - "part": &schema.Schema{ + "part": { Type: schema.TypeList, Required: true, Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ - "content_type": &schema.Schema{ + "content_type": { Type: schema.TypeString, Optional: true, }, - "content": &schema.Schema{ + "content": { Type: schema.TypeString, Required: true, }, - "filename": &schema.Schema{ + "filename": { Type: schema.TypeString, Optional: true, }, - "merge_type": &schema.Schema{ + "merge_type": { Type: schema.TypeString, Optional: true, }, }, }, }, - "gzip": &schema.Schema{ + "gzip": { Type: schema.TypeBool, Optional: true, Default: true, }, - "base64_encode": &schema.Schema{ + "base64_encode": { Type: schema.TypeBool, Optional: true, Default: true, }, - "rendered": &schema.Schema{ + "rendered": { Type: schema.TypeString, Computed: true, Description: "rendered cloudinit configuration", @@ -84,7 +84,10 @@ func renderCloudinitConfig(d *schema.ResourceData) (string, error) { cloudInitParts := make(cloudInitParts, len(partsValue.([]interface{}))) for i, v := range partsValue.([]interface{}) { - p := v.(map[string]interface{}) + p, castOk := v.(map[string]interface{}) + if !castOk { + return "", fmt.Errorf("Unable to parse parts in cloudinit resource declaration") + } part := cloudInitPart{} if p, ok := p["content_type"]; ok { @@ -137,7 +140,7 @@ func renderPartsToWriter(parts cloudInitParts, writer io.Writer) error { } writer.Write([]byte(fmt.Sprintf("Content-Type: multipart/mixed; boundary=\"%s\"\n", mimeWriter.Boundary()))) - writer.Write([]byte("MIME-Version: 1.0\r\n")) + writer.Write([]byte("MIME-Version: 1.0\r\n\r\n")) for _, part := range parts { header := textproto.MIMEHeader{} diff --git a/builtin/providers/template/datasource_cloudinit_config_test.go b/builtin/providers/template/datasource_cloudinit_config_test.go index e3e7225db..7ea49ca7d 100644 --- a/builtin/providers/template/datasource_cloudinit_config_test.go +++ b/builtin/providers/template/datasource_cloudinit_config_test.go @@ -1,6 +1,7 @@ package template import ( + "regexp" "testing" r "github.com/hashicorp/terraform/helper/resource" @@ -21,7 +22,7 @@ func TestRender(t *testing.T) { content = "baz" } }`, - "Content-Type: multipart/mixed; boundary=\"MIMEBOUNDARY\"\nMIME-Version: 1.0\r\n--MIMEBOUNDARY\r\nContent-Transfer-Encoding: 7bit\r\nContent-Type: text/x-shellscript\r\nMime-Version: 1.0\r\n\r\nbaz\r\n--MIMEBOUNDARY--\r\n", + "Content-Type: multipart/mixed; boundary=\"MIMEBOUNDARY\"\nMIME-Version: 1.0\r\n\r\n--MIMEBOUNDARY\r\nContent-Transfer-Encoding: 7bit\r\nContent-Type: text/x-shellscript\r\nMime-Version: 1.0\r\n\r\nbaz\r\n--MIMEBOUNDARY--\r\n", }, { `data "template_cloudinit_config" "foo" { @@ -34,7 +35,7 @@ func TestRender(t *testing.T) { filename = "foobar.sh" } }`, - "Content-Type: multipart/mixed; boundary=\"MIMEBOUNDARY\"\nMIME-Version: 1.0\r\n--MIMEBOUNDARY\r\nContent-Disposition: attachment; filename=\"foobar.sh\"\r\nContent-Transfer-Encoding: 7bit\r\nContent-Type: text/x-shellscript\r\nMime-Version: 1.0\r\n\r\nbaz\r\n--MIMEBOUNDARY--\r\n", + "Content-Type: multipart/mixed; boundary=\"MIMEBOUNDARY\"\nMIME-Version: 1.0\r\n\r\n--MIMEBOUNDARY\r\nContent-Disposition: attachment; filename=\"foobar.sh\"\r\nContent-Transfer-Encoding: 7bit\r\nContent-Type: text/x-shellscript\r\nMime-Version: 1.0\r\n\r\nbaz\r\n--MIMEBOUNDARY--\r\n", }, { `data "template_cloudinit_config" "foo" { @@ -50,7 +51,7 @@ func TestRender(t *testing.T) { content = "ffbaz" } }`, - "Content-Type: multipart/mixed; boundary=\"MIMEBOUNDARY\"\nMIME-Version: 1.0\r\n--MIMEBOUNDARY\r\nContent-Transfer-Encoding: 7bit\r\nContent-Type: text/x-shellscript\r\nMime-Version: 1.0\r\n\r\nbaz\r\n--MIMEBOUNDARY\r\nContent-Transfer-Encoding: 7bit\r\nContent-Type: text/x-shellscript\r\nMime-Version: 1.0\r\n\r\nffbaz\r\n--MIMEBOUNDARY--\r\n", + "Content-Type: multipart/mixed; boundary=\"MIMEBOUNDARY\"\nMIME-Version: 1.0\r\n\r\n--MIMEBOUNDARY\r\nContent-Transfer-Encoding: 7bit\r\nContent-Type: text/x-shellscript\r\nMime-Version: 1.0\r\n\r\nbaz\r\n--MIMEBOUNDARY\r\nContent-Transfer-Encoding: 7bit\r\nContent-Type: text/x-shellscript\r\nMime-Version: 1.0\r\n\r\nffbaz\r\n--MIMEBOUNDARY--\r\n", }, } @@ -58,7 +59,7 @@ func TestRender(t *testing.T) { r.UnitTest(t, r.TestCase{ Providers: testProviders, Steps: []r.TestStep{ - r.TestStep{ + { Config: tt.ResourceBlock, Check: r.ComposeTestCheckFunc( r.TestCheckResourceAttr("data.template_cloudinit_config.foo", "rendered", tt.Expected), @@ -69,12 +70,23 @@ func TestRender(t *testing.T) { } } -var testCloudInitConfig_basic = ` -data "template_cloudinit_config" "config" { - part { - content_type = "text/x-shellscript" - content = "baz" - } -}` +// From GH-13572, Correctly handle panic on a misconfigured cloudinit part +func TestRender_handlePanic(t *testing.T) { + r.UnitTest(t, r.TestCase{ + Providers: testProviders, + Steps: []r.TestStep{ + { + Config: testCloudInitConfig_misconfiguredParts, + ExpectError: regexp.MustCompile("Unable to parse parts in cloudinit resource declaration"), + }, + }, + }) +} -var testCloudInitConfig_basic_expected = `Content-Type: multipart/mixed; boundary=\"MIMEBOUNDARY\"\nMIME-Version: 1.0\r\n--MIMEBOUNDARY\r\nContent-Transfer-Encoding: 7bit\r\nContent-Type: text/x-shellscript\r\nMime-Version: 1.0\r\n\r\nbaz\r\n--MIMEBOUNDARY--\r\n` +var testCloudInitConfig_misconfiguredParts = ` +data "template_cloudinit_config" "foo" { + part { + content = "" + } +} +` diff --git a/builtin/providers/template/provider.go b/builtin/providers/template/provider.go index ece6c9f34..fb340754d 100644 --- a/builtin/providers/template/provider.go +++ b/builtin/providers/template/provider.go @@ -20,6 +20,7 @@ func Provider() terraform.ResourceProvider { "template_cloudinit_config", dataSourceCloudinitConfig(), ), + "template_dir": resourceDir(), }, } } diff --git a/builtin/providers/template/resource_template_dir.go b/builtin/providers/template/resource_template_dir.go new file mode 100644 index 000000000..63a2f18dc --- /dev/null +++ b/builtin/providers/template/resource_template_dir.go @@ -0,0 +1,234 @@ +package template + +import ( + "archive/tar" + "bytes" + "crypto/sha1" + "encoding/hex" + "fmt" + "io" + "io/ioutil" + "os" + "path" + "path/filepath" + + "github.com/hashicorp/terraform/helper/pathorcontents" + "github.com/hashicorp/terraform/helper/schema" +) + +func resourceDir() *schema.Resource { + return &schema.Resource{ + Create: resourceTemplateDirCreate, + Read: resourceTemplateDirRead, + Delete: resourceTemplateDirDelete, + + Schema: map[string]*schema.Schema{ + "source_dir": { + Type: schema.TypeString, + Description: "Path to the directory where the files to template reside", + Required: true, + ForceNew: true, + }, + "vars": { + Type: schema.TypeMap, + Optional: true, + Default: make(map[string]interface{}), + Description: "Variables to substitute", + ValidateFunc: validateVarsAttribute, + ForceNew: true, + }, + "destination_dir": { + Type: schema.TypeString, + Description: "Path to the directory where the templated files will be written", + Required: true, + ForceNew: true, + }, + }, + } +} + +func resourceTemplateDirRead(d *schema.ResourceData, meta interface{}) error { + sourceDir := d.Get("source_dir").(string) + destinationDir := d.Get("destination_dir").(string) + + // If the output doesn't exist, mark the resource for creation. + if _, err := os.Stat(destinationDir); os.IsNotExist(err) { + d.SetId("") + return nil + } + + // If the combined hash of the input and output directories is different from + // the stored one, mark the resource for re-creation. + // + // The output directory is technically enough for the general case, but by + // hashing the input directory as well, we make development much easier: when + // a developer modifies one of the input files, the generation is + // re-triggered. + hash, err := generateID(sourceDir, destinationDir) + if err != nil { + return err + } + if hash != d.Id() { + d.SetId("") + return nil + } + + return nil +} + +func resourceTemplateDirCreate(d *schema.ResourceData, meta interface{}) error { + sourceDir := d.Get("source_dir").(string) + destinationDir := d.Get("destination_dir").(string) + vars := d.Get("vars").(map[string]interface{}) + + // Always delete the output first, otherwise files that got deleted from the + // input directory might still be present in the output afterwards. + if err := resourceTemplateDirDelete(d, meta); err != nil { + return err + } + + // Create the destination directory and any other intermediate directories + // leading to it. + if _, err := os.Stat(destinationDir); err != nil { + if err := os.MkdirAll(destinationDir, 0777); err != nil { + return err + } + } + + // Recursively crawl the input files/directories and generate the output ones. + err := filepath.Walk(sourceDir, func(p string, f os.FileInfo, err error) error { + if err != nil { + return err + } + + if f.IsDir() { + return nil + } + + relPath, _ := filepath.Rel(sourceDir, p) + return generateDirFile(p, path.Join(destinationDir, relPath), f, vars) + }) + if err != nil { + return err + } + + // Compute ID. + hash, err := generateID(sourceDir, destinationDir) + if err != nil { + return err + } + d.SetId(hash) + + return nil +} + +func resourceTemplateDirDelete(d *schema.ResourceData, _ interface{}) error { + d.SetId("") + + destinationDir := d.Get("destination_dir").(string) + if _, err := os.Stat(destinationDir); os.IsNotExist(err) { + return nil + } + + if err := os.RemoveAll(destinationDir); err != nil { + return fmt.Errorf("could not delete directory %q: %s", destinationDir, err) + } + + return nil +} + +func generateDirFile(sourceDir, destinationDir string, f os.FileInfo, vars map[string]interface{}) error { + inputContent, _, err := pathorcontents.Read(sourceDir) + if err != nil { + return err + } + + outputContent, err := execute(inputContent, vars) + if err != nil { + return templateRenderError(fmt.Errorf("failed to render %v: %v", sourceDir, err)) + } + + outputDir := path.Dir(destinationDir) + if _, err := os.Stat(outputDir); err != nil { + if err := os.MkdirAll(outputDir, 0777); err != nil { + return err + } + } + + err = ioutil.WriteFile(destinationDir, []byte(outputContent), f.Mode()) + if err != nil { + return err + } + + return nil +} + +func generateID(sourceDir, destinationDir string) (string, error) { + inputHash, err := generateDirHash(sourceDir) + if err != nil { + return "", err + } + outputHash, err := generateDirHash(destinationDir) + if err != nil { + return "", err + } + checksum := sha1.Sum([]byte(inputHash + outputHash)) + return hex.EncodeToString(checksum[:]), nil +} + +func generateDirHash(directoryPath string) (string, error) { + tarData, err := tarDir(directoryPath) + if err != nil { + return "", fmt.Errorf("could not generate output checksum: %s", err) + } + + checksum := sha1.Sum(tarData) + return hex.EncodeToString(checksum[:]), nil +} + +func tarDir(directoryPath string) ([]byte, error) { + buf := new(bytes.Buffer) + tw := tar.NewWriter(buf) + + writeFile := func(p string, f os.FileInfo, err error) error { + if err != nil { + return err + } + + var header *tar.Header + var file *os.File + + header, err = tar.FileInfoHeader(f, f.Name()) + if err != nil { + return err + } + relPath, _ := filepath.Rel(directoryPath, p) + header.Name = relPath + + if err := tw.WriteHeader(header); err != nil { + return err + } + + if f.IsDir() { + return nil + } + + file, err = os.Open(p) + if err != nil { + return err + } + defer file.Close() + + _, err = io.Copy(tw, file) + return err + } + + if err := filepath.Walk(directoryPath, writeFile); err != nil { + return []byte{}, err + } + if err := tw.Flush(); err != nil { + return []byte{}, err + } + + return buf.Bytes(), nil +} diff --git a/builtin/providers/template/resource_template_dir_test.go b/builtin/providers/template/resource_template_dir_test.go new file mode 100644 index 000000000..716a5f0af --- /dev/null +++ b/builtin/providers/template/resource_template_dir_test.go @@ -0,0 +1,104 @@ +package template + +import ( + "fmt" + "testing" + + "errors" + r "github.com/hashicorp/terraform/helper/resource" + "github.com/hashicorp/terraform/terraform" + "io/ioutil" + "os" + "path/filepath" +) + +const templateDirRenderingConfig = ` +resource "template_dir" "dir" { + source_dir = "%s" + destination_dir = "%s" + vars = %s +}` + +type testTemplate struct { + template string + want string +} + +func testTemplateDirWriteFiles(files map[string]testTemplate) (in, out string, err error) { + in, err = ioutil.TempDir(os.TempDir(), "terraform_template_dir") + if err != nil { + return + } + + for name, file := range files { + path := filepath.Join(in, name) + + err = os.MkdirAll(filepath.Dir(path), 0777) + if err != nil { + return + } + + err = ioutil.WriteFile(path, []byte(file.template), 0777) + if err != nil { + return + } + } + + out = fmt.Sprintf("%s.out", in) + return +} + +func TestTemplateDirRendering(t *testing.T) { + var cases = []struct { + vars string + files map[string]testTemplate + }{ + { + files: map[string]testTemplate{ + "foo.txt": {"${bar}", "bar"}, + "nested/monkey.txt": {"ooh-ooh-ooh-eee-eee", "ooh-ooh-ooh-eee-eee"}, + "maths.txt": {"${1+2+3}", "6"}, + }, + vars: `{bar = "bar"}`, + }, + } + + for _, tt := range cases { + // Write the desired templates in a temporary directory. + in, out, err := testTemplateDirWriteFiles(tt.files) + if err != nil { + t.Skipf("could not write templates to temporary directory: %s", err) + continue + } + defer os.RemoveAll(in) + defer os.RemoveAll(out) + + // Run test case. + r.UnitTest(t, r.TestCase{ + Providers: testProviders, + Steps: []r.TestStep{ + { + Config: fmt.Sprintf(templateDirRenderingConfig, in, out, tt.vars), + Check: func(s *terraform.State) error { + for name, file := range tt.files { + content, err := ioutil.ReadFile(filepath.Join(out, name)) + if err != nil { + return fmt.Errorf("template:\n%s\nvars:\n%s\ngot:\n%s\nwant:\n%s\n", file.template, tt.vars, err, file.want) + } + if string(content) != file.want { + return fmt.Errorf("template:\n%s\nvars:\n%s\ngot:\n%s\nwant:\n%s\n", file.template, tt.vars, content, file.want) + } + } + return nil + }, + }, + }, + CheckDestroy: func(*terraform.State) error { + if _, err := os.Stat(out); os.IsNotExist(err) { + return nil + } + return errors.New("template_dir did not get destroyed") + }, + }) + } +} diff --git a/builtin/providers/test/data_source_label.go b/builtin/providers/test/data_source_label.go new file mode 100644 index 000000000..40f3bad58 --- /dev/null +++ b/builtin/providers/test/data_source_label.go @@ -0,0 +1,25 @@ +package test + +import ( + "github.com/hashicorp/terraform/helper/schema" +) + +func providerLabelDataSource() *schema.Resource { + return &schema.Resource{ + Read: providerLabelDataSourceRead, + + Schema: map[string]*schema.Schema{ + "label": { + Type: schema.TypeString, + Computed: true, + }, + }, + } +} + +func providerLabelDataSourceRead(d *schema.ResourceData, meta interface{}) error { + label := meta.(string) + d.SetId(label) + d.Set("label", label) + return nil +} diff --git a/builtin/providers/test/data_source_label_test.go b/builtin/providers/test/data_source_label_test.go new file mode 100644 index 000000000..d98a27b06 --- /dev/null +++ b/builtin/providers/test/data_source_label_test.go @@ -0,0 +1,45 @@ +package test + +import ( + "errors" + "fmt" + "strings" + "testing" + + "github.com/hashicorp/terraform/helper/resource" + "github.com/hashicorp/terraform/terraform" +) + +func TestProviderLabelDataSource(t *testing.T) { + resource.UnitTest(t, resource.TestCase{ + Providers: testAccProviders, + CheckDestroy: func(s *terraform.State) error { + return nil + }, + Steps: []resource.TestStep{ + { + Config: strings.TrimSpace(` +provider "test" { + label = "foo" +} + +data "test_provider_label" "test" { +} + `), + Check: func(s *terraform.State) error { + res, hasRes := s.RootModule().Resources["data.test_provider_label.test"] + if !hasRes { + return errors.New("No test_provider_label in state") + } + if got, want := res.Primary.ID, "foo"; got != want { + return fmt.Errorf("wrong id %q; want %q", got, want) + } + if got, want := res.Primary.Attributes["label"], "foo"; got != want { + return fmt.Errorf("wrong id %q; want %q", got, want) + } + return nil + }, + }, + }, + }) +} diff --git a/builtin/providers/test/data_source_test.go b/builtin/providers/test/data_source_test.go index 3f4e5ada6..77e235f3d 100644 --- a/builtin/providers/test/data_source_test.go +++ b/builtin/providers/test/data_source_test.go @@ -99,3 +99,59 @@ resource "test_resource" "foo" { }, }) } + +// TestDataSource_dataSourceCountGrandChild tests that a grandchild data source +// that is based off of count works, ie: dependency chain foo -> bar -> baz. +// This was failing because CountBoundaryTransformer is being run during apply +// instead of plan, which meant that it wasn't firing after data sources were +// potentially changing state and causing diff/interpolation issues. +// +// This happens after the initial apply, after state is saved. +func TestDataSource_dataSourceCountGrandChild(t *testing.T) { + resource.UnitTest(t, resource.TestCase{ + Providers: testAccProviders, + CheckDestroy: func(s *terraform.State) error { + return nil + }, + Steps: []resource.TestStep{ + { + Config: dataSourceCountGrandChildConfig, + }, + { + Config: dataSourceCountGrandChildConfig, + Check: func(s *terraform.State) error { + for _, v := range []string{"foo", "bar", "baz"} { + count := 0 + for k := range s.RootModule().Resources { + if strings.HasPrefix(k, fmt.Sprintf("data.test_data_source.%s.", v)) { + count++ + } + } + + if count != 2 { + return fmt.Errorf("bad count for data.test_data_source.%s: %d", v, count) + } + } + return nil + }, + }, + }, + }) +} + +const dataSourceCountGrandChildConfig = ` +data "test_data_source" "foo" { + count = 2 + input = "one" +} + +data "test_data_source" "bar" { + count = "${length(data.test_data_source.foo.*.id)}" + input = "${data.test_data_source.foo.*.output[count.index]}" +} + +data "test_data_source" "baz" { + count = "${length(data.test_data_source.bar.*.id)}" + input = "${data.test_data_source.bar.*.output[count.index]}" +} +` diff --git a/builtin/providers/test/provider.go b/builtin/providers/test/provider.go index a11e3f1cd..4afec61b0 100644 --- a/builtin/providers/test/provider.go +++ b/builtin/providers/test/provider.go @@ -7,17 +7,27 @@ import ( func Provider() terraform.ResourceProvider { return &schema.Provider{ + Schema: map[string]*schema.Schema{ + // Optional attribute to label a particular instance for a test + // that has multiple instances of this provider, so that they + // can be distinguished using the test_provider_label data source. + "label": { + Type: schema.TypeString, + Optional: true, + }, + }, ResourcesMap: map[string]*schema.Resource{ "test_resource": testResource(), "test_resource_gh12183": testResourceGH12183(), }, DataSourcesMap: map[string]*schema.Resource{ - "test_data_source": testDataSource(), + "test_data_source": testDataSource(), + "test_provider_label": providerLabelDataSource(), }, ConfigureFunc: providerConfigure, } } func providerConfigure(d *schema.ResourceData) (interface{}, error) { - return nil, nil + return d.Get("label"), nil } diff --git a/builtin/providers/test/resource_data_dep_test.go b/builtin/providers/test/resource_data_dep_test.go new file mode 100644 index 000000000..109b4be66 --- /dev/null +++ b/builtin/providers/test/resource_data_dep_test.go @@ -0,0 +1,224 @@ +package test + +import ( + "fmt" + "testing" + + "github.com/hashicorp/terraform/helper/resource" + "github.com/hashicorp/terraform/terraform" +) + +// TestResourceDataDep_alignedCountScaleOut tests to make sure interpolation +// works (namely without index errors) when a data source and a resource share +// the same count variable during scale-out with an existing state. +func TestResourceDataDep_alignedCountScaleOut(t *testing.T) { + resource.UnitTest(t, resource.TestCase{ + Providers: testAccProviders, + CheckDestroy: func(s *terraform.State) error { + return nil + }, + Steps: []resource.TestStep{ + { + Config: testResourceDataDepConfig(2), + }, + { + Config: testResourceDataDepConfig(4), + Check: resource.TestCheckOutput("out", "value_from_api,value_from_api,value_from_api,value_from_api"), + }, + }, + }) +} + +// TestResourceDataDep_alignedCountScaleIn tests to make sure interpolation +// works (namely without index errors) when a data source and a resource share +// the same count variable during scale-in with an existing state. +func TestResourceDataDep_alignedCountScaleIn(t *testing.T) { + resource.UnitTest(t, resource.TestCase{ + Providers: testAccProviders, + CheckDestroy: func(s *terraform.State) error { + return nil + }, + Steps: []resource.TestStep{ + { + Config: testResourceDataDepConfig(4), + }, + { + Config: testResourceDataDepConfig(2), + Check: resource.TestCheckOutput("out", "value_from_api,value_from_api"), + }, + }, + }) +} + +// TestDataResourceDep_alignedCountScaleOut functions like +// TestResourceDataDep_alignedCountScaleOut, but with the dependencies swapped +// (resource now depends on data source, a pretty regular use case, but +// included here to check for regressions). +func TestDataResourceDep_alignedCountScaleOut(t *testing.T) { + resource.UnitTest(t, resource.TestCase{ + Providers: testAccProviders, + CheckDestroy: func(s *terraform.State) error { + return nil + }, + Steps: []resource.TestStep{ + { + Config: testDataResourceDepConfig(2), + }, + { + Config: testDataResourceDepConfig(4), + Check: resource.TestCheckOutput("out", "test,test,test,test"), + }, + }, + }) +} + +// TestDataResourceDep_alignedCountScaleIn functions like +// TestResourceDataDep_alignedCountScaleIn, but with the dependencies swapped +// (resource now depends on data source, a pretty regular use case, but +// included here to check for regressions). +func TestDataResourceDep_alignedCountScaleIn(t *testing.T) { + resource.UnitTest(t, resource.TestCase{ + Providers: testAccProviders, + CheckDestroy: func(s *terraform.State) error { + return nil + }, + Steps: []resource.TestStep{ + { + Config: testDataResourceDepConfig(4), + }, + { + Config: testDataResourceDepConfig(2), + Check: resource.TestCheckOutput("out", "test,test"), + }, + }, + }) +} + +// TestResourceResourceDep_alignedCountScaleOut functions like +// TestResourceDataDep_alignedCountScaleOut, but with a resource-to-resource +// dependency instead, a pretty regular use case, but included here to check +// for regressions. +func TestResourceResourceDep_alignedCountScaleOut(t *testing.T) { + resource.UnitTest(t, resource.TestCase{ + Providers: testAccProviders, + CheckDestroy: func(s *terraform.State) error { + return nil + }, + Steps: []resource.TestStep{ + { + Config: testResourceResourceDepConfig(2), + }, + { + Config: testResourceResourceDepConfig(4), + Check: resource.TestCheckOutput("out", "test,test,test,test"), + }, + }, + }) +} + +// TestResourceResourceDep_alignedCountScaleIn functions like +// TestResourceDataDep_alignedCountScaleIn, but with a resource-to-resource +// dependency instead, a pretty regular use case, but included here to check +// for regressions. +func TestResourceResourceDep_alignedCountScaleIn(t *testing.T) { + resource.UnitTest(t, resource.TestCase{ + Providers: testAccProviders, + CheckDestroy: func(s *terraform.State) error { + return nil + }, + Steps: []resource.TestStep{ + { + Config: testResourceResourceDepConfig(4), + }, + { + Config: testResourceResourceDepConfig(2), + Check: resource.TestCheckOutput("out", "test,test"), + }, + }, + }) +} + +func testResourceDataDepConfig(count int) string { + return fmt.Sprintf(` +variable count { + default = "%d" +} + +resource "test_resource" "foo" { + count = "${var.count}" + required = "yes" + + required_map = { + "foo" = "bar" + } +} + +data "test_data_source" "bar" { + count = "${var.count}" + input = "${test_resource.foo.*.computed_read_only[count.index]}" +} + +output "out" { + value = "${join(",", data.test_data_source.bar.*.output)}" +} +`, count) +} + +func testDataResourceDepConfig(count int) string { + return fmt.Sprintf(` +variable count { + default = "%d" +} + +data "test_data_source" "foo" { + count = "${var.count}" + input = "test" +} + +resource "test_resource" "bar" { + count = "${var.count}" + required = "yes" + optional = "${data.test_data_source.foo.*.output[count.index]}" + + required_map = { + "foo" = "bar" + } +} + +output "out" { + value = "${join(",", test_resource.bar.*.optional)}" +} +`, count) +} + +func testResourceResourceDepConfig(count int) string { + return fmt.Sprintf(` +variable count { + default = "%d" +} + +resource "test_resource" "foo" { + count = "${var.count}" + required = "yes" + optional = "test" + + required_map = { + "foo" = "bar" + } +} + +resource "test_resource" "bar" { + count = "${var.count}" + required = "yes" + optional = "${test_resource.foo.*.optional[count.index]}" + + required_map = { + "foo" = "bar" + } +} + +output "out" { + value = "${join(",", test_resource.bar.*.optional)}" +} +`, count) +} diff --git a/builtin/providers/triton/provider.go b/builtin/providers/triton/provider.go index 216ed1c08..8a56b5dc4 100644 --- a/builtin/providers/triton/provider.go +++ b/builtin/providers/triton/provider.go @@ -1,44 +1,52 @@ package triton import ( - "fmt" - "log" - "os" + "crypto/md5" + "encoding/base64" + "errors" + "sort" + "time" + "github.com/hashicorp/errwrap" "github.com/hashicorp/go-multierror" "github.com/hashicorp/terraform/helper/schema" "github.com/hashicorp/terraform/terraform" - "github.com/joyent/gocommon/client" - "github.com/joyent/gosdc/cloudapi" - "github.com/joyent/gosign/auth" + "github.com/joyent/triton-go" + "github.com/joyent/triton-go/authentication" ) // Provider returns a terraform.ResourceProvider. func Provider() terraform.ResourceProvider { return &schema.Provider{ Schema: map[string]*schema.Schema{ - "account": &schema.Schema{ + "account": { Type: schema.TypeString, Required: true, - DefaultFunc: schema.EnvDefaultFunc("SDC_ACCOUNT", ""), + DefaultFunc: schema.MultiEnvDefaultFunc([]string{"TRITON_ACCOUNT", "SDC_ACCOUNT"}, ""), }, - "url": &schema.Schema{ + "url": { Type: schema.TypeString, Required: true, - DefaultFunc: schema.EnvDefaultFunc("SDC_URL", "https://us-west-1.api.joyentcloud.com"), + DefaultFunc: schema.MultiEnvDefaultFunc([]string{"TRITON_URL", "SDC_URL"}, "https://us-west-1.api.joyentcloud.com"), }, - "key_material": &schema.Schema{ + "key_material": { Type: schema.TypeString, - Required: true, - DefaultFunc: schema.EnvDefaultFunc("SDC_KEY_MATERIAL", ""), + Optional: true, + DefaultFunc: schema.MultiEnvDefaultFunc([]string{"TRITON_KEY_MATERIAL", "SDC_KEY_MATERIAL"}, ""), }, - "key_id": &schema.Schema{ + "key_id": { Type: schema.TypeString, Required: true, - DefaultFunc: schema.EnvDefaultFunc("SDC_KEY_ID", ""), + DefaultFunc: schema.MultiEnvDefaultFunc([]string{"TRITON_KEY_ID", "SDC_KEY_ID"}, ""), + }, + + "insecure_skip_tls_verify": { + Type: schema.TypeBool, + Optional: true, + DefaultFunc: schema.EnvDefaultFunc("TRITON_SKIP_TLS_VERIFY", ""), }, }, @@ -53,70 +61,120 @@ func Provider() terraform.ResourceProvider { } } -type SDCConfig struct { - Account string - KeyMaterial string - KeyID string - URL string +type Config struct { + Account string + KeyMaterial string + KeyID string + URL string + InsecureSkipTLSVerify bool } -func (c SDCConfig) validate() error { +func (c Config) validate() error { var err *multierror.Error if c.URL == "" { - err = multierror.Append(err, fmt.Errorf("URL must be configured for the Triton provider")) - } - if c.KeyMaterial == "" { - err = multierror.Append(err, fmt.Errorf("Key Material must be configured for the Triton provider")) + err = multierror.Append(err, errors.New("URL must be configured for the Triton provider")) } if c.KeyID == "" { - err = multierror.Append(err, fmt.Errorf("Key ID must be configured for the Triton provider")) + err = multierror.Append(err, errors.New("Key ID must be configured for the Triton provider")) } if c.Account == "" { - err = multierror.Append(err, fmt.Errorf("Account must be configured for the Triton provider")) + err = multierror.Append(err, errors.New("Account must be configured for the Triton provider")) } return err.ErrorOrNil() } -func (c SDCConfig) getSDCClient() (*cloudapi.Client, error) { - userauth, err := auth.NewAuth(c.Account, c.KeyMaterial, "rsa-sha256") +func (c Config) getTritonClient() (*triton.Client, error) { + var signer authentication.Signer + var err error + if c.KeyMaterial == "" { + signer, err = authentication.NewSSHAgentSigner(c.KeyID, c.Account) + if err != nil { + return nil, errwrap.Wrapf("Error Creating SSH Agent Signer: {{err}}", err) + } + } else { + signer, err = authentication.NewPrivateKeySigner(c.KeyID, []byte(c.KeyMaterial), c.Account) + if err != nil { + return nil, errwrap.Wrapf("Error Creating SSH Private Key Signer: {{err}}", err) + } + } + + client, err := triton.NewClient(c.URL, c.Account, signer) if err != nil { - return nil, err + return nil, errwrap.Wrapf("Error Creating Triton Client: {{err}}", err) } - creds := &auth.Credentials{ - UserAuthentication: userauth, - SdcKeyId: c.KeyID, - SdcEndpoint: auth.Endpoint{URL: c.URL}, + if c.InsecureSkipTLSVerify { + client.InsecureSkipTLSVerify() } - client := cloudapi.New(client.NewClient( - c.URL, - cloudapi.DefaultAPIVersion, - creds, - log.New(os.Stderr, "", log.LstdFlags), - )) - return client, nil } func providerConfigure(d *schema.ResourceData) (interface{}, error) { - config := SDCConfig{ - Account: d.Get("account").(string), - URL: d.Get("url").(string), - KeyMaterial: d.Get("key_material").(string), - KeyID: d.Get("key_id").(string), + config := Config{ + Account: d.Get("account").(string), + URL: d.Get("url").(string), + KeyID: d.Get("key_id").(string), + + InsecureSkipTLSVerify: d.Get("insecure_skip_tls_verify").(bool), + } + + if keyMaterial, ok := d.GetOk("key_material"); ok { + config.KeyMaterial = keyMaterial.(string) } if err := config.validate(); err != nil { return nil, err } - client, err := config.getSDCClient() + client, err := config.getTritonClient() if err != nil { return nil, err } return client, nil } + +func resourceExists(resource interface{}, err error) (bool, error) { + if err != nil { + if triton.IsResourceNotFound(err) { + return false, nil + } + + return false, err + } + + return resource != nil, nil +} + +func stableMapHash(input map[string]string) string { + keys := make([]string, 0, len(input)) + for k := range input { + keys = append(keys, k) + } + sort.Strings(keys) + + hash := md5.New() + for _, key := range keys { + hash.Write([]byte(key)) + hash.Write([]byte(input[key])) + } + + return base64.StdEncoding.EncodeToString(hash.Sum([]byte{})) +} + +var fastResourceTimeout = &schema.ResourceTimeout{ + Create: schema.DefaultTimeout(1 * time.Minute), + Read: schema.DefaultTimeout(30 * time.Second), + Update: schema.DefaultTimeout(1 * time.Minute), + Delete: schema.DefaultTimeout(1 * time.Minute), +} + +var slowResourceTimeout = &schema.ResourceTimeout{ + Create: schema.DefaultTimeout(10 * time.Minute), + Read: schema.DefaultTimeout(30 * time.Second), + Update: schema.DefaultTimeout(10 * time.Minute), + Delete: schema.DefaultTimeout(10 * time.Minute), +} diff --git a/builtin/providers/triton/provider_test.go b/builtin/providers/triton/provider_test.go index 2aa283ec3..11b962aca 100644 --- a/builtin/providers/triton/provider_test.go +++ b/builtin/providers/triton/provider_test.go @@ -32,13 +32,13 @@ func testAccPreCheck(t *testing.T) { sdcURL := os.Getenv("SDC_URL") account := os.Getenv("SDC_ACCOUNT") keyID := os.Getenv("SDC_KEY_ID") - keyMaterial := os.Getenv("SDC_KEY_MATERIAL") if sdcURL == "" { sdcURL = "https://us-west-1.api.joyentcloud.com" } - if sdcURL == "" || account == "" || keyID == "" || keyMaterial == "" { - t.Fatal("SDC_ACCOUNT, SDC_KEY_ID and SDC_KEY_MATERIAL must be set for acceptance tests") + if sdcURL == "" || account == "" || keyID == "" { + t.Fatal("SDC_ACCOUNT and SDC_KEY_ID must be set for acceptance tests. To test with the SSH" + + " private key signer, SDC_KEY_MATERIAL must also be set.") } } diff --git a/builtin/providers/triton/resource_fabric.go b/builtin/providers/triton/resource_fabric.go index be85a4381..9b296d40a 100644 --- a/builtin/providers/triton/resource_fabric.go +++ b/builtin/providers/triton/resource_fabric.go @@ -1,10 +1,11 @@ package triton import ( + "context" "fmt" "github.com/hashicorp/terraform/helper/schema" - "github.com/joyent/gosdc/cloudapi" + "github.com/joyent/triton-go" ) func resourceFabric() *schema.Resource { @@ -16,74 +17,74 @@ func resourceFabric() *schema.Resource { Schema: map[string]*schema.Schema{ "name": { - Description: "network name", + Description: "Network name", Required: true, ForceNew: true, Type: schema.TypeString, }, "public": { - Description: "whether or not this is an RFC1918 network", + Description: "Whether or not this is an RFC1918 network", Computed: true, Type: schema.TypeBool, }, "fabric": { - Description: "whether or not this network is on a fabric", + Description: "Whether or not this network is on a fabric", Computed: true, Type: schema.TypeBool, }, "description": { - Description: "optional description of network", + Description: "Description of network", Optional: true, ForceNew: true, Type: schema.TypeString, }, "subnet": { - Description: "CIDR formatted string describing network", + Description: "CIDR formatted string describing network address space", Required: true, ForceNew: true, Type: schema.TypeString, }, "provision_start_ip": { - Description: "first IP on the network that can be assigned", + Description: "First IP on the network that can be assigned", Required: true, ForceNew: true, Type: schema.TypeString, }, "provision_end_ip": { - Description: "last assignable IP on the network", + Description: "Last assignable IP on the network", Required: true, ForceNew: true, Type: schema.TypeString, }, "gateway": { - Description: "optional gateway IP", + Description: "Gateway IP", Optional: true, ForceNew: true, Type: schema.TypeString, }, "resolvers": { - Description: "array of IP addresses for resolvers", + Description: "List of IP addresses for DNS resolvers", Optional: true, Computed: true, Type: schema.TypeList, Elem: &schema.Schema{Type: schema.TypeString}, }, "routes": { - Description: "map of CIDR block to Gateway IP address", + Description: "Map of CIDR block to Gateway IP address", Computed: true, Optional: true, ForceNew: true, Type: schema.TypeMap, }, "internet_nat": { - Description: "if a NAT zone is provisioned at Gateway IP address", + Description: "Whether or not a NAT zone is provisioned at the Gateway IP address", Computed: true, Optional: true, ForceNew: true, Type: schema.TypeBool, }, "vlan_id": { - Description: "VLAN network is on", + Description: "VLAN on which the network exists", Required: true, ForceNew: true, Type: schema.TypeInt, @@ -93,7 +94,7 @@ func resourceFabric() *schema.Resource { } func resourceFabricCreate(d *schema.ResourceData, meta interface{}) error { - client := meta.(*cloudapi.Client) + client := meta.(*triton.Client) var resolvers []string for _, resolver := range d.Get("resolvers").([]interface{}) { @@ -104,24 +105,23 @@ func resourceFabricCreate(d *schema.ResourceData, meta interface{}) error { for cidr, v := range d.Get("routes").(map[string]interface{}) { ip, ok := v.(string) if !ok { - return fmt.Errorf(`cannot use "%v" as an IP address`, v) + return fmt.Errorf(`Cannot use "%v" as an IP address`, v) } routes[cidr] = ip } - fabric, err := client.CreateFabricNetwork( - int16(d.Get("vlan_id").(int)), - cloudapi.CreateFabricNetworkOpts{ - Name: d.Get("name").(string), - Description: d.Get("description").(string), - Subnet: d.Get("subnet").(string), - ProvisionStartIp: d.Get("provision_start_ip").(string), - ProvisionEndIp: d.Get("provision_end_ip").(string), - Gateway: d.Get("gateway").(string), - Resolvers: resolvers, - Routes: routes, - InternetNAT: d.Get("internet_nat").(bool), - }, + fabric, err := client.Fabrics().CreateFabricNetwork(context.Background(), &triton.CreateFabricNetworkInput{ + FabricVLANID: d.Get("vlan_id").(int), + Name: d.Get("name").(string), + Description: d.Get("description").(string), + Subnet: d.Get("subnet").(string), + ProvisionStartIP: d.Get("provision_start_ip").(string), + ProvisionEndIP: d.Get("provision_end_ip").(string), + Gateway: d.Get("gateway").(string), + Resolvers: resolvers, + Routes: routes, + InternetNAT: d.Get("internet_nat").(bool), + }, ) if err != nil { return err @@ -129,26 +129,25 @@ func resourceFabricCreate(d *schema.ResourceData, meta interface{}) error { d.SetId(fabric.Id) - err = resourceFabricRead(d, meta) - if err != nil { - return err - } - - return nil + return resourceFabricRead(d, meta) } func resourceFabricExists(d *schema.ResourceData, meta interface{}) (bool, error) { - client := meta.(*cloudapi.Client) + client := meta.(*triton.Client) - fabric, err := client.GetFabricNetwork(int16(d.Get("vlan_id").(int)), d.Id()) - - return fabric != nil && err == nil, err + return resourceExists(client.Fabrics().GetFabricNetwork(context.Background(), &triton.GetFabricNetworkInput{ + FabricVLANID: d.Get("vlan_id").(int), + NetworkID: d.Id(), + })) } func resourceFabricRead(d *schema.ResourceData, meta interface{}) error { - client := meta.(*cloudapi.Client) + client := meta.(*triton.Client) - fabric, err := client.GetFabricNetwork(int16(d.Get("vlan_id").(int)), d.Id()) + fabric, err := client.Fabrics().GetFabricNetwork(context.Background(), &triton.GetFabricNetworkInput{ + FabricVLANID: d.Get("vlan_id").(int), + NetworkID: d.Id(), + }) if err != nil { return err } @@ -156,23 +155,25 @@ func resourceFabricRead(d *schema.ResourceData, meta interface{}) error { d.SetId(fabric.Id) d.Set("name", fabric.Name) d.Set("public", fabric.Public) - d.Set("public", fabric.Public) d.Set("fabric", fabric.Fabric) d.Set("description", fabric.Description) d.Set("subnet", fabric.Subnet) - d.Set("provision_start_ip", fabric.ProvisionStartIp) - d.Set("provision_end_ip", fabric.ProvisionEndIp) + d.Set("provision_start_ip", fabric.ProvisioningStartIP) + d.Set("provision_end_ip", fabric.ProvisioningEndIP) d.Set("gateway", fabric.Gateway) d.Set("resolvers", fabric.Resolvers) d.Set("routes", fabric.Routes) d.Set("internet_nat", fabric.InternetNAT) - d.Set("vlan_id", fabric.VLANId) + d.Set("vlan_id", d.Get("vlan_id").(int)) return nil } func resourceFabricDelete(d *schema.ResourceData, meta interface{}) error { - client := meta.(*cloudapi.Client) + client := meta.(*triton.Client) - return client.DeleteFabricNetwork(int16(d.Get("vlan_id").(int)), d.Id()) + return client.Fabrics().DeleteFabricNetwork(context.Background(), &triton.DeleteFabricNetworkInput{ + FabricVLANID: d.Get("vlan_id").(int), + NetworkID: d.Id(), + }) } diff --git a/builtin/providers/triton/resource_fabric_test.go b/builtin/providers/triton/resource_fabric_test.go index a6b1d8847..48198da23 100644 --- a/builtin/providers/triton/resource_fabric_test.go +++ b/builtin/providers/triton/resource_fabric_test.go @@ -1,6 +1,7 @@ package triton import ( + "context" "fmt" "strconv" "testing" @@ -9,19 +10,19 @@ import ( "github.com/hashicorp/terraform/helper/acctest" "github.com/hashicorp/terraform/helper/resource" "github.com/hashicorp/terraform/terraform" - "github.com/joyent/gosdc/cloudapi" + "github.com/joyent/triton-go" ) func TestAccTritonFabric_basic(t *testing.T) { fabricName := fmt.Sprintf("acctest-%d", acctest.RandInt()) - config := fmt.Sprintf(testAccTritonFabric_basic, fabricName) + config := fmt.Sprintf(testAccTritonFabric_basic, acctest.RandIntRange(3, 2049), fabricName, fabricName) resource.Test(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, CheckDestroy: testCheckTritonFabricDestroy, Steps: []resource.TestStep{ - resource.TestStep{ + { Config: config, Check: resource.ComposeTestCheckFunc( testCheckTritonFabricExists("triton_fabric.test"), @@ -37,62 +38,75 @@ func TestAccTritonFabric_basic(t *testing.T) { func testCheckTritonFabricExists(name string) resource.TestCheckFunc { return func(s *terraform.State) error { - // Ensure we have enough information in state to look up in API rs, ok := s.RootModule().Resources[name] if !ok { return fmt.Errorf("Not found: %s", name) } - conn := testAccProvider.Meta().(*cloudapi.Client) + conn := testAccProvider.Meta().(*triton.Client) - id, err := strconv.ParseInt(rs.Primary.Attributes["vlan_id"], 10, 16) + vlanID, err := strconv.Atoi(rs.Primary.Attributes["vlan_id"]) if err != nil { return err } - fabric, err := conn.GetFabricNetwork(int16(id), rs.Primary.ID) + exists, err := resourceExists(conn.Fabrics().GetFabricNetwork(context.Background(), &triton.GetFabricNetworkInput{ + FabricVLANID: vlanID, + NetworkID: rs.Primary.ID, + })) if err != nil { - return fmt.Errorf("Bad: Check Fabric Exists: %s", err) + return fmt.Errorf("Error: Check Fabric Exists: %s", err) } - if fabric == nil { - return fmt.Errorf("Bad: Fabric %q does not exist", rs.Primary.ID) + if exists { + return nil } - return nil + return fmt.Errorf("Error: Fabric %q (VLAN %d) Does Not Exist", rs.Primary.ID, vlanID) } } func testCheckTritonFabricDestroy(s *terraform.State) error { - conn := testAccProvider.Meta().(*cloudapi.Client) + conn := testAccProvider.Meta().(*triton.Client) for _, rs := range s.RootModule().Resources { if rs.Type != "triton_fabric" { continue } - id, err := strconv.ParseInt(rs.Primary.Attributes["vlan_id"], 10, 16) + vlanID, err := strconv.Atoi(rs.Primary.Attributes["vlan_id"]) if err != nil { return err } - fabric, err := conn.GetFabricNetwork(int16(id), rs.Primary.ID) + exists, err := resourceExists(conn.Fabrics().GetFabricNetwork(context.Background(), &triton.GetFabricNetworkInput{ + FabricVLANID: vlanID, + NetworkID: rs.Primary.ID, + })) if err != nil { return nil } - if fabric != nil { - return fmt.Errorf("Bad: Fabric %q still exists", rs.Primary.ID) + if exists { + return fmt.Errorf("Error: Fabric %q (VLAN %d) Still Exists", rs.Primary.ID, vlanID) } + + return nil } return nil } var testAccTritonFabric_basic = ` +resource "triton_vlan" "test" { + vlan_id = "%d" + name = "%s" + description = "testAccTritonFabric_basic" +} + resource "triton_fabric" "test" { name = "%s" description = "test network" - vlan_id = 2 # every DC seems to have a vlan 2 available + vlan_id = "${triton_vlan.test.id}" subnet = "10.0.0.0/22" gateway = "10.0.0.1" diff --git a/builtin/providers/triton/resource_firewall_rule.go b/builtin/providers/triton/resource_firewall_rule.go index af43dbaff..06abde0e2 100644 --- a/builtin/providers/triton/resource_firewall_rule.go +++ b/builtin/providers/triton/resource_firewall_rule.go @@ -1,9 +1,10 @@ package triton import ( + "context" + "github.com/hashicorp/terraform/helper/schema" - "github.com/joyent/gocommon/errors" - "github.com/joyent/gosdc/cloudapi" + "github.com/joyent/triton-go" ) func resourceFirewallRule() *schema.Resource { @@ -14,7 +15,7 @@ func resourceFirewallRule() *schema.Resource { Update: resourceFirewallRuleUpdate, Delete: resourceFirewallRuleDelete, Importer: &schema.ResourceImporter{ - State: resourceFirewallRuleImporter, + State: schema.ImportStatePassthrough, }, Schema: map[string]*schema.Schema{ @@ -29,67 +30,73 @@ func resourceFirewallRule() *schema.Resource { Optional: true, Default: false, }, + "description": { + Description: "Human-readable description of the rule", + Type: schema.TypeString, + Optional: true, + }, + "global": { + Description: "Indicates whether or not the rule is global", + Type: schema.TypeBool, + Computed: true, + }, }, } } func resourceFirewallRuleCreate(d *schema.ResourceData, meta interface{}) error { - client := meta.(*cloudapi.Client) + client := meta.(*triton.Client) - rule, err := client.CreateFirewallRule(cloudapi.CreateFwRuleOpts{ - Rule: d.Get("rule").(string), - Enabled: d.Get("enabled").(bool), + rule, err := client.Firewall().CreateFirewallRule(context.Background(), &triton.CreateFirewallRuleInput{ + Rule: d.Get("rule").(string), + Enabled: d.Get("enabled").(bool), + Description: d.Get("description").(string), }) if err != nil { return err } - d.SetId(rule.Id) + d.SetId(rule.ID) - err = resourceFirewallRuleRead(d, meta) - if err != nil { - return err - } - - return nil + return resourceFirewallRuleRead(d, meta) } func resourceFirewallRuleExists(d *schema.ResourceData, meta interface{}) (bool, error) { - client := meta.(*cloudapi.Client) + client := meta.(*triton.Client) - rule, err := client.GetFirewallRule(d.Id()) - if errors.IsResourceNotFound(err) { - return false, nil - } - - return rule != nil && err == nil, err + return resourceExists(client.Firewall().GetFirewallRule(context.Background(), &triton.GetFirewallRuleInput{ + ID: d.Id(), + })) } func resourceFirewallRuleRead(d *schema.ResourceData, meta interface{}) error { - client := meta.(*cloudapi.Client) + client := meta.(*triton.Client) - rule, err := client.GetFirewallRule(d.Id()) + rule, err := client.Firewall().GetFirewallRule(context.Background(), &triton.GetFirewallRuleInput{ + ID: d.Id(), + }) if err != nil { return err } - d.SetId(rule.Id) + d.SetId(rule.ID) d.Set("rule", rule.Rule) d.Set("enabled", rule.Enabled) + d.Set("global", rule.Global) + d.Set("description", rule.Description) return nil } func resourceFirewallRuleUpdate(d *schema.ResourceData, meta interface{}) error { - client := meta.(*cloudapi.Client) + client := meta.(*triton.Client) - _, err := client.UpdateFirewallRule( - d.Id(), - cloudapi.CreateFwRuleOpts{ - Rule: d.Get("rule").(string), - Enabled: d.Get("enabled").(bool), - }, - ) + _, err := client.Firewall().UpdateFirewallRule(context.Background(), &triton.UpdateFirewallRuleInput{ + ID: d.Id(), + Rule: d.Get("rule").(string), + Enabled: d.Get("enabled").(bool), + Description: d.Get("description").(string), + }) if err != nil { return err } @@ -98,15 +105,9 @@ func resourceFirewallRuleUpdate(d *schema.ResourceData, meta interface{}) error } func resourceFirewallRuleDelete(d *schema.ResourceData, meta interface{}) error { - client := meta.(*cloudapi.Client) + client := meta.(*triton.Client) - if err := client.DeleteFirewallRule(d.Id()); err != nil { - return err - } - - return nil -} - -func resourceFirewallRuleImporter(d *schema.ResourceData, meta interface{}) ([]*schema.ResourceData, error) { - return []*schema.ResourceData{d}, nil + return client.Firewall().DeleteFirewallRule(context.Background(), &triton.DeleteFirewallRuleInput{ + ID: d.Id(), + }) } diff --git a/builtin/providers/triton/resource_firewall_rule_test.go b/builtin/providers/triton/resource_firewall_rule_test.go index 2c3c8cdde..fbaa5d7ee 100644 --- a/builtin/providers/triton/resource_firewall_rule_test.go +++ b/builtin/providers/triton/resource_firewall_rule_test.go @@ -1,12 +1,13 @@ package triton import ( + "context" "fmt" "testing" "github.com/hashicorp/terraform/helper/resource" "github.com/hashicorp/terraform/terraform" - "github.com/joyent/gosdc/cloudapi" + "github.com/joyent/triton-go" ) func TestAccTritonFirewallRule_basic(t *testing.T) { @@ -17,7 +18,7 @@ func TestAccTritonFirewallRule_basic(t *testing.T) { Providers: testAccProviders, CheckDestroy: testCheckTritonFirewallRuleDestroy, Steps: []resource.TestStep{ - resource.TestStep{ + { Config: config, Check: resource.ComposeTestCheckFunc( testCheckTritonFirewallRuleExists("triton_firewall_rule.test"), @@ -36,20 +37,20 @@ func TestAccTritonFirewallRule_update(t *testing.T) { Providers: testAccProviders, CheckDestroy: testCheckTritonFirewallRuleDestroy, Steps: []resource.TestStep{ - resource.TestStep{ + { Config: preConfig, Check: resource.ComposeTestCheckFunc( testCheckTritonFirewallRuleExists("triton_firewall_rule.test"), - resource.TestCheckResourceAttr("triton_firewall_rule.test", "rule", "FROM any TO tag www ALLOW tcp PORT 80"), + resource.TestCheckResourceAttr("triton_firewall_rule.test", "rule", "FROM any TO tag \"www\" ALLOW tcp PORT 80"), resource.TestCheckResourceAttr("triton_firewall_rule.test", "enabled", "false"), ), }, - resource.TestStep{ + { Config: postConfig, Check: resource.ComposeTestCheckFunc( testCheckTritonFirewallRuleExists("triton_firewall_rule.test"), - resource.TestCheckResourceAttr("triton_firewall_rule.test", "rule", "FROM any TO tag www BLOCK tcp PORT 80"), + resource.TestCheckResourceAttr("triton_firewall_rule.test", "rule", "FROM any TO tag \"www\" BLOCK tcp PORT 80"), resource.TestCheckResourceAttr("triton_firewall_rule.test", "enabled", "true"), ), }, @@ -66,20 +67,20 @@ func TestAccTritonFirewallRule_enable(t *testing.T) { Providers: testAccProviders, CheckDestroy: testCheckTritonFirewallRuleDestroy, Steps: []resource.TestStep{ - resource.TestStep{ + { Config: preConfig, Check: resource.ComposeTestCheckFunc( testCheckTritonFirewallRuleExists("triton_firewall_rule.test"), - resource.TestCheckResourceAttr("triton_firewall_rule.test", "rule", "FROM any TO tag www ALLOW tcp PORT 80"), + resource.TestCheckResourceAttr("triton_firewall_rule.test", "rule", "FROM any TO tag \"www\" ALLOW tcp PORT 80"), resource.TestCheckResourceAttr("triton_firewall_rule.test", "enabled", "false"), ), }, - resource.TestStep{ + { Config: postConfig, Check: resource.ComposeTestCheckFunc( testCheckTritonFirewallRuleExists("triton_firewall_rule.test"), - resource.TestCheckResourceAttr("triton_firewall_rule.test", "rule", "FROM any TO tag www ALLOW tcp PORT 80"), + resource.TestCheckResourceAttr("triton_firewall_rule.test", "rule", "FROM any TO tag \"www\" ALLOW tcp PORT 80"), resource.TestCheckResourceAttr("triton_firewall_rule.test", "enabled", "true"), ), }, @@ -94,15 +95,19 @@ func testCheckTritonFirewallRuleExists(name string) resource.TestCheckFunc { if !ok { return fmt.Errorf("Not found: %s", name) } - conn := testAccProvider.Meta().(*cloudapi.Client) + conn := testAccProvider.Meta().(*triton.Client) - rule, err := conn.GetFirewallRule(rs.Primary.ID) - if err != nil { + resp, err := conn.Firewall().GetFirewallRule(context.Background(), &triton.GetFirewallRuleInput{ + ID: rs.Primary.ID, + }) + if err != nil && triton.IsResourceNotFound(err) { return fmt.Errorf("Bad: Check Firewall Rule Exists: %s", err) + } else if err != nil { + return err } - if rule == nil { - return fmt.Errorf("Bad: Firewall rule %q does not exist", rs.Primary.ID) + if resp == nil { + return fmt.Errorf("Bad: Firewall Rule %q does not exist", rs.Primary.ID) } return nil @@ -110,20 +115,24 @@ func testCheckTritonFirewallRuleExists(name string) resource.TestCheckFunc { } func testCheckTritonFirewallRuleDestroy(s *terraform.State) error { - conn := testAccProvider.Meta().(*cloudapi.Client) + conn := testAccProvider.Meta().(*triton.Client) for _, rs := range s.RootModule().Resources { if rs.Type != "triton_firewall_rule" { continue } - resp, err := conn.GetFirewallRule(rs.Primary.ID) - if err != nil { + resp, err := conn.Firewall().GetFirewallRule(context.Background(), &triton.GetFirewallRuleInput{ + ID: rs.Primary.ID, + }) + if triton.IsResourceNotFound(err) { return nil + } else if err != nil { + return err } if resp != nil { - return fmt.Errorf("Bad: Firewall rule %q still exists", rs.Primary.ID) + return fmt.Errorf("Bad: Firewall Rule %q still exists", rs.Primary.ID) } } @@ -132,21 +141,21 @@ func testCheckTritonFirewallRuleDestroy(s *terraform.State) error { var testAccTritonFirewallRule_basic = ` resource "triton_firewall_rule" "test" { - rule = "FROM any TO tag www ALLOW tcp PORT 80" - enabled = false + rule = "FROM any TO tag \"www\" ALLOW tcp PORT 80" + enabled = false } ` var testAccTritonFirewallRule_update = ` resource "triton_firewall_rule" "test" { - rule = "FROM any TO tag www BLOCK tcp PORT 80" + rule = "FROM any TO tag \"www\" BLOCK tcp PORT 80" enabled = true } ` var testAccTritonFirewallRule_enable = ` resource "triton_firewall_rule" "test" { - rule = "FROM any TO tag www ALLOW tcp PORT 80" + rule = "FROM any TO tag \"www\" ALLOW tcp PORT 80" enabled = true } ` diff --git a/builtin/providers/triton/resource_key.go b/builtin/providers/triton/resource_key.go index aa730a48d..21b13de8a 100644 --- a/builtin/providers/triton/resource_key.go +++ b/builtin/providers/triton/resource_key.go @@ -1,39 +1,35 @@ package triton import ( + "context" "errors" "strings" "github.com/hashicorp/terraform/helper/schema" - "github.com/joyent/gosdc/cloudapi" -) - -var ( - // ErrNoKeyComment will be returned when the key name cannot be generated from - // the key comment and is not otherwise specified. - ErrNoKeyComment = errors.New("no key comment found to use as a name (and none specified)") + "github.com/joyent/triton-go" ) func resourceKey() *schema.Resource { return &schema.Resource{ - Create: resourceKeyCreate, - Exists: resourceKeyExists, - Read: resourceKeyRead, - Delete: resourceKeyDelete, + Create: resourceKeyCreate, + Exists: resourceKeyExists, + Read: resourceKeyRead, + Delete: resourceKeyDelete, + Timeouts: fastResourceTimeout, Importer: &schema.ResourceImporter{ - State: resourceKeyImporter, + State: schema.ImportStatePassthrough, }, Schema: map[string]*schema.Schema{ - "name": &schema.Schema{ - Description: "name of this key (will be generated from the key comment, if not set and comment present)", + "name": { + Description: "Name of the key (generated from the key comment if not set)", Type: schema.TypeString, Optional: true, Computed: true, ForceNew: true, }, - "key": &schema.Schema{ - Description: "content of public key from disk", + "key": { + Description: "Content of public key from disk in OpenSSH format", Type: schema.TypeString, Required: true, ForceNew: true, @@ -43,18 +39,18 @@ func resourceKey() *schema.Resource { } func resourceKeyCreate(d *schema.ResourceData, meta interface{}) error { - client := meta.(*cloudapi.Client) + client := meta.(*triton.Client) - if d.Get("name").(string) == "" { + if keyName := d.Get("name").(string); keyName == "" { parts := strings.SplitN(d.Get("key").(string), " ", 3) if len(parts) == 3 { d.Set("name", parts[2]) } else { - return ErrNoKeyComment + return errors.New("No key name specified, and key material has no comment") } } - _, err := client.CreateKey(cloudapi.CreateKeyOpts{ + _, err := client.Keys().CreateKey(context.Background(), &triton.CreateKeyInput{ Name: d.Get("name").(string), Key: d.Get("key").(string), }) @@ -64,35 +60,28 @@ func resourceKeyCreate(d *schema.ResourceData, meta interface{}) error { d.SetId(d.Get("name").(string)) - err = resourceKeyRead(d, meta) - if err != nil { - return err - } - - return nil + return resourceKeyRead(d, meta) } func resourceKeyExists(d *schema.ResourceData, meta interface{}) (bool, error) { - client := meta.(*cloudapi.Client) + client := meta.(*triton.Client) - keys, err := client.ListKeys() + _, err := client.Keys().GetKey(context.Background(), &triton.GetKeyInput{ + KeyName: d.Id(), + }) if err != nil { return false, err } - for _, key := range keys { - if key.Name == d.Id() { - return true, nil - } - } - - return false, nil + return true, nil } func resourceKeyRead(d *schema.ResourceData, meta interface{}) error { - client := meta.(*cloudapi.Client) + client := meta.(*triton.Client) - key, err := client.GetKey(d.Id()) + key, err := client.Keys().GetKey(context.Background(), &triton.GetKeyInput{ + KeyName: d.Id(), + }) if err != nil { return err } @@ -104,15 +93,9 @@ func resourceKeyRead(d *schema.ResourceData, meta interface{}) error { } func resourceKeyDelete(d *schema.ResourceData, meta interface{}) error { - client := meta.(*cloudapi.Client) + client := meta.(*triton.Client) - if err := client.DeleteKey(d.Get("name").(string)); err != nil { - return err - } - - return nil -} - -func resourceKeyImporter(d *schema.ResourceData, meta interface{}) ([]*schema.ResourceData, error) { - return []*schema.ResourceData{d}, nil + return client.Keys().DeleteKey(context.Background(), &triton.DeleteKeyInput{ + KeyName: d.Id(), + }) } diff --git a/builtin/providers/triton/resource_key_test.go b/builtin/providers/triton/resource_key_test.go index 1d1bf79a2..ae97eb25b 100644 --- a/builtin/providers/triton/resource_key_test.go +++ b/builtin/providers/triton/resource_key_test.go @@ -1,6 +1,7 @@ package triton import ( + "context" "fmt" "testing" "time" @@ -8,22 +9,57 @@ import ( "github.com/hashicorp/terraform/helper/acctest" "github.com/hashicorp/terraform/helper/resource" "github.com/hashicorp/terraform/terraform" - "github.com/joyent/gosdc/cloudapi" + "github.com/joyent/triton-go" ) func TestAccTritonKey_basic(t *testing.T) { keyName := fmt.Sprintf("acctest-%d", acctest.RandInt()) - config := fmt.Sprintf(testAccTritonKey_basic, keyName, testAccTritonKey_basicMaterial) + publicKeyMaterial, _, err := acctest.RandSSHKeyPair("TestAccTritonKey_basic@terraform") + if err != nil { + t.Fatalf("Cannot generate test SSH key pair: %s", err) + } + config := testAccTritonKey_basic(keyName, publicKeyMaterial) resource.Test(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, CheckDestroy: testCheckTritonKeyDestroy, Steps: []resource.TestStep{ - resource.TestStep{ + { Config: config, Check: resource.ComposeTestCheckFunc( testCheckTritonKeyExists("triton_key.test"), + resource.TestCheckResourceAttr("triton_key.test", "name", keyName), + resource.TestCheckResourceAttr("triton_key.test", "key", publicKeyMaterial), + func(*terraform.State) error { + time.Sleep(10 * time.Second) + return nil + }, + ), + }, + }, + }) +} + +func TestAccTritonKey_noKeyName(t *testing.T) { + keyComment := fmt.Sprintf("acctest_%d@terraform", acctest.RandInt()) + keyMaterial, _, err := acctest.RandSSHKeyPair(keyComment) + if err != nil { + t.Fatalf("Cannot generate test SSH key pair: %s", err) + } + config := testAccTritonKey_noKeyName(keyMaterial) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testCheckTritonKeyDestroy, + Steps: []resource.TestStep{ + { + Config: config, + Check: resource.ComposeTestCheckFunc( + testCheckTritonKeyExists("triton_key.test"), + resource.TestCheckResourceAttr("triton_key.test", "name", keyComment), + resource.TestCheckResourceAttr("triton_key.test", "key", keyMaterial), func(*terraform.State) error { time.Sleep(10 * time.Second) return nil @@ -41,14 +77,16 @@ func testCheckTritonKeyExists(name string) resource.TestCheckFunc { if !ok { return fmt.Errorf("Not found: %s", name) } - conn := testAccProvider.Meta().(*cloudapi.Client) + conn := testAccProvider.Meta().(*triton.Client) - rule, err := conn.GetKey(rs.Primary.ID) + key, err := conn.Keys().GetKey(context.Background(), &triton.GetKeyInput{ + KeyName: rs.Primary.ID, + }) if err != nil { return fmt.Errorf("Bad: Check Key Exists: %s", err) } - if rule == nil { + if key == nil { return fmt.Errorf("Bad: Key %q does not exist", rs.Primary.ID) } @@ -57,7 +95,7 @@ func testCheckTritonKeyExists(name string) resource.TestCheckFunc { } func testCheckTritonKeyDestroy(s *terraform.State) error { - conn := testAccProvider.Meta().(*cloudapi.Client) + conn := testAccProvider.Meta().(*triton.Client) return resource.Retry(1*time.Minute, func() *resource.RetryError { for _, rs := range s.RootModule().Resources { @@ -65,12 +103,14 @@ func testCheckTritonKeyDestroy(s *terraform.State) error { continue } - resp, err := conn.GetKey(rs.Primary.ID) + key, err := conn.Keys().GetKey(context.Background(), &triton.GetKeyInput{ + KeyName: rs.Primary.ID, + }) if err != nil { return nil } - if resp != nil { + if key != nil { return resource.RetryableError(fmt.Errorf("Bad: Key %q still exists", rs.Primary.ID)) } } @@ -79,11 +119,17 @@ func testCheckTritonKeyDestroy(s *terraform.State) error { }) } -var testAccTritonKey_basic = ` -resource "triton_key" "test" { - name = "%s" - key = "%s" +var testAccTritonKey_basic = func(keyName string, keyMaterial string) string { + return fmt.Sprintf(`resource "triton_key" "test" { + name = "%s" + key = "%s" + } + `, keyName, keyMaterial) } -` -const testAccTritonKey_basicMaterial = `ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDL18KJIe8N7FxcgOMtabo10qZEDyYUSlOpsh/EYrugQCQHMKuNytog1lhFNZNk4LGNAz5L8/btG9+/axY/PfundbjR3SXt0hupAGQIVHuygWTr7foj5iGhckrEM+r3eMCXqoCnIFLhDZLDcq/zN2MxNbqDKcWSYmc8ul9dZWuiQpKOL+0nNXjhYA8Ewu+07kVAtsZD0WfvnAUjxmYb3rB15eBWk7gLxHrOPfZpeDSvOOX2bmzikpLn+L5NKrJsLrzO6hU/rpxD4OTHLULcsnIts3lYH8hShU8uY5ry94PBzdix++se3pUGvNSe967fKlHw3Ymh9nE/LJDQnzTNyFMj James@jn-mpb13` +var testAccTritonKey_noKeyName = func(keyMaterial string) string { + return fmt.Sprintf(`resource "triton_key" "test" { + key = "%s" + } + `, keyMaterial) +} diff --git a/builtin/providers/triton/resource_machine.go b/builtin/providers/triton/resource_machine.go index 2523dd5d0..32505746d 100644 --- a/builtin/providers/triton/resource_machine.go +++ b/builtin/providers/triton/resource_machine.go @@ -1,23 +1,22 @@ package triton import ( + "context" "fmt" - "reflect" "regexp" "time" "github.com/hashicorp/terraform/helper/hashcode" + "github.com/hashicorp/terraform/helper/resource" "github.com/hashicorp/terraform/helper/schema" - "github.com/joyent/gosdc/cloudapi" + "github.com/joyent/triton-go" ) var ( machineStateRunning = "running" - machineStateStopped = "stopped" machineStateDeleted = "deleted" - machineStateChangeTimeout = 10 * time.Minute - machineStateChangeCheckInterval = 10 * time.Second + machineStateChangeTimeout = 10 * time.Minute resourceMachineMetadataKeys = map[string]string{ // semantics: "schema_name": "metadata_name" @@ -25,55 +24,52 @@ var ( "user_script": "user-script", "user_data": "user-data", "administrator_pw": "administrator-pw", + "cloud_config": "cloud-init:user-data", } ) func resourceMachine() *schema.Resource { return &schema.Resource{ - Create: resourceMachineCreate, - Exists: resourceMachineExists, - Read: resourceMachineRead, - Update: resourceMachineUpdate, - Delete: resourceMachineDelete, + Create: resourceMachineCreate, + Exists: resourceMachineExists, + Read: resourceMachineRead, + Update: resourceMachineUpdate, + Delete: resourceMachineDelete, + Timeouts: slowResourceTimeout, Importer: &schema.ResourceImporter{ - State: resourceMachineImporter, + State: schema.ImportStatePassthrough, }, Schema: map[string]*schema.Schema{ "name": { - Description: "friendly name", + Description: "Friendly name for machine", Type: schema.TypeString, Optional: true, Computed: true, ValidateFunc: resourceMachineValidateName, }, "type": { - Description: "machine type (smartmachine or virtualmachine)", - Type: schema.TypeString, - Computed: true, - }, - "state": { - Description: "current state of the machine", + Description: "Machine type (smartmachine or virtualmachine)", Type: schema.TypeString, Computed: true, }, "dataset": { - Description: "dataset URN the machine was provisioned with", + Description: "Dataset URN with which the machine was provisioned", Type: schema.TypeString, Computed: true, }, "memory": { - Description: "amount of memory the machine has (in Mb)", + Description: "Amount of memory allocated to the machine (in Mb)", Type: schema.TypeInt, Computed: true, }, "disk": { - Description: "amount of disk the machine has (in Gb)", + Description: "Amount of disk allocated to the machine (in Gb)", Type: schema.TypeInt, Computed: true, }, "ips": { - Description: "IP addresses the machine has", + Description: "IP addresses assigned to the machine", Type: schema.TypeList, Computed: true, Elem: &schema.Schema{ @@ -81,39 +77,38 @@ func resourceMachine() *schema.Resource { }, }, "tags": { - Description: "machine tags", + Description: "Machine tags", Type: schema.TypeMap, Optional: true, }, "created": { - Description: "when the machine was created", + Description: "When the machine was created", Type: schema.TypeString, Computed: true, }, "updated": { - Description: "when the machine was update", + Description: "When the machine was updated", Type: schema.TypeString, Computed: true, }, "package": { - Description: "name of the package to use on provisioning", + Description: "The package for use for provisioning", Type: schema.TypeString, Required: true, }, "image": { - Description: "image UUID", + Description: "UUID of the image", Type: schema.TypeString, Required: true, ForceNew: true, - // TODO: validate that the UUID is valid }, "primaryip": { - Description: "the primary (public) IP address for the machine", + Description: "Primary (public) IP address for the machine", Type: schema.TypeString, Computed: true, }, "nic": { - Description: "network interface", + Description: "Network interface", Type: schema.TypeSet, Computed: true, Optional: true, @@ -148,27 +143,27 @@ func resourceMachine() *schema.Resource { Computed: true, Type: schema.TypeString, }, - "state": { - Description: "describes the state of the NIC (e.g. provisioning, running, or stopped)", - Computed: true, + "network": { + Description: "ID of the network to which the NIC is attached", + Required: true, Type: schema.TypeString, }, - "network": { - Description: "Network ID this NIC is attached to", - Required: true, + "state": { + Description: "Provisioning state of the NIC", + Computed: true, Type: schema.TypeString, }, }, }, }, "firewall_enabled": { - Description: "enable firewall for this machine", + Description: "Whether to enable the firewall for this machine", Type: schema.TypeBool, Optional: true, Default: false, }, "domain_names": { - Description: "list of domain names from Triton's CNS", + Description: "List of domain names from Triton CNS", Type: schema.TypeList, Computed: true, Elem: &schema.Schema{ @@ -178,25 +173,31 @@ func resourceMachine() *schema.Resource { // computed resources from metadata "root_authorized_keys": { - Description: "authorized keys for the root user on this machine", + Description: "Authorized keys for the root user on this machine", Type: schema.TypeString, Optional: true, Computed: true, }, "user_script": { - Description: "user script to run on boot (every boot on SmartMachines)", + Description: "User script to run on boot (every boot on SmartMachines)", Type: schema.TypeString, Optional: true, Computed: true, }, - "user_data": { + "cloud_config": { Description: "copied to machine on boot", Type: schema.TypeString, Optional: true, Computed: true, }, + "user_data": { + Description: "Data copied to machine on boot", + Type: schema.TypeString, + Optional: true, + Computed: true, + }, "administrator_pw": { - Description: "administrator's initial password (Windows only)", + Description: "Administrator's initial password (Windows only)", Type: schema.TypeString, Optional: true, Computed: true, @@ -204,7 +205,7 @@ func resourceMachine() *schema.Resource { // deprecated fields "networks": { - Description: "desired network IDs", + Description: "Desired network IDs", Type: schema.TypeList, Optional: true, Computed: true, @@ -218,7 +219,7 @@ func resourceMachine() *schema.Resource { } func resourceMachineCreate(d *schema.ResourceData, meta interface{}) error { - client := meta.(*cloudapi.Client) + client := meta.(*triton.Client) var networks []string for _, network := range d.Get("networks").([]interface{}) { @@ -242,7 +243,7 @@ func resourceMachineCreate(d *schema.ResourceData, meta interface{}) error { tags[k] = v.(string) } - machine, err := client.CreateMachine(cloudapi.CreateMachineOpts{ + machine, err := client.Machines().CreateMachine(context.Background(), &triton.CreateMachineInput{ Name: d.Get("name").(string), Package: d.Get("package").(string), Image: d.Get("image").(string), @@ -255,47 +256,64 @@ func resourceMachineCreate(d *schema.ResourceData, meta interface{}) error { return err } - err = waitForMachineState(client, machine.Id, machineStateRunning, machineStateChangeTimeout) + d.SetId(machine.ID) + stateConf := &resource.StateChangeConf{ + Target: []string{fmt.Sprintf(machineStateRunning)}, + Refresh: func() (interface{}, string, error) { + getResp, err := client.Machines().GetMachine(context.Background(), &triton.GetMachineInput{ + ID: d.Id(), + }) + if err != nil { + return nil, "", err + } + + return getResp, getResp.State, nil + }, + Timeout: machineStateChangeTimeout, + MinTimeout: 3 * time.Second, + } + _, err = stateConf.WaitForState() + if err != nil { + return err + } if err != nil { return err } // refresh state after it provisions - d.SetId(machine.Id) - err = resourceMachineRead(d, meta) - if err != nil { - return err - } - - return nil + return resourceMachineRead(d, meta) } func resourceMachineExists(d *schema.ResourceData, meta interface{}) (bool, error) { - client := meta.(*cloudapi.Client) + client := meta.(*triton.Client) - machine, err := client.GetMachine(d.Id()) - - return machine != nil && err == nil, err + return resourceExists(client.Machines().GetMachine(context.Background(), &triton.GetMachineInput{ + ID: d.Id(), + })) } func resourceMachineRead(d *schema.ResourceData, meta interface{}) error { - client := meta.(*cloudapi.Client) + client := meta.(*triton.Client) - machine, err := client.GetMachine(d.Id()) + machine, err := client.Machines().GetMachine(context.Background(), &triton.GetMachineInput{ + ID: d.Id(), + }) if err != nil { return err } - nics, err := client.ListNICs(d.Id()) + nics, err := client.Machines().ListNICs(context.Background(), &triton.ListNICsInput{ + MachineID: d.Id(), + }) if err != nil { return err } - d.SetId(machine.Id) d.Set("name", machine.Name) d.Set("type", machine.Type) d.Set("state", machine.State) - d.Set("dataset", machine.Dataset) + d.Set("dataset", machine.Image) + d.Set("image", machine.Image) d.Set("memory", machine.Memory) d.Set("disk", machine.Disk) d.Set("ips", machine.IPs) @@ -340,23 +358,40 @@ func resourceMachineRead(d *schema.ResourceData, meta interface{}) error { } func resourceMachineUpdate(d *schema.ResourceData, meta interface{}) error { - client := meta.(*cloudapi.Client) + client := meta.(*triton.Client) d.Partial(true) if d.HasChange("name") { - if err := client.RenameMachine(d.Id(), d.Get("name").(string)); err != nil { + oldNameInterface, newNameInterface := d.GetChange("name") + oldName := oldNameInterface.(string) + newName := newNameInterface.(string) + + err := client.Machines().RenameMachine(context.Background(), &triton.RenameMachineInput{ + ID: d.Id(), + Name: newName, + }) + if err != nil { return err } - err := waitFor( - func() (bool, error) { - machine, err := client.GetMachine(d.Id()) - return machine.Name == d.Get("name").(string), err + stateConf := &resource.StateChangeConf{ + Pending: []string{oldName}, + Target: []string{newName}, + Refresh: func() (interface{}, string, error) { + getResp, err := client.Machines().GetMachine(context.Background(), &triton.GetMachineInput{ + ID: d.Id(), + }) + if err != nil { + return nil, "", err + } + + return getResp, getResp.Name, nil }, - machineStateChangeCheckInterval, - 1*time.Minute, - ) + Timeout: machineStateChangeTimeout, + MinTimeout: 3 * time.Second, + } + _, err = stateConf.WaitForState() if err != nil { return err } @@ -372,22 +407,36 @@ func resourceMachineUpdate(d *schema.ResourceData, meta interface{}) error { var err error if len(tags) == 0 { - err = client.DeleteMachineTags(d.Id()) + err = client.Machines().DeleteMachineTags(context.Background(), &triton.DeleteMachineTagsInput{ + ID: d.Id(), + }) } else { - _, err = client.ReplaceMachineTags(d.Id(), tags) + err = client.Machines().ReplaceMachineTags(context.Background(), &triton.ReplaceMachineTagsInput{ + ID: d.Id(), + Tags: tags, + }) } if err != nil { return err } - err = waitFor( - func() (bool, error) { - machine, err := client.GetMachine(d.Id()) - return reflect.DeepEqual(machine.Tags, tags), err + expectedTagsMD5 := stableMapHash(tags) + stateConf := &resource.StateChangeConf{ + Target: []string{expectedTagsMD5}, + Refresh: func() (interface{}, string, error) { + getResp, err := client.Machines().GetMachine(context.Background(), &triton.GetMachineInput{ + ID: d.Id(), + }) + if err != nil { + return nil, "", err + } + + return getResp, stableMapHash(getResp.Tags), nil }, - machineStateChangeCheckInterval, - 1*time.Minute, - ) + Timeout: machineStateChangeTimeout, + MinTimeout: 3 * time.Second, + } + _, err = stateConf.WaitForState() if err != nil { return err } @@ -396,18 +445,32 @@ func resourceMachineUpdate(d *schema.ResourceData, meta interface{}) error { } if d.HasChange("package") { - if err := client.ResizeMachine(d.Id(), d.Get("package").(string)); err != nil { + newPackage := d.Get("package").(string) + + err := client.Machines().ResizeMachine(context.Background(), &triton.ResizeMachineInput{ + ID: d.Id(), + Package: newPackage, + }) + if err != nil { return err } - err := waitFor( - func() (bool, error) { - machine, err := client.GetMachine(d.Id()) - return machine.Package == d.Get("package").(string) && machine.State == machineStateRunning, err + stateConf := &resource.StateChangeConf{ + Target: []string{fmt.Sprintf("%s@%s", newPackage, "running")}, + Refresh: func() (interface{}, string, error) { + getResp, err := client.Machines().GetMachine(context.Background(), &triton.GetMachineInput{ + ID: d.Id(), + }) + if err != nil { + return nil, "", err + } + + return getResp, fmt.Sprintf("%s@%s", getResp.Package, getResp.State), nil }, - machineStateChangeCheckInterval, - machineStateChangeTimeout, - ) + Timeout: machineStateChangeTimeout, + MinTimeout: 3 * time.Second, + } + _, err = stateConf.WaitForState() if err != nil { return err } @@ -416,25 +479,38 @@ func resourceMachineUpdate(d *schema.ResourceData, meta interface{}) error { } if d.HasChange("firewall_enabled") { + enable := d.Get("firewall_enabled").(bool) + var err error - if d.Get("firewall_enabled").(bool) { - err = client.EnableFirewallMachine(d.Id()) + if enable { + err = client.Machines().EnableMachineFirewall(context.Background(), &triton.EnableMachineFirewallInput{ + ID: d.Id(), + }) } else { - err = client.DisableFirewallMachine(d.Id()) + err = client.Machines().DisableMachineFirewall(context.Background(), &triton.DisableMachineFirewallInput{ + ID: d.Id(), + }) } if err != nil { return err } - err = waitFor( - func() (bool, error) { - machine, err := client.GetMachine(d.Id()) - return machine.FirewallEnabled == d.Get("firewall_enabled").(bool), err - }, - machineStateChangeCheckInterval, - machineStateChangeTimeout, - ) + stateConf := &resource.StateChangeConf{ + Target: []string{fmt.Sprintf("%t", enable)}, + Refresh: func() (interface{}, string, error) { + getResp, err := client.Machines().GetMachine(context.Background(), &triton.GetMachineInput{ + ID: d.Id(), + }) + if err != nil { + return nil, "", err + } + return getResp, fmt.Sprintf("%t", getResp.FirewallEnabled), nil + }, + Timeout: machineStateChangeTimeout, + MinTimeout: 3 * time.Second, + } + _, err = stateConf.WaitForState() if err != nil { return err } @@ -452,24 +528,24 @@ func resourceMachineUpdate(d *schema.ResourceData, meta interface{}) error { } oldNICs := o.(*schema.Set) - newNICs := o.(*schema.Set) + newNICs := n.(*schema.Set) - // add new NICs that are not in old NICs for _, nicI := range newNICs.Difference(oldNICs).List() { nic := nicI.(map[string]interface{}) - fmt.Printf("adding %+v\n", nic) - _, err := client.AddNIC(d.Id(), nic["network"].(string)) - if err != nil { + if _, err := client.Machines().AddNIC(context.Background(), &triton.AddNICInput{ + MachineID: d.Id(), + Network: nic["network"].(string), + }); err != nil { return err } } - // remove old NICs that are not in new NICs for _, nicI := range oldNICs.Difference(newNICs).List() { nic := nicI.(map[string]interface{}) - fmt.Printf("removing %+v\n", nic) - err := client.RemoveNIC(d.Id(), nic["mac"].(string)) - if err != nil { + if err := client.Machines().RemoveNIC(context.Background(), &triton.RemoveNICInput{ + MachineID: d.Id(), + MAC: nic["mac"].(string), + }); err != nil { return err } } @@ -477,7 +553,6 @@ func resourceMachineUpdate(d *schema.ResourceData, meta interface{}) error { d.SetPartial("nic") } - // metadata stuff metadata := map[string]string{} for schemaName, metadataKey := range resourceMachineMetadataKeys { if d.HasChange(schemaName) { @@ -485,24 +560,35 @@ func resourceMachineUpdate(d *schema.ResourceData, meta interface{}) error { } } if len(metadata) > 0 { - _, err := client.UpdateMachineMetadata(d.Id(), metadata) - if err != nil { + if _, err := client.Machines().UpdateMachineMetadata(context.Background(), &triton.UpdateMachineMetadataInput{ + ID: d.Id(), + Metadata: metadata, + }); err != nil { return err } - err = waitFor( - func() (bool, error) { - machine, err := client.GetMachine(d.Id()) + stateConf := &resource.StateChangeConf{ + Target: []string{"converged"}, + Refresh: func() (interface{}, string, error) { + getResp, err := client.Machines().GetMachine(context.Background(), &triton.GetMachineInput{ + ID: d.Id(), + }) + if err != nil { + return nil, "", err + } + for k, v := range metadata { - if provider_v, ok := machine.Metadata[k]; !ok || v != provider_v { - return false, err + if upstream, ok := getResp.Metadata[k]; !ok || v != upstream { + return getResp, "converging", nil } } - return true, err + + return getResp, "converged", nil }, - machineStateChangeCheckInterval, - 1*time.Minute, - ) + Timeout: machineStateChangeTimeout, + MinTimeout: 3 * time.Second, + } + _, err := stateConf.WaitForState() if err != nil { return err } @@ -516,57 +602,43 @@ func resourceMachineUpdate(d *schema.ResourceData, meta interface{}) error { d.Partial(false) - err := resourceMachineRead(d, meta) - if err != nil { - return err - } - - return nil + return resourceMachineRead(d, meta) } func resourceMachineDelete(d *schema.ResourceData, meta interface{}) error { - client := meta.(*cloudapi.Client) + client := meta.(*triton.Client) - state, err := readMachineState(client, d.Id()) - if state != machineStateStopped { - err = client.StopMachine(d.Id()) - if err != nil { - return err - } - - waitForMachineState(client, d.Id(), machineStateStopped, machineStateChangeTimeout) - } - - err = client.DeleteMachine(d.Id()) + err := client.Machines().DeleteMachine(context.Background(), &triton.DeleteMachineInput{ + ID: d.Id(), + }) if err != nil { return err } - waitForMachineState(client, d.Id(), machineStateDeleted, machineStateChangeTimeout) - return nil -} + stateConf := &resource.StateChangeConf{ + Target: []string{machineStateDeleted}, + Refresh: func() (interface{}, string, error) { + getResp, err := client.Machines().GetMachine(context.Background(), &triton.GetMachineInput{ + ID: d.Id(), + }) + if err != nil { + if triton.IsResourceNotFound(err) { + return getResp, "deleted", nil + } + return nil, "", err + } -func readMachineState(api *cloudapi.Client, id string) (string, error) { - machine, err := api.GetMachine(id) + return getResp, getResp.State, nil + }, + Timeout: machineStateChangeTimeout, + MinTimeout: 3 * time.Second, + } + _, err = stateConf.WaitForState() if err != nil { - return "", err + return err } - return machine.State, nil -} - -// waitForMachineState waits for a machine to be in the desired state (waiting -// some seconds between each poll). If it doesn't reach the state within the -// duration specified in `timeout`, it returns ErrMachineStateTimeout. -func waitForMachineState(api *cloudapi.Client, id, state string, timeout time.Duration) error { - return waitFor( - func() (bool, error) { - currentState, err := readMachineState(api, id) - return currentState == state, err - }, - machineStateChangeCheckInterval, - machineStateChangeTimeout, - ) + return nil } func resourceMachineValidateName(value interface{}, name string) (warnings []string, errors []error) { @@ -580,7 +652,3 @@ func resourceMachineValidateName(value interface{}, name string) (warnings []str return warnings, errors } - -func resourceMachineImporter(d *schema.ResourceData, meta interface{}) ([]*schema.ResourceData, error) { - return []*schema.ResourceData{d}, nil -} diff --git a/builtin/providers/triton/resource_machine_test.go b/builtin/providers/triton/resource_machine_test.go index f6f43bb77..8c49f739e 100644 --- a/builtin/providers/triton/resource_machine_test.go +++ b/builtin/providers/triton/resource_machine_test.go @@ -1,15 +1,18 @@ package triton import ( + "context" "fmt" + "log" "regexp" "testing" "time" + "github.com/davecgh/go-spew/spew" "github.com/hashicorp/terraform/helper/acctest" "github.com/hashicorp/terraform/helper/resource" "github.com/hashicorp/terraform/terraform" - "github.com/joyent/gosdc/cloudapi" + "github.com/joyent/triton-go" ) func TestAccTritonMachine_basic(t *testing.T) { @@ -21,7 +24,7 @@ func TestAccTritonMachine_basic(t *testing.T) { Providers: testAccProviders, CheckDestroy: testCheckTritonMachineDestroy, Steps: []resource.TestStep{ - resource.TestStep{ + { Config: config, Check: resource.ComposeTestCheckFunc( testCheckTritonMachineExists("triton_machine.test"), @@ -44,20 +47,16 @@ func TestAccTritonMachine_dns(t *testing.T) { Providers: testAccProviders, CheckDestroy: testCheckTritonMachineDestroy, Steps: []resource.TestStep{ - resource.TestStep{ + { Config: dns_output, Check: resource.ComposeTestCheckFunc( testCheckTritonMachineExists("triton_machine.test"), - func(*terraform.State) error { + func(state *terraform.State) error { time.Sleep(10 * time.Second) + log.Printf("[DEBUG] %s", spew.Sdump(state)) return nil }, - ), - }, - resource.TestStep{ - Config: dns_output, - Check: resource.TestMatchOutput( - "domain_names", regexp.MustCompile(".*acctest-.*"), + resource.TestMatchOutput("domain_names", regexp.MustCompile(".*acctest-.*")), ), }, }, @@ -66,14 +65,14 @@ func TestAccTritonMachine_dns(t *testing.T) { func TestAccTritonMachine_nic(t *testing.T) { machineName := fmt.Sprintf("acctest-%d", acctest.RandInt()) - config := fmt.Sprintf(testAccTritonMachine_withnic, machineName, machineName) + config := testAccTritonMachine_singleNIC(machineName, acctest.RandIntRange(1024, 2048), acctest.RandIntRange(0, 256)) resource.Test(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, CheckDestroy: testCheckTritonMachineDestroy, Steps: []resource.TestStep{ - resource.TestStep{ + { Config: config, Check: resource.ComposeTestCheckFunc( testCheckTritonMachineExists("triton_machine.test"), @@ -88,32 +87,34 @@ func TestAccTritonMachine_nic(t *testing.T) { }) } -func TestAccTritonMachine_addnic(t *testing.T) { +func TestAccTritonMachine_addNIC(t *testing.T) { machineName := fmt.Sprintf("acctest-%d", acctest.RandInt()) - without := fmt.Sprintf(testAccTritonMachine_withoutnic, machineName, machineName) - with := fmt.Sprintf(testAccTritonMachine_withnic, machineName, machineName) + vlanNumber := acctest.RandIntRange(1024, 2048) + subnetNumber := acctest.RandIntRange(0, 256) + + singleNICConfig := testAccTritonMachine_singleNIC(machineName, vlanNumber, subnetNumber) + dualNICConfig := testAccTritonMachine_dualNIC(machineName, vlanNumber, subnetNumber) resource.Test(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, CheckDestroy: testCheckTritonMachineDestroy, Steps: []resource.TestStep{ - resource.TestStep{ - Config: without, + { + Config: singleNICConfig, Check: resource.ComposeTestCheckFunc( testCheckTritonMachineExists("triton_machine.test"), func(*terraform.State) error { time.Sleep(10 * time.Second) return nil }, - testCheckTritonMachineHasNoFabric("triton_machine.test", "triton_fabric.test"), ), }, - resource.TestStep{ - Config: with, + { + Config: dualNICConfig, Check: resource.ComposeTestCheckFunc( testCheckTritonMachineExists("triton_machine.test"), - testCheckTritonMachineHasFabric("triton_machine.test", "triton_fabric.test"), + testCheckTritonMachineHasFabric("triton_machine.test", "triton_fabric.test_add"), ), }, }, @@ -127,14 +128,16 @@ func testCheckTritonMachineExists(name string) resource.TestCheckFunc { if !ok { return fmt.Errorf("Not found: %s", name) } - conn := testAccProvider.Meta().(*cloudapi.Client) + conn := testAccProvider.Meta().(*triton.Client) - rule, err := conn.GetMachine(rs.Primary.ID) + machine, err := conn.Machines().GetMachine(context.Background(), &triton.GetMachineInput{ + ID: rs.Primary.ID, + }) if err != nil { return fmt.Errorf("Bad: Check Machine Exists: %s", err) } - if rule == nil { + if machine == nil { return fmt.Errorf("Bad: Machine %q does not exist", rs.Primary.ID) } @@ -154,9 +157,11 @@ func testCheckTritonMachineHasFabric(name, fabricName string) resource.TestCheck if !ok { return fmt.Errorf("Not found: %s", fabricName) } - conn := testAccProvider.Meta().(*cloudapi.Client) + conn := testAccProvider.Meta().(*triton.Client) - nics, err := conn.ListNICs(machine.Primary.ID) + nics, err := conn.Machines().ListNICs(context.Background(), &triton.ListNICsInput{ + MachineID: machine.Primary.ID, + }) if err != nil { return fmt.Errorf("Bad: Check NICs Exist: %s", err) } @@ -171,49 +176,25 @@ func testCheckTritonMachineHasFabric(name, fabricName string) resource.TestCheck } } -func testCheckTritonMachineHasNoFabric(name, fabricName string) resource.TestCheckFunc { - return func(s *terraform.State) error { - // Ensure we have enough information in state to look up in API - machine, ok := s.RootModule().Resources[name] - if !ok { - return fmt.Errorf("Not found: %s", name) - } - - network, ok := s.RootModule().Resources[fabricName] - if !ok { - return fmt.Errorf("Not found: %s", fabricName) - } - conn := testAccProvider.Meta().(*cloudapi.Client) - - nics, err := conn.ListNICs(machine.Primary.ID) - if err != nil { - return fmt.Errorf("Bad: Check NICs Exist: %s", err) - } - - for _, nic := range nics { - if nic.Network == network.Primary.ID { - return fmt.Errorf("Bad: Machine %q has Fabric %q", machine.Primary.ID, network.Primary.ID) - } - } - - return nil - } -} - func testCheckTritonMachineDestroy(s *terraform.State) error { - conn := testAccProvider.Meta().(*cloudapi.Client) + conn := testAccProvider.Meta().(*triton.Client) for _, rs := range s.RootModule().Resources { if rs.Type != "triton_machine" { continue } - resp, err := conn.GetMachine(rs.Primary.ID) + resp, err := conn.Machines().GetMachine(context.Background(), &triton.GetMachineInput{ + ID: rs.Primary.ID, + }) if err != nil { - return nil + if triton.IsResourceNotFound(err) { + return nil + } + return err } - if resp != nil { + if resp != nil && resp.State != machineStateDeleted { return fmt.Errorf("Bad: Machine %q still exists", rs.Primary.ID) } } @@ -231,7 +212,7 @@ func TestAccTritonMachine_firewall(t *testing.T) { Providers: testAccProviders, CheckDestroy: testCheckTritonMachineDestroy, Steps: []resource.TestStep{ - resource.TestStep{ + { Config: enabled_config, Check: resource.ComposeTestCheckFunc( testCheckTritonMachineExists("triton_machine.test"), @@ -239,7 +220,7 @@ func TestAccTritonMachine_firewall(t *testing.T) { "triton_machine.test", "firewall_enabled", "true"), ), }, - resource.TestStep{ + { Config: disabled_config, Check: resource.ComposeTestCheckFunc( testCheckTritonMachineExists("triton_machine.test"), @@ -247,7 +228,7 @@ func TestAccTritonMachine_firewall(t *testing.T) { "triton_machine.test", "firewall_enabled", "false"), ), }, - resource.TestStep{ + { Config: enabled_config, Check: resource.ComposeTestCheckFunc( testCheckTritonMachineExists("triton_machine.test"), @@ -271,13 +252,13 @@ func TestAccTritonMachine_metadata(t *testing.T) { Providers: testAccProviders, CheckDestroy: testCheckTritonMachineDestroy, Steps: []resource.TestStep{ - resource.TestStep{ + { Config: basic, Check: resource.ComposeTestCheckFunc( testCheckTritonMachineExists("triton_machine.test"), ), }, - resource.TestStep{ + { Config: add_metadata, Check: resource.ComposeTestCheckFunc( testCheckTritonMachineExists("triton_machine.test"), @@ -285,7 +266,7 @@ func TestAccTritonMachine_metadata(t *testing.T) { "triton_machine.test", "user_data", "hello"), ), }, - resource.TestStep{ + { Config: add_metadata_2, Check: resource.ComposeTestCheckFunc( testCheckTritonMachineExists("triton_machine.test"), @@ -294,7 +275,7 @@ func TestAccTritonMachine_metadata(t *testing.T) { "tags.triton.cns.services", "test-cns-service"), ), }, - resource.TestStep{ + { Config: add_metadata_3, Check: resource.ComposeTestCheckFunc( testCheckTritonMachineExists("triton_machine.test"), @@ -311,7 +292,7 @@ var testAccTritonMachine_basic = ` resource "triton_machine" "test" { name = "%s" package = "g4-general-4G" - image = "c20b4b7c-e1a6-11e5-9a4d-ef590901732e" + image = "fb5fe970-e6e4-11e6-9820-4b51be190db9" tags = { test = "hello!" @@ -332,7 +313,7 @@ var testAccTritonMachine_firewall_1 = ` resource "triton_machine" "test" { name = "%s" package = "g4-general-4G" - image = "c20b4b7c-e1a6-11e5-9a4d-ef590901732e" + image = "fb5fe970-e6e4-11e6-9820-4b51be190db9" firewall_enabled = 1 } @@ -361,7 +342,7 @@ variable "tags" { resource "triton_machine" "test" { name = "%s" package = "g4-highcpu-128M" - image = "c20b4b7c-e1a6-11e5-9a4d-ef590901732e" + image = "fb5fe970-e6e4-11e6-9820-4b51be190db9" user_data = "hello" @@ -372,7 +353,7 @@ var testAccTritonMachine_metadata_3 = ` resource "triton_machine" "test" { name = "%s" package = "g4-highcpu-128M" - image = "c20b4b7c-e1a6-11e5-9a4d-ef590901732e" + image = "fb5fe970-e6e4-11e6-9820-4b51be190db9" user_data = "hello" @@ -382,57 +363,91 @@ resource "triton_machine" "test" { } } ` -var testAccTritonMachine_withnic = ` +var testAccTritonMachine_singleNIC = func(name string, vlanNumber int, subnetNumber int) string { + return fmt.Sprintf(`resource "triton_vlan" "test" { + vlan_id = %d + name = "%s-vlan" + description = "test vlan" +} + resource "triton_fabric" "test" { - name = "%s-network" - description = "test network" - vlan_id = 2 # every DC seems to have a vlan 2 available + name = "%s-network" + description = "test network" + vlan_id = "${triton_vlan.test.vlan_id}" - subnet = "10.0.0.0/22" - gateway = "10.0.0.1" - provision_start_ip = "10.0.0.5" - provision_end_ip = "10.0.3.250" + subnet = "10.%d.0.0/24" + gateway = "10.%d.0.1" + provision_start_ip = "10.%d.0.10" + provision_end_ip = "10.%d.0.250" - resolvers = ["8.8.8.8", "8.8.4.4"] + resolvers = ["8.8.8.8", "8.8.4.4"] } resource "triton_machine" "test" { - name = "%s" - package = "g4-general-4G" - image = "842e6fa6-6e9b-11e5-8402-1b490459e334" + name = "%s-instance" + package = "g4-highcpu-128M" + image = "fb5fe970-e6e4-11e6-9820-4b51be190db9" - tags = { - test = "hello!" + tags = { + test = "Test" } - nic { network = "${triton_fabric.test.id}" } + nic { + network = "${triton_fabric.test.id}" + } +}`, vlanNumber, name, name, subnetNumber, subnetNumber, subnetNumber, subnetNumber, name) +} + +var testAccTritonMachine_dualNIC = func(name string, vlanNumber, subnetNumber int) string { + return fmt.Sprintf(`resource "triton_vlan" "test" { + vlan_id = %d + name = "%s-vlan" + description = "test vlan" } -` -var testAccTritonMachine_withoutnic = ` resource "triton_fabric" "test" { - name = "%s-network" - description = "test network" - vlan_id = 2 # every DC seems to have a vlan 2 available + name = "%s-network" + description = "test network" + vlan_id = "${triton_vlan.test.vlan_id}" - subnet = "10.0.0.0/22" - gateway = "10.0.0.1" - provision_start_ip = "10.0.0.5" - provision_end_ip = "10.0.3.250" + subnet = "10.%d.0.0/24" + gateway = "10.%d.0.1" + provision_start_ip = "10.%d.0.10" + provision_end_ip = "10.%d.0.250" - resolvers = ["8.8.8.8", "8.8.4.4"] + resolvers = ["8.8.8.8", "8.8.4.4"] +} + +resource "triton_fabric" "test_add" { + name = "%s-network-2" + description = "test network 2" + vlan_id = "${triton_vlan.test.vlan_id}" + + subnet = "172.23.%d.0/24" + gateway = "172.23.%d.1" + provision_start_ip = "172.23.%d.10" + provision_end_ip = "172.23.%d.250" + + resolvers = ["8.8.8.8", "8.8.4.4"] } resource "triton_machine" "test" { - name = "%s" - package = "g4-general-4G" - image = "842e6fa6-6e9b-11e5-8402-1b490459e334" + name = "%s-instance" + package = "g4-highcpu-128M" + image = "fb5fe970-e6e4-11e6-9820-4b51be190db9" - tags = { - test = "hello!" + tags = { + test = "Test" } + + nic { + network = "${triton_fabric.test.id}" + } + nic { + network = "${triton_fabric.test_add.id}" + } +}`, vlanNumber, name, name, subnetNumber, subnetNumber, subnetNumber, subnetNumber, name, subnetNumber, subnetNumber, subnetNumber, subnetNumber, name) } -` var testAccTritonMachine_dns = ` provider "triton" { @@ -441,8 +456,9 @@ provider "triton" { resource "triton_machine" "test" { name = "%s" package = "g4-highcpu-128M" - image = "e1faace4-e19b-11e5-928b-83849e2fd94a" + image = "fb5fe970-e6e4-11e6-9820-4b51be190db9" } + output "domain_names" { value = "${join(", ", triton_machine.test.domain_names)}" } diff --git a/builtin/providers/triton/resource_vlan.go b/builtin/providers/triton/resource_vlan.go index 34eb5d67c..6cf246bc2 100644 --- a/builtin/providers/triton/resource_vlan.go +++ b/builtin/providers/triton/resource_vlan.go @@ -1,27 +1,29 @@ package triton import ( + "context" "errors" "strconv" "github.com/hashicorp/terraform/helper/schema" - "github.com/joyent/gosdc/cloudapi" + "github.com/joyent/triton-go" ) func resourceVLAN() *schema.Resource { return &schema.Resource{ - Create: resourceVLANCreate, - Exists: resourceVLANExists, - Read: resourceVLANRead, - Update: resourceVLANUpdate, - Delete: resourceVLANDelete, + Create: resourceVLANCreate, + Exists: resourceVLANExists, + Read: resourceVLANRead, + Update: resourceVLANUpdate, + Delete: resourceVLANDelete, + Timeouts: fastResourceTimeout, Importer: &schema.ResourceImporter{ - State: resourceVLANImporter, + State: schema.ImportStatePassthrough, }, Schema: map[string]*schema.Schema{ "vlan_id": { - Description: "number between 0-4095 indicating VLAN ID", + Description: "Number between 0-4095 indicating VLAN ID", Required: true, ForceNew: true, Type: schema.TypeInt, @@ -39,7 +41,7 @@ func resourceVLAN() *schema.Resource { Type: schema.TypeString, }, "description": { - Description: "Optional description of the VLAN", + Description: "Description of the VLAN", Optional: true, Type: schema.TypeString, }, @@ -48,10 +50,10 @@ func resourceVLAN() *schema.Resource { } func resourceVLANCreate(d *schema.ResourceData, meta interface{}) error { - client := meta.(*cloudapi.Client) + client := meta.(*triton.Client) - vlan, err := client.CreateFabricVLAN(cloudapi.FabricVLAN{ - Id: int16(d.Get("vlan_id").(int)), + vlan, err := client.Fabrics().CreateFabricVLAN(context.Background(), &triton.CreateFabricVLANInput{ + ID: d.Get("vlan_id").(int), Name: d.Get("name").(string), Description: d.Get("description").(string), }) @@ -59,33 +61,39 @@ func resourceVLANCreate(d *schema.ResourceData, meta interface{}) error { return err } - d.SetId(resourceVLANIDString(vlan.Id)) + d.SetId(strconv.Itoa(vlan.ID)) return resourceVLANRead(d, meta) } func resourceVLANExists(d *schema.ResourceData, meta interface{}) (bool, error) { - client := meta.(*cloudapi.Client) + client := meta.(*triton.Client) - id, err := resourceVLANIDInt16(d.Id()) + id, err := resourceVLANIDInt(d.Id()) if err != nil { return false, err } - vlan, err := client.GetFabricVLAN(id) - - return vlan != nil && err == nil, err + return resourceExists(client.Fabrics().GetFabricVLAN(context.Background(), &triton.GetFabricVLANInput{ + ID: id, + })) } func resourceVLANRead(d *schema.ResourceData, meta interface{}) error { - client := meta.(*cloudapi.Client) + client := meta.(*triton.Client) - vlan, err := client.GetFabricVLAN(int16(d.Get("vlan_id").(int))) + id, err := resourceVLANIDInt(d.Id()) if err != nil { return err } - d.SetId(resourceVLANIDString(vlan.Id)) - d.Set("vlan_id", vlan.Id) + vlan, err := client.Fabrics().GetFabricVLAN(context.Background(), &triton.GetFabricVLANInput{ + ID: id, + }) + if err != nil { + return err + } + + d.Set("vlan_id", vlan.ID) d.Set("name", vlan.Name) d.Set("description", vlan.Description) @@ -93,10 +101,10 @@ func resourceVLANRead(d *schema.ResourceData, meta interface{}) error { } func resourceVLANUpdate(d *schema.ResourceData, meta interface{}) error { - client := meta.(*cloudapi.Client) + client := meta.(*triton.Client) - vlan, err := client.UpdateFabricVLAN(cloudapi.FabricVLAN{ - Id: int16(d.Get("vlan_id").(int)), + vlan, err := client.Fabrics().UpdateFabricVLAN(context.Background(), &triton.UpdateFabricVLANInput{ + ID: d.Get("vlan_id").(int), Name: d.Get("name").(string), Description: d.Get("description").(string), }) @@ -104,36 +112,28 @@ func resourceVLANUpdate(d *schema.ResourceData, meta interface{}) error { return err } - d.SetId(resourceVLANIDString(vlan.Id)) + d.SetId(strconv.Itoa(vlan.ID)) return resourceVLANRead(d, meta) } func resourceVLANDelete(d *schema.ResourceData, meta interface{}) error { - client := meta.(*cloudapi.Client) + client := meta.(*triton.Client) - id, err := resourceVLANIDInt16(d.Id()) + id, err := resourceVLANIDInt(d.Id()) if err != nil { return err } - return client.DeleteFabricVLAN(id) + return client.Fabrics().DeleteFabricVLAN(context.Background(), &triton.DeleteFabricVLANInput{ + ID: id, + }) } -// convenience conversion functions - -func resourceVLANIDString(id int16) string { - return strconv.Itoa(int(id)) -} - -func resourceVLANIDInt16(id string) (int16, error) { - result, err := strconv.ParseInt(id, 10, 16) +func resourceVLANIDInt(id string) (int, error) { + result, err := strconv.ParseInt(id, 10, 32) if err != nil { - return 0, err + return -1, err } - return int16(result), nil -} - -func resourceVLANImporter(d *schema.ResourceData, meta interface{}) ([]*schema.ResourceData, error) { - return []*schema.ResourceData{d}, nil + return int(result), nil } diff --git a/builtin/providers/triton/resource_vlan_test.go b/builtin/providers/triton/resource_vlan_test.go index 91333aed6..1c2af5865 100644 --- a/builtin/providers/triton/resource_vlan_test.go +++ b/builtin/providers/triton/resource_vlan_test.go @@ -1,23 +1,26 @@ package triton import ( + "context" "fmt" + "strconv" "testing" + "github.com/hashicorp/terraform/helper/acctest" "github.com/hashicorp/terraform/helper/resource" "github.com/hashicorp/terraform/terraform" - "github.com/joyent/gosdc/cloudapi" + "github.com/joyent/triton-go" ) func TestAccTritonVLAN_basic(t *testing.T) { - config := testAccTritonVLAN_basic + config := testAccTritonVLAN_basic(acctest.RandIntRange(3, 2048)) resource.Test(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, CheckDestroy: testCheckTritonVLANDestroy, Steps: []resource.TestStep{ - resource.TestStep{ + { Config: config, Check: resource.ComposeTestCheckFunc( testCheckTritonVLANExists("triton_vlan.test"), @@ -28,27 +31,30 @@ func TestAccTritonVLAN_basic(t *testing.T) { } func TestAccTritonVLAN_update(t *testing.T) { - preConfig := testAccTritonVLAN_basic - postConfig := testAccTritonVLAN_update + vlanNumber := acctest.RandIntRange(3, 2048) + preConfig := testAccTritonVLAN_basic(vlanNumber) + postConfig := testAccTritonVLAN_update(vlanNumber) resource.Test(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, CheckDestroy: testCheckTritonVLANDestroy, Steps: []resource.TestStep{ - resource.TestStep{ + { Config: preConfig, Check: resource.ComposeTestCheckFunc( testCheckTritonVLANExists("triton_vlan.test"), + resource.TestCheckResourceAttr("triton_vlan.test", "vlan_id", strconv.Itoa(vlanNumber)), resource.TestCheckResourceAttr("triton_vlan.test", "name", "test-vlan"), resource.TestCheckResourceAttr("triton_vlan.test", "description", "test vlan"), ), }, - resource.TestStep{ + { Config: postConfig, Check: resource.ComposeTestCheckFunc( testCheckTritonVLANExists("triton_vlan.test"), + resource.TestCheckResourceAttr("triton_vlan.test", "vlan_id", strconv.Itoa(vlanNumber)), resource.TestCheckResourceAttr("triton_vlan.test", "name", "test-vlan-2"), resource.TestCheckResourceAttr("triton_vlan.test", "description", "test vlan 2"), ), @@ -64,19 +70,23 @@ func testCheckTritonVLANExists(name string) resource.TestCheckFunc { if !ok { return fmt.Errorf("Not found: %s", name) } - conn := testAccProvider.Meta().(*cloudapi.Client) + conn := testAccProvider.Meta().(*triton.Client) - id, err := resourceVLANIDInt16(rs.Primary.ID) + id, err := resourceVLANIDInt(rs.Primary.ID) if err != nil { return err } - rule, err := conn.GetFabricVLAN(id) - if err != nil { + resp, err := conn.Fabrics().GetFabricVLAN(context.Background(), &triton.GetFabricVLANInput{ + ID: id, + }) + if err != nil && triton.IsResourceNotFound(err) { return fmt.Errorf("Bad: Check VLAN Exists: %s", err) + } else if err != nil { + return err } - if rule == nil { + if resp == nil { return fmt.Errorf("Bad: VLAN %q does not exist", rs.Primary.ID) } @@ -85,21 +95,25 @@ func testCheckTritonVLANExists(name string) resource.TestCheckFunc { } func testCheckTritonVLANDestroy(s *terraform.State) error { - conn := testAccProvider.Meta().(*cloudapi.Client) + conn := testAccProvider.Meta().(*triton.Client) for _, rs := range s.RootModule().Resources { if rs.Type != "triton_vlan" { continue } - id, err := resourceVLANIDInt16(rs.Primary.ID) + id, err := resourceVLANIDInt(rs.Primary.ID) if err != nil { return err } - resp, err := conn.GetFabricVLAN(id) - if err != nil { + resp, err := conn.Fabrics().GetFabricVLAN(context.Background(), &triton.GetFabricVLANInput{ + ID: id, + }) + if triton.IsResourceNotFound(err) { return nil + } else if err != nil { + return err } if resp != nil { @@ -110,18 +124,18 @@ func testCheckTritonVLANDestroy(s *terraform.State) error { return nil } -var testAccTritonVLAN_basic = ` -resource "triton_vlan" "test" { - vlan_id = 1024 - name = "test-vlan" - description = "test vlan" +var testAccTritonVLAN_basic = func(vlanID int) string { + return fmt.Sprintf(`resource "triton_vlan" "test" { + vlan_id = %d + name = "test-vlan" + description = "test vlan" + }`, vlanID) } -` -var testAccTritonVLAN_update = ` -resource "triton_vlan" "test" { - vlan_id = 1024 - name = "test-vlan-2" - description = "test vlan 2" +var testAccTritonVLAN_update = func(vlanID int) string { + return fmt.Sprintf(`resource "triton_vlan" "test" { + vlan_id = %d + name = "test-vlan-2" + description = "test vlan 2" + }`, vlanID) } -` diff --git a/builtin/providers/triton/utils.go b/builtin/providers/triton/utils.go deleted file mode 100644 index ef8ae23cb..000000000 --- a/builtin/providers/triton/utils.go +++ /dev/null @@ -1,30 +0,0 @@ -package triton - -import ( - "errors" - "time" -) - -var ( - // ErrTimeout is returned when waiting for state change - ErrTimeout = errors.New("timed out while waiting for resource change") -) - -func waitFor(f func() (bool, error), every, timeout time.Duration) error { - start := time.Now() - - for time.Since(start) <= timeout { - stop, err := f() - if err != nil { - return err - } - - if stop { - return nil - } - - time.Sleep(every) - } - - return ErrTimeout -} diff --git a/builtin/providers/ultradns/common_test.go b/builtin/providers/ultradns/common_test.go index 24470e0d3..05823fdcd 100644 --- a/builtin/providers/ultradns/common_test.go +++ b/builtin/providers/ultradns/common_test.go @@ -8,6 +8,29 @@ import ( "github.com/hashicorp/terraform/terraform" ) +func testAccRdpoolCheckDestroy(s *terraform.State) error { + client := testAccProvider.Meta().(*udnssdk.Client) + + for _, rs := range s.RootModule().Resources { + if rs.Type != "ultradns_rdpool" { + continue + } + + k := udnssdk.RRSetKey{ + Zone: rs.Primary.Attributes["zone"], + Name: rs.Primary.Attributes["name"], + Type: rs.Primary.Attributes["type"], + } + + _, err := client.RRSets.Select(k) + if err == nil { + return fmt.Errorf("Record still exists") + } + } + + return nil +} + func testAccTcpoolCheckDestroy(s *terraform.State) error { client := testAccProvider.Meta().(*udnssdk.Client) diff --git a/builtin/providers/ultradns/provider.go b/builtin/providers/ultradns/provider.go index e10015ab2..70f0dbed7 100644 --- a/builtin/providers/ultradns/provider.go +++ b/builtin/providers/ultradns/provider.go @@ -38,6 +38,7 @@ func Provider() terraform.ResourceProvider { "ultradns_probe_ping": resourceUltradnsProbePing(), "ultradns_record": resourceUltradnsRecord(), "ultradns_tcpool": resourceUltradnsTcpool(), + "ultradns_rdpool": resourceUltradnsRdpool(), }, ConfigureFunc: providerConfigure, diff --git a/builtin/providers/ultradns/resource_ultradns_rdpool.go b/builtin/providers/ultradns/resource_ultradns_rdpool.go new file mode 100644 index 000000000..5f8bbff6c --- /dev/null +++ b/builtin/providers/ultradns/resource_ultradns_rdpool.go @@ -0,0 +1,218 @@ +package ultradns + +import ( + "fmt" + "log" + "strings" + + "github.com/Ensighten/udnssdk" + "github.com/hashicorp/terraform/helper/schema" + "github.com/hashicorp/terraform/helper/validation" +) + +func resourceUltradnsRdpool() *schema.Resource { + return &schema.Resource{ + Create: resourceUltradnsRdpoolCreate, + Read: resourceUltradnsRdpoolRead, + Update: resourceUltradnsRdpoolUpdate, + Delete: resourceUltradnsRdpoolDelete, + + Schema: map[string]*schema.Schema{ + // Required + "zone": &schema.Schema{ + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + "name": &schema.Schema{ + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + "rdata": &schema.Schema{ + Type: schema.TypeSet, + Set: schema.HashString, + Required: true, + Elem: &schema.Schema{Type: schema.TypeString}, + }, + // Optional + "order": &schema.Schema{ + Type: schema.TypeString, + Optional: true, + Default: "ROUND_ROBIN", + ValidateFunc: validation.StringInSlice([]string{ + "ROUND_ROBIN", + "FIXED", + "RANDOM", + }, false), + }, + "description": &schema.Schema{ + Type: schema.TypeString, + Optional: true, + ValidateFunc: validation.StringLenBetween(0, 255), + }, + "ttl": &schema.Schema{ + Type: schema.TypeInt, + Optional: true, + Default: 3600, + }, + // Computed + "hostname": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + }, + }, + } +} + +// CRUD Operations + +func resourceUltradnsRdpoolCreate(d *schema.ResourceData, meta interface{}) error { + log.Printf("[INFO] ultradns_rdpool create") + client := meta.(*udnssdk.Client) + + r, err := newRRSetResourceFromRdpool(d) + if err != nil { + return err + } + + log.Printf("[INFO] ultradns_rdpool create: %#v", r) + _, err = client.RRSets.Create(r.RRSetKey(), r.RRSet()) + if err != nil { + return fmt.Errorf("create failed: %#v -> %v", r, err) + } + + d.SetId(r.ID()) + log.Printf("[INFO] ultradns_rdpool.id: %v", d.Id()) + + return resourceUltradnsRdpoolRead(d, meta) +} + +func resourceUltradnsRdpoolRead(d *schema.ResourceData, meta interface{}) error { + log.Printf("[INFO] ultradns_rdpool read") + client := meta.(*udnssdk.Client) + + rr, err := newRRSetResourceFromRdpool(d) + if err != nil { + return err + } + + rrsets, err := client.RRSets.Select(rr.RRSetKey()) + if err != nil { + uderr, ok := err.(*udnssdk.ErrorResponseList) + if ok { + for _, resps := range uderr.Responses { + // 70002 means Records Not Found + if resps.ErrorCode == 70002 { + d.SetId("") + return nil + } + return fmt.Errorf("resource not found: %v", err) + } + } + return fmt.Errorf("resource not found: %v", err) + } + + r := rrsets[0] + + zone := d.Get("zone") + + // hostname + if r.OwnerName == "" { + d.Set("hostname", zone) + } else { + if strings.HasSuffix(r.OwnerName, ".") { + d.Set("hostname", r.OwnerName) + } else { + d.Set("hostname", fmt.Sprintf("%s.%s", r.OwnerName, zone)) + } + } + + // And now... the Profile! + if r.Profile == nil { + return fmt.Errorf("RRSet.profile missing: invalid RDPool schema in: %#v", r) + } + p, err := r.Profile.RDPoolProfile() + if err != nil { + return fmt.Errorf("RRSet.profile could not be unmarshalled: %v\n", err) + } + + // Set simple values + d.Set("ttl", r.TTL) + d.Set("description", p.Description) + d.Set("order", p.Order) + + err = d.Set("rdata", makeSetFromStrings(r.RData)) + if err != nil { + return fmt.Errorf("rdata set failed: %#v", err) + } + return nil +} + +func resourceUltradnsRdpoolUpdate(d *schema.ResourceData, meta interface{}) error { + log.Printf("[INFO] ultradns_rdpool update") + client := meta.(*udnssdk.Client) + + r, err := newRRSetResourceFromRdpool(d) + if err != nil { + return err + } + + log.Printf("[INFO] ultradns_rdpool update: %+v", r) + _, err = client.RRSets.Update(r.RRSetKey(), r.RRSet()) + if err != nil { + return fmt.Errorf("resource update failed: %v", err) + } + + return resourceUltradnsRdpoolRead(d, meta) +} + +func resourceUltradnsRdpoolDelete(d *schema.ResourceData, meta interface{}) error { + log.Printf("[INFO] ultradns_rdpool delete") + client := meta.(*udnssdk.Client) + + r, err := newRRSetResourceFromRdpool(d) + if err != nil { + return err + } + + log.Printf("[INFO] ultradns_rdpool delete: %+v", r) + _, err = client.RRSets.Delete(r.RRSetKey()) + if err != nil { + return fmt.Errorf("resource delete failed: %v", err) + } + + return nil +} + +// Resource Helpers + +func newRRSetResourceFromRdpool(d *schema.ResourceData) (rRSetResource, error) { + //rDataRaw := d.Get("rdata").(*schema.Set).List() + r := rRSetResource{ + // "The only valid rrtype value for RDpools is A" + // per https://portal.ultradns.com/static/docs/REST-API_User_Guide.pdf + RRType: "A", + Zone: d.Get("zone").(string), + OwnerName: d.Get("name").(string), + TTL: d.Get("ttl").(int), + } + if attr, ok := d.GetOk("rdata"); ok { + rdata := attr.(*schema.Set).List() + r.RData = make([]string, len(rdata)) + for i, j := range rdata { + r.RData[i] = j.(string) + } + } + + profile := udnssdk.RDPoolProfile{ + Context: udnssdk.RDPoolSchema, + Order: d.Get("order").(string), + Description: d.Get("description").(string), + } + + rp := profile.RawProfile() + r.Profile = rp + + return r, nil +} diff --git a/builtin/providers/ultradns/resource_ultradns_rdpool_test.go b/builtin/providers/ultradns/resource_ultradns_rdpool_test.go new file mode 100644 index 000000000..1ddd9c025 --- /dev/null +++ b/builtin/providers/ultradns/resource_ultradns_rdpool_test.go @@ -0,0 +1,100 @@ +package ultradns + +import ( + "fmt" + "testing" + + "github.com/Ensighten/udnssdk" + "github.com/hashicorp/terraform/helper/resource" +) + +func TestAccUltradnsRdpool(t *testing.T) { + var record udnssdk.RRSet + domain := "ultradns.phinze.com" + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccRdpoolCheckDestroy, + Steps: []resource.TestStep{ + resource.TestStep{ + Config: fmt.Sprintf(testCfgRdpoolMinimal, domain), + Check: resource.ComposeTestCheckFunc( + testAccCheckUltradnsRecordExists("ultradns_rdpool.it", &record), + // Specified + resource.TestCheckResourceAttr("ultradns_rdpool.it", "zone", domain), + resource.TestCheckResourceAttr("ultradns_rdpool.it", "name", "test-rdpool-minimal"), + resource.TestCheckResourceAttr("ultradns_rdpool.it", "ttl", "300"), + + // hashRdatas(): 10.6.0.1 -> 2847814707 + resource.TestCheckResourceAttr("ultradns_rdpool.it", "rdata.2847814707.host", "10.6.0.1"), + // Defaults + resource.TestCheckResourceAttr("ultradns_rdpool.it", "description", "Minimal RD Pool"), + resource.TestCheckResourceAttr("ultradns_rdpool.it", "rdata.2847814707.priority", "1"), + // Generated + resource.TestCheckResourceAttr("ultradns_rdpool.it", "id", "test-rdpool-minimal.ultradns.phinze.com"), + resource.TestCheckResourceAttr("ultradns_rdpool.it", "hostname", "test-rdpool-minimal.ultradns.phinze.com."), + ), + }, + resource.TestStep{ + Config: fmt.Sprintf(testCfgRdpoolMaximal, domain), + Check: resource.ComposeTestCheckFunc( + testAccCheckUltradnsRecordExists("ultradns_rdpool.it", &record), + // Specified + resource.TestCheckResourceAttr("ultradns_rdpool.it", "zone", domain), + resource.TestCheckResourceAttr("ultradns_rdpool.it", "name", "test-rdpool-maximal"), + resource.TestCheckResourceAttr("ultradns_rdpool.it", "ttl", "300"), + resource.TestCheckResourceAttr("ultradns_rdpool.it", "description", "traffic controller pool with all settings tuned"), + + resource.TestCheckResourceAttr("ultradns_rdpool.it", "act_on_probes", "false"), + resource.TestCheckResourceAttr("ultradns_rdpool.it", "max_to_lb", "2"), + resource.TestCheckResourceAttr("ultradns_rdpool.it", "run_probes", "false"), + + // hashRdatas(): 10.6.1.1 -> 2826722820 + resource.TestCheckResourceAttr("ultradns_rdpool.it", "rdata.2826722820.host", "10.6.1.1"), + resource.TestCheckResourceAttr("ultradns_rdpool.it", "rdata.2826722820.priority", "1"), + + // hashRdatas(): 10.6.1.2 -> 829755326 + resource.TestCheckResourceAttr("ultradns_rdpool.it", "rdata.829755326.host", "10.6.1.2"), + resource.TestCheckResourceAttr("ultradns_rdpool.it", "rdata.829755326.priority", "2"), + + // Generated + resource.TestCheckResourceAttr("ultradns_rdpool.it", "id", "test-rdpool-maximal.ultradns.phinze.com"), + resource.TestCheckResourceAttr("ultradns_rdpool.it", "hostname", "test-rdpool-maximal.ultradns.phinze.com."), + ), + }, + }, + }) +} + +const testCfgRdpoolMinimal = ` +resource "ultradns_rdpool" "it" { + zone = "%s" + name = "test-rdpool-minimal" + ttl = 300 + description = "Minimal RD Pool" + + rdata { + host = "10.6.0.1" + } +} +` + +const testCfgRdpoolMaximal = ` +resource "ultradns_rdpool" "it" { + zone = "%s" + name = "test-rdpool-maximal" + order = "ROUND_ROBIN" + ttl = 300 + description = "traffic controller pool with all settings tuned" + rdata { + host = "10.6.1.1" + priority = 1 + } + + rdata { + host = "10.6.1.2" + priority = 2 + } +} +` diff --git a/builtin/providers/vault/data_source_generic_secret.go b/builtin/providers/vault/data_source_generic_secret.go index b99f8b0fa..34f353707 100644 --- a/builtin/providers/vault/data_source_generic_secret.go +++ b/builtin/providers/vault/data_source_generic_secret.go @@ -16,43 +16,43 @@ func genericSecretDataSource() *schema.Resource { Read: genericSecretDataSourceRead, Schema: map[string]*schema.Schema{ - "path": &schema.Schema{ + "path": { Type: schema.TypeString, Required: true, Description: "Full path from which a secret will be read.", }, - "data_json": &schema.Schema{ + "data_json": { Type: schema.TypeString, Computed: true, Description: "JSON-encoded secret data read from Vault.", }, - "data": &schema.Schema{ + "data": { Type: schema.TypeMap, Computed: true, Description: "Map of strings read from Vault.", }, - "lease_id": &schema.Schema{ + "lease_id": { Type: schema.TypeString, Computed: true, Description: "Lease identifier assigned by vault.", }, - "lease_duration": &schema.Schema{ + "lease_duration": { Type: schema.TypeInt, Computed: true, Description: "Lease duration in seconds relative to the time in lease_start_time.", }, - "lease_start_time": &schema.Schema{ + "lease_start_time": { Type: schema.TypeString, Computed: true, Description: "Time at which the lease was read, using the clock of the system where Terraform was running", }, - "lease_renewable": &schema.Schema{ + "lease_renewable": { Type: schema.TypeBool, Computed: true, Description: "True if the duration of this lease can be extended through renewal.", @@ -71,6 +71,9 @@ func genericSecretDataSourceRead(d *schema.ResourceData, meta interface{}) error if err != nil { return fmt.Errorf("error reading from Vault: %s", err) } + if secret == nil { + return fmt.Errorf("No secret found at %q", path) + } d.SetId(secret.RequestID) diff --git a/builtin/providers/vault/provider.go b/builtin/providers/vault/provider.go index ceebd4acf..d9c7719e9 100644 --- a/builtin/providers/vault/provider.go +++ b/builtin/providers/vault/provider.go @@ -87,6 +87,7 @@ func Provider() terraform.ResourceProvider { }, ResourcesMap: map[string]*schema.Resource{ + "vault_auth_backend": authBackendResource(), "vault_generic_secret": genericSecretResource(), "vault_policy": policyResource(), }, diff --git a/builtin/providers/vault/resource_auth_backend.go b/builtin/providers/vault/resource_auth_backend.go new file mode 100644 index 000000000..800155040 --- /dev/null +++ b/builtin/providers/vault/resource_auth_backend.go @@ -0,0 +1,121 @@ +package vault + +import ( + "errors" + "fmt" + "log" + "strings" + + "github.com/hashicorp/terraform/helper/schema" + "github.com/hashicorp/vault/api" +) + +func authBackendResource() *schema.Resource { + return &schema.Resource{ + Create: authBackendWrite, + Delete: authBackendDelete, + Read: authBackendRead, + + Schema: map[string]*schema.Schema{ + "type": &schema.Schema{ + Type: schema.TypeString, + Required: true, + ForceNew: true, + Description: "Name of the auth backend", + }, + + "path": &schema.Schema{ + Type: schema.TypeString, + Optional: true, + Computed: true, + ForceNew: true, + Description: "path to mount the backend. This defaults to the type.", + ValidateFunc: func(v interface{}, k string) (ws []string, errs []error) { + value := v.(string) + if strings.HasSuffix(value, "/") { + errs = append(errs, errors.New("cannot write to a path ending in '/'")) + } + return + }, + }, + + "description": &schema.Schema{ + Type: schema.TypeString, + ForceNew: true, + Optional: true, + Description: "The description of the auth backend", + }, + }, + } +} + +func authBackendWrite(d *schema.ResourceData, meta interface{}) error { + client := meta.(*api.Client) + + name := d.Get("type").(string) + desc := d.Get("description").(string) + path := d.Get("path").(string) + + log.Printf("[DEBUG] Writing auth %s to Vault", name) + + var err error + + if path == "" { + path = name + err = d.Set("path", name) + if err != nil { + return fmt.Errorf("unable to set state: %s", err) + } + } + + err = client.Sys().EnableAuth(path, name, desc) + + if err != nil { + return fmt.Errorf("error writing to Vault: %s", err) + } + + d.SetId(name) + + return nil +} + +func authBackendDelete(d *schema.ResourceData, meta interface{}) error { + client := meta.(*api.Client) + + name := d.Id() + + log.Printf("[DEBUG] Deleting auth %s from Vault", name) + + err := client.Sys().DisableAuth(name) + + if err != nil { + return fmt.Errorf("error disabling auth from Vault: %s", err) + } + + return nil +} + +func authBackendRead(d *schema.ResourceData, meta interface{}) error { + client := meta.(*api.Client) + + name := d.Id() + + auths, err := client.Sys().ListAuth() + + if err != nil { + return fmt.Errorf("error reading from Vault: %s", err) + } + + for path, auth := range auths { + configuredPath := d.Get("path").(string) + + vaultPath := configuredPath + "/" + if auth.Type == name && path == vaultPath { + return nil + } + } + + // If we fell out here then we didn't find our Auth in the list. + d.SetId("") + return nil +} diff --git a/builtin/providers/vault/resource_auth_backend_test.go b/builtin/providers/vault/resource_auth_backend_test.go new file mode 100644 index 000000000..344eafbd5 --- /dev/null +++ b/builtin/providers/vault/resource_auth_backend_test.go @@ -0,0 +1,129 @@ +package vault + +import ( + "fmt" + "testing" + + r "github.com/hashicorp/terraform/helper/resource" + "github.com/hashicorp/terraform/terraform" + "github.com/hashicorp/vault/api" +) + +func TestResourceAuth(t *testing.T) { + r.Test(t, r.TestCase{ + Providers: testProviders, + PreCheck: func() { testAccPreCheck(t) }, + Steps: []r.TestStep{ + r.TestStep{ + Config: testResourceAuth_initialConfig, + Check: testResourceAuth_initialCheck, + }, + r.TestStep{ + Config: testResourceAuth_updateConfig, + Check: testResourceAuth_updateCheck, + }, + }, + }) +} + +var testResourceAuth_initialConfig = ` + +resource "vault_auth_backend" "test" { + type = "github" +} + +` + +func testResourceAuth_initialCheck(s *terraform.State) error { + resourceState := s.Modules[0].Resources["vault_auth_backend.test"] + if resourceState == nil { + return fmt.Errorf("resource not found in state") + } + + instanceState := resourceState.Primary + if instanceState == nil { + return fmt.Errorf("resource has no primary instance") + } + + name := instanceState.ID + + if name != instanceState.Attributes["type"] { + return fmt.Errorf("id doesn't match name") + } + + if name != "github" { + return fmt.Errorf("unexpected auth name %s", name) + } + + client := testProvider.Meta().(*api.Client) + auths, err := client.Sys().ListAuth() + + if err != nil { + return fmt.Errorf("error reading back auth: %s", err) + } + + found := false + for _, auth := range auths { + if auth.Type == name { + found = true + break + } + } + + if !found { + return fmt.Errorf("could not find auth backend %s in %+v", name, auths) + } + + return nil +} + +var testResourceAuth_updateConfig = ` + +resource "vault_auth_backend" "test" { + type = "ldap" +} + +` + +func testResourceAuth_updateCheck(s *terraform.State) error { + resourceState := s.Modules[0].Resources["vault_auth_backend.test"] + if resourceState == nil { + return fmt.Errorf("resource not found in state") + } + + instanceState := resourceState.Primary + if instanceState == nil { + return fmt.Errorf("resource has no primary instance") + } + + name := instanceState.ID + + if name != instanceState.Attributes["type"] { + return fmt.Errorf("id doesn't match name") + } + + if name != "ldap" { + return fmt.Errorf("unexpected auth name") + } + + client := testProvider.Meta().(*api.Client) + auths, err := client.Sys().ListAuth() + + if err != nil { + return fmt.Errorf("error reading back auth: %s", err) + } + + found := false + for _, auth := range auths { + if auth.Type == name { + found = true + break + } + } + + if !found { + return fmt.Errorf("could not find auth backend %s in %+v", name, auths) + } + + return nil +} diff --git a/builtin/providers/vault/resource_generic_secret.go b/builtin/providers/vault/resource_generic_secret.go index a2a820c74..cbb8deda0 100644 --- a/builtin/providers/vault/resource_generic_secret.go +++ b/builtin/providers/vault/resource_generic_secret.go @@ -31,11 +31,53 @@ func genericSecretResource() *schema.Resource { Type: schema.TypeString, Required: true, Description: "JSON-encoded secret data to write.", + // We rebuild the attached JSON string to a simple singleline + // string. This makes terraform not want to change when an extra + // space is included in the JSON string. It is also necesarry + // when allow_read is true for comparing values. + StateFunc: NormalizeDataJSON, + ValidateFunc: ValidateDataJSON, + }, + + "allow_read": &schema.Schema{ + Type: schema.TypeBool, + Optional: true, + Default: false, + Description: "True if the provided token is allowed to read the secret from vault", }, }, } } +func ValidateDataJSON(configI interface{}, k string) ([]string, []error) { + dataJSON := configI.(string) + dataMap := map[string]interface{}{} + err := json.Unmarshal([]byte(dataJSON), &dataMap) + if err != nil { + return nil, []error{err} + } + return nil, nil +} + +func NormalizeDataJSON(configI interface{}) string { + dataJSON := configI.(string) + + dataMap := map[string]interface{}{} + err := json.Unmarshal([]byte(dataJSON), &dataMap) + if err != nil { + // The validate function should've taken care of this. + return "" + } + + ret, err := json.Marshal(dataMap) + if err != nil { + // Should never happen. + return dataJSON + } + + return string(ret) +} + func genericSecretResourceWrite(d *schema.ResourceData, meta interface{}) error { client := meta.(*api.Client) @@ -73,15 +115,25 @@ func genericSecretResourceDelete(d *schema.ResourceData, meta interface{}) error } func genericSecretResourceRead(d *schema.ResourceData, meta interface{}) error { - // We don't actually attempt to read back the secret data - // here, so that Terraform can be configured with a token - // that has only write access to the relevant part of the - // store. - // - // This means that Terraform cannot detect drift for - // generic secrets, but detecting drift seems less important - // than being able to limit the effect of exposure of - // Terraform's Vault token. - log.Printf("[WARN] vault_generic_secret does not automatically refresh") + allowed_to_read := d.Get("allow_read").(bool) + path := d.Get("path").(string) + + if allowed_to_read { + client := meta.(*api.Client) + + log.Printf("[DEBUG] Reading %s from Vault", path) + secret, err := client.Logical().Read(path) + if err != nil { + return fmt.Errorf("error reading from Vault: %s", err) + } + + // Ignoring error because this value came from JSON in the + // first place so no reason why it should fail to re-encode. + jsonDataBytes, _ := json.Marshal(secret.Data) + d.Set("data_json", string(jsonDataBytes)) + } + + d.SetId(path) + log.Printf("[WARN] vault_generic_secret does not automatically refresh if allow_read is set to false") return nil } diff --git a/builtin/providers/vault/resource_generic_secret_test.go b/builtin/providers/vault/resource_generic_secret_test.go index 7636565cd..5acaac9b1 100644 --- a/builtin/providers/vault/resource_generic_secret_test.go +++ b/builtin/providers/vault/resource_generic_secret_test.go @@ -31,6 +31,7 @@ var testResourceGenericSecret_initialConfig = ` resource "vault_generic_secret" "test" { path = "secret/foo" + allow_read = true data_json = < 0 { + return argument, nil + } + } + return make([]ast.Variable, 0), nil + }, + } +} + // interpolationFuncConcat implements the "concat" function that concatenates // multiple lists. func interpolationFuncConcat() ast.Function { @@ -456,6 +490,29 @@ func interpolationFuncCeil() ast.Function { } } +// interpolationFuncLog returns the logarithnm. +func interpolationFuncLog() ast.Function { + return ast.Function{ + ArgTypes: []ast.Type{ast.TypeFloat, ast.TypeFloat}, + ReturnType: ast.TypeFloat, + Callback: func(args []interface{}) (interface{}, error) { + return math.Log(args[0].(float64)) / math.Log(args[1].(float64)), nil + }, + } +} + +// interpolationFuncChomp removes trailing newlines from the given string +func interpolationFuncChomp() ast.Function { + newlines := regexp.MustCompile(`(?:\r\n?|\n)*\z`) + return ast.Function{ + ArgTypes: []ast.Type{ast.TypeString}, + ReturnType: ast.TypeString, + Callback: func(args []interface{}) (interface{}, error) { + return newlines.ReplaceAllString(args[0].(string), ""), nil + }, + } +} + // interpolationFuncFloorreturns returns the greatest integer value less than or equal to the argument func interpolationFuncFloor() ast.Function { return ast.Function{ @@ -600,6 +657,17 @@ func interpolationFuncIndex() ast.Function { } } +// interpolationFuncBasename implements the "dirname" function. +func interpolationFuncDirname() ast.Function { + return ast.Function{ + ArgTypes: []ast.Type{ast.TypeString}, + ReturnType: ast.TypeString, + Callback: func(args []interface{}) (interface{}, error) { + return filepath.Dir(args[0].(string)), nil + }, + } +} + // interpolationFuncDistinct implements the "distinct" function that // removes duplicate elements from a list. func interpolationFuncDistinct() ast.Function { @@ -641,6 +709,57 @@ func appendIfMissing(slice []string, element string) []string { return append(slice, element) } +// for two lists `keys` and `values` of equal length, returns all elements +// from `values` where the corresponding element from `keys` is in `searchset`. +func interpolationFuncMatchKeys() ast.Function { + return ast.Function{ + ArgTypes: []ast.Type{ast.TypeList, ast.TypeList, ast.TypeList}, + ReturnType: ast.TypeList, + Callback: func(args []interface{}) (interface{}, error) { + output := make([]ast.Variable, 0) + + values, _ := args[0].([]ast.Variable) + keys, _ := args[1].([]ast.Variable) + searchset, _ := args[2].([]ast.Variable) + + if len(keys) != len(values) { + return nil, fmt.Errorf("length of keys and values should be equal") + } + + for i, key := range keys { + for _, search := range searchset { + if res, err := compareSimpleVariables(key, search); err != nil { + return nil, err + } else if res == true { + output = append(output, values[i]) + break + } + } + } + // if searchset is empty, then output is an empty list as well. + // if we haven't matched any key, then output is an empty list. + return output, nil + }, + } +} + +// compare two variables of the same type, i.e. non complex one, such as TypeList or TypeMap +func compareSimpleVariables(a, b ast.Variable) (bool, error) { + if a.Type != b.Type { + return false, fmt.Errorf( + "won't compare items of different types %s and %s", + a.Type.Printable(), b.Type.Printable()) + } + switch a.Type { + case ast.TypeString: + return a.Value.(string) == b.Value.(string), nil + default: + return false, fmt.Errorf( + "can't compare items of type %s", + a.Type.Printable()) + } +} + // interpolationFuncJoin implements the "join" function that allows // multi-variable values to be joined by some character. func interpolationFuncJoin() ast.Function { @@ -1006,6 +1125,17 @@ func interpolationFuncValues(vs map[string]ast.Variable) ast.Function { } } +// interpolationFuncBasename implements the "basename" function. +func interpolationFuncBasename() ast.Function { + return ast.Function{ + ArgTypes: []ast.Type{ast.TypeString}, + ReturnType: ast.TypeString, + Callback: func(args []interface{}) (interface{}, error) { + return filepath.Base(args[0].(string)), nil + }, + } +} + // interpolationFuncBase64Encode implements the "base64encode" function that // allows Base64 encoding. func interpolationFuncBase64Encode() ast.Function { @@ -1125,6 +1255,20 @@ func interpolationFuncSha256() ast.Function { } } +func interpolationFuncSha512() ast.Function { + return ast.Function{ + ArgTypes: []ast.Type{ast.TypeString}, + ReturnType: ast.TypeString, + Callback: func(args []interface{}) (interface{}, error) { + s := args[0].(string) + h := sha512.New() + h.Write([]byte(s)) + hash := hex.EncodeToString(h.Sum(nil)) + return hash, nil + }, + } +} + func interpolationFuncTrimSpace() ast.Function { return ast.Function{ ArgTypes: []ast.Type{ast.TypeString}, @@ -1151,6 +1295,21 @@ func interpolationFuncBase64Sha256() ast.Function { } } +func interpolationFuncBase64Sha512() ast.Function { + return ast.Function{ + ArgTypes: []ast.Type{ast.TypeString}, + ReturnType: ast.TypeString, + Callback: func(args []interface{}) (interface{}, error) { + s := args[0].(string) + h := sha512.New() + h.Write([]byte(s)) + shaSum := h.Sum(nil) + encoded := base64.StdEncoding.EncodeToString(shaSum[:]) + return encoded, nil + }, + } +} + func interpolationFuncUUID() ast.Function { return ast.Function{ ArgTypes: []ast.Type{}, diff --git a/config/interpolate_funcs_test.go b/config/interpolate_funcs_test.go index c5ef36da5..6ed65a6f4 100644 --- a/config/interpolate_funcs_test.go +++ b/config/interpolate_funcs_test.go @@ -370,6 +370,88 @@ func TestInterpolateFuncCeil(t *testing.T) { }) } +func TestInterpolateFuncLog(t *testing.T) { + testFunction(t, testFunctionConfig{ + Cases: []testFunctionCase{ + { + `${log(1, 10)}`, + "0", + false, + }, + { + `${log(10, 10)}`, + "1", + false, + }, + + { + `${log(0, 10)}`, + "-Inf", + false, + }, + { + `${log(10, 0)}`, + "-0", + false, + }, + }, + }) +} + +func TestInterpolateFuncChomp(t *testing.T) { + testFunction(t, testFunctionConfig{ + Cases: []testFunctionCase{ + { + `${chomp()}`, + nil, + true, + }, + + { + `${chomp("hello world")}`, + "hello world", + false, + }, + + { + fmt.Sprintf(`${chomp("%s")}`, "goodbye\ncruel\nworld"), + "goodbye\ncruel\nworld", + false, + }, + + { + fmt.Sprintf(`${chomp("%s")}`, "goodbye\r\nwindows\r\nworld"), + "goodbye\r\nwindows\r\nworld", + false, + }, + + { + fmt.Sprintf(`${chomp("%s")}`, "goodbye\ncruel\nworld\n"), + "goodbye\ncruel\nworld", + false, + }, + + { + fmt.Sprintf(`${chomp("%s")}`, "goodbye\ncruel\nworld\n\n\n\n"), + "goodbye\ncruel\nworld", + false, + }, + + { + fmt.Sprintf(`${chomp("%s")}`, "goodbye\r\nwindows\r\nworld\r\n"), + "goodbye\r\nwindows\r\nworld", + false, + }, + + { + fmt.Sprintf(`${chomp("%s")}`, "goodbye\r\nwindows\r\nworld\r\n\r\n\r\n\r\n"), + "goodbye\r\nwindows\r\nworld", + false, + }, + }, + }) +} + func TestInterpolateFuncMap(t *testing.T) { testFunction(t, testFunctionConfig{ Cases: []testFunctionCase{ @@ -487,11 +569,26 @@ func TestInterpolateFuncCidrHost(t *testing.T) { "192.168.1.5", false, }, + { + `${cidrhost("192.168.1.0/24", -5)}`, + "192.168.1.251", + false, + }, + { + `${cidrhost("192.168.1.0/24", -256)}`, + "192.168.1.0", + false, + }, { `${cidrhost("192.168.1.0/30", 255)}`, nil, true, // 255 doesn't fit in two bits }, + { + `${cidrhost("192.168.1.0/30", -255)}`, + nil, + true, // 255 doesn't fit in two bits + }, { `${cidrhost("not-a-cidr", 6)}`, nil, @@ -615,6 +712,33 @@ func TestInterpolateFuncCoalesce(t *testing.T) { }) } +func TestInterpolateFuncCoalesceList(t *testing.T) { + testFunction(t, testFunctionConfig{ + Cases: []testFunctionCase{ + { + `${coalescelist(list("first"), list("second"), list("third"))}`, + []interface{}{"first"}, + false, + }, + { + `${coalescelist(list(), list("second"), list("third"))}`, + []interface{}{"second"}, + false, + }, + { + `${coalescelist(list(), list(), list())}`, + []interface{}{}, + false, + }, + { + `${coalescelist(list("foo"))}`, + nil, + true, + }, + }, + }) +} + func TestInterpolateFuncConcat(t *testing.T) { testFunction(t, testFunctionConfig{ Cases: []testFunctionCase{ @@ -852,6 +976,18 @@ func TestInterpolateFuncMerge(t *testing.T) { } +func TestInterpolateFuncDirname(t *testing.T) { + testFunction(t, testFunctionConfig{ + Cases: []testFunctionCase{ + { + `${dirname("/foo/bar/baz")}`, + "/foo/bar", + false, + }, + }, + }) +} + func TestInterpolateFuncDistinct(t *testing.T) { testFunction(t, testFunctionConfig{ Cases: []testFunctionCase{ @@ -883,6 +1019,74 @@ func TestInterpolateFuncDistinct(t *testing.T) { }) } +func TestInterpolateFuncMatchKeys(t *testing.T) { + testFunction(t, testFunctionConfig{ + Cases: []testFunctionCase{ + // normal usage + { + `${matchkeys(list("a", "b", "c"), list("ref1", "ref2", "ref3"), list("ref2"))}`, + []interface{}{"b"}, + false, + }, + // normal usage 2, check the order + { + `${matchkeys(list("a", "b", "c"), list("ref1", "ref2", "ref3"), list("ref2", "ref1"))}`, + []interface{}{"a", "b"}, + false, + }, + // duplicate item in searchset + { + `${matchkeys(list("a", "b", "c"), list("ref1", "ref2", "ref3"), list("ref2", "ref2"))}`, + []interface{}{"b"}, + false, + }, + // no matches + { + `${matchkeys(list("a", "b", "c"), list("ref1", "ref2", "ref3"), list("ref4"))}`, + []interface{}{}, + false, + }, + // no matches 2 + { + `${matchkeys(list("a", "b", "c"), list("ref1", "ref2", "ref3"), list())}`, + []interface{}{}, + false, + }, + // zero case + { + `${matchkeys(list(), list(), list("nope"))}`, + []interface{}{}, + false, + }, + // complex values + { + `${matchkeys(list(list("a", "a")), list("a"), list("a"))}`, + []interface{}{[]interface{}{"a", "a"}}, + false, + }, + // errors + // different types + { + `${matchkeys(list("a"), list(1), list("a"))}`, + nil, + true, + }, + // different types + { + `${matchkeys(list("a"), list(list("a"), list("a")), list("a"))}`, + nil, + true, + }, + // lists of different length is an error + { + `${matchkeys(list("a"), list("a", "b"), list("a"))}`, + nil, + true, + }, + }, + }) +} + func TestInterpolateFuncFile(t *testing.T) { tf, err := ioutil.TempFile("", "tf") if err != nil { @@ -1777,6 +1981,18 @@ func TestInterpolateFuncElement(t *testing.T) { }) } +func TestInterpolateFuncBasename(t *testing.T) { + testFunction(t, testFunctionConfig{ + Cases: []testFunctionCase{ + { + `${basename("/foo/bar/baz")}`, + "baz", + false, + }, + }, + }) +} + func TestInterpolateFuncBase64Encode(t *testing.T) { testFunction(t, testFunctionConfig{ Cases: []testFunctionCase{ @@ -1882,6 +2098,18 @@ func TestInterpolateFuncSha256(t *testing.T) { }) } +func TestInterpolateFuncSha512(t *testing.T) { + testFunction(t, testFunctionConfig{ + Cases: []testFunctionCase{ + { + `${sha512("test")}`, + "ee26b0dd4af7e749aa1a8ee3c10ae9923f618980772e473f8819a5d4940e0db27ac185f8a0e1d5f84f88bc887fd67b143732c304cc5fa9ad8e6f57f50028a8ff", + false, + }, + }, + }) +} + func TestInterpolateFuncTitle(t *testing.T) { testFunction(t, testFunctionConfig{ Cases: []testFunctionCase{ @@ -1941,6 +2169,23 @@ func TestInterpolateFuncBase64Sha256(t *testing.T) { }) } +func TestInterpolateFuncBase64Sha512(t *testing.T) { + testFunction(t, testFunctionConfig{ + Cases: []testFunctionCase{ + { + `${base64sha512("test")}`, + "7iaw3Ur350mqGo7jwQrpkj9hiYB3Lkc/iBml1JQODbJ6wYX4oOHV+E+IvIh/1nsUNzLDBMxfqa2Ob1f1ACio/w==", + false, + }, + { // This will differ because we're base64-encoding hex represantiation, not raw bytes + `${base64encode(sha512("test"))}`, + "ZWUyNmIwZGQ0YWY3ZTc0OWFhMWE4ZWUzYzEwYWU5OTIzZjYxODk4MDc3MmU0NzNmODgxOWE1ZDQ5NDBlMGRiMjdhYzE4NWY4YTBlMWQ1Zjg0Zjg4YmM4ODdmZDY3YjE0MzczMmMzMDRjYzVmYTlhZDhlNmY1N2Y1MDAyOGE4ZmY=", + false, + }, + }, + }) +} + func TestInterpolateFuncMd5(t *testing.T) { testFunction(t, testFunctionConfig{ Cases: []testFunctionCase{ diff --git a/config/loader_hcl.go b/config/loader_hcl.go index a40ad5ba7..9abb1960f 100644 --- a/config/loader_hcl.go +++ b/config/loader_hcl.go @@ -327,6 +327,10 @@ func loadAtlasHcl(list *ast.ObjectList) (*AtlasConfig, error) { // represents exactly one module definition in the HCL configuration. // We leave it up to another pass to merge them together. func loadModulesHcl(list *ast.ObjectList) ([]*Module, error) { + if err := assertAllBlocksHaveNames("module", list); err != nil { + return nil, err + } + list = list.Children() if len(list.Items) == 0 { return nil, nil @@ -391,12 +395,12 @@ func loadModulesHcl(list *ast.ObjectList) ([]*Module, error) { // LoadOutputsHcl recurses into the given HCL object and turns // it into a mapping of outputs. func loadOutputsHcl(list *ast.ObjectList) ([]*Output, error) { - list = list.Children() - if len(list.Items) == 0 { - return nil, fmt.Errorf( - "'output' must be followed by exactly one string: a name") + if err := assertAllBlocksHaveNames("output", list); err != nil { + return nil, err } + list = list.Children() + // Go through each object and turn it into an actual result. result := make([]*Output, 0, len(list.Items)) for _, item := range list.Items { @@ -450,12 +454,12 @@ func loadOutputsHcl(list *ast.ObjectList) ([]*Output, error) { // LoadVariablesHcl recurses into the given HCL object and turns // it into a list of variables. func loadVariablesHcl(list *ast.ObjectList) ([]*Variable, error) { - list = list.Children() - if len(list.Items) == 0 { - return nil, fmt.Errorf( - "'variable' must be followed by exactly one strings: a name") + if err := assertAllBlocksHaveNames("variable", list); err != nil { + return nil, err } + list = list.Children() + // hclVariable is the structure each variable is decoded into type hclVariable struct { DeclaredType string `hcl:"type"` @@ -531,6 +535,10 @@ func loadVariablesHcl(list *ast.ObjectList) ([]*Variable, error) { // LoadProvidersHcl recurses into the given HCL object and turns // it into a mapping of provider configs. func loadProvidersHcl(list *ast.ObjectList) ([]*ProviderConfig, error) { + if err := assertAllBlocksHaveNames("provider", list); err != nil { + return nil, err + } + list = list.Children() if len(list.Items) == 0 { return nil, nil @@ -592,6 +600,10 @@ func loadProvidersHcl(list *ast.ObjectList) ([]*ProviderConfig, error) { // represents exactly one data definition in the HCL configuration. // We leave it up to another pass to merge them together. func loadDataResourcesHcl(list *ast.ObjectList) ([]*Resource, error) { + if err := assertAllBlocksHaveNames("data", list); err != nil { + return nil, err + } + list = list.Children() if len(list.Items) == 0 { return nil, nil @@ -901,6 +913,10 @@ func loadManagedResourcesHcl(list *ast.ObjectList) ([]*Resource, error) { } func loadProvisionersHcl(list *ast.ObjectList, connInfo map[string]interface{}) ([]*Provisioner, error) { + if err := assertAllBlocksHaveNames("provisioner", list); err != nil { + return nil, err + } + list = list.Children() if len(list.Items) == 0 { return nil, nil @@ -1023,6 +1039,29 @@ func hclObjectMap(os *hclobj.Object) map[string]ast.ListNode { } */ +// assertAllBlocksHaveNames returns an error if any of the items in +// the given object list are blocks without keys (like "module {}") +// or simple assignments (like "module = 1"). It returns nil if +// neither of these things are true. +// +// The given name is used in any generated error messages, and should +// be the name of the block we're dealing with. The given list should +// be the result of calling .Filter on an object list with that same +// name. +func assertAllBlocksHaveNames(name string, list *ast.ObjectList) error { + if elem := list.Elem(); len(elem.Items) != 0 { + switch et := elem.Items[0].Val.(type) { + case *ast.ObjectType: + pos := et.Lbrace + return fmt.Errorf("%s: %q must be followed by a name", pos, name) + default: + pos := elem.Items[0].Val.Pos() + return fmt.Errorf("%s: %q must be a configuration block", pos, name) + } + } + return nil +} + func checkHCLKeys(node ast.Node, valid []string) error { var list *ast.ObjectList switch n := node.(type) { diff --git a/config/loader_test.go b/config/loader_test.go index ace70d90e..a3aeb7321 100644 --- a/config/loader_test.go +++ b/config/loader_test.go @@ -314,6 +314,18 @@ func TestLoadFileBasic_modules(t *testing.T) { } } +func TestLoadFile_unnamedModule(t *testing.T) { + _, err := LoadFile(filepath.Join(fixtureDir, "module-unnamed.tf")) + if err == nil { + t.Fatalf("bad: expected error") + } + + errorStr := err.Error() + if !strings.Contains(errorStr, `"module" must be followed`) { + t.Fatalf("bad: expected error has wrong text: %s", errorStr) + } +} + func TestLoadFile_outputDependsOn(t *testing.T) { c, err := LoadFile(filepath.Join(fixtureDir, "output-depends-on.tf")) if err != nil { @@ -684,7 +696,7 @@ func TestLoadFile_badVariableTypes(t *testing.T) { } errorStr := err.Error() - if !strings.Contains(errorStr, "'bad_type' must be of type string") { + if !strings.Contains(errorStr, "'bad_type' type must be one of") { t.Fatalf("bad: expected error has wrong text: %s", errorStr) } } @@ -696,7 +708,7 @@ func TestLoadFile_variableNoName(t *testing.T) { } errorStr := err.Error() - if !strings.Contains(errorStr, "'variable' must be followed") { + if !strings.Contains(errorStr, `"variable" must be followed`) { t.Fatalf("bad: expected error has wrong text: %s", errorStr) } } @@ -740,7 +752,7 @@ func TestLoadFile_unnamedOutput(t *testing.T) { } errorStr := err.Error() - if !strings.Contains(errorStr, "'output' must be followed") { + if !strings.Contains(errorStr, `"output" must be followed`) { t.Fatalf("bad: expected error has wrong text: %s", errorStr) } } diff --git a/config/resource_mode_string.go b/config/resource_mode_string.go index 930645fa8..ea68b4fcd 100644 --- a/config/resource_mode_string.go +++ b/config/resource_mode_string.go @@ -1,4 +1,4 @@ -// Code generated by "stringer -type=ResourceMode -output=resource_mode_string.go resource_mode.go"; DO NOT EDIT +// Code generated by "stringer -type=ResourceMode -output=resource_mode_string.go resource_mode.go"; DO NOT EDIT. package config diff --git a/config/test-fixtures/module-unnamed.tf b/config/test-fixtures/module-unnamed.tf new file mode 100644 index 000000000..e285519bf --- /dev/null +++ b/config/test-fixtures/module-unnamed.tf @@ -0,0 +1,7 @@ +module "okay" { + source = "./okay" +} + +module { + source = "./not-okay" +} diff --git a/config/test-fixtures/output-unnamed.tf b/config/test-fixtures/output-unnamed.tf index 7e7529153..7ef8ebe1b 100644 --- a/config/test-fixtures/output-unnamed.tf +++ b/config/test-fixtures/output-unnamed.tf @@ -1,3 +1,7 @@ +output "okay" { + value = "bar" +} + output { value = "foo" } diff --git a/config/test-fixtures/validate-var-default-interpolate-escaped/main.tf b/config/test-fixtures/validate-var-default-interpolate-escaped/main.tf new file mode 100644 index 000000000..da2758f6a --- /dev/null +++ b/config/test-fixtures/validate-var-default-interpolate-escaped/main.tf @@ -0,0 +1,5 @@ +variable "foo" { + # This should be considered valid since the sequence is escaped and is + # thus not actually an interpolation. + default = "foo bar $${aws_instance.foo.bar}" +} diff --git a/config/test-fixtures/variable-no-name.tf b/config/test-fixtures/variable-no-name.tf index f3856886f..7f09d1e64 100644 --- a/config/test-fixtures/variable-no-name.tf +++ b/config/test-fixtures/variable-no-name.tf @@ -1,3 +1,6 @@ +variable "okay" { +} + variable { name = "test" default = "test_value" diff --git a/contrib/fish-completion/README.md b/contrib/fish-completion/README.md new file mode 100644 index 000000000..a50ed1e81 --- /dev/null +++ b/contrib/fish-completion/README.md @@ -0,0 +1,10 @@ +# Terraform fish shell completion + +Copy the completions to your local fish configuration: + +``` +mkdir -p ~/.config/fish/completions +cp terraform.fish ~/.config/fish/completions +``` + +Please note that these completions have been merged upstream and should be bundled with fish 2.6 or later. diff --git a/contrib/fish-completion/terraform.fish b/contrib/fish-completion/terraform.fish new file mode 100644 index 000000000..41f3660f7 --- /dev/null +++ b/contrib/fish-completion/terraform.fish @@ -0,0 +1,171 @@ +# general options +complete -f -c terraform -l version -d 'Print version information' +complete -f -c terraform -l help -d 'Show help' + +### apply +complete -f -c terraform -n '__fish_use_subcommand' -a apply -d 'Build or change infrastructure' +complete -f -c terraform -n '__fish_seen_subcommand_from apply' -o backup -d 'Path to backup the existing state file' +complete -f -c terraform -n '__fish_seen_subcommand_from apply' -o lock -d 'Lock the state file when locking is supported' +complete -f -c terraform -n '__fish_seen_subcommand_from apply' -o lock-timeout -d 'Duration to retry a state lock' +complete -f -c terraform -n '__fish_seen_subcommand_from apply' -o input -d 'Ask for input for variables if not directly set' +complete -f -c terraform -n '__fish_seen_subcommand_from apply' -o no-color -d 'If specified, output won\'t contain any color' +complete -f -c terraform -n '__fish_seen_subcommand_from apply' -o parallelism -d 'Limit the number of concurrent operations' +complete -f -c terraform -n '__fish_seen_subcommand_from apply' -o refresh -d 'Update state prior to checking for differences' +complete -f -c terraform -n '__fish_seen_subcommand_from apply' -o state -d 'Path to a Terraform state file' +complete -f -c terraform -n '__fish_seen_subcommand_from apply' -o state-out -d 'Path to write state' +complete -f -c terraform -n '__fish_seen_subcommand_from apply' -o target -d 'Resource to target' +complete -f -c terraform -n '__fish_seen_subcommand_from apply' -o var -d 'Set a variable in the Terraform configuration' +complete -f -c terraform -n '__fish_seen_subcommand_from apply' -o var-file -d 'Set variables from a file' + +### console +complete -f -c terraform -n '__fish_use_subcommand' -a console -d 'Interactive console for Terraform interpolations' +complete -f -c terraform -n '__fish_seen_subcommand_from console' -o state -d 'Path to a Terraform state file' +complete -f -c terraform -n '__fish_seen_subcommand_from console' -o var -d 'Set a variable in the Terraform configuration' +complete -f -c terraform -n '__fish_seen_subcommand_from console' -o var-file -d 'Set variables from a file' + +### destroy +complete -f -c terraform -n '__fish_use_subcommand' -a destroy -d 'Destroy Terraform-managed infrastructure' +complete -f -c terraform -n '__fish_seen_subcommand_from destroy' -o backup -d 'Path to backup the existing state file' +complete -f -c terraform -n '__fish_seen_subcommand_from destroy' -o force -d 'Don\'t ask for input for destroy confirmation' +complete -f -c terraform -n '__fish_seen_subcommand_from destroy' -o lock -d 'Lock the state file when locking is supported' +complete -f -c terraform -n '__fish_seen_subcommand_from destroy' -o lock-timeout -d 'Duration to retry a state lock' +complete -f -c terraform -n '__fish_seen_subcommand_from destroy' -o no-color -d 'If specified, output won\'t contain any color' +complete -f -c terraform -n '__fish_seen_subcommand_from destroy' -o parallelism -d 'Limit the number of concurrent operations' +complete -f -c terraform -n '__fish_seen_subcommand_from destroy' -o refresh -d 'Update state prior to checking for differences' +complete -f -c terraform -n '__fish_seen_subcommand_from destroy' -o state -d 'Path to a Terraform state file' +complete -f -c terraform -n '__fish_seen_subcommand_from destroy' -o state-out -d 'Path to write state' +complete -f -c terraform -n '__fish_seen_subcommand_from destroy' -o target -d 'Resource to target' +complete -f -c terraform -n '__fish_seen_subcommand_from destroy' -o var -d 'Set a variable in the Terraform configuration' +complete -f -c terraform -n '__fish_seen_subcommand_from destroy' -o var-file -d 'Set variables from a file' + +### env +complete -f -c terraform -n '__fish_use_subcommand' -a env -d 'Environment management' +complete -f -c terraform -n '__fish_seen_subcommand_from env' -a list -d 'List environments' +complete -f -c terraform -n '__fish_seen_subcommand_from env' -a select -d 'Select an environment' +complete -f -c terraform -n '__fish_seen_subcommand_from env' -a new -d 'Create a new environment' +complete -f -c terraform -n '__fish_seen_subcommand_from env' -a delete -d 'Delete an existing environment' + +### fmt +complete -f -c terraform -n '__fish_use_subcommand' -a fmt -d 'Rewrite config files to canonical format' +complete -f -c terraform -n '__fish_seen_subcommand_from fmt' -o list -d 'List files whose formatting differs' +complete -f -c terraform -n '__fish_seen_subcommand_from fmt' -o write -d 'Write result to source file' +complete -f -c terraform -n '__fish_seen_subcommand_from fmt' -o diff -d 'Display diffs of formatting changes' + +### get +complete -f -c terraform -n '__fish_use_subcommand' -a get -d 'Download and install modules for the configuration' +complete -f -c terraform -n '__fish_seen_subcommand_from get' -o update -d 'Check modules for updates' +complete -f -c terraform -n '__fish_seen_subcommand_from get' -o no-color -d 'If specified, output won\'t contain any color' + +### graph +complete -f -c terraform -n '__fish_use_subcommand' -a graph -d 'Create a visual graph of Terraform resources' +complete -f -c terraform -n '__fish_seen_subcommand_from graph' -o draw-cycles -d 'Highlight any cycles in the graph' +complete -f -c terraform -n '__fish_seen_subcommand_from graph' -o no-color -d 'If specified, output won\'t contain any color' +complete -f -c terraform -n '__fish_seen_subcommand_from graph' -o type -d 'Type of graph to output' + +### import +complete -f -c terraform -n '__fish_use_subcommand' -a import -d 'Import existing infrastructure into Terraform' +complete -f -c terraform -n '__fish_seen_subcommand_from import' -o backup -d 'Path to backup the existing state file' +complete -f -c terraform -n '__fish_seen_subcommand_from import' -o config -d 'Path to a directory of configuration files' +complete -f -c terraform -n '__fish_seen_subcommand_from import' -o input -d 'Ask for input for variables if not directly set' +complete -f -c terraform -n '__fish_seen_subcommand_from import' -o lock -d 'Lock the state file when locking is supported' +complete -f -c terraform -n '__fish_seen_subcommand_from import' -o lock-timeout -d 'Duration to retry a state lock' +complete -f -c terraform -n '__fish_seen_subcommand_from import' -o no-color -d 'If specified, output won\'t contain any color' +complete -f -c terraform -n '__fish_seen_subcommand_from import' -o provider -d 'Specific provider to use for import' +complete -f -c terraform -n '__fish_seen_subcommand_from import' -o state -d 'Path to a Terraform state file' +complete -f -c terraform -n '__fish_seen_subcommand_from import' -o state-out -d 'Path to write state' +complete -f -c terraform -n '__fish_seen_subcommand_from import' -o var -d 'Set a variable in the Terraform configuration' +complete -f -c terraform -n '__fish_seen_subcommand_from import' -o var-file -d 'Set variables from a file' + +### init +complete -f -c terraform -n '__fish_use_subcommand' -a init -d 'Initialize a new or existing Terraform configuration' +complete -f -c terraform -n '__fish_seen_subcommand_from init' -o backend -d 'Configure the backend for this environment' +complete -f -c terraform -n '__fish_seen_subcommand_from init' -o backend-config -d 'Backend configuration' +complete -f -c terraform -n '__fish_seen_subcommand_from init' -o get -d 'Download modules for this configuration' +complete -f -c terraform -n '__fish_seen_subcommand_from init' -o input -d 'Ask for input if necessary' +complete -f -c terraform -n '__fish_seen_subcommand_from init' -o lock -d 'Lock the state file when locking is supported' +complete -f -c terraform -n '__fish_seen_subcommand_from init' -o lock-timeout -d 'Duration to retry a state lock' +complete -f -c terraform -n '__fish_seen_subcommand_from init' -o no-color -d 'If specified, output won\'t contain any color' +complete -f -c terraform -n '__fish_seen_subcommand_from init' -o force-copy -d 'Suppress prompts about copying state data' + +### output +complete -f -c terraform -n '__fish_use_subcommand' -a output -d 'Read an output from a state file' +complete -f -c terraform -n '__fish_seen_subcommand_from output' -o state -d 'Path to the state file to read' +complete -f -c terraform -n '__fish_seen_subcommand_from output' -o no-color -d 'If specified, output won\'t contain any color' +complete -f -c terraform -n '__fish_seen_subcommand_from output' -o module -d 'Return the outputs for a specific module' +complete -f -c terraform -n '__fish_seen_subcommand_from output' -o json -d 'Print output in JSON format' + +### plan +complete -f -c terraform -n '__fish_use_subcommand' -a plan -d 'Generate and show an execution plan' +complete -f -c terraform -n '__fish_seen_subcommand_from plan' -o destroy -d 'Generate a plan to destroy all resources' +complete -f -c terraform -n '__fish_seen_subcommand_from plan' -o detailed-exitcode -d 'Return detailed exit codes' +complete -f -c terraform -n '__fish_seen_subcommand_from plan' -o input -d 'Ask for input for variables if not directly set' +complete -f -c terraform -n '__fish_seen_subcommand_from plan' -o lock -d 'Lock the state file when locking is supported' +complete -f -c terraform -n '__fish_seen_subcommand_from plan' -o lock-timeout -d 'Duration to retry a state lock' +complete -f -c terraform -n '__fish_seen_subcommand_from plan' -o module-depth -d 'Depth of modules to show in the output' +complete -f -c terraform -n '__fish_seen_subcommand_from plan' -o no-color -d 'If specified, output won\'t contain any color' +complete -f -c terraform -n '__fish_seen_subcommand_from plan' -o out -d 'Write a plan file to the given path' +complete -f -c terraform -n '__fish_seen_subcommand_from plan' -o parallelism -d 'Limit the number of concurrent operations' +complete -f -c terraform -n '__fish_seen_subcommand_from plan' -o refresh -d 'Update state prior to checking for differences' +complete -f -c terraform -n '__fish_seen_subcommand_from plan' -o state -d 'Path to a Terraform state file' +complete -f -c terraform -n '__fish_seen_subcommand_from plan' -o target -d 'Resource to target' +complete -f -c terraform -n '__fish_seen_subcommand_from plan' -o var -d 'Set a variable in the Terraform configuration' +complete -f -c terraform -n '__fish_seen_subcommand_from plan' -o var-file -d 'Set variables from a file' + +### push +complete -f -c terraform -n '__fish_use_subcommand' -a push -d 'Upload this Terraform module to Atlas to run' +complete -f -c terraform -n '__fish_seen_subcommand_from push' -o atlas-address -d 'An alternate address to an Atlas instance' +complete -f -c terraform -n '__fish_seen_subcommand_from push' -o upload-modules -d 'Lock modules and upload completely' +complete -f -c terraform -n '__fish_seen_subcommand_from push' -o name -d 'Name of the configuration in Atlas' +complete -f -c terraform -n '__fish_seen_subcommand_from push' -o token -d 'Access token to use to upload' +complete -f -c terraform -n '__fish_seen_subcommand_from push' -o overwrite -d 'Variable keys that should overwrite values in Atlas' +complete -f -c terraform -n '__fish_seen_subcommand_from push' -o var -d 'Set a variable in the Terraform configuration' +complete -f -c terraform -n '__fish_seen_subcommand_from push' -o var-file -d 'Set variables from a file' +complete -f -c terraform -n '__fish_seen_subcommand_from push' -o vcs -d 'Upload only files committed to your VCS' +complete -f -c terraform -n '__fish_seen_subcommand_from push' -o no-color -d 'If specified, output won\'t contain any color' + +### refresh +complete -f -c terraform -n '__fish_use_subcommand' -a refresh -d 'Update local state file against real resources' +complete -f -c terraform -n '__fish_seen_subcommand_from refresh' -o backup -d 'Path to backup the existing state file' +complete -f -c terraform -n '__fish_seen_subcommand_from refresh' -o input -d 'Ask for input for variables if not directly set' +complete -f -c terraform -n '__fish_seen_subcommand_from refresh' -o lock -d 'Lock the state file when locking is supported' +complete -f -c terraform -n '__fish_seen_subcommand_from refresh' -o lock-timeout -d 'Duration to retry a state lock' +complete -f -c terraform -n '__fish_seen_subcommand_from refresh' -o no-color -d 'If specified, output won\'t contain any color' +complete -f -c terraform -n '__fish_seen_subcommand_from refresh' -o state -d 'Path to a Terraform state file' +complete -f -c terraform -n '__fish_seen_subcommand_from refresh' -o state-out -d 'Path to write state' +complete -f -c terraform -n '__fish_seen_subcommand_from refresh' -o target -d 'Resource to target' +complete -f -c terraform -n '__fish_seen_subcommand_from refresh' -o var -d 'Set a variable in the Terraform configuration' +complete -f -c terraform -n '__fish_seen_subcommand_from refresh' -o var-file -d 'Set variables from a file' + +### show +complete -f -c terraform -n '__fish_use_subcommand' -a show -d 'Inspect Terraform state or plan' +complete -f -c terraform -n '__fish_seen_subcommand_from show' -o module-depth -d 'Depth of modules to show in the output' +complete -f -c terraform -n '__fish_seen_subcommand_from show' -o no-color -d 'If specified, output won\'t contain any color' + +### taint +complete -f -c terraform -n '__fish_use_subcommand' -a taint -d 'Manually mark a resource for recreation' +complete -f -c terraform -n '__fish_seen_subcommand_from taint' -o allow-missing -d 'Succeed even if resource is missing' +complete -f -c terraform -n '__fish_seen_subcommand_from taint' -o backup -d 'Path to backup the existing state file' +complete -f -c terraform -n '__fish_seen_subcommand_from taint' -o lock -d 'Lock the state file when locking is supported' +complete -f -c terraform -n '__fish_seen_subcommand_from taint' -o lock-timeout -d 'Duration to retry a state lock' +complete -f -c terraform -n '__fish_seen_subcommand_from taint' -o module -d 'The module path where the resource lives' +complete -f -c terraform -n '__fish_seen_subcommand_from taint' -o no-color -d 'If specified, output won\'t contain any color' +complete -f -c terraform -n '__fish_seen_subcommand_from taint' -o state -d 'Path to a Terraform state file' +complete -f -c terraform -n '__fish_seen_subcommand_from taint' -o state-out -d 'Path to write state' + +### untaint +complete -f -c terraform -n '__fish_use_subcommand' -a untaint -d 'Manually unmark a resource as tainted' +complete -f -c terraform -n '__fish_seen_subcommand_from untaint' -o allow-missing -d 'Succeed even if resource is missing' +complete -f -c terraform -n '__fish_seen_subcommand_from untaint' -o backup -d 'Path to backup the existing state file' +complete -f -c terraform -n '__fish_seen_subcommand_from untaint' -o lock -d 'Lock the state file when locking is supported' +complete -f -c terraform -n '__fish_seen_subcommand_from untaint' -o lock-timeout -d 'Duration to retry a state lock' +complete -f -c terraform -n '__fish_seen_subcommand_from untaint' -o module -d 'The module path where the resource lives' +complete -f -c terraform -n '__fish_seen_subcommand_from untaint' -o no-color -d 'If specified, output won\'t contain any color' +complete -f -c terraform -n '__fish_seen_subcommand_from untaint' -o state -d 'Path to a Terraform state file' +complete -f -c terraform -n '__fish_seen_subcommand_from untaint' -o state-out -d 'Path to write state' + +### validate +complete -f -c terraform -n '__fish_use_subcommand' -a validate -d 'Validate the Terraform files' +complete -f -c terraform -n '__fish_seen_subcommand_from validate' -o no-color -d 'If specified, output won\'t contain any color' + +### version +complete -f -c terraform -n '__fish_use_subcommand' -a version -d 'Print the Terraform version' diff --git a/dag/set.go b/dag/set.go index 3929c9d0e..92b42151d 100644 --- a/dag/set.go +++ b/dag/set.go @@ -81,6 +81,20 @@ func (s *Set) Difference(other *Set) *Set { return result } +// Filter returns a set that contains the elements from the receiver +// where the given callback returns true. +func (s *Set) Filter(cb func(interface{}) bool) *Set { + result := new(Set) + + for _, v := range s.m { + if cb(v) { + result.Add(v) + } + } + + return result +} + // Len is the number of items in the set. func (s *Set) Len() int { if s == nil { diff --git a/dag/set_test.go b/dag/set_test.go index 8aeae7073..c70da475e 100644 --- a/dag/set_test.go +++ b/dag/set_test.go @@ -54,3 +54,45 @@ func TestSetDifference(t *testing.T) { }) } } + +func TestSetFilter(t *testing.T) { + cases := []struct { + Input []interface{} + Expected []interface{} + }{ + { + []interface{}{1, 2, 3}, + []interface{}{1, 2, 3}, + }, + + { + []interface{}{4, 5, 6}, + []interface{}{4}, + }, + + { + []interface{}{7, 8, 9}, + []interface{}{}, + }, + } + + for i, tc := range cases { + t.Run(fmt.Sprintf("%d-%#v", i, tc.Input), func(t *testing.T) { + var input, expected Set + for _, v := range tc.Input { + input.Add(v) + } + for _, v := range tc.Expected { + expected.Add(v) + } + + actual := input.Filter(func(v interface{}) bool { + return v.(int) < 5 + }) + match := actual.Intersection(&expected) + if match.Len() != expected.Len() { + t.Fatalf("bad: %#v", actual.List()) + } + }) + } +} diff --git a/dag/walk.go b/dag/walk.go index a74f1142a..23c87adc1 100644 --- a/dag/walk.go +++ b/dag/walk.go @@ -352,7 +352,7 @@ func (w *Walker) walkVertex(v Vertex, info *walkerVertex) { } // Check if we have updated dependencies. This can happen if the - // dependencies were satisfied exactly prior to an Update occuring. + // dependencies were satisfied exactly prior to an Update occurring. // In that case, we'd like to take into account new dependencies // if possible. info.DepsLock.Lock() diff --git a/docs/maintainer-etiquette.md b/docs/maintainer-etiquette.md new file mode 100644 index 000000000..eb3f90064 --- /dev/null +++ b/docs/maintainer-etiquette.md @@ -0,0 +1,91 @@ +# Maintainer's Etiquette + +Are you a core maintainer of Terraform? Great! Here's a few notes +to help you get comfortable when working on the project. + +## Expectations + +We value the time you spend on the project and as such your maintainer status +doesn't imply any obligations to do any specific work. + +### Your PRs + +These apply to all contributors, but maintainers should lead by examples! :wink: + + - for `provider/*` PRs it's useful to attach test results & advise on how to run the relevant tests + - for `bug`fixes it's useful to attach repro case, ideally in a form of a test + +### PRs/issues from others + + - you're welcomed to triage (attach labels to) other PRs and issues + - we generally use 2-label system (= at least 2 labels per issue/PR) where one label is generic and other one API-specific, e.g. `enhancement` & `provider/aws` + +## Merging + + - you're free to review PRs from the community or other HC employees and give :+1: / :-1: + - if the PR submitter has push privileges (recognizable via `Collaborator`, `Member` or `Owner` badge) - we expect **the submitter** to merge their own PR after receiving a positive review from either HC employee or another maintainer. _Exceptions apply - see below._ + - we prefer to use the Github's interface or API to do this, just click the green button + - squash? + - squash when you think the commit history is irrelevant (will not be helpful for any readers in T+6mons) + - Add the new PR to the **Changelog** if it may affect the user (almost any PR except test changes and docs updates) + - we prefer to use the Github's web interface to modify the Changelog and use `[GH-12345]` to format the PR number. These will be turned into links as part of the release process. Breaking changes should be always documented separately. + +## Release process + + - HC employees are responsible for cutting new releases + - The employee cutting the release will always notify all maintainers via Slack channel before & after each release + so you can avoid merging PRs during the release process. + +## Exceptions + +Any PR that is significantly changing or even breaking user experience cross-providers should always get at least one :+1: from a HC employee prior to merge. + +It is generally advisable to leave PRs labelled as `core` for HC employees to review and merge. + +Examples include: + - adding/changing/removing a CLI (sub)command or a [flag](https://github.com/hashicorp/terraform/pull/12939) + - introduce a new feature like [Environments](https://github.com/hashicorp/terraform/pull/12182) or [Shadow Graph](https://github.com/hashicorp/terraform/pull/9334) + - changing config (HCL) like [adding support for lists](https://github.com/hashicorp/terraform/pull/6322) + - change of the [build process or test environment](https://github.com/hashicorp/terraform/pull/9355) + +## Breaking Changes + + - we always try to avoid breaking changes where possible and/or defer them to the nearest major release + - [state migration](https://github.com/hashicorp/terraform/blob/2fe5976aec290f4b53f07534f4cde13f6d877a3f/helper/schema/resource.go#L33-L56) may help you avoid breaking changes, see [example](https://github.com/hashicorp/terraform/blob/351c6bed79abbb40e461d3f7d49fe4cf20bced41/builtin/providers/aws/resource_aws_route53_record_migrate.go) + - either way BCs should be clearly documented in special section of the Changelog + - Any BC must always receive at least one :+1: from HC employee prior to merge, two :+1:s are advisable + + ### Examples of Breaking Changes + + - https://github.com/hashicorp/terraform/pull/12396 + - https://github.com/hashicorp/terraform/pull/13872 + - https://github.com/hashicorp/terraform/pull/13752 + +## Unsure? + +If you're unsure about anything, ask in the committer's Slack channel. + +## New Providers + +These will require :+1: and some extra effort from HC employee. + +We expect all acceptance tests to be as self-sustainable as possible +to keep the bar for running any acceptance test low for anyone +outside of HashiCorp or core maintainers team. + +We expect any test to run **in parallel** alongside any other test (even the same test). +To ensure this is possible, we need all tests to avoid sharing namespaces or using static unique names. +In rare occasions this may require the use of mutexes in the resource code. + +### New Remote-API-based provider (e.g. AWS, Google Cloud, PagerDuty, Atlas) + +We will need some details about who to contact or where to register for a new account +and generally we can't merge providers before ensuring we have a way to test them nightly, +which usually involves setting up a new account and obtaining API credentials. + +### Local provider (e.g. MySQL, PostgreSQL, Kubernetes, Vault) + +We will need either Terraform configs that will set up the underlying test infrastructure +(e.g. GKE cluster for Kubernetes) or Dockerfile(s) that will prepare test environment (e.g. MySQL) +and expose the endpoint for testing. + diff --git a/examples/alicloud-ess-scaling/README.md b/examples/alicloud-ess-scaling/README.md new file mode 100644 index 000000000..3d9d2abb3 --- /dev/null +++ b/examples/alicloud-ess-scaling/README.md @@ -0,0 +1,17 @@ +### ESS scaling configuration Example + +The example launches ESS scaling configuration, will create ECS instance automatic by system schedule. + +### Get up and running + +* Planning phase + + terraform plan + +* Apply phase + + terraform apply + +* Destroy + + terraform destroy \ No newline at end of file diff --git a/examples/alicloud-ess-scaling/main.tf b/examples/alicloud-ess-scaling/main.tf new file mode 100644 index 000000000..0f7575bc9 --- /dev/null +++ b/examples/alicloud-ess-scaling/main.tf @@ -0,0 +1,38 @@ +data "alicloud_images" "ecs_image" { + most_recent = true + name_regex = "^centos_6\\w{1,5}[64].*" +} + +resource "alicloud_security_group" "sg" { + name = "${var.security_group_name}" + description = "tf-sg" +} + +resource "alicloud_security_group_rule" "ssh-in" { + type = "ingress" + ip_protocol = "tcp" + nic_type = "internet" + policy = "accept" + port_range = "22/22" + priority = 1 + security_group_id = "${alicloud_security_group.sg.id}" + cidr_ip = "0.0.0.0/0" +} + +resource "alicloud_ess_scaling_group" "scaling" { + min_size = "${var.scaling_min_size}" + max_size = "${var.scaling_max_size}" + scaling_group_name = "tf-scaling" + removal_policies = "${var.removal_policies}" + +} + +resource "alicloud_ess_scaling_configuration" "config" { + scaling_group_id = "${alicloud_ess_scaling_group.scaling.id}" + enable = "${var.enable}" + + image_id = "${data.alicloud_images.ecs_image.images.0.id}" + instance_type = "${var.ecs_instance_type}" + io_optimized = "optimized" + security_group_id = "${alicloud_security_group.sg.id}" +} \ No newline at end of file diff --git a/examples/alicloud-ess-scaling/outputs.tf b/examples/alicloud-ess-scaling/outputs.tf new file mode 100644 index 000000000..c4bfbb73e --- /dev/null +++ b/examples/alicloud-ess-scaling/outputs.tf @@ -0,0 +1,7 @@ +output "scaling_group_id" { + value = "${alicloud_ess_scaling_group.scaling.id}" +} + +output "configuration_id" { + value = "${alicloud_ess_scaling_configuration.config.id}" +} \ No newline at end of file diff --git a/examples/alicloud-ess-scaling/variables.tf b/examples/alicloud-ess-scaling/variables.tf new file mode 100644 index 000000000..11d2ef567 --- /dev/null +++ b/examples/alicloud-ess-scaling/variables.tf @@ -0,0 +1,24 @@ +variable "security_group_name" { + default = "tf-sg" +} + +variable "scaling_min_size" { + default = 1 +} + +variable "scaling_max_size" { + default = 1 +} + +variable "enable" { + default = true +} + +variable "removal_policies" { + type = "list" + default = ["OldestInstance", "NewestInstance"] +} + +variable "ecs_instance_type" { + default = "ecs.s2.large" +} \ No newline at end of file diff --git a/examples/alicloud-ess-schedule/README.md b/examples/alicloud-ess-schedule/README.md new file mode 100644 index 000000000..e606951b1 --- /dev/null +++ b/examples/alicloud-ess-schedule/README.md @@ -0,0 +1,17 @@ +### ESS scaling schedule Example + +The example launches ESS schedule task, which will create ECS by the schedule time. + +### Get up and running + +* Planning phase + + terraform plan + +* Apply phase + + terraform apply + +* Destroy + + terraform destroy \ No newline at end of file diff --git a/examples/alicloud-ess-schedule/main.tf b/examples/alicloud-ess-schedule/main.tf new file mode 100644 index 000000000..339ba670b --- /dev/null +++ b/examples/alicloud-ess-schedule/main.tf @@ -0,0 +1,51 @@ +data "alicloud_images" "ecs_image" { + most_recent = true + name_regex = "^centos_6\\w{1,5}[64].*" +} + +resource "alicloud_security_group" "sg" { + name = "${var.security_group_name}" + description = "tf-sg" +} + +resource "alicloud_security_group_rule" "ssh-in" { + type = "ingress" + ip_protocol = "tcp" + nic_type = "internet" + policy = "accept" + port_range = "22/22" + priority = 1 + security_group_id = "${alicloud_security_group.sg.id}" + cidr_ip = "0.0.0.0/0" +} + +resource "alicloud_ess_scaling_group" "scaling" { + min_size = "${var.scaling_min_size}" + max_size = "${var.scaling_max_size}" + scaling_group_name = "tf-scaling" + removal_policies = "${var.removal_policies}" + +} + +resource "alicloud_ess_scaling_configuration" "config" { + scaling_group_id = "${alicloud_ess_scaling_group.scaling.id}" + enable = "${var.enable}" + + image_id = "${data.alicloud_images.ecs_image.images.0.id}" + instance_type = "${var.ecs_instance_type}" + io_optimized = "optimized" + security_group_id = "${alicloud_security_group.sg.id}" +} + +resource "alicloud_ess_scaling_rule" "rule" { + scaling_group_id = "${alicloud_ess_scaling_group.scaling.id}" + adjustment_type = "TotalCapacity" + adjustment_value = "${var.rule_adjust_size}" + cooldown = 60 +} + +resource "alicloud_ess_schedule" "run" { + scheduled_action = "${alicloud_ess_scaling_rule.rule.ari}" + launch_time = "${var.schedule_launch_time}" + scheduled_task_name = "tf-run" +} \ No newline at end of file diff --git a/examples/alicloud-ess-schedule/outputs.tf b/examples/alicloud-ess-schedule/outputs.tf new file mode 100644 index 000000000..1d48aabfd --- /dev/null +++ b/examples/alicloud-ess-schedule/outputs.tf @@ -0,0 +1,11 @@ +output "scaling_group_id" { + value = "${alicloud_ess_scaling_group.scaling.id}" +} + +output "configuration_id" { + value = "${alicloud_ess_scaling_configuration.config.id}" +} + +output "configuration_ari" { + value = "${alicloud_ess_scaling_configuration.config.ari}" +} \ No newline at end of file diff --git a/examples/alicloud-ess-schedule/variables.tf b/examples/alicloud-ess-schedule/variables.tf new file mode 100644 index 000000000..fb95b6bee --- /dev/null +++ b/examples/alicloud-ess-schedule/variables.tf @@ -0,0 +1,32 @@ +variable "security_group_name" { + default = "tf-sg" +} + +variable "scaling_min_size" { + default = 1 +} + +variable "scaling_max_size" { + default = 1 +} + +variable "enable" { + default = true +} + +variable "removal_policies" { + type = "list" + default = ["OldestInstance", "NewestInstance"] +} + +variable "ecs_instance_type" { + default = "ecs.s2.large" +} + +variable "rule_adjust_size" { + default = 3 +} + +variable "schedule_launch_time" { + default = "2017-04-01T01:59Z" +} \ No newline at end of file diff --git a/examples/alicloud-vpc-snat/main.tf b/examples/alicloud-vpc-snat/main.tf new file mode 100644 index 000000000..1f204432a --- /dev/null +++ b/examples/alicloud-vpc-snat/main.tf @@ -0,0 +1,87 @@ +provider "alicloud" { + region = "cn-hangzhou" +} + +data "alicloud_instance_types" "1c2g" { + cpu_core_count = 1 + memory_size = 2 + instance_type_family = "ecs.n1" +} + +data "alicloud_zones" "default" { + "available_instance_type"= "${data.alicloud_instance_types.1c2g.instance_types.0.id}" + "available_disk_category"= "${var.disk_category}" +} + +resource "alicloud_vpc" "default" { + name = "tf_vpc" + cidr_block = "${var.vpc_cidr}" +} + +resource "alicloud_vswitch" "default" { + vpc_id = "${alicloud_vpc.default.id}" + cidr_block = "${var.vswitch_cidr}" + availability_zone = "${data.alicloud_zones.default.zones.0.id}" +} + +resource "alicloud_nat_gateway" "default" { + vpc_id = "${alicloud_vpc.default.id}" + spec = "Small" + name = "test_foo" + bandwidth_packages = [{ + ip_count = 2 + bandwidth = 5 + zone = "${data.alicloud_zones.default.zones.0.id}" + }] + depends_on = [ + "alicloud_vswitch.default"] +} +resource "alicloud_snat_entry" "default"{ + snat_table_id = "${alicloud_nat_gateway.default.snat_table_ids}" + source_vswitch_id = "${alicloud_vswitch.default.id}" + snat_ip = "${element(split(",", alicloud_nat_gateway.default.bandwidth_packages.0.public_ip_addresses),0)}" +} + +resource "alicloud_forward_entry" "default"{ + forward_table_id = "${alicloud_nat_gateway.default.forward_table_ids}" + external_ip = "${element(split(",", alicloud_nat_gateway.default.bandwidth_packages.0.public_ip_addresses),1)}" + external_port = "80" + ip_protocol = "tcp" + internal_ip = "${alicloud_instance.default.private_ip}" + internal_port = "8080" +} + +resource "alicloud_security_group" "sg" { + name = "tf_sg" + description = "tf_sg" + vpc_id = "${alicloud_vpc.default.id}" +} + +resource "alicloud_security_group_rule" "http-in" { + type = "ingress" + ip_protocol = "tcp" + nic_type = "intranet" + policy = "accept" + port_range = "80/80" + priority = 1 + security_group_id = "${alicloud_security_group.sg.id}" + cidr_ip = "0.0.0.0/0" +} + +resource "alicloud_instance" "default" { + # cn-beijing + availability_zone = "${data.alicloud_zones.default.zones.0.id}" + security_groups = ["${alicloud_security_group.sg.id}"] + + vswitch_id = "${alicloud_vswitch.default.id}" + + # series II + instance_charge_type = "PostPaid" + instance_type = "${var.instance_type}" + internet_max_bandwidth_out = 0 + io_optimized = "${var.io_optimized}" + + system_disk_category = "cloud_efficiency" + image_id = "${var.image_id}" + instance_name = "tf_vpc_snat" +} \ No newline at end of file diff --git a/examples/alicloud-vpc-snat/ouputs.tf b/examples/alicloud-vpc-snat/ouputs.tf new file mode 100644 index 000000000..f9a55914f --- /dev/null +++ b/examples/alicloud-vpc-snat/ouputs.tf @@ -0,0 +1,7 @@ +output "instance_id" { + value = "${alicloud_instance.default.id}" +} + +output "bindwidth_package_ip" { + value = "${alicloud_nat_gateway.default.bandwidth_packages.0.public_ip_addresses}" +} diff --git a/examples/alicloud-vpc-snat/variables.tf b/examples/alicloud-vpc-snat/variables.tf new file mode 100644 index 000000000..9e9eb76db --- /dev/null +++ b/examples/alicloud-vpc-snat/variables.tf @@ -0,0 +1,22 @@ + +variable "vpc_cidr" { + default = "10.1.0.0/21" +} +variable "vswitch_cidr" { + default = "10.1.1.0/24" +} +variable "rule_policy" { + default = "accept" +} +variable "instance_type" { + default = "ecs.n1.small" +} +variable "image_id" { + default = "ubuntu_140405_64_40G_cloudinit_20161115.vhd" +} +variable "io_optimized" { + default = "optimized" +} +variable "disk_category"{ + default = "cloud_efficiency" +} \ No newline at end of file diff --git a/examples/aws-ecs-alb/main.tf b/examples/aws-ecs-alb/main.tf index f0dd7d33b..aaa5bfad9 100644 --- a/examples/aws-ecs-alb/main.tf +++ b/examples/aws-ecs-alb/main.tf @@ -249,7 +249,7 @@ EOF resource "aws_iam_instance_profile" "app" { name = "tf-ecs-instprofile" - roles = ["${aws_iam_role.app_instance.name}"] + role = "${aws_iam_role.app_instance.name}" } resource "aws_iam_role" "app_instance" { diff --git a/examples/aws-two-tier/README.md b/examples/aws-two-tier/README.md index 3c0e54bc0..3920a15f4 100644 --- a/examples/aws-two-tier/README.md +++ b/examples/aws-two-tier/README.md @@ -26,7 +26,7 @@ Run with a command like this: ``` terraform apply -var 'key_name={your_aws_key_name}' \ - -var 'public_key_path={location_of_your_key_in_your_local_machine}'` + -var 'public_key_path={location_of_your_key_in_your_local_machine}' ``` For example: diff --git a/examples/azure-2-vms-loadbalancer-lbrules/README.md b/examples/azure-2-vms-loadbalancer-lbrules/README.md new file mode 100644 index 000000000..3d547056e --- /dev/null +++ b/examples/azure-2-vms-loadbalancer-lbrules/README.md @@ -0,0 +1,22 @@ +# Create 2 Virtual Machines under a Load balancer and configures Load Balancing rules for the VMs + +This Terraform template was based on [this](https://github.com/Azure/azure-quickstart-templates/tree/master/201-2-vms-loadbalancer-lbrules) Azure Quickstart Template. Changes to the ARM template may have occured since the creation of this example may not be reflected here. + +This template allows you to create 2 Virtual Machines under a Load balancer and configure a load balancing rule on Port 80. This template also deploys a Storage Account, Virtual Network, Public IP address, Availability Set, and Network Interfaces. + +## main.tf +The `main.tf` file contains the actual resources that will be deployed. It also contains the Azure Resource Group definition and any defined variables. + +## outputs.tf +This data is outputted when `terraform apply` is called, and can be queried using the `terraform output` command. + +## provider.tf +Azure requires that an application is added to Azure Active Directory to generate the `client_id`, `client_secret`, and `tenant_id` needed by Terraform (`subscription_id` can be recovered from your Azure account details). Please go [here](https://www.terraform.io/docs/providers/azurerm/) for full instructions on how to create this to populate your `provider.tf` file. + +## terraform.tfvars +If a `terraform.tfvars` file is present in the current directory, Terraform automatically loads it to populate variables. We don't recommend saving usernames and password to version control, but you can create a local secret variables file and use `-var-file` to load it. + +If you are committing this template to source control, please insure that you add this file to your .gitignore file. + +## variables.tf +The `variables.tf` file contains all of the input parameters that the user can specify when deploying this Terraform template. diff --git a/examples/azure-2-vms-loadbalancer-lbrules/deploy.ci.sh b/examples/azure-2-vms-loadbalancer-lbrules/deploy.ci.sh new file mode 100755 index 000000000..57e0dc9b1 --- /dev/null +++ b/examples/azure-2-vms-loadbalancer-lbrules/deploy.ci.sh @@ -0,0 +1,36 @@ +#!/bin/bash + +set -o errexit -o nounset + +docker run --rm -it \ + -e ARM_CLIENT_ID \ + -e ARM_CLIENT_SECRET \ + -e ARM_SUBSCRIPTION_ID \ + -e ARM_TENANT_ID \ + -v $(pwd):/data \ + --entrypoint "/bin/sh" \ + hashicorp/terraform:light \ + -c "cd /data; \ + /bin/terraform get; \ + /bin/terraform validate; \ + /bin/terraform plan -out=out.tfplan -var dns_name=$KEY -var hostname=$KEY -var lb_ip_dns_name=$KEY -var resource_group=$KEY -var admin_password=$PASSWORD; \ + /bin/terraform apply out.tfplan" + +# cleanup deployed azure resources via azure-cli +docker run --rm -it \ + azuresdk/azure-cli-python \ + sh -c "az login --service-principal -u $ARM_CLIENT_ID -p $ARM_CLIENT_SECRET --tenant $ARM_TENANT_ID > /dev/null; \ + az network lb show -g $KEY -n rglb; \ + az network lb rule list -g $KEY --lb-name rglb;" + +# cleanup deployed azure resources via terraform +docker run --rm -it \ + -e ARM_CLIENT_ID \ + -e ARM_CLIENT_SECRET \ + -e ARM_SUBSCRIPTION_ID \ + -e ARM_TENANT_ID \ + -v $(pwd):/data \ + --workdir=/data \ + --entrypoint "/bin/sh" \ + hashicorp/terraform:light \ + -c "/bin/terraform destroy -force -var dns_name=$KEY -var hostname=$KEY -var lb_ip_dns_name=$KEY -var resource_group=$KEY -var admin_password=$PASSWORD;" diff --git a/examples/azure-2-vms-loadbalancer-lbrules/deploy.mac.sh b/examples/azure-2-vms-loadbalancer-lbrules/deploy.mac.sh new file mode 100755 index 000000000..cf5cdc322 --- /dev/null +++ b/examples/azure-2-vms-loadbalancer-lbrules/deploy.mac.sh @@ -0,0 +1,15 @@ +#!/bin/bash + +set -o errexit -o nounset + +if docker -v; then + + # generate a unique string for CI deployment + export KEY=$(cat /dev/urandom | env LC_CTYPE=C tr -cd 'a-z' | head -c 12) + export PASSWORD=$KEY$(cat /dev/urandom | env LC_CTYPE=C tr -cd 'A-Z' | head -c 2)$(cat /dev/urandom | env LC_CTYPE=C tr -cd '0-9' | head -c 2) + +/bin/sh ./deploy.ci.sh + +else + echo "Docker is used to run terraform commands, please install before run: https://docs.docker.com/docker-for-mac/install/" +fi \ No newline at end of file diff --git a/examples/azure-2-vms-loadbalancer-lbrules/main.tf b/examples/azure-2-vms-loadbalancer-lbrules/main.tf new file mode 100644 index 000000000..495a5565f --- /dev/null +++ b/examples/azure-2-vms-loadbalancer-lbrules/main.tf @@ -0,0 +1,145 @@ +# provider "azurerm" { +# subscription_id = "REPLACE-WITH-YOUR-SUBSCRIPTION-ID" +# client_id = "REPLACE-WITH-YOUR-CLIENT-ID" +# client_secret = "REPLACE-WITH-YOUR-CLIENT-SECRET" +# tenant_id = "REPLACE-WITH-YOUR-TENANT-ID" +# } + +resource "azurerm_resource_group" "rg" { + name = "${var.resource_group}" + location = "${var.location}" +} + +resource "azurerm_storage_account" "stor" { + name = "${var.dns_name}stor" + location = "${var.location}" + resource_group_name = "${azurerm_resource_group.rg.name}" + account_type = "${var.storage_account_type}" +} + +resource "azurerm_availability_set" "avset" { + name = "${var.dns_name}avset" + location = "${var.location}" + resource_group_name = "${azurerm_resource_group.rg.name}" + platform_fault_domain_count = 2 + platform_update_domain_count = 2 + managed = true +} + +resource "azurerm_public_ip" "lbpip" { + name = "${var.rg_prefix}-ip" + location = "${var.location}" + resource_group_name = "${azurerm_resource_group.rg.name}" + public_ip_address_allocation = "dynamic" + domain_name_label = "${var.lb_ip_dns_name}" +} + +resource "azurerm_virtual_network" "vnet" { + name = "${var.virtual_network_name}" + location = "${var.location}" + address_space = ["${var.address_space}"] + resource_group_name = "${azurerm_resource_group.rg.name}" +} + +resource "azurerm_subnet" "subnet" { + name = "${var.rg_prefix}subnet" + virtual_network_name = "${azurerm_virtual_network.vnet.name}" + resource_group_name = "${azurerm_resource_group.rg.name}" + address_prefix = "${var.subnet_prefix}" +} + +resource "azurerm_lb" "lb" { + resource_group_name = "${azurerm_resource_group.rg.name}" + name = "${var.rg_prefix}lb" + location = "${var.location}" + + frontend_ip_configuration { + name = "LoadBalancerFrontEnd" + public_ip_address_id = "${azurerm_public_ip.lbpip.id}" + } +} + +resource "azurerm_lb_backend_address_pool" "backend_pool" { + resource_group_name = "${azurerm_resource_group.rg.name}" + loadbalancer_id = "${azurerm_lb.lb.id}" + name = "BackendPool1" +} + +resource "azurerm_lb_nat_rule" "tcp" { + resource_group_name = "${azurerm_resource_group.rg.name}" + loadbalancer_id = "${azurerm_lb.lb.id}" + name = "RDP-VM-${count.index}" + protocol = "tcp" + frontend_port = "5000${count.index + 1}" + backend_port = 3389 + frontend_ip_configuration_name = "LoadBalancerFrontEnd" + count = 2 +} + +resource "azurerm_lb_rule" "lb_rule" { + resource_group_name = "${azurerm_resource_group.rg.name}" + loadbalancer_id = "${azurerm_lb.lb.id}" + name = "LBRule" + protocol = "tcp" + frontend_port = 80 + backend_port = 80 + frontend_ip_configuration_name = "LoadBalancerFrontEnd" + enable_floating_ip = false + backend_address_pool_id = "${azurerm_lb_backend_address_pool.backend_pool.id}" + idle_timeout_in_minutes = 5 + probe_id = "${azurerm_lb_probe.lb_probe.id}" + depends_on = ["azurerm_lb_probe.lb_probe"] +} + +resource "azurerm_lb_probe" "lb_probe" { + resource_group_name = "${azurerm_resource_group.rg.name}" + loadbalancer_id = "${azurerm_lb.lb.id}" + name = "tcpProbe" + protocol = "tcp" + port = 80 + interval_in_seconds = 5 + number_of_probes = 2 +} + +resource "azurerm_network_interface" "nic" { + name = "nic${count.index}" + location = "${var.location}" + resource_group_name = "${azurerm_resource_group.rg.name}" + count = 2 + + ip_configuration { + name = "ipconfig${count.index}" + subnet_id = "${azurerm_subnet.subnet.id}" + private_ip_address_allocation = "Dynamic" + load_balancer_backend_address_pools_ids = ["${azurerm_lb_backend_address_pool.backend_pool.id}"] + load_balancer_inbound_nat_rules_ids = ["${element(azurerm_lb_nat_rule.tcp.*.id, count.index)}"] + } +} + +resource "azurerm_virtual_machine" "vm" { + name = "vm${count.index}" + location = "${var.location}" + resource_group_name = "${azurerm_resource_group.rg.name}" + availability_set_id = "${azurerm_availability_set.avset.id}" + vm_size = "${var.vm_size}" + network_interface_ids = ["${element(azurerm_network_interface.nic.*.id, count.index)}"] + count = 2 + + storage_image_reference { + publisher = "${var.image_publisher}" + offer = "${var.image_offer}" + sku = "${var.image_sku}" + version = "${var.image_version}" + } + + storage_os_disk { + name = "osdisk${count.index}" + create_option = "FromImage" + } + + os_profile { + computer_name = "${var.hostname}" + admin_username = "${var.admin_username}" + admin_password = "${var.admin_password}" + } +} diff --git a/examples/azure-2-vms-loadbalancer-lbrules/outputs.tf b/examples/azure-2-vms-loadbalancer-lbrules/outputs.tf new file mode 100644 index 000000000..19757fa52 --- /dev/null +++ b/examples/azure-2-vms-loadbalancer-lbrules/outputs.tf @@ -0,0 +1,11 @@ +output "hostname" { + value = "${var.hostname}" +} + +output "vm_fqdn" { + value = "${azurerm_public_ip.lbpip.fqdn}" +} + +output "ssh_command" { + value = "ssh ${var.admin_username}@${azurerm_public_ip.lbpip.fqdn}" +} diff --git a/examples/azure-2-vms-loadbalancer-lbrules/variables.tf b/examples/azure-2-vms-loadbalancer-lbrules/variables.tf new file mode 100644 index 000000000..0e652606a --- /dev/null +++ b/examples/azure-2-vms-loadbalancer-lbrules/variables.tf @@ -0,0 +1,79 @@ +variable "resource_group" { + description = "The name of the resource group in which to create the virtual network." +} + +variable "rg_prefix" { + description = "The shortened abbreviation to represent your resource group that will go on the front of some resources." + default = "rg" +} + +variable "hostname" { + description = "VM name referenced also in storage-related names." +} + +variable "dns_name" { + description = " Label for the Domain Name. Will be used to make up the FQDN. If a domain name label is specified, an A DNS record is created for the public IP in the Microsoft Azure DNS system." +} + +variable "lb_ip_dns_name" { + description = "DNS for Load Balancer IP" +} + +variable "location" { + description = "The location/region where the virtual network is created. Changing this forces a new resource to be created." + default = "southcentralus" +} + +variable "virtual_network_name" { + description = "The name for the virtual network." + default = "vnet" +} + +variable "address_space" { + description = "The address space that is used by the virtual network. You can supply more than one address space. Changing this forces a new resource to be created." + default = "10.0.0.0/16" +} + +variable "subnet_prefix" { + description = "The address prefix to use for the subnet." + default = "10.0.10.0/24" +} + +variable "storage_account_type" { + description = "Defines the type of storage account to be created. Valid options are Standard_LRS, Standard_ZRS, Standard_GRS, Standard_RAGRS, Premium_LRS. Changing this is sometimes valid - see the Azure documentation for more information on which types of accounts can be converted into other types." + default = "Standard_LRS" +} + +variable "vm_size" { + description = "Specifies the size of the virtual machine." + default = "Standard_D1" +} + +variable "image_publisher" { + description = "name of the publisher of the image (az vm image list)" + default = "MicrosoftWindowsServer" +} + +variable "image_offer" { + description = "the name of the offer (az vm image list)" + default = "WindowsServer" +} + +variable "image_sku" { + description = "image sku to apply (az vm image list)" + default = "2012-R2-Datacenter" +} + +variable "image_version" { + description = "version of the image to apply (az vm image list)" + default = "latest" +} + +variable "admin_username" { + description = "administrator user name" + default = "vmadmin" +} + +variable "admin_password" { + description = "administrator password (recommended to disable password auth)" +} diff --git a/examples/azure-cdn-with-storage-account/README.md b/examples/azure-cdn-with-storage-account/README.md new file mode 100644 index 000000000..8d2d0377c --- /dev/null +++ b/examples/azure-cdn-with-storage-account/README.md @@ -0,0 +1,28 @@ +# Create a CDN Profile, a CDN Endpoint with a Storage Account as origin + +This Terraform template was based on [this](https://github.com/Azure/azure-quickstart-templates/tree/master/201-cdn-with-storage-account) Azure Quickstart Template. Changes to the ARM template that may have occurred since the creation of this example may not be reflected in this Terraform template. + +This template creates a [CDN Profile](https://docs.microsoft.com/en-us/azure/cdn/cdn-overview) and a CDN Endpoint with the origin as a Storage Account. Note that the user needs to create a public container in the Storage Account in order for CDN Endpoint to serve content from the Storage Account. + +# Important + +The endpoint will not immediately be available for use, as it takes time for the registration to propagate through the CDN. For Azure CDN from Akamai profiles, propagation will usually complete within one minute. For Azure CDN from Verizon profiles, propagation will usually complete within 90 minutes, but in some cases can take longer. + +Users who try to use the CDN domain name before the endpoint configuration has propagated to the POPs will receive HTTP 404 response codes. If it has been several hours since you created your endpoint and you're still receiving 404 responses, please see [Troubleshooting CDN endpoints returning 404 statuses](https://docs.microsoft.com/en-us/azure/cdn/cdn-troubleshoot-endpoint). + +## main.tf +The `main.tf` file contains the actual resources that will be deployed. It also contains the Azure Resource Group definition and any defined variables. + +## outputs.tf +This data is outputted when `terraform apply` is called, and can be queried using the `terraform output` command. + +## provider.tf +Azure requires that an application is added to Azure Active Directory to generate the `client_id`, `client_secret`, and `tenant_id` needed by Terraform (`subscription_id` can be recovered from your Azure account details). Please go [here](https://www.terraform.io/docs/providers/azurerm/) for full instructions on how to create this to populate your `provider.tf` file. + +## terraform.tfvars +If a `terraform.tfvars` file is present in the current directory, Terraform automatically loads it to populate variables. We don't recommend saving usernames and password to version control, but you can create a local secret variables file and use `-var-file` to load it. + +If you are committing this template to source control, please insure that you add this file to your `.gitignore` file. + +## variables.tf +The `variables.tf` file contains all of the input parameters that the user can specify when deploying this Terraform template. diff --git a/examples/azure-cdn-with-storage-account/deploy.ci.sh b/examples/azure-cdn-with-storage-account/deploy.ci.sh new file mode 100755 index 000000000..406ac1d9e --- /dev/null +++ b/examples/azure-cdn-with-storage-account/deploy.ci.sh @@ -0,0 +1,29 @@ +#!/bin/bash + +set -o errexit -o nounset + +docker run --rm -it \ + -e ARM_CLIENT_ID \ + -e ARM_CLIENT_SECRET \ + -e ARM_SUBSCRIPTION_ID \ + -e ARM_TENANT_ID \ + -v $(pwd):/data \ + --workdir=/data \ + --entrypoint "/bin/sh" \ + hashicorp/terraform:light \ + -c "/bin/terraform get; \ + /bin/terraform validate; \ + /bin/terraform plan -out=out.tfplan -var resource_group=$KEY; \ + /bin/terraform apply out.tfplan" + +# cleanup deployed azure resources via terraform +docker run --rm -it \ + -e ARM_CLIENT_ID \ + -e ARM_CLIENT_SECRET \ + -e ARM_SUBSCRIPTION_ID \ + -e ARM_TENANT_ID \ + -v $(pwd):/data \ + --workdir=/data \ + --entrypoint "/bin/sh" \ + hashicorp/terraform:light \ + -c "/bin/terraform destroy -force -var resource_group=$KEY;" \ No newline at end of file diff --git a/examples/azure-cdn-with-storage-account/deploy.mac.sh b/examples/azure-cdn-with-storage-account/deploy.mac.sh new file mode 100755 index 000000000..dfc34c2be --- /dev/null +++ b/examples/azure-cdn-with-storage-account/deploy.mac.sh @@ -0,0 +1,15 @@ +#!/bin/bash + +set -o errexit -o nounset + +if docker -v; then + + # generate a unique string for CI deployment + export KEY=$(cat /dev/urandom | env LC_CTYPE=C tr -cd 'a-z' | head -c 12) + export PASSWORD=$KEY$(cat /dev/urandom | env LC_CTYPE=C tr -cd 'A-Z' | head -c 2)$(cat /dev/urandom | env LC_CTYPE=C tr -cd '0-9' | head -c 2) + + /bin/sh ./deploy.ci.sh + +else + echo "Docker is used to run terraform commands, please install before run: https://docs.docker.com/docker-for-mac/install/" +fi \ No newline at end of file diff --git a/examples/azure-cdn-with-storage-account/graph.png b/examples/azure-cdn-with-storage-account/graph.png new file mode 100644 index 000000000..b68b0087f Binary files /dev/null and b/examples/azure-cdn-with-storage-account/graph.png differ diff --git a/examples/azure-cdn-with-storage-account/main.tf b/examples/azure-cdn-with-storage-account/main.tf new file mode 100644 index 000000000..0f50bb5eb --- /dev/null +++ b/examples/azure-cdn-with-storage-account/main.tf @@ -0,0 +1,39 @@ +# provider "azurerm" { +# subscription_id = "REPLACE-WITH-YOUR-SUBSCRIPTION-ID" +# client_id = "REPLACE-WITH-YOUR-CLIENT-ID" +# client_secret = "REPLACE-WITH-YOUR-CLIENT-SECRET" +# tenant_id = "REPLACE-WITH-YOUR-TENANT-ID" +# } + +resource "azurerm_resource_group" "rg" { + name = "${var.resource_group}" + location = "${var.location}" +} + +resource "azurerm_storage_account" "stor" { + name = "${var.resource_group}stor" + location = "${var.location}" + resource_group_name = "${azurerm_resource_group.rg.name}" + account_type = "${var.storage_account_type}" +} + +resource "azurerm_cdn_profile" "cdn" { + name = "${var.resource_group}CdnProfile1" + location = "${var.location}" + resource_group_name = "${azurerm_resource_group.rg.name}" + sku = "Standard_Akamai" +} + +resource "azurerm_cdn_endpoint" "cdnendpt" { + name = "${var.resource_group}CdnEndpoint1" + profile_name = "${azurerm_cdn_profile.cdn.name}" + location = "${var.location}" + resource_group_name = "${azurerm_resource_group.rg.name}" + + origin { + name = "${var.resource_group}Origin1" + host_name = "${var.host_name}" + http_port = 80 + https_port = 443 + } +} \ No newline at end of file diff --git a/examples/azure-cdn-with-storage-account/outputs.tf b/examples/azure-cdn-with-storage-account/outputs.tf new file mode 100644 index 000000000..8f7c1e5c8 --- /dev/null +++ b/examples/azure-cdn-with-storage-account/outputs.tf @@ -0,0 +1,3 @@ +output "CDN Endpoint ID" { + value = "${azurerm_cdn_endpoint.cdnendpt.name}.azureedge.net" +} diff --git a/examples/azure-cdn-with-storage-account/variables.tf b/examples/azure-cdn-with-storage-account/variables.tf new file mode 100644 index 000000000..d9bf51015 --- /dev/null +++ b/examples/azure-cdn-with-storage-account/variables.tf @@ -0,0 +1,18 @@ +variable "resource_group" { + description = "The name of the resource group in which to create the virtual network." +} + +variable "location" { + description = "The location/region where the virtual network is created. Changing this forces a new resource to be created." + default = "southcentralus" +} + +variable "storage_account_type" { + description = "Specifies the type of the storage account" + default = "Standard_LRS" +} + +variable "host_name" { + description = "A string that determines the hostname/IP address of the origin server. This string could be a domain name, IPv4 address or IPv6 address." + default = "www.hostnameoforiginserver.com" +} \ No newline at end of file diff --git a/examples/azure-search-create/README.md b/examples/azure-search-create/README.md new file mode 100644 index 000000000..268034a17 --- /dev/null +++ b/examples/azure-search-create/README.md @@ -0,0 +1,28 @@ +# Azure Search service + +This Terraform template was based on [this](https://github.com/Azure/azure-quickstart-templates/tree/bf842409eeeeb7c4523add3922b204793eb4d85f/101-azure-search-create) Azure Quickstart Template. Changes to the ARM template that may have occurred since the creation of this example may not be reflected in this Terraform template. + +This template creates a new Azure Search Service. + +If you are unclear as to what parameters are allowed you can check the [Azure Search Management REST API docs on MSDN](https://msdn.microsoft.com/en-us/library/azure/dn832687.aspx). + +## main.tf +The `main.tf` file contains the actual resources that will be deployed. It also contains the Azure Resource Group definition and any defined variables. + +## outputs.tf +This data is outputted when `terraform apply` is called, and can be queried using the `terraform output` command. + +## provider.tf +You may leave the provider block in the `main.tf`, as it is in this template, or you can create a file called `provider.tf` and add it to your `.gitignore` file. + +Azure requires that an application is added to Azure Active Directory to generate the `client_id`, `client_secret`, and `tenant_id` needed by Terraform (`subscription_id` can be recovered from your Azure account details). Please go [here](https://www.terraform.io/docs/providers/azurerm/) for full instructions on how to create this to populate your `provider.tf` file. + +## terraform.tfvars +If a `terraform.tfvars` file is present in the current directory, Terraform automatically loads it to populate variables. We don't recommend saving usernames and password to version control, but you can create a local secret variables file and use `-var-file` to load it. + +If you are committing this template to source control, please insure that you add this file to your `.gitignore` file. + +## variables.tf +The `variables.tf` file contains all of the input parameters that the user can specify when deploying this Terraform template. + +![graph](/examples/azure-search-create/graph.png) \ No newline at end of file diff --git a/examples/azure-search-create/deploy.ci.sh b/examples/azure-search-create/deploy.ci.sh new file mode 100755 index 000000000..cbd6773bf --- /dev/null +++ b/examples/azure-search-create/deploy.ci.sh @@ -0,0 +1,36 @@ +#!/bin/bash + +set -o errexit -o nounset + +docker run --rm -it \ + -e ARM_CLIENT_ID \ + -e ARM_CLIENT_SECRET \ + -e ARM_SUBSCRIPTION_ID \ + -e ARM_TENANT_ID \ + -v $(pwd):/data \ + --workdir=/data \ + --entrypoint "/bin/sh" \ + hashicorp/terraform:light \ + -c "/bin/terraform get; \ + /bin/terraform validate; \ + /bin/terraform plan -out=out.tfplan -var search_name=$KEY -var resource_group=$KEY; \ + /bin/terraform apply out.tfplan; \ + /bin/terraform show;" + +# cleanup deployed azure resources via azure-cli +docker run --rm -it \ + azuresdk/azure-cli-python \ + sh -c "az login --service-principal -u $ARM_CLIENT_ID -p $ARM_CLIENT_SECRET --tenant $ARM_TENANT_ID > /dev/null; \ + az resource list --name $KEY" + +# cleanup deployed azure resources via terraform +docker run --rm -it \ + -e ARM_CLIENT_ID \ + -e ARM_CLIENT_SECRET \ + -e ARM_SUBSCRIPTION_ID \ + -e ARM_TENANT_ID \ + -v $(pwd):/data \ + --workdir=/data \ + --entrypoint "/bin/sh" \ + hashicorp/terraform:light \ + -c "/bin/terraform destroy -force -var search_name=$KEY -var resource_group=$KEY;" \ No newline at end of file diff --git a/examples/azure-search-create/deploy.mac.sh b/examples/azure-search-create/deploy.mac.sh new file mode 100755 index 000000000..dfc34c2be --- /dev/null +++ b/examples/azure-search-create/deploy.mac.sh @@ -0,0 +1,15 @@ +#!/bin/bash + +set -o errexit -o nounset + +if docker -v; then + + # generate a unique string for CI deployment + export KEY=$(cat /dev/urandom | env LC_CTYPE=C tr -cd 'a-z' | head -c 12) + export PASSWORD=$KEY$(cat /dev/urandom | env LC_CTYPE=C tr -cd 'A-Z' | head -c 2)$(cat /dev/urandom | env LC_CTYPE=C tr -cd '0-9' | head -c 2) + + /bin/sh ./deploy.ci.sh + +else + echo "Docker is used to run terraform commands, please install before run: https://docs.docker.com/docker-for-mac/install/" +fi \ No newline at end of file diff --git a/examples/azure-search-create/graph.png b/examples/azure-search-create/graph.png new file mode 100644 index 000000000..5a1961e28 Binary files /dev/null and b/examples/azure-search-create/graph.png differ diff --git a/examples/azure-search-create/main.tf b/examples/azure-search-create/main.tf new file mode 100644 index 000000000..d19fdace9 --- /dev/null +++ b/examples/azure-search-create/main.tf @@ -0,0 +1,20 @@ +# provider "azurerm" { +# subscription_id = "REPLACE-WITH-YOUR-SUBSCRIPTION-ID" +# client_id = "REPLACE-WITH-YOUR-CLIENT-ID" +# client_secret = "REPLACE-WITH-YOUR-CLIENT-SECRET" +# tenant_id = "REPLACE-WITH-YOUR-TENANT-ID" +# } + +resource "azurerm_resource_group" "rg" { + name = "${var.resource_group}" + location = "${var.location}" +} + +resource "azurerm_search_service" "search" { + name = "${var.search_name}" + resource_group_name = "${azurerm_resource_group.rg.name}" + location = "${var.location}" + sku = "${var.sku}" + replica_count = "${var.replica_count}" + partition_count = "${var.partition_count}" +} diff --git a/examples/azure-search-create/outputs.tf b/examples/azure-search-create/outputs.tf new file mode 100644 index 000000000..fb2c03b1e --- /dev/null +++ b/examples/azure-search-create/outputs.tf @@ -0,0 +1,3 @@ +output "Azure Search Service" { + value = "${azurerm_search_service.search.name}" +} diff --git a/examples/azure-search-create/variables.tf b/examples/azure-search-create/variables.tf new file mode 100644 index 000000000..72b3a8e1c --- /dev/null +++ b/examples/azure-search-create/variables.tf @@ -0,0 +1,32 @@ +variable "resource_group" { + description = "The name of the resource group in which to create search service" +} + +variable "location" { + description = "The location/region where the search service is created. Changing this forces a new resource to be created." + default = "southcentralus" +} + +variable "search_name" { + description = "Service name must only contain lowercase letters, digits or dashes, cannot use dash as the first two or last one characters, cannot contain consecutive dashes, and is limited between 2 and 60 characters in length." +} + +variable "sku" { + description = "Valid values are 'free', 'standard', 'standard2', and 'standard3' (2 & 3 must be enabled on the backend by Microsoft support). 'free' provisions the service in shared clusters. 'standard' provisions the service in dedicated clusters." + default = "standard" +} + +variable "replica_count" { + description = "Replicas distribute search workloads across the service. You need 2 or more to support high availability (applies to Basic and Standard only)." + default = 1 +} + +variable "partition_count" { + description = "Partitions allow for scaling of document count as well as faster indexing by sharding your index over multiple Azure Search units. Allowed values: 1, 2, 3, 4, 6, 12" + default = 1 +} + +variable "hosting_mode" { + description = "Applicable only for SKU set to standard3. You can set this property to enable a single, high density partition that allows up to 1000 indexes, which is much higher than the maximum indexes allowed for any other SKU. Allowed values: default, highDensity" + default = "default" +} diff --git a/examples/azure-servicebus-create-topic-and-subscription/README.md b/examples/azure-servicebus-create-topic-and-subscription/README.md new file mode 100644 index 000000000..6234b7ccf --- /dev/null +++ b/examples/azure-servicebus-create-topic-and-subscription/README.md @@ -0,0 +1,22 @@ +# 201 Create a Servicebus with Topic and Subscription + +For information about using this template, see [Create a Service Bus namespace with Topic and Subscription using an ARM template](http://azure.microsoft.com/documentation/articles/service-bus-resource-manager-namespace-topic/). + +## main.tf +The `main.tf` file contains the actual resources that will be deployed. It also contains the Azure Resource Group definition and any defined variables. + +## outputs.tf +This data is outputted when `terraform apply` is called, and can be queried using the `terraform output` command. + +## provider.tf +Azure requires that an application is added to Azure Active Directory to generate the `client_id`, `client_secret`, and `tenant_id` needed by Terraform (`subscription_id` can be recovered from your Azure account details). Please go [here](https://www.terraform.io/docs/providers/azurerm/) for full instructions on how to create this to populate your `provider.tf` file. + +## terraform.tfvars +If a `terraform.tfvars` file is present in the current directory, Terraform automatically loads it to populate variables. We don't recommend saving usernames and password to version control, but you can create a local secret variables file and use `-var-file` to load it. + +If you are committing this template to source control, please insure that you add this file to your `.gitignore` file. + +## variables.tf +The `variables.tf` file contains all of the input parameters that the user can specify when deploying this Terraform template. + +![graph](/examples/azure-servicebus-create-topic-and-subscription/graph.png) \ No newline at end of file diff --git a/examples/azure-servicebus-create-topic-and-subscription/deploy.ci.sh b/examples/azure-servicebus-create-topic-and-subscription/deploy.ci.sh new file mode 100755 index 000000000..ef99ef866 --- /dev/null +++ b/examples/azure-servicebus-create-topic-and-subscription/deploy.ci.sh @@ -0,0 +1,31 @@ +#!/bin/bash + +set -o errexit -o nounset + +docker run --rm -it \ + -e ARM_CLIENT_ID \ + -e ARM_CLIENT_SECRET \ + -e ARM_SUBSCRIPTION_ID \ + -e ARM_TENANT_ID \ + -v $(pwd):/data \ + --workdir=/data \ + --entrypoint "/bin/sh" \ + hashicorp/terraform:light \ + -c "/bin/terraform get; \ + /bin/terraform validate; \ + /bin/terraform plan -out=out.tfplan -var unique=$KEY -var resource_group=$KEY; \ + /bin/terraform apply out.tfplan; \ + /bin/terraform show;" + + +# cleanup deployed azure resources via terraform +docker run --rm -it \ + -e ARM_CLIENT_ID \ + -e ARM_CLIENT_SECRET \ + -e ARM_SUBSCRIPTION_ID \ + -e ARM_TENANT_ID \ + -v $(pwd):/data \ + --workdir=/data \ + --entrypoint "/bin/sh" \ + hashicorp/terraform:light \ + -c "/bin/terraform destroy -force -var unique=$KEY -var resource_group=$KEY;" \ No newline at end of file diff --git a/examples/azure-servicebus-create-topic-and-subscription/deploy.mac.sh b/examples/azure-servicebus-create-topic-and-subscription/deploy.mac.sh new file mode 100755 index 000000000..9c6563f07 --- /dev/null +++ b/examples/azure-servicebus-create-topic-and-subscription/deploy.mac.sh @@ -0,0 +1,15 @@ +#!/bin/bash + +set -o errexit -o nounset + +if docker -v; then + + # generate a unique string for CI deployment + export KEY=$(cat /dev/urandom | env LC_CTYPE=C tr -cd 'a-z' | head -c 12) + export PASSWORD=$KEY$(cat /dev/urandom | env LC_CTYPE=C tr -cd 'A-Z' | head -c 2)$(cat /dev/urandom | env LC_CTYPE=C tr -cd '0-9' | head -c 2) + + /bin/sh ./deploy.ci.sh + +else + echo "Docker is used to run terraform commands, please install before run: https://docs.docker.com/docker-for-mac/install/" +fi diff --git a/examples/azure-servicebus-create-topic-and-subscription/graph.png b/examples/azure-servicebus-create-topic-and-subscription/graph.png new file mode 100644 index 000000000..c2292cdeb Binary files /dev/null and b/examples/azure-servicebus-create-topic-and-subscription/graph.png differ diff --git a/examples/azure-servicebus-create-topic-and-subscription/main.tf b/examples/azure-servicebus-create-topic-and-subscription/main.tf new file mode 100644 index 000000000..5aa6d4815 --- /dev/null +++ b/examples/azure-servicebus-create-topic-and-subscription/main.tf @@ -0,0 +1,37 @@ +# provider "azurerm" { +# subscription_id = "REPLACE-WITH-YOUR-SUBSCRIPTION-ID" +# client_id = "REPLACE-WITH-YOUR-CLIENT-ID" +# client_secret = "REPLACE-WITH-YOUR-CLIENT-SECRET" +# tenant_id = "REPLACE-WITH-YOUR-TENANT-ID" +# } + +resource "azurerm_resource_group" "rg" { + name = "${var.resource_group}" + location = "${var.location}" +} + +resource "azurerm_servicebus_namespace" "test" { + depends_on = ["azurerm_resource_group.rg"] + name = "${var.unique}servicebus" + location = "${var.location}" + resource_group_name = "${var.resource_group}" + sku = "standard" +} + +resource "azurerm_servicebus_topic" "test" { + name = "${var.unique}Topic" + location = "${var.location}" + resource_group_name = "${var.resource_group}" + namespace_name = "${azurerm_servicebus_namespace.test.name}" + + enable_partitioning = true +} + +resource "azurerm_servicebus_subscription" "test" { + name = "${var.unique}Subscription" + location = "${var.location}" + resource_group_name = "${var.resource_group}" + namespace_name = "${azurerm_servicebus_namespace.test.name}" + topic_name = "${azurerm_servicebus_topic.test.name}" + max_delivery_count = 1 +} diff --git a/examples/azure-servicebus-create-topic-and-subscription/outputs.tf b/examples/azure-servicebus-create-topic-and-subscription/outputs.tf new file mode 100644 index 000000000..a35fe80d2 --- /dev/null +++ b/examples/azure-servicebus-create-topic-and-subscription/outputs.tf @@ -0,0 +1,7 @@ +output "Namespace Connection String" { + value = "${azurerm_servicebus_namespace.test.default_primary_connection_string}" +} + +output "Shared Access Policy PrimaryKey" { + value = "${azurerm_servicebus_namespace.test.default_primary_key}" +} diff --git a/examples/azure-servicebus-create-topic-and-subscription/variables.tf b/examples/azure-servicebus-create-topic-and-subscription/variables.tf new file mode 100644 index 000000000..e1df4f302 --- /dev/null +++ b/examples/azure-servicebus-create-topic-and-subscription/variables.tf @@ -0,0 +1,12 @@ +variable "resource_group" { + description = "The name of the resource group in which to create the Service Bus" +} + +variable "location" { + description = "The location/region where the Service Bus is created. Changing this forces a new resource to be created." + default = "southcentralus" +} + +variable "unique" { + description = "a unique string that will be used to comprise the names of the Service Bus, Topic, and Subscription name spaces" +} diff --git a/examples/azure-traffic-manager-vm/README.md b/examples/azure-traffic-manager-vm/README.md new file mode 100644 index 000000000..5fcc99aae --- /dev/null +++ b/examples/azure-traffic-manager-vm/README.md @@ -0,0 +1,29 @@ +# Azure Traffic Manager with virtual machines + +This Terraform template was based on [this](https://github.com/Azure/azure-quickstart-templates/tree/master/201-traffic-manager-vm) Azure Quickstart Template. Changes to the ARM template that may have occurred since the creation of this example may not be reflected here. + +This template shows how to create an Azure Traffic Manager profile to load-balance across a couple of Azure virtual machines. Each endpoint has an equal weight but different weights can be specified to distribute load non-uniformly. + +See also: + +- Traffic Manager routing methods for details of the different routing methods available. +- Create or update a Traffic Manager profile for details of the JSON elements relating to a Traffic Manager profile. + +## main.tf +The `main.tf` file contains the actual resources that will be deployed. It also contains the Azure Resource Group definition and any defined variables. + +## outputs.tf +This data is outputted when `terraform apply` is called, and can be queried using the `terraform output` command. + +## provider.tf +Azure requires that an application is added to Azure Active Directory to generate the `client_id`, `client_secret`, and `tenant_id` needed by Terraform (`subscription_id` can be recovered from your Azure account details). Please go [here](https://www.terraform.io/docs/providers/azurerm/) for full instructions on how to create this to populate your `provider.tf` file. + +## terraform.tfvars +If a `terraform.tfvars` file is present in the current directory, Terraform automatically loads it to populate variables. We don't recommend saving usernames and password to version control, but you can create a local secret variables file and use `-var-file` to load it. + +If you are committing this template to source control, please insure that you add this file to your `.gitignore` file. + +## variables.tf +The `variables.tf` file contains all of the input parameters that the user can specify when deploying this Terraform template. + +![`terraform graph`](/examples/azure-traffic-manager-vm/graph.png) diff --git a/examples/azure-traffic-manager-vm/deploy.ci.sh b/examples/azure-traffic-manager-vm/deploy.ci.sh new file mode 100755 index 000000000..c9f291444 --- /dev/null +++ b/examples/azure-traffic-manager-vm/deploy.ci.sh @@ -0,0 +1,36 @@ +#!/bin/bash + +set -o errexit -o nounset + +docker run --rm -it \ + -e ARM_CLIENT_ID \ + -e ARM_CLIENT_SECRET \ + -e ARM_SUBSCRIPTION_ID \ + -e ARM_TENANT_ID \ + -v $(pwd):/data \ + --workdir=/data \ + --entrypoint "/bin/sh" \ + hashicorp/terraform:light \ + -c "/bin/terraform get; \ + /bin/terraform validate; \ + /bin/terraform plan -out=out.tfplan -var dns_name=$KEY -var resource_group=$KEY -var admin_password=$PASSWORD; \ + /bin/terraform apply out.tfplan; \ + /bin/terraform show;" + +# cleanup deployed azure resources via azure-cli +docker run --rm -it \ + azuresdk/azure-cli-python \ + sh -c "az login --service-principal -u $ARM_CLIENT_ID -p $ARM_CLIENT_SECRET --tenant $ARM_TENANT_ID > /dev/null; \ + az vm show -g $KEY -n rgvm" + +# cleanup deployed azure resources via terraform +docker run --rm -it \ + -e ARM_CLIENT_ID \ + -e ARM_CLIENT_SECRET \ + -e ARM_SUBSCRIPTION_ID \ + -e ARM_TENANT_ID \ + -v $(pwd):/data \ + --workdir=/data \ + --entrypoint "/bin/sh" \ + hashicorp/terraform:light \ + -c "/bin/terraform destroy -force -var dns_name=$KEY -var resource_group=$KEY -var admin_password=$PASSWORD;" \ No newline at end of file diff --git a/examples/azure-traffic-manager-vm/deploy.mac.sh b/examples/azure-traffic-manager-vm/deploy.mac.sh new file mode 100755 index 000000000..dfc34c2be --- /dev/null +++ b/examples/azure-traffic-manager-vm/deploy.mac.sh @@ -0,0 +1,15 @@ +#!/bin/bash + +set -o errexit -o nounset + +if docker -v; then + + # generate a unique string for CI deployment + export KEY=$(cat /dev/urandom | env LC_CTYPE=C tr -cd 'a-z' | head -c 12) + export PASSWORD=$KEY$(cat /dev/urandom | env LC_CTYPE=C tr -cd 'A-Z' | head -c 2)$(cat /dev/urandom | env LC_CTYPE=C tr -cd '0-9' | head -c 2) + + /bin/sh ./deploy.ci.sh + +else + echo "Docker is used to run terraform commands, please install before run: https://docs.docker.com/docker-for-mac/install/" +fi \ No newline at end of file diff --git a/examples/azure-traffic-manager-vm/graph.png b/examples/azure-traffic-manager-vm/graph.png new file mode 100644 index 000000000..fddb46a66 Binary files /dev/null and b/examples/azure-traffic-manager-vm/graph.png differ diff --git a/examples/azure-traffic-manager-vm/main.tf b/examples/azure-traffic-manager-vm/main.tf new file mode 100644 index 000000000..ef34a8ad5 --- /dev/null +++ b/examples/azure-traffic-manager-vm/main.tf @@ -0,0 +1,125 @@ +# provider "azurerm" { +# subscription_id = "REPLACE-WITH-YOUR-SUBSCRIPTION-ID" +# client_id = "REPLACE-WITH-YOUR-CLIENT-ID" +# client_secret = "REPLACE-WITH-YOUR-CLIENT-SECRET" +# tenant_id = "REPLACE-WITH-YOUR-TENANT-ID" +# } + +resource "azurerm_resource_group" "rg" { + name = "${var.resource_group}" + location = "${var.location}" +} + +resource "azurerm_public_ip" "pip" { + name = "ip${count.index}" + location = "${var.location}" + resource_group_name = "${azurerm_resource_group.rg.name}" + public_ip_address_allocation = "dynamic" + domain_name_label = "${var.dns_name}${count.index}" + count = "${var.num_vms}" +} + +resource "azurerm_virtual_network" "vnet" { + name = "${var.vnet}" + location = "${var.location}" + address_space = ["${var.address_space}"] + resource_group_name = "${azurerm_resource_group.rg.name}" +} + +resource "azurerm_subnet" "subnet" { + name = "${var.subnet_name}" + virtual_network_name = "${azurerm_virtual_network.vnet.name}" + resource_group_name = "${azurerm_resource_group.rg.name}" + address_prefix = "${var.subnet_prefix}" +} + +resource "azurerm_network_interface" "nic" { + name = "nic${count.index}" + location = "${var.location}" + resource_group_name = "${azurerm_resource_group.rg.name}" + count = "${var.num_vms}" + + ip_configuration { + name = "ipconfig${count.index}" + subnet_id = "${azurerm_subnet.subnet.id}" + private_ip_address_allocation = "Dynamic" + public_ip_address_id = "${element(azurerm_public_ip.pip.*.id, count.index)}" + } +} + +resource "azurerm_virtual_machine" "vm" { + name = "vm${count.index}" + location = "${var.location}" + resource_group_name = "${azurerm_resource_group.rg.name}" + vm_size = "${var.vm_size}" + count = "${var.num_vms}" + network_interface_ids = ["${element(azurerm_network_interface.nic.*.id, count.index)}"] + + storage_image_reference { + publisher = "${var.image_publisher}" + offer = "${var.image_offer}" + sku = "${var.image_sku}" + version = "${var.image_version}" + } + + storage_os_disk { + name = "osdisk${count.index}" + create_option = "FromImage" + } + + os_profile { + computer_name = "vm${count.index}" + admin_username = "${var.admin_username}" + admin_password = "${var.admin_password}" + } + + os_profile_linux_config { + disable_password_authentication = false + } +} + +resource "azurerm_virtual_machine_extension" "ext" { + depends_on = ["azurerm_virtual_machine.vm"] + name = "CustomScript" + location = "${var.location}" + resource_group_name = "${azurerm_resource_group.rg.name}" + virtual_machine_name = "vm${count.index}" + publisher = "Microsoft.Azure.Extensions" + type = "CustomScript" + type_handler_version = "2.0" + count = "${var.num_vms}" + auto_upgrade_minor_version = true + + settings = < /dev/null; \ + az vm show -g $KEY -n myvm; \ + az storage account show -g $KEY -n $KEY;" + +# cleanup deployed azure resources via terraform +docker run --rm -it \ + -e ARM_CLIENT_ID \ + -e ARM_CLIENT_SECRET \ + -e ARM_SUBSCRIPTION_ID \ + -e ARM_TENANT_ID \ + -v $(pwd):/data \ + --workdir=/data \ + --entrypoint "/bin/sh" \ + hashicorp/terraform:light \ + -c "/bin/terraform destroy -force \ + -var source_img_uri=$EXISTING_IMAGE_URI \ + -var hostname=$KEY \ + -var resource_group=$KEY \ + -var existing_resource_group=$EXISTING_RESOURCE_GROUP \ + -var admin_password=$PASSWORD \ + -var existing_storage_acct=$EXISTING_STORAGE_ACCOUNT_NAME \ + -var custom_image_name=$CUSTOM_IMAGE_NAME \ + -target=azurerm_virtual_machine.myvm \ + -target=azurerm_virtual_machine.transfer \ + -target=azurerm_network_interface.transfernic \ + -target=azurerm_network_interface.mynic \ + -target=azurerm_virtual_network.vnet \ + -target=azurerm_public_ip.mypip \ + -target=azurerm_public_ip.transferpip \ + -target=azurerm_storage_account.stor;" \ No newline at end of file diff --git a/examples/azure-vm-custom-image-new-storage-account/deploy.mac.sh b/examples/azure-vm-custom-image-new-storage-account/deploy.mac.sh new file mode 100755 index 000000000..3520afac6 --- /dev/null +++ b/examples/azure-vm-custom-image-new-storage-account/deploy.mac.sh @@ -0,0 +1,19 @@ +#!/bin/bash + +set -o errexit -o nounset + +if docker -v; then + + # generate a unique string for CI deployment + export KEY=$(cat /dev/urandom | env LC_CTYPE=C tr -cd 'a-z' | head -c 12) + export PASSWORD=$KEY$(cat /dev/urandom | env LC_CTYPE=C tr -cd 'A-Z' | head -c 2)$(cat /dev/urandom | env LC_CTYPE=C tr -cd '0-9' | head -c 2) + export EXISTING_RESOURCE_GROUP=donotdelete + export EXISTING_IMAGE_URI=https://donotdeletedisks636.blob.core.windows.net/vhds/mywindowsimage20170510184809.vhd + export EXISTING_STORAGE_ACCOUNT_NAME=donotdeletedisks636 + export CUSTOM_IMAGE_NAME=mywindowsimage20170510184809 + + /bin/sh ./deploy.ci.sh + +else + echo "Docker is used to run terraform commands, please install before run: https://docs.docker.com/docker-for-mac/install/" +fi \ No newline at end of file diff --git a/examples/azure-vm-custom-image-new-storage-account/graph.png b/examples/azure-vm-custom-image-new-storage-account/graph.png new file mode 100644 index 000000000..35f0c0a0e Binary files /dev/null and b/examples/azure-vm-custom-image-new-storage-account/graph.png differ diff --git a/examples/azure-vm-custom-image-new-storage-account/main.tf b/examples/azure-vm-custom-image-new-storage-account/main.tf new file mode 100644 index 000000000..e59983197 --- /dev/null +++ b/examples/azure-vm-custom-image-new-storage-account/main.tf @@ -0,0 +1,165 @@ +# provider "azurerm" { +# subscription_id = "REPLACE-WITH-YOUR-SUBSCRIPTION-ID" +# client_id = "REPLACE-WITH-YOUR-CLIENT-ID" +# client_secret = "REPLACE-WITH-YOUR-CLIENT-SECRET" +# tenant_id = "REPLACE-WITH-YOUR-TENANT-ID" +# } + +resource "azurerm_resource_group" "rg" { + name = "${var.resource_group}" + location = "${var.location}" +} + +resource "azurerm_virtual_network" "vnet" { + name = "${var.hostname}vnet" + location = "${azurerm_resource_group.rg.location}" + resource_group_name = "${azurerm_resource_group.rg.name}" + address_space = ["${var.address_space}"] +} + +resource "azurerm_subnet" "subnet" { + name = "${var.hostname}subnet" + virtual_network_name = "${azurerm_virtual_network.vnet.name}" + resource_group_name = "${azurerm_resource_group.rg.name}" + address_prefix = "${var.subnet_prefix}" +} + +resource "azurerm_public_ip" "transferpip" { + name = "transferpip" + location = "${azurerm_resource_group.rg.location}" + resource_group_name = "${azurerm_resource_group.rg.name}" + public_ip_address_allocation = "Static" +} + +resource "azurerm_network_interface" "transfernic" { + name = "transfernic" + location = "${azurerm_resource_group.rg.location}" + resource_group_name = "${azurerm_resource_group.rg.name}" + + ip_configuration { + name = "${azurerm_public_ip.transferpip.name}" + subnet_id = "${azurerm_subnet.subnet.id}" + private_ip_address_allocation = "Static" + public_ip_address_id = "${azurerm_public_ip.transferpip.id}" + private_ip_address = "10.0.0.5" + } +} + +resource "azurerm_public_ip" "mypip" { + name = "mypip" + location = "${azurerm_resource_group.rg.location}" + resource_group_name = "${azurerm_resource_group.rg.name}" + public_ip_address_allocation = "Dynamic" +} + +resource "azurerm_network_interface" "mynic" { + name = "mynic" + location = "${azurerm_resource_group.rg.location}" + resource_group_name = "${azurerm_resource_group.rg.name}" + + ip_configuration { + name = "${azurerm_public_ip.mypip.name}" + subnet_id = "${azurerm_subnet.subnet.id}" + private_ip_address_allocation = "Dynamic" + public_ip_address_id = "${azurerm_public_ip.mypip.id}" + } +} + +resource "azurerm_storage_account" "existing" { + name = "${var.existing_storage_acct}" + resource_group_name = "${var.existing_resource_group}" + location = "${azurerm_resource_group.rg.location}" + account_type = "${var.existing_storage_acct_type}" + + lifecycle = { + prevent_destroy = true + } +} + +resource "azurerm_storage_account" "stor" { + name = "${var.hostname}" + resource_group_name = "${azurerm_resource_group.rg.name}" + location = "${azurerm_resource_group.rg.location}" + account_type = "${var.storage_account_type}" +} + +resource "azurerm_virtual_machine" "transfer" { + name = "${var.transfer_vm_name}" + location = "${azurerm_resource_group.rg.location}" + resource_group_name = "${azurerm_resource_group.rg.name}" + vm_size = "${var.vm_size}" + network_interface_ids = ["${azurerm_network_interface.transfernic.id}"] + + storage_os_disk { + name = "${var.hostname}-osdisk" + image_uri = "${var.source_img_uri}" + vhd_uri = "https://${var.existing_storage_acct}.blob.core.windows.net/${var.existing_resource_group}-vhds/${var.hostname}osdisk.vhd" + os_type = "${var.os_type}" + caching = "ReadWrite" + create_option = "FromImage" + } + + os_profile { + computer_name = "${var.hostname}" + admin_username = "${var.admin_username}" + admin_password = "${var.admin_password}" + } +} + +resource "azurerm_virtual_machine_extension" "script" { + name = "CustomScriptExtension" + location = "${azurerm_resource_group.rg.location}" + resource_group_name = "${azurerm_resource_group.rg.name}" + virtual_machine_name = "${azurerm_virtual_machine.transfer.name}" + publisher = "Microsoft.Compute" + type = "CustomScriptExtension" + type_handler_version = "1.4" + depends_on = ["azurerm_virtual_machine.transfer"] + + settings = < Prerequisite - The generalized image VHD should exist, as well as a Storage Account for boot diagnostics + +This template allows you to create a Virtual Machine from an unmanaged User image vhd. This template also deploys a Virtual Network, Public IP addresses and a Network Interface. + +## main.tf +The `main.tf` file contains the actual resources that will be deployed. It also contains the Azure Resource Group definition and any defined variables. + +## outputs.tf +This data is outputted when `terraform apply` is called, and can be queried using the `terraform output` command. + +## provider.tf +Azure requires that an application is added to Azure Active Directory to generate the `client_id`, `client_secret`, and `tenant_id` needed by Terraform (`subscription_id` can be recovered from your Azure account details). Please go [here](https://www.terraform.io/docs/providers/azurerm/) for full instructions on how to create this to populate your `provider.tf` file. + +## terraform.tfvars +If a `terraform.tfvars` file is present in the current directory, Terraform automatically loads it to populate variables. We don't recommend saving usernames and password to version control, but you can create a local secret variables file and use `-var-file` to load it. + +If you are committing this template to source control, please insure that you add this file to your `.gitignore` file. + +## variables.tf +The `variables.tf` file contains all of the input parameters that the user can specify when deploying this Terraform template. + +![graph](/examples/azure-vm-from-user-image/graph.png) \ No newline at end of file diff --git a/examples/azure-vm-from-user-image/deploy.ci.sh b/examples/azure-vm-from-user-image/deploy.ci.sh new file mode 100755 index 000000000..37578ed7d --- /dev/null +++ b/examples/azure-vm-from-user-image/deploy.ci.sh @@ -0,0 +1,45 @@ +#!/bin/bash + +set -o errexit -o nounset + +docker run --rm -it \ + -e ARM_CLIENT_ID \ + -e ARM_CLIENT_SECRET \ + -e ARM_SUBSCRIPTION_ID \ + -e ARM_TENANT_ID \ + -v $(pwd):/data \ + --workdir=/data \ + --entrypoint "/bin/sh" \ + hashicorp/terraform:light \ + -c "/bin/terraform get; \ + /bin/terraform validate; \ + /bin/terraform plan -out=out.tfplan -var hostname=$KEY -var resource_group=$EXISTING_RESOURCE_GROUP -var admin_username=$KEY -var admin_password=$PASSWORD -var image_uri=$EXISTING_IMAGE_URI -var storage_account_name=$EXISTING_STORAGE_ACCOUNT_NAME; \ + /bin/terraform apply out.tfplan; \ + /bin/terraform show;" + +docker run --rm -it \ + azuresdk/azure-cli-python \ + sh -c "az login --service-principal -u $ARM_CLIENT_ID -p $ARM_CLIENT_SECRET --tenant $ARM_TENANT_ID > /dev/null; \ + az vm show --name $KEY --resource-group permanent" + +# cleanup deployed azure resources via terraform +docker run --rm -it \ + -e ARM_CLIENT_ID \ + -e ARM_CLIENT_SECRET \ + -e ARM_SUBSCRIPTION_ID \ + -e ARM_TENANT_ID \ + -v $(pwd):/data \ + --workdir=/data \ + --entrypoint "/bin/sh" \ + hashicorp/terraform:light \ + -c "/bin/terraform destroy -force \ + -var hostname=$KEY \ + -var resource_group=$EXISTING_RESOURCE_GROUP \ + -var admin_username=$KEY \ + -var admin_password=$PASSWORD \ + -var image_uri=$EXISTING_IMAGE_URI \ + -var storage_account_name=$EXISTING_STORAGE_ACCOUNT_NAME \ + -target=azurerm_virtual_machine.vm \ + -target=azurerm_network_interface.nic \ + -target=azurerm_virtual_network.vnet \ + -target=azurerm_public_ip.pip;" diff --git a/examples/azure-vm-from-user-image/deploy.mac.sh b/examples/azure-vm-from-user-image/deploy.mac.sh new file mode 100755 index 000000000..5073b4035 --- /dev/null +++ b/examples/azure-vm-from-user-image/deploy.mac.sh @@ -0,0 +1,18 @@ +#!/bin/bash + +set -o errexit -o nounset + +if docker -v; then + + # generate a unique string for CI deployment + export KEY=$(cat /dev/urandom | env LC_CTYPE=C tr -cd 'a-z' | head -c 12) + export PASSWORD=$KEY$(cat /dev/urandom | env LC_CTYPE=C tr -cd 'A-Z' | head -c 2)$(cat /dev/urandom | env LC_CTYPE=C tr -cd '0-9' | head -c 2) + export EXISTING_IMAGE_URI=https://permanentstor.blob.core.windows.net/permanent-vhds/permanent-osdisk1.vhd + export EXISTING_STORAGE_ACCOUNT_NAME=permanentstor + export EXISTING_RESOURCE_GROUP=permanent + + /bin/sh ./deploy.ci.sh + +else + echo "Docker is used to run terraform commands, please install before run: https://docs.docker.com/docker-for-mac/install/" +fi \ No newline at end of file diff --git a/examples/azure-vm-from-user-image/graph.png b/examples/azure-vm-from-user-image/graph.png new file mode 100644 index 000000000..2384ff0ce Binary files /dev/null and b/examples/azure-vm-from-user-image/graph.png differ diff --git a/examples/azure-vm-from-user-image/main.tf b/examples/azure-vm-from-user-image/main.tf new file mode 100644 index 000000000..8444377f8 --- /dev/null +++ b/examples/azure-vm-from-user-image/main.tf @@ -0,0 +1,73 @@ +# provider "azurerm" { +# subscription_id = "REPLACE-WITH-YOUR-SUBSCRIPTION-ID" +# client_id = "REPLACE-WITH-YOUR-CLIENT-ID" +# client_secret = "REPLACE-WITH-YOUR-CLIENT-SECRET" +# tenant_id = "REPLACE-WITH-YOUR-TENANT-ID" +# } + +resource "azurerm_resource_group" "rg" { + name = "${var.resource_group}" + location = "${var.location}" +} + +resource "azurerm_virtual_network" "vnet" { + name = "${var.hostname}vnet" + location = "${var.location}" + address_space = ["${var.address_space}"] + resource_group_name = "${azurerm_resource_group.rg.name}" +} + +resource "azurerm_subnet" "subnet" { + name = "${var.hostname}subnet" + virtual_network_name = "${azurerm_virtual_network.vnet.name}" + resource_group_name = "${azurerm_resource_group.rg.name}" + address_prefix = "${var.subnet_prefix}" +} + +resource "azurerm_network_interface" "nic" { + name = "${var.hostname}nic" + location = "${var.location}" + resource_group_name = "${azurerm_resource_group.rg.name}" + + ip_configuration { + name = "${var.hostname}ipconfig" + subnet_id = "${azurerm_subnet.subnet.id}" + private_ip_address_allocation = "Dynamic" + public_ip_address_id = "${azurerm_public_ip.pip.id}" + } +} + +resource "azurerm_public_ip" "pip" { + name = "${var.hostname}-ip" + location = "${var.location}" + resource_group_name = "${azurerm_resource_group.rg.name}" + public_ip_address_allocation = "Dynamic" + domain_name_label = "${var.hostname}" +} + +resource "azurerm_virtual_machine" "vm" { + name = "${var.hostname}" + location = "${var.location}" + resource_group_name = "${azurerm_resource_group.rg.name}" + vm_size = "${var.vm_size}" + network_interface_ids = ["${azurerm_network_interface.nic.id}"] + + storage_os_disk { + name = "${var.hostname}-osdisk1" + image_uri = "${var.image_uri}" + vhd_uri = "https://${var.storage_account_name}.blob.core.windows.net/vhds/${var.hostname}osdisk.vhd" + os_type = "${var.os_type}" + caching = "ReadWrite" + create_option = "FromImage" + } + + os_profile { + computer_name = "${var.hostname}" + admin_username = "${var.admin_username}" + admin_password = "${var.admin_password}" + } + + os_profile_linux_config { + disable_password_authentication = false + } +} diff --git a/examples/azure-vm-from-user-image/outputs.tf b/examples/azure-vm-from-user-image/outputs.tf new file mode 100644 index 000000000..58a17046f --- /dev/null +++ b/examples/azure-vm-from-user-image/outputs.tf @@ -0,0 +1,11 @@ +output "hostname" { + value = "${var.hostname}" +} + +output "vm_fqdn" { + value = "${azurerm_public_ip.pip.fqdn}" +} + +output "ssh_command" { + value = "${concat("ssh ", var.admin_username, "@", azurerm_public_ip.pip.fqdn)}" +} diff --git a/examples/azure-vm-from-user-image/variables.tf b/examples/azure-vm-from-user-image/variables.tf new file mode 100644 index 000000000..133c02bbb --- /dev/null +++ b/examples/azure-vm-from-user-image/variables.tf @@ -0,0 +1,55 @@ +variable "resource_group" { + description = "The name of the resource group in which the image to clone resides." + default = "myrg" +} + +variable "image_uri" { + description = "Specifies the image_uri in the form publisherName:offer:skus:version. image_uri can also specify the VHD uri of a custom VM image to clone." +} + +variable "os_type" { + description = "Specifies the operating system Type, valid values are windows, linux." + default = "linux" +} + +variable "location" { + description = "The location/region where the virtual network is created. Changing this forces a new resource to be created." + default = "southcentralus" +} + +variable "address_space" { + description = "The address space that is used by the virtual network. You can supply more than one address space. Changing this forces a new resource to be created." + default = "10.0.0.0/24" +} + +variable "subnet_prefix" { + description = "The address prefix to use for the subnet." + default = "10.0.0.0/24" +} + +variable "storage_account_name" { + description = "The name of the storage account in which the image from which you are cloning resides." +} + +variable "storage_account_type" { + description = "Defines the type of storage account to be created. Valid options are Standard_LRS, Standard_ZRS, Standard_GRS, Standard_RAGRS, Premium_LRS. Changing this is sometimes valid - see the Azure documentation for more information on which types of accounts can be converted into other types." + default = "Premium_LRS" +} + +variable "vm_size" { + description = "Specifies the size of the virtual machine. This must be the same as the vm image from which you are copying." + default = "Standard_DS1_v2" +} + +variable "hostname" { + description = "VM name referenced also in storage-related names. This is also used as the label for the Domain Name and to make up the FQDN. If a domain name label is specified, an A DNS record is created for the public IP in the Microsoft Azure DNS system." +} + +variable "admin_username" { + description = "administrator user name" + default = "vmadmin" +} + +variable "admin_password" { + description = "The Password for the account specified in the 'admin_username' field. We recommend disabling Password Authentication in a Production environment." +} diff --git a/examples/azure-vm-simple-linux-managed-disk/README.md b/examples/azure-vm-simple-linux-managed-disk/README.md new file mode 100644 index 000000000..42201eb44 --- /dev/null +++ b/examples/azure-vm-simple-linux-managed-disk/README.md @@ -0,0 +1,22 @@ +# Very simple deployment of a Linux VM + +This template allows you to deploy a simple Linux VM using a few different options for the Ubuntu version, using the latest patched version. This will deploy an A0 size VM in the resource group location and return the FQDN of the VM. + +This template takes a minimum amount of parameters and deploys a Linux VM, using the latest patched version. + +## main.tf +The `main.tf` file contains the actual resources that will be deployed. It also contains the Azure Resource Group definition and any defined variables. + +## outputs.tf +This data is outputted when `terraform apply` is called, and can be queried using the `terraform output` command. + +## provider.tf +Azure requires that an application is added to Azure Active Directory to generate the `client_id`, `client_secret`, and `tenant_id` needed by Terraform (`subscription_id` can be recovered from your Azure account details). Please go [here](https://www.terraform.io/docs/providers/azurerm/) for full instructions on how to create this to populate your `provider.tf` file. + +## terraform.tfvars +If a `terraform.tfvars` file is present in the current directory, Terraform automatically loads it to populate variables. We don't recommend saving usernames and password to version control, but you can create a local secret variables file and use `-var-file` to load it. + +## variables.tf +The `variables.tf` file contains all of the input parameters that the user can specify when deploying this Terraform template. + +![graph](/examples/azure-vm-simple-linux-managed-disk/graph.png) \ No newline at end of file diff --git a/examples/azure-vm-simple-linux-managed-disk/deploy.ci.sh b/examples/azure-vm-simple-linux-managed-disk/deploy.ci.sh new file mode 100755 index 000000000..71e407526 --- /dev/null +++ b/examples/azure-vm-simple-linux-managed-disk/deploy.ci.sh @@ -0,0 +1,36 @@ +#!/bin/bash + +set -o errexit -o nounset + +docker run --rm -it \ + -e ARM_CLIENT_ID \ + -e ARM_CLIENT_SECRET \ + -e ARM_SUBSCRIPTION_ID \ + -e ARM_TENANT_ID \ + -v $(pwd):/data \ + --workdir=/data \ + --entrypoint "/bin/sh" \ + hashicorp/terraform:light \ + -c "/bin/terraform get; \ + /bin/terraform validate; \ + /bin/terraform plan -out=out.tfplan -var dns_name=$KEY -var hostname=$KEY -var resource_group=$KEY -var admin_password=$PASSWORD; \ + /bin/terraform apply out.tfplan; \ + /bin/terraform show;" + +# cleanup deployed azure resources via azure-cli +docker run --rm -it \ + azuresdk/azure-cli-python \ + sh -c "az login --service-principal -u $ARM_CLIENT_ID -p $ARM_CLIENT_SECRET --tenant $ARM_TENANT_ID > /dev/null; \ + az vm show -g $KEY -n rgvm" + +# cleanup deployed azure resources via terraform +docker run --rm -it \ + -e ARM_CLIENT_ID \ + -e ARM_CLIENT_SECRET \ + -e ARM_SUBSCRIPTION_ID \ + -e ARM_TENANT_ID \ + -v $(pwd):/data \ + --workdir=/data \ + --entrypoint "/bin/sh" \ + hashicorp/terraform:light \ + -c "/bin/terraform destroy -force -var dns_name=$KEY -var hostname=$KEY -var resource_group=$KEY -var admin_password=$PASSWORD;" \ No newline at end of file diff --git a/examples/azure-vm-simple-linux-managed-disk/deploy.mac.sh b/examples/azure-vm-simple-linux-managed-disk/deploy.mac.sh new file mode 100755 index 000000000..dfc34c2be --- /dev/null +++ b/examples/azure-vm-simple-linux-managed-disk/deploy.mac.sh @@ -0,0 +1,15 @@ +#!/bin/bash + +set -o errexit -o nounset + +if docker -v; then + + # generate a unique string for CI deployment + export KEY=$(cat /dev/urandom | env LC_CTYPE=C tr -cd 'a-z' | head -c 12) + export PASSWORD=$KEY$(cat /dev/urandom | env LC_CTYPE=C tr -cd 'A-Z' | head -c 2)$(cat /dev/urandom | env LC_CTYPE=C tr -cd '0-9' | head -c 2) + + /bin/sh ./deploy.ci.sh + +else + echo "Docker is used to run terraform commands, please install before run: https://docs.docker.com/docker-for-mac/install/" +fi \ No newline at end of file diff --git a/examples/azure-vm-simple-linux-managed-disk/graph.png b/examples/azure-vm-simple-linux-managed-disk/graph.png new file mode 100644 index 000000000..ea993bfc4 Binary files /dev/null and b/examples/azure-vm-simple-linux-managed-disk/graph.png differ diff --git a/examples/azure-vm-simple-linux-managed-disk/main.tf b/examples/azure-vm-simple-linux-managed-disk/main.tf new file mode 100644 index 000000000..5dc9ce1cb --- /dev/null +++ b/examples/azure-vm-simple-linux-managed-disk/main.tf @@ -0,0 +1,108 @@ +# provider "azurerm" { +# subscription_id = "REPLACE-WITH-YOUR-SUBSCRIPTION-ID" +# client_id = "REPLACE-WITH-YOUR-CLIENT-ID" +# client_secret = "REPLACE-WITH-YOUR-CLIENT-SECRET" +# tenant_id = "REPLACE-WITH-YOUR-TENANT-ID" +# } + +resource "azurerm_resource_group" "rg" { + name = "${var.resource_group}" + location = "${var.location}" +} + +resource "azurerm_virtual_network" "vnet" { + name = "${var.virtual_network_name}" + location = "${var.location}" + address_space = ["${var.address_space}"] + resource_group_name = "${azurerm_resource_group.rg.name}" +} + +resource "azurerm_subnet" "subnet" { + name = "${var.rg_prefix}subnet" + virtual_network_name = "${azurerm_virtual_network.vnet.name}" + resource_group_name = "${azurerm_resource_group.rg.name}" + address_prefix = "${var.subnet_prefix}" +} + +resource "azurerm_network_interface" "nic" { + name = "${var.rg_prefix}nic" + location = "${var.location}" + resource_group_name = "${azurerm_resource_group.rg.name}" + + ip_configuration { + name = "${var.rg_prefix}ipconfig" + subnet_id = "${azurerm_subnet.subnet.id}" + private_ip_address_allocation = "Dynamic" + public_ip_address_id = "${azurerm_public_ip.pip.id}" + } +} + +resource "azurerm_public_ip" "pip" { + name = "${var.rg_prefix}-ip" + location = "${var.location}" + resource_group_name = "${azurerm_resource_group.rg.name}" + public_ip_address_allocation = "Dynamic" + domain_name_label = "${var.dns_name}" +} + +resource "azurerm_storage_account" "stor" { + name = "${var.dns_name}stor" + location = "${var.location}" + resource_group_name = "${azurerm_resource_group.rg.name}" + account_type = "${var.storage_account_type}" +} + +resource "azurerm_managed_disk" "datadisk" { + name = "${var.hostname}-datadisk" + location = "${var.location}" + resource_group_name = "${azurerm_resource_group.rg.name}" + storage_account_type = "Standard_LRS" + create_option = "Empty" + disk_size_gb = "1023" +} + +resource "azurerm_virtual_machine" "vm" { + name = "${var.rg_prefix}vm" + location = "${var.location}" + resource_group_name = "${azurerm_resource_group.rg.name}" + vm_size = "${var.vm_size}" + network_interface_ids = ["${azurerm_network_interface.nic.id}"] + + storage_image_reference { + publisher = "${var.image_publisher}" + offer = "${var.image_offer}" + sku = "${var.image_sku}" + version = "${var.image_version}" + } + + storage_os_disk { + name = "${var.hostname}-osdisk" + managed_disk_type = "Standard_LRS" + caching = "ReadWrite" + create_option = "FromImage" + } + + storage_data_disk { + name = "${var.hostname}-datadisk" + managed_disk_id = "${azurerm_managed_disk.datadisk.id}" + managed_disk_type = "Standard_LRS" + disk_size_gb = "1023" + create_option = "Attach" + lun = 0 + } + + os_profile { + computer_name = "${var.hostname}" + admin_username = "${var.admin_username}" + admin_password = "${var.admin_password}" + } + + os_profile_linux_config { + disable_password_authentication = false + } + + boot_diagnostics { + enabled = true + storage_uri = "${azurerm_storage_account.stor.primary_blob_endpoint}" + } +} \ No newline at end of file diff --git a/examples/azure-vm-simple-linux-managed-disk/outputs.tf b/examples/azure-vm-simple-linux-managed-disk/outputs.tf new file mode 100644 index 000000000..32c6294ce --- /dev/null +++ b/examples/azure-vm-simple-linux-managed-disk/outputs.tf @@ -0,0 +1,11 @@ +output "hostname" { + value = "${var.hostname}" +} + +output "vm_fqdn" { + value = "${azurerm_public_ip.pip.fqdn}" +} + +output "ssh_command" { + value = "ssh ${var.admin_username}@${azurerm_public_ip.pip.fqdn}" +} \ No newline at end of file diff --git a/examples/azure-vm-simple-linux-managed-disk/variables.tf b/examples/azure-vm-simple-linux-managed-disk/variables.tf new file mode 100644 index 000000000..91024000b --- /dev/null +++ b/examples/azure-vm-simple-linux-managed-disk/variables.tf @@ -0,0 +1,75 @@ +variable "resource_group" { + description = "The name of the resource group in which to create the virtual network." +} + +variable "rg_prefix" { + description = "The shortened abbreviation to represent your resource group that will go on the front of some resources." + default = "rg" +} + +variable "hostname" { + description = "VM name referenced also in storage-related names." +} + +variable "dns_name" { + description = " Label for the Domain Name. Will be used to make up the FQDN. If a domain name label is specified, an A DNS record is created for the public IP in the Microsoft Azure DNS system." +} + +variable "location" { + description = "The location/region where the virtual network is created. Changing this forces a new resource to be created." + default = "southcentralus" +} + +variable "virtual_network_name" { + description = "The name for the virtual network." + default = "vnet" +} + +variable "address_space" { + description = "The address space that is used by the virtual network. You can supply more than one address space. Changing this forces a new resource to be created." + default = "10.0.0.0/16" +} + +variable "subnet_prefix" { + description = "The address prefix to use for the subnet." + default = "10.0.10.0/24" +} + +variable "storage_account_type" { + description = "Defines the type of storage account to be created. Valid options are Standard_LRS, Standard_ZRS, Standard_GRS, Standard_RAGRS, Premium_LRS. Changing this is sometimes valid - see the Azure documentation for more information on which types of accounts can be converted into other types." + default = "Standard_LRS" +} + +variable "vm_size" { + description = "Specifies the size of the virtual machine." + default = "Standard_A0" +} + +variable "image_publisher" { + description = "name of the publisher of the image (az vm image list)" + default = "Canonical" +} + +variable "image_offer" { + description = "the name of the offer (az vm image list)" + default = "UbuntuServer" +} + +variable "image_sku" { + description = "image sku to apply (az vm image list)" + default = "16.04-LTS" +} + +variable "image_version" { + description = "version of the image to apply (az vm image list)" + default = "latest" +} + +variable "admin_username" { + description = "administrator user name" + default = "vmadmin" +} + +variable "admin_password" { + description = "administrator password (recommended to disable password auth)" +} \ No newline at end of file diff --git a/examples/azure-vm-specialized-vhd-existing-vnet/README.md b/examples/azure-vm-specialized-vhd-existing-vnet/README.md new file mode 100644 index 000000000..921979846 --- /dev/null +++ b/examples/azure-vm-specialized-vhd-existing-vnet/README.md @@ -0,0 +1,35 @@ +# Create a specialized virtual machine in an existing virtual network [![Build Status](https://travis-ci.org/harijayms/terraform.svg?branch=topic-201-vm-specialized-vhd-existing-vnet)](https://travis-ci.org/harijayms/terraform) + +This Terraform template was based on [this](https://github.com/Azure/azure-quickstart-templates/tree/master/201-vm-specialized-vhd-existing-vnet) Azure Quickstart Template. Changes to the ARM template that may have occurred since the creation of this example may not be reflected in this Terraform template. + +## Prerequisites + +- VHD file from which to create a VM that already exists in a storage account +- Name of the existing VNET and subnet to which the new virtual machine will connect +- Name of the Resource Group in which the VNET resides + + +### NOTE + +This template will create an additional Standard_GRS storage account for enabling boot diagnostics each time you execute this template. To avoid running into storage account limits, it is best to delete the storage account when the VM is deleted. + +This template creates a VM from a specialized VHD and lets you connect it to an existing VNET that can reside in a different Resource Group from which the virtual machine resides. + +_Please note: This deployment template does not create or attach an existing Network Security Group to the virtual machine._ + +## main.tf +The `main.tf` file contains the actual resources that will be deployed. It also contains the Azure Resource Group definition and any defined variables. + +## outputs.tf +This data is outputted when `terraform apply` is called, and can be queried using the `terraform output` command. + +## provider.tf +Azure requires that an application is added to Azure Active Directory to generate the `client_id`, `client_secret`, and `tenant_id` needed by Terraform (`subscription_id` can be recovered from your Azure account details). Please go [here](https://www.terraform.io/docs/providers/azurerm/) for full instructions on how to create this to populate your `provider.tf` file. + +## terraform.tfvars +If a `terraform.tfvars` file is present in the current directory, Terraform automatically loads it to populate variables. We don't recommend saving usernames and password to version control, but you can create a local secret variables file and use `-var-file` to load it. + +## variables.tf +The `variables.tf` file contains all of the input parameters that the user can specify when deploying this Terraform template. + +![graph](/examples/azure-vm-specialized-vhd-existing-vnet/graph.png) \ No newline at end of file diff --git a/examples/azure-vm-specialized-vhd-existing-vnet/deploy.ci.sh b/examples/azure-vm-specialized-vhd-existing-vnet/deploy.ci.sh new file mode 100755 index 000000000..3ffdcaa21 --- /dev/null +++ b/examples/azure-vm-specialized-vhd-existing-vnet/deploy.ci.sh @@ -0,0 +1,55 @@ +#!/bin/bash + +set -o errexit -o nounset + +docker run --rm -it \ + -e ARM_CLIENT_ID \ + -e ARM_CLIENT_SECRET \ + -e ARM_SUBSCRIPTION_ID \ + -e ARM_TENANT_ID \ + -v $(pwd):/data \ + --workdir=/data \ + --entrypoint "/bin/sh" \ + hashicorp/terraform:light \ + -c "/bin/terraform get; \ + /bin/terraform validate; \ + /bin/terraform plan -out=out.tfplan \ + -var os_disk_vhd_uri=$EXISTING_IMAGE_URI \ + -var hostname=$KEY \ + -var resource_group=$KEY \ + -var existing_vnet_resource_group=$EXISTING_RESOURCE_GROUP \ + -var admin_password=$PASSWORD \ + -var existing_subnet_id=/subscriptions/$ARM_SUBSCRIPTION_ID/resourceGroups/permanent/providers/Microsoft.Network/virtualNetworks/$EXISTING_VIRTUAL_NETWORK_NAME/subnets/$EXISTING_SUBNET_NAME \ + -var existing_subnet_name=$EXISTING_SUBNET_NAME \ + -var existing_virtual_network_name=$EXISTING_VIRTUAL_NETWORK_NAME \ + -var existing_storage_acct=$EXISTING_STORAGE_ACCOUNT_NAME; \ + /bin/terraform apply out.tfplan; \ + /bin/terraform show;" + +# cleanup deployed azure resources via azure-cli +docker run --rm -it \ + azuresdk/azure-cli-python \ + sh -c "az login --service-principal -u $ARM_CLIENT_ID -p $ARM_CLIENT_SECRET --tenant $ARM_TENANT_ID > /dev/null; \ + az vm show -g $KEY -n $KEY" + +# cleanup deployed azure resources via terraform +docker run --rm -it \ + -e ARM_CLIENT_ID \ + -e ARM_CLIENT_SECRET \ + -e ARM_SUBSCRIPTION_ID \ + -e ARM_TENANT_ID \ + -v $(pwd):/data \ + --workdir=/data \ + --entrypoint "/bin/sh" \ + hashicorp/terraform:light \ + -c "/bin/terraform destroy -force \ + -var os_disk_vhd_uri=$EXISTING_IMAGE_URI \ + -var hostname=$KEY \ + -var resource_group=$KEY \ + -var existing_vnet_resource_group=$EXISTING_RESOURCE_GROUP \ + -var admin_password=$PASSWORD \ + -var existing_subnet_id=$EXISTING_SUBNET_ID \ + -var existing_subnet_name=$EXISTING_SUBNET_NAME \ + -var existing_virtual_network_name=$EXISTING_VIRTUAL_NETWORK_NAME \ + -var existing_storage_acct=$EXISTING_STORAGE_ACCOUNT_NAME \ + -target=azurerm_resource_group.rg" \ No newline at end of file diff --git a/examples/azure-vm-specialized-vhd-existing-vnet/deploy.mac.sh b/examples/azure-vm-specialized-vhd-existing-vnet/deploy.mac.sh new file mode 100755 index 000000000..6f555e7a6 --- /dev/null +++ b/examples/azure-vm-specialized-vhd-existing-vnet/deploy.mac.sh @@ -0,0 +1,20 @@ +#!/bin/bash + +set -o errexit -o nounset + +if docker -v; then + + # generate a unique string for CI deployment + export KEY=$(cat /dev/urandom | env LC_CTYPE=C tr -cd 'a-z' | head -c 12) + export PASSWORD=$KEY$(cat /dev/urandom | env LC_CTYPE=C tr -cd 'A-Z' | head -c 2)$(cat /dev/urandom | env LC_CTYPE=C tr -cd '0-9' | head -c 2) + export EXISTING_RESOURCE_GROUP=permanent + export EXISTING_IMAGE_URI=https://permanentstor.blob.core.windows.net/permanent-vhds/permanent-osdisk1.vhd + export EXISTING_STORAGE_ACCOUNT_NAME=permanentstor + export EXISTING_VIRTUAL_NETWORK_NAME=vqeeopeictwmvnet + export EXISTING_SUBNET_NAME=vqeeopeictwmsubnet + + /bin/sh ./deploy.ci.sh + +else + echo "Docker is used to run terraform commands, please install before run: https://docs.docker.com/docker-for-mac/install/" +fi \ No newline at end of file diff --git a/examples/azure-vm-specialized-vhd-existing-vnet/graph.png b/examples/azure-vm-specialized-vhd-existing-vnet/graph.png new file mode 100644 index 000000000..14e4779df Binary files /dev/null and b/examples/azure-vm-specialized-vhd-existing-vnet/graph.png differ diff --git a/examples/azure-vm-specialized-vhd-existing-vnet/main.tf b/examples/azure-vm-specialized-vhd-existing-vnet/main.tf new file mode 100644 index 000000000..821ee8c31 --- /dev/null +++ b/examples/azure-vm-specialized-vhd-existing-vnet/main.tf @@ -0,0 +1,71 @@ +# provider "azurerm" { +# subscription_id = "REPLACE-WITH-YOUR-SUBSCRIPTION-ID" +# client_id = "REPLACE-WITH-YOUR-CLIENT-ID" +# client_secret = "REPLACE-WITH-YOUR-CLIENT-SECRET" +# tenant_id = "REPLACE-WITH-YOUR-TENANT-ID" +# } + +resource "azurerm_resource_group" "rg" { + name = "${var.resource_group}" + location = "${var.location}" +} + +resource "azurerm_public_ip" "pip" { + name = "PublicIp" + location = "${var.location}" + resource_group_name = "${azurerm_resource_group.rg.name}" + public_ip_address_allocation = "Dynamic" + domain_name_label = "${var.hostname}" +} + +resource "azurerm_network_interface" "nic" { + name = "nic" + location = "${var.location}" + resource_group_name = "${azurerm_resource_group.rg.name}" + + ip_configuration { + name = "ipconfig" + subnet_id = "${var.existing_subnet_id}" + private_ip_address_allocation = "Dynamic" + public_ip_address_id = "${azurerm_public_ip.pip.id}" + } +} + +resource "azurerm_storage_account" "stor" { + name = "${var.hostname}" + resource_group_name = "${azurerm_resource_group.rg.name}" + location = "${var.location}" + account_type = "${var.storage_account_type}" +} + +resource "azurerm_virtual_machine" "vm" { + name = "${var.hostname}" + location = "${var.location}" + resource_group_name = "${azurerm_resource_group.rg.name}" + vm_size = "${var.vm_size}" + network_interface_ids = ["${azurerm_network_interface.nic.id}"] + + storage_os_disk { + name = "${var.hostname}osdisk1" + image_uri = "${var.os_disk_vhd_uri}" + vhd_uri = "https://${var.existing_storage_acct}.blob.core.windows.net/${var.existing_vnet_resource_group}-vhds/${var.hostname}osdisk.vhd" + os_type = "${var.os_type}" + caching = "ReadWrite" + create_option = "FromImage" + } + + os_profile { + computer_name = "${var.hostname}" + admin_username = "${var.admin_username}" + admin_password = "${var.admin_password}" + } + + os_profile_linux_config { + disable_password_authentication = false + } + + boot_diagnostics { + enabled = true + storage_uri = "${azurerm_storage_account.stor.primary_blob_endpoint}" + } +} diff --git a/examples/azure-vm-specialized-vhd-existing-vnet/outputs.tf b/examples/azure-vm-specialized-vhd-existing-vnet/outputs.tf new file mode 100644 index 000000000..13768e554 --- /dev/null +++ b/examples/azure-vm-specialized-vhd-existing-vnet/outputs.tf @@ -0,0 +1,11 @@ +output "hostname" { + value = "${var.hostname}" +} + +output "vm_fqdn" { + value = "${azurerm_public_ip.pip.fqdn}" +} + +output "ssh_command" { + value = "ssh ${var.admin_username}@${azurerm_public_ip.pip.fqdn}" +} diff --git a/examples/azure-vm-specialized-vhd-existing-vnet/variables.tf b/examples/azure-vm-specialized-vhd-existing-vnet/variables.tf new file mode 100644 index 000000000..4e53919a8 --- /dev/null +++ b/examples/azure-vm-specialized-vhd-existing-vnet/variables.tf @@ -0,0 +1,90 @@ +variable "resource_group" { + description = "Name of the resource group in which to deploy your new Virtual Machine" +} + +variable "existing_vnet_resource_group" { + description = "Name of the existing resource group in which the existing vnet resides" +} + +variable "location" { + description = "The location/region where the virtual network resides." + default = "southcentralus" +} + +variable "hostname" { + description = "This variable is used in this template to create the domain name label as well as the virtual machine name. Must be unique." +} + +variable "os_type" { + description = "Type of OS on the existing vhd. Allowed values: 'windows' or 'linux'." + default = "linux" +} + +variable "os_disk_vhd_uri" { + description = "Uri of the existing VHD in ARM standard or premium storage" +} + +variable "existing_storage_acct" { + description = "The name of the storage account in which your existing VHD and image reside" +} + +variable "existing_virtual_network_name" { + description = "The name for the existing virtual network" +} + +variable "existing_subnet_name" { + description = "The name for the existing subnet in the existing virtual network" +} + +variable "existing_subnet_id" { + description = "The id for the existing subnet in the existing virtual network" +} + +variable "address_space" { + description = "The address space that is used by the virtual network. You can supply more than one address space. Changing this forces a new resource to be created." + default = "10.0.0.0/16" +} + +variable "subnet_prefix" { + description = "The address prefix to use for the subnet." + default = "10.0.10.0/24" +} + +variable "storage_account_type" { + description = "Defines the type of storage account to be created. Valid options are Standard_LRS, Standard_ZRS, Standard_GRS, Standard_RAGRS, Premium_LRS. Changing this is sometimes valid - see the Azure documentation for more information on which types of accounts can be converted into other types." + default = "Standard_GRS" +} + +variable "vm_size" { + description = "Specifies the size of the virtual machine." + default = "Standard_DS1_v2" +} + +variable "image_publisher" { + description = "name of the publisher of the image (az vm image list)" + default = "Canonical" +} + +variable "image_offer" { + description = "the name of the offer (az vm image list)" + default = "UbuntuServer" +} + +variable "image_sku" { + description = "image sku to apply (az vm image list)" + default = "16.04-LTS" +} + +variable "image_version" { + description = "version of the image to apply (az vm image list)" + default = "latest" +} + +variable "admin_username" { + description = "administrator user name" + default = "vmadmin" +} + +variable "admin_password" { + description = "administrator password (recommended to disable password auth)" +} diff --git a/examples/azure-vnet-to-vnet-peering/README.md b/examples/azure-vnet-to-vnet-peering/README.md new file mode 100644 index 000000000..cf6318bb9 --- /dev/null +++ b/examples/azure-vnet-to-vnet-peering/README.md @@ -0,0 +1,24 @@ +# VNET to VNET Peering + +This template creates two VNETs in the same location, each containing a single subnet, and creates connections between them using VNET Peering. + +## main.tf +The `main.tf` file contains the actual resources that will be deployed. It also contains the Azure Resource Group definition and any defined variables. + +## outputs.tf +This data is outputted when `terraform apply` is called, and can be queried using the `terraform output` command. + +## provider.tf +You may leave the provider block in the `main.tf`, as it is in this template, or you can create a file called `provider.tf` and add it to your `.gitignore` file. + +Azure requires that an application is added to Azure Active Directory to generate the `client_id`, `client_secret`, and `tenant_id` needed by Terraform (`subscription_id` can be recovered from your Azure account details). Please go [here](https://www.terraform.io/docs/providers/azurerm/) for full instructions on how to create this to populate your `provider.tf` file. + +## terraform.tfvars +If a `terraform.tfvars` file is present in the current directory, Terraform automatically loads it to populate variables. We don't recommend saving usernames and password to version control, but you can create a local secret variables file and use `-var-file` to load it. + +If you are committing this template to source control, please insure that you add this file to your `.gitignore` file. + +## variables.tf +The `variables.tf` file contains all of the input parameters that the user can specify when deploying this Terraform template. + +![`terraform graph`](/examples/azure-vnet-to-vnet-peering/graph.png) \ No newline at end of file diff --git a/examples/azure-vnet-to-vnet-peering/deploy.ci.sh b/examples/azure-vnet-to-vnet-peering/deploy.ci.sh new file mode 100755 index 000000000..4b7c1d693 --- /dev/null +++ b/examples/azure-vnet-to-vnet-peering/deploy.ci.sh @@ -0,0 +1,37 @@ +#!/bin/bash + +set -o errexit -o nounset + +docker run --rm -it \ + -e ARM_CLIENT_ID \ + -e ARM_CLIENT_SECRET \ + -e ARM_SUBSCRIPTION_ID \ + -e ARM_TENANT_ID \ + -v $(pwd):/data \ + --workdir=/data \ + --entrypoint "/bin/sh" \ + hashicorp/terraform:light \ + -c "/bin/terraform get; \ + /bin/terraform validate; \ + /bin/terraform plan -out=out.tfplan -var resource_group=$KEY; \ + /bin/terraform apply out.tfplan; \ + /bin/terraform show;" + +# cleanup deployed azure resources via azure-cli +docker run --rm -it \ + azuresdk/azure-cli-python \ + sh -c "az login --service-principal -u $ARM_CLIENT_ID -p $ARM_CLIENT_SECRET --tenant $ARM_TENANT_ID > /dev/null; \ + az network vnet peering show -g $KEY --vnet-name $KEY'-vnet1' -n vNet1-to-vNet2; + az network vnet peering show -g $KEY --vnet-name $KEY'-vnet2' -n vNet2-to-vNet1;" + +# cleanup deployed azure resources via terraform +docker run --rm -it \ + -e ARM_CLIENT_ID \ + -e ARM_CLIENT_SECRET \ + -e ARM_SUBSCRIPTION_ID \ + -e ARM_TENANT_ID \ + -v $(pwd):/data \ + --workdir=/data \ + --entrypoint "/bin/sh" \ + hashicorp/terraform:light \ + -c "/bin/terraform destroy -force -var resource_group=$KEY;" \ No newline at end of file diff --git a/examples/azure-vnet-to-vnet-peering/deploy.mac.sh b/examples/azure-vnet-to-vnet-peering/deploy.mac.sh new file mode 100755 index 000000000..dfc34c2be --- /dev/null +++ b/examples/azure-vnet-to-vnet-peering/deploy.mac.sh @@ -0,0 +1,15 @@ +#!/bin/bash + +set -o errexit -o nounset + +if docker -v; then + + # generate a unique string for CI deployment + export KEY=$(cat /dev/urandom | env LC_CTYPE=C tr -cd 'a-z' | head -c 12) + export PASSWORD=$KEY$(cat /dev/urandom | env LC_CTYPE=C tr -cd 'A-Z' | head -c 2)$(cat /dev/urandom | env LC_CTYPE=C tr -cd '0-9' | head -c 2) + + /bin/sh ./deploy.ci.sh + +else + echo "Docker is used to run terraform commands, please install before run: https://docs.docker.com/docker-for-mac/install/" +fi \ No newline at end of file diff --git a/examples/azure-vnet-to-vnet-peering/graph.png b/examples/azure-vnet-to-vnet-peering/graph.png new file mode 100644 index 000000000..342a78062 Binary files /dev/null and b/examples/azure-vnet-to-vnet-peering/graph.png differ diff --git a/examples/azure-vnet-to-vnet-peering/main.tf b/examples/azure-vnet-to-vnet-peering/main.tf new file mode 100644 index 000000000..6bdfb8a24 --- /dev/null +++ b/examples/azure-vnet-to-vnet-peering/main.tf @@ -0,0 +1,56 @@ +# provider "azurerm" { +# subscription_id = "REPLACE-WITH-YOUR-SUBSCRIPTION-ID" +# client_id = "REPLACE-WITH-YOUR-CLIENT-ID" +# client_secret = "REPLACE-WITH-YOUR-CLIENT-SECRET" +# tenant_id = "REPLACE-WITH-YOUR-TENANT-ID" +# } + +resource "azurerm_resource_group" "rg" { + name = "${var.resource_group}" + location = "${var.location}" +} + +resource "azurerm_virtual_network" "vnet1" { + name = "${var.resource_group}-vnet1" + location = "${var.location}" + address_space = ["10.0.0.0/24"] + resource_group_name = "${azurerm_resource_group.rg.name}" + + subnet { + name = "subnet1" + address_prefix = "10.0.0.0/24" + } +} + +resource "azurerm_virtual_network" "vnet2" { + name = "${var.resource_group}-vnet2" + location = "${var.location}" + address_space = ["192.168.0.0/24"] + resource_group_name = "${azurerm_resource_group.rg.name}" + + subnet { + name = "subnet1" + address_prefix = "192.168.0.0/24" + } +} + +resource "azurerm_virtual_network_peering" "peer1" { + name = "vNet1-to-vNet2" + resource_group_name = "${azurerm_resource_group.rg.name}" + virtual_network_name = "${azurerm_virtual_network.vnet1.name}" + remote_virtual_network_id = "${azurerm_virtual_network.vnet2.id}" + allow_virtual_network_access = true + allow_forwarded_traffic = false + allow_gateway_transit = false +} + +resource "azurerm_virtual_network_peering" "peer2" { + name = "vNet2-to-vNet1" + resource_group_name = "${azurerm_resource_group.rg.name}" + virtual_network_name = "${azurerm_virtual_network.vnet2.name}" + remote_virtual_network_id = "${azurerm_virtual_network.vnet1.id}" + allow_virtual_network_access = true + allow_forwarded_traffic = false + allow_gateway_transit = false + use_remote_gateways = false +} diff --git a/examples/azure-vnet-to-vnet-peering/variables.tf b/examples/azure-vnet-to-vnet-peering/variables.tf new file mode 100644 index 000000000..2701af343 --- /dev/null +++ b/examples/azure-vnet-to-vnet-peering/variables.tf @@ -0,0 +1,9 @@ +variable "resource_group" { + description = "The name of the resource group in which the virtual networks are created" + default = "myrg" +} + +variable "location" { + description = "The location/region where the virtual networks are created. Changing this forces a new resource to be created." + default = "southcentralus" +} diff --git a/examples/azure-vnet-two-subnets/README.md b/examples/azure-vnet-two-subnets/README.md new file mode 100644 index 000000000..dcd42e79e --- /dev/null +++ b/examples/azure-vnet-two-subnets/README.md @@ -0,0 +1,20 @@ +# Virtual Network with Two Subnets + +This template allows you to create a Virtual Network with two subnets. + +## main.tf +The `main.tf` file contains the actual resources that will be deployed. It also contains the Azure Resource Group definition and any defined variables. + +## outputs.tf +This data is outputted when `terraform apply` is called, and can be queried using the `terraform output` command. + +## provider.tf +Azure requires that an application is added to Azure Active Directory to generate the `client_id`, `client_secret`, and `tenant_id` needed by Terraform (`subscription_id` can be recovered from your Azure account details). Please go [here](https://www.terraform.io/docs/providers/azurerm/) for full instructions on how to create this to populate your `provider.tf` file. + +## terraform.tfvars +If a `terraform.tfvars` file is present in the current directory, Terraform automatically loads it to populate variables. We don't recommend saving usernames and password to version control, but you can create a local secret variables file and use `-var-file` to load it. + +## variables.tf +The `variables.tf` file contains all of the input parameters that the user can specify when deploying this Terraform template. + +![graph](/examples/azure-vnet-two-subnets/graph.png) \ No newline at end of file diff --git a/examples/azure-vnet-two-subnets/deploy.ci.sh b/examples/azure-vnet-two-subnets/deploy.ci.sh new file mode 100755 index 000000000..49fb955c7 --- /dev/null +++ b/examples/azure-vnet-two-subnets/deploy.ci.sh @@ -0,0 +1,41 @@ +#!/bin/bash + +set -o errexit -o nounset + +# generate a unique string for CI deployment +# KEY=$(cat /dev/urandom | tr -cd 'a-z' | head -c 12) +# PASSWORD=$KEY$(cat /dev/urandom | tr -cd 'A-Z' | head -c 2)$(cat /dev/urandom | tr -cd '0-9' | head -c 2) + +docker run --rm -it \ + -e ARM_CLIENT_ID \ + -e ARM_CLIENT_SECRET \ + -e ARM_SUBSCRIPTION_ID \ + -e ARM_TENANT_ID \ + -v $(pwd):/data \ + --workdir=/data \ + --entrypoint "/bin/sh" \ + hashicorp/terraform:light \ + -c "/bin/terraform get; \ + /bin/terraform validate; \ + /bin/terraform plan -out=out.tfplan -var resource_group=$KEY; \ + /bin/terraform apply out.tfplan; \ + /bin/terraform show;" + +# check that resources exist via azure cli +docker run --rm -it \ + azuresdk/azure-cli-python \ + sh -c "az login --service-principal -u $ARM_CLIENT_ID -p $ARM_CLIENT_SECRET --tenant $ARM_TENANT_ID > /dev/null; \ + az network vnet subnet show -n subnet1 -g $KEY --vnet-name '$KEY'vnet; \ + az network vnet subnet show -n subnet2 -g $KEY --vnet-name '$KEY'vnet;" + +# cleanup deployed azure resources via terraform +docker run --rm -it \ + -e ARM_CLIENT_ID \ + -e ARM_CLIENT_SECRET \ + -e ARM_SUBSCRIPTION_ID \ + -e ARM_TENANT_ID \ + -v $(pwd):/data \ + --workdir=/data \ + --entrypoint "/bin/sh" \ + hashicorp/terraform:light \ + -c "/bin/terraform destroy -force -var resource_group=$KEY;" \ No newline at end of file diff --git a/examples/azure-vnet-two-subnets/deploy.mac.sh b/examples/azure-vnet-two-subnets/deploy.mac.sh new file mode 100755 index 000000000..dfc34c2be --- /dev/null +++ b/examples/azure-vnet-two-subnets/deploy.mac.sh @@ -0,0 +1,15 @@ +#!/bin/bash + +set -o errexit -o nounset + +if docker -v; then + + # generate a unique string for CI deployment + export KEY=$(cat /dev/urandom | env LC_CTYPE=C tr -cd 'a-z' | head -c 12) + export PASSWORD=$KEY$(cat /dev/urandom | env LC_CTYPE=C tr -cd 'A-Z' | head -c 2)$(cat /dev/urandom | env LC_CTYPE=C tr -cd '0-9' | head -c 2) + + /bin/sh ./deploy.ci.sh + +else + echo "Docker is used to run terraform commands, please install before run: https://docs.docker.com/docker-for-mac/install/" +fi \ No newline at end of file diff --git a/examples/azure-vnet-two-subnets/graph.png b/examples/azure-vnet-two-subnets/graph.png new file mode 100644 index 000000000..1df101bab Binary files /dev/null and b/examples/azure-vnet-two-subnets/graph.png differ diff --git a/examples/azure-vnet-two-subnets/main.tf b/examples/azure-vnet-two-subnets/main.tf new file mode 100644 index 000000000..aee3593f3 --- /dev/null +++ b/examples/azure-vnet-two-subnets/main.tf @@ -0,0 +1,32 @@ +# provider "azurerm" { +# subscription_id = "REPLACE-WITH-YOUR-SUBSCRIPTION-ID" +# client_id = "REPLACE-WITH-YOUR-CLIENT-ID" +# client_secret = "REPLACE-WITH-YOUR-CLIENT-SECRET" +# tenant_id = "REPLACE-WITH-YOUR-TENANT-ID" +# } + +resource "azurerm_resource_group" "rg" { + name = "${var.resource_group}" + location = "${var.location}" +} + +resource "azurerm_virtual_network" "vnet" { + name = "${var.resource_group}vnet" + location = "${var.location}" + address_space = ["10.0.0.0/16"] + resource_group_name = "${azurerm_resource_group.rg.name}" +} + +resource "azurerm_subnet" "subnet1" { + name = "subnet1" + virtual_network_name = "${azurerm_virtual_network.vnet.name}" + resource_group_name = "${azurerm_resource_group.rg.name}" + address_prefix = "10.0.0.0/24" +} + +resource "azurerm_subnet" "subnet2" { + name = "subnet2" + virtual_network_name = "${azurerm_virtual_network.vnet.name}" + resource_group_name = "${azurerm_resource_group.rg.name}" + address_prefix = "10.0.1.0/24" +} diff --git a/examples/azure-vnet-two-subnets/variables.tf b/examples/azure-vnet-two-subnets/variables.tf new file mode 100644 index 000000000..8d5dd4131 --- /dev/null +++ b/examples/azure-vnet-two-subnets/variables.tf @@ -0,0 +1,8 @@ +variable "resource_group" { + description = "The name of the resource group in which to create the virtual network." +} + +variable "location" { + description = "The location/region where the virtual network is created. Changing this forces a new resource to be created." + default = "southcentralus" +} diff --git a/examples/digitalocean/variable.tf b/examples/digitalocean/variable.tf index 179b8d803..2068806a4 100644 --- a/examples/digitalocean/variable.tf +++ b/examples/digitalocean/variable.tf @@ -1,6 +1,6 @@ # #### -# Current Availiable Datacenter Regions +# Current Available Datacenter Regions # As of 05-07-2016 diff --git a/examples/gce-vpn/vpn.tf b/examples/gce-vpn/vpn.tf index d9f86cbc7..a588fd53d 100644 --- a/examples/gce-vpn/vpn.tf +++ b/examples/gce-vpn/vpn.tf @@ -5,7 +5,7 @@ provider "google" { region = "${var.region1}" } -# Create the two networks we want to join. They must have seperate, internal +# Create the two networks we want to join. They must have separate, internal # ranges. resource "google_compute_network" "network1" { name = "network1" diff --git a/flatmap/expand.go b/flatmap/expand.go index e325077ef..e0b81b641 100644 --- a/flatmap/expand.go +++ b/flatmap/expand.go @@ -37,7 +37,7 @@ func Expand(m map[string]string, key string) interface{} { // Check if this is a prefix in the map prefix := key + "." - for k, _ := range m { + for k := range m { if strings.HasPrefix(k, prefix) { return expandMap(m, prefix) } @@ -52,9 +52,17 @@ func expandArray(m map[string]string, prefix string) []interface{} { panic(err) } - // The Schema "Set" type stores its values in an array format, but using - // numeric hash values instead of ordinal keys. Take the set of keys - // regardless of value, and expand them in numeric order. + // If the number of elements in this array is 0, then return an + // empty slice as there is nothing to expand. Trying to expand it + // anyway could lead to crashes as any child maps, arrays or sets + // that no longer exist are still shown as empty with a count of 0. + if num == 0 { + return []interface{}{} + } + + // The Schema "Set" type stores its values in an array format, but + // using numeric hash values instead of ordinal keys. Take the set + // of keys regardless of value, and expand them in numeric order. // See GH-11042 for more details. keySet := map[int]bool{} computed := map[string]bool{} @@ -106,8 +114,14 @@ func expandArray(m map[string]string, prefix string) []interface{} { } func expandMap(m map[string]string, prefix string) map[string]interface{} { + // Submaps may not have a '%' key, so we can't count on this value being + // here. If we don't have a count, just proceed as if we have have a map. + if count, ok := m[prefix+"%"]; ok && count == "0" { + return map[string]interface{}{} + } + result := make(map[string]interface{}) - for k, _ := range m { + for k := range m { if !strings.HasPrefix(k, prefix) { continue } @@ -125,6 +139,7 @@ func expandMap(m map[string]string, prefix string) map[string]interface{} { if key == "%" { continue } + result[key] = Expand(m, k[:len(prefix)+len(key)]) } diff --git a/flatmap/expand_test.go b/flatmap/expand_test.go index cf74fadbc..c0fa83211 100644 --- a/flatmap/expand_test.go +++ b/flatmap/expand_test.go @@ -147,17 +147,45 @@ func TestExpand(t *testing.T) { }, }, }, + + { + Map: map[string]string{ + "struct.#": "1", + "struct.0.name": "hello", + "struct.0.set.#": "0", + "struct.0.set.0.key": "value", + }, + Key: "struct", + Output: []interface{}{ + map[string]interface{}{ + "name": "hello", + "set": []interface{}{}, + }, + }, + }, + + { + Map: map[string]string{ + "empty_map_of_sets.%": "0", + "empty_map_of_sets.set1.#": "0", + "empty_map_of_sets.set1.1234": "x", + }, + Key: "empty_map_of_sets", + Output: map[string]interface{}{}, + }, } for _, tc := range cases { - actual := Expand(tc.Map, tc.Key) - if !reflect.DeepEqual(actual, tc.Output) { - t.Errorf( - "Key: %v\nMap:\n\n%#v\n\nOutput:\n\n%#v\n\nExpected:\n\n%#v\n", - tc.Key, - tc.Map, - actual, - tc.Output) - } + t.Run(tc.Key, func(t *testing.T) { + actual := Expand(tc.Map, tc.Key) + if !reflect.DeepEqual(actual, tc.Output) { + t.Errorf( + "Key: %v\nMap:\n\n%#v\n\nOutput:\n\n%#v\n\nExpected:\n\n%#v\n", + tc.Key, + tc.Map, + actual, + tc.Output) + } + }) } } diff --git a/helper/acctest/random.go b/helper/acctest/random.go index 1a6fc8d19..3ddc078d3 100644 --- a/helper/acctest/random.go +++ b/helper/acctest/random.go @@ -24,6 +24,21 @@ func RandInt() int { return rand.New(rand.NewSource(time.Now().UnixNano())).Int() } +// RandomWithPrefix is used to generate a unique name with a prefix, for +// randomizing names in acceptance tests +func RandomWithPrefix(name string) string { + reseed() + return fmt.Sprintf("%s-%d", name, rand.New(rand.NewSource(time.Now().UnixNano())).Int()) +} + +func RandIntRange(min int, max int) int { + reseed() + source := rand.New(rand.NewSource(time.Now().UnixNano())) + rangeMax := max - min + + return int(source.Int31n(int32(rangeMax))) +} + // RandString generates a random alphanumeric string of the length specified func RandString(strlen int) string { return RandStringFromCharSet(strlen, CharSetAlphaNum) diff --git a/helper/logging/transport.go b/helper/logging/transport.go new file mode 100644 index 000000000..447792487 --- /dev/null +++ b/helper/logging/transport.go @@ -0,0 +1,53 @@ +package logging + +import ( + "log" + "net/http" + "net/http/httputil" +) + +type transport struct { + name string + transport http.RoundTripper +} + +func (t *transport) RoundTrip(req *http.Request) (*http.Response, error) { + if IsDebugOrHigher() { + reqData, err := httputil.DumpRequestOut(req, true) + if err == nil { + log.Printf("[DEBUG] "+logReqMsg, t.name, string(reqData)) + } else { + log.Printf("[ERROR] %s API Request error: %#v", t.name, err) + } + } + + resp, err := t.transport.RoundTrip(req) + if err != nil { + return resp, err + } + + if IsDebugOrHigher() { + respData, err := httputil.DumpResponse(resp, true) + if err == nil { + log.Printf("[DEBUG] "+logRespMsg, t.name, string(respData)) + } else { + log.Printf("[ERROR] %s API Response error: %#v", t.name, err) + } + } + + return resp, nil +} + +func NewTransport(name string, t http.RoundTripper) *transport { + return &transport{name, t} +} + +const logReqMsg = `%s API Request Details: +---[ REQUEST ]--------------------------------------- +%s +-----------------------------------------------------` + +const logRespMsg = `%s API Response Details: +---[ RESPONSE ]-------------------------------------- +%s +-----------------------------------------------------` diff --git a/helper/resource/state.go b/helper/resource/state.go index aafa7f3bc..37c586a11 100644 --- a/helper/resource/state.go +++ b/helper/resource/state.go @@ -2,10 +2,11 @@ package resource import ( "log" - "sync/atomic" "time" ) +var refreshGracePeriod = 30 * time.Second + // StateRefreshFunc is a function type used for StateChangeConf that is // responsible for refreshing the item being watched for a state change. // @@ -62,58 +63,76 @@ func (conf *StateChangeConf) WaitForState() (interface{}, error) { conf.ContinuousTargetOccurence = 1 } - // We can't safely read the result values if we timeout, so store them in - // an atomic.Value type Result struct { Result interface{} State string Error error + Done bool } - var lastResult atomic.Value - lastResult.Store(Result{}) - doneCh := make(chan struct{}) + // Read every result from the refresh loop, waiting for a positive result.Done. + resCh := make(chan Result, 1) + // cancellation channel for the refresh loop + cancelCh := make(chan struct{}) + + result := Result{} + go func() { - defer close(doneCh) + defer close(resCh) - // Wait for the delay time.Sleep(conf.Delay) - wait := 100 * time.Millisecond + // start with 0 delay for the first loop + var wait time.Duration for { + // store the last result + resCh <- result + + // wait and watch for cancellation + select { + case <-cancelCh: + return + case <-time.After(wait): + // first round had no wait + if wait == 0 { + wait = 100 * time.Millisecond + } + } + res, currentState, err := conf.Refresh() - result := Result{ + result = Result{ Result: res, State: currentState, Error: err, } - lastResult.Store(result) if err != nil { + resCh <- result return } // If we're waiting for the absence of a thing, then return if res == nil && len(conf.Target) == 0 { - targetOccurence += 1 + targetOccurence++ if conf.ContinuousTargetOccurence == targetOccurence { + result.Done = true + resCh <- result return - } else { - continue } + continue } if res == nil { // If we didn't find the resource, check if we have been // not finding it for awhile, and if so, report an error. - notfoundTick += 1 + notfoundTick++ if notfoundTick > conf.NotFoundChecks { result.Error = &NotFoundError{ LastError: err, Retries: notfoundTick, } - lastResult.Store(result) + resCh <- result return } } else { @@ -124,12 +143,13 @@ func (conf *StateChangeConf) WaitForState() (interface{}, error) { for _, allowed := range conf.Target { if currentState == allowed { found = true - targetOccurence += 1 + targetOccurence++ if conf.ContinuousTargetOccurence == targetOccurence { + result.Done = true + resCh <- result return - } else { - continue } + continue } } @@ -141,17 +161,23 @@ func (conf *StateChangeConf) WaitForState() (interface{}, error) { } } - if !found { + if !found && len(conf.Pending) > 0 { result.Error = &UnexpectedStateError{ LastError: err, State: result.State, ExpectedState: conf.Target, } - lastResult.Store(result) + resCh <- result return } } + // Wait between refreshes using exponential backoff, except when + // waiting for the target state to reoccur. + if targetOccurence == 0 { + wait *= 2 + } + // If a poll interval has been specified, choose that interval. // Otherwise bound the default value. if conf.PollInterval > 0 && conf.PollInterval < 180*time.Second { @@ -165,27 +191,69 @@ func (conf *StateChangeConf) WaitForState() (interface{}, error) { } log.Printf("[TRACE] Waiting %s before next try", wait) - time.Sleep(wait) - - // Wait between refreshes using exponential backoff, except when - // waiting for the target state to reoccur. - if targetOccurence == 0 { - wait *= 2 - } } }() - select { - case <-doneCh: - r := lastResult.Load().(Result) - return r.Result, r.Error - case <-time.After(conf.Timeout): - r := lastResult.Load().(Result) - return nil, &TimeoutError{ - LastError: r.Error, - LastState: r.State, - Timeout: conf.Timeout, - ExpectedState: conf.Target, + // store the last value result from the refresh loop + lastResult := Result{} + + timeout := time.After(conf.Timeout) + for { + select { + case r, ok := <-resCh: + // channel closed, so return the last result + if !ok { + return lastResult.Result, lastResult.Error + } + + // we reached the intended state + if r.Done { + return r.Result, r.Error + } + + // still waiting, store the last result + lastResult = r + + case <-timeout: + log.Printf("[WARN] WaitForState timeout after %s", conf.Timeout) + log.Printf("[WARN] WaitForState starting %s refresh grace period", refreshGracePeriod) + + // cancel the goroutine and start our grace period timer + close(cancelCh) + timeout := time.After(refreshGracePeriod) + + // we need a for loop and a label to break on, because we may have + // an extra response value to read, but still want to wait for the + // channel to close. + forSelect: + for { + select { + case r, ok := <-resCh: + if r.Done { + // the last refresh loop reached the desired state + return r.Result, r.Error + } + + if !ok { + // the goroutine returned + break forSelect + } + + // target state not reached, save the result for the + // TimeoutError and wait for the channel to close + lastResult = r + case <-timeout: + log.Println("[ERROR] WaitForState exceeded refresh grace period") + break forSelect + } + } + + return nil, &TimeoutError{ + LastError: lastResult.Error, + LastState: lastResult.State, + Timeout: conf.Timeout, + ExpectedState: conf.Target, + } } } } diff --git a/helper/resource/state_test.go b/helper/resource/state_test.go index dcbb3ce67..6d6b329a1 100644 --- a/helper/resource/state_test.go +++ b/helper/resource/state_test.go @@ -2,6 +2,8 @@ package resource import ( "errors" + "strings" + "sync/atomic" "testing" "time" ) @@ -70,6 +72,23 @@ func InconsistentStateRefreshFunc() StateRefreshFunc { } } +func UnknownPendingStateRefreshFunc() StateRefreshFunc { + sequence := []string{ + "unknown1", "unknown2", "done", + } + + r := NewStateGenerator(sequence) + + return func() (interface{}, string, error) { + idx, s, err := r.NextState() + if err != nil { + return nil, "", err + } + + return idx, s, nil + } +} + func TestWaitForState_inconsistent_positive(t *testing.T) { conf := &StateChangeConf{ Pending: []string{"replicating"}, @@ -92,11 +111,18 @@ func TestWaitForState_inconsistent_positive(t *testing.T) { } func TestWaitForState_inconsistent_negative(t *testing.T) { + refreshCount := int64(0) + f := InconsistentStateRefreshFunc() + refresh := func() (interface{}, string, error) { + atomic.AddInt64(&refreshCount, 1) + return f() + } + conf := &StateChangeConf{ Pending: []string{"replicating"}, Target: []string{"done"}, - Refresh: InconsistentStateRefreshFunc(), - Timeout: 90 * time.Millisecond, + Refresh: refresh, + Timeout: 85 * time.Millisecond, PollInterval: 10 * time.Millisecond, ContinuousTargetOccurence: 4, } @@ -106,13 +132,27 @@ func TestWaitForState_inconsistent_negative(t *testing.T) { if err == nil { t.Fatal("Expected timeout error. No error returned.") } - expectedErr := "timeout while waiting for state to become 'done' (last state: 'done', timeout: 90ms)" - if err.Error() != expectedErr { - t.Fatalf("Errors don't match.\nExpected: %q\nGiven: %q\n", expectedErr, err.Error()) + + // we can't guarantee the exact number of refresh calls in the tests by + // timing them, but we want to make sure the test at least went through th + // required states. + if atomic.LoadInt64(&refreshCount) < 6 { + t.Fatal("refreshed called too few times") + } + + expectedErr := "timeout while waiting for state to become 'done'" + if !strings.HasPrefix(err.Error(), expectedErr) { + t.Fatalf("error prefix doesn't match.\nExpected: %q\nGiven: %q\n", expectedErr, err.Error()) } } func TestWaitForState_timeout(t *testing.T) { + old := refreshGracePeriod + refreshGracePeriod = 5 * time.Millisecond + defer func() { + refreshGracePeriod = old + }() + conf := &StateChangeConf{ Pending: []string{"pending", "incomplete"}, Target: []string{"running"}, @@ -131,6 +171,62 @@ func TestWaitForState_timeout(t *testing.T) { t.Fatalf("Errors don't match.\nExpected: %q\nGiven: %q\n", expectedErr, err.Error()) } + if obj != nil { + t.Fatalf("should not return obj") + } +} + +// Make sure a timeout actually cancels the refresh goroutine and waits for its +// return. +func TestWaitForState_cancel(t *testing.T) { + // make this refresh func block until we cancel it + cancel := make(chan struct{}) + refresh := func() (interface{}, string, error) { + <-cancel + return nil, "pending", nil + } + conf := &StateChangeConf{ + Pending: []string{"pending", "incomplete"}, + Target: []string{"running"}, + Refresh: refresh, + Timeout: 10 * time.Millisecond, + PollInterval: 10 * time.Second, + } + + var obj interface{} + var err error + + waitDone := make(chan struct{}) + go func() { + defer close(waitDone) + obj, err = conf.WaitForState() + }() + + // make sure WaitForState is blocked + select { + case <-waitDone: + t.Fatal("WaitForState returned too early") + case <-time.After(10 * time.Millisecond): + } + + // unlock the refresh function + close(cancel) + // make sure WaitForState returns + select { + case <-waitDone: + case <-time.After(time.Second): + t.Fatal("WaitForState didn't return after refresh finished") + } + + if err == nil { + t.Fatal("Expected timeout error. No error returned.") + } + + expectedErr := "timeout while waiting for state to become 'running'" + if !strings.HasPrefix(err.Error(), expectedErr) { + t.Fatalf("Errors don't match.\nExpected: %q\nGiven: %q\n", expectedErr, err.Error()) + } + if obj != nil { t.Fatalf("should not return obj") } @@ -154,6 +250,22 @@ func TestWaitForState_success(t *testing.T) { } } +func TestWaitForState_successUnknownPending(t *testing.T) { + conf := &StateChangeConf{ + Target: []string{"done"}, + Refresh: UnknownPendingStateRefreshFunc(), + Timeout: 200 * time.Second, + } + + obj, err := conf.WaitForState() + if err != nil { + t.Fatalf("err: %s", err) + } + if obj == nil { + t.Fatalf("should return obj") + } +} + func TestWaitForState_successEmpty(t *testing.T) { conf := &StateChangeConf{ Pending: []string{"pending", "incomplete"}, diff --git a/helper/resource/testing.go b/helper/resource/testing.go index 9557207c3..04367c53c 100644 --- a/helper/resource/testing.go +++ b/helper/resource/testing.go @@ -174,6 +174,13 @@ type TestStep struct { // determined by inspecting the state for ResourceName's ID. ImportStateId string + // ImportStateIdPrefix is the prefix added in front of ImportStateId. + // This can be useful in complex import cases, where more than one + // attribute needs to be passed on as the Import ID. Mainly in cases + // where the ID is not known, and a known prefix needs to be added to + // the unset ImportStateId field. + ImportStateIdPrefix string + // ImportStateCheck checks the results of ImportState. It should be // used to verify that the resulting value of ImportState has the // proper resources, IDs, and attributes. @@ -347,26 +354,23 @@ func Test(t TestT, c TestCase) { // Any errors are stored so that they can be returned by the factory in // terraform to match non-test behavior. func testProviderFactories(c TestCase) (map[string]terraform.ResourceProviderFactory, error) { - ctxProviders := make(map[string]terraform.ResourceProviderFactory) - + ctxProviders := c.ProviderFactories // make(map[string]terraform.ResourceProviderFactory) + if ctxProviders == nil { + ctxProviders = make(map[string]terraform.ResourceProviderFactory) + } // add any fixed providers for k, p := range c.Providers { ctxProviders[k] = terraform.ResourceProviderFactoryFixed(p) } - // call any factory functions and store the result. - for k, pf := range c.ProviderFactories { - p, err := pf() - ctxProviders[k] = func() (terraform.ResourceProvider, error) { - return p, err - } - } - // reset the providers if needed for k, pf := range ctxProviders { // we can ignore any errors here, if we don't have a provider to reset // the error will be handled later - p, _ := pf() + p, err := pf() + if err != nil { + return nil, err + } if p, ok := p.(TestProvider); ok { err := p.TestReset() if err != nil { diff --git a/helper/resource/testing_import_state.go b/helper/resource/testing_import_state.go index d5c579629..28ad10526 100644 --- a/helper/resource/testing_import_state.go +++ b/helper/resource/testing_import_state.go @@ -25,6 +25,10 @@ func testStepImportState( importId = resource.Primary.ID } + importPrefix := step.ImportStateIdPrefix + if importPrefix != "" { + importId = fmt.Sprintf("%s%s", importPrefix, importId) + } // Setup the context. We initialize with an empty state. We use the // full config for provider configurations. diff --git a/helper/resource/testing_import_state_test.go b/helper/resource/testing_import_state_test.go index 56e6a4845..96b1edc3d 100644 --- a/helper/resource/testing_import_state_test.go +++ b/helper/resource/testing_import_state_test.go @@ -178,6 +178,80 @@ func TestTest_importStateDetectId(t *testing.T) { } } +func TestTest_importStateIdPrefix(t *testing.T) { + mp := testProvider() + mp.DiffReturn = nil + mp.ApplyFn = func( + info *terraform.InstanceInfo, + state *terraform.InstanceState, + diff *terraform.InstanceDiff) (*terraform.InstanceState, error) { + if !diff.Destroy { + return &terraform.InstanceState{ + ID: "foo", + }, nil + } + + return nil, nil + } + + mp.RefreshFn = func( + i *terraform.InstanceInfo, + s *terraform.InstanceState) (*terraform.InstanceState, error) { + return s, nil + } + + mp.ImportStateFn = func( + info *terraform.InstanceInfo, id string) ([]*terraform.InstanceState, error) { + if id != "bazfoo" { + return nil, fmt.Errorf("bad import ID: %s", id) + } + + return []*terraform.InstanceState{ + { + ID: "bar", + Ephemeral: terraform.EphemeralState{Type: "test_instance"}, + }, + }, nil + } + + checked := false + checkFn := func(s []*terraform.InstanceState) error { + checked = true + + if s[0].ID != "bar" { + return fmt.Errorf("bad: %#v", s) + } + + return nil + } + + mt := new(mockT) + Test(mt, TestCase{ + Providers: map[string]terraform.ResourceProvider{ + "test": mp, + }, + + Steps: []TestStep{ + { + Config: testConfigStr, + }, + { + ResourceName: "test_instance.foo", + ImportState: true, + ImportStateCheck: checkFn, + ImportStateIdPrefix: "baz", + }, + }, + }) + + if mt.failed() { + t.Fatalf("test failed: %s", mt.failMessage()) + } + if !checked { + t.Fatal("didn't call check") + } +} + func TestTest_importStateVerify(t *testing.T) { mp := testProvider() mp.DiffReturn = nil diff --git a/helper/resource/wait_test.go b/helper/resource/wait_test.go index bb17d9fe4..526b21ae3 100644 --- a/helper/resource/wait_test.go +++ b/helper/resource/wait_test.go @@ -25,6 +25,21 @@ func TestRetry(t *testing.T) { } } +// make sure a slow StateRefreshFunc is allowed to complete after timeout +func TestRetry_grace(t *testing.T) { + t.Parallel() + + f := func() *RetryError { + time.Sleep(1 * time.Second) + return nil + } + + err := Retry(10*time.Millisecond, f) + if err != nil { + t.Fatalf("err: %s", err) + } +} + func TestRetry_timeout(t *testing.T) { t.Parallel() @@ -39,14 +54,18 @@ func TestRetry_timeout(t *testing.T) { } func TestRetry_hang(t *testing.T) { - t.Parallel() + old := refreshGracePeriod + refreshGracePeriod = 50 * time.Millisecond + defer func() { + refreshGracePeriod = old + }() f := func() *RetryError { time.Sleep(2 * time.Second) return nil } - err := Retry(1*time.Second, f) + err := Retry(50*time.Millisecond, f) if err == nil { t.Fatal("should error") } diff --git a/helper/schema/backend.go b/helper/schema/backend.go index 33fe2c190..a0729c02c 100644 --- a/helper/schema/backend.go +++ b/helper/schema/backend.go @@ -28,8 +28,8 @@ type Backend struct { config *ResourceData } -const ( - backendConfigKey = iota +var ( + backendConfigKey = contextKey("backend config") ) // FromContextBackendConfig extracts a ResourceData with the configuration diff --git a/helper/schema/getsource_string.go b/helper/schema/getsource_string.go index 790dbff91..3a9762939 100644 --- a/helper/schema/getsource_string.go +++ b/helper/schema/getsource_string.go @@ -1,4 +1,4 @@ -// Code generated by "stringer -type=getSource resource_data_get_source.go"; DO NOT EDIT +// Code generated by "stringer -type=getSource resource_data_get_source.go"; DO NOT EDIT. package schema diff --git a/helper/schema/provisioner.go b/helper/schema/provisioner.go index 6ac3fc1bf..c1564a215 100644 --- a/helper/schema/provisioner.go +++ b/helper/schema/provisioner.go @@ -46,25 +46,25 @@ type Provisioner struct { stopOnce sync.Once } -// These constants are the keys that can be used to access data in -// the context parameters for Provisioners. -const ( - connDataInvalid int = iota +// Keys that can be used to access data in the context parameters for +// Provisioners. +var ( + connDataInvalid = contextKey("data invalid") // This returns a *ResourceData for the connection information. // Guaranteed to never be nil. - ProvConnDataKey + ProvConnDataKey = contextKey("provider conn data") // This returns a *ResourceData for the config information. // Guaranteed to never be nil. - ProvConfigDataKey + ProvConfigDataKey = contextKey("provider config data") // This returns a terraform.UIOutput. Guaranteed to never be nil. - ProvOutputKey + ProvOutputKey = contextKey("provider output") // This returns the raw InstanceState passed to Apply. Guaranteed to // be set, but may be nil. - ProvRawStateKey + ProvRawStateKey = contextKey("provider raw state") ) // InternalValidate should be called to validate the structure diff --git a/helper/schema/schema.go b/helper/schema/schema.go index f62c4d128..32d172139 100644 --- a/helper/schema/schema.go +++ b/helper/schema/schema.go @@ -23,6 +23,9 @@ import ( "github.com/mitchellh/mapstructure" ) +// type used for schema package context keys +type contextKey string + // Schema is used to describe the structure of a value. // // Read the documentation of the struct elements for important details. @@ -62,10 +65,20 @@ type Schema struct { DiffSuppressFunc SchemaDiffSuppressFunc // If this is non-nil, then this will be a default value that is used - // when this item is not set in the configuration/state. + // when this item is not set in the configuration. // - // DefaultFunc can be specified if you want a dynamic default value. - // Only one of Default or DefaultFunc can be set. + // DefaultFunc can be specified to compute a dynamic default. + // Only one of Default or DefaultFunc can be set. If DefaultFunc is + // used then its return value should be stable to avoid generating + // confusing/perpetual diffs. + // + // Changing either Default or the return value of DefaultFunc can be + // a breaking change, especially if the attribute in question has + // ForceNew set. If a default needs to change to align with changing + // assumptions in an upstream API then it may be necessary to also use + // the MigrateState function on the resource to change the state to match, + // or have the Read function adjust the state value to align with the + // new default. // // If Required is true above, then Default cannot be set. DefaultFunc // can be set with Required. If the DefaultFunc returns nil, then there @@ -632,6 +645,19 @@ func (m schemaMap) InternalValidate(topSchemaMap schemaMap) error { } } + // Computed-only field + if v.Computed && !v.Optional { + if v.ValidateFunc != nil { + return fmt.Errorf("%s: ValidateFunc is for validating user input, "+ + "there's nothing to validate on computed-only field", k) + } + if v.DiffSuppressFunc != nil { + return fmt.Errorf("%s: DiffSuppressFunc is for suppressing differences"+ + " between config and state representation. "+ + "There is no config for computed-only field, nothing to compare.", k) + } + } + if v.ValidateFunc != nil { switch v.Type { case TypeList, TypeSet: @@ -643,19 +669,6 @@ func (m schemaMap) InternalValidate(topSchemaMap schemaMap) error { return nil } -func (m schemaMap) markAsRemoved(k string, schema *Schema, diff *terraform.InstanceDiff) { - existingDiff, ok := diff.Attributes[k] - if ok { - existingDiff.NewRemoved = true - diff.Attributes[k] = schema.finalizeDiff(existingDiff) - return - } - - diff.Attributes[k] = schema.finalizeDiff(&terraform.ResourceAttrDiff{ - NewRemoved: true, - }) -} - func (m schemaMap) diff( k string, schema *Schema, @@ -744,6 +757,7 @@ func (m schemaMap) diffList( diff.Attributes[k+".#"] = &terraform.ResourceAttrDiff{ Old: oldStr, NewComputed: true, + RequiresNew: schema.ForceNew, } return nil } @@ -779,7 +793,6 @@ func (m schemaMap) diffList( switch t := schema.Elem.(type) { case *Resource: - countDiff, cOk := diff.GetAttribute(k + ".#") // This is a complex resource for i := 0; i < maxLen; i++ { for k2, schema := range t.Schema { @@ -788,15 +801,6 @@ func (m schemaMap) diffList( if err != nil { return err } - - // If parent list is being removed - // remove all subfields which were missed by the diff func - // We process these separately because type-specific diff functions - // lack the context (hierarchy of fields) - subKeyIsCount := strings.HasSuffix(subK, ".#") - if cOk && countDiff.New == "0" && !subKeyIsCount { - m.markAsRemoved(subK, schema, diff) - } } } case *Schema: @@ -1006,7 +1010,6 @@ func (m schemaMap) diffSet( for _, code := range list { switch t := schema.Elem.(type) { case *Resource: - countDiff, cOk := diff.GetAttribute(k + ".#") // This is a complex resource for k2, schema := range t.Schema { subK := fmt.Sprintf("%s.%s.%s", k, code, k2) @@ -1014,17 +1017,7 @@ func (m schemaMap) diffSet( if err != nil { return err } - - // If parent set is being removed - // remove all subfields which were missed by the diff func - // We process these separately because type-specific diff functions - // lack the context (hierarchy of fields) - subKeyIsCount := strings.HasSuffix(subK, ".#") - if cOk && countDiff.New == "0" && !subKeyIsCount { - m.markAsRemoved(subK, schema, diff) - } } - case *Schema: // Copy the schema so that we can set Computed/ForceNew from // the parent schema (the TypeSet). diff --git a/helper/schema/schema_test.go b/helper/schema/schema_test.go index 4d93ffd17..3f8ca2329 100644 --- a/helper/schema/schema_test.go +++ b/helper/schema/schema_test.go @@ -2779,360 +2779,49 @@ func TestSchemaMap_Diff(t *testing.T) { }, { - Name: "Removal of TypeList should cause nested Bool fields w/ Default to be removed too", + Name: "List with computed schema and ForceNew", Schema: map[string]*Schema{ - "deployment_group_name": &Schema{ - Type: TypeString, - Required: true, + "config": &Schema{ + Type: TypeList, + Optional: true, ForceNew: true, - }, - - "alarm_configuration": &Schema{ - Type: TypeList, - Optional: true, - MaxItems: 1, - Elem: &Resource{ - Schema: map[string]*Schema{ - "alarms": &Schema{ - Type: TypeSet, - Optional: true, - Set: HashString, - Elem: &Schema{Type: TypeString}, - }, - - "enabled": &Schema{ - Type: TypeBool, - Optional: true, - }, - - "ignore_poll_alarm_failure": &Schema{ - Type: TypeBool, - Optional: true, - Default: false, - }, - }, + Elem: &Schema{ + Type: TypeString, }, }, }, State: &terraform.InstanceState{ Attributes: map[string]string{ - "alarm_configuration.#": "1", - "alarm_configuration.0.alarms.#": "1", - "alarm_configuration.0.alarms.2356372769": "foo", - "alarm_configuration.0.enabled": "true", - "alarm_configuration.0.ignore_poll_alarm_failure": "false", - "deployment_group_name": "foo-group-32345345345", + "config.#": "2", + "config.0": "a", + "config.1": "b", }, }, Config: map[string]interface{}{ - "deployment_group_name": "foo-group-32345345345", + "config": []interface{}{"${var.a}", "${var.b}"}, + }, + + ConfigVariables: map[string]ast.Variable{ + "var.a": interfaceToVariableSwallowError( + config.UnknownVariableValue), + "var.b": interfaceToVariableSwallowError( + config.UnknownVariableValue), }, Diff: &terraform.InstanceDiff{ Attributes: map[string]*terraform.ResourceAttrDiff{ - "alarm_configuration.#": &terraform.ResourceAttrDiff{ - Old: "1", - New: "0", - NewRemoved: false, - }, - "alarm_configuration.0.alarms": &terraform.ResourceAttrDiff{ - Old: "", - New: "", - NewRemoved: true, - }, - "alarm_configuration.0.alarms.#": &terraform.ResourceAttrDiff{ - Old: "1", - New: "0", - NewRemoved: false, - }, - "alarm_configuration.0.alarms.2356372769": &terraform.ResourceAttrDiff{ - Old: "foo", - New: "", - NewRemoved: true, - }, - "alarm_configuration.0.enabled": &terraform.ResourceAttrDiff{ - Old: "true", - New: "false", - NewRemoved: true, - }, - "alarm_configuration.0.ignore_poll_alarm_failure": &terraform.ResourceAttrDiff{ - Old: "", - New: "", - NewRemoved: true, - }, - }, - }, - }, - - { - Name: "Removal of TypeList should cause all empty nested String fields to be removed too", - Schema: map[string]*Schema{ - "bucket": { - Type: TypeString, - Required: true, - ForceNew: true, - }, - - "acl": { - Type: TypeString, - Default: "private", - Optional: true, - }, - - "website": { - Type: TypeList, - Optional: true, - Elem: &Resource{ - Schema: map[string]*Schema{ - "index_document": { - Type: TypeString, - Optional: true, - }, - - "error_document": { - Type: TypeString, - Optional: true, - }, - - "redirect_all_requests_to": { - Type: TypeString, - Optional: true, - }, - - "routing_rules": { - Type: TypeString, - Optional: true, - }, - }, + "config.#": &terraform.ResourceAttrDiff{ + Old: "2", + New: "", + RequiresNew: true, + NewComputed: true, }, }, }, - State: &terraform.InstanceState{ - Attributes: map[string]string{ - "acl": "public-read", - "bucket": "tf-test-bucket-5011072831090096749", - "website.#": "1", - "website.0.error_document": "error.html", - "website.0.index_document": "index.html", - "website.0.redirect_all_requests_to": "", - }, - }, - - Config: map[string]interface{}{ - "acl": "public-read", - "bucket": "tf-test-bucket-5011072831090096749", - }, - - Diff: &terraform.InstanceDiff{ - Attributes: map[string]*terraform.ResourceAttrDiff{ - "website.#": &terraform.ResourceAttrDiff{ - Old: "1", - New: "0", - NewRemoved: false, - }, - "website.0.index_document": &terraform.ResourceAttrDiff{ - Old: "index.html", - New: "", - NewRemoved: true, - }, - "website.0.error_document": &terraform.ResourceAttrDiff{ - Old: "error.html", - New: "", - NewRemoved: true, - }, - "website.0.redirect_all_requests_to": &terraform.ResourceAttrDiff{ - Old: "", - New: "", - NewRemoved: true, - }, - "website.0.routing_rules": &terraform.ResourceAttrDiff{ - Old: "", - New: "", - NewRemoved: true, - }, - }, - }, - }, - - { - Name: "Removal of TypeList should cause nested Int fields w/ Default to be removed too", - Schema: map[string]*Schema{ - "availability_zones": &Schema{ - Type: TypeSet, - Elem: &Schema{Type: TypeString}, - Optional: true, - Computed: true, - Set: HashString, - }, - - "access_logs": &Schema{ - Type: TypeList, - Optional: true, - MaxItems: 1, - Elem: &Resource{ - Schema: map[string]*Schema{ - "interval": &Schema{ - Type: TypeInt, - Optional: true, - Default: 60, - }, - "bucket": &Schema{ - Type: TypeString, - Required: true, - }, - "bucket_prefix": &Schema{ - Type: TypeString, - Optional: true, - }, - "enabled": &Schema{ - Type: TypeBool, - Optional: true, - Default: true, - }, - }, - }, - }, - }, - - State: &terraform.InstanceState{ - Attributes: map[string]string{ - "access_logs.#": "1", - "access_logs.0.bucket": "terraform-access-logs-bucket-5906065226840117876", - "access_logs.0.bucket_prefix": "", - "access_logs.0.enabled": "true", - "access_logs.0.interval": "5", - "availability_zones.#": "3", - "availability_zones.2050015877": "us-west-2c", - "availability_zones.221770259": "us-west-2b", - "availability_zones.2487133097": "us-west-2a", - }, - }, - - Config: map[string]interface{}{ - "availability_zones": []interface{}{"us-west-2a", "us-west-2b", "us-west-2c"}, - }, - - Diff: &terraform.InstanceDiff{ - Attributes: map[string]*terraform.ResourceAttrDiff{ - "access_logs.#": &terraform.ResourceAttrDiff{ - Old: "1", - New: "0", - NewRemoved: false, - }, - "access_logs.0.bucket": &terraform.ResourceAttrDiff{ - Old: "terraform-access-logs-bucket-5906065226840117876", - New: "", - NewRemoved: true, - }, - "access_logs.0.bucket_prefix": &terraform.ResourceAttrDiff{ - Old: "", - New: "", - NewRemoved: true, - }, - "access_logs.0.enabled": &terraform.ResourceAttrDiff{ - Old: "", - New: "", - NewRemoved: true, - }, - "access_logs.0.interval": &terraform.ResourceAttrDiff{ - Old: "5", - New: "60", - NewRemoved: true, - }, - }, - }, - }, - - { - Name: "Removal of TypeSet should cause computed fields to be removed", - Schema: map[string]*Schema{ - "type_set": &Schema{ - Type: TypeSet, - Optional: true, - Elem: &Resource{ - Schema: map[string]*Schema{ - "name": &Schema{ - Type: TypeString, - Optional: true, - }, - "required": &Schema{ - Type: TypeString, - Required: true, - }, - "value": &Schema{ - Type: TypeInt, - Optional: true, - }, - "required_value": &Schema{ - Type: TypeInt, - Required: true, - }, - "computed_value": &Schema{ - Type: TypeString, - Optional: true, - Computed: true, - }, - }, - }, - Set: func(i interface{}) int { - if i != nil { - return 12345 - } - return 0 - }, - }, - }, - - State: &terraform.InstanceState{ - Attributes: map[string]string{ - "type_set.#": "1", - "type_set.12345.name": "Name", - "type_set.12345.required": "Required", - "type_set.12345.value": "0", - "type_set.12345.required_value": "5", - "type_set.12345.computed_value": "COMPUTED", - }, - }, - - Config: map[string]interface{}{ - "type_set": []interface{}{}, - }, - - Diff: &terraform.InstanceDiff{ - Attributes: map[string]*terraform.ResourceAttrDiff{ - "type_set.#": &terraform.ResourceAttrDiff{ - Old: "1", - New: "0", - NewRemoved: false, - }, - "type_set.12345.name": &terraform.ResourceAttrDiff{ - Old: "Name", - New: "", - NewRemoved: true, - }, - "type_set.12345.required": &terraform.ResourceAttrDiff{ - Old: "Required", - New: "", - NewRemoved: true, - }, - "type_set.12345.value": &terraform.ResourceAttrDiff{ - Old: "0", - New: "0", - NewRemoved: true, - }, - "type_set.12345.required_value": &terraform.ResourceAttrDiff{ - Old: "5", - New: "0", - NewRemoved: true, - }, - "type_set.12345.computed_value": &terraform.ResourceAttrDiff{ - NewRemoved: true, - }, - }, - }, + Err: false, }, } @@ -3636,16 +3325,46 @@ func TestSchemaMap_InternalValidate(t *testing.T) { }, true, }, + + "computed-only field with validateFunc": { + map[string]*Schema{ + "string": &Schema{ + Type: TypeString, + Computed: true, + ValidateFunc: func(v interface{}, k string) (ws []string, es []error) { + es = append(es, fmt.Errorf("this is not fine")) + return + }, + }, + }, + true, + }, + + "computed-only field with diffSuppressFunc": { + map[string]*Schema{ + "string": &Schema{ + Type: TypeString, + Computed: true, + DiffSuppressFunc: func(k, old, new string, d *ResourceData) bool { + // Always suppress any diff + return false + }, + }, + }, + true, + }, } for tn, tc := range cases { - err := schemaMap(tc.In).InternalValidate(nil) - if err != nil != tc.Err { - if tc.Err { - t.Fatalf("%q: Expected error did not occur:\n\n%#v", tn, tc.In) + t.Run(tn, func(t *testing.T) { + err := schemaMap(tc.In).InternalValidate(nil) + if err != nil != tc.Err { + if tc.Err { + t.Fatalf("%q: Expected error did not occur:\n\n%#v", tn, tc.In) + } + t.Fatalf("%q: Unexpected error occurred: %s\n\n%#v", tn, err, tc.In) } - t.Fatalf("%q: Unexpected error occurred:\n\n%#v", tn, tc.In) - } + }) } } diff --git a/helper/schema/serialize.go b/helper/schema/serialize.go index 3eb2d0075..fe6d7504c 100644 --- a/helper/schema/serialize.go +++ b/helper/schema/serialize.go @@ -85,6 +85,9 @@ func SerializeValueForHash(buf *bytes.Buffer, val interface{}, schema *Schema) { // to hash complex substructures when used in sets, and so the serialization // is not reversible. func SerializeResourceForHash(buf *bytes.Buffer, val interface{}, resource *Resource) { + if val == nil { + return + } sm := resource.Schema m := val.(map[string]interface{}) var keys []string diff --git a/helper/schema/set_test.go b/helper/schema/set_test.go index 87a9f7228..21f292954 100644 --- a/helper/schema/set_test.go +++ b/helper/schema/set_test.go @@ -111,3 +111,20 @@ func TestSetUnion(t *testing.T) { func testSetInt(v interface{}) int { return v.(int) } + +func TestHashResource_nil(t *testing.T) { + resource := &Resource{ + Schema: map[string]*Schema{ + "name": { + Type: TypeString, + Optional: true, + }, + }, + } + f := HashResource(resource) + + idx := f(nil) + if idx != 0 { + t.Fatalf("Expected 0 when hashing nil, given: %d", idx) + } +} diff --git a/helper/schema/valuetype_string.go b/helper/schema/valuetype_string.go index 08f008450..1610cec2d 100644 --- a/helper/schema/valuetype_string.go +++ b/helper/schema/valuetype_string.go @@ -1,4 +1,4 @@ -// Code generated by "stringer -type=ValueType valuetype.go"; DO NOT EDIT +// Code generated by "stringer -type=ValueType valuetype.go"; DO NOT EDIT. package schema diff --git a/helper/structure/expand_json.go b/helper/structure/expand_json.go new file mode 100644 index 000000000..b3eb90fdf --- /dev/null +++ b/helper/structure/expand_json.go @@ -0,0 +1,11 @@ +package structure + +import "encoding/json" + +func ExpandJsonFromString(jsonString string) (map[string]interface{}, error) { + var result map[string]interface{} + + err := json.Unmarshal([]byte(jsonString), &result) + + return result, err +} diff --git a/helper/structure/expand_json_test.go b/helper/structure/expand_json_test.go new file mode 100644 index 000000000..431cd19e0 --- /dev/null +++ b/helper/structure/expand_json_test.go @@ -0,0 +1,48 @@ +package structure + +import ( + "reflect" + "testing" +) + +func TestExpandJson_emptyString(t *testing.T) { + _, err := ExpandJsonFromString("") + if err == nil { + t.Fatal("Expected to throw an error while Expanding JSON") + } +} + +func TestExpandJson_singleItem(t *testing.T) { + input := `{ + "foo": "bar" + }` + expected := make(map[string]interface{}, 1) + expected["foo"] = "bar" + actual, err := ExpandJsonFromString(input) + if err != nil { + t.Fatalf("Expected not to throw an error while Expanding JSON, but got: %s", err) + } + + if !reflect.DeepEqual(actual, expected) { + t.Fatalf("Got:\n\n%+v\n\nExpected:\n\n%+v\n", actual, expected) + } +} + +func TestExpandJson_multipleItems(t *testing.T) { + input := `{ + "foo": "bar", + "hello": "world" + }` + expected := make(map[string]interface{}, 1) + expected["foo"] = "bar" + expected["hello"] = "world" + + actual, err := ExpandJsonFromString(input) + if err != nil { + t.Fatalf("Expected not to throw an error while Expanding JSON, but got: %s", err) + } + + if !reflect.DeepEqual(actual, expected) { + t.Fatalf("Got:\n\n%+v\n\nExpected:\n\n%+v\n", actual, expected) + } +} diff --git a/helper/structure/flatten_json.go b/helper/structure/flatten_json.go new file mode 100644 index 000000000..578ad2ead --- /dev/null +++ b/helper/structure/flatten_json.go @@ -0,0 +1,16 @@ +package structure + +import "encoding/json" + +func FlattenJsonToString(input map[string]interface{}) (string, error) { + if len(input) == 0 { + return "", nil + } + + result, err := json.Marshal(input) + if err != nil { + return "", err + } + + return string(result), nil +} diff --git a/helper/structure/flatten_json_test.go b/helper/structure/flatten_json_test.go new file mode 100644 index 000000000..fe131a9dc --- /dev/null +++ b/helper/structure/flatten_json_test.go @@ -0,0 +1,47 @@ +package structure + +import ( + "testing" +) + +func TestFlattenJson_empty(t *testing.T) { + input := make(map[string]interface{}, 0) + expected := "" + actual, err := FlattenJsonToString(input) + if err != nil { + t.Fatalf("Expected not to throw an error while Flattening JSON, but got: %s", err) + } + + if expected != actual { + t.Fatalf("Got: `%+v`. Expected: `%+v`", actual, expected) + } +} + +func TestFlattenJson_singleItem(t *testing.T) { + input := make(map[string]interface{}, 1) + input["foo"] = "bar" + expected := `{"foo":"bar"}` + actual, err := FlattenJsonToString(input) + if err != nil { + t.Fatalf("Expected not to throw an error while Flattening JSON, but got: %s", err) + } + + if expected != actual { + t.Fatalf("Got: `%+v`. Expected: `%+v`", actual, expected) + } +} + +func TestFlattenJson_multipleItems(t *testing.T) { + input := make(map[string]interface{}, 1) + input["foo"] = "bar" + input["bar"] = "foo" + expected := `{"bar":"foo","foo":"bar"}` + actual, err := FlattenJsonToString(input) + if err != nil { + t.Fatalf("Expected not to throw an error while Flattening JSON, but got: %s", err) + } + + if expected != actual { + t.Fatalf("Got: `%+v`. Expected: `%+v`", actual, expected) + } +} diff --git a/builtin/providers/azurerm/structure.go b/helper/structure/normalize_json.go similarity index 84% rename from builtin/providers/azurerm/structure.go rename to helper/structure/normalize_json.go index 47acd631e..3256b476d 100644 --- a/builtin/providers/azurerm/structure.go +++ b/helper/structure/normalize_json.go @@ -1,11 +1,11 @@ -package azurerm +package structure import "encoding/json" // Takes a value containing JSON string and passes it through // the JSON parser to normalize it, returns either a parsing // error or normalized JSON string. -func normalizeJsonString(jsonString interface{}) (string, error) { +func NormalizeJsonString(jsonString interface{}) (string, error) { var j interface{} if jsonString == nil || jsonString.(string) == "" { diff --git a/builtin/providers/azurerm/structure_test.go b/helper/structure/normalize_json_test.go similarity index 74% rename from builtin/providers/azurerm/structure_test.go rename to helper/structure/normalize_json_test.go index 7ad258333..9350c95c2 100644 --- a/builtin/providers/azurerm/structure_test.go +++ b/helper/structure/normalize_json_test.go @@ -1,11 +1,10 @@ -package azurerm +package structure -import "testing" - -func TestNormalizeJsonString(t *testing.T) { - var err error - var actual string +import ( + "testing" +) +func TestNormalizeJsonString_valid(t *testing.T) { // Well formatted and valid. validJson := `{ "abc": { @@ -22,7 +21,7 @@ func TestNormalizeJsonString(t *testing.T) { }` expected := `{"abc":{"def":123,"xyz":[{"a":"ホリネズミ"},{"b":"1\\n2"}]}}` - actual, err = normalizeJsonString(validJson) + actual, err := NormalizeJsonString(validJson) if err != nil { t.Fatalf("Expected not to throw an error while parsing JSON, but got: %s", err) } @@ -30,7 +29,9 @@ func TestNormalizeJsonString(t *testing.T) { if actual != expected { t.Fatalf("Got:\n\n%s\n\nExpected:\n\n%s\n", actual, expected) } +} +func TestNormalizeJsonString_invalid(t *testing.T) { // Well formatted but not valid, // missing closing squre bracket. invalidJson := `{ @@ -43,7 +44,8 @@ func TestNormalizeJsonString(t *testing.T) { } } }` - actual, err = normalizeJsonString(invalidJson) + expected := `{"abc":{"def":123,"xyz":[{"a":"ホリネズミ"},{"b":"1\\n2"}]}}` + actual, err := NormalizeJsonString(invalidJson) if err == nil { t.Fatalf("Expected to throw an error while parsing JSON, but got: %s", err) } diff --git a/helper/structure/suppress_json_diff.go b/helper/structure/suppress_json_diff.go new file mode 100644 index 000000000..46f794a71 --- /dev/null +++ b/helper/structure/suppress_json_diff.go @@ -0,0 +1,21 @@ +package structure + +import ( + "reflect" + + "github.com/hashicorp/terraform/helper/schema" +) + +func SuppressJsonDiff(k, old, new string, d *schema.ResourceData) bool { + oldMap, err := ExpandJsonFromString(old) + if err != nil { + return false + } + + newMap, err := ExpandJsonFromString(new) + if err != nil { + return false + } + + return reflect.DeepEqual(oldMap, newMap) +} diff --git a/helper/structure/suppress_json_diff_test.go b/helper/structure/suppress_json_diff_test.go new file mode 100644 index 000000000..c017981bc --- /dev/null +++ b/helper/structure/suppress_json_diff_test.go @@ -0,0 +1,51 @@ +package structure + +import ( + "testing" +) + +func TestSuppressJsonDiff_same(t *testing.T) { + original := `{ "enabled": true }` + new := `{ "enabled": true }` + expected := true + + actual := SuppressJsonDiff("test", original, new, nil) + if actual != expected { + t.Fatal("[ERROR] Identical JSON values shouldn't cause a diff") + } +} + +func TestSuppressJsonDiff_sameWithWhitespace(t *testing.T) { + original := `{ + "enabled": true + }` + new := `{ "enabled": true }` + expected := true + + actual := SuppressJsonDiff("test", original, new, nil) + if actual != expected { + t.Fatal("[ERROR] Identical JSON values shouldn't cause a diff") + } +} + +func TestSuppressJsonDiff_differentValue(t *testing.T) { + original := `{ "enabled": true }` + new := `{ "enabled": false }` + expected := false + + actual := SuppressJsonDiff("test", original, new, nil) + if actual != expected { + t.Fatal("[ERROR] Different JSON values should cause a diff") + } +} + +func TestSuppressJsonDiff_newValue(t *testing.T) { + original := `{ "enabled": true }` + new := `{ "enabled": false, "world": "round" }` + expected := false + + actual := SuppressJsonDiff("test", original, new, nil) + if actual != expected { + t.Fatal("[ERROR] Different JSON values should cause a diff") + } +} diff --git a/helper/validation/validation.go b/helper/validation/validation.go index 82a9dec72..7b894f540 100644 --- a/helper/validation/validation.go +++ b/helper/validation/validation.go @@ -6,6 +6,7 @@ import ( "strings" "github.com/hashicorp/terraform/helper/schema" + "github.com/hashicorp/terraform/helper/structure" ) // IntBetween returns a SchemaValidateFunc which tests if the provided value @@ -98,3 +99,10 @@ func CIDRNetwork(min, max int) schema.SchemaValidateFunc { return } } + +func ValidateJsonString(v interface{}, k string) (ws []string, errors []error) { + if _, err := structure.NormalizeJsonString(v); err != nil { + errors = append(errors, fmt.Errorf("%q contains an invalid JSON: %s", k, err)) + } + return +} diff --git a/helper/validation/validation_test.go b/helper/validation/validation_test.go index ed488ae32..991955d23 100644 --- a/helper/validation/validation_test.go +++ b/helper/validation/validation_test.go @@ -65,6 +65,61 @@ func TestValidationStringInSlice(t *testing.T) { }) } +func TestValidateJsonString(t *testing.T) { + type testCases struct { + Value string + ErrCount int + } + + invalidCases := []testCases{ + { + Value: `{0:"1"}`, + ErrCount: 1, + }, + { + Value: `{'abc':1}`, + ErrCount: 1, + }, + { + Value: `{"def":}`, + ErrCount: 1, + }, + { + Value: `{"xyz":[}}`, + ErrCount: 1, + }, + } + + for _, tc := range invalidCases { + _, errors := ValidateJsonString(tc.Value, "json") + if len(errors) != tc.ErrCount { + t.Fatalf("Expected %q to trigger a validation error.", tc.Value) + } + } + + validCases := []testCases{ + { + Value: ``, + ErrCount: 0, + }, + { + Value: `{}`, + ErrCount: 0, + }, + { + Value: `{"abc":["1","2"]}`, + ErrCount: 0, + }, + } + + for _, tc := range validCases { + _, errors := ValidateJsonString(tc.Value, "json") + if len(errors) != tc.ErrCount { + t.Fatalf("Expected %q not to trigger a validation error.", tc.Value) + } + } +} + func runTestCases(t *testing.T, cases []testCase) { matchErr := func(errs []error, r *regexp.Regexp) bool { // err must match one provided diff --git a/main.go b/main.go index b94de2ebc..237581200 100644 --- a/main.go +++ b/main.go @@ -258,6 +258,15 @@ func copyOutput(r io.Reader, doneCh chan<- struct{}) { if runtime.GOOS == "windows" { stdout = colorable.NewColorableStdout() stderr = colorable.NewColorableStderr() + + // colorable is not concurrency-safe when stdout and stderr are the + // same console, so we need to add some synchronization to ensure that + // we can't be concurrently writing to both stderr and stdout at + // once, or else we get intermingled writes that create gibberish + // in the console. + wrapped := synchronizedWriters(stdout, stderr) + stdout = wrapped[0] + stderr = wrapped[1] } var wg sync.WaitGroup diff --git a/scripts/generate-plugins.go b/scripts/generate-plugins.go index 07bf33be7..b4a0bc9a4 100644 --- a/scripts/generate-plugins.go +++ b/scripts/generate-plugins.go @@ -271,6 +271,9 @@ IMPORTS "github.com/hashicorp/terraform/plugin" "github.com/hashicorp/terraform/terraform" + //New Provider Builds + opcprovider "github.com/hashicorp/terraform-provider-opc/opc" + // Legacy, will remove once it conforms with new structure chefprovisioner "github.com/hashicorp/terraform/builtin/provisioners/chef" ) @@ -287,6 +290,9 @@ func init() { // Legacy provisioners that don't match our heuristics for auto-finding // built-in provisioners. InternalProvisioners["chef"] = func() terraform.ResourceProvisioner { return new(chefprovisioner.ResourceProvisioner) } + + // New Provider Layouts + InternalProviders["opc"] = func() terraform.ResourceProvider { return opcprovider.Provider() } } ` diff --git a/state/backup.go b/state/backup.go index 15d8f6f3e..c357bba49 100644 --- a/state/backup.go +++ b/state/backup.go @@ -41,19 +41,12 @@ func (s *BackupState) PersistState() error { return s.Real.PersistState() } -// all states get wrapped by BackupState, so it has to be a Locker func (s *BackupState) Lock(info *LockInfo) (string, error) { - if s, ok := s.Real.(Locker); ok { - return s.Lock(info) - } - return "", nil + return s.Real.Lock(info) } func (s *BackupState) Unlock(id string) error { - if s, ok := s.Real.(Locker); ok { - return s.Unlock(id) - } - return nil + return s.Real.Unlock(id) } func (s *BackupState) backup() error { diff --git a/state/inmem.go b/state/inmem.go index ff8daab8f..2bbfb3d44 100644 --- a/state/inmem.go +++ b/state/inmem.go @@ -1,6 +1,10 @@ package state import ( + "errors" + "sync" + "time" + "github.com/hashicorp/terraform/terraform" ) @@ -26,3 +30,59 @@ func (s *InmemState) WriteState(state *terraform.State) error { func (s *InmemState) PersistState() error { return nil } + +func (s *InmemState) Lock(*LockInfo) (string, error) { + return "", nil +} + +func (s *InmemState) Unlock(string) error { + return nil +} + +// inmemLocker is an in-memory State implementation for testing locks. +type inmemLocker struct { + *InmemState + + mu sync.Mutex + lockInfo *LockInfo + // count the calls to Lock + lockCounter int +} + +func (s *inmemLocker) Lock(info *LockInfo) (string, error) { + s.mu.Lock() + defer s.mu.Unlock() + s.lockCounter++ + + lockErr := &LockError{ + Info: &LockInfo{}, + } + + if s.lockInfo != nil { + lockErr.Err = errors.New("state locked") + *lockErr.Info = *s.lockInfo + return "", lockErr + } + + info.Created = time.Now().UTC() + s.lockInfo = info + return s.lockInfo.ID, nil +} + +func (s *inmemLocker) Unlock(id string) error { + s.mu.Lock() + defer s.mu.Unlock() + + lockErr := &LockError{ + Info: &LockInfo{}, + } + + if id != s.lockInfo.ID { + lockErr.Err = errors.New("invalid lock id") + *lockErr.Info = *s.lockInfo + return lockErr + } + + s.lockInfo = nil + return nil +} diff --git a/state/inmem_test.go b/state/inmem_test.go index 885127122..6ca8a69a5 100644 --- a/state/inmem_test.go +++ b/state/inmem_test.go @@ -14,3 +14,39 @@ func TestInmemState_impl(t *testing.T) { var _ StatePersister = new(InmemState) var _ StateRefresher = new(InmemState) } + +func TestInmemLocker(t *testing.T) { + inmem := &InmemState{state: TestStateInitial()} + // test that it correctly wraps the inmem state + s := &inmemLocker{InmemState: inmem} + TestState(t, s) + + info := NewLockInfo() + + id, err := s.Lock(info) + if err != nil { + t.Fatal(err) + } + + if id == "" { + t.Fatal("no lock id from state lock") + } + + // locking again should fail + _, err = s.Lock(NewLockInfo()) + if err == nil { + t.Fatal("state locked while locked") + } + + if err.(*LockError).Info.ID != id { + t.Fatal("wrong lock id from lock failure") + } + + if err := s.Unlock(id); err != nil { + t.Fatal(err) + } + + if _, err := s.Lock(NewLockInfo()); err != nil { + t.Fatal(err) + } +} diff --git a/state/remote/swift.go b/state/remote/swift.go index 6fe490d40..2f12aa4e7 100644 --- a/state/remote/swift.go +++ b/state/remote/swift.go @@ -18,6 +18,7 @@ import ( "github.com/gophercloud/gophercloud/openstack" "github.com/gophercloud/gophercloud/openstack/objectstorage/v1/containers" "github.com/gophercloud/gophercloud/openstack/objectstorage/v1/objects" + tf_openstack "github.com/hashicorp/terraform/builtin/providers/openstack" ) const TFSTATE_NAME = "tfstate.tf" @@ -249,8 +250,19 @@ func (c *SwiftClient) validateConfig(conf map[string]string) (err error) { config.BuildNameToCertificate() } + // if OS_DEBUG is set, log the requests and responses + var osDebug bool + if os.Getenv("OS_DEBUG") != "" { + osDebug = true + } + transport := &http.Transport{Proxy: http.ProxyFromEnvironment, TLSClientConfig: config} - provider.HTTPClient.Transport = transport + provider.HTTPClient = http.Client{ + Transport: &tf_openstack.LogRoundTripper{ + Rt: transport, + OsDebug: osDebug, + }, + } err = openstack.Authenticate(provider, ao) if err != nil { diff --git a/state/state.go b/state/state.go index 9491958a3..45163852b 100644 --- a/state/state.go +++ b/state/state.go @@ -2,6 +2,7 @@ package state import ( "bytes" + "context" "encoding/json" "errors" "fmt" @@ -28,6 +29,7 @@ type State interface { StateWriter StateRefresher StatePersister + Locker } // StateReader is the interface for things that can return a state. Retrieving @@ -72,6 +74,48 @@ type Locker interface { Unlock(id string) error } +// test hook to verify that LockWithContext has attempted a lock +var postLockHook func() + +// Lock the state, using the provided context for timeout and cancellation. +// This backs off slightly to an upper limit. +func LockWithContext(ctx context.Context, s State, info *LockInfo) (string, error) { + delay := time.Second + maxDelay := 16 * time.Second + for { + id, err := s.Lock(info) + if err == nil { + return id, nil + } + + le, ok := err.(*LockError) + if !ok { + // not a lock error, so we can't retry + return "", err + } + + if le == nil || le.Info == nil || le.Info.ID == "" { + // If we dont' have a complete LockError, there's something wrong with the lock + return "", err + } + + if postLockHook != nil { + postLockHook() + } + + // there's an existing lock, wait and try again + select { + case <-ctx.Done(): + // return the last lock error with the info + return "", err + case <-time.After(delay): + if delay < maxDelay { + delay *= 2 + } + } + } +} + // Generate a LockInfo structure, populating the required fields. func NewLockInfo() *LockInfo { // this doesn't need to be cryptographically secure, just unique. diff --git a/state/state_test.go b/state/state_test.go index e93f5680a..a8fdec6ab 100644 --- a/state/state_test.go +++ b/state/state_test.go @@ -1,12 +1,14 @@ package state import ( + "context" "encoding/json" "flag" "io/ioutil" "log" "os" "testing" + "time" "github.com/hashicorp/terraform/helper/logging" ) @@ -50,3 +52,59 @@ func TestNewLockInfo(t *testing.T) { t.Fatal(err) } } + +func TestLockWithContext(t *testing.T) { + inmem := &InmemState{state: TestStateInitial()} + // test that it correctly wraps the inmem state + s := &inmemLocker{InmemState: inmem} + + id, err := s.Lock(NewLockInfo()) + if err != nil { + t.Fatal(err) + } + + // use a cancelled context for an immediate timeout + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + info := NewLockInfo() + info.Info = "lock with context" + _, err = LockWithContext(ctx, s, info) + if err == nil { + t.Fatal("lock should have failed immediately") + } + + // block until LockwithContext has made a first attempt + attempted := make(chan struct{}) + postLockHook = func() { + close(attempted) + postLockHook = nil + } + + // unlock the state during LockWithContext + unlocked := make(chan struct{}) + go func() { + defer close(unlocked) + <-attempted + if err := s.Unlock(id); err != nil { + t.Fatal(err) + } + }() + + ctx, cancel = context.WithTimeout(context.Background(), 2*time.Second) + defer cancel() + + id, err = LockWithContext(ctx, s, info) + if err != nil { + t.Fatal("lock should have completed within 2s:", err) + } + + // ensure the goruotine completes + <-unlocked + + // Lock should have been called a total of 4 times. + // 1 initial lock, 1 failure, 1 failure + 1 retry + if s.lockCounter != 4 { + t.Fatalf("lock only called %d times", s.lockCounter) + } +} diff --git a/synchronized_writers.go b/synchronized_writers.go new file mode 100644 index 000000000..2533d1316 --- /dev/null +++ b/synchronized_writers.go @@ -0,0 +1,31 @@ +package main + +import ( + "io" + "sync" +) + +type synchronizedWriter struct { + io.Writer + mutex *sync.Mutex +} + +// synchronizedWriters takes a set of writers and returns wrappers that ensure +// that only one write can be outstanding at a time across the whole set. +func synchronizedWriters(targets ...io.Writer) []io.Writer { + mutex := &sync.Mutex{} + ret := make([]io.Writer, len(targets)) + for i, target := range targets { + ret[i] = &synchronizedWriter{ + Writer: target, + mutex: mutex, + } + } + return ret +} + +func (w *synchronizedWriter) Write(p []byte) (int, error) { + w.mutex.Lock() + defer w.mutex.Unlock() + return w.Writer.Write(p) +} diff --git a/terraform/context.go b/terraform/context.go index 15528beed..306128edf 100644 --- a/terraform/context.go +++ b/terraform/context.go @@ -453,8 +453,17 @@ func (c *Context) Input(mode InputMode) error { // Apply applies the changes represented by this context and returns // the resulting state. // -// In addition to returning the resulting state, this context is updated -// with the latest state. +// Even in the case an error is returned, the state may be returned and will +// potentially be partially updated. In addition to returning the resulting +// state, this context is updated with the latest state. +// +// If the state is required after an error, the caller should call +// Context.State, rather than rely on the return value. +// +// TODO: Apply and Refresh should either always return a state, or rely on the +// State() method. Currently the helper/resource testing framework relies +// on the absence of a returned state to determine if Destroy can be +// called, so that will need to be refactored before this can be changed. func (c *Context) Apply() (*State, error) { defer c.acquireRun("apply")() @@ -580,7 +589,7 @@ func (c *Context) Plan() (*Plan, error) { // to their latest state. This will update the state that this context // works with, along with returning it. // -// Even in the case an error is returned, the state will be returned and +// Even in the case an error is returned, the state may be returned and // will potentially be partially updated. func (c *Context) Refresh() (*State, error) { defer c.acquireRun("refresh")() diff --git a/terraform/context_apply_test.go b/terraform/context_apply_test.go index afe2f85a7..7d6a75e97 100644 --- a/terraform/context_apply_test.go +++ b/terraform/context_apply_test.go @@ -3447,6 +3447,36 @@ func TestContext2Apply_multiVarCountDec(t *testing.T) { } } +// Test that we can resolve a multi-var (splat) for the first resource +// created in a non-root module, which happens when the module state doesn't +// exist yet. +// https://github.com/hashicorp/terraform/issues/14438 +func TestContext2Apply_multiVarMissingState(t *testing.T) { + m := testModule(t, "apply-multi-var-missing-state") + p := testProvider("test") + p.ApplyFn = testApplyFn + p.DiffFn = testDiffFn + + // First, apply with a count of 3 + ctx := testContext2(t, &ContextOpts{ + Module: m, + Providers: map[string]ResourceProviderFactory{ + "test": testProviderFuncFixed(p), + }, + }) + + if _, err := ctx.Plan(); err != nil { + t.Fatalf("plan failed: %s", err) + } + + // Before the relevant bug was fixed, Terraform would panic during apply. + if _, err := ctx.Apply(); err != nil { + t.Fatalf("apply failed: %s", err) + } + + // If we get here with no errors or panics then our test was successful. +} + func TestContext2Apply_nilDiff(t *testing.T) { m := testModule(t, "apply-good") p := testProvider("aws") @@ -4430,6 +4460,7 @@ func TestContext2Apply_provisionerDestroyFailContinue(t *testing.T) { p.ApplyFn = testApplyFn p.DiffFn = testDiffFn + var l sync.Mutex var calls []string pr.ApplyFn = func(rs *InstanceState, c *ResourceConfig) error { val, ok := c.Config["foo"] @@ -4437,6 +4468,8 @@ func TestContext2Apply_provisionerDestroyFailContinue(t *testing.T) { t.Fatalf("bad value for foo: %v %#v", val, c) } + l.Lock() + defer l.Unlock() calls = append(calls, val.(string)) return fmt.Errorf("provisioner error") } @@ -4501,6 +4534,7 @@ func TestContext2Apply_provisionerDestroyFailContinueFail(t *testing.T) { p.ApplyFn = testApplyFn p.DiffFn = testDiffFn + var l sync.Mutex var calls []string pr.ApplyFn = func(rs *InstanceState, c *ResourceConfig) error { val, ok := c.Config["foo"] @@ -4508,6 +4542,8 @@ func TestContext2Apply_provisionerDestroyFailContinueFail(t *testing.T) { t.Fatalf("bad value for foo: %v %#v", val, c) } + l.Lock() + defer l.Unlock() calls = append(calls, val.(string)) return fmt.Errorf("provisioner error") } @@ -7181,6 +7217,30 @@ func TestContext2Apply_targetedModuleUnrelatedOutputs(t *testing.T) { "aws": testProviderFuncFixed(p), }, Targets: []string{"module.child2"}, + State: &State{ + Modules: []*ModuleState{ + { + Path: []string{"root"}, + Outputs: map[string]*OutputState{}, + Resources: map[string]*ResourceState{}, + }, + { + Path: []string{"root", "child1"}, + Outputs: map[string]*OutputState{ + "instance_id": { + Type: "string", + Value: "foo-bar-baz", + }, + }, + Resources: map[string]*ResourceState{}, + }, + { + Path: []string{"root", "child2"}, + Outputs: map[string]*OutputState{}, + Resources: map[string]*ResourceState{}, + }, + }, + }, }) if _, err := ctx.Plan(); err != nil { @@ -7192,12 +7252,28 @@ func TestContext2Apply_targetedModuleUnrelatedOutputs(t *testing.T) { t.Fatalf("err: %s", err) } + // module.child1's instance_id output should be retained from state + // module.child2's instance_id is updated because its dependency is updated + // child2_id is updated because if its transitive dependency via module.child2 checkStateString(t, state, ` +Outputs: + +child2_id = foo + +module.child1: + + Outputs: + + instance_id = foo-bar-baz module.child2: aws_instance.foo: ID = foo - `) + + Outputs: + + instance_id = foo +`) } func TestContext2Apply_targetedModuleResource(t *testing.T) { @@ -8100,3 +8176,32 @@ func TestContext2Apply_terraformEnv(t *testing.T) { t.Fatalf("bad: \n%s", actual) } } + +// verify that multiple config references only create a single depends_on entry +func TestContext2Apply_multiRef(t *testing.T) { + m := testModule(t, "apply-multi-ref") + p := testProvider("aws") + p.ApplyFn = testApplyFn + p.DiffFn = testDiffFn + + ctx := testContext2(t, &ContextOpts{ + Module: m, + Providers: map[string]ResourceProviderFactory{ + "aws": testProviderFuncFixed(p), + }, + }) + + if _, err := ctx.Plan(); err != nil { + t.Fatalf("err: %s", err) + } + + state, err := ctx.Apply() + if err != nil { + t.Fatalf("err: %s", err) + } + + deps := state.Modules[0].Resources["aws_instance.other"].Dependencies + if len(deps) > 1 || deps[0] != "aws_instance.create" { + t.Fatalf("expected 1 depends_on entry for aws_instance.create, got %q", deps) + } +} diff --git a/terraform/context_plan_test.go b/terraform/context_plan_test.go index 7064f6465..aeabcb021 100644 --- a/terraform/context_plan_test.go +++ b/terraform/context_plan_test.go @@ -532,6 +532,9 @@ func TestContext2Plan_moduleProviderInherit(t *testing.T) { state *InstanceState, c *ResourceConfig) (*InstanceDiff, error) { v, _ := c.Get("from") + + l.Lock() + defer l.Unlock() calls = append(calls, v.(string)) return testDiffFn(info, state, c) } @@ -628,6 +631,9 @@ func TestContext2Plan_moduleProviderDefaults(t *testing.T) { state *InstanceState, c *ResourceConfig) (*InstanceDiff, error) { v, _ := c.Get("from") + + l.Lock() + defer l.Unlock() calls = append(calls, v.(string)) return testDiffFn(info, state, c) } @@ -677,6 +683,8 @@ func TestContext2Plan_moduleProviderDefaultsVar(t *testing.T) { buf.WriteString(v.(string) + "\n") } + l.Lock() + defer l.Unlock() calls = append(calls, buf.String()) return nil } @@ -1863,6 +1871,107 @@ func TestContext2Plan_countIncreaseFromOneCorrupted(t *testing.T) { } } +// A common pattern in TF configs is to have a set of resources with the same +// count and to use count.index to create correspondences between them: +// +// foo_id = "${foo.bar.*.id[count.index]}" +// +// This test is for the situation where some instances already exist and the +// count is increased. In that case, we should see only the create diffs +// for the new instances and not any update diffs for the existing ones. +func TestContext2Plan_countIncreaseWithSplatReference(t *testing.T) { + m := testModule(t, "plan-count-splat-reference") + p := testProvider("aws") + p.DiffFn = testDiffFn + s := &State{ + Modules: []*ModuleState{ + &ModuleState{ + Path: rootModulePath, + Resources: map[string]*ResourceState{ + "aws_instance.foo.0": &ResourceState{ + Type: "aws_instance", + Primary: &InstanceState{ + ID: "bar", + Attributes: map[string]string{ + "name": "foo 0", + }, + }, + }, + "aws_instance.foo.1": &ResourceState{ + Type: "aws_instance", + Primary: &InstanceState{ + ID: "bar", + Attributes: map[string]string{ + "name": "foo 1", + }, + }, + }, + "aws_instance.bar.0": &ResourceState{ + Type: "aws_instance", + Primary: &InstanceState{ + ID: "bar", + Attributes: map[string]string{ + "foo_name": "foo 0", + }, + }, + }, + "aws_instance.bar.1": &ResourceState{ + Type: "aws_instance", + Primary: &InstanceState{ + ID: "bar", + Attributes: map[string]string{ + "foo_name": "foo 1", + }, + }, + }, + }, + }, + }, + } + ctx := testContext2(t, &ContextOpts{ + Module: m, + Providers: map[string]ResourceProviderFactory{ + "aws": testProviderFuncFixed(p), + }, + State: s, + }) + + plan, err := ctx.Plan() + if err != nil { + t.Fatalf("err: %s", err) + } + + actual := strings.TrimSpace(plan.String()) + expected := strings.TrimSpace(` +DIFF: + +CREATE: aws_instance.bar.2 + foo_name: "" => "foo 2" + type: "" => "aws_instance" +CREATE: aws_instance.foo.2 + name: "" => "foo 2" + type: "" => "aws_instance" + +STATE: + +aws_instance.bar.0: + ID = bar + foo_name = foo 0 +aws_instance.bar.1: + ID = bar + foo_name = foo 1 +aws_instance.foo.0: + ID = bar + name = foo 0 +aws_instance.foo.1: + ID = bar + name = foo 1 +`) + if actual != expected { + t.Fatalf("bad:\n%s", actual) + } +} + func TestContext2Plan_destroy(t *testing.T) { m := testModule(t, "plan-destroy") p := testProvider("aws") @@ -3146,3 +3255,146 @@ func TestContext2Plan_ignoreChangesWithFlatmaps(t *testing.T) { t.Fatalf("bad:\n%s\n\nexpected\n\n%s", actual, expected) } } + +// TestContext2Plan_resourceNestedCount ensures resource sets that depend on +// the count of another resource set (ie: count of a data source that depends +// on another data source's instance count - data.x.foo.*.id) get properly +// normalized to the indexes they should be. This case comes up when there is +// an existing state (after an initial apply). +func TestContext2Plan_resourceNestedCount(t *testing.T) { + m := testModule(t, "nested-resource-count-plan") + p := testProvider("aws") + p.DiffFn = testDiffFn + p.RefreshFn = func(i *InstanceInfo, is *InstanceState) (*InstanceState, error) { + return is, nil + } + s := &State{ + Modules: []*ModuleState{ + &ModuleState{ + Path: rootModulePath, + Resources: map[string]*ResourceState{ + "aws_instance.foo.0": &ResourceState{ + Type: "aws_instance", + Primary: &InstanceState{ + ID: "foo0", + Attributes: map[string]string{ + "id": "foo0", + }, + }, + }, + "aws_instance.foo.1": &ResourceState{ + Type: "aws_instance", + Primary: &InstanceState{ + ID: "foo1", + Attributes: map[string]string{ + "id": "foo1", + }, + }, + }, + "aws_instance.bar.0": &ResourceState{ + Type: "aws_instance", + Dependencies: []string{"aws_instance.foo.*"}, + Primary: &InstanceState{ + ID: "bar0", + Attributes: map[string]string{ + "id": "bar0", + }, + }, + }, + "aws_instance.bar.1": &ResourceState{ + Type: "aws_instance", + Dependencies: []string{"aws_instance.foo.*"}, + Primary: &InstanceState{ + ID: "bar1", + Attributes: map[string]string{ + "id": "bar1", + }, + }, + }, + "aws_instance.baz.0": &ResourceState{ + Type: "aws_instance", + Dependencies: []string{"aws_instance.bar.*"}, + Primary: &InstanceState{ + ID: "baz0", + Attributes: map[string]string{ + "id": "baz0", + }, + }, + }, + "aws_instance.baz.1": &ResourceState{ + Type: "aws_instance", + Dependencies: []string{"aws_instance.bar.*"}, + Primary: &InstanceState{ + ID: "baz1", + Attributes: map[string]string{ + "id": "baz1", + }, + }, + }, + }, + }, + }, + } + ctx := testContext2(t, &ContextOpts{ + Module: m, + Providers: map[string]ResourceProviderFactory{ + "aws": testProviderFuncFixed(p), + }, + State: s, + }) + + w, e := ctx.Validate() + if len(w) > 0 { + t.Fatalf("warnings generated on validate: %#v", w) + } + if len(e) > 0 { + t.Fatalf("errors generated on validate: %#v", e) + } + + _, err := ctx.Refresh() + if err != nil { + t.Fatalf("refresh err: %s", err) + } + + plan, err := ctx.Plan() + if err != nil { + t.Fatalf("plan err: %s", err) + } + + actual := strings.TrimSpace(plan.String()) + expected := strings.TrimSpace(` +DIFF: + + + +STATE: + +aws_instance.bar.0: + ID = bar0 + + Dependencies: + aws_instance.foo.* +aws_instance.bar.1: + ID = bar1 + + Dependencies: + aws_instance.foo.* +aws_instance.baz.0: + ID = baz0 + + Dependencies: + aws_instance.bar.* +aws_instance.baz.1: + ID = baz1 + + Dependencies: + aws_instance.bar.* +aws_instance.foo.0: + ID = foo0 +aws_instance.foo.1: + ID = foo1 +`) + if actual != expected { + t.Fatalf("bad:\n%s\n\nexpected\n\n%s", actual, expected) + } +} diff --git a/terraform/eval_provider.go b/terraform/eval_provider.go index 61efcc235..092fd18d8 100644 --- a/terraform/eval_provider.go +++ b/terraform/eval_provider.go @@ -30,6 +30,11 @@ func (n *EvalBuildProviderConfig) Eval(ctx EvalContext) (interface{}, error) { // If we have a configuration set, then merge that in if input := ctx.ProviderInput(n.Provider); input != nil { + // "input" is a map of the subset of config values that were known + // during the input walk, set by EvalInputProvider. Note that + // in particular it does *not* include attributes that had + // computed values at input time; those appear *only* in + // "cfg" here. rc, err := config.NewRawConfig(input) if err != nil { return nil, err @@ -136,7 +141,21 @@ func (n *EvalInputProvider) Eval(ctx EvalContext) (interface{}, error) { // Set the input that we received so that child modules don't attempt // to ask for input again. if config != nil && len(config.Config) > 0 { - ctx.SetProviderInput(n.Name, config.Config) + // This repository of provider input results on the context doesn't + // retain config.ComputedKeys, so we need to filter those out here + // in order that later users of this data won't try to use the unknown + // value placeholder as if it were a literal value. This map is just + // of known values we've been able to complete so far; dynamic stuff + // will be merged in by EvalBuildProviderConfig on subsequent + // (post-input) walks. + confMap := config.Config + if config.ComputedKeys != nil { + for _, key := range config.ComputedKeys { + delete(confMap, key) + } + } + + ctx.SetProviderInput(n.Name, confMap) } else { ctx.SetProviderInput(n.Name, map[string]interface{}{}) } diff --git a/terraform/eval_provider_test.go b/terraform/eval_provider_test.go index 5719b62c5..40af542e2 100644 --- a/terraform/eval_provider_test.go +++ b/terraform/eval_provider_test.go @@ -3,6 +3,8 @@ package terraform import ( "reflect" "testing" + + "github.com/hashicorp/terraform/config" ) func TestEvalBuildProviderConfig_impl(t *testing.T) { @@ -10,7 +12,11 @@ func TestEvalBuildProviderConfig_impl(t *testing.T) { } func TestEvalBuildProviderConfig(t *testing.T) { - config := testResourceConfig(t, map[string]interface{}{}) + config := testResourceConfig(t, map[string]interface{}{ + "set_in_config": "config", + "set_in_config_and_parent": "config", + "computed_in_config": "config", + }) provider := "foo" n := &EvalBuildProviderConfig{ @@ -21,22 +27,33 @@ func TestEvalBuildProviderConfig(t *testing.T) { ctx := &MockEvalContext{ ParentProviderConfigConfig: testResourceConfig(t, map[string]interface{}{ - "foo": "bar", + "inherited_from_parent": "parent", + "set_in_config_and_parent": "parent", }), ProviderInputConfig: map[string]interface{}{ - "bar": "baz", + "set_in_config": "input", + "set_by_input": "input", }, } if _, err := n.Eval(ctx); err != nil { t.Fatalf("err: %s", err) } + // This is a merger of the following, with later items taking precedence: + // - "config" (the config as written in the current module, with all + // interpolation expressions resolved) + // - ProviderInputConfig (mock of config produced by the input walk, after + // prompting the user interactively for values unspecified in config) + // - ParentProviderConfigConfig (mock of config inherited from a parent module) expected := map[string]interface{}{ - "foo": "bar", - "bar": "baz", + "set_in_config": "input", // in practice, input map contains identical literals from config + "set_in_config_and_parent": "parent", + "inherited_from_parent": "parent", + "computed_in_config": "config", + "set_by_input": "input", } if !reflect.DeepEqual(config.Raw, expected) { - t.Fatalf("bad: %#v", config.Raw) + t.Fatalf("incorrect merged config %#v; want %#v", config.Raw, expected) } } @@ -151,3 +168,66 @@ func TestEvalGetProvider(t *testing.T) { t.Fatalf("bad: %#v", ctx.ProviderName) } } + +func TestEvalInputProvider(t *testing.T) { + var provider ResourceProvider = &MockResourceProvider{ + InputFn: func(ui UIInput, c *ResourceConfig) (*ResourceConfig, error) { + if c.Config["mock_config"] != "mock" { + t.Fatalf("original config not passed to provider.Input") + } + + rawConfig, err := config.NewRawConfig(map[string]interface{}{ + "set_in_config": "input", + "set_by_input": "input", + "computed": "fake_computed", + }) + if err != nil { + return nil, err + } + config := NewResourceConfig(rawConfig) + config.ComputedKeys = []string{"computed"} // fake computed key + + return config, nil + }, + } + ctx := &MockEvalContext{ProviderProvider: provider} + rawConfig, err := config.NewRawConfig(map[string]interface{}{ + "mock_config": "mock", + }) + if err != nil { + t.Fatalf("NewRawConfig failed: %s", err) + } + config := NewResourceConfig(rawConfig) + + n := &EvalInputProvider{ + Name: "mock", + Provider: &provider, + Config: &config, + } + + result, err := n.Eval(ctx) + if err != nil { + t.Fatalf("Eval failed: %s", err) + } + if result != nil { + t.Fatalf("Eval returned non-nil result %#v", result) + } + + if !ctx.SetProviderInputCalled { + t.Fatalf("ctx.SetProviderInput wasn't called") + } + + if got, want := ctx.SetProviderInputName, "mock"; got != want { + t.Errorf("wrong provider name %q; want %q", got, want) + } + + inputCfg := ctx.SetProviderInputConfig + want := map[string]interface{}{ + "set_in_config": "input", + "set_by_input": "input", + // "computed" is omitted because it value isn't known at input time + } + if !reflect.DeepEqual(inputCfg, want) { + t.Errorf("got incorrect input config %#v; want %#v", inputCfg, want) + } +} diff --git a/terraform/eval_validate.go b/terraform/eval_validate.go index a2c122d6a..478aa6400 100644 --- a/terraform/eval_validate.go +++ b/terraform/eval_validate.go @@ -4,6 +4,7 @@ import ( "fmt" "github.com/hashicorp/terraform/config" + "github.com/mitchellh/mapstructure" ) // EvalValidateError is the error structure returned if there were @@ -85,12 +86,31 @@ func (n *EvalValidateProvider) Eval(ctx EvalContext) (interface{}, error) { type EvalValidateProvisioner struct { Provisioner *ResourceProvisioner Config **ResourceConfig + ConnConfig **ResourceConfig } func (n *EvalValidateProvisioner) Eval(ctx EvalContext) (interface{}, error) { provisioner := *n.Provisioner config := *n.Config - warns, errs := provisioner.Validate(config) + var warns []string + var errs []error + + { + // Validate the provisioner's own config first + w, e := provisioner.Validate(config) + warns = append(warns, w...) + errs = append(errs, e...) + } + + { + // Now validate the connection config, which might either be from + // the provisioner block itself or inherited from the resource's + // shared connection info. + w, e := n.validateConnConfig(*n.ConnConfig) + warns = append(warns, w...) + errs = append(errs, e...) + } + if len(warns) == 0 && len(errs) == 0 { return nil, nil } @@ -101,6 +121,64 @@ func (n *EvalValidateProvisioner) Eval(ctx EvalContext) (interface{}, error) { } } +func (n *EvalValidateProvisioner) validateConnConfig(connConfig *ResourceConfig) (warns []string, errs []error) { + // We can't comprehensively validate the connection config since its + // final structure is decided by the communicator and we can't instantiate + // that until we have a complete instance state. However, we *can* catch + // configuration keys that are not valid for *any* communicator, catching + // typos early rather than waiting until we actually try to run one of + // the resource's provisioners. + + type connConfigSuperset struct { + // All attribute types are interface{} here because at this point we + // may still have unresolved interpolation expressions, which will + // appear as strings regardless of the final goal type. + + Type interface{} `mapstructure:"type"` + User interface{} `mapstructure:"user"` + Password interface{} `mapstructure:"password"` + Host interface{} `mapstructure:"host"` + Port interface{} `mapstructure:"port"` + Timeout interface{} `mapstructure:"timeout"` + ScriptPath interface{} `mapstructure:"script_path"` + + // For type=ssh only (enforced in ssh communicator) + PrivateKey interface{} `mapstructure:"private_key"` + Agent interface{} `mapstructure:"agent"` + BastionHost interface{} `mapstructure:"bastion_host"` + BastionPort interface{} `mapstructure:"bastion_port"` + BastionUser interface{} `mapstructure:"bastion_user"` + BastionPassword interface{} `mapstructure:"bastion_password"` + BastionPrivateKey interface{} `mapstructure:"bastion_private_key"` + + // For type=winrm only (enforced in winrm communicator) + HTTPS interface{} `mapstructure:"https"` + Insecure interface{} `mapstructure:"insecure"` + CACert interface{} `mapstructure:"cacert"` + } + + var metadata mapstructure.Metadata + decoder, err := mapstructure.NewDecoder(&mapstructure.DecoderConfig{ + Metadata: &metadata, + Result: &connConfigSuperset{}, // result is disregarded; we only care about unused keys + }) + if err != nil { + // should never happen + errs = append(errs, err) + return + } + + if err := decoder.Decode(connConfig.Config); err != nil { + errs = append(errs, err) + return + } + + for _, attrName := range metadata.Unused { + errs = append(errs, fmt.Errorf("unknown 'connection' argument %q", attrName)) + } + return +} + // EvalValidateResource is an EvalNode implementation that validates // the configuration of a resource. type EvalValidateResource struct { diff --git a/terraform/eval_validate_test.go b/terraform/eval_validate_test.go index ac20f617c..0bde2a870 100644 --- a/terraform/eval_validate_test.go +++ b/terraform/eval_validate_test.go @@ -178,3 +178,117 @@ func TestEvalValidateResource_ignoreWarnings(t *testing.T) { t.Fatalf("Expected no error, got: %s", err) } } + +func TestEvalValidateProvisioner_valid(t *testing.T) { + mp := &MockResourceProvisioner{} + var p ResourceProvisioner = mp + ctx := &MockEvalContext{} + + cfg := &ResourceConfig{} + connInfo, err := config.NewRawConfig(map[string]interface{}{}) + if err != nil { + t.Fatalf("failed to make connInfo: %s", err) + } + connConfig := NewResourceConfig(connInfo) + + node := &EvalValidateProvisioner{ + Provisioner: &p, + Config: &cfg, + ConnConfig: &connConfig, + } + + result, err := node.Eval(ctx) + if err != nil { + t.Fatalf("node.Eval failed: %s", err) + } + if result != nil { + t.Errorf("node.Eval returned non-nil result") + } + + if !mp.ValidateCalled { + t.Fatalf("p.Config not called") + } + if mp.ValidateConfig != cfg { + t.Errorf("p.Config called with wrong config") + } +} + +func TestEvalValidateProvisioner_warning(t *testing.T) { + mp := &MockResourceProvisioner{} + var p ResourceProvisioner = mp + ctx := &MockEvalContext{} + + cfg := &ResourceConfig{} + connInfo, err := config.NewRawConfig(map[string]interface{}{}) + if err != nil { + t.Fatalf("failed to make connInfo: %s", err) + } + connConfig := NewResourceConfig(connInfo) + + node := &EvalValidateProvisioner{ + Provisioner: &p, + Config: &cfg, + ConnConfig: &connConfig, + } + + mp.ValidateReturnWarns = []string{"foo is deprecated"} + + _, err = node.Eval(ctx) + if err == nil { + t.Fatalf("node.Eval succeeded; want error") + } + + valErr, ok := err.(*EvalValidateError) + if !ok { + t.Fatalf("node.Eval error is %#v; want *EvalValidateError", valErr) + } + + warns := valErr.Warnings + if warns == nil || len(warns) != 1 { + t.Fatalf("wrong number of warnings in %#v; want one warning", warns) + } + if warns[0] != mp.ValidateReturnWarns[0] { + t.Fatalf("wrong warning %q; want %q", warns[0], mp.ValidateReturnWarns[0]) + } +} + +func TestEvalValidateProvisioner_connectionInvalid(t *testing.T) { + var p ResourceProvisioner = &MockResourceProvisioner{} + ctx := &MockEvalContext{} + + cfg := &ResourceConfig{} + connInfo, err := config.NewRawConfig(map[string]interface{}{ + "bananananananana": "foo", + "bazaz": "bar", + }) + if err != nil { + t.Fatalf("failed to make connInfo: %s", err) + } + connConfig := NewResourceConfig(connInfo) + + node := &EvalValidateProvisioner{ + Provisioner: &p, + Config: &cfg, + ConnConfig: &connConfig, + } + + _, err = node.Eval(ctx) + if err == nil { + t.Fatalf("node.Eval succeeded; want error") + } + + valErr, ok := err.(*EvalValidateError) + if !ok { + t.Fatalf("node.Eval error is %#v; want *EvalValidateError", valErr) + } + + errs := valErr.Errors + if errs == nil || len(errs) != 2 { + t.Fatalf("wrong number of errors in %#v; want two errors", errs) + } + + errStr := errs[0].Error() + if !(strings.Contains(errStr, "bananananananana") || strings.Contains(errStr, "bazaz")) { + t.Fatalf("wrong first error %q; want something about our invalid connInfo keys", errStr) + } +} diff --git a/terraform/eval_variable.go b/terraform/eval_variable.go index 47bd2ea2b..e39a33c2a 100644 --- a/terraform/eval_variable.go +++ b/terraform/eval_variable.go @@ -114,7 +114,6 @@ type EvalVariableBlock struct { VariableValues map[string]interface{} } -// TODO: test func (n *EvalVariableBlock) Eval(ctx EvalContext) (interface{}, error) { // Clear out the existing mapping for k, _ := range n.VariableValues { @@ -124,22 +123,27 @@ func (n *EvalVariableBlock) Eval(ctx EvalContext) (interface{}, error) { // Get our configuration rc := *n.Config for k, v := range rc.Config { - var vString string - if err := hilmapstructure.WeakDecode(v, &vString); err == nil { - n.VariableValues[k] = vString - continue - } + vKind := reflect.ValueOf(v).Type().Kind() - var vMap map[string]interface{} - if err := hilmapstructure.WeakDecode(v, &vMap); err == nil { - n.VariableValues[k] = vMap - continue - } - - var vSlice []interface{} - if err := hilmapstructure.WeakDecode(v, &vSlice); err == nil { - n.VariableValues[k] = vSlice - continue + switch vKind { + case reflect.Slice: + var vSlice []interface{} + if err := hilmapstructure.WeakDecode(v, &vSlice); err == nil { + n.VariableValues[k] = vSlice + continue + } + case reflect.Map: + var vMap map[string]interface{} + if err := hilmapstructure.WeakDecode(v, &vMap); err == nil { + n.VariableValues[k] = vMap + continue + } + default: + var vString string + if err := hilmapstructure.WeakDecode(v, &vString); err == nil { + n.VariableValues[k] = vString + continue + } } return nil, fmt.Errorf("Variable value for %s is not a string, list or map type", k) @@ -174,9 +178,15 @@ func (n *EvalVariableBlock) setUnknownVariableValueForPath(path string) error { // Otherwise find the correct point in the tree and then set to unknown var current interface{} = n.VariableValues[pathComponents[0]] for i := 1; i < len(pathComponents); i++ { - switch current.(type) { - case []interface{}, []map[string]interface{}: - tCurrent := current.([]interface{}) + switch tCurrent := current.(type) { + case []interface{}: + index, err := strconv.Atoi(pathComponents[i]) + if err != nil { + return fmt.Errorf("Cannot convert %s to slice index in path %s", + pathComponents[i], path) + } + current = tCurrent[index] + case []map[string]interface{}: index, err := strconv.Atoi(pathComponents[i]) if err != nil { return fmt.Errorf("Cannot convert %s to slice index in path %s", @@ -184,7 +194,6 @@ func (n *EvalVariableBlock) setUnknownVariableValueForPath(path string) error { } current = tCurrent[index] case map[string]interface{}: - tCurrent := current.(map[string]interface{}) if val, hasVal := tCurrent[pathComponents[i]]; hasVal { current = val continue diff --git a/terraform/eval_variable_test.go b/terraform/eval_variable_test.go index 05fc2b850..eb7ff92a3 100644 --- a/terraform/eval_variable_test.go +++ b/terraform/eval_variable_test.go @@ -3,6 +3,8 @@ package terraform import ( "reflect" "testing" + + "github.com/hashicorp/terraform/config" ) func TestCoerceMapVariable(t *testing.T) { @@ -140,3 +142,78 @@ func TestCoerceMapVariable(t *testing.T) { } } } + +func TestEvalVariableBlock(t *testing.T) { + rc, err := config.NewRawConfig(map[string]interface{}{ + "known": "foo", + "known_list": []interface{}{"foo"}, + "known_map": map[string]interface{}{ + "foo": "foo", + }, + "known_list_of_maps": []map[string]interface{}{ + map[string]interface{}{ + "foo": "foo", + }, + }, + "computed_map": map[string]interface{}{}, + "computed_list_of_maps": []map[string]interface{}{ + map[string]interface{}{}, + }, + // No computed_list right now, because that isn't currently supported: + // EvalVariableBlock assumes the final step of the path will always + // be a map. + }) + if err != nil { + t.Fatalf("config.NewRawConfig failed: %s", err) + } + + cfg := NewResourceConfig(rc) + cfg.ComputedKeys = []string{ + "computed", + "computed_map.foo", + "computed_list_of_maps.0.foo", + } + + n := &EvalVariableBlock{ + VariableValues: map[string]interface{}{ + // Should be cleared out on Eval + "should_be_deleted": true, + }, + Config: &cfg, + } + + ctx := &MockEvalContext{} + val, err := n.Eval(ctx) + if err != nil { + t.Fatalf("n.Eval failed: %s", err) + } + if val != nil { + t.Fatalf("n.Eval returned non-nil result: %#v", val) + } + + got := n.VariableValues + want := map[string]interface{}{ + "known": "foo", + "known_list": []interface{}{"foo"}, + "known_map": map[string]interface{}{ + "foo": "foo", + }, + "known_list_of_maps": []interface{}{ + map[string]interface{}{ + "foo": "foo", + }, + }, + "computed": config.UnknownVariableValue, + "computed_map": map[string]interface{}{ + "foo": config.UnknownVariableValue, + }, + "computed_list_of_maps": []interface{}{ + map[string]interface{}{ + "foo": config.UnknownVariableValue, + }, + }, + } + if !reflect.DeepEqual(got, want) { + t.Errorf("Incorrect variables\ngot: %#v\nwant: %#v", got, want) + } +} diff --git a/terraform/graph_builder_apply.go b/terraform/graph_builder_apply.go index 61242586a..38a90f277 100644 --- a/terraform/graph_builder_apply.go +++ b/terraform/graph_builder_apply.go @@ -123,6 +123,10 @@ func (b *ApplyGraphBuilder) Steps() []GraphTransformer { // Target &TargetsTransformer{Targets: b.Targets}, + // Close opened plugin connections + &CloseProviderTransformer{}, + &CloseProvisionerTransformer{}, + // Single root &RootTransformer{}, } diff --git a/terraform/graph_builder_apply_test.go b/terraform/graph_builder_apply_test.go index b62833103..a1c02dfa8 100644 --- a/terraform/graph_builder_apply_test.go +++ b/terraform/graph_builder_apply_test.go @@ -510,6 +510,18 @@ module.child.provider.aws provider.aws module.child.provisioner.exec provider.aws +provider.aws (close) + aws_instance.create + aws_instance.other + module.child.aws_instance.create + module.child.aws_instance.other + provider.aws +provisioner.exec (close) + module.child.aws_instance.create +root + meta.count-boundary (count boundary fixup) + provider.aws (close) + provisioner.exec (close) ` const testApplyGraphBuilderDoubleCBDStr = ` @@ -533,6 +545,15 @@ meta.count-boundary (count boundary fixup) aws_instance.B (destroy) provider.aws provider.aws +provider.aws (close) + aws_instance.A + aws_instance.A (destroy) + aws_instance.B + aws_instance.B (destroy) + provider.aws +root + meta.count-boundary (count boundary fixup) + provider.aws (close) ` const testApplyGraphBuilderDestroyCountStr = ` @@ -546,4 +567,11 @@ meta.count-boundary (count boundary fixup) aws_instance.B provider.aws provider.aws +provider.aws (close) + aws_instance.A[1] (destroy) + aws_instance.B + provider.aws +root + meta.count-boundary (count boundary fixup) + provider.aws (close) ` diff --git a/terraform/graph_builder_import.go b/terraform/graph_builder_import.go index 7fa76ded7..7070c59e4 100644 --- a/terraform/graph_builder_import.go +++ b/terraform/graph_builder_import.go @@ -62,6 +62,9 @@ func (b *ImportGraphBuilder) Steps() []GraphTransformer { // This validates that the providers only depend on variables &ImportProviderValidateTransformer{}, + // Close opened plugin connections + &CloseProviderTransformer{}, + // Single root &RootTransformer{}, diff --git a/terraform/graph_builder_plan.go b/terraform/graph_builder_plan.go index 275cb32f3..a6a3a90d4 100644 --- a/terraform/graph_builder_plan.go +++ b/terraform/graph_builder_plan.go @@ -113,9 +113,16 @@ func (b *PlanGraphBuilder) Steps() []GraphTransformer { // have to connect again later for providers and so on. &ReferenceTransformer{}, + // Add the node to fix the state count boundaries + &CountBoundaryTransformer{}, + // Target &TargetsTransformer{Targets: b.Targets}, + // Close opened plugin connections + &CloseProviderTransformer{}, + &CloseProvisionerTransformer{}, + // Single root &RootTransformer{}, } diff --git a/terraform/graph_builder_plan_test.go b/terraform/graph_builder_plan_test.go index 02366fe4f..25578ebaf 100644 --- a/terraform/graph_builder_plan_test.go +++ b/terraform/graph_builder_plan_test.go @@ -29,7 +29,7 @@ func TestPlanGraphBuilder(t *testing.T) { actual := strings.TrimSpace(g.String()) expected := strings.TrimSpace(testPlanGraphBuilderStr) if actual != expected { - t.Fatalf("bad: %s", actual) + t.Fatalf("expected:\n%s\n\ngot:\n%s", expected, actual) } } @@ -61,10 +61,30 @@ aws_load_balancer.weblb provider.aws aws_security_group.firewall provider.aws +meta.count-boundary (count boundary fixup) + aws_instance.web + aws_load_balancer.weblb + aws_security_group.firewall + openstack_floating_ip.random + provider.aws + provider.openstack + var.foo openstack_floating_ip.random provider.openstack provider.aws openstack_floating_ip.random +provider.aws (close) + aws_instance.web + aws_load_balancer.weblb + aws_security_group.firewall + provider.aws provider.openstack +provider.openstack (close) + openstack_floating_ip.random + provider.openstack +root + meta.count-boundary (count boundary fixup) + provider.aws (close) + provider.openstack (close) var.foo ` diff --git a/terraform/graph_builder_refresh.go b/terraform/graph_builder_refresh.go index 8fed21d61..0634f9698 100644 --- a/terraform/graph_builder_refresh.go +++ b/terraform/graph_builder_refresh.go @@ -1,6 +1,8 @@ package terraform import ( + "log" + "github.com/hashicorp/terraform/config" "github.com/hashicorp/terraform/config/module" "github.com/hashicorp/terraform/dag" @@ -56,8 +58,16 @@ func (b *RefreshGraphBuilder) Steps() []GraphTransformer { } } - concreteResource := func(a *NodeAbstractResource) dag.Vertex { - return &NodeRefreshableResource{ + concreteManagedResource := func(a *NodeAbstractResource) dag.Vertex { + return &NodeRefreshableManagedResource{ + NodeAbstractCountResource: &NodeAbstractCountResource{ + NodeAbstractResource: a, + }, + } + } + + concreteManagedResourceInstance := func(a *NodeAbstractResource) dag.Vertex { + return &NodeRefreshableManagedResourceInstance{ NodeAbstractResource: a, } } @@ -71,13 +81,25 @@ func (b *RefreshGraphBuilder) Steps() []GraphTransformer { } steps := []GraphTransformer{ - // Creates all the resources represented in the state - &StateTransformer{ - Concrete: concreteResource, - State: b.State, - }, + // Creates all the managed resources that aren't in the state, but only if + // we have a state already. No resources in state means there's not + // anything to refresh. + func() GraphTransformer { + if b.State.HasResources() { + return &ConfigTransformer{ + Concrete: concreteManagedResource, + Module: b.Module, + Unique: true, + ModeFilter: true, + Mode: config.ManagedResourceMode, + } + } + log.Println("[TRACE] No managed resources in state during refresh, skipping managed resource transformer") + return nil + }(), - // Creates all the data resources that aren't in the state + // Creates all the data resources that aren't in the state. This will also + // add any orphans from scaling in as destroy nodes. &ConfigTransformer{ Concrete: concreteDataResource, Module: b.Module, @@ -86,6 +108,15 @@ func (b *RefreshGraphBuilder) Steps() []GraphTransformer { Mode: config.DataResourceMode, }, + // Add any fully-orphaned resources from config (ones that have been + // removed completely, not ones that are just orphaned due to a scaled-in + // count. + &OrphanResourceTransformer{ + Concrete: concreteManagedResourceInstance, + State: b.State, + Module: b.Module, + }, + // Attach the state &AttachStateTransformer{State: b.State}, @@ -115,6 +146,9 @@ func (b *RefreshGraphBuilder) Steps() []GraphTransformer { // Target &TargetsTransformer{Targets: b.Targets}, + // Close opened plugin connections + &CloseProviderTransformer{}, + // Single root &RootTransformer{}, } diff --git a/terraform/graph_builder_refresh_test.go b/terraform/graph_builder_refresh_test.go new file mode 100644 index 000000000..e4383ab4e --- /dev/null +++ b/terraform/graph_builder_refresh_test.go @@ -0,0 +1,96 @@ +package terraform + +import "testing" + +func TestRefreshGraphBuilder_configOrphans(t *testing.T) { + + m := testModule(t, "refresh-config-orphan") + + state := &State{ + Modules: []*ModuleState{ + &ModuleState{ + Path: rootModulePath, + Resources: map[string]*ResourceState{ + "aws_instance.foo.0": &ResourceState{ + Type: "aws_instance", + Deposed: []*InstanceState{ + &InstanceState{ + ID: "foo", + }, + }, + }, + "aws_instance.foo.1": &ResourceState{ + Type: "aws_instance", + Deposed: []*InstanceState{ + &InstanceState{ + ID: "bar", + }, + }, + }, + "aws_instance.foo.2": &ResourceState{ + Type: "aws_instance", + Deposed: []*InstanceState{ + &InstanceState{ + ID: "baz", + }, + }, + }, + "data.aws_instance.foo.0": &ResourceState{ + Type: "aws_instance", + Deposed: []*InstanceState{ + &InstanceState{ + ID: "foo", + }, + }, + }, + "data.aws_instance.foo.1": &ResourceState{ + Type: "aws_instance", + Deposed: []*InstanceState{ + &InstanceState{ + ID: "bar", + }, + }, + }, + "data.aws_instance.foo.2": &ResourceState{ + Type: "aws_instance", + Deposed: []*InstanceState{ + &InstanceState{ + ID: "baz", + }, + }, + }, + }, + }, + }, + } + + b := &RefreshGraphBuilder{ + Module: m, + State: state, + Providers: []string{"aws"}, + } + g, err := b.Build(rootModulePath) + if err != nil { + t.Fatalf("Error building graph: %s", err) + } + + actual := g.StringWithNodeTypes() + expected := `aws_instance.foo - *terraform.NodeRefreshableManagedResource + provider.aws - *terraform.NodeApplyableProvider +data.aws_instance.foo[0] - *terraform.NodeRefreshableManagedResourceInstance + provider.aws - *terraform.NodeApplyableProvider +data.aws_instance.foo[1] - *terraform.NodeRefreshableManagedResourceInstance + provider.aws - *terraform.NodeApplyableProvider +data.aws_instance.foo[2] - *terraform.NodeRefreshableManagedResourceInstance + provider.aws - *terraform.NodeApplyableProvider +provider.aws - *terraform.NodeApplyableProvider +provider.aws (close) - *terraform.graphNodeCloseProvider + aws_instance.foo - *terraform.NodeRefreshableManagedResource + data.aws_instance.foo[0] - *terraform.NodeRefreshableManagedResourceInstance + data.aws_instance.foo[1] - *terraform.NodeRefreshableManagedResourceInstance + data.aws_instance.foo[2] - *terraform.NodeRefreshableManagedResourceInstance +` + if expected != actual { + t.Fatalf("Expected:\n%s\nGot:\n%s", expected, actual) + } +} diff --git a/terraform/graphtype_string.go b/terraform/graphtype_string.go index 88ecad4f6..e97b4855a 100644 --- a/terraform/graphtype_string.go +++ b/terraform/graphtype_string.go @@ -1,4 +1,4 @@ -// Code generated by "stringer -type=GraphType context_graph_type.go"; DO NOT EDIT +// Code generated by "stringer -type=GraphType context_graph_type.go"; DO NOT EDIT. package terraform diff --git a/terraform/instancetype_string.go b/terraform/instancetype_string.go index f65414b34..f69267cd5 100644 --- a/terraform/instancetype_string.go +++ b/terraform/instancetype_string.go @@ -1,4 +1,4 @@ -// Code generated by "stringer -type=InstanceType instancetype.go"; DO NOT EDIT +// Code generated by "stringer -type=InstanceType instancetype.go"; DO NOT EDIT. package terraform diff --git a/terraform/interpolate.go b/terraform/interpolate.go index 0c5acaa35..0def295fa 100644 --- a/terraform/interpolate.go +++ b/terraform/interpolate.go @@ -306,10 +306,10 @@ func (i *Interpolater) valueSimpleVar( // relied on this for their template_file data sources. We should // remove this at some point but there isn't any rush. return fmt.Errorf( - "invalid variable syntax: %q. If this is part of inline `template` parameter\n"+ + "invalid variable syntax: %q. Did you mean 'var.%s'? If this is part of inline `template` parameter\n"+ "then you must escape the interpolation with two dollar signs. For\n"+ "example: ${a} becomes $${a}.", - n) + n, n) } func (i *Interpolater) valueTerraformVar( @@ -594,10 +594,6 @@ func (i *Interpolater) computeResourceMultiVariable( } if singleAttr, ok := r.Primary.Attributes[v.Field]; ok { - if singleAttr == config.UnknownVariableValue { - return &unknownVariable, nil - } - values = append(values, singleAttr) continue } @@ -613,10 +609,6 @@ func (i *Interpolater) computeResourceMultiVariable( return nil, err } - if multiAttr == unknownVariable { - return &unknownVariable, nil - } - values = append(values, multiAttr) } @@ -739,6 +731,19 @@ func (i *Interpolater) resourceCountMax( return count, nil } + // If we have no module state in the apply walk, that suggests we've hit + // a rather awkward edge-case: the resource this variable refers to + // has count = 0 and is the only resource processed so far on this walk, + // and so we've ended up not creating any resource states yet. We don't + // create a module state until the first resource is written into it, + // so the module state doesn't exist when we get here. + // + // In this case we act as we would if we had been passed a module + // with an empty resource state map. + if ms == nil { + return 0, nil + } + // We need to determine the list of resource keys to get values from. // This needs to be sorted so the order is deterministic. We used to // use "cr.Count()" but that doesn't work if the count is interpolated diff --git a/terraform/interpolate_test.go b/terraform/interpolate_test.go index 6f1d2c344..46c0cbf8c 100644 --- a/terraform/interpolate_test.go +++ b/terraform/interpolate_test.go @@ -359,8 +359,109 @@ func TestInterpolater_resourceVariableMulti(t *testing.T) { } testInterpolate(t, i, scope, "aws_instance.web.*.foo", ast.Variable{ - Value: config.UnknownVariableValue, - Type: ast.TypeUnknown, + Type: ast.TypeList, + Value: []ast.Variable{ + { + Type: ast.TypeUnknown, + Value: config.UnknownVariableValue, + }, + }, + }) +} + +func TestInterpolater_resourceVariableMultiPartialUnknown(t *testing.T) { + lock := new(sync.RWMutex) + state := &State{ + Modules: []*ModuleState{ + &ModuleState{ + Path: rootModulePath, + Resources: map[string]*ResourceState{ + "aws_instance.web.0": &ResourceState{ + Type: "aws_instance", + Primary: &InstanceState{ + ID: "bar", + Attributes: map[string]string{ + "foo": "1", + }, + }, + }, + "aws_instance.web.1": &ResourceState{ + Type: "aws_instance", + Primary: &InstanceState{ + ID: "bar", + Attributes: map[string]string{ + "foo": config.UnknownVariableValue, + }, + }, + }, + "aws_instance.web.2": &ResourceState{ + Type: "aws_instance", + Primary: &InstanceState{ + ID: "bar", + Attributes: map[string]string{ + "foo": "2", + }, + }, + }, + }, + }, + }, + } + + i := &Interpolater{ + Module: testModule(t, "interpolate-resource-variable-multi"), + State: state, + StateLock: lock, + } + + scope := &InterpolationScope{ + Path: rootModulePath, + } + + testInterpolate(t, i, scope, "aws_instance.web.*.foo", ast.Variable{ + Type: ast.TypeList, + Value: []ast.Variable{ + { + Type: ast.TypeString, + Value: "1", + }, + { + Type: ast.TypeUnknown, + Value: config.UnknownVariableValue, + }, + { + Type: ast.TypeString, + Value: "2", + }, + }, + }) +} + +func TestInterpolater_resourceVariableMultiNoState(t *testing.T) { + // When evaluating a "splat" variable in a module that doesn't have + // any state yet, we should still be able to resolve to an empty + // list. + // See https://github.com/hashicorp/terraform/issues/14438 for an + // example of what we're testing for here. + lock := new(sync.RWMutex) + state := &State{ + Modules: []*ModuleState{}, + } + + i := &Interpolater{ + Module: testModule(t, "interpolate-resource-variable-multi"), + State: state, + StateLock: lock, + Operation: walkApply, + } + + scope := &InterpolationScope{ + Path: rootModulePath, + } + + testInterpolate(t, i, scope, "aws_instance.web.*.foo", ast.Variable{ + Type: ast.TypeList, + Value: []ast.Variable{}, }) } @@ -408,8 +509,13 @@ func TestInterpolater_resourceVariableMultiList(t *testing.T) { } testInterpolate(t, i, scope, "aws_instance.web.*.ip", ast.Variable{ - Value: config.UnknownVariableValue, - Type: ast.TypeUnknown, + Type: ast.TypeList, + Value: []ast.Variable{ + { + Type: ast.TypeUnknown, + Value: config.UnknownVariableValue, + }, + }, }) } diff --git a/terraform/node_data_refresh.go b/terraform/node_data_refresh.go index d504c892c..45129b3cb 100644 --- a/terraform/node_data_refresh.go +++ b/terraform/node_data_refresh.go @@ -33,6 +33,17 @@ func (n *NodeRefreshableDataResource) DynamicExpand(ctx EvalContext) (*Graph, er } } + // We also need a destroyable resource for orphans that are a result of a + // scaled-in count. + concreteResourceDestroyable := func(a *NodeAbstractResource) dag.Vertex { + // Add the config since we don't do that via transforms + a.Config = n.Config + + return &NodeDestroyableDataResource{ + NodeAbstractResource: a, + } + } + // Start creating the steps steps := []GraphTransformer{ // Expand the count. @@ -42,6 +53,15 @@ func (n *NodeRefreshableDataResource) DynamicExpand(ctx EvalContext) (*Graph, er Addr: n.ResourceAddr(), }, + // Add the count orphans. As these are orphaned refresh nodes, we add them + // directly as NodeDestroyableDataResource. + &OrphanResourceCountTransformer{ + Concrete: concreteResourceDestroyable, + Count: count, + Addr: n.ResourceAddr(), + State: state, + }, + // Attach the state &AttachStateTransformer{State: state}, diff --git a/terraform/node_data_refresh_test.go b/terraform/node_data_refresh_test.go new file mode 100644 index 000000000..6aa3af37a --- /dev/null +++ b/terraform/node_data_refresh_test.go @@ -0,0 +1,154 @@ +package terraform + +import ( + "sync" + "testing" +) + +func TestNodeRefreshableDataResourceDynamicExpand_scaleOut(t *testing.T) { + var stateLock sync.RWMutex + + addr, err := ParseResourceAddress("data.aws_instance.foo") + if err != nil { + t.Fatalf("bad: %s", err) + } + + m := testModule(t, "refresh-data-scale-inout") + + state := &State{ + Modules: []*ModuleState{ + &ModuleState{ + Path: rootModulePath, + Resources: map[string]*ResourceState{ + "data.aws_instance.foo.0": &ResourceState{ + Type: "aws_instance", + Deposed: []*InstanceState{ + &InstanceState{ + ID: "foo", + }, + }, + }, + "data.aws_instance.foo.1": &ResourceState{ + Type: "aws_instance", + Deposed: []*InstanceState{ + &InstanceState{ + ID: "bar", + }, + }, + }, + }, + }, + }, + } + + n := &NodeRefreshableDataResource{ + NodeAbstractCountResource: &NodeAbstractCountResource{ + NodeAbstractResource: &NodeAbstractResource{ + Addr: addr, + Config: m.Config().Resources[0], + }, + }, + } + + g, err := n.DynamicExpand(&MockEvalContext{ + PathPath: []string{"root"}, + StateState: state, + StateLock: &stateLock, + }) + + actual := g.StringWithNodeTypes() + expected := `data.aws_instance.foo[0] - *terraform.NodeRefreshableDataResourceInstance +data.aws_instance.foo[1] - *terraform.NodeRefreshableDataResourceInstance +data.aws_instance.foo[2] - *terraform.NodeRefreshableDataResourceInstance +root - terraform.graphNodeRoot + data.aws_instance.foo[0] - *terraform.NodeRefreshableDataResourceInstance + data.aws_instance.foo[1] - *terraform.NodeRefreshableDataResourceInstance + data.aws_instance.foo[2] - *terraform.NodeRefreshableDataResourceInstance +` + if expected != actual { + t.Fatalf("Expected:\n%s\nGot:\n%s", expected, actual) + } +} + +func TestNodeRefreshableDataResourceDynamicExpand_scaleIn(t *testing.T) { + var stateLock sync.RWMutex + + addr, err := ParseResourceAddress("data.aws_instance.foo") + if err != nil { + t.Fatalf("bad: %s", err) + } + + m := testModule(t, "refresh-data-scale-inout") + + state := &State{ + Modules: []*ModuleState{ + &ModuleState{ + Path: rootModulePath, + Resources: map[string]*ResourceState{ + "data.aws_instance.foo.0": &ResourceState{ + Type: "aws_instance", + Deposed: []*InstanceState{ + &InstanceState{ + ID: "foo", + }, + }, + }, + "data.aws_instance.foo.1": &ResourceState{ + Type: "aws_instance", + Deposed: []*InstanceState{ + &InstanceState{ + ID: "bar", + }, + }, + }, + "data.aws_instance.foo.2": &ResourceState{ + Type: "aws_instance", + Deposed: []*InstanceState{ + &InstanceState{ + ID: "baz", + }, + }, + }, + "data.aws_instance.foo.3": &ResourceState{ + Type: "aws_instance", + Deposed: []*InstanceState{ + &InstanceState{ + ID: "qux", + }, + }, + }, + }, + }, + }, + } + + n := &NodeRefreshableDataResource{ + NodeAbstractCountResource: &NodeAbstractCountResource{ + NodeAbstractResource: &NodeAbstractResource{ + Addr: addr, + Config: m.Config().Resources[0], + }, + }, + } + + g, err := n.DynamicExpand(&MockEvalContext{ + PathPath: []string{"root"}, + StateState: state, + StateLock: &stateLock, + }) + + actual := g.StringWithNodeTypes() + expected := `data.aws_instance.foo[0] - *terraform.NodeRefreshableDataResourceInstance +data.aws_instance.foo[1] - *terraform.NodeRefreshableDataResourceInstance +data.aws_instance.foo[2] - *terraform.NodeRefreshableDataResourceInstance +data.aws_instance.foo[3] - *terraform.NodeDestroyableDataResource +root - terraform.graphNodeRoot + data.aws_instance.foo[0] - *terraform.NodeRefreshableDataResourceInstance + data.aws_instance.foo[1] - *terraform.NodeRefreshableDataResourceInstance + data.aws_instance.foo[2] - *terraform.NodeRefreshableDataResourceInstance + data.aws_instance.foo[3] - *terraform.NodeDestroyableDataResource +` + if expected != actual { + t.Fatalf("Expected:\n%s\nGot:\n%s", expected, actual) + } +} diff --git a/terraform/node_output.go b/terraform/node_output.go index e28e6f02f..9017a63c4 100644 --- a/terraform/node_output.go +++ b/terraform/node_output.go @@ -5,6 +5,7 @@ import ( "strings" "github.com/hashicorp/terraform/config" + "github.com/hashicorp/terraform/dag" ) // NodeApplyableOutput represents an output that is "applyable": @@ -35,6 +36,14 @@ func (n *NodeApplyableOutput) RemoveIfNotTargeted() bool { return true } +// GraphNodeTargetDownstream +func (n *NodeApplyableOutput) TargetDownstream(targetedDeps, untargetedDeps *dag.Set) bool { + // If any of the direct dependencies of an output are targeted then + // the output must always be targeted as well, so its value will always + // be up-to-date at the completion of an apply walk. + return true +} + // GraphNodeReferenceable func (n *NodeApplyableOutput) ReferenceableName() []string { name := fmt.Sprintf("output.%s", n.Config.Name) diff --git a/terraform/node_resource_abstract.go b/terraform/node_resource_abstract.go index e4577e9db..50bb70792 100644 --- a/terraform/node_resource_abstract.go +++ b/terraform/node_resource_abstract.go @@ -102,7 +102,7 @@ func (n *NodeAbstractResource) References() []string { } } - return result + return uniqueStrings(result) } // If we have state, that is our next source diff --git a/terraform/node_resource_refresh.go b/terraform/node_resource_refresh.go index 3a44926ce..6ab9df7a2 100644 --- a/terraform/node_resource_refresh.go +++ b/terraform/node_resource_refresh.go @@ -4,21 +4,99 @@ import ( "fmt" "github.com/hashicorp/terraform/config" + "github.com/hashicorp/terraform/dag" ) -// NodeRefreshableResource represents a resource that is "applyable": +// NodeRefreshableManagedResource represents a resource that is expanabled into +// NodeRefreshableManagedResourceInstance. Resource count orphans are also added. +type NodeRefreshableManagedResource struct { + *NodeAbstractCountResource +} + +// GraphNodeDynamicExpandable +func (n *NodeRefreshableManagedResource) DynamicExpand(ctx EvalContext) (*Graph, error) { + // Grab the state which we read + state, lock := ctx.State() + lock.RLock() + defer lock.RUnlock() + + // Expand the resource count which must be available by now from EvalTree + count, err := n.Config.Count() + if err != nil { + return nil, err + } + + // The concrete resource factory we'll use + concreteResource := func(a *NodeAbstractResource) dag.Vertex { + // Add the config and state since we don't do that via transforms + a.Config = n.Config + + return &NodeRefreshableManagedResourceInstance{ + NodeAbstractResource: a, + } + } + + // Start creating the steps + steps := []GraphTransformer{ + // Expand the count. + &ResourceCountTransformer{ + Concrete: concreteResource, + Count: count, + Addr: n.ResourceAddr(), + }, + + // Switch up any node missing state to a plannable resource. This helps + // catch cases where data sources depend on the counts from this resource + // during a scale out. + &ResourceRefreshPlannableTransformer{ + State: state, + }, + + // Add the count orphans to make sure these resources are accounted for + // during a scale in. + &OrphanResourceCountTransformer{ + Concrete: concreteResource, + Count: count, + Addr: n.ResourceAddr(), + State: state, + }, + + // Attach the state + &AttachStateTransformer{State: state}, + + // Targeting + &TargetsTransformer{ParsedTargets: n.Targets}, + + // Connect references so ordering is correct + &ReferenceTransformer{}, + + // Make sure there is a single root + &RootTransformer{}, + } + + // Build the graph + b := &BasicGraphBuilder{ + Steps: steps, + Validate: true, + Name: "NodeRefreshableManagedResource", + } + + return b.Build(ctx.Path()) +} + +// NodeRefreshableManagedResourceInstance represents a resource that is "applyable": // it is ready to be applied and is represented by a diff. -type NodeRefreshableResource struct { +type NodeRefreshableManagedResourceInstance struct { *NodeAbstractResource } // GraphNodeDestroyer -func (n *NodeRefreshableResource) DestroyAddr() *ResourceAddress { +func (n *NodeRefreshableManagedResourceInstance) DestroyAddr() *ResourceAddress { return n.Addr } // GraphNodeEvalable -func (n *NodeRefreshableResource) EvalTree() EvalNode { +func (n *NodeRefreshableManagedResourceInstance) EvalTree() EvalNode { // Eval info is different depending on what kind of resource this is switch mode := n.Addr.Mode; mode { case config.ManagedResourceMode: @@ -44,7 +122,7 @@ func (n *NodeRefreshableResource) EvalTree() EvalNode { } } -func (n *NodeRefreshableResource) evalTreeManagedResource() EvalNode { +func (n *NodeRefreshableManagedResourceInstance) evalTreeManagedResource() EvalNode { addr := n.NodeAbstractResource.Addr // stateId is the ID to put into the state diff --git a/terraform/node_resource_refresh_test.go b/terraform/node_resource_refresh_test.go new file mode 100644 index 000000000..b2ac4d346 --- /dev/null +++ b/terraform/node_resource_refresh_test.go @@ -0,0 +1,154 @@ +package terraform + +import ( + "sync" + "testing" +) + +func TestNodeRefreshableManagedResourceDynamicExpand_scaleOut(t *testing.T) { + var stateLock sync.RWMutex + + addr, err := ParseResourceAddress("aws_instance.foo") + if err != nil { + t.Fatalf("bad: %s", err) + } + + m := testModule(t, "refresh-resource-scale-inout") + + state := &State{ + Modules: []*ModuleState{ + &ModuleState{ + Path: rootModulePath, + Resources: map[string]*ResourceState{ + "aws_instance.foo.0": &ResourceState{ + Type: "aws_instance", + Deposed: []*InstanceState{ + &InstanceState{ + ID: "foo", + }, + }, + }, + "aws_instance.foo.1": &ResourceState{ + Type: "aws_instance", + Deposed: []*InstanceState{ + &InstanceState{ + ID: "bar", + }, + }, + }, + }, + }, + }, + } + + n := &NodeRefreshableManagedResource{ + NodeAbstractCountResource: &NodeAbstractCountResource{ + NodeAbstractResource: &NodeAbstractResource{ + Addr: addr, + Config: m.Config().Resources[0], + }, + }, + } + + g, err := n.DynamicExpand(&MockEvalContext{ + PathPath: []string{"root"}, + StateState: state, + StateLock: &stateLock, + }) + + actual := g.StringWithNodeTypes() + expected := `aws_instance.foo[0] - *terraform.NodeRefreshableManagedResourceInstance +aws_instance.foo[1] - *terraform.NodeRefreshableManagedResourceInstance +aws_instance.foo[2] - *terraform.NodePlannableResourceInstance +root - terraform.graphNodeRoot + aws_instance.foo[0] - *terraform.NodeRefreshableManagedResourceInstance + aws_instance.foo[1] - *terraform.NodeRefreshableManagedResourceInstance + aws_instance.foo[2] - *terraform.NodePlannableResourceInstance +` + if expected != actual { + t.Fatalf("Expected:\n%s\nGot:\n%s", expected, actual) + } +} + +func TestNodeRefreshableManagedResourceDynamicExpand_scaleIn(t *testing.T) { + var stateLock sync.RWMutex + + addr, err := ParseResourceAddress("aws_instance.foo") + if err != nil { + t.Fatalf("bad: %s", err) + } + + m := testModule(t, "refresh-resource-scale-inout") + + state := &State{ + Modules: []*ModuleState{ + &ModuleState{ + Path: rootModulePath, + Resources: map[string]*ResourceState{ + "aws_instance.foo.0": &ResourceState{ + Type: "aws_instance", + Deposed: []*InstanceState{ + &InstanceState{ + ID: "foo", + }, + }, + }, + "aws_instance.foo.1": &ResourceState{ + Type: "aws_instance", + Deposed: []*InstanceState{ + &InstanceState{ + ID: "bar", + }, + }, + }, + "aws_instance.foo.2": &ResourceState{ + Type: "aws_instance", + Deposed: []*InstanceState{ + &InstanceState{ + ID: "baz", + }, + }, + }, + "aws_instance.foo.3": &ResourceState{ + Type: "aws_instance", + Deposed: []*InstanceState{ + &InstanceState{ + ID: "qux", + }, + }, + }, + }, + }, + }, + } + + n := &NodeRefreshableManagedResource{ + NodeAbstractCountResource: &NodeAbstractCountResource{ + NodeAbstractResource: &NodeAbstractResource{ + Addr: addr, + Config: m.Config().Resources[0], + }, + }, + } + + g, err := n.DynamicExpand(&MockEvalContext{ + PathPath: []string{"root"}, + StateState: state, + StateLock: &stateLock, + }) + + actual := g.StringWithNodeTypes() + expected := `aws_instance.foo[0] - *terraform.NodeRefreshableManagedResourceInstance +aws_instance.foo[1] - *terraform.NodeRefreshableManagedResourceInstance +aws_instance.foo[2] - *terraform.NodeRefreshableManagedResourceInstance +aws_instance.foo[3] - *terraform.NodeRefreshableManagedResourceInstance +root - terraform.graphNodeRoot + aws_instance.foo[0] - *terraform.NodeRefreshableManagedResourceInstance + aws_instance.foo[1] - *terraform.NodeRefreshableManagedResourceInstance + aws_instance.foo[2] - *terraform.NodeRefreshableManagedResourceInstance + aws_instance.foo[3] - *terraform.NodeRefreshableManagedResourceInstance +` + if expected != actual { + t.Fatalf("Expected:\n%s\nGot:\n%s", expected, actual) + } +} diff --git a/terraform/node_resource_validate.go b/terraform/node_resource_validate.go index e01518de4..f528f24b1 100644 --- a/terraform/node_resource_validate.go +++ b/terraform/node_resource_validate.go @@ -129,17 +129,29 @@ func (n *NodeValidatableResourceInstance) EvalTree() EvalNode { // Validate all the provisioners for _, p := range n.Config.Provisioners { var provisioner ResourceProvisioner - seq.Nodes = append(seq.Nodes, &EvalGetProvisioner{ - Name: p.Type, - Output: &provisioner, - }, &EvalInterpolate{ - Config: p.RawConfig.Copy(), - Resource: resource, - Output: &config, - }, &EvalValidateProvisioner{ - Provisioner: &provisioner, - Config: &config, - }) + var connConfig *ResourceConfig + seq.Nodes = append( + seq.Nodes, + &EvalGetProvisioner{ + Name: p.Type, + Output: &provisioner, + }, + &EvalInterpolate{ + Config: p.RawConfig.Copy(), + Resource: resource, + Output: &config, + }, + &EvalInterpolate{ + Config: p.ConnInfo.Copy(), + Resource: resource, + Output: &connConfig, + }, + &EvalValidateProvisioner{ + Provisioner: &provisioner, + Config: &config, + ConnConfig: &connConfig, + }, + ) } return seq diff --git a/terraform/state.go b/terraform/state.go index 4e5aa713f..074b68245 100644 --- a/terraform/state.go +++ b/terraform/state.go @@ -10,7 +10,6 @@ import ( "io/ioutil" "log" "reflect" - "regexp" "sort" "strconv" "strings" @@ -801,6 +800,27 @@ func (s *BackendState) Empty() bool { return s == nil || s.Type == "" } +// Rehash returns a unique content hash for this backend's configuration +// as a uint64 value. +// The Hash stored in the backend state needs to match the config itself, but +// we need to compare the backend config after it has been combined with all +// options. +// This function must match the implementation used by config.Backend. +func (s *BackendState) Rehash() uint64 { + if s == nil { + return 0 + } + + cfg := config.Backend{ + Type: s.Type, + RawConfig: &config.RawConfig{ + Raw: s.Config, + }, + } + + return cfg.Rehash() +} + // RemoteState is used to track the information about a remote // state store that we push/pull state to. type RemoteState struct { @@ -1142,6 +1162,8 @@ func (m *ModuleState) prune() { delete(m.Outputs, k) } } + + m.Dependencies = uniqueStrings(m.Dependencies) } func (m *ModuleState) sort() { @@ -1505,8 +1527,9 @@ func (s *ResourceState) prune() { i-- } } - s.Deposed = s.Deposed[:n] + + s.Dependencies = uniqueStrings(s.Dependencies) } func (s *ResourceState) sort() { @@ -1689,32 +1712,6 @@ func (s *InstanceState) MergeDiff(d *InstanceDiff) *InstanceState { } } - // Remove any now empty array, maps or sets because a parent structure - // won't include these entries in the count value. - isCount := regexp.MustCompile(`\.[%#]$`).MatchString - var deleted []string - - for k, v := range result.Attributes { - if isCount(k) && v == "0" { - delete(result.Attributes, k) - deleted = append(deleted, k) - } - } - - for _, k := range deleted { - // Sanity check for invalid structures. - // If we removed the primary count key, there should have been no - // other keys left with this prefix. - - // this must have a "#" or "%" which we need to remove - base := k[:len(k)-1] - for k, _ := range result.Attributes { - if strings.HasPrefix(k, base) { - panic(fmt.Sprintf("empty structure %q has entry %q", base, k)) - } - } - } - return result } @@ -1936,12 +1933,12 @@ func ReadStateV2(jsonBytes []byte) (*State, error) { } } - // Sort it - state.sort() - // catch any unitialized fields in the state state.init() + // Sort it + state.sort() + return state, nil } @@ -1971,12 +1968,12 @@ func ReadStateV3(jsonBytes []byte) (*State, error) { } } - // Sort it - state.sort() - // catch any unitialized fields in the state state.init() + // Sort it + state.sort() + // Now we write the state back out to detect any changes in normaliztion. // If our state is now written out differently, bump the serial number to // prevent conflicts. @@ -1996,12 +1993,17 @@ func ReadStateV3(jsonBytes []byte) (*State, error) { // WriteState writes a state somewhere in a binary format. func WriteState(d *State, dst io.Writer) error { - // Make sure it is sorted - d.sort() + // writing a nil state is a noop. + if d == nil { + return nil + } // make sure we have no uninitialized fields d.init() + // Make sure it is sorted + d.sort() + // Ensure the version is set d.Version = StateVersion diff --git a/terraform/state_test.go b/terraform/state_test.go index c10ebf133..5578f89c9 100644 --- a/terraform/state_test.go +++ b/terraform/state_test.go @@ -1450,66 +1450,6 @@ func TestInstanceState_MergeDiff(t *testing.T) { } } -// Make sure we don't leave empty maps or arrays in the flatmapped Attributes, -// since those may affect the counts of a parent structure. -func TestInstanceState_MergeDiffRemoveCounts(t *testing.T) { - is := InstanceState{ - ID: "foo", - Attributes: map[string]string{ - "all.#": "3", - "all.1111": "x", - "all.1234.#": "1", - "all.1234.0": "a", - "all.5678.%": "1", - "all.5678.key": "val", - - // nested empty lists need to be removed cleanly - "all.nested.#": "0", - "all.nested.0.empty.#": "0", - "all.nested.1.empty.#": "0", - - // the value has a prefix that matches another key - // and ntohing should happen to this. - "all.nested_value": "y", - }, - } - - diff := &InstanceDiff{ - Attributes: map[string]*ResourceAttrDiff{ - "all.#": &ResourceAttrDiff{ - Old: "3", - New: "1", - }, - "all.1234.0": &ResourceAttrDiff{ - NewRemoved: true, - }, - "all.1234.#": &ResourceAttrDiff{ - Old: "1", - New: "0", - }, - "all.5678.key": &ResourceAttrDiff{ - NewRemoved: true, - }, - "all.5678.%": &ResourceAttrDiff{ - Old: "1", - New: "0", - }, - }, - } - - is2 := is.MergeDiff(diff) - - expected := map[string]string{ - "all.#": "1", - "all.1111": "x", - "all.nested_value": "y", - } - - if !reflect.DeepEqual(expected, is2.Attributes) { - t.Fatalf("bad: %#v", is2.Attributes) - } -} - // GH-12183. This tests that a list with a computed set generates the // right partial state. This never failed but is put here for completion // of the test case for GH-12183. @@ -1898,6 +1838,62 @@ func TestReadState_prune(t *testing.T) { } } +func TestReadState_pruneDependencies(t *testing.T) { + state := &State{ + Serial: 9, + Lineage: "5d1ad1a1-4027-4665-a908-dbe6adff11d8", + Remote: &RemoteState{ + Type: "http", + Config: map[string]string{ + "url": "http://my-cool-server.com/", + }, + }, + Modules: []*ModuleState{ + &ModuleState{ + Path: rootModulePath, + Dependencies: []string{ + "aws_instance.bar", + "aws_instance.bar", + }, + Resources: map[string]*ResourceState{ + "foo": &ResourceState{ + Dependencies: []string{ + "aws_instance.baz", + "aws_instance.baz", + }, + Primary: &InstanceState{ + ID: "bar", + }, + }, + }, + }, + }, + } + state.init() + + buf := new(bytes.Buffer) + if err := WriteState(state, buf); err != nil { + t.Fatalf("err: %s", err) + } + + actual, err := ReadState(buf) + if err != nil { + t.Fatalf("err: %s", err) + } + + // make sure the duplicate Dependencies are filtered + modDeps := actual.Modules[0].Dependencies + resourceDeps := actual.Modules[0].Resources["foo"].Dependencies + + if len(modDeps) > 1 || modDeps[0] != "aws_instance.bar" { + t.Fatalf("expected 1 module depends_on entry, got %q", modDeps) + } + + if len(resourceDeps) > 1 || resourceDeps[0] != "aws_instance.baz" { + t.Fatalf("expected 1 resource depends_on entry, got %q", resourceDeps) + } +} + func TestResourceNameSort(t *testing.T) { names := []string{ "a", diff --git a/terraform/test-fixtures/apply-multi-ref/main.tf b/terraform/test-fixtures/apply-multi-ref/main.tf new file mode 100644 index 000000000..2a6a67152 --- /dev/null +++ b/terraform/test-fixtures/apply-multi-ref/main.tf @@ -0,0 +1,8 @@ +resource "aws_instance" "create" { + bar = "abc" +} + +resource "aws_instance" "other" { + var = "${aws_instance.create.id}" + foo = "${aws_instance.create.bar}" +} diff --git a/terraform/test-fixtures/apply-multi-var-missing-state/child/child.tf b/terraform/test-fixtures/apply-multi-var-missing-state/child/child.tf new file mode 100644 index 000000000..928018627 --- /dev/null +++ b/terraform/test-fixtures/apply-multi-var-missing-state/child/child.tf @@ -0,0 +1,15 @@ + +# This resource gets visited first on the apply walk, but since it DynamicExpands +# to an empty subgraph it ends up being a no-op, leaving the module state +# uninitialized. +resource "test_thing" "a" { + count = 0 +} + +# This resource is visited second. During its eval walk we try to build the +# array for the null_resource.a.*.id interpolation, which involves iterating +# over all of the resource in the state. This should succeed even though the +# module state will be nil when evaluating the variable. +resource "test_thing" "b" { + a_ids = "${join(" ", null_resource.a.*.id)}" +} diff --git a/terraform/test-fixtures/apply-multi-var-missing-state/root.tf b/terraform/test-fixtures/apply-multi-var-missing-state/root.tf new file mode 100644 index 000000000..25a0a1f9b --- /dev/null +++ b/terraform/test-fixtures/apply-multi-var-missing-state/root.tf @@ -0,0 +1,7 @@ +// We test this in a child module, since the root module state exists +// very early on, even before any resources are created in it, but that is not +// true for child modules. + +module "child" { + source = "./child" +} diff --git a/terraform/test-fixtures/apply-targeted-module-unrelated-outputs/child1/main.tf b/terraform/test-fixtures/apply-targeted-module-unrelated-outputs/child1/main.tf index b6de394c9..cffe3829e 100644 --- a/terraform/test-fixtures/apply-targeted-module-unrelated-outputs/child1/main.tf +++ b/terraform/test-fixtures/apply-targeted-module-unrelated-outputs/child1/main.tf @@ -2,6 +2,13 @@ variable "instance_id" { } output "instance_id" { + # The instance here isn't targeted, so this output shouldn't get updated. + # But it already has an existing value in state (specified within the + # test code) so we expect this to remain unchanged afterwards. + value = "${aws_instance.foo.id}" +} + +output "given_instance_id" { value = "${var.instance_id}" } diff --git a/terraform/test-fixtures/apply-targeted-module-unrelated-outputs/child2/main.tf b/terraform/test-fixtures/apply-targeted-module-unrelated-outputs/child2/main.tf index b626e60c8..dce2d167b 100644 --- a/terraform/test-fixtures/apply-targeted-module-unrelated-outputs/child2/main.tf +++ b/terraform/test-fixtures/apply-targeted-module-unrelated-outputs/child2/main.tf @@ -1,2 +1,9 @@ resource "aws_instance" "foo" { } + +output "instance_id" { + # Even though we're targeting just the resource a bove, this should still + # be populated because outputs are implicitly targeted when their + # dependencies are + value = "${aws_instance.foo.id}" +} diff --git a/terraform/test-fixtures/apply-targeted-module-unrelated-outputs/main.tf b/terraform/test-fixtures/apply-targeted-module-unrelated-outputs/main.tf index 236f0c495..117007237 100644 --- a/terraform/test-fixtures/apply-targeted-module-unrelated-outputs/main.tf +++ b/terraform/test-fixtures/apply-targeted-module-unrelated-outputs/main.tf @@ -8,3 +8,30 @@ module "child1" { module "child2" { source = "./child2" } + +output "child1_id" { + value = "${module.child1.instance_id}" +} + +output "child1_given_id" { + value = "${module.child1.given_instance_id}" +} + +output "child2_id" { + # This should get updated even though we're targeting specifically + # module.child2, because outputs are implicitly targeted when their + # dependencies are. + value = "${module.child2.instance_id}" +} + +output "all_ids" { + # Here we are intentionally referencing values covering three different scenarios: + # - not targeted and not already in state + # - not targeted and already in state + # - targeted + # This is important because this output must appear in the graph after + # target filtering in case the targeted node changes its value, but we must + # therefore silently ignore the failure that results from trying to + # interpolate the un-targeted, not-in-state node. + value = "${aws_instance.foo.id} ${module.child1.instance_id} ${module.child2.instance_id}" +} diff --git a/terraform/test-fixtures/interpolate-resource-variable-multi/main.tf b/terraform/test-fixtures/interpolate-resource-variable-multi/main.tf new file mode 100644 index 000000000..b00b04eff --- /dev/null +++ b/terraform/test-fixtures/interpolate-resource-variable-multi/main.tf @@ -0,0 +1,3 @@ +resource "aws_instance" "web" { + count = 3 +} diff --git a/terraform/test-fixtures/nested-resource-count-plan/main.tf b/terraform/test-fixtures/nested-resource-count-plan/main.tf new file mode 100644 index 000000000..f803fd1f6 --- /dev/null +++ b/terraform/test-fixtures/nested-resource-count-plan/main.tf @@ -0,0 +1,11 @@ +resource "aws_instance" "foo" { + count = 2 +} + +resource "aws_instance" "bar" { + count = "${length(aws_instance.foo.*.id)}" +} + +resource "aws_instance" "baz" { + count = "${length(aws_instance.bar.*.id)}" +} diff --git a/terraform/test-fixtures/plan-count-splat-reference/main.tf b/terraform/test-fixtures/plan-count-splat-reference/main.tf new file mode 100644 index 000000000..76834e255 --- /dev/null +++ b/terraform/test-fixtures/plan-count-splat-reference/main.tf @@ -0,0 +1,9 @@ +resource "aws_instance" "foo" { + name = "foo ${count.index}" + count = 3 +} + +resource "aws_instance" "bar" { + foo_name = "${aws_instance.foo.*.name[count.index]}" + count = 3 +} diff --git a/terraform/test-fixtures/refresh-config-orphan/main.tf b/terraform/test-fixtures/refresh-config-orphan/main.tf new file mode 100644 index 000000000..acef373b3 --- /dev/null +++ b/terraform/test-fixtures/refresh-config-orphan/main.tf @@ -0,0 +1,3 @@ +resource "aws_instance" "foo" { + count = 3 +} diff --git a/terraform/test-fixtures/refresh-data-scale-inout/main.tf b/terraform/test-fixtures/refresh-data-scale-inout/main.tf new file mode 100644 index 000000000..480ba9483 --- /dev/null +++ b/terraform/test-fixtures/refresh-data-scale-inout/main.tf @@ -0,0 +1,3 @@ +data "aws_instance" "foo" { + count = 3 +} diff --git a/terraform/test-fixtures/refresh-resource-scale-inout/main.tf b/terraform/test-fixtures/refresh-resource-scale-inout/main.tf new file mode 100644 index 000000000..acef373b3 --- /dev/null +++ b/terraform/test-fixtures/refresh-resource-scale-inout/main.tf @@ -0,0 +1,3 @@ +resource "aws_instance" "foo" { + count = 3 +} diff --git a/terraform/test-fixtures/transform-targets-downstream/child/child.tf b/terraform/test-fixtures/transform-targets-downstream/child/child.tf new file mode 100644 index 000000000..6548b7949 --- /dev/null +++ b/terraform/test-fixtures/transform-targets-downstream/child/child.tf @@ -0,0 +1,14 @@ +resource "aws_instance" "foo" { +} + +module "grandchild" { + source = "./grandchild" +} + +output "id" { + value = "${aws_instance.foo.id}" +} + +output "grandchild_id" { + value = "${module.grandchild.id}" +} diff --git a/terraform/test-fixtures/transform-targets-downstream/child/grandchild/grandchild.tf b/terraform/test-fixtures/transform-targets-downstream/child/grandchild/grandchild.tf new file mode 100644 index 000000000..3ad8fd077 --- /dev/null +++ b/terraform/test-fixtures/transform-targets-downstream/child/grandchild/grandchild.tf @@ -0,0 +1,6 @@ +resource "aws_instance" "foo" { +} + +output "id" { + value = "${aws_instance.foo.id}" +} diff --git a/terraform/test-fixtures/transform-targets-downstream/main.tf b/terraform/test-fixtures/transform-targets-downstream/main.tf new file mode 100644 index 000000000..b732fdad7 --- /dev/null +++ b/terraform/test-fixtures/transform-targets-downstream/main.tf @@ -0,0 +1,18 @@ +resource "aws_instance" "foo" { +} + +module "child" { + source = "./child" +} + +output "root_id" { + value = "${aws_instance.foo.id}" +} + +output "child_id" { + value = "${module.child.id}" +} + +output "grandchild_id" { + value = "${module.child.grandchild_id}" +} diff --git a/terraform/transform_resource_refresh_plannable.go b/terraform/transform_resource_refresh_plannable.go new file mode 100644 index 000000000..35358a318 --- /dev/null +++ b/terraform/transform_resource_refresh_plannable.go @@ -0,0 +1,55 @@ +package terraform + +import ( + "fmt" + "log" +) + +// ResourceRefreshPlannableTransformer is a GraphTransformer that replaces any +// nodes that don't have state yet exist in config with +// NodePlannableResourceInstance. +// +// This transformer is used when expanding count on managed resource nodes +// during the refresh phase to ensure that data sources that have +// interpolations that depend on resources existing in the graph can be walked +// properly. +type ResourceRefreshPlannableTransformer struct { + // The full global state. + State *State +} + +// Transform implements GraphTransformer for +// ResourceRefreshPlannableTransformer. +func (t *ResourceRefreshPlannableTransformer) Transform(g *Graph) error { +nextVertex: + for _, v := range g.Vertices() { + addr := v.(*NodeRefreshableManagedResourceInstance).Addr + + // Find the state for this address, if there is one + filter := &StateFilter{State: t.State} + results, err := filter.Filter(addr.String()) + if err != nil { + return err + } + + // Check to see if we have a state for this resource. If we do, skip this + // node. + for _, result := range results { + if _, ok := result.Value.(*ResourceState); ok { + continue nextVertex + } + } + // If we don't, convert this resource to a NodePlannableResourceInstance node + // with all of the data we need to make it happen. + log.Printf("[TRACE] No state for %s, converting to NodePlannableResourceInstance", addr.String()) + new := &NodePlannableResourceInstance{ + NodeAbstractResource: v.(*NodeRefreshableManagedResourceInstance).NodeAbstractResource, + } + // Replace the node in the graph + if !g.Replace(v, new) { + return fmt.Errorf("ResourceRefreshPlannableTransformer: Could not replace node %#v with %#v", v, new) + } + } + + return nil +} diff --git a/terraform/transform_targets.go b/terraform/transform_targets.go index 225ac4b4a..125f9e302 100644 --- a/terraform/transform_targets.go +++ b/terraform/transform_targets.go @@ -15,6 +15,21 @@ type GraphNodeTargetable interface { SetTargets([]ResourceAddress) } +// GraphNodeTargetDownstream is an interface for graph nodes that need to +// be remain present under targeting if any of their dependencies are targeted. +// TargetDownstream is called with the set of vertices that are direct +// dependencies for the node, and it should return true if the node must remain +// in the graph in support of those dependencies. +// +// This is used in situations where the dependency edges are representing an +// ordering relationship but the dependency must still be visited if its +// dependencies are visited. This is true for outputs, for example, since +// they must get updated if any of their dependent resources get updated, +// which would not normally be true if one of their dependencies were targeted. +type GraphNodeTargetDownstream interface { + TargetDownstream(targeted, untargeted *dag.Set) bool +} + // TargetsTransformer is a GraphTransformer that, when the user specifies a // list of resources to target, limits the graph to only those resources and // their dependencies. @@ -84,7 +99,10 @@ func (t *TargetsTransformer) parseTargetAddresses() ([]ResourceAddress, error) { func (t *TargetsTransformer) selectTargetedNodes( g *Graph, addrs []ResourceAddress) (*dag.Set, error) { targetedNodes := new(dag.Set) - for _, v := range g.Vertices() { + + vertices := g.Vertices() + + for _, v := range vertices { if t.nodeIsTarget(v, addrs) { targetedNodes.Add(v) @@ -112,6 +130,63 @@ func (t *TargetsTransformer) selectTargetedNodes( } } + // Handle nodes that need to be included if their dependencies are included. + // This requires multiple passes since we need to catch transitive + // dependencies if and only if they are via other nodes that also + // support TargetDownstream. For example: + // output -> output -> targeted-resource: both outputs need to be targeted + // output -> non-targeted-resource -> targeted-resource: output not targeted + // + // We'll keep looping until we stop targeting more nodes. + queue := targetedNodes.List() + for len(queue) > 0 { + vertices := queue + queue = nil // ready to append for next iteration if neccessary + for _, v := range vertices { + dependers := g.UpEdges(v) + if dependers == nil { + // indicates that there are no up edges for this node, so + // we have nothing to do here. + continue + } + + dependers = dependers.Filter(func(dv interface{}) bool { + // Can ignore nodes that are already targeted + /*if targetedNodes.Include(dv) { + return false + }*/ + + _, ok := dv.(GraphNodeTargetDownstream) + return ok + }) + + if dependers.Len() == 0 { + continue + } + + for _, dv := range dependers.List() { + if targetedNodes.Include(dv) { + // Already present, so nothing to do + continue + } + + // We'll give the node some information about what it's + // depending on in case that informs its decision about whether + // it is safe to be targeted. + deps := g.DownEdges(v) + depsTargeted := deps.Intersection(targetedNodes) + depsUntargeted := deps.Difference(depsTargeted) + + if dv.(GraphNodeTargetDownstream).TargetDownstream(depsTargeted, depsUntargeted) { + targetedNodes.Add(dv) + // Need to visit this node on the next pass to see if it + // has any transitive dependers. + queue = append(queue, dv) + } + } + } + } + return targetedNodes, nil } diff --git a/terraform/transform_targets_test.go b/terraform/transform_targets_test.go index 9418860e2..c5c97cd22 100644 --- a/terraform/transform_targets_test.go +++ b/terraform/transform_targets_test.go @@ -50,6 +50,69 @@ aws_vpc.me } } +func TestTargetsTransformer_downstream(t *testing.T) { + mod := testModule(t, "transform-targets-downstream") + + g := Graph{Path: RootModulePath} + { + transform := &ConfigTransformer{Module: mod} + if err := transform.Transform(&g); err != nil { + t.Fatalf("%T failed: %s", transform, err) + } + } + + { + transform := &AttachResourceConfigTransformer{Module: mod} + if err := transform.Transform(&g); err != nil { + t.Fatalf("%T failed: %s", transform, err) + } + } + + { + transform := &AttachResourceConfigTransformer{Module: mod} + if err := transform.Transform(&g); err != nil { + t.Fatalf("%T failed: %s", transform, err) + } + } + + { + transform := &OutputTransformer{Module: mod} + if err := transform.Transform(&g); err != nil { + t.Fatalf("%T failed: %s", transform, err) + } + } + + { + transform := &ReferenceTransformer{} + if err := transform.Transform(&g); err != nil { + t.Fatalf("err: %s", err) + } + } + + { + transform := &TargetsTransformer{Targets: []string{"module.child.module.grandchild.aws_instance.foo"}} + if err := transform.Transform(&g); err != nil { + t.Fatalf("%T failed: %s", transform, err) + } + } + + actual := strings.TrimSpace(g.String()) + // Even though we only asked to target the grandchild resource, all of the + // outputs that descend from it are also targeted. + expected := strings.TrimSpace(` +module.child.module.grandchild.aws_instance.foo +module.child.module.grandchild.output.id + module.child.module.grandchild.aws_instance.foo +module.child.output.grandchild_id + module.child.module.grandchild.output.id +output.grandchild_id + module.child.output.grandchild_id + `) + if actual != expected { + t.Fatalf("bad:\n\nexpected:\n%s\n\ngot:\n%s\n", expected, actual) + } +} + func TestTargetsTransformer_destroy(t *testing.T) { mod := testModule(t, "transform-targets-destroy") diff --git a/terraform/util.go b/terraform/util.go index e1d951c01..f41f0d7d6 100644 --- a/terraform/util.go +++ b/terraform/util.go @@ -1,6 +1,7 @@ package terraform import ( + "sort" "strings" ) @@ -73,3 +74,20 @@ func strSliceContains(haystack []string, needle string) bool { } return false } + +// deduplicate a slice of strings +func uniqueStrings(s []string) []string { + if len(s) < 2 { + return s + } + + sort.Strings(s) + result := make([]string, 1, len(s)) + result[0] = s[0] + for i := 1; i < len(s); i++ { + if s[i] != result[len(result)-1] { + result = append(result, s[i]) + } + } + return result +} diff --git a/terraform/util_test.go b/terraform/util_test.go index 3c95e361a..9c5712cfa 100644 --- a/terraform/util_test.go +++ b/terraform/util_test.go @@ -1,6 +1,8 @@ package terraform import ( + "fmt" + "reflect" "testing" "time" ) @@ -96,3 +98,44 @@ func TestUtilResourceProvider(t *testing.T) { } } } + +func TestUniqueStrings(t *testing.T) { + cases := []struct { + Input []string + Expected []string + }{ + { + []string{}, + []string{}, + }, + { + []string{"x"}, + []string{"x"}, + }, + { + []string{"a", "b", "c"}, + []string{"a", "b", "c"}, + }, + { + []string{"a", "a", "a"}, + []string{"a"}, + }, + { + []string{"a", "b", "a", "b", "a", "a"}, + []string{"a", "b"}, + }, + { + []string{"c", "b", "a", "c", "b"}, + []string{"a", "b", "c"}, + }, + } + + for i, tc := range cases { + t.Run(fmt.Sprintf("unique-%d", i), func(t *testing.T) { + actual := uniqueStrings(tc.Input) + if !reflect.DeepEqual(tc.Expected, actual) { + t.Fatalf("Expected: %q\nGot: %q", tc.Expected, actual) + } + }) + } +} diff --git a/terraform/version.go b/terraform/version.go index ada5dcc38..577dc85ab 100644 --- a/terraform/version.go +++ b/terraform/version.go @@ -7,7 +7,7 @@ import ( ) // The main version number that is being run at the moment. -const Version = "0.9.3" +const Version = "0.9.6" // 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/terraform/walkoperation_string.go b/terraform/walkoperation_string.go index 8fb33d7b5..cbd78dd93 100644 --- a/terraform/walkoperation_string.go +++ b/terraform/walkoperation_string.go @@ -1,4 +1,4 @@ -// Code generated by "stringer -type=walkOperation graph_walk_operation.go"; DO NOT EDIT +// Code generated by "stringer -type=walkOperation graph_walk_operation.go"; DO NOT EDIT. package terraform diff --git a/vendor/github.com/1and1/oneandone-cloudserver-sdk-go/LICENSE b/vendor/github.com/1and1/oneandone-cloudserver-sdk-go/LICENSE new file mode 100644 index 000000000..9fb7e22bc --- /dev/null +++ b/vendor/github.com/1and1/oneandone-cloudserver-sdk-go/LICENSE @@ -0,0 +1,202 @@ + Apache License + Version 2.0, January 2004 + http://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 + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright (c) 2016 1&1 Internet SE + + 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. + diff --git a/vendor/github.com/1and1/oneandone-cloudserver-sdk-go/README.md b/vendor/github.com/1and1/oneandone-cloudserver-sdk-go/README.md new file mode 100644 index 000000000..adb9cd19b --- /dev/null +++ b/vendor/github.com/1and1/oneandone-cloudserver-sdk-go/README.md @@ -0,0 +1,2573 @@ +# 1&1 Cloudserver Go SDK + +The 1&1 Go SDK is a Go library designed for interaction with the 1&1 cloud platform over the REST API. + +This guide contains instructions on getting started with the library and automating various management tasks available through the 1&1 Cloud Panel UI. + +## Table of Contents + +- [Overview](#overview) +- [Getting Started](#getting-started) + - [Installation](#installation) + - [Authentication](#authentication) +- [Operations](#operations) + - [Servers](#servers) + - [Images](#images) + - [Shared Storages](#shared-storages) + - [Firewall Policies](#firewall-policies) + - [Load Balancers](#load-balancers) + - [Public IPs](#public-ips) + - [Private Networks](#private-networks) + - [VPNs](#vpns) + - [Monitoring Center](#monitoring-center) + - [Monitoring Policies](#monitoring-policies) + - [Logs](#logs) + - [Users](#users) + - [Roles](#roles) + - [Usages](#usages) + - [Server Appliances](#server-appliances) + - [DVD ISO](#dvd-iso) + - [Ping](#ping) + - [Pricing](#pricing) + - [Data Centers](#data-centers) +- [Examples](#examples) +- [Index](#index) + +## Overview + +This SDK is a wrapper for the 1&1 REST API written in Go(lang). All operations against the API are performed over SSL and authenticated using your 1&1 token key. The Go library facilitates the access to the REST API either within an instance running on 1&1 platform or directly across the Internet from any HTTPS-enabled application. + +For more information on the 1&1 Cloud Server SDK for Go, visit the [Community Portal](https://www.1and1.com/cloud-community/). + +## Getting Started + +Before you begin you will need to have signed up for a 1&1 account. The credentials you create during sign-up will be used to authenticate against the API. + +Install the Go language tools. Find the install package and instructions on the official Go website. Make sure that you have set up the `GOPATH` environment variable properly, as indicated in the instructions. + +### Installation + +The official Go library is available from the 1&1 GitHub account found here. + +Use the following Go command to download oneandone-cloudserver-sdk-go to your configured GOPATH: + +`go get github.com/1and1/oneandone-cloudserver-sdk-go` + +Import the library in your Go code: + +`import "github.com/1and1/oneandone-cloudserver-sdk-go"` + +### Authentication + +Set the authentication token and create the API client: + +``` +token := oneandone.SetToken("82ee732b8d47e451be5c6ad5b7b56c81") +api := oneandone.New(token, oneandone.BaseUrl) +``` + +Refer to the [Examples](#examples) and [Operations](#operations) sections for additional information. + +## Operations + +### Servers + +**List all servers:** + +`servers, err := api.ListServers()` + +Alternatively, use the method with query parameters. + +`servers, err := api.ListServers(page, per_page, sort, query, fields)` + +To paginate the list of servers received in the response use `page` and `per_page` parameters. Set `per_page` to the number of servers that will be shown in each page. `page` indicates the current page. When set to an integer value that is less or equal to zero, the parameters are ignored by the framework. + +To receive the list of servers sorted in expected order pass a server property (e.g. `"name"`) in `sort` parameter. + +Use `query` parameter to search for a string in the response and return only the server instances that contain it. + +To retrieve a collection of servers containing only the requested fields pass a list of comma separated properties (e.g. `"id,name,description,hardware.ram"`) in `fields` parameter. + +If any of the parameters `sort`, `query` or `fields` is set to an empty string, it is ignored in the request. + +**Retrieve a single server:** + +`server, err := api.GetServer(server_id)` + +**List fixed-size server templates:** + +`fiss, err := api.ListFixedInstanceSizes()` + +**Retrieve information about a fixed-size server template:** + +`fis, err := api.GetFixedInstanceSize(fis_id)` + +**Retrieve information about a server's hardware:** + +`hardware, err := api.GetServerHardware(server_id)` + +**List a server's HDDs:** + +`hdds, err := api.ListServerHdds(server_id)` + +**Retrieve a single server HDD:** + +`hdd, err := api.GetServerHdd(server_id, hdd_id)` + +**Retrieve information about a server's image:** + +`image, err := api.GetServerImage(server_id)` + +**List a server's IPs:** + +`ips, err := api.ListServerIps(server_id)` + +**Retrieve information about a single server IP:** + +`ip, err := api.GetServerIp(server_id, ip_id)` + +**Retrieve information about a server's firewall policy:** + +`firewall, err := api.GetServerIpFirewallPolicy(server_id, ip_id)` + +**List all load balancers assigned to a server IP:** + +`lbs, err := api.ListServerIpLoadBalancers(server_id, ip_id)` + +**Retrieve information about a server's status:** + +`status, err := api.GetServerStatus(server_id)` + +**Retrieve information about the DVD loaded into the virtual DVD unit of a server:** + +`dvd, err := api.GetServerDvd(server_id)` + +**List a server's private networks:** + +`pns, err := api.ListServerPrivateNetworks(server_id)` + +**Retrieve information about a server's private network:** + +`pn, err := api.GetServerPrivateNetwork(server_id, pn_id)` + +**Retrieve information about a server's snapshot:** + +`snapshot, err := api.GetServerSnapshot(server_id)` + +**Create a server:** + +``` +req := oneandone.ServerRequest { + Name: "Server Name", + Description: "Server description.", + ApplianceId: server_appliance_id, + PowerOn: true, + Hardware: oneandone.Hardware { + Vcores: 1, + CoresPerProcessor: 1, + Ram: 2, + Hdds: []oneandone.Hdd { + oneandone.Hdd { + Size: 100, + IsMain: true, + }, + }, + }, + } + +server_id, server, err := api.CreateServer(&req) +``` + +**Create a fixed-size server and return back the server's IP address and first password:** + +``` +req := oneandone.ServerRequest { + Name: server_name, + ApplianceId: server_appliance_id, + PowerOn: true_or_false, + Hardware: oneandone.Hardware { + FixedInsSizeId: fixed_instance_size_id, + }, + } + +ip_address, password, err := api.CreateServerEx(&req, timeout) +``` + +**Update a server:** + +`server, err := api.RenameServer(server_id, new_name, new_desc)` + +**Delete a server:** + +`server, err := api.DeleteServer(server_id, keep_ips)` + +Set `keep_ips` parameter to `true` for keeping server IPs after deleting a server. + +**Update a server's hardware:** + +``` +hardware := oneandone.Hardware { + Vcores: 2, + CoresPerProcessor: 1, + Ram: 2, + } + +server, err := api.UpdateServerHardware(server_id, &hardware) +``` + +**Add new hard disk(s) to a server:** + +``` +hdds := oneandone.ServerHdds { + Hdds: []oneandone.Hdd { + { + Size: 50, + IsMain: false, + }, + }, + } + +server, err := api.AddServerHdds(server_id, &hdds) +``` + +**Resize a server's hard disk:** + +`server, err := api.ResizeServerHdd(server_id, hdd_id, new_size)` + +**Remove a server's hard disk:** + +`server, err := api.DeleteServerHdd(server_id, hdd_id)` + +**Load a DVD into the virtual DVD unit of a server:** + +`server, err := api.LoadServerDvd(server_id, dvd_id)` + +**Unload a DVD from the virtual DVD unit of a server:** + +`server, err := api.EjectServerDvd(server_id)` + +**Reinstall a new image into a server:** + +`server, err := api.ReinstallServerImage(server_id, image_id, password, fp_id)` + +**Assign a new IP to a server:** + +`server, err := api.AssignServerIp(server_id, ip_type)` + +**Release an IP and optionally remove it from a server:** + +`server, err := api.DeleteServerIp(server_id, ip_id, keep_ip)` + +Set `keep_ip` to true for releasing the IP without removing it. + +**Assign a new firewall policy to a server's IP:** + +`server, err := api.AssignServerIpFirewallPolicy(server_id, ip_id, fp_id)` + +**Remove a firewall policy from a server's IP:** + +`server, err := api.UnassignServerIpFirewallPolicy(server_id, ip_id)` + +**Assign a new load balancer to a server's IP:** + +`server, err := api.AssignServerIpLoadBalancer(server_id, ip_id, lb_id)` + +**Remove a load balancer from a server's IP:** + +`server, err := api.UnassignServerIpLoadBalancer(server_id, ip_id, lb_id)` + +**Start a server:** + +`server, err := api.StartServer(server_id)` + +**Reboot a server:** + +`server, err := api.RebootServer(server_id, is_hardware)` + +Set `is_hardware` to true for HARDWARE method of rebooting. + +Set `is_hardware` to false for SOFTWARE method of rebooting. + +**Shutdown a server:** + +`server, err := api.ShutdownServer(server_id, is_hardware)` + +Set `is_hardware` to true for HARDWARE method of powering off. + +Set `is_hardware` to false for SOFTWARE method of powering off. + +**Assign a private network to a server:** + +`server, err := api.AssignServerPrivateNetwork(server_id, pn_id)` + +**Remove a server's private network:** + +`server, err := api.RemoveServerPrivateNetwork(server_id, pn_id)` + +**Create a new server's snapshot:** + +`server, err := api.CreateServerSnapshot(server_id)` + +**Restore a server's snapshot:** + +`server, err := api.RestoreServerSnapshot(server_id, snapshot_id)` + +**Remove a server's snapshot:** + +`server, err := api.DeleteServerSnapshot(server_id, snapshot_id);` + +**Clone a server:** + +`server, err := api.CloneServer(server_id, new_name)` + + +### Images + +**List all images:** + +`images, err = api.ListImages()` + +Alternatively, use the method with query parameters. + +`images, err = api.ListImages(page, per_page, sort, query, fields)` + +To paginate the list of images received in the response use `page` and `per_page` parameters. set `per_page` to the number of images that will be shown in each page. `page` indicates the current page. When set to an integer value that is less or equal to zero, the parameters are ignored by the framework. + +To receive the list of images sorted in expected order pass an image property (e.g. `"name"`) in `sort` parameter. Prefix the sorting attribute with `-` sign for sorting in descending order. + +Use `query` parameter to search for a string in the response and return only the elements that contain it. + +To retrieve a collection of images containing only the requested fields pass a list of comma separated properties (e.g. `"id,name,creation_date"`) in `fields` parameter. + +If any of the parameters `sort`, `query` or `fields` is set to an empty string, it is ignored in the request. + +**Retrieve a single image:** + +`image, err = api.GetImage(image_id)` + + +**Create an image:** + +``` +request := oneandone.ImageConfig { + Name: image_name, + Description: image_description, + ServerId: server_id, + Frequency: image_frequenct, + NumImages: number_of_images, + } + +image_id, image, err = api.CreateImage(&request) +``` +All fields except `Description` are required. `Frequency` may be set to `"ONCE"`, `"DAILY"` or `"WEEKLY"`. + +**Update an image:** + + +`image, err = api.UpdateImage(image_id, new_name, new_description, new_frequenct)` + +If any of the parameters `new_name`, `new_description` or `new_frequenct` is set to an empty string, it is ignored in the request. `Frequency` may be set to `"ONCE"`, `"DAILY"` or `"WEEKLY"`. + +**Delete an image:** + +`image, err = api.DeleteImage(image_id)` + +### Shared Storages + +`ss, err := api.ListSharedStorages()` + +Alternatively, use the method with query parameters. + +`ss, err := api.ListSharedStorages(page, per_page, sort, query, fields)` + +To paginate the list of shared storages received in the response use `page` and `per_page` parameters. Set `per_page` to the number of volumes that will be shown in each page. `page` indicates the current page. When set to an integer value that is less or equal to zero, the parameters are ignored by the framework. + +To receive the list of shared storages sorted in expected order pass a volume property (e.g. `"name"`) in `sort` parameter. Prefix the sorting attribute with `-` sign for sorting in descending order. + +Use `query` parameter to search for a string in the response and return only the volume instances that contain it. + +To retrieve a collection of shared storages containing only the requested fields pass a list of comma separated properties (e.g. `"id,name,size,size_used"`) in `fields` parameter. + +If any of the parameters `sort`, `query` or `fields` is set to an empty string, it is ignored in the request. + +**Retrieve a shared storage:** + +`ss, err := api.GetSharedStorage(ss_id)` + + +**Create a shared storage:** + +``` +request := oneandone.SharedStorageRequest { + Name: test_ss_name, + Description: test_ss_desc, + Size: oneandone.Int2Pointer(size), + } + +ss_id, ss, err := api.CreateSharedStorage(&request) + +``` +`Description` is optional parameter. + + +**Update a shared storage:** + +``` +request := oneandone.SharedStorageRequest { + Name: new_name, + Description: new_desc, + Size: oneandone.Int2Pointer(new_size), + } + +ss, err := api.UpdateSharedStorage(ss_id, &request) +``` +All request's parameters are optional. + + +**Remove a shared storage:** + +`ss, err := api.DeleteSharedStorage(ss_id)` + + +**List a shared storage servers:** + +`ss_servers, err := api.ListSharedStorageServers(ss_id)` + + +**Retrieve a shared storage server:** + +`ss_server, err := api.GetSharedStorageServer(ss_id, server_id)` + + +**Add servers to a shared storage:** + +``` +servers := []oneandone.SharedStorageServer { + { + Id: server_id, + Rights: permissions, + } , + } + +ss, err := api.AddSharedStorageServers(ss_id, servers) +``` +`Rights` may be set to `R` or `RW` string. + + +**Remove a server from a shared storage:** + +`ss, err := api.DeleteSharedStorageServer(ss_id, server_id)` + + +**Retrieve the credentials for accessing the shared storages:** + +`ss_credentials, err := api.GetSharedStorageCredentials()` + + +**Change the password for accessing the shared storages:** + +`ss_credentials, err := api.UpdateSharedStorageCredentials(new_password)` + + +### Firewall Policies + +**List firewall policies:** + +`firewalls, err := api.ListFirewallPolicies()` + +Alternatively, use the method with query parameters. + +`firewalls, err := api.ListFirewallPolicies(page, per_page, sort, query, fields)` + +To paginate the list of firewall policies received in the response use `page` and `per_page` parameters. Set `per_page` to the number of firewall policies that will be shown in each page. `page` indicates the current page. When set to an integer value that is less or equal to zero, the parameters are ignored by the framework. + +To receive the list of firewall policies sorted in expected order pass a firewall policy property (e.g. `"name"`) in `sort` parameter. Prefix the sorting attribute with `-` sign for sorting in descending order. + +Use `query` parameter to search for a string in the response and return only the firewall policy instances that contain it. + +To retrieve a collection of firewall policies containing only the requested fields pass a list of comma separated properties (e.g. `"id,name,creation_date"`) in `fields` parameter. + +If any of the parameters `sort`, `query` or `fields` is set to an empty string, it is ignored in the request. + +**Retrieve a single firewall policy:** + +`firewall, err := api.GetFirewallPolicy(fp_id)` + + +**Create a firewall policy:** + +``` +request := oneandone.FirewallPolicyRequest { + Name: fp_name, + Description: fp_desc, + Rules: []oneandone.FirewallPolicyRule { + { + Protocol: protocol, + PortFrom: oneandone.Int2Pointer(port_from), + PortTo: oneandone.Int2Pointer(port_to), + SourceIp: source_ip, + }, + }, + } + +firewall_id, firewall, err := api.CreateFirewallPolicy(&request) +``` +`SourceIp` and `Description` are optional parameters. + + +**Update a firewall policy:** + +`firewall, err := api.UpdateFirewallPolicy(fp_id, fp_new_name, fp_new_description)` + +Passing an empty string in `fp_new_name` or `fp_new_description` skips updating the firewall policy name or description respectively. + + +**Delete a firewall policy:** + +`firewall, err := api.DeleteFirewallPolicy(fp_id)` + + +**List servers/IPs attached to a firewall policy:** + +`server_ips, err := api.ListFirewallPolicyServerIps(fp_id)` + + +**Retrieve information about a server/IP assigned to a firewall policy:** + +`server_ip, err := api.GetFirewallPolicyServerIp(fp_id, ip_id)` + + +**Add servers/IPs to a firewall policy:** + +`firewall, err := api.AddFirewallPolicyServerIps(fp_id, ip_ids)` + +`ip_ids` is a slice of IP ID's. + + +**Remove a server/IP from a firewall policy:** + +`firewall, err := api.DeleteFirewallPolicyServerIp(fp_id, ip_id)` + + +**List rules of a firewall policy:** + +`fp_rules, err := api.ListFirewallPolicyRules(fp_id)` + + +**Retrieve information about a rule of a firewall policy:** + +`fp_rule, err := api.GetFirewallPolicyRule(fp_id, rule_id)` + + +**Adds new rules to a firewall policy:** + +``` +fp_rules := []oneandone.FirewallPolicyRule { + { + Protocol: protocol1, + PortFrom: oneandone.Int2Pointer(port_from1), + PortTo: oneandone.Int2Pointer(port_to1), + SourceIp: source_ip, + }, + { + Protocol: protocol2, + PortFrom: oneandone.Int2Pointer(port_from2), + PortTo: oneandone.Int2Pointer(port_to2), + }, + } + +firewall, err := api.AddFirewallPolicyRules(fp_id, fp_rules) +``` + +**Remove a rule from a firewall policy:** + +`firewall, err := api.DeleteFirewallPolicyRule(fp_id, rule_id)` + + +### Load Balancers + +**List load balancers:** + +`loadbalancers, err := api.ListLoadBalancers()` + +Alternatively, use the method with query parameters. + +`loadbalancers, err := api.ListLoadBalancers(page, per_page, sort, query, fields)` + +To paginate the list of load balancers received in the response use `page` and `per_page` parameters. Set `per_page` to the number of load balancers that will be shown in each page. `page` indicates the current page. When set to an integer value that is less or equal to zero, the parameters are ignored by the framework. + +To receive the list of load balancers sorted in expected order pass a load balancer property (e.g. `"name"`) in `sort` parameter. Prefix the sorting attribute with `-` sign for sorting in descending order. + +Use `query` parameter to search for a string in the response and return only the load balancer instances that contain it. + +To retrieve a collection of load balancers containing only the requested fields pass a list of comma separated properties (e.g. `"ip,name,method"`) in `fields` parameter. + +If any of the parameters `sort`, `query` or `fields` is set to an empty string, it is ignored in the request. + +**Retrieve a single load balancer:** + +`loadbalancer, err := api.GetLoadBalancer(lb_id)` + + +**Create a load balancer:** + +``` +request := oneandone.LoadBalancerRequest { + Name: lb_name, + Description: lb_description, + Method: lb_method, + Persistence: oneandone.Bool2Pointer(true_or_false), + PersistenceTime: oneandone.Int2Pointer(seconds1), + HealthCheckTest: protocol1, + HealthCheckInterval: oneandone.Int2Pointer(seconds2), + HealthCheckPath: health_check_path, + HealthCheckPathParser: health_check_path_parser, + Rules: []oneandone.LoadBalancerRule { + { + Protocol: protocol1, + PortBalancer: lb_port, + PortServer: server_port, + Source: source_ip, + }, + }, + } + +loadbalancer_id, loadbalancer, err := api.CreateLoadBalancer(&request) +``` +Optional parameters are `HealthCheckPath`, `HealthCheckPathParser`, `Source` and `Description`. Load balancer `Method` must be set to `"ROUND_ROBIN"` or `"LEAST_CONNECTIONS"`. + +**Update a load balancer:** +``` +request := oneandone.LoadBalancerRequest { + Name: new_name, + Description: new_description, + Persistence: oneandone.Bool2Pointer(true_or_false), + PersistenceTime: oneandone.Int2Pointer(new_seconds1), + HealthCheckTest: new_protocol, + HealthCheckInterval: oneandone.Int2Pointer(new_seconds2), + HealthCheckPath: new_path, + HealthCheckPathParser: new_parser, + Method: new_lb_method, + } + +loadbalancer, err := api.UpdateLoadBalancer(lb_id, &request) +``` +All updatable fields are optional. + + +**Delete a load balancer:** + +`loadbalancer, err := api.DeleteLoadBalancer(lb_id)` + + +**List servers/IPs attached to a load balancer:** + +`server_ips, err := api.ListLoadBalancerServerIps(lb_id)` + + +**Retrieve information about a server/IP assigned to a load balancer:** + +`server_ip, err := api.GetLoadBalancerServerIp(lb_id, ip_id)` + + +**Add servers/IPs to a load balancer:** + +`loadbalancer, err := api.AddLoadBalancerServerIps(lb_id, ip_ids)` + +`ip_ids` is a slice of IP ID's. + + +**Remove a server/IP from a load balancer:** + +`loadbalancer, err := api.DeleteLoadBalancerServerIp(lb_id, ip_id)` + + +**List rules of a load balancer:** + +`lb_rules, err := api.ListLoadBalancerRules(lb_id)` + + +**Retrieve information about a rule of a load balancer:** + +`lb_rule, err := api.GetLoadBalancerRule(lb_id, rule_id)` + + +**Adds new rules to a load balancer:** + +``` +lb_rules := []oneandone.LoadBalancerRule { + { + Protocol: protocol1, + PortBalancer: lb_port1, + PortServer: server_port1, + Source: source_ip, + }, + { + Protocol: protocol2, + PortBalancer: lb_port2, + PortServer: server_port2, + }, + } + +loadbalancer, err := api.AddLoadBalancerRules(lb_id, lb_rules) +``` + +**Remove a rule from a load balancer:** + +`loadbalancer, err := api.DeleteLoadBalancerRule(lb_id, rule_id)` + + +### Public IPs + +**Retrieve a list of your public IPs:** + +`public_ips, err := api.ListPublicIps()` + +Alternatively, use the method with query parameters. + +`public_ips, err := api.ListPublicIps(page, per_page, sort, query, fields)` + +To paginate the list of public IPs received in the response use `page` and `per_page` parameters. Set `per_page` to the number of public IPs that will be shown in each page. `page` indicates the current page. When set to an integer value that is less or equal to zero, the parameters are ignored by the framework. + +To receive the list of public IPs sorted in expected order pass a public IP property (e.g. `"ip"`) in `sort` parameter. Prefix the sorting attribute with `-` sign for sorting in descending order. + +Use `query` parameter to search for a string in the response and return only the public IP instances that contain it. + +To retrieve a collection of public IPs containing only the requested fields pass a list of comma separated properties (e.g. `"id,ip,reverse_dns"`) in `fields` parameter. + +If any of the parameters `sort`, `query` or `fields` is set to an empty string, it is ignored in the request. + + +**Retrieve a single public IP:** + +`public_ip, err := api.GetPublicIp(ip_id)` + + +**Create a public IP:** + +`ip_id, public_ip, err := api.CreatePublicIp(ip_type, reverse_dns)` + +Both parameters are optional and may be left blank. `ip_type` may be set to `"IPV4"` or `"IPV6"`. Presently, only IPV4 is supported. + +**Update the reverse DNS of a public IP:** + +`public_ip, err := api.UpdatePublicIp(ip_id, reverse_dns)` + +If an empty string is passed in `reverse_dns,` it removes previous reverse dns of the public IP. + +**Remove a public IP:** + +`public_ip, err := api.DeletePublicIp(ip_id)` + + +### Private Networks + +**List all private networks:** + +`private_nets, err := api.ListPrivateNetworks()` + +Alternatively, use the method with query parameters. + +`private_nets, err := api.ListPrivateNetworks(page, per_page, sort, query, fields)` + +To paginate the list of private networks received in the response use `page` and `per_page` parameters. Set `per_page` to the number of private networks that will be shown in each page. `page` indicates the current page. When set to an integer value that is less or equal to zero, the parameters are ignored by the framework. + +To receive the list of private networks sorted in expected order pass a private network property (e.g. `"-creation_date"`) in `sort` parameter. Prefix the sorting attribute with `-` sign for sorting in descending order. + +Use `query` parameter to search for a string in the response and return only the private network instances that contain it. + +To retrieve a collection of private networks containing only the requested fields pass a list of comma separated properties (e.g. `"id,name,creation_date"`) in `fields` parameter. + +If any of the parameters `sort`, `query` or `fields` is blank, it is ignored in the request. + +**Retrieve information about a private network:** + +`private_net, err := api.GetPrivateNetwork(pn_id)` + +**Create a new private network:** + +``` +request := oneandone.PrivateNetworkRequest { + Name: pn_name, + Description: pn_description, + NetworkAddress: network_address, + SubnetMask: subnet_mask, + } + +pnet_id, private_net, err := api.CreatePrivateNetwork(&request) +``` +Private network `Name` is required parameter. + + +**Modify a private network:** + +``` +request := oneandone.PrivateNetworkRequest { + Name: new_pn_name, + Description: new_pn_description, + NetworkAddress: new_network_address, + SubnetMask: new_subnet_mask, + } + +private_net, err := api.UpdatePrivateNetwork(pn_id, &request) +``` +All parameters in the request are optional. + + +**Delete a private network:** + +`private_net, err := api.DeletePrivateNetwork(pn_id)` + + +**List all servers attached to a private network:** + +`servers, err = := api.ListPrivateNetworkServers(pn_id)` + + +**Retrieve a server attached to a private network:** + +`server, err = := api.GetPrivateNetworkServer(pn_id, server_id)` + + +**Attach servers to a private network:** + +`private_net, err := api.AttachPrivateNetworkServers(pn_id, server_ids)` + +`server_ids` is a slice of server ID's. + +*Note:* Servers cannot be attached to a private network if they currently have a snapshot. + + +**Remove a server from a private network:** + +`private_net, err := api.DetachPrivateNetworkServer(pn_id, server_id)` + +*Note:* The server cannot be removed from a private network if it currently has a snapshot or it is powered on. + + +### VPNs + +**List all VPNs:** + +`vpns, err := api.ListVPNs()` + +Alternatively, use the method with query parameters. + +`vpns, err := api.ListVPNs(page, per_page, sort, query, fields)` + +To paginate the list of VPNs received in the response use `page` and `per_page` parameters. Set ` per_page` to the number of VPNs that will be shown in each page. `page` indicates the current page. When set to an integer value that is less or equal to zero, the parameters are ignored by the framework. + +To receive the list of VPNs sorted in expected order pass a VPN property (e.g. `"name"`) in `sort` parameter. Prefix the sorting attribute with `-` sign for sorting in descending order. + +Use `query` parameter to search for a string in the response and return only the VPN instances that contain it. + +To retrieve a collection of VPNs containing only the requested fields pass a list of comma separated properties (e.g. `"id,name,creation_date"`) in `fields` parameter. + +If any of the parameters `sort`, `query` or `fields` is set to an empty string, it is ignored in the request. + +**Retrieve information about a VPN:** + +`vpn, err := api.GetVPN(vpn_id)` + +**Create a VPN:** + +`vpn, err := api.CreateVPN(vpn_name, vpn_description, datacenter_id)` + +**Modify a VPN:** + +`vpn, err := api.ModifyVPN(vpn_id, new_name, new_description)` + +**Delete a VPN:** + +`vpn, err := api.DeleteVPN(vpn_id)` + +**Retrieve a VPN's configuration file:** + +`base64_encoded_string, err := api.GetVPNConfigFile(vpn_id)` + + +### Monitoring Center + +**List all usages and alerts of monitoring servers:** + +`server_usages, err := api.ListMonitoringServersUsages()` + +Alternatively, use the method with query parameters. + +`server_usages, err := api.ListMonitoringServersUsages(page, per_page, sort, query, fields)` + +To paginate the list of server usages received in the response use `page` and `per_page` parameters. Set `per_page` to the number of server usages that will be shown in each page. `page` indicates the current page. When set to an integer value that is less or equal to zero, the parameters are ignored by the framework. + +To receive the list of server usages sorted in expected order pass a server usage property (e.g. `"name"`) in `sort` parameter. Prefix the sorting attribute with `-` sign for sorting in descending order. + +Use `query` parameter to search for a string in the response and return only the usage instances that contain it. + +To retrieve a collection of server usages containing only the requested fields pass a list of comma separated properties (e.g. `"id,name,status.state"`) in `fields` parameter. + +If any of the parameters `sort`, `query` or `fields` is blank, it is ignored in the request. + +**Retrieve the usages and alerts for a monitoring server:** + +`server_usage, err := api.GetMonitoringServerUsage(server_id, period)` + +`period` may be set to `"LAST_HOUR"`, `"LAST_24H"`, `"LAST_7D"`, `"LAST_30D"`, `"LAST_365D"` or `"CUSTOM"`. If `period` is set to `"CUSTOM"`, the `start_date` and `end_date` parameters are required to be set in **RFC 3339** date/time format (e.g. `2015-13-12T00:01:00Z`). + +`server_usage, err := api.GetMonitoringServerUsage(server_id, period, start_date, end_date)` + +### Monitoring Policies + +**List all monitoring policies:** + +`mon_policies, err := api.ListMonitoringPolicies()` + +Alternatively, use the method with query parameters. + +`mon_policies, err := api.ListMonitoringPolicies(page, per_page, sort, query, fields)` + +To paginate the list of monitoring policies received in the response use `page` and `per_page` parameters. Set `per_page` to the number of monitoring policies that will be shown in each page. `page` indicates the current page. When set to an integer value that is less or equal to zero, the parameters are ignored by the framework. + +To receive the list of monitoring policies sorted in expected order pass a monitoring policy property (e.g. `"name"`) in `sort` parameter. Prefix the sorting attribute with `-` sign for sorting in descending order. + +Use `query` parameter to search for a string in the response and return only the monitoring policy instances that contain it. + +To retrieve a collection of monitoring policies containing only the requested fields pass a list of comma separated properties (e.g. `"id,name,creation_date"`) in `fields` parameter. + +If any of the parameters `sort`, `query` or `fields` is set to an empty string, it is ignored in the request. + +**Retrieve a single monitoring policy:** + +`mon_policy, err := api.GetMonitoringPolicy(mp_id)` + + +**Create a monitoring policy:** + +``` +request := oneandone.MonitoringPolicy { + Name: mp_name, + Description: mp_desc, + Email: mp_mail, + Agent: true_or_false, + Thresholds: &oneandone.MonitoringThreshold { + Cpu: &oneandone.MonitoringLevel { + Warning: &oneandone.MonitoringValue { + Value: threshold_value, + Alert: true_or_false, + }, + Critical: &oneandone.MonitoringValue { + Value: threshold_value, + Alert: true_or_false, + }, + }, + Ram: &oneandone.MonitoringLevel { + Warning: &oneandone.MonitoringValue { + Value: threshold_value, + Alert: true_or_false, + }, + Critical: &oneandone.MonitoringValue { + Value: threshold_value, + Alert: true_or_false, + }, + }, + Disk: &oneandone.MonitoringLevel { + Warning: &oneandone.MonitoringValue { + Value: threshold_value, + Alert: true_or_false, + }, + Critical: &oneandone.MonitoringValue { + Value: threshold_value, + Alert: true_or_false, + }, + }, + Transfer: &oneandone.MonitoringLevel { + Warning: &oneandone.MonitoringValue { + Value: threshold_value, + Alert: true_or_false, + }, + Critical: &oneandone.MonitoringValue { + Value: threshold_value, + Alert: true_or_false, + }, + }, + InternalPing: &oneandone.MonitoringLevel { + Warning: &oneandone.MonitoringValue { + Value: threshold_value, + Alert: true_or_false, + }, + Critical: &oneandone.MonitoringValue { + Value: threshold_value, + Alert: true_or_false, + }, + }, + }, + Ports: []oneandone.MonitoringPort { + { + Protocol: protocol, + Port: port, + AlertIf: responding_or_not_responding, + EmailNotification: true_or_false, + }, + }, + Processes: []oneandone.MonitoringProcess { + { + Process: process_name, + AlertIf: running_or_not_running, + EmailNotification: true_or_false, + }, + }, + } + +mpolicy_id, mon_policy, err := api.CreateMonitoringPolicy(&request) +``` +All fields, except `Description`, are required. `AlertIf` property accepts values `"RESPONDING"`/`"NOT_RESPONDING"` for ports, and `"RUNNING"`/`"NOT_RUNNING"` for processes. + + +**Update a monitoring policy:** + +``` +request := oneandone.MonitoringPolicy { + Name: new_mp_name, + Description: new_mp_desc, + Email: new_mp_mail, + Thresholds: &oneandone.MonitoringThreshold { + Cpu: &oneandone.MonitoringLevel { + Warning: &oneandone.MonitoringValue { + Value: new_threshold_value, + Alert: true_or_false, + }, + Critical: &oneandone.MonitoringValue { + Value: new_threshold_value, + Alert: true_or_false, + }, + }, + Ram: &oneandone.MonitoringLevel { + Warning: &oneandone.MonitoringValue { + Value: new_threshold_value, + Alert: true_or_false, + }, + Critical: &oneandone.MonitoringValue { + Value: new_threshold_value, + Alert: true_or_false, + }, + }, + Disk: &oneandone.MonitoringLevel { + Warning: &oneandone.MonitoringValue { + Value: new_threshold_value, + Alert: true_or_false, + }, + Critical: &oneandone.MonitoringValue { + Value: new_threshold_value, + Alert: true_or_false, + }, + }, + Transfer: &oneandone.MonitoringLevel { + Warning: &oneandone.MonitoringValue { + Value: new_threshold_value, + Alert: true_or_false, + }, + Critical: &oneandone.MonitoringValue { + Value: new_threshold_value, + Alert: true_or_false, + }, + }, + InternalPing: &oneandone.MonitoringLevel { + Warning: &oneandone.MonitoringValue { + Value: new_threshold_value, + Alert: true_or_false, + }, + Critical: &oneandone.MonitoringValue { + Value: new_threshold_value, + Alert: true_or_false, + }, + }, + }, + } + +mon_policy, err := api.UpdateMonitoringPolicy(mp_id, &request) +``` +All fields of the request are optional. When a threshold is specified in the request, the threshold fields are required. + +**Delete a monitoring policy:** + +`mon_policy, err := api.DeleteMonitoringPolicy(mp_id)` + + +**List all ports of a monitoring policy:** + +`mp_ports, err := api.ListMonitoringPolicyPorts(mp_id)` + + +**Retrieve information about a port of a monitoring policy:** + +`mp_port, err := api.GetMonitoringPolicyPort(mp_id, port_id)` + + +**Add new ports to a monitoring policy:** + +``` +mp_ports := []oneandone.MonitoringPort { + { + Protocol: protocol1, + Port: port1, + AlertIf: responding_or_not_responding, + EmailNotification: true_or_false, + }, + { + Protocol: protocol2, + Port: port2, + AlertIf: responding_or_not_responding, + EmailNotification: true_or_false, + }, + } + +mon_policy, err := api.AddMonitoringPolicyPorts(mp_id, mp_ports) +``` +Port properties are mandatory. + + +**Modify a port of a monitoring policy:** + +``` +mp_port := oneandone.MonitoringPort { + Protocol: protocol, + Port: port, + AlertIf: responding_or_not_responding, + EmailNotification: true_or_false, + } + +mon_policy, err := api.ModifyMonitoringPolicyPort(mp_id, port_id, &mp_port) +``` +*Note:* `Protocol` and `Port` cannot be changed. + + +**Remove a port from a monitoring policy:** + +`mon_policy, err := api.DeleteMonitoringPolicyPort(mp_id, port_id)` + + +**List the processes of a monitoring policy:** + +`mp_processes, err := api.ListMonitoringPolicyProcesses(mp_id)` + + +**Retrieve information about a process of a monitoring policy:** + +`mp_process, err := api.GetMonitoringPolicyProcess(mp_id, process_id)` + + +**Add new processes to a monitoring policy:** + +``` +processes := []oneandone.MonitoringProcess { + { + Process: process_name1, + AlertIf: running_or_not_running, + EmailNotification: true_or_false, + }, + { + Process: process_name2, + AlertIf: running_or_not_running, + EmailNotification: true_or_false, + }, + } + +mon_policy, err := api.AddMonitoringPolicyProcesses(mp_id, processes) +``` +All properties of the `MonitoringProcess` instance are required. + + +**Modify a process of a monitoring policy:** + +``` +process := oneandone.MonitoringProcess { + Process: process_name, + AlertIf: running_or_not_running, + EmailNotification: true_or_false, + } + +mon_policy, err := api.ModifyMonitoringPolicyProcess(mp_id, process_id, &process) +``` + +*Note:* Process name cannot be changed. + +**Remove a process from a monitoring policy:** + +`mon_policy, err := api.DeleteMonitoringPolicyProcess(mp_id, process_id)` + +**List all servers attached to a monitoring policy:** + +`mp_servers, err := api.ListMonitoringPolicyServers(mp_id)` + +**Retrieve information about a server attached to a monitoring policy:** + +`mp_server, err := api.GetMonitoringPolicyServer(mp_id, server_id)` + +**Attach servers to a monitoring policy:** + +`mon_policy, err := api.AttachMonitoringPolicyServers(mp_id, server_ids)` + +`server_ids` is a slice of server ID's. + +**Remove a server from a monitoring policy:** + +`mon_policy, err := api.RemoveMonitoringPolicyServer(mp_id, server_id)` + + +### Logs + +**List all logs:** + +`logs, err := api.ListLogs(period, nil, nil)` + +`period` can be set to `"LAST_HOUR"`, `"LAST_24H"`, `"LAST_7D"`, `"LAST_30D"`, `"LAST_365D"` or `"CUSTOM"`. If `period` is set to `"CUSTOM"`, the `start_date` and `end_date` parameters are required to be set in **RFC 3339** date/time format (e.g. `2015-13-12T00:01:00Z`). + +`logs, err := api.ListLogs(period, start_date, end_date)` + +Additional query parameters can be used. + +`logs, err := api.ListLogs(period, start_date, end_date, page, per_page, sort, query, fields)` + +To paginate the list of logs received in the response use `page` and `per_page` parameters. Set ` per_page` to the number of logs that will be shown in each page. `page` indicates the current page. When set to an integer value that is less or equal to zero, the parameters are ignored by the framework. + +To receive the list of logs sorted in expected order pass a logs property (e.g. `"action"`) in `sort` parameter. Prefix the sorting attribute with `-` sign for sorting in descending order. + +Use `query` parameter to search for a string in the response and return only the logs instances that contain it. + +To retrieve a collection of logs containing only the requested fields pass a list of comma separated properties (e.g. `"id,action,type"`) in `fields` parameter. + +If any of the parameters `sort`, `query` or `fields` is set to an empty string, it is ignored in the request. + +**Retrieve a single log:** + +`log, err := api.GetLog(log_id)` + + +### Users + +**List all users:** + +`users, err := api.ListUsers()` + +Alternatively, use the method with query parameters. + +`users, err := api.ListUsers(page, per_page, sort, query, fields)` + +To paginate the list of users received in the response use `page` and `per_page` parameters. Set ` per_page` to the number of users that will be shown in each page. `page` indicates the current page. When set to an integer value that is less or equal to zero, the parameters are ignored by the framework. + +To receive the list of users sorted in expected order pass a user property (e.g. `"name"`) in `sort` parameter. Prefix the sorting attribute with `-` sign for sorting in descending order. + +Use `query` parameter to search for a string in the response and return only the user instances that contain it. + +To retrieve a collection of users containing only the requested fields pass a list of comma separated properties (e.g. `"id,name,creation_date,email"`) in `fields` parameter. + +If any of the parameters `sort`, `query` or `fields` is set to an empty string, it is ignored in the request. + +**Retrieve information about a user:** + +`user, err := api.GetUser(user_id)` + +**Create a user:** + +``` +request := oneandone.UserRequest { + Name: username, + Description: user_description, + Password: password, + Email: user_email, + } + +user_id, user, err := api.CreateUser(&request) +``` + +`Name` and `Password` are required parameters. The password must contain at least 8 characters using uppercase letters, numbers and other special symbols. + +**Modify a user:** + +``` +request := oneandone.UserRequest { + Description: new_desc, + Email: new_mail, + Password: new_pass, + State: state, + } + +user, err := api.ModifyUser(user_id, &request) +``` + +All listed fields in the request are optional. `State` can be set to `"ACTIVE"` or `"DISABLED"`. + +**Delete a user:** + +`user, err := api.DeleteUser(user_id)` + +**Retrieve information about a user's API privileges:** + +`api_info, err := api.GetUserApi(user_id)` + +**Retrieve a user's API key:** + +`api_key, err := api.GetUserApiKey(user_id)` + +**List IP's from which API access is allowed for a user:** + +`allowed_ips, err := api.ListUserApiAllowedIps(user_id)` + +**Add new IP's to a user:** + +``` +user_ips := []string{ my_public_ip, "192.168.7.77", "10.81.12.101" } +user, err := api.AddUserApiAlowedIps(user_id, user_ips) +``` + +**Remove an IP and forbid API access from it:** + +`user, err := api.RemoveUserApiAllowedIp(user_id, ip)` + +**Modify a user's API privileges:** + +`user, err := api.ModifyUserApi(user_id, is_active)` + +**Renew a user's API key:** + +`user, err := api.RenewUserApiKey(user_id)` + +**Retrieve current user permissions:** + +`permissions, err := api.GetCurrentUserPermissions()` + + +### Roles + +**List all roles:** + +`roles, err := api.ListRoles()` + +Alternatively, use the method with query parameters. + +`roles, err := api.ListRoles(page, per_page, sort, query, fields)` + +To paginate the list of roles received in the response use `page` and `per_page` parameters. Set ` per_page` to the number of roles that will be shown in each page. `page` indicates the current page. When set to an integer value that is less or equal to zero, the parameters are ignored by the framework. + +To receive the list of roles sorted in expected order pass a role property (e.g. `"name"`) in `sort` parameter. Prefix the sorting attribute with `-` sign for sorting in descending order. + +Use `query` parameter to search for a string in the response and return only the role instances that contain it. + +To retrieve a collection of roles containing only the requested fields pass a list of comma separated properties (e.g. `"id,name,creation_date"`) in `fields` parameter. + +If any of the parameters `sort`, `query` or `fields` is set to an empty string, it is ignored in the request. + +**Retrieve information about a role:** + +`role, err := api.GetRole(role_id)` + +**Create a role:** + +`role, err := api.CreateRole(role_name)` + +**Clone a role:** + +`role, err := api.CloneRole(role_id, new_role_name)` + +**Modify a role:** + +`role, err := api.ModifyRole(role_id, new_name, new_description, new_state)` + +`ACTIVE` and `DISABLE` are valid values for the state. + +**Delete a role:** + +`role, err := api.DeleteRole(role_id)` + +**Retrieve information about a role's permissions:** + +`permissions, err := api.GetRolePermissions(role_id)` + +**Modify a role's permissions:** + +`role, err := api.ModifyRolePermissions(role_id, permissions)` + +**Assign users to a role:** + +`role, err := api.AssignRoleUsers(role_id, user_ids)` + +`user_ids` is a slice of user ID's. + +**List a role's users:** + +`users, err := api.ListRoleUsers(role_id)` + +**Retrieve information about a role's user:** + +`user, err := api.GetRoleUser(role_id, user_id)` + +**Remove a role's user:** + +`role, err := api.RemoveRoleUser(role_id, user_id)` + + +### Usages + +**List your usages:** + +`usages, err := api.ListUsages(period, nil, nil)` + +`period` can be set to `"LAST_HOUR"`, `"LAST_24H"`, `"LAST_7D"`, `"LAST_30D"`, `"LAST_365D"` or `"CUSTOM"`. If `period` is set to `"CUSTOM"`, the `start_date` and `end_date` parameters are required to be set in **RFC 3339** date/time format (e.g. `2015-13-12T00:01:00Z`). + +`usages, err := api.ListUsages(period, start_date, end_date)` + +Additional query parameters can be used. + +`usages, err := api.ListUsages(period, start_date, end_date, page, per_page, sort, query, fields)` + +To paginate the list of usages received in the response use `page` and `per_page` parameters. Set ` per_page` to the number of usages that will be shown in each page. `page` indicates the current page. When set to an integer value that is less or equal to zero, the parameters are ignored by the framework. + +To receive the list of usages sorted in expected order pass a usages property (e.g. `"name"`) in `sort` parameter. Prefix the sorting attribute with `-` sign for sorting in descending order. + +Use `query` parameter to search for a string in the response and return only the usages instances that contain it. + +To retrieve a collection of usages containing only the requested fields pass a list of comma separated properties (e.g. `"id,name"`) in `fields` parameter. + +If any of the parameters `sort`, `query` or `fields` is set to an empty string, it is ignored in the request. + + +### Server Appliances + +**List all the appliances that you can use to create a server:** + +`server_appliances, err := api.ListServerAppliances()` + +Alternatively, use the method with query parameters. + +`server_appliances, err := api.ListServerAppliances(page, per_page, sort, query, fields)` + +To paginate the list of server appliances received in the response use `page` and `per_page` parameters. Set `per_page` to the number of server appliances that will be shown in each page. `page` indicates the current page. When set to an integer value that is less or equal to zero, the parameters are ignored by the framework. + +To receive the list of server appliances sorted in expected order pass a server appliance property (e.g. `"os"`) in `sort` parameter. Prefix the sorting attribute with `-` sign for sorting in descending order. + +Use `query` parameter to search for a string in the response and return only the server appliance instances that contain it. + +To retrieve a collection of server appliances containing only the requested fields pass a list of comma separated properties (e.g. `"id,os,architecture"`) in `fields` parameter. + +If any of the parameters `sort`, `query` or `fields` is blank, it is ignored in the request. + +**Retrieve information about specific appliance:** + +`server_appliance, err := api.GetServerAppliance(appliance_id)` + + +### DVD ISO + +**List all operative systems and tools that you can load into your virtual DVD unit:** + +`dvd_isos, err := api.ListDvdIsos()` + +Alternatively, use the method with query parameters. + +`dvd_isos, err := api.ListDvdIsos(page, per_page, sort, query, fields)` + +To paginate the list of ISO DVDs received in the response use `page` and `per_page` parameters. Set `per_page` to the number of ISO DVDs that will be shown in each page. `page` indicates the current page. When set to an integer value that is less or equal to zero, the parameters are ignored by the framework. + +To receive the list of ISO DVDs sorted in expected order pass a ISO DVD property (e.g. `"type"`) in `sort` parameter. Prefix the sorting attribute with `-` sign for sorting in descending order. + +Use `query` parameter to search for a string in the response and return only the ISO DVD instances that contain it. + +To retrieve a collection of ISO DVDs containing only the requested fields pass a list of comma separated properties (e.g. `"id,name,type"`) in `fields` parameter. + +If any of the parameters `sort`, `query` or `fields` is blank, it is ignored in the request. + +**Retrieve a specific ISO image:** + +`dvd_iso, err := api.GetDvdIso(dvd_id)` + + +### Ping + +**Check if 1&1 REST API is running:** + +`response, err := api.Ping()` + +If the API is running, the response is a single-element slice `["PONG"]`. + +**Validate if 1&1 REST API is running and the authorization token is valid:** + +`response, err := api.PingAuth()` + +The response should be a single-element slice `["PONG"]` if the API is running and the token is valid. + + +### Pricing + +**Show prices for all available resources in the Cloud Panel:** + +`pricing, err := api.GetPricing()` + + +### Data Centers + +**List all 1&1 Cloud Server data centers:** + +`datacenters, err := api.ListDatacenters()` + +Here is another example of an alternative form of the list function that includes query parameters. + +`datacenters, err := api.ListDatacenters(0, 0, "country_code", "DE", "id,country_code")` + +**Retrieve a specific data center:** + +`datacenter, err := api.GetDatacenter(datacenter_id)` + + +## Examples + +```Go +package main + +import ( + "fmt" + "github.com/1and1/oneandone-cloudserver-sdk-go" + "time" +) + +func main() { + //Set an authentication token + token := oneandone.SetToken("82ee732b8d47e451be5c6ad5b7b56c81") + //Create an API client + api := oneandone.New(token, oneandone.BaseUrl) + + // List server appliances + saps, err := api.ListServerAppliances() + + var sa oneandone.ServerAppliance + for _, a := range saps { + if a.Type == "IMAGE" { + sa = a + } + } + + // Create a server + req := oneandone.ServerRequest{ + Name: "Example Server", + Description: "Example server description.", + ApplianceId: sa.Id, + PowerOn: true, + Hardware: oneandone.Hardware{ + Vcores: 1, + CoresPerProcessor: 1, + Ram: 2, + Hdds: []oneandone.Hdd { + oneandone.Hdd { + Size: sa.MinHddSize, + IsMain: true, + }, + }, + }, + } + + server_id, server, err := api.CreateServer(&req) + + if err == nil { + // Wait until server is created and powered on for at most 60 x 10 seconds + err = api.WaitForState(server, "POWERED_ON", 10, 60) + } + + // Get the server + server, err = api.GetServer(server_id) + + // Create a load balancer + lbr := oneandone.LoadBalancerRequest { + Name: "Load Balancer Example", + Description: "API created load balancer.", + Method: "ROUND_ROBIN", + Persistence: oneandone.Bool2Pointer(true), + PersistenceTime: oneandone.Int2Pointer(1200), + HealthCheckTest: "TCP", + HealthCheckInterval: oneandone.Int2Pointer(40), + Rules: []oneandone.LoadBalancerRule { + { + Protocol: "TCP", + PortBalancer: 80, + PortServer: 80, + Source: "0.0.0.0", + }, + }, + } + + var lb *oneandone.LoadBalancer + var lb_id string + + lb_id, lb, err = api.CreateLoadBalancer(&lbr) + if err != nil { + api.WaitForState(lb, "ACTIVE", 10, 30) + } + + // Get the load balancer + lb, err = api.GetLoadBalancer(lb.Id) + + // Assign the load balancer to server's IP + server, err = api.AssignServerIpLoadBalancer(server.Id, server.Ips[0].Id, lb_id) + + // Create a firewall policy + fpr := oneandone.FirewallPolicyRequest{ + Name: "Firewall Policy Example", + Description: "API created firewall policy.", + Rules: []oneandone.FirewallPolicyRule { + { + Protocol: "TCP", + PortFrom: oneandone.Int2Pointer(80), + PortTo: oneandone.Int2Pointer(80), + }, + }, + } + + var fp *oneandone.FirewallPolicy + + fp_id, fp, err = api.CreateFirewallPolicy(&fpr) + if err == nil { + api.WaitForState(fp, "ACTIVE", 10, 30) + } + + // Get the firewall policy + fp, err = api.GetFirewallPolicy(fp_id) + + // Add servers IPs to the firewall policy. + ips := []string{ server.Ips[0].Id } + + fp, err = api.AddFirewallPolicyServerIps(fp.Id, ips) + if err == nil { + api.WaitForState(fp, "ACTIVE", 10, 60) + } + + //Shutdown the server using 'SOFTWARE' method + server, err = api.ShutdownServer(server.Id, false) + if err != nil { + err = api.WaitForState(server, "POWERED_OFF", 5, 20) + } + + // Delete the load balancer + lb, err = api.DeleteLoadBalancer(lb.Id) + if err != nil { + err = api.WaitUntilDeleted(lb) + } + + // Delete the firewall policy + fp, err = api.DeleteFirewallPolicy(fp.Id) + if err != nil { + err = api.WaitUntilDeleted(fp) + } + + // List usages in last 24h + var usages *oneandone.Usages + usages, err = api.ListUsages("LAST_24H", nil, nil) + + fmt.Println(usages.Servers) + + // List usages in last 5 hours + n := time.Now() + ed := time.Date(n.Year(), n.Month(), n.Day(), n.Hour(), n.Minute(), n.Second(), 0, time.UTC) + sd := ed.Add(-(time.Hour * 5)) + + usages, err = api.ListUsages("CUSTOM", &sd, &ed) + + //Create a shared storage + ssr := oneandone.SharedStorageRequest { + Name: "Shared Storage Example", + Description: "API alocated 100 GB disk.", + Size: oneandone.Int2Pointer(100), + } + + var ss *oneandone.SharedStorage + var ss_id string + + ss_id, ss, err = api.CreateSharedStorage(&ssr) + if err != nil { + api.WaitForState(ss, "ACTIVE", 10, 30) + } + + // List shared storages on page 1, 5 results per page and sort by 'name' field. + // Include only 'name', 'size' and 'minimum_size_allowed' fields in the result. + var shs []oneandone.SharedStorage + shs, err = api.ListSharedStorages(1, 5, "name", "", "name,size,minimum_size_allowed") + + // List all shared storages that contain 'example' string + shs, err = api.ListSharedStorages(0, 0, "", "example", "") + + // Delete the shared storage + ss, err = api.DeleteSharedStorage(ss_id) + if err == nil { + err = api.WaitUntilDeleted(ss) + } + + // Delete the server + server, err = api.DeleteServer(server.Id, false) + if err == nil { + err = api.WaitUntilDeleted(server) + } +} + +``` +The next example illustrates how to create a `TYPO3` application server of a fixed size with an initial password and a firewall policy that has just been created. + +```Go +package main + +import "github.com/1and1/oneandone-cloudserver-sdk-go" + +func main() { + token := oneandone.SetToken("bde36026df9d548f699ea97e75a7e87f") + client := oneandone.New(token, oneandone.BaseUrl) + + // Create a new firewall policy + fpr := oneandone.FirewallPolicyRequest{ + Name: "HTTPS Traffic Policy", + Rules: []oneandone.FirewallPolicyRule{ + { + Protocol: "TCP", + PortFrom: oneandone.Int2Pointer(443), + PortTo: oneandone.Int2Pointer(443), + }, + }, + } + + _, fp, err := client.CreateFirewallPolicy(&fpr) + if fp != nil && err == nil { + client.WaitForState(fp, "ACTIVE", 5, 60) + + // Look for the TYPO3 application appliance + saps, _ := client.ListServerAppliances(0, 0, "", "typo3", "") + + var sa oneandone.ServerAppliance + for _, a := range saps { + if a.Type == "APPLICATION" { + sa = a + break + } + } + + var fixed_flavours []oneandone.FixedInstanceInfo + var fixed_size_id string + + fixed_flavours, err = client.ListFixedInstanceSizes() + for _, fl := range fixed_flavours { + //look for 'M' size + if fl.Name == "M" { + fixed_size_id = fl.Id + break + } + } + + req := oneandone.ServerRequest{ + Name: "TYPO3 Server", + ApplianceId: sa.Id, + PowerOn: true, + Password: "ucr_kXW8,.2SdMU", + Hardware: oneandone.Hardware{ + FixedInsSizeId: fixed_size_id, + }, + FirewallPolicyId: fp.Id, + } + _, server, _ := client.CreateServer(&req) + if server != nil { + client.WaitForState(server, "POWERED_ON", 10, 90) + } + } +} +``` + + +## Index + +```Go +func New(token string, url string) *API +``` + +```Go +func (api *API) AddFirewallPolicyRules(fp_id string, fp_rules []FirewallPolicyRule) (*FirewallPolicy, error) +``` + +```Go +func (api *API) AddFirewallPolicyServerIps(fp_id string, ip_ids []string) (*FirewallPolicy, error) +``` + +```Go +func (api *API) AddLoadBalancerRules(lb_id string, lb_rules []LoadBalancerRule) (*LoadBalancer, error) +``` + +```Go +func (api *API) AddLoadBalancerServerIps(lb_id string, ip_ids []string) (*LoadBalancer, error) +``` + +```Go +func (api *API) AddMonitoringPolicyPorts(mp_id string, mp_ports []MonitoringPort) (*MonitoringPolicy, error) +``` + +```Go +func (api *API) AddMonitoringPolicyProcesses(mp_id string, mp_procs []MonitoringProcess) (*MonitoringPolicy, error) +``` + +```Go +func (api *API) AddServerHdds(server_id string, hdds *ServerHdds) (*Server, error) +``` + +```Go +func (api *API) AddSharedStorageServers(st_id string, servers []SharedStorageServer) (*SharedStorage, error) +``` + +```Go +func (api *API) AddUserApiAlowedIps(user_id string, ips []string) (*User, error) +``` + +```Go +func (api *API) AssignRoleUsers(role_id string, user_ids []string) (*Role, error) +``` + +```Go +func (api *API) AssignServerIp(server_id string, ip_type string) (*Server, error) +``` + +```Go +func (api *API) AssignServerIpFirewallPolicy(server_id string, ip_id string, fp_id string) (*Server, error) +``` + +```Go +func (api *API) AssignServerIpLoadBalancer(server_id string, ip_id string, lb_id string) (*Server, error) +``` + +```Go +func (api *API) AssignServerPrivateNetwork(server_id string, pn_id string) (*Server, error) +``` + +```Go +func (api *API) AttachMonitoringPolicyServers(mp_id string, sids []string) (*MonitoringPolicy, error) +``` + +```Go +func (api *API) AttachPrivateNetworkServers(pn_id string, sids []string) (*PrivateNetwork, error) +``` + +```Go +func (api *API) CloneRole(role_id string, name string) (*Role, error) +``` + +```Go +func (api *API) CloneServer(server_id string, new_name string, datacenter_id string) (*Server, error) +``` + +```Go +func (api *API) CreateFirewallPolicy(fp_data *FirewallPolicyRequest) (string, *FirewallPolicy, error) +``` + +```Go +func (api *API) CreateImage(request *ImageConfig) (string, *Image, error) +``` + +```Go +func (api *API) CreateLoadBalancer(request *LoadBalancerRequest) (string, *LoadBalancer, error) +``` + +```Go +func (api *API) CreateMonitoringPolicy(mp *MonitoringPolicy) (string, *MonitoringPolicy, error) +``` + +```Go +func (api *API) CreatePrivateNetwork(request *PrivateNetworkRequest) (string, *PrivateNetwork, error) +``` + +```Go +func (api *API) CreatePublicIp(ip_type string, reverse_dns string, datacenter_id string) (string, *PublicIp, error) +``` + +```Go +func (api *API) CreateRole(name string) (string, *Role, error) +``` + +```Go +func (api *API) CreateServer(request *ServerRequest) (string, *Server, error) +``` + +```Go +func (api *API) CreateServerEx(request *ServerRequest, timeout int) (string, string, error) +``` + +```Go +func (api *API) CreateServerSnapshot(server_id string) (*Server, error) +``` + +```Go +func (api *API) CreateSharedStorage(request *SharedStorageRequest) (string, *SharedStorage, error) +``` + +```Go +func (api *API) CreateUser(user *UserRequest) (string, *User, error) +``` + +```Go +func (api *API) CreateVPN(name string, description string, datacenter_id string) (string, *VPN, error) +``` + +```Go +func (api *API) DeleteFirewallPolicy(fp_id string) (*FirewallPolicy, error) +``` + +```Go +func (api *API) DeleteFirewallPolicyRule(fp_id string, rule_id string) (*FirewallPolicy, error) +``` + +```Go +func (api *API) DeleteFirewallPolicyServerIp(fp_id string, ip_id string) (*FirewallPolicy, error) +``` + +```Go +func (api *API) DeleteImage(img_id string) (*Image, error) +``` + +```Go +func (api *API) DeleteLoadBalancer(lb_id string) (*LoadBalancer, error) +``` + +```Go +func (api *API) DeleteLoadBalancerRule(lb_id string, rule_id string) (*LoadBalancer, error) +``` + +```Go +func (api *API) DeleteLoadBalancerServerIp(lb_id string, ip_id string) (*LoadBalancer, error) +``` + +```Go +func (api *API) DeleteMonitoringPolicy(mp_id string) (*MonitoringPolicy, error) +``` + +```Go +func (api *API) DeleteMonitoringPolicyPort(mp_id string, port_id string) (*MonitoringPolicy, error) +``` + +```Go +func (api *API) DeleteMonitoringPolicyProcess(mp_id string, proc_id string) (*MonitoringPolicy, error) +``` + +```Go +func (api *API) DeletePrivateNetwork(pn_id string) (*PrivateNetwork, error) +``` + +```Go +func (api *API) DeletePublicIp(ip_id string) (*PublicIp, error) +``` + +```Go +func (api *API) DeleteRole(role_id string) (*Role, error) +``` + +```Go +func (api *API) DeleteServer(server_id string, keep_ips bool) (*Server, error) +``` + +```Go +func (api *API) DeleteServerHdd(server_id string, hdd_id string) (*Server, error) +``` + +```Go +func (api *API) DeleteServerIp(server_id string, ip_id string, keep_ip bool) (*Server, error) +``` + +```Go +func (api *API) DeleteServerSnapshot(server_id string, snapshot_id string) (*Server, error) +``` + +```Go +func (api *API) DeleteSharedStorage(ss_id string) (*SharedStorage, error) +``` + +```Go +func (api *API) DeleteSharedStorageServer(st_id string, ser_id string) (*SharedStorage, error) +``` + +```Go +func (api *API) DeleteUser(user_id string) (*User, error) +``` + +```Go +func (api *API) DeleteVPN(vpn_id string) (*VPN, error) +``` + +```Go +func (api *API) DetachPrivateNetworkServer(pn_id string, pns_id string) (*PrivateNetwork, error) +``` + +```Go +func (api *API) EjectServerDvd(server_id string) (*Server, error) +``` + +```Go +func (api *API) GetCurrentUserPermissions() (*Permissions, error) +``` + +```Go +func (api *API) GetDatacenter(dc_id string) (*Datacenter, error) +``` + +```Go +func (api *API) GetDvdIso(dvd_id string) (*DvdIso, error) +``` + +```Go +func (api *API) GetFirewallPolicy(fp_id string) (*FirewallPolicy, error) +``` + +```Go +func (api *API) GetFirewallPolicyRule(fp_id string, rule_id string) (*FirewallPolicyRule, error) +``` + +```Go +func (api *API) GetFirewallPolicyServerIp(fp_id string, ip_id string) (*ServerIpInfo, error) +``` + +```Go +func (api *API) GetFixedInstanceSize(fis_id string) (*FixedInstanceInfo, error) +``` + +```Go +func (api *API) GetImage(img_id string) (*Image, error) +``` + +```Go +func (api *API) GetLoadBalancer(lb_id string) (*LoadBalancer, error) +``` + +```Go +func (api *API) GetLoadBalancerRule(lb_id string, rule_id string) (*LoadBalancerRule, error) +``` + +```Go +func (api *API) GetLoadBalancerServerIp(lb_id string, ip_id string) (*ServerIpInfo, error) +``` + +```Go +func (api *API) GetLog(log_id string) (*Log, error) +``` + +```Go +func (api *API) GetMonitoringPolicy(mp_id string) (*MonitoringPolicy, error) +``` + +```Go +func (api *API) GetMonitoringPolicyPort(mp_id string, port_id string) (*MonitoringPort, error) +``` + +```Go +func (api *API) GetMonitoringPolicyProcess(mp_id string, proc_id string) (*MonitoringProcess, error) +``` + +```Go +func (api *API) GetMonitoringPolicyServer(mp_id string, ser_id string) (*Identity, error) +``` + +```Go +func (api *API) GetMonitoringServerUsage(ser_id string, period string, dates ...time.Time) (*MonServerUsageDetails, error) +``` + +```Go +func (api *API) GetPricing() (*Pricing, error) +``` + +```Go +func (api *API) GetPrivateNetwork(pn_id string) (*PrivateNetwork, error) +``` + +```Go +func (api *API) GetPrivateNetworkServer(pn_id string, server_id string) (*Identity, error) +``` + +```Go +func (api *API) GetPublicIp(ip_id string) (*PublicIp, error) +``` + +```Go +func (api *API) GetRole(role_id string) (*Role, error) +``` + +```Go +func (api *API) GetRolePermissions(role_id string) (*Permissions, error) +``` + +```Go +func (api *API) GetRoleUser(role_id string, user_id string) (*Identity, error) +``` + +```Go +func (api *API) GetServer(server_id string) (*Server, error) +``` + +```Go +func (api *API) GetServerAppliance(sa_id string) (*ServerAppliance, error) +``` + +```Go +func (api *API) GetServerDvd(server_id string) (*Identity, error) +``` + +```Go +func (api *API) GetServerHardware(server_id string) (*Hardware, error) +``` + +```Go +func (api *API) GetServerHdd(server_id string, hdd_id string) (*Hdd, error) +``` + +```Go +func (api *API) GetServerImage(server_id string) (*Identity, error) +``` + +```Go +func (api *API) GetServerIp(server_id string, ip_id string) (*ServerIp, error) +``` + +```Go +func (api *API) GetServerIpFirewallPolicy(server_id string, ip_id string) (*Identity, error) +``` + +```Go +func (api *API) GetServerPrivateNetwork(server_id string, pn_id string) (*PrivateNetwork, error) +``` + +```Go +func (api *API) GetServerSnapshot(server_id string) (*ServerSnapshot, error) +``` + +```Go +func (api *API) GetServerStatus(server_id string) (*Status, error) +``` + +```Go +func (api *API) GetSharedStorage(ss_id string) (*SharedStorage, error) +``` + +```Go +func (api *API) GetSharedStorageCredentials() ([]SharedStorageAccess, error) +``` + +```Go +func (api *API) GetSharedStorageServer(st_id string, ser_id string) (*SharedStorageServer, error) +``` + +```Go +func (api *API) GetUser(user_id string) (*User, error) +``` + +```Go +func (api *API) GetUserApi(user_id string) (*UserApi, error) +``` + +```Go +func (api *API) GetUserApiKey(user_id string) (*UserApiKey, error) +``` + +```Go +func (api *API) GetVPN(vpn_id string) (*VPN, error) +``` + +```Go +func (api *API) GetVPNConfigFile(vpn_id string) (string, error) +``` + +```Go +func (api *API) ListDatacenters(args ...interface{}) ([]Datacenter, error) +``` + +```Go +func (api *API) ListDvdIsos(args ...interface{}) ([]DvdIso, error) +``` + +```Go +func (api *API) ListFirewallPolicies(args ...interface{}) ([]FirewallPolicy, error) +``` + +```Go +func (api *API) ListFirewallPolicyRules(fp_id string) ([]FirewallPolicyRule, error) +``` + +```Go +func (api *API) ListFirewallPolicyServerIps(fp_id string) ([]ServerIpInfo, error) +``` + +```Go +func (api *API) ListFixedInstanceSizes() ([]FixedInstanceInfo, error) +``` + +```Go +func (api *API) ListImages(args ...interface{}) ([]Image, error) +``` + +```Go +func (api *API) ListLoadBalancerRules(lb_id string) ([]LoadBalancerRule, error) +``` + +```Go +func (api *API) ListLoadBalancerServerIps(lb_id string) ([]ServerIpInfo, error) +``` + +```Go +func (api *API) ListLoadBalancers(args ...interface{}) ([]LoadBalancer, error) +``` + +```Go +func (api *API) ListLogs(period string, sd *time.Time, ed *time.Time, args ...interface{}) ([]Log, error) +``` + +```Go +func (api *API) ListMonitoringPolicies(args ...interface{}) ([]MonitoringPolicy, error) +``` + +```Go +func (api *API) ListMonitoringPolicyPorts(mp_id string) ([]MonitoringPort, error) +``` + +```Go +func (api *API) ListMonitoringPolicyProcesses(mp_id string) ([]MonitoringProcess, error) +``` + +```Go +func (api *API) ListMonitoringPolicyServers(mp_id string) ([]Identity, error) +``` + +```Go +func (api *API) ListMonitoringServersUsages(args ...interface{}) ([]MonServerUsageSummary, error) +``` + +```Go +func (api *API) ListPrivateNetworkServers(pn_id string) ([]Identity, error) +``` + +```Go +func (api *API) ListPrivateNetworks(args ...interface{}) ([]PrivateNetwork, error) +``` + +```Go +func (api *API) ListPublicIps(args ...interface{}) ([]PublicIp, error) +``` + +```Go +func (api *API) ListRoleUsers(role_id string) ([]Identity, error) +``` + +```Go +func (api *API) ListRoles(args ...interface{}) ([]Role, error) +``` + +```Go +func (api *API) ListServerAppliances(args ...interface{}) ([]ServerAppliance, error) +``` + +```Go +func (api *API) ListServerHdds(server_id string) ([]Hdd, error) +``` + +```Go +func (api *API) ListServerIpLoadBalancers(server_id string, ip_id string) ([]Identity, error) +``` + +```Go +func (api *API) ListServerIps(server_id string) ([]ServerIp, error) +``` + +```Go +func (api *API) ListServerPrivateNetworks(server_id string) ([]Identity, error) +``` + +```Go +func (api *API) ListServers(args ...interface{}) ([]Server, error) +``` + +```Go +func (api *API) ListSharedStorageServers(st_id string) ([]SharedStorageServer, error) +``` + +```Go +func (api *API) ListSharedStorages(args ...interface{}) ([]SharedStorage, error) +``` + +```Go +func (api *API) ListUsages(period string, sd *time.Time, ed *time.Time, args ...interface{}) (*Usages, error) +``` + +```Go +func (api *API) ListUserApiAllowedIps(user_id string) ([]string, error) +``` + +```Go +func (api *API) ListUsers(args ...interface{}) ([]User, error) +``` + +```Go +func (api *API) ListVPNs(args ...interface{}) ([]VPN, error) +``` + +```Go +func (api *API) LoadServerDvd(server_id string, dvd_id string) (*Server, error) +``` + +```Go +func (api *API) ModifyMonitoringPolicyPort(mp_id string, port_id string, mp_port *MonitoringPort) (*MonitoringPolicy, error) +``` + +```Go +func (api *API) ModifyMonitoringPolicyProcess(mp_id string, proc_id string, mp_proc *MonitoringProcess) (*MonitoringPolicy, error) +``` + +```Go +func (api *API) ModifyRole(role_id string, name string, description string, state string) (*Role, error) +``` + +```Go +func (api *API) ModifyRolePermissions(role_id string, perm *Permissions) (*Role, error) +``` + +```Go +func (api *API) ModifyUser(user_id string, user *UserRequest) (*User, error) +``` + +```Go +func (api *API) ModifyUserApi(user_id string, active bool) (*User, error) +``` + +```Go +func (api *API) ModifyVPN(vpn_id string, name string, description string) (*VPN, error) +``` + +```Go +func (api *API) Ping() ([]string, error) +``` + +```Go +func (api *API) PingAuth() ([]string, error) +``` + +```Go +func (api *API) RebootServer(server_id string, is_hardware bool) (*Server, error) +``` + +```Go +func (api *API) ReinstallServerImage(server_id string, image_id string, password string, fp_id string) (*Server, error) +``` + +```Go +func (api *API) RemoveMonitoringPolicyServer(mp_id string, ser_id string) (*MonitoringPolicy, error) +``` + +```Go +func (api *API) RemoveRoleUser(role_id string, user_id string) (*Role, error) +``` + +```Go +func (api *API) RemoveServerPrivateNetwork(server_id string, pn_id string) (*Server, error) +``` + +```Go +func (api *API) RemoveUserApiAllowedIp(user_id string, ip string) (*User, error) +``` + +```Go +func (api *API) RenameServer(server_id string, new_name string, new_desc string) (*Server, error) +``` + +```Go +func (api *API) RenewUserApiKey(user_id string) (*User, error) +``` + +```Go +func (api *API) ResizeServerHdd(server_id string, hdd_id string, new_size int) (*Server, error) +``` + +```Go +func (api *API) RestoreServerSnapshot(server_id string, snapshot_id string) (*Server, error) +``` + +```Go +func (api *API) ShutdownServer(server_id string, is_hardware bool) (*Server, error) +``` + +```Go +func (api *API) StartServer(server_id string) (*Server, error) +``` + +```Go +func (api *API) UnassignServerIpFirewallPolicy(server_id string, ip_id string) (*Server, error) +``` + +```Go +func (api *API) UnassignServerIpLoadBalancer(server_id string, ip_id string, lb_id string) (*Server, error) +``` + +```Go +func (api *API) UpdateFirewallPolicy(fp_id string, fp_new_name string, fp_new_desc string) (*FirewallPolicy, error) +``` + +```Go +func (api *API) UpdateImage(img_id string, new_name string, new_desc string, new_freq string) (*Image, error) +``` + +```Go +func (api *API) UpdateLoadBalancer(lb_id string, request *LoadBalancerRequest) (*LoadBalancer, error) +``` + +```Go +func (api *API) UpdateMonitoringPolicy(mp_id string, mp *MonitoringPolicy) (*MonitoringPolicy, error) +``` + +```Go +func (api *API) UpdatePrivateNetwork(pn_id string, request *PrivateNetworkRequest) (*PrivateNetwork, error) +``` + +```Go +func (api *API) UpdatePublicIp(ip_id string, reverse_dns string) (*PublicIp, error) +``` + +```Go +func (api *API) UpdateServerHardware(server_id string, hardware *Hardware) (*Server, error) +``` + +```Go +func (api *API) UpdateSharedStorage(ss_id string, request *SharedStorageRequest) (*SharedStorage, error) +``` + +```Go +func (api *API) UpdateSharedStorageCredentials(new_pass string) ([]SharedStorageAccess, error) +``` + +```Go +func (api *API) WaitForState(in ApiInstance, state string, sec time.Duration, count int) error +``` + +```Go +func (api *API) WaitUntilDeleted(in ApiInstance) error +``` + +```Go +func (fp *FirewallPolicy) GetState() (string, error) +``` + +```Go +func (im *Image) GetState() (string, error) +``` + +```Go +func (lb *LoadBalancer) GetState() (string, error) +``` + +```Go +func (mp *MonitoringPolicy) GetState() (string, error) +``` + +```Go +func (pn *PrivateNetwork) GetState() (string, error) +``` + +```Go +func (ip *PublicIp) GetState() (string, error) +``` + +```Go +func (role *Role) GetState() (string, error) +``` + +```Go +func (s *Server) GetState() (string, error) +``` + +```Go +func (ss *SharedStorage) GetState() (string, error) +``` + +```Go +func (u *User) GetState() (string, error) +``` + +```Go +func (u *User) GetState() (string, error) +``` + +```Go +func (vpn *VPN) GetState() (string, error) +``` + +```Go +func Bool2Pointer(input bool) *bool +``` + +```Go +func Int2Pointer(input int) *int +``` + +```Go +func (bp *BackupPerm) SetAll(value bool) +``` + +```Go +func (fp *FirewallPerm) SetAll(value bool) +``` + +```Go +func (imp *ImagePerm) SetAll(value bool) +``` + +```Go +unc (inp *InvoicePerm) SetAll(value bool) +``` + +```Go +func (ipp *IPPerm) SetAll(value bool) +``` + +```Go +func (lbp *LoadBalancerPerm) SetAll(value bool) +``` + +```Go +func (lp *LogPerm) SetAll(value bool) +``` + +```Go +func (mcp *MonitorCenterPerm) SetAll(value bool) +``` + +```Go +func (mpp *MonitorPolicyPerm) SetAll(value bool) +``` + +```Go +func (p *Permissions) SetAll(v bool) +``` + +```Go +func (pnp *PrivateNetworkPerm) SetAll(value bool) +``` + +```Go +func (rp *RolePerm) SetAll(value bool) +``` + +```Go +func (sp *ServerPerm) SetAll(value bool) +``` + +```Go +func (ssp *SharedStoragePerm) SetAll(value bool) +``` + +```Go +func (up *UsagePerm) SetAll(value bool) +``` + +```Go +func (up *UserPerm) SetAll(value bool) +``` + +```Go +func (vpnp *VPNPerm) SetAll(value bool) +``` + +```Go +func SetBaseUrl(newbaseurl string) string +``` + +```Go +func SetToken(newtoken string) string +``` + diff --git a/vendor/github.com/1and1/oneandone-cloudserver-sdk-go/datacenters.go b/vendor/github.com/1and1/oneandone-cloudserver-sdk-go/datacenters.go new file mode 100644 index 000000000..cf193fb88 --- /dev/null +++ b/vendor/github.com/1and1/oneandone-cloudserver-sdk-go/datacenters.go @@ -0,0 +1,36 @@ +package oneandone + +import "net/http" + +type Datacenter struct { + idField + CountryCode string `json:"country_code,omitempty"` + Location string `json:"location,omitempty"` +} + +// GET /datacenters +func (api *API) ListDatacenters(args ...interface{}) ([]Datacenter, error) { + url, err := processQueryParams(createUrl(api, datacenterPathSegment), args...) + if err != nil { + return nil, err + } + result := []Datacenter{} + err = api.Client.Get(url, &result, http.StatusOK) + if err != nil { + return nil, err + } + + return result, nil +} + +// GET /datacenters/{datacenter_id} +func (api *API) GetDatacenter(dc_id string) (*Datacenter, error) { + result := new(Datacenter) + url := createUrl(api, datacenterPathSegment, dc_id) + err := api.Client.Get(url, &result, http.StatusOK) + if err != nil { + return nil, err + } + + return result, nil +} diff --git a/vendor/github.com/1and1/oneandone-cloudserver-sdk-go/dvdisos.go b/vendor/github.com/1and1/oneandone-cloudserver-sdk-go/dvdisos.go new file mode 100644 index 000000000..ba54c3f7f --- /dev/null +++ b/vendor/github.com/1and1/oneandone-cloudserver-sdk-go/dvdisos.go @@ -0,0 +1,48 @@ +package oneandone + +import "net/http" + +// Struct to describe a ISO image that can be used to boot a server. +// +// Values of this type describe ISO images that can be inserted into the servers virtual DVD drive. +// +// +type DvdIso struct { + Identity + OsFamily string `json:"os_family,omitempty"` + Os string `json:"os,omitempty"` + OsVersion string `json:"os_version,omitempty"` + Type string `json:"type,omitempty"` + AvailableDatacenters []string `json:"available_datacenters,omitempty"` + Architecture interface{} `json:"os_architecture,omitempty"` + ApiPtr +} + +// GET /dvd_isos +func (api *API) ListDvdIsos(args ...interface{}) ([]DvdIso, error) { + url, err := processQueryParams(createUrl(api, dvdIsoPathSegment), args...) + if err != nil { + return nil, err + } + result := []DvdIso{} + err = api.Client.Get(url, &result, http.StatusOK) + if err != nil { + return nil, err + } + for index, _ := range result { + result[index].api = api + } + return result, nil +} + +// GET /dvd_isos/{id} +func (api *API) GetDvdIso(dvd_id string) (*DvdIso, error) { + result := new(DvdIso) + url := createUrl(api, dvdIsoPathSegment, dvd_id) + err := api.Client.Get(url, &result, http.StatusOK) + if err != nil { + return nil, err + } + result.api = api + return result, nil +} diff --git a/vendor/github.com/1and1/oneandone-cloudserver-sdk-go/errors.go b/vendor/github.com/1and1/oneandone-cloudserver-sdk-go/errors.go new file mode 100644 index 000000000..08cc9c250 --- /dev/null +++ b/vendor/github.com/1and1/oneandone-cloudserver-sdk-go/errors.go @@ -0,0 +1,27 @@ +package oneandone + +import ( + "fmt" +) + +type errorResponse struct { + Type string `json:"type"` + Message string `json:"message"` +} + +type apiError struct { + httpStatusCode int + message string +} + +func (e apiError) Error() string { + return fmt.Sprintf("%d - %s", e.httpStatusCode, e.message) +} + +func (e *apiError) HttpStatusCode() int { + return e.httpStatusCode +} + +func (e *apiError) Message() string { + return e.message +} diff --git a/vendor/github.com/1and1/oneandone-cloudserver-sdk-go/firewallpolicies.go b/vendor/github.com/1and1/oneandone-cloudserver-sdk-go/firewallpolicies.go new file mode 100644 index 000000000..3e89c9b17 --- /dev/null +++ b/vendor/github.com/1and1/oneandone-cloudserver-sdk-go/firewallpolicies.go @@ -0,0 +1,208 @@ +package oneandone + +import ( + "net/http" +) + +type FirewallPolicy struct { + Identity + descField + DefaultPolicy uint8 `json:"default"` + CloudpanelId string `json:"cloudpanel_id,omitempty"` + CreationDate string `json:"creation_date,omitempty"` + State string `json:"state,omitempty"` + Rules []FirewallPolicyRule `json:"rules,omitempty"` + ServerIps []ServerIpInfo `json:"server_ips,omitempty"` + ApiPtr +} + +type FirewallPolicyRule struct { + idField + Protocol string `json:"protocol,omitempty"` + PortFrom *int `json:"port_from,omitempty"` + PortTo *int `json:"port_to,omitempty"` + SourceIp string `json:"source,omitempty"` +} + +type FirewallPolicyRequest struct { + Name string `json:"name,omitempty"` + Description string `json:"description,omitempty"` + Rules []FirewallPolicyRule `json:"rules,omitempty"` +} + +// GET /firewall_policies +func (api *API) ListFirewallPolicies(args ...interface{}) ([]FirewallPolicy, error) { + url, err := processQueryParams(createUrl(api, firewallPolicyPathSegment), args...) + if err != nil { + return nil, err + } + result := []FirewallPolicy{} + err = api.Client.Get(url, &result, http.StatusOK) + if err != nil { + return nil, err + } + for index, _ := range result { + result[index].api = api + } + return result, nil +} + +// POST /firewall_policies +func (api *API) CreateFirewallPolicy(fp_data *FirewallPolicyRequest) (string, *FirewallPolicy, error) { + result := new(FirewallPolicy) + url := createUrl(api, firewallPolicyPathSegment) + err := api.Client.Post(url, &fp_data, &result, http.StatusAccepted) + if err != nil { + return "", nil, err + } + result.api = api + return result.Id, result, nil +} + +// GET /firewall_policies/{id} +func (api *API) GetFirewallPolicy(fp_id string) (*FirewallPolicy, error) { + result := new(FirewallPolicy) + url := createUrl(api, firewallPolicyPathSegment, fp_id) + err := api.Client.Get(url, &result, http.StatusOK) + if err != nil { + return nil, err + } + result.api = api + return result, nil + +} + +// DELETE /firewall_policies/{id} +func (api *API) DeleteFirewallPolicy(fp_id string) (*FirewallPolicy, error) { + result := new(FirewallPolicy) + url := createUrl(api, firewallPolicyPathSegment, fp_id) + err := api.Client.Delete(url, nil, &result, http.StatusAccepted) + if err != nil { + return nil, err + } + result.api = api + return result, nil +} + +// PUT /firewall_policies/{id} +func (api *API) UpdateFirewallPolicy(fp_id string, fp_new_name string, fp_new_desc string) (*FirewallPolicy, error) { + result := new(FirewallPolicy) + data := FirewallPolicyRequest{ + Name: fp_new_name, + Description: fp_new_desc, + } + url := createUrl(api, firewallPolicyPathSegment, fp_id) + err := api.Client.Put(url, &data, &result, http.StatusOK) + if err != nil { + return nil, err + } + result.api = api + return result, nil +} + +// GET /firewall_policies/{id}/server_ips +func (api *API) ListFirewallPolicyServerIps(fp_id string) ([]ServerIpInfo, error) { + result := []ServerIpInfo{} + url := createUrl(api, firewallPolicyPathSegment, fp_id, "server_ips") + err := api.Client.Get(url, &result, http.StatusOK) + if err != nil { + return nil, err + } + return result, nil +} + +// GET /firewall_policies/{id}/server_ips/{id} +func (api *API) GetFirewallPolicyServerIp(fp_id string, ip_id string) (*ServerIpInfo, error) { + result := new(ServerIpInfo) + url := createUrl(api, firewallPolicyPathSegment, fp_id, "server_ips", ip_id) + err := api.Client.Get(url, &result, http.StatusOK) + if err != nil { + return nil, err + } + return result, nil +} + +// POST /firewall_policies/{id}/server_ips +func (api *API) AddFirewallPolicyServerIps(fp_id string, ip_ids []string) (*FirewallPolicy, error) { + result := new(FirewallPolicy) + request := serverIps{ + ServerIps: ip_ids, + } + + url := createUrl(api, firewallPolicyPathSegment, fp_id, "server_ips") + err := api.Client.Post(url, &request, &result, http.StatusAccepted) + if err != nil { + return nil, err + } + result.api = api + return result, nil +} + +// DELETE /firewall_policies/{id}/server_ips/{id} +func (api *API) DeleteFirewallPolicyServerIp(fp_id string, ip_id string) (*FirewallPolicy, error) { + result := new(FirewallPolicy) + url := createUrl(api, firewallPolicyPathSegment, fp_id, "server_ips", ip_id) + err := api.Client.Delete(url, nil, &result, http.StatusAccepted) + if err != nil { + return nil, err + } + result.api = api + return result, nil +} + +// GET /firewall_policies/{id}/rules +func (api *API) ListFirewallPolicyRules(fp_id string) ([]FirewallPolicyRule, error) { + result := []FirewallPolicyRule{} + url := createUrl(api, firewallPolicyPathSegment, fp_id, "rules") + err := api.Client.Get(url, &result, http.StatusOK) + if err != nil { + return nil, err + } + return result, nil +} + +// POST /firewall_policies/{id}/rules +func (api *API) AddFirewallPolicyRules(fp_id string, fp_rules []FirewallPolicyRule) (*FirewallPolicy, error) { + result := new(FirewallPolicy) + data := struct { + Rules []FirewallPolicyRule `json:"rules"` + }{fp_rules} + url := createUrl(api, firewallPolicyPathSegment, fp_id, "rules") + err := api.Client.Post(url, &data, &result, http.StatusAccepted) + if err != nil { + return nil, err + } + result.api = api + return result, nil +} + +// GET /firewall_policies/{id}/rules/{id} +func (api *API) GetFirewallPolicyRule(fp_id string, rule_id string) (*FirewallPolicyRule, error) { + result := new(FirewallPolicyRule) + url := createUrl(api, firewallPolicyPathSegment, fp_id, "rules", rule_id) + err := api.Client.Get(url, &result, http.StatusOK) + if err != nil { + return nil, err + } + return result, nil +} + +// DELETE /firewall_policies/{id}/rules/{id} +func (api *API) DeleteFirewallPolicyRule(fp_id string, rule_id string) (*FirewallPolicy, error) { + result := new(FirewallPolicy) + url := createUrl(api, firewallPolicyPathSegment, fp_id, "rules", rule_id) + err := api.Client.Delete(url, nil, &result, http.StatusAccepted) + if err != nil { + return nil, err + } + result.api = api + return result, nil +} + +func (fp *FirewallPolicy) GetState() (string, error) { + in, err := fp.api.GetFirewallPolicy(fp.Id) + if in == nil { + return "", err + } + return in.State, err +} diff --git a/vendor/github.com/1and1/oneandone-cloudserver-sdk-go/images.go b/vendor/github.com/1and1/oneandone-cloudserver-sdk-go/images.go new file mode 100644 index 000000000..a3551cef7 --- /dev/null +++ b/vendor/github.com/1and1/oneandone-cloudserver-sdk-go/images.go @@ -0,0 +1,110 @@ +package oneandone + +import ( + "net/http" +) + +type Image struct { + idField + ImageConfig + MinHddSize int `json:"min_hdd_size"` + Architecture *int `json:"os_architecture"` + CloudPanelId string `json:"cloudpanel_id,omitempty"` + CreationDate string `json:"creation_date,omitempty"` + State string `json:"state,omitempty"` + OsImageType string `json:"os_image_type,omitempty"` + OsFamily string `json:"os_family,omitempty"` + Os string `json:"os,omitempty"` + OsVersion string `json:"os_version,omitempty"` + Type string `json:"type,omitempty"` + Licenses []License `json:"licenses,omitempty"` + Hdds []Hdd `json:"hdds,omitempty"` + Datacenter *Datacenter `json:"datacenter,omitempty"` + ApiPtr +} + +type ImageConfig struct { + Name string `json:"name,omitempty"` + Description string `json:"description,omitempty"` + Frequency string `json:"frequency,omitempty"` + ServerId string `json:"server_id,omitempty"` + NumImages int `json:"num_images"` +} + +// GET /images +func (api *API) ListImages(args ...interface{}) ([]Image, error) { + url, err := processQueryParams(createUrl(api, imagePathSegment), args...) + if err != nil { + return nil, err + } + result := []Image{} + err = api.Client.Get(url, &result, http.StatusOK) + if err != nil { + return nil, err + } + for index, _ := range result { + result[index].api = api + } + return result, nil +} + +// POST /images +func (api *API) CreateImage(request *ImageConfig) (string, *Image, error) { + res := new(Image) + url := createUrl(api, imagePathSegment) + err := api.Client.Post(url, &request, &res, http.StatusAccepted) + if err != nil { + return "", nil, err + } + res.api = api + return res.Id, res, nil +} + +// GET /images/{id} +func (api *API) GetImage(img_id string) (*Image, error) { + result := new(Image) + url := createUrl(api, imagePathSegment, img_id) + err := api.Client.Get(url, &result, http.StatusOK) + if err != nil { + return nil, err + } + result.api = api + return result, nil +} + +// DELETE /images/{id} +func (api *API) DeleteImage(img_id string) (*Image, error) { + result := new(Image) + url := createUrl(api, imagePathSegment, img_id) + err := api.Client.Delete(url, nil, &result, http.StatusAccepted) + if err != nil { + return nil, err + } + result.api = api + return result, nil +} + +// PUT /images/{id} +func (api *API) UpdateImage(img_id string, new_name string, new_desc string, new_freq string) (*Image, error) { + result := new(Image) + req := struct { + Name string `json:"name,omitempty"` + Description string `json:"description,omitempty"` + Frequency string `json:"frequency,omitempty"` + }{Name: new_name, Description: new_desc, Frequency: new_freq} + url := createUrl(api, imagePathSegment, img_id) + err := api.Client.Put(url, &req, &result, http.StatusOK) + if err != nil { + return nil, err + } + result.api = api + return result, nil +} + +func (im *Image) GetState() (string, error) { + in, err := im.api.GetImage(im.Id) + if in == nil { + return "", err + } + return in.State, err +} diff --git a/vendor/github.com/1and1/oneandone-cloudserver-sdk-go/loadbalancers.go b/vendor/github.com/1and1/oneandone-cloudserver-sdk-go/loadbalancers.go new file mode 100644 index 000000000..c965a25a8 --- /dev/null +++ b/vendor/github.com/1and1/oneandone-cloudserver-sdk-go/loadbalancers.go @@ -0,0 +1,219 @@ +package oneandone + +import ( + "net/http" +) + +type LoadBalancer struct { + ApiPtr + idField + Name string `json:"name,omitempty"` + Description string `json:"description,omitempty"` + State string `json:"state,omitempty"` + CreationDate string `json:"creation_date,omitempty"` + Ip string `json:"ip,omitempty"` + HealthCheckTest string `json:"health_check_test,omitempty"` + HealthCheckInterval int `json:"health_check_interval"` + HealthCheckPath string `json:"health_check_path,omitempty"` + HealthCheckPathParser string `json:"health_check_path_parser,omitempty"` + Persistence bool `json:"persistence"` + PersistenceTime int `json:"persistence_time"` + Method string `json:"method,omitempty"` + Rules []LoadBalancerRule `json:"rules,omitempty"` + ServerIps []ServerIpInfo `json:"server_ips,omitempty"` + Datacenter *Datacenter `json:"datacenter,omitempty"` + CloudPanelId string `json:"cloudpanel_id,omitempty"` +} + +type LoadBalancerRule struct { + idField + Protocol string `json:"protocol,omitempty"` + PortBalancer uint16 `json:"port_balancer"` + PortServer uint16 `json:"port_server"` + Source string `json:"source,omitempty"` +} + +type LoadBalancerRequest struct { + Name string `json:"name,omitempty"` + Description string `json:"description,omitempty"` + DatacenterId string `json:"datacenter_id,omitempty"` + HealthCheckTest string `json:"health_check_test,omitempty"` + HealthCheckInterval *int `json:"health_check_interval"` + HealthCheckPath string `json:"health_check_path,omitempty"` + HealthCheckPathParser string `json:"health_check_path_parser,omitempty"` + Persistence *bool `json:"persistence"` + PersistenceTime *int `json:"persistence_time"` + Method string `json:"method,omitempty"` + Rules []LoadBalancerRule `json:"rules,omitempty"` +} + +// GET /load_balancers +func (api *API) ListLoadBalancers(args ...interface{}) ([]LoadBalancer, error) { + url, err := processQueryParams(createUrl(api, loadBalancerPathSegment), args...) + if err != nil { + return nil, err + } + result := []LoadBalancer{} + err = api.Client.Get(url, &result, http.StatusOK) + if err != nil { + return nil, err + } + for index, _ := range result { + result[index].api = api + } + return result, nil +} + +// POST /load_balancers +func (api *API) CreateLoadBalancer(request *LoadBalancerRequest) (string, *LoadBalancer, error) { + url := createUrl(api, loadBalancerPathSegment) + result := new(LoadBalancer) + err := api.Client.Post(url, &request, &result, http.StatusAccepted) + if err != nil { + return "", nil, err + } + result.api = api + return result.Id, result, nil +} + +// GET /load_balancers/{id} +func (api *API) GetLoadBalancer(lb_id string) (*LoadBalancer, error) { + url := createUrl(api, loadBalancerPathSegment, lb_id) + result := new(LoadBalancer) + err := api.Client.Get(url, &result, http.StatusOK) + if err != nil { + return nil, err + } + result.api = api + return result, nil +} + +// DELETE /load_balancers/{id} +func (api *API) DeleteLoadBalancer(lb_id string) (*LoadBalancer, error) { + url := createUrl(api, loadBalancerPathSegment, lb_id) + result := new(LoadBalancer) + err := api.Client.Delete(url, nil, &result, http.StatusAccepted) + if err != nil { + return nil, err + } + result.api = api + return result, nil +} + +// PUT /load_balancers/{id} +func (api *API) UpdateLoadBalancer(lb_id string, request *LoadBalancerRequest) (*LoadBalancer, error) { + url := createUrl(api, loadBalancerPathSegment, lb_id) + result := new(LoadBalancer) + err := api.Client.Put(url, &request, &result, http.StatusAccepted) + if err != nil { + return nil, err + } + result.api = api + return result, nil +} + +// GET /load_balancers/{id}/server_ips +func (api *API) ListLoadBalancerServerIps(lb_id string) ([]ServerIpInfo, error) { + result := []ServerIpInfo{} + url := createUrl(api, loadBalancerPathSegment, lb_id, "server_ips") + err := api.Client.Get(url, &result, http.StatusOK) + if err != nil { + return nil, err + } + return result, nil +} + +// GET /load_balancers/{id}/server_ips/{id} +func (api *API) GetLoadBalancerServerIp(lb_id string, ip_id string) (*ServerIpInfo, error) { + result := new(ServerIpInfo) + url := createUrl(api, loadBalancerPathSegment, lb_id, "server_ips", ip_id) + err := api.Client.Get(url, &result, http.StatusOK) + if err != nil { + return nil, err + } + return result, nil +} + +// POST /load_balancers/{id}/server_ips +func (api *API) AddLoadBalancerServerIps(lb_id string, ip_ids []string) (*LoadBalancer, error) { + result := new(LoadBalancer) + request := serverIps{ + ServerIps: ip_ids, + } + url := createUrl(api, loadBalancerPathSegment, lb_id, "server_ips") + err := api.Client.Post(url, &request, &result, http.StatusAccepted) + if err != nil { + return nil, err + } + result.api = api + return result, nil +} + +// DELETE /load_balancers/{id}/server_ips/{id} +func (api *API) DeleteLoadBalancerServerIp(lb_id string, ip_id string) (*LoadBalancer, error) { + result := new(LoadBalancer) + url := createUrl(api, loadBalancerPathSegment, lb_id, "server_ips", ip_id) + err := api.Client.Delete(url, nil, &result, http.StatusAccepted) + if err != nil { + return nil, err + } + result.api = api + return result, nil +} + +// GET /load_balancers/{load_balancer_id}/rules +func (api *API) ListLoadBalancerRules(lb_id string) ([]LoadBalancerRule, error) { + result := []LoadBalancerRule{} + url := createUrl(api, loadBalancerPathSegment, lb_id, "rules") + err := api.Client.Get(url, &result, http.StatusOK) + if err != nil { + return nil, err + } + return result, nil +} + +// POST /load_balancers/{load_balancer_id}/rules +func (api *API) AddLoadBalancerRules(lb_id string, lb_rules []LoadBalancerRule) (*LoadBalancer, error) { + result := new(LoadBalancer) + data := struct { + Rules []LoadBalancerRule `json:"rules"` + }{lb_rules} + url := createUrl(api, loadBalancerPathSegment, lb_id, "rules") + err := api.Client.Post(url, &data, &result, http.StatusAccepted) + if err != nil { + return nil, err + } + result.api = api + return result, nil +} + +// GET /load_balancers/{load_balancer_id}/rules/{rule_id} +func (api *API) GetLoadBalancerRule(lb_id string, rule_id string) (*LoadBalancerRule, error) { + result := new(LoadBalancerRule) + url := createUrl(api, loadBalancerPathSegment, lb_id, "rules", rule_id) + err := api.Client.Get(url, &result, http.StatusOK) + if err != nil { + return nil, err + } + return result, nil +} + +// DELETE /load_balancers/{load_balancer_id}/rules/{rule_id} +func (api *API) DeleteLoadBalancerRule(lb_id string, rule_id string) (*LoadBalancer, error) { + result := new(LoadBalancer) + url := createUrl(api, loadBalancerPathSegment, lb_id, "rules", rule_id) + err := api.Client.Delete(url, nil, &result, http.StatusAccepted) + if err != nil { + return nil, err + } + result.api = api + return result, nil +} + +func (lb *LoadBalancer) GetState() (string, error) { + in, err := lb.api.GetLoadBalancer(lb.Id) + if in == nil { + return "", err + } + return in.State, err +} diff --git a/vendor/github.com/1and1/oneandone-cloudserver-sdk-go/logs.go b/vendor/github.com/1and1/oneandone-cloudserver-sdk-go/logs.go new file mode 100644 index 000000000..b16ef31d5 --- /dev/null +++ b/vendor/github.com/1and1/oneandone-cloudserver-sdk-go/logs.go @@ -0,0 +1,50 @@ +package oneandone + +import ( + "net/http" + "time" +) + +type Log struct { + ApiPtr + idField + typeField + CloudPanelId string `json:"cloudpanel_id,omitempty"` + SiteId string `json:"site_id,omitempty"` + StartDate string `json:"start_date,omitempty"` + EndDate string `json:"end_date,omitempty"` + Action string `json:"action,omitempty"` + Duration int `json:"duration"` + Status *Status `json:"Status,omitempty"` + Resource *Identity `json:"resource,omitempty"` + User *Identity `json:"user,omitempty"` +} + +// GET /logs +func (api *API) ListLogs(period string, sd *time.Time, ed *time.Time, args ...interface{}) ([]Log, error) { + result := []Log{} + url, err := processQueryParamsExt(createUrl(api, logPathSegment), period, sd, ed, args...) + if err != nil { + return nil, err + } + err = api.Client.Get(url, &result, http.StatusOK) + if err != nil { + return nil, err + } + for index, _ := range result { + result[index].api = api + } + return result, nil +} + +// GET /logs/{id} +func (api *API) GetLog(log_id string) (*Log, error) { + result := new(Log) + url := createUrl(api, logPathSegment, log_id) + err := api.Client.Get(url, &result, http.StatusOK) + if err != nil { + return nil, err + } + result.api = api + return result, nil +} diff --git a/vendor/github.com/1and1/oneandone-cloudserver-sdk-go/monitoringcenter.go b/vendor/github.com/1and1/oneandone-cloudserver-sdk-go/monitoringcenter.go new file mode 100644 index 000000000..86e899889 --- /dev/null +++ b/vendor/github.com/1and1/oneandone-cloudserver-sdk-go/monitoringcenter.go @@ -0,0 +1,158 @@ +package oneandone + +import ( + "errors" + "net/http" + "time" +) + +type MonServerUsageSummary struct { + Identity + Agent *monitoringAgent `json:"agent,omitempty"` + Alerts *monitoringAlerts `json:"alerts,omitempty"` + Status *monitoringStatus `json:"status,omitempty"` + ApiPtr +} + +type MonServerUsageDetails struct { + Identity + Status *statusState `json:"status,omitempty"` + Agent *monitoringAgent `json:"agent,omitempty"` + Alerts *monitoringAlerts `json:"alerts,omitempty"` + CpuStatus *utilizationStatus `json:"cpu,omitempty"` + DiskStatus *utilizationStatus `json:"disk,omitempty"` + RamStatus *utilizationStatus `json:"ram,omitempty"` + PingStatus *pingStatus `json:"internal_ping,omitempty"` + TransferStatus *transferStatus `json:"transfer,omitempty"` + ApiPtr +} + +type monitoringStatus struct { + State string `json:"state,omitempty"` + Cpu *statusState `json:"cpu,omitempty"` + Disk *statusState `json:"disk,omitempty"` + InternalPing *statusState `json:"internal_ping,omitempty"` + Ram *statusState `json:"ram,omitempty"` + Transfer *statusState `json:"transfer,omitempty"` +} + +type utilizationStatus struct { + CriticalThreshold int `json:"critical,omitempty"` + WarningThreshold int `json:"warning,omitempty"` + Status string `json:"status,omitempty"` + Data []usageData `json:"data,omitempty"` + Unit *usageUnit `json:"unit,omitempty"` +} + +type pingStatus struct { + CriticalThreshold int `json:"critical,omitempty"` + WarningThreshold int `json:"warning,omitempty"` + Status string `json:"status,omitempty"` + Data []pingData `json:"data,omitempty"` + Unit *pingUnit `json:"unit,omitempty"` +} + +type transferStatus struct { + CriticalThreshold int `json:"critical,omitempty"` + WarningThreshold int `json:"warning,omitempty"` + Status string `json:"status,omitempty"` + Data []transferData `json:"data,omitempty"` + Unit *transferUnit `json:"unit,omitempty"` +} + +type monitoringAgent struct { + AgentInstalled bool `json:"agent_installed"` + MissingAgentAlert bool `json:"missing_agent_alert"` + MonitoringNeedsAgent bool `json:"monitoring_needs_agent"` +} + +type monitoringAlerts struct { + Ports *monitoringAlertInfo `json:"ports,omitempty"` + Process *monitoringAlertInfo `json:"process,omitempty"` + Resources *monitoringAlertInfo `json:"resources,omitempty"` +} + +type monitoringAlertInfo struct { + Ok int `json:"ok"` + Warning int `json:"warning"` + Critical int `json:"critical"` +} + +type usageData struct { + Date string `json:"date,omitempty"` + UsedPercent float32 `json:"used_percent"` +} + +type usageUnit struct { + UsedPercent string `json:"used_percent,omitempty"` +} + +type pingUnit struct { + PackagesLost string `json:"pl,omitempty"` + AccessTime string `json:"rta,omitempty"` +} + +type pingData struct { + Date string `json:"date,omitempty"` + PackagesLost int `json:"pl"` + AccessTime float32 `json:"rta"` +} + +type transferUnit struct { + Downstream string `json:"downstream,omitempty"` + Upstream string `json:"upstream,omitempty"` +} + +type transferData struct { + Date string `json:"date,omitempty"` + Downstream int `json:"downstream"` + Upstream int `json:"upstream"` +} + +// GET /monitoring_center +func (api *API) ListMonitoringServersUsages(args ...interface{}) ([]MonServerUsageSummary, error) { + url, err := processQueryParams(createUrl(api, monitorCenterPathSegment), args...) + if err != nil { + return nil, err + } + result := []MonServerUsageSummary{} + err = api.Client.Get(url, &result, http.StatusOK) + if err != nil { + return nil, err + } + for index, _ := range result { + result[index].api = api + } + return result, nil +} + +// GET /monitoring_center/{server_id} +func (api *API) GetMonitoringServerUsage(ser_id string, period string, dates ...time.Time) (*MonServerUsageDetails, error) { + if period == "" { + return nil, errors.New("Time period must be provided.") + } + + params := make(map[string]interface{}, len(dates)+1) + params["period"] = period + + if len(dates) == 2 { + if dates[0].After(dates[1]) { + return nil, errors.New("Start date cannot be after end date.") + } + + params["start_date"] = dates[0].Format(time.RFC3339) + params["end_date"] = dates[1].Format(time.RFC3339) + + } else if len(dates) > 0 { + return nil, errors.New("Start and end dates must be provided.") + } + url := createUrl(api, monitorCenterPathSegment, ser_id) + url = appendQueryParams(url, params) + result := new(MonServerUsageDetails) + err := api.Client.Get(url, &result, http.StatusOK) + if err != nil { + return nil, err + } + result.api = api + return result, nil +} diff --git a/vendor/github.com/1and1/oneandone-cloudserver-sdk-go/monitoringpolicies.go b/vendor/github.com/1and1/oneandone-cloudserver-sdk-go/monitoringpolicies.go new file mode 100644 index 000000000..4272461b6 --- /dev/null +++ b/vendor/github.com/1and1/oneandone-cloudserver-sdk-go/monitoringpolicies.go @@ -0,0 +1,305 @@ +package oneandone + +import ( + "net/http" +) + +type MonitoringPolicy struct { + ApiPtr + idField + Name string `json:"name,omitempty"` + Description string `json:"description,omitempty"` + State string `json:"state,omitempty"` + Default *int `json:"default,omitempty"` + CreationDate string `json:"creation_date,omitempty"` + Email string `json:"email,omitempty"` + Agent bool `json:"agent"` + Servers []Identity `json:"servers,omitempty"` + Thresholds *MonitoringThreshold `json:"thresholds,omitempty"` + Ports []MonitoringPort `json:"ports,omitempty"` + Processes []MonitoringProcess `json:"processes,omitempty"` + CloudPanelId string `json:"cloudpanel_id,omitempty"` +} + +type MonitoringThreshold struct { + Cpu *MonitoringLevel `json:"cpu,omitempty"` + Ram *MonitoringLevel `json:"ram,omitempty"` + Disk *MonitoringLevel `json:"disk,omitempty"` + Transfer *MonitoringLevel `json:"transfer,omitempty"` + InternalPing *MonitoringLevel `json:"internal_ping,omitempty"` +} + +type MonitoringLevel struct { + Warning *MonitoringValue `json:"warning,omitempty"` + Critical *MonitoringValue `json:"critical,omitempty"` +} + +type MonitoringValue struct { + Value int `json:"value"` + Alert bool `json:"alert"` +} + +type MonitoringPort struct { + idField + Protocol string `json:"protocol,omitempty"` + Port int `json:"port"` + AlertIf string `json:"alert_if,omitempty"` + EmailNotification bool `json:"email_notification"` +} + +type MonitoringProcess struct { + idField + Process string `json:"process,omitempty"` + AlertIf string `json:"alert_if,omitempty"` + EmailNotification bool `json:"email_notification"` +} + +// GET /monitoring_policies +func (api *API) ListMonitoringPolicies(args ...interface{}) ([]MonitoringPolicy, error) { + url, err := processQueryParams(createUrl(api, monitorPolicyPathSegment), args...) + if err != nil { + return nil, err + } + result := []MonitoringPolicy{} + err = api.Client.Get(url, &result, http.StatusOK) + if err != nil { + return nil, err + } + for index, _ := range result { + result[index].api = api + } + return result, nil +} + +// POST /monitoring_policies +func (api *API) CreateMonitoringPolicy(mp *MonitoringPolicy) (string, *MonitoringPolicy, error) { + result := new(MonitoringPolicy) + url := createUrl(api, monitorPolicyPathSegment) + err := api.Client.Post(url, &mp, &result, http.StatusCreated) + if err != nil { + return "", nil, err + } + result.api = api + return result.Id, result, nil +} + +// GET /monitoring_policies/{id} +func (api *API) GetMonitoringPolicy(mp_id string) (*MonitoringPolicy, error) { + result := new(MonitoringPolicy) + url := createUrl(api, monitorPolicyPathSegment, mp_id) + err := api.Client.Get(url, &result, http.StatusOK) + if err != nil { + return nil, err + } + result.api = api + return result, nil +} + +// DELETE /monitoring_policies/{id} +func (api *API) DeleteMonitoringPolicy(mp_id string) (*MonitoringPolicy, error) { + result := new(MonitoringPolicy) + url := createUrl(api, monitorPolicyPathSegment, mp_id) + err := api.Client.Delete(url, nil, &result, http.StatusAccepted) + if err != nil { + return nil, err + } + result.api = api + return result, nil +} + +// PUT /monitoring_policies/{id} +func (api *API) UpdateMonitoringPolicy(mp_id string, mp *MonitoringPolicy) (*MonitoringPolicy, error) { + url := createUrl(api, monitorPolicyPathSegment, mp_id) + result := new(MonitoringPolicy) + err := api.Client.Put(url, &mp, &result, http.StatusAccepted) + if err != nil { + return nil, err + } + result.api = api + return result, nil +} + +// GET /monitoring_policies/{id}/ports +func (api *API) ListMonitoringPolicyPorts(mp_id string) ([]MonitoringPort, error) { + result := []MonitoringPort{} + url := createUrl(api, monitorPolicyPathSegment, mp_id, "ports") + err := api.Client.Get(url, &result, http.StatusOK) + if err != nil { + return nil, err + } + return result, nil +} + +// POST /monitoring_policies/{id}/ports +func (api *API) AddMonitoringPolicyPorts(mp_id string, mp_ports []MonitoringPort) (*MonitoringPolicy, error) { + result := new(MonitoringPolicy) + data := struct { + Ports []MonitoringPort `json:"ports"` + }{mp_ports} + url := createUrl(api, monitorPolicyPathSegment, mp_id, "ports") + err := api.Client.Post(url, &data, &result, http.StatusAccepted) + if err != nil { + return nil, err + } + result.api = api + return result, nil +} + +// GET /monitoring_policies/{id}/ports/{id} +func (api *API) GetMonitoringPolicyPort(mp_id string, port_id string) (*MonitoringPort, error) { + result := new(MonitoringPort) + url := createUrl(api, monitorPolicyPathSegment, mp_id, "ports", port_id) + err := api.Client.Get(url, &result, http.StatusOK) + if err != nil { + return nil, err + } + return result, nil +} + +// DELETE /monitoring_policies/{id}/ports/{id} +func (api *API) DeleteMonitoringPolicyPort(mp_id string, port_id string) (*MonitoringPolicy, error) { + result := new(MonitoringPolicy) + url := createUrl(api, monitorPolicyPathSegment, mp_id, "ports", port_id) + err := api.Client.Delete(url, nil, &result, http.StatusAccepted) + if err != nil { + return nil, err + } + result.api = api + return result, nil +} + +// PUT /monitoring_policies/{id}/ports/{id} +func (api *API) ModifyMonitoringPolicyPort(mp_id string, port_id string, mp_port *MonitoringPort) (*MonitoringPolicy, error) { + url := createUrl(api, monitorPolicyPathSegment, mp_id, "ports", port_id) + result := new(MonitoringPolicy) + req := struct { + Ports *MonitoringPort `json:"ports"` + }{mp_port} + err := api.Client.Put(url, &req, &result, http.StatusAccepted) + if err != nil { + return nil, err + } + result.api = api + return result, nil +} + +// GET /monitoring_policies/{id}/processes +func (api *API) ListMonitoringPolicyProcesses(mp_id string) ([]MonitoringProcess, error) { + result := []MonitoringProcess{} + url := createUrl(api, monitorPolicyPathSegment, mp_id, "processes") + err := api.Client.Get(url, &result, http.StatusOK) + if err != nil { + return nil, err + } + return result, nil +} + +// POST /monitoring_policies/{id}/processes +func (api *API) AddMonitoringPolicyProcesses(mp_id string, mp_procs []MonitoringProcess) (*MonitoringPolicy, error) { + result := new(MonitoringPolicy) + request := struct { + Processes []MonitoringProcess `json:"processes"` + }{mp_procs} + url := createUrl(api, monitorPolicyPathSegment, mp_id, "processes") + err := api.Client.Post(url, &request, &result, http.StatusAccepted) + if err != nil { + return nil, err + } + result.api = api + return result, nil +} + +// GET /monitoring_policies/{id}/processes/{id} +func (api *API) GetMonitoringPolicyProcess(mp_id string, proc_id string) (*MonitoringProcess, error) { + result := new(MonitoringProcess) + url := createUrl(api, monitorPolicyPathSegment, mp_id, "processes", proc_id) + err := api.Client.Get(url, &result, http.StatusOK) + if err != nil { + return nil, err + } + return result, nil +} + +// DELETE /monitoring_policies/{id}/processes/{id} +func (api *API) DeleteMonitoringPolicyProcess(mp_id string, proc_id string) (*MonitoringPolicy, error) { + result := new(MonitoringPolicy) + url := createUrl(api, monitorPolicyPathSegment, mp_id, "processes", proc_id) + err := api.Client.Delete(url, nil, &result, http.StatusAccepted) + if err != nil { + return nil, err + } + result.api = api + return result, nil +} + +// PUT /monitoring_policies/{id}/processes/{id} +func (api *API) ModifyMonitoringPolicyProcess(mp_id string, proc_id string, mp_proc *MonitoringProcess) (*MonitoringPolicy, error) { + url := createUrl(api, monitorPolicyPathSegment, mp_id, "processes", proc_id) + result := new(MonitoringPolicy) + req := struct { + Processes *MonitoringProcess `json:"processes"` + }{mp_proc} + err := api.Client.Put(url, &req, &result, http.StatusAccepted) + if err != nil { + return nil, err + } + result.api = api + return result, nil +} + +// GET /monitoring_policies/{id}/servers +func (api *API) ListMonitoringPolicyServers(mp_id string) ([]Identity, error) { + result := []Identity{} + url := createUrl(api, monitorPolicyPathSegment, mp_id, "servers") + err := api.Client.Get(url, &result, http.StatusOK) + if err != nil { + return nil, err + } + return result, nil +} + +// POST /monitoring_policies/{id}/servers +func (api *API) AttachMonitoringPolicyServers(mp_id string, sids []string) (*MonitoringPolicy, error) { + result := new(MonitoringPolicy) + request := servers{ + Servers: sids, + } + url := createUrl(api, monitorPolicyPathSegment, mp_id, "servers") + err := api.Client.Post(url, &request, &result, http.StatusAccepted) + if err != nil { + return nil, err + } + result.api = api + return result, nil +} + +// GET /monitoring_policies/{id}/servers/{id} +func (api *API) GetMonitoringPolicyServer(mp_id string, ser_id string) (*Identity, error) { + result := new(Identity) + url := createUrl(api, monitorPolicyPathSegment, mp_id, "servers", ser_id) + err := api.Client.Get(url, &result, http.StatusOK) + if err != nil { + return nil, err + } + return result, nil +} + +// DELETE /monitoring_policies/{id}/servers/{id} +func (api *API) RemoveMonitoringPolicyServer(mp_id string, ser_id string) (*MonitoringPolicy, error) { + result := new(MonitoringPolicy) + url := createUrl(api, monitorPolicyPathSegment, mp_id, "servers", ser_id) + err := api.Client.Delete(url, nil, &result, http.StatusAccepted) + if err != nil { + return nil, err + } + result.api = api + return result, nil +} + +func (mp *MonitoringPolicy) GetState() (string, error) { + in, err := mp.api.GetMonitoringPolicy(mp.Id) + if in == nil { + return "", err + } + return in.State, err +} diff --git a/vendor/github.com/1and1/oneandone-cloudserver-sdk-go/oneandone.go b/vendor/github.com/1and1/oneandone-cloudserver-sdk-go/oneandone.go new file mode 100644 index 000000000..e007fcb22 --- /dev/null +++ b/vendor/github.com/1and1/oneandone-cloudserver-sdk-go/oneandone.go @@ -0,0 +1,163 @@ +package oneandone + +import ( + "errors" + "net/http" + "reflect" + "time" +) + +// Struct to hold the required information for accessing the API. +// +// Instances of this type contain the URL of the endpoint to access the API as well as the API access token to be used. +// They offer also all methods that allow to access the various objects that are returned by top level resources of +// the API. +type API struct { + Endpoint string + Client *restClient +} + +type ApiPtr struct { + api *API +} + +type idField struct { + Id string `json:"id,omitempty"` +} + +type typeField struct { + Type string `json:"type,omitempty"` +} + +type nameField struct { + Name string `json:"name,omitempty"` +} + +type descField struct { + Description string `json:"description,omitempty"` +} + +type countField struct { + Count int `json:"count,omitempty"` +} + +type serverIps struct { + ServerIps []string `json:"server_ips"` +} + +type servers struct { + Servers []string `json:"servers"` +} + +type ApiInstance interface { + GetState() (string, error) +} + +const ( + datacenterPathSegment = "datacenters" + dvdIsoPathSegment = "dvd_isos" + firewallPolicyPathSegment = "firewall_policies" + imagePathSegment = "images" + loadBalancerPathSegment = "load_balancers" + logPathSegment = "logs" + monitorCenterPathSegment = "monitoring_center" + monitorPolicyPathSegment = "monitoring_policies" + pingPathSegment = "ping" + pingAuthPathSegment = "ping_auth" + pricingPathSegment = "pricing" + privateNetworkPathSegment = "private_networks" + publicIpPathSegment = "public_ips" + rolePathSegment = "roles" + serverPathSegment = "servers" + serverAppliancePathSegment = "server_appliances" + sharedStoragePathSegment = "shared_storages" + usagePathSegment = "usages" + userPathSegment = "users" + vpnPathSegment = "vpns" +) + +// Struct to hold the status of an API object. +// +// Values of this type are used to represent the status of API objects like servers, firewall policies and the like. +// +// The value of the "State" field can represent fixed states like "ACTIVE" or "POWERED_ON" but also transitional +// states like "POWERING_ON" or "CONFIGURING". +// +// For fixed states the "Percent" field is empty where as for transitional states it contains the progress of the +// transition in percent. +type Status struct { + State string `json:"state"` + Percent int `json:"percent"` +} + +type statusState struct { + State string `json:"state,omitempty"` +} + +type Identity struct { + idField + nameField +} + +type License struct { + nameField +} + +// Creates a new API instance. +// +// Explanations about given token and url information can be found online under the following url TODO add url! +func New(token string, url string) *API { + api := new(API) + api.Endpoint = url + api.Client = newRestClient(token) + return api +} + +// Converts a given integer value into a pointer of the same type. +func Int2Pointer(input int) *int { + result := new(int) + *result = input + return result +} + +// Converts a given boolean value into a pointer of the same type. +func Bool2Pointer(input bool) *bool { + result := new(bool) + *result = input + return result +} + +// Performs busy-waiting for types that implement ApiInstance interface. +func (api *API) WaitForState(in ApiInstance, state string, sec time.Duration, count int) error { + if in != nil { + for i := 0; i < count; i++ { + s, err := in.GetState() + if err != nil { + return err + } + if s == state { + return nil + } + time.Sleep(sec * time.Second) + } + return errors.New(reflect.ValueOf(in).Type().String() + " operation timeout.") + } + return nil +} + +// Waits until instance is deleted for types that implement ApiInstance interface. +func (api *API) WaitUntilDeleted(in ApiInstance) error { + var err error + for in != nil { + _, err = in.GetState() + if err != nil { + if apiError, ok := err.(apiError); ok && apiError.httpStatusCode == http.StatusNotFound { + return nil + } else { + return err + } + } + time.Sleep(5 * time.Second) + } + return nil +} diff --git a/vendor/github.com/1and1/oneandone-cloudserver-sdk-go/ping.go b/vendor/github.com/1and1/oneandone-cloudserver-sdk-go/ping.go new file mode 100644 index 000000000..255608885 --- /dev/null +++ b/vendor/github.com/1and1/oneandone-cloudserver-sdk-go/ping.go @@ -0,0 +1,29 @@ +package oneandone + +import "net/http" + +// GET /ping +// Returns "PONG" if API is running +func (api *API) Ping() ([]string, error) { + url := createUrl(api, pingPathSegment) + result := []string{} + err := api.Client.Get(url, &result, http.StatusOK) + if err != nil { + return nil, err + } + + return result, nil +} + +// GET /ping_auth +// Returns "PONG" if the API is running and the authentication token is valid +func (api *API) PingAuth() ([]string, error) { + url := createUrl(api, pingAuthPathSegment) + result := []string{} + err := api.Client.Get(url, &result, http.StatusOK) + if err != nil { + return nil, err + } + + return result, nil +} diff --git a/vendor/github.com/1and1/oneandone-cloudserver-sdk-go/pricing.go b/vendor/github.com/1and1/oneandone-cloudserver-sdk-go/pricing.go new file mode 100644 index 000000000..90eb2abd9 --- /dev/null +++ b/vendor/github.com/1and1/oneandone-cloudserver-sdk-go/pricing.go @@ -0,0 +1,40 @@ +package oneandone + +import "net/http" + +type Pricing struct { + Currency string `json:"currency,omitempty"` + Plan *pricingPlan `json:"pricing_plans,omitempty"` +} + +type pricingPlan struct { + Image *pricingItem `json:"image,omitempty"` + PublicIPs []pricingItem `json:"public_ips,omitempty"` + Servers *serverPricing `json:"servers,omitempty"` + SharedStorage *pricingItem `json:"shared_storage,omitempty"` + SoftwareLicenses []pricingItem `json:"software_licences,omitempty"` +} + +type serverPricing struct { + FixedServers []pricingItem `json:"fixed_servers,omitempty"` + FlexServers []pricingItem `json:"flexible_server,omitempty"` +} + +type pricingItem struct { + Name string `json:"name,omitempty"` + GrossPrice string `json:"price_gross,omitempty"` + NetPrice string `json:"price_net,omitempty"` + Unit string `json:"unit,omitempty"` +} + +// GET /pricing +func (api *API) GetPricing() (*Pricing, error) { + result := new(Pricing) + url := createUrl(api, pricingPathSegment) + err := api.Client.Get(url, &result, http.StatusOK) + if err != nil { + return nil, err + } + + return result, nil +} diff --git a/vendor/github.com/1and1/oneandone-cloudserver-sdk-go/privatenetworks.go b/vendor/github.com/1and1/oneandone-cloudserver-sdk-go/privatenetworks.go new file mode 100644 index 000000000..667494e04 --- /dev/null +++ b/vendor/github.com/1and1/oneandone-cloudserver-sdk-go/privatenetworks.go @@ -0,0 +1,149 @@ +package oneandone + +import ( + "net/http" +) + +type PrivateNetwork struct { + Identity + descField + CloudpanelId string `json:"cloudpanel_id,omitempty"` + NetworkAddress string `json:"network_address,omitempty"` + SubnetMask string `json:"subnet_mask,omitempty"` + State string `json:"state,omitempty"` + SiteId string `json:"site_id,omitempty"` + CreationDate string `json:"creation_date,omitempty"` + Servers []Identity `json:"servers,omitempty"` + Datacenter *Datacenter `json:"datacenter,omitempty"` + ApiPtr +} + +type PrivateNetworkRequest struct { + Name string `json:"name,omitempty"` + Description string `json:"description,omitempty"` + DatacenterId string `json:"datacenter_id,omitempty"` + NetworkAddress string `json:"network_address,omitempty"` + SubnetMask string `json:"subnet_mask,omitempty"` +} + +// GET /private_networks +func (api *API) ListPrivateNetworks(args ...interface{}) ([]PrivateNetwork, error) { + url, err := processQueryParams(createUrl(api, privateNetworkPathSegment), args...) + if err != nil { + return nil, err + } + result := []PrivateNetwork{} + err = api.Client.Get(url, &result, http.StatusOK) + if err != nil { + return nil, err + } + for index, _ := range result { + result[index].api = api + } + return result, nil +} + +// POST /private_networks +func (api *API) CreatePrivateNetwork(request *PrivateNetworkRequest) (string, *PrivateNetwork, error) { + result := new(PrivateNetwork) + url := createUrl(api, privateNetworkPathSegment) + err := api.Client.Post(url, &request, &result, http.StatusAccepted) + if err != nil { + return "", nil, err + } + result.api = api + return result.Id, result, nil +} + +// GET /private_networks/{id} +func (api *API) GetPrivateNetwork(pn_id string) (*PrivateNetwork, error) { + result := new(PrivateNetwork) + url := createUrl(api, privateNetworkPathSegment, pn_id) + err := api.Client.Get(url, &result, http.StatusOK) + if err != nil { + return nil, err + } + result.api = api + return result, nil +} + +// PUT /private_networks/{id} +func (api *API) UpdatePrivateNetwork(pn_id string, request *PrivateNetworkRequest) (*PrivateNetwork, error) { + result := new(PrivateNetwork) + url := createUrl(api, privateNetworkPathSegment, pn_id) + err := api.Client.Put(url, &request, &result, http.StatusOK) + if err != nil { + return nil, err + } + result.api = api + return result, nil +} + +// DELETE /private_networks/{id} +func (api *API) DeletePrivateNetwork(pn_id string) (*PrivateNetwork, error) { + result := new(PrivateNetwork) + url := createUrl(api, privateNetworkPathSegment, pn_id) + err := api.Client.Delete(url, nil, &result, http.StatusAccepted) + if err != nil { + return nil, err + } + result.api = api + return result, nil +} + +// GET /private_networks/{id}/servers +func (api *API) ListPrivateNetworkServers(pn_id string) ([]Identity, error) { + result := []Identity{} + url := createUrl(api, privateNetworkPathSegment, pn_id, "servers") + err := api.Client.Get(url, &result, http.StatusOK) + if err != nil { + return nil, err + } + return result, nil +} + +// POST /private_networks/{id}/servers +func (api *API) AttachPrivateNetworkServers(pn_id string, sids []string) (*PrivateNetwork, error) { + result := new(PrivateNetwork) + req := servers{ + Servers: sids, + } + url := createUrl(api, privateNetworkPathSegment, pn_id, "servers") + err := api.Client.Post(url, &req, &result, http.StatusAccepted) + if err != nil { + return nil, err + } + result.api = api + return result, nil +} + +// GET /private_networks/{id}/servers/{id} +func (api *API) GetPrivateNetworkServer(pn_id string, server_id string) (*Identity, error) { + result := new(Identity) + url := createUrl(api, privateNetworkPathSegment, pn_id, "servers", server_id) + err := api.Client.Get(url, &result, http.StatusOK) + if err != nil { + return nil, err + } + return result, nil +} + +// DELETE /private_networks/{id}/servers/{id} +func (api *API) DetachPrivateNetworkServer(pn_id string, pns_id string) (*PrivateNetwork, error) { + result := new(PrivateNetwork) + url := createUrl(api, privateNetworkPathSegment, pn_id, "servers", pns_id) + err := api.Client.Delete(url, nil, &result, http.StatusAccepted) + if err != nil { + return nil, err + } + result.api = api + return result, nil +} + +func (pn *PrivateNetwork) GetState() (string, error) { + in, err := pn.api.GetPrivateNetwork(pn.Id) + if in == nil { + return "", err + } + return in.State, err +} diff --git a/vendor/github.com/1and1/oneandone-cloudserver-sdk-go/publicips.go b/vendor/github.com/1and1/oneandone-cloudserver-sdk-go/publicips.go new file mode 100644 index 000000000..b0b6bd6ed --- /dev/null +++ b/vendor/github.com/1and1/oneandone-cloudserver-sdk-go/publicips.go @@ -0,0 +1,108 @@ +package oneandone + +import "net/http" + +type PublicIp struct { + idField + typeField + IpAddress string `json:"ip,omitempty"` + AssignedTo *assignedTo `json:"assigned_to,omitempty"` + ReverseDns string `json:"reverse_dns,omitempty"` + IsDhcp *bool `json:"is_dhcp,omitempty"` + State string `json:"state,omitempty"` + SiteId string `json:"site_id,omitempty"` + CreationDate string `json:"creation_date,omitempty"` + Datacenter *Datacenter `json:"datacenter,omitempty"` + ApiPtr +} + +type assignedTo struct { + Identity + typeField +} + +const ( + IpTypeV4 = "IPV4" + IpTypeV6 = "IPV6" +) + +// GET /public_ips +func (api *API) ListPublicIps(args ...interface{}) ([]PublicIp, error) { + url, err := processQueryParams(createUrl(api, publicIpPathSegment), args...) + if err != nil { + return nil, err + } + result := []PublicIp{} + err = api.Client.Get(url, &result, http.StatusOK) + if err != nil { + return nil, err + } + for index, _ := range result { + result[index].api = api + } + return result, nil +} + +// POST /public_ips +func (api *API) CreatePublicIp(ip_type string, reverse_dns string, datacenter_id string) (string, *PublicIp, error) { + res := new(PublicIp) + url := createUrl(api, publicIpPathSegment) + req := struct { + DatacenterId string `json:"datacenter_id,omitempty"` + ReverseDns string `json:"reverse_dns,omitempty"` + Type string `json:"type,omitempty"` + }{DatacenterId: datacenter_id, ReverseDns: reverse_dns, Type: ip_type} + err := api.Client.Post(url, &req, &res, http.StatusCreated) + if err != nil { + return "", nil, err + } + res.api = api + return res.Id, res, nil +} + +// GET /public_ips/{id} +func (api *API) GetPublicIp(ip_id string) (*PublicIp, error) { + result := new(PublicIp) + url := createUrl(api, publicIpPathSegment, ip_id) + err := api.Client.Get(url, &result, http.StatusOK) + if err != nil { + return nil, err + } + result.api = api + return result, nil +} + +// DELETE /public_ips/{id} +func (api *API) DeletePublicIp(ip_id string) (*PublicIp, error) { + result := new(PublicIp) + url := createUrl(api, publicIpPathSegment, ip_id) + err := api.Client.Delete(url, nil, &result, http.StatusOK) + if err != nil { + return nil, err + } + result.api = api + return result, nil +} + +// PUT /public_ips/{id} +func (api *API) UpdatePublicIp(ip_id string, reverse_dns string) (*PublicIp, error) { + result := new(PublicIp) + url := createUrl(api, publicIpPathSegment, ip_id) + req := struct { + ReverseDns string `json:"reverse_dns,omitempty"` + }{reverse_dns} + err := api.Client.Put(url, &req, &result, http.StatusOK) + if err != nil { + return nil, err + } + result.api = api + return result, nil +} + +func (ip *PublicIp) GetState() (string, error) { + in, err := ip.api.GetPublicIp(ip.Id) + if in == nil { + return "", err + } + return in.State, err +} diff --git a/vendor/github.com/1and1/oneandone-cloudserver-sdk-go/restclient.go b/vendor/github.com/1and1/oneandone-cloudserver-sdk-go/restclient.go new file mode 100644 index 000000000..b200a1089 --- /dev/null +++ b/vendor/github.com/1and1/oneandone-cloudserver-sdk-go/restclient.go @@ -0,0 +1,213 @@ +package oneandone + +import ( + "bytes" + "encoding/json" + "errors" + "fmt" + "io" + "io/ioutil" + "net/http" + p_url "net/url" + "time" +) + +type restClient struct { + token string +} + +func newRestClient(token string) *restClient { + restClient := new(restClient) + restClient.token = token + return restClient +} + +func (c *restClient) Get(url string, result interface{}, expectedStatus int) error { + return c.doRequest(url, "GET", nil, result, expectedStatus) +} + +func (c *restClient) Delete(url string, requestBody interface{}, result interface{}, expectedStatus int) error { + return c.doRequest(url, "DELETE", requestBody, result, expectedStatus) +} + +func (c *restClient) Post(url string, requestBody interface{}, result interface{}, expectedStatus int) error { + return c.doRequest(url, "POST", requestBody, result, expectedStatus) +} + +func (c *restClient) Put(url string, requestBody interface{}, result interface{}, expectedStatus int) error { + return c.doRequest(url, "PUT", requestBody, result, expectedStatus) +} + +func (c *restClient) doRequest(url string, method string, requestBody interface{}, result interface{}, expectedStatus int) error { + var bodyData io.Reader + if requestBody != nil { + data, _ := json.Marshal(requestBody) + bodyData = bytes.NewBuffer(data) + } + + request, err := http.NewRequest(method, url, bodyData) + if err != nil { + return err + } + + request.Header.Add("X-Token", c.token) + request.Header.Add("Content-Type", "application/json") + client := http.Client{} + response, err := client.Do(request) + if err = isError(response, expectedStatus, err); err != nil { + return err + } + + defer response.Body.Close() + body, err := ioutil.ReadAll(response.Body) + if err != nil { + return err + } + return c.unmarshal(body, result) +} + +func (c *restClient) unmarshal(data []byte, result interface{}) error { + err := json.Unmarshal(data, result) + if err != nil { + // handle the case when the result is an empty array instead of an object + switch err.(type) { + case *json.UnmarshalTypeError: + var ra []interface{} + e := json.Unmarshal(data, &ra) + if e != nil { + return e + } else if len(ra) > 0 { + return err + } + return nil + default: + return err + } + } + + return nil +} + +func isError(response *http.Response, expectedStatus int, err error) error { + if err != nil { + return err + } + if response != nil { + if response.StatusCode == expectedStatus { + // we got a response with the expected HTTP status code, hence no error + return nil + } + body, _ := ioutil.ReadAll(response.Body) + // extract the API's error message to be returned later + er_resp := new(errorResponse) + err = json.Unmarshal(body, er_resp) + if err != nil { + return err + } + + return apiError{response.StatusCode, fmt.Sprintf("Type: %s; Message: %s", er_resp.Type, er_resp.Message)} + } + return errors.New("Generic error - no response from the REST API service.") +} + +func createUrl(api *API, sections ...interface{}) string { + url := api.Endpoint + for _, section := range sections { + url += "/" + fmt.Sprint(section) + } + return url +} + +func makeParameterMap(args ...interface{}) (map[string]interface{}, error) { + qps := make(map[string]interface{}, len(args)) + var is_true bool + var page, per_page int + var sort, query, fields string + + for i, p := range args { + switch i { + case 0: + page, is_true = p.(int) + if !is_true { + return nil, errors.New("1st parameter must be a page number (integer).") + } else if page > 0 { + qps["page"] = page + } + case 1: + per_page, is_true = p.(int) + if !is_true { + return nil, errors.New("2nd parameter must be a per_page number (integer).") + } else if per_page > 0 { + qps["per_page"] = per_page + } + case 2: + sort, is_true = p.(string) + if !is_true { + return nil, errors.New("3rd parameter must be a sorting property string (e.g. 'name' or '-name').") + } else if sort != "" { + qps["sort"] = sort + } + case 3: + query, is_true = p.(string) + if !is_true { + return nil, errors.New("4th parameter must be a query string to look for the response.") + } else if query != "" { + qps["q"] = query + } + case 4: + fields, is_true = p.(string) + if !is_true { + return nil, errors.New("5th parameter must be fields properties string (e.g. 'id,name').") + } else if fields != "" { + qps["fields"] = fields + } + default: + return nil, errors.New("Wrong number of parameters.") + } + } + return qps, nil +} + +func processQueryParams(url string, args ...interface{}) (string, error) { + if len(args) > 0 { + params, err := makeParameterMap(args...) + if err != nil { + return "", err + } + url = appendQueryParams(url, params) + } + return url, nil +} + +func processQueryParamsExt(url string, period string, sd *time.Time, ed *time.Time, args ...interface{}) (string, error) { + var qm map[string]interface{} + var err error + if len(args) > 0 { + qm, err = makeParameterMap(args...) + if err != nil { + return "", err + } + } else { + qm = make(map[string]interface{}, 3) + } + qm["period"] = period + if sd != nil && ed != nil { + if sd.After(*ed) { + return "", errors.New("Start date cannot be after end date.") + } + qm["start_date"] = sd.Format(time.RFC3339) + qm["end_date"] = ed.Format(time.RFC3339) + } + url = appendQueryParams(url, qm) + return url, nil +} + +func appendQueryParams(url string, params map[string]interface{}) string { + queryUrl, _ := p_url.Parse(url) + parameters := p_url.Values{} + for key, value := range params { + parameters.Add(key, fmt.Sprintf("%v", value)) + } + queryUrl.RawQuery = parameters.Encode() + return queryUrl.String() +} diff --git a/vendor/github.com/1and1/oneandone-cloudserver-sdk-go/roles.go b/vendor/github.com/1and1/oneandone-cloudserver-sdk-go/roles.go new file mode 100644 index 000000000..e8aa44fee --- /dev/null +++ b/vendor/github.com/1and1/oneandone-cloudserver-sdk-go/roles.go @@ -0,0 +1,595 @@ +package oneandone + +import "net/http" + +type Role struct { + Identity + descField + CreationDate string `json:"creation_date,omitempty"` + State string `json:"state,omitempty"` + Default *int `json:"default,omitempty"` + Permissions *Permissions `json:"permissions,omitempty"` + Users []Identity `json:"users,omitempty"` + ApiPtr +} + +type Permissions struct { + Backups *BackupPerm `json:"backups,omitempty"` + Firewalls *FirewallPerm `json:"firewall_policies,omitempty"` + Images *ImagePerm `json:"images,omitempty"` + Invoice *InvoicePerm `json:"interactive_invoices,omitempty"` + IPs *IPPerm `json:"public_ips,omitempty"` + LoadBalancers *LoadBalancerPerm `json:"load_balancers,omitempty"` + Logs *LogPerm `json:"logs,omitempty"` + MonitorCenter *MonitorCenterPerm `json:"monitoring_center,omitempty"` + MonitorPolicies *MonitorPolicyPerm `json:"monitoring_policies,omitempty"` + PrivateNetworks *PrivateNetworkPerm `json:"private_networks,omitempty"` + Roles *RolePerm `json:"roles,omitempty"` + Servers *ServerPerm `json:"servers,omitempty"` + SharedStorage *SharedStoragePerm `json:"shared_storages,omitempty"` + Usages *UsagePerm `json:"usages,omitempty"` + Users *UserPerm `json:"users,omitempty"` + VPNs *VPNPerm `json:"vpn,omitempty"` +} + +type BackupPerm struct { + Create bool `json:"create"` + Delete bool `json:"delete"` + Show bool `json:"show"` +} + +type FirewallPerm struct { + Clone bool `json:"clone"` + Create bool `json:"create"` + Delete bool `json:"delete"` + ManageAttachedServerIPs bool `json:"manage_attached_server_ips"` + ManageRules bool `json:"manage_rules"` + SetDescription bool `json:"set_description"` + SetName bool `json:"set_name"` + Show bool `json:"show"` +} + +type ImagePerm struct { + Create bool `json:"create"` + Delete bool `json:"delete"` + DisableAutoCreate bool `json:"disable_automatic_creation"` + SetDescription bool `json:"set_description"` + SetName bool `json:"set_name"` + Show bool `json:"show"` +} + +type InvoicePerm struct { + Show bool `json:"show"` +} + +type IPPerm struct { + Create bool `json:"create"` + Delete bool `json:"delete"` + Release bool `json:"release"` + SetReverseDNS bool `json:"set_reverse_dns"` + Show bool `json:"show"` +} + +type LoadBalancerPerm struct { + Create bool `json:"create"` + Delete bool `json:"delete"` + ManageAttachedServerIPs bool `json:"manage_attached_server_ips"` + ManageRules bool `json:"manage_rules"` + Modify bool `json:"modify"` + SetDescription bool `json:"set_description"` + SetName bool `json:"set_name"` + Show bool `json:"show"` +} + +type LogPerm struct { + Show bool `json:"show"` +} + +type MonitorCenterPerm struct { + Show bool `json:"show"` +} + +type MonitorPolicyPerm struct { + Clone bool `json:"clone"` + Create bool `json:"create"` + Delete bool `json:"delete"` + ManageAttachedServers bool `json:"manage_attached_servers"` + ManagePorts bool `json:"manage_ports"` + ManageProcesses bool `json:"manage_processes"` + ModifyResources bool `json:"modify_resources"` + SetDescription bool `json:"set_description"` + SetEmail bool `json:"set_email"` + SetName bool `json:"set_name"` + Show bool `json:"show"` +} + +type PrivateNetworkPerm struct { + Create bool `json:"create"` + Delete bool `json:"delete"` + ManageAttachedServers bool `json:"manage_attached_servers"` + SetDescription bool `json:"set_description"` + SetName bool `json:"set_name"` + SetNetworkInfo bool `json:"set_network_info"` + Show bool `json:"show"` +} + +type RolePerm struct { + Clone bool `json:"clone"` + Create bool `json:"create"` + Delete bool `json:"delete"` + ManageUsers bool `json:"manage_users"` + Modify bool `json:"modify"` + SetDescription bool `json:"set_description"` + SetName bool `json:"set_name"` + Show bool `json:"show"` +} + +type ServerPerm struct { + AccessKVMConsole bool `json:"access_kvm_console"` + AssignIP bool `json:"assign_ip"` + Clone bool `json:"clone"` + Create bool `json:"create"` + Delete bool `json:"delete"` + ManageDVD bool `json:"manage_dvd"` + ManageSnapshot bool `json:"manage_snapshot"` + Reinstall bool `json:"reinstall"` + Resize bool `json:"resize"` + Restart bool `json:"restart"` + SetDescription bool `json:"set_description"` + SetName bool `json:"set_name"` + Show bool `json:"show"` + Shutdown bool `json:"shutdown"` + Start bool `json:"start"` +} + +type SharedStoragePerm struct { + Access bool `json:"access"` + Create bool `json:"create"` + Delete bool `json:"delete"` + ManageAttachedServers bool `json:"manage_attached_servers"` + Resize bool `json:"resize"` + SetDescription bool `json:"set_description"` + SetName bool `json:"set_name"` + Show bool `json:"show"` +} + +type UsagePerm struct { + Show bool `json:"show"` +} + +type UserPerm struct { + ChangeRole bool `json:"change_role"` + Create bool `json:"create"` + Delete bool `json:"delete"` + Disable bool `json:"disable"` + Enable bool `json:"enable"` + ManageAPI bool `json:"manage_api"` + SetDescription bool `json:"set_description"` + SetEmail bool `json:"set_email"` + SetPassword bool `json:"set_password"` + Show bool `json:"show"` +} + +type VPNPerm struct { + Create bool `json:"create"` + Delete bool `json:"delete"` + DownloadFile bool `json:"download_file"` + SetDescription bool `json:"set_description"` + SetName bool `json:"set_name"` + Show bool `json:"show"` +} + +// GET /roles +func (api *API) ListRoles(args ...interface{}) ([]Role, error) { + url, err := processQueryParams(createUrl(api, rolePathSegment), args...) + if err != nil { + return nil, err + } + result := []Role{} + err = api.Client.Get(url, &result, http.StatusOK) + if err != nil { + return nil, err + } + for _, role := range result { + role.api = api + } + return result, nil +} + +// POST /roles +func (api *API) CreateRole(name string) (string, *Role, error) { + result := new(Role) + url := createUrl(api, rolePathSegment) + req := struct { + Name string `json:"name"` + }{name} + err := api.Client.Post(url, &req, &result, http.StatusCreated) + if err != nil { + return "", nil, err + } + result.api = api + return result.Id, result, nil +} + +// GET /roles/{role_id} +func (api *API) GetRole(role_id string) (*Role, error) { + result := new(Role) + url := createUrl(api, rolePathSegment, role_id) + err := api.Client.Get(url, &result, http.StatusOK) + if err != nil { + return nil, err + } + result.api = api + return result, nil +} + +// PUT /roles/{role_id} +func (api *API) ModifyRole(role_id string, name string, description string, state string) (*Role, error) { + result := new(Role) + url := createUrl(api, rolePathSegment, role_id) + req := struct { + Name string `json:"name,omitempty"` + Description string `json:"description,omitempty"` + State string `json:"state,omitempty"` + }{Name: name, Description: description, State: state} + err := api.Client.Put(url, &req, &result, http.StatusOK) + if err != nil { + return nil, err + } + result.api = api + return result, nil +} + +// DELETE /roles/{role_id} +func (api *API) DeleteRole(role_id string) (*Role, error) { + result := new(Role) + url := createUrl(api, rolePathSegment, role_id) + err := api.Client.Delete(url, nil, &result, http.StatusOK) + if err != nil { + return nil, err + } + result.api = api + return result, nil +} + +// GET /roles/{role_id}/permissions +func (api *API) GetRolePermissions(role_id string) (*Permissions, error) { + result := new(Permissions) + url := createUrl(api, rolePathSegment, role_id, "permissions") + err := api.Client.Get(url, &result, http.StatusOK) + if err != nil { + return nil, err + } + return result, nil +} + +// PUT /roles/{role_id}/permissions +func (api *API) ModifyRolePermissions(role_id string, perm *Permissions) (*Role, error) { + result := new(Role) + url := createUrl(api, rolePathSegment, role_id, "permissions") + err := api.Client.Put(url, &perm, &result, http.StatusOK) + if err != nil { + return nil, err + } + result.api = api + return result, nil +} + +// GET /roles/{role_id}/users +func (api *API) ListRoleUsers(role_id string) ([]Identity, error) { + result := []Identity{} + url := createUrl(api, rolePathSegment, role_id, "users") + err := api.Client.Get(url, &result, http.StatusOK) + if err != nil { + return nil, err + } + return result, nil +} + +// POST /roles/{role_id}/users +func (api *API) AssignRoleUsers(role_id string, user_ids []string) (*Role, error) { + result := new(Role) + url := createUrl(api, rolePathSegment, role_id, "users") + req := struct { + Users []string `json:"users"` + }{user_ids} + err := api.Client.Post(url, &req, &result, http.StatusCreated) + if err != nil { + return nil, err + } + result.api = api + return result, nil +} + +// GET /roles/{role_id}/users/{user_id} +func (api *API) GetRoleUser(role_id string, user_id string) (*Identity, error) { + result := new(Identity) + url := createUrl(api, rolePathSegment, role_id, "users", user_id) + err := api.Client.Get(url, &result, http.StatusOK) + if err != nil { + return nil, err + } + return result, nil +} + +// DELETE /roles/{role_id}/users/{user_id} +func (api *API) RemoveRoleUser(role_id string, user_id string) (*Role, error) { + result := new(Role) + url := createUrl(api, rolePathSegment, role_id, "users", user_id) + err := api.Client.Delete(url, nil, &result, http.StatusAccepted) + if err != nil { + return nil, err + } + result.api = api + return result, nil +} + +// POST /roles/{role_id}/clone +func (api *API) CloneRole(role_id string, name string) (*Role, error) { + result := new(Role) + url := createUrl(api, rolePathSegment, role_id, "clone") + req := struct { + Name string `json:"name"` + }{name} + err := api.Client.Post(url, &req, &result, http.StatusCreated) + if err != nil { + return nil, err + } + result.api = api + return result, nil +} + +func (role *Role) GetState() (string, error) { + in, err := role.api.GetRole(role.Id) + if in == nil { + return "", err + } + return in.State, err +} + +// Sets all backups' permissions +func (bp *BackupPerm) SetAll(value bool) { + bp.Create = value + bp.Delete = value + bp.Show = value +} + +// Sets all firewall policies' permissions +func (fp *FirewallPerm) SetAll(value bool) { + fp.Clone = value + fp.Create = value + fp.Delete = value + fp.ManageAttachedServerIPs = value + fp.ManageRules = value + fp.SetDescription = value + fp.SetName = value + fp.Show = value +} + +// Sets all images' permissions +func (imp *ImagePerm) SetAll(value bool) { + imp.Create = value + imp.Delete = value + imp.DisableAutoCreate = value + imp.SetDescription = value + imp.SetName = value + imp.Show = value +} + +// Sets all invoice's permissions +func (inp *InvoicePerm) SetAll(value bool) { + inp.Show = value +} + +// Sets all IPs' permissions +func (ipp *IPPerm) SetAll(value bool) { + ipp.Create = value + ipp.Delete = value + ipp.Release = value + ipp.SetReverseDNS = value + ipp.Show = value +} + +// Sets all load balancers' permissions +func (lbp *LoadBalancerPerm) SetAll(value bool) { + lbp.Create = value + lbp.Delete = value + lbp.ManageAttachedServerIPs = value + lbp.ManageRules = value + lbp.Modify = value + lbp.SetDescription = value + lbp.SetName = value + lbp.Show = value +} + +// Sets all logs' permissions +func (lp *LogPerm) SetAll(value bool) { + lp.Show = value +} + +// Sets all monitoring center's permissions +func (mcp *MonitorCenterPerm) SetAll(value bool) { + mcp.Show = value +} + +// Sets all monitoring policies' permissions +func (mpp *MonitorPolicyPerm) SetAll(value bool) { + mpp.Clone = value + mpp.Create = value + mpp.Delete = value + mpp.ManageAttachedServers = value + mpp.ManagePorts = value + mpp.ManageProcesses = value + mpp.ModifyResources = value + mpp.SetDescription = value + mpp.SetEmail = value + mpp.SetName = value + mpp.Show = value +} + +// Sets all private networks' permissions +func (pnp *PrivateNetworkPerm) SetAll(value bool) { + pnp.Create = value + pnp.Delete = value + pnp.ManageAttachedServers = value + pnp.SetDescription = value + pnp.SetName = value + pnp.SetNetworkInfo = value + pnp.Show = value +} + +// Sets all roles' permissions +func (rp *RolePerm) SetAll(value bool) { + rp.Clone = value + rp.Create = value + rp.Delete = value + rp.ManageUsers = value + rp.Modify = value + rp.SetDescription = value + rp.SetName = value + rp.Show = value +} + +// Sets all servers' permissions +func (sp *ServerPerm) SetAll(value bool) { + sp.AccessKVMConsole = value + sp.AssignIP = value + sp.Clone = value + sp.Create = value + sp.Delete = value + sp.ManageDVD = value + sp.ManageSnapshot = value + sp.Reinstall = value + sp.Resize = value + sp.Restart = value + sp.SetDescription = value + sp.SetName = value + sp.Show = value + sp.Shutdown = value + sp.Start = value +} + +// Sets all shared storages' permissions +func (ssp *SharedStoragePerm) SetAll(value bool) { + ssp.Access = value + ssp.Create = value + ssp.Delete = value + ssp.ManageAttachedServers = value + ssp.Resize = value + ssp.SetDescription = value + ssp.SetName = value + ssp.Show = value +} + +// Sets all usages' permissions +func (up *UsagePerm) SetAll(value bool) { + up.Show = value +} + +// Sets all users' permissions +func (up *UserPerm) SetAll(value bool) { + up.ChangeRole = value + up.Create = value + up.Delete = value + up.Disable = value + up.Enable = value + up.ManageAPI = value + up.SetDescription = value + up.SetEmail = value + up.SetPassword = value + up.Show = value +} + +// Sets all VPNs' permissions +func (vpnp *VPNPerm) SetAll(value bool) { + vpnp.Create = value + vpnp.Delete = value + vpnp.DownloadFile = value + vpnp.SetDescription = value + vpnp.SetName = value + vpnp.Show = value +} + +// Sets all available permissions +func (p *Permissions) SetAll(v bool) { + if p.Backups == nil { + p.Backups = &BackupPerm{v, v, v} + } else { + p.Backups.SetAll(v) + } + if p.Firewalls == nil { + p.Firewalls = &FirewallPerm{v, v, v, v, v, v, v, v} + } else { + p.Firewalls.SetAll(v) + } + if p.Images == nil { + p.Images = &ImagePerm{v, v, v, v, v, v} + } else { + p.Images.SetAll(v) + } + if p.Invoice == nil { + p.Invoice = &InvoicePerm{v} + } else { + p.Invoice.SetAll(v) + } + if p.IPs == nil { + p.IPs = &IPPerm{v, v, v, v, v} + } else { + p.IPs.SetAll(v) + } + if p.LoadBalancers == nil { + p.LoadBalancers = &LoadBalancerPerm{v, v, v, v, v, v, v, v} + } else { + p.LoadBalancers.SetAll(v) + } + if p.Logs == nil { + p.Logs = &LogPerm{v} + } else { + p.Logs.SetAll(v) + } + if p.MonitorCenter == nil { + p.MonitorCenter = &MonitorCenterPerm{v} + } else { + p.MonitorCenter.SetAll(v) + } + if p.MonitorPolicies == nil { + p.MonitorPolicies = &MonitorPolicyPerm{v, v, v, v, v, v, v, v, v, v, v} + } else { + p.MonitorPolicies.SetAll(v) + } + if p.PrivateNetworks == nil { + p.PrivateNetworks = &PrivateNetworkPerm{v, v, v, v, v, v, v} + } else { + p.PrivateNetworks.SetAll(v) + } + if p.Roles == nil { + p.Roles = &RolePerm{v, v, v, v, v, v, v, v} + } else { + p.Roles.SetAll(v) + } + if p.Servers == nil { + p.Servers = &ServerPerm{v, v, v, v, v, v, v, v, v, v, v, v, v, v, v} + } else { + p.Servers.SetAll(v) + } + if p.SharedStorage == nil { + p.SharedStorage = &SharedStoragePerm{v, v, v, v, v, v, v, v} + } else { + p.SharedStorage.SetAll(v) + } + if p.Usages == nil { + p.Usages = &UsagePerm{v} + } else { + p.Usages.SetAll(v) + } + if p.Users == nil { + p.Users = &UserPerm{v, v, v, v, v, v, v, v, v, v} + } else { + p.Users.SetAll(v) + } + if p.VPNs == nil { + p.VPNs = &VPNPerm{v, v, v, v, v, v} + } else { + p.VPNs.SetAll(v) + } +} diff --git a/vendor/github.com/1and1/oneandone-cloudserver-sdk-go/serverappliances.go b/vendor/github.com/1and1/oneandone-cloudserver-sdk-go/serverappliances.go new file mode 100644 index 000000000..03c45f3d8 --- /dev/null +++ b/vendor/github.com/1and1/oneandone-cloudserver-sdk-go/serverappliances.go @@ -0,0 +1,48 @@ +package oneandone + +import "net/http" + +type ServerAppliance struct { + Identity + typeField + OsInstallBase string `json:"os_installation_base,omitempty"` + OsFamily string `json:"os_family,omitempty"` + Os string `json:"os,omitempty"` + OsVersion string `json:"os_version,omitempty"` + Version string `json:"version,omitempty"` + MinHddSize int `json:"min_hdd_size"` + Architecture interface{} `json:"os_architecture"` + Licenses interface{} `json:"licenses,omitempty"` + Categories []string `json:"categories,omitempty"` + // AvailableDatacenters []string `json:"available_datacenters,omitempty"` + ApiPtr +} + +// GET /server_appliances +func (api *API) ListServerAppliances(args ...interface{}) ([]ServerAppliance, error) { + url, err := processQueryParams(createUrl(api, serverAppliancePathSegment), args...) + if err != nil { + return nil, err + } + res := []ServerAppliance{} + err = api.Client.Get(url, &res, http.StatusOK) + if err != nil { + return nil, err + } + for index, _ := range res { + res[index].api = api + } + return res, nil +} + +// GET /server_appliances/{id} +func (api *API) GetServerAppliance(sa_id string) (*ServerAppliance, error) { + res := new(ServerAppliance) + url := createUrl(api, serverAppliancePathSegment, sa_id) + err := api.Client.Get(url, &res, http.StatusOK) + if err != nil { + return nil, err + } + // res.api = api + return res, nil +} diff --git a/vendor/github.com/1and1/oneandone-cloudserver-sdk-go/servers.go b/vendor/github.com/1and1/oneandone-cloudserver-sdk-go/servers.go new file mode 100644 index 000000000..18fad51a2 --- /dev/null +++ b/vendor/github.com/1and1/oneandone-cloudserver-sdk-go/servers.go @@ -0,0 +1,808 @@ +package oneandone + +import ( + "encoding/json" + "errors" + "math/big" + "net/http" +) + +type Server struct { + ApiPtr + Identity + descField + CloudPanelId string `json:"cloudpanel_id,omitempty"` + CreationDate string `json:"creation_date,omitempty"` + FirstPassword string `json:"first_password,omitempty"` + Datacenter *Datacenter `json:"datacenter,omitempty"` + Status *Status `json:"status,omitempty"` + Hardware *Hardware `json:"hardware,omitempty"` + Image *Identity `json:"image,omitempty"` + Dvd *Identity `json:"dvd,omitempty"` + MonPolicy *Identity `json:"monitoring_policy,omitempty"` + Snapshot *ServerSnapshot `json:"snapshot,omitempty"` + Ips []ServerIp `json:"ips,omitempty"` + PrivateNets []Identity `json:"private_networks,omitempty"` + Alerts *ServerAlerts `json:"-"` + AlertsRaw *json.RawMessage `json:"alerts,omitempty"` +} + +type Hardware struct { + Vcores int `json:"vcore,omitempty"` + CoresPerProcessor int `json:"cores_per_processor"` + Ram float32 `json:"ram"` + Hdds []Hdd `json:"hdds,omitempty"` + FixedInsSizeId string `json:"fixed_instance_size_id,omitempty"` + ApiPtr +} + +type ServerHdds struct { + Hdds []Hdd `json:"hdds,omitempty"` +} + +type Hdd struct { + idField + Size int `json:"size,omitempty"` + IsMain bool `json:"is_main,omitempty"` + ApiPtr +} + +type serverDeployImage struct { + idField + Password string `json:"password,omitempty"` + Firewall *Identity `json:"firewall_policy,omitempty"` +} + +type ServerIp struct { + idField + typeField + Ip string `json:"ip,omitempty"` + ReverseDns string `json:"reverse_dns,omitempty"` + Firewall *Identity `json:"firewall_policy,omitempty"` + LoadBalancers []Identity `json:"load_balancers,omitempty"` + ApiPtr +} + +type ServerIpInfo struct { + idField // IP id + Ip string `json:"ip,omitempty"` + ServerName string `json:"server_name,omitempty"` +} + +type ServerSnapshot struct { + idField + CreationDate string `json:"creation_date,omitempty"` + DeletionDate string `json:"deletion_date,omitempty"` +} + +type ServerAlerts struct { + AlertSummary []serverAlertSummary + AlertDetails *serverAlertDetails +} + +type serverAlertSummary struct { + countField + typeField +} + +type serverAlertDetails struct { + Criticals []ServerAlert `json:"critical,omitempty"` + Warnings []ServerAlert `json:"warning,omitempty"` +} + +type ServerAlert struct { + typeField + descField + Date string `json:"date"` +} + +type ServerRequest struct { + Name string `json:"name,omitempty"` + Description string `json:"description,omitempty"` + Hardware Hardware `json:"hardware"` + ApplianceId string `json:"appliance_id,omitempty"` + Password string `json:"password,omitempty"` + PowerOn bool `json:"power_on"` + FirewallPolicyId string `json:"firewall_policy_id,omitempty"` + IpId string `json:"ip_id,omitempty"` + LoadBalancerId string `json:"load_balancer_id,omitempty"` + MonitoringPolicyId string `json:"monitoring_policy_id,omitempty"` + DatacenterId string `json:"datacenter_id,omitempty"` + SSHKey string `json:"rsa_key,omitempty"` +} + +type ServerAction struct { + Action string `json:"action,omitempty"` + Method string `json:"method,omitempty"` +} + +type FixedInstanceInfo struct { + Identity + Hardware *Hardware `json:"hardware,omitempty"` + ApiPtr +} + +// GET /servers +func (api *API) ListServers(args ...interface{}) ([]Server, error) { + url, err := processQueryParams(createUrl(api, serverPathSegment), args...) + if err != nil { + return nil, err + } + result := []Server{} + err = api.Client.Get(url, &result, http.StatusOK) + if err != nil { + return nil, err + } + for _, s := range result { + s.api = api + s.decodeRaws() + } + return result, nil +} + +// POST /servers +func (api *API) CreateServer(request *ServerRequest) (string, *Server, error) { + result := new(Server) + url := createUrl(api, serverPathSegment) + insert2map := func(hasht map[string]interface{}, key string, value string) { + if key != "" && value != "" { + hasht[key] = value + } + } + req := make(map[string]interface{}) + hw := make(map[string]interface{}) + req["name"] = request.Name + req["description"] = request.Description + req["appliance_id"] = request.ApplianceId + req["power_on"] = request.PowerOn + insert2map(req, "password", request.Password) + insert2map(req, "firewall_policy_id", request.FirewallPolicyId) + insert2map(req, "ip_id", request.IpId) + insert2map(req, "load_balancer_id", request.LoadBalancerId) + insert2map(req, "monitoring_policy_id", request.MonitoringPolicyId) + insert2map(req, "datacenter_id", request.DatacenterId) + insert2map(req, "rsa_key", request.SSHKey) + req["hardware"] = hw + if request.Hardware.FixedInsSizeId != "" { + hw["fixed_instance_size_id"] = request.Hardware.FixedInsSizeId + } else { + hw["vcore"] = request.Hardware.Vcores + hw["cores_per_processor"] = request.Hardware.CoresPerProcessor + hw["ram"] = request.Hardware.Ram + hw["hdds"] = request.Hardware.Hdds + } + err := api.Client.Post(url, &req, &result, http.StatusAccepted) + if err != nil { + return "", nil, err + } + result.api = api + result.decodeRaws() + return result.Id, result, nil +} + +// This is a wraper function for `CreateServer` that returns the server's IP address and first password. +// The function waits at most `timeout` seconds for the server to be created. +// The initial `POST /servers` response does not contain the IP address, so we need to wait +// until the server is created. +func (api *API) CreateServerEx(request *ServerRequest, timeout int) (string, string, error) { + id, server, err := api.CreateServer(request) + if server != nil && err == nil { + count := timeout / 5 + if request.PowerOn { + err = api.WaitForState(server, "POWERED_ON", 5, count) + } else { + err = api.WaitForState(server, "POWERED_OFF", 5, count) + } + if err != nil { + return "", "", err + } + server, err := api.GetServer(id) + if server != nil && err == nil && server.Ips[0].Ip != "" { + if server.FirstPassword != "" { + return server.Ips[0].Ip, server.FirstPassword, nil + } + if request.Password != "" { + return server.Ips[0].Ip, request.Password, nil + } + // should never reach here + return "", "", errors.New("No server's password was found.") + } + } + return "", "", err +} + +// GET /servers/{id} +func (api *API) GetServer(server_id string) (*Server, error) { + result := new(Server) + url := createUrl(api, serverPathSegment, server_id) + err := api.Client.Get(url, &result, http.StatusOK) + if err != nil { + return nil, err + } + result.api = api + result.decodeRaws() + return result, nil +} + +// GET /servers/fixed_instance_sizes +func (api *API) ListFixedInstanceSizes() ([]FixedInstanceInfo, error) { + result := []FixedInstanceInfo{} + url := createUrl(api, serverPathSegment, "fixed_instance_sizes") + err := api.Client.Get(url, &result, http.StatusOK) + if err != nil { + return nil, err + } + for index, _ := range result { + result[index].api = api + } + return result, nil +} + +// GET /servers/fixed_instance_sizes/{fixed_instance_size_id} +func (api *API) GetFixedInstanceSize(fis_id string) (*FixedInstanceInfo, error) { + result := new(FixedInstanceInfo) + url := createUrl(api, serverPathSegment, "fixed_instance_sizes", fis_id) + err := api.Client.Get(url, &result, http.StatusOK) + if err != nil { + return nil, err + } + result.api = api + return result, nil +} + +// DELETE /servers/{id} +func (api *API) DeleteServer(server_id string, keep_ips bool) (*Server, error) { + result := new(Server) + url := createUrl(api, serverPathSegment, server_id) + pm := make(map[string]interface{}, 1) + pm["keep_ips"] = keep_ips + url = appendQueryParams(url, pm) + err := api.Client.Delete(url, nil, &result, http.StatusAccepted) + if err != nil { + return nil, err + } + result.api = api + result.decodeRaws() + return result, nil +} + +// PUT /servers/{id} +func (api *API) RenameServer(server_id string, new_name string, new_desc string) (*Server, error) { + data := struct { + Name string `json:"name,omitempty"` + Description string `json:"description,omitempty"` + }{Name: new_name, Description: new_desc} + result := new(Server) + url := createUrl(api, serverPathSegment, server_id) + err := api.Client.Put(url, &data, &result, http.StatusOK) + if err != nil { + return nil, err + } + result.api = api + result.decodeRaws() + return result, nil +} + +// GET /servers/{server_id}/hardware +func (api *API) GetServerHardware(server_id string) (*Hardware, error) { + result := new(Hardware) + url := createUrl(api, serverPathSegment, server_id, "hardware") + err := api.Client.Get(url, &result, http.StatusOK) + if err != nil { + return nil, err + } + result.api = api + return result, nil +} + +// PUT /servers/{server_id}/hardware +func (api *API) UpdateServerHardware(server_id string, hardware *Hardware) (*Server, error) { + var vc, cpp *int + var ram *float32 + if hardware.Vcores > 0 { + vc = new(int) + *vc = hardware.Vcores + } + if hardware.CoresPerProcessor > 0 { + cpp = new(int) + *cpp = hardware.CoresPerProcessor + } + if big.NewFloat(float64(hardware.Ram)).Cmp(big.NewFloat(0)) != 0 { + ram = new(float32) + *ram = hardware.Ram + } + req := struct { + VCores *int `json:"vcore,omitempty"` + Cpp *int `json:"cores_per_processor,omitempty"` + Ram *float32 `json:"ram,omitempty"` + Flavor string `json:"fixed_instance_size_id,omitempty"` + }{VCores: vc, Cpp: cpp, Ram: ram, Flavor: hardware.FixedInsSizeId} + + result := new(Server) + url := createUrl(api, serverPathSegment, server_id, "hardware") + err := api.Client.Put(url, &req, &result, http.StatusAccepted) + if err != nil { + return nil, err + } + result.api = api + result.decodeRaws() + return result, nil +} + +// GET /servers/{id}/hardware/hdds +func (api *API) ListServerHdds(server_id string) ([]Hdd, error) { + result := []Hdd{} + url := createUrl(api, serverPathSegment, server_id, "hardware/hdds") + err := api.Client.Get(url, &result, http.StatusOK) + if err != nil { + return nil, err + } + for index, _ := range result { + result[index].api = api + } + return result, nil +} + +// POST /servers/{id}/hardware/hdds +func (api *API) AddServerHdds(server_id string, hdds *ServerHdds) (*Server, error) { + result := new(Server) + url := createUrl(api, serverPathSegment, server_id, "hardware/hdds") + err := api.Client.Post(url, &hdds, &result, http.StatusAccepted) + if err != nil { + return nil, err + } + result.api = api + result.decodeRaws() + return result, nil +} + +// GET /servers/{id}/hardware/hdds/{id} +func (api *API) GetServerHdd(server_id string, hdd_id string) (*Hdd, error) { + result := new(Hdd) + url := createUrl(api, serverPathSegment, server_id, "hardware/hdds", hdd_id) + err := api.Client.Get(url, &result, http.StatusOK) + if err != nil { + return nil, err + } + result.api = api + return result, nil +} + +// DELETE /servers/{id}/hardware/hdds/{id} +func (api *API) DeleteServerHdd(server_id string, hdd_id string) (*Server, error) { + result := new(Server) + url := createUrl(api, serverPathSegment, server_id, "hardware/hdds", hdd_id) + err := api.Client.Delete(url, nil, &result, http.StatusAccepted) + if err != nil { + return nil, err + } + result.api = api + result.decodeRaws() + return result, nil +} + +// PUT /servers/{id}/hardware/hdds/{id} +func (api *API) ResizeServerHdd(server_id string, hdd_id string, new_size int) (*Server, error) { + data := Hdd{Size: new_size} + result := new(Server) + url := createUrl(api, serverPathSegment, server_id, "hardware/hdds", hdd_id) + err := api.Client.Put(url, &data, &result, http.StatusAccepted) + if err != nil { + return nil, err + } + result.api = api + result.decodeRaws() + return result, nil +} + +// GET /servers/{id}/image +func (api *API) GetServerImage(server_id string) (*Identity, error) { + result := new(Identity) + url := createUrl(api, serverPathSegment, server_id, "image") + err := api.Client.Get(url, &result, http.StatusOK) + if err != nil { + return nil, err + } + return result, nil +} + +// PUT /servers/{id}/image +func (api *API) ReinstallServerImage(server_id string, image_id string, password string, fp_id string) (*Server, error) { + data := new(serverDeployImage) + data.Id = image_id + data.Password = password + if fp_id != "" { + fp := new(Identity) + fp.Id = fp_id + data.Firewall = fp + } + + result := new(Server) + url := createUrl(api, serverPathSegment, server_id, "image") + err := api.Client.Put(url, &data, &result, http.StatusAccepted) + if err != nil { + return nil, err + } + result.api = api + result.decodeRaws() + return result, nil +} + +// GET /servers/{id}/ips +func (api *API) ListServerIps(server_id string) ([]ServerIp, error) { + result := []ServerIp{} + url := createUrl(api, serverPathSegment, server_id, "ips") + err := api.Client.Get(url, &result, http.StatusOK) + if err != nil { + return nil, err + } + for index, _ := range result { + result[index].api = api + } + return result, nil +} + +// POST /servers/{id}/ips +func (api *API) AssignServerIp(server_id string, ip_type string) (*Server, error) { + data := typeField{Type: ip_type} + result := new(Server) + url := createUrl(api, serverPathSegment, server_id, "ips") + err := api.Client.Post(url, &data, &result, http.StatusCreated) + if err != nil { + return nil, err + } + result.api = api + result.decodeRaws() + return result, nil +} + +// GET /servers/{id}/ips/{id} +func (api *API) GetServerIp(server_id string, ip_id string) (*ServerIp, error) { + result := new(ServerIp) + url := createUrl(api, serverPathSegment, server_id, "ips", ip_id) + err := api.Client.Get(url, &result, http.StatusOK) + if err != nil { + return nil, err + } + result.api = api + return result, nil +} + +// DELETE /servers/{id}/ips/{id} +func (api *API) DeleteServerIp(server_id string, ip_id string, keep_ip bool) (*Server, error) { + result := new(Server) + url := createUrl(api, serverPathSegment, server_id, "ips", ip_id) + qm := make(map[string]interface{}, 1) + qm["keep_ip"] = keep_ip + url = appendQueryParams(url, qm) + err := api.Client.Delete(url, nil, &result, http.StatusAccepted) + if err != nil { + return nil, err + } + result.api = api + return result, nil +} + +// GET /servers/{id}/status +func (api *API) GetServerStatus(server_id string) (*Status, error) { + result := new(Status) + url := createUrl(api, serverPathSegment, server_id, "status") + err := api.Client.Get(url, &result, http.StatusOK) + if err != nil { + return nil, err + } + return result, nil +} + +// PUT /servers/{id}/status/action (action = REBOOT) +func (api *API) RebootServer(server_id string, is_hardware bool) (*Server, error) { + result := new(Server) + request := ServerAction{} + request.Action = "REBOOT" + if is_hardware { + request.Method = "HARDWARE" + } else { + request.Method = "SOFTWARE" + } + url := createUrl(api, serverPathSegment, server_id, "status", "action") + err := api.Client.Put(url, &request, &result, http.StatusAccepted) + if err != nil { + return nil, err + } + result.api = api + result.decodeRaws() + return result, nil +} + +// PUT /servers/{id}/status/action (action = POWER_OFF) +func (api *API) ShutdownServer(server_id string, is_hardware bool) (*Server, error) { + result := new(Server) + request := ServerAction{} + request.Action = "POWER_OFF" + if is_hardware { + request.Method = "HARDWARE" + } else { + request.Method = "SOFTWARE" + } + url := createUrl(api, serverPathSegment, server_id, "status", "action") + err := api.Client.Put(url, &request, &result, http.StatusAccepted) + if err != nil { + return nil, err + } + result.api = api + result.decodeRaws() + return result, nil +} + +// PUT /servers/{id}/status/action (action = POWER_ON) +func (api *API) StartServer(server_id string) (*Server, error) { + result := new(Server) + request := ServerAction{} + request.Action = "POWER_ON" + url := createUrl(api, serverPathSegment, server_id, "status", "action") + err := api.Client.Put(url, &request, &result, http.StatusAccepted) + if err != nil { + return nil, err + } + result.api = api + result.decodeRaws() + return result, nil +} + +// GET /servers/{id}/dvd +func (api *API) GetServerDvd(server_id string) (*Identity, error) { + result := new(Identity) + url := createUrl(api, serverPathSegment, server_id, "dvd") + err := api.Client.Get(url, &result, http.StatusOK) + if err != nil { + return nil, err + } + return result, nil +} + +// DELETE /servers/{id}/dvd +func (api *API) EjectServerDvd(server_id string) (*Server, error) { + result := new(Server) + url := createUrl(api, serverPathSegment, server_id, "dvd") + err := api.Client.Delete(url, nil, &result, http.StatusAccepted) + if err != nil { + return nil, err + } + result.api = api + result.decodeRaws() + return result, nil +} + +// PUT /servers/{id}/dvd +func (api *API) LoadServerDvd(server_id string, dvd_id string) (*Server, error) { + request := Identity{} + request.Id = dvd_id + result := new(Server) + url := createUrl(api, serverPathSegment, server_id, "dvd") + err := api.Client.Put(url, &request, &result, http.StatusAccepted) + if err != nil { + return nil, err + } + result.api = api + result.decodeRaws() + return result, nil +} + +// GET /servers/{id}/private_networks +func (api *API) ListServerPrivateNetworks(server_id string) ([]Identity, error) { + result := []Identity{} + url := createUrl(api, serverPathSegment, server_id, "private_networks") + err := api.Client.Get(url, &result, http.StatusOK) + if err != nil { + return nil, err + } + return result, nil +} + +// POST /servers/{id}/private_networks +func (api *API) AssignServerPrivateNetwork(server_id string, pn_id string) (*Server, error) { + req := new(Identity) + req.Id = pn_id + result := new(Server) + url := createUrl(api, serverPathSegment, server_id, "private_networks") + err := api.Client.Post(url, &req, &result, http.StatusAccepted) + if err != nil { + return nil, err + } + result.api = api + result.decodeRaws() + return result, nil +} + +// GET /servers/{id}/private_networks/{id} +func (api *API) GetServerPrivateNetwork(server_id string, pn_id string) (*PrivateNetwork, error) { + result := new(PrivateNetwork) + url := createUrl(api, serverPathSegment, server_id, "private_networks", pn_id) + err := api.Client.Get(url, &result, http.StatusOK) + if err != nil { + return nil, err + } + result.api = api + return result, nil +} + +// DELETE /servers/{id}/private_networks/{id} +func (api *API) RemoveServerPrivateNetwork(server_id string, pn_id string) (*Server, error) { + result := new(Server) + url := createUrl(api, serverPathSegment, server_id, "private_networks", pn_id) + err := api.Client.Delete(url, nil, &result, http.StatusAccepted) + if err != nil { + return nil, err + } + result.api = api + result.decodeRaws() + return result, nil +} + +// GET /servers/{server_id}/ips/{ip_id}/load_balancers +func (api *API) ListServerIpLoadBalancers(server_id string, ip_id string) ([]Identity, error) { + result := []Identity{} + url := createUrl(api, serverPathSegment, server_id, "ips", ip_id, "load_balancers") + err := api.Client.Get(url, &result, http.StatusOK) + if err != nil { + return nil, err + } + return result, nil +} + +// POST /servers/{server_id}/ips/{ip_id}/load_balancers +func (api *API) AssignServerIpLoadBalancer(server_id string, ip_id string, lb_id string) (*Server, error) { + req := struct { + LbId string `json:"load_balancer_id"` + }{lb_id} + result := new(Server) + url := createUrl(api, serverPathSegment, server_id, "ips", ip_id, "load_balancers") + err := api.Client.Post(url, &req, &result, http.StatusAccepted) + if err != nil { + return nil, err + } + result.api = api + result.decodeRaws() + return result, nil +} + +// DELETE /servers/{server_id}/ips/{ip_id}/load_balancers +func (api *API) UnassignServerIpLoadBalancer(server_id string, ip_id string, lb_id string) (*Server, error) { + result := new(Server) + url := createUrl(api, serverPathSegment, server_id, "ips", ip_id, "load_balancers", lb_id) + err := api.Client.Delete(url, nil, &result, http.StatusAccepted) + if err != nil { + return nil, err + } + result.api = api + result.decodeRaws() + return result, nil +} + +// GET /servers/{server_id}/ips/{ip_id}/firewall_policy +func (api *API) GetServerIpFirewallPolicy(server_id string, ip_id string) (*Identity, error) { + result := new(Identity) + url := createUrl(api, serverPathSegment, server_id, "ips", ip_id, "firewall_policy") + err := api.Client.Get(url, &result, http.StatusOK) + if err != nil { + return nil, err + } + return result, nil +} + +// PUT /servers/{server_id}/ips/{ip_id}/firewall_policy +func (api *API) AssignServerIpFirewallPolicy(server_id string, ip_id string, fp_id string) (*Server, error) { + req := idField{fp_id} + result := new(Server) + url := createUrl(api, serverPathSegment, server_id, "ips", ip_id, "firewall_policy") + err := api.Client.Put(url, &req, &result, http.StatusAccepted) + if err != nil { + return nil, err + } + result.api = api + result.decodeRaws() + return result, nil +} + +// DELETE /servers/{server_id}/ips/{ip_id}/firewall_policy +func (api *API) UnassignServerIpFirewallPolicy(server_id string, ip_id string) (*Server, error) { + result := new(Server) + url := createUrl(api, serverPathSegment, server_id, "ips", ip_id, "firewall_policy") + err := api.Client.Delete(url, nil, &result, http.StatusAccepted) + if err != nil { + return nil, err + } + result.api = api + result.decodeRaws() + return result, nil +} + +// GET /servers/{id}/snapshots +func (api *API) GetServerSnapshot(server_id string) (*ServerSnapshot, error) { + result := new(ServerSnapshot) + url := createUrl(api, serverPathSegment, server_id, "snapshots") + err := api.Client.Get(url, &result, http.StatusOK) + if err != nil { + return nil, err + } + return result, nil +} + +// POST /servers/{id}/snapshots +func (api *API) CreateServerSnapshot(server_id string) (*Server, error) { + result := new(Server) + url := createUrl(api, serverPathSegment, server_id, "snapshots") + err := api.Client.Post(url, nil, &result, http.StatusAccepted) + if err != nil { + return nil, err + } + result.api = api + result.decodeRaws() + return result, nil +} + +// PUT /servers/{server_id}/snapshots/{snapshot_id} +func (api *API) RestoreServerSnapshot(server_id string, snapshot_id string) (*Server, error) { + result := new(Server) + url := createUrl(api, serverPathSegment, server_id, "snapshots", snapshot_id) + err := api.Client.Put(url, nil, &result, http.StatusAccepted) + if err != nil { + return nil, err + } + result.api = api + result.decodeRaws() + return result, nil +} + +// DELETE /servers/{server_id}/snapshots/{snapshot_id} +func (api *API) DeleteServerSnapshot(server_id string, snapshot_id string) (*Server, error) { + result := new(Server) + url := createUrl(api, serverPathSegment, server_id, "snapshots", snapshot_id) + err := api.Client.Delete(url, nil, &result, http.StatusAccepted) + if err != nil { + return nil, err + } + result.api = api + result.decodeRaws() + return result, nil +} + +// POST /servers/{server_id}/clone +func (api *API) CloneServer(server_id string, new_name string, datacenter_id string) (*Server, error) { + data := struct { + Name string `json:"name"` + DatacenterId string `json:"datacenter_id,omitempty"` + }{Name: new_name, DatacenterId: datacenter_id} + result := new(Server) + url := createUrl(api, serverPathSegment, server_id, "clone") + err := api.Client.Post(url, &data, &result, http.StatusAccepted) + if err != nil { + return nil, err + } + result.api = api + result.decodeRaws() + return result, nil +} + +func (s *Server) GetState() (string, error) { + st, err := s.api.GetServerStatus(s.Id) + if st == nil { + return "", err + } + return st.State, err +} + +func (server *Server) decodeRaws() { + if server.AlertsRaw != nil { + server.Alerts = new(ServerAlerts) + var sad serverAlertDetails + if err := json.Unmarshal(*server.AlertsRaw, &sad); err == nil { + server.Alerts.AlertDetails = &sad + return + } + var sams []serverAlertSummary + if err := json.Unmarshal(*server.AlertsRaw, &sams); err == nil { + server.Alerts.AlertSummary = sams + } + } +} diff --git a/vendor/github.com/1and1/oneandone-cloudserver-sdk-go/setup.go b/vendor/github.com/1and1/oneandone-cloudserver-sdk-go/setup.go new file mode 100644 index 000000000..7d910c653 --- /dev/null +++ b/vendor/github.com/1and1/oneandone-cloudserver-sdk-go/setup.go @@ -0,0 +1,19 @@ +package oneandone + +// The base url for 1&1 Cloud Server REST API. +var BaseUrl = "https://cloudpanel-api.1and1.com/v1" + +// Authentication token +var Token string + +// SetBaseUrl is intended to set the REST base url. BaseUrl is declared in setup.go +func SetBaseUrl(newbaseurl string) string { + BaseUrl = newbaseurl + return BaseUrl +} + +// SetToken is used to set authentication Token for the REST service. Token is declared in setup.go +func SetToken(newtoken string) string { + Token = newtoken + return Token +} diff --git a/vendor/github.com/1and1/oneandone-cloudserver-sdk-go/sharedstorages.go b/vendor/github.com/1and1/oneandone-cloudserver-sdk-go/sharedstorages.go new file mode 100644 index 000000000..fdb2a7bfd --- /dev/null +++ b/vendor/github.com/1and1/oneandone-cloudserver-sdk-go/sharedstorages.go @@ -0,0 +1,190 @@ +package oneandone + +import ( + "net/http" +) + +type SharedStorage struct { + Identity + descField + Size int `json:"size"` + MinSizeAllowed int `json:"minimum_size_allowed"` + SizeUsed string `json:"size_used,omitempty"` + State string `json:"state,omitempty"` + CloudPanelId string `json:"cloudpanel_id,omitempty"` + SiteId string `json:"site_id,omitempty"` + CifsPath string `json:"cifs_path,omitempty"` + NfsPath string `json:"nfs_path,omitempty"` + CreationDate string `json:"creation_date,omitempty"` + Servers []SharedStorageServer `json:"servers,omitempty"` + Datacenter *Datacenter `json:"datacenter,omitempty"` + ApiPtr +} + +type SharedStorageServer struct { + Id string `json:"id,omitempty"` + Name string `json:"name,omitempty"` + Rights string `json:"rights,omitempty"` +} + +type SharedStorageRequest struct { + DatacenterId string `json:"datacenter_id,omitempty"` + Name string `json:"name,omitempty"` + Description string `json:"description,omitempty"` + Size *int `json:"size"` +} + +type SharedStorageAccess struct { + State string `json:"state,omitempty"` + KerberosContentFile string `json:"kerberos_content_file,omitempty"` + UserDomain string `json:"user_domain,omitempty"` + SiteId string `json:"site_id,omitempty"` + NeedsPasswordReset int `json:"needs_password_reset"` +} + +// GET /shared_storages +func (api *API) ListSharedStorages(args ...interface{}) ([]SharedStorage, error) { + url, err := processQueryParams(createUrl(api, sharedStoragePathSegment), args...) + if err != nil { + return nil, err + } + result := []SharedStorage{} + err = api.Client.Get(url, &result, http.StatusOK) + if err != nil { + return nil, err + } + for index, _ := range result { + result[index].api = api + } + return result, nil +} + +// POST /shared_storages +func (api *API) CreateSharedStorage(request *SharedStorageRequest) (string, *SharedStorage, error) { + result := new(SharedStorage) + url := createUrl(api, sharedStoragePathSegment) + err := api.Client.Post(url, request, &result, http.StatusAccepted) + if err != nil { + return "", nil, err + } + result.api = api + return result.Id, result, nil +} + +// GET /shared_storages/{id} +func (api *API) GetSharedStorage(ss_id string) (*SharedStorage, error) { + result := new(SharedStorage) + url := createUrl(api, sharedStoragePathSegment, ss_id) + err := api.Client.Get(url, &result, http.StatusOK) + if err != nil { + return nil, err + } + result.api = api + return result, nil +} + +// DELETE /shared_storages/{id} +func (api *API) DeleteSharedStorage(ss_id string) (*SharedStorage, error) { + result := new(SharedStorage) + url := createUrl(api, sharedStoragePathSegment, ss_id) + err := api.Client.Delete(url, nil, &result, http.StatusAccepted) + if err != nil { + return nil, err + } + result.api = api + return result, nil +} + +// PUT /shared_storages/{id} +func (api *API) UpdateSharedStorage(ss_id string, request *SharedStorageRequest) (*SharedStorage, error) { + result := new(SharedStorage) + url := createUrl(api, sharedStoragePathSegment, ss_id) + err := api.Client.Put(url, &request, &result, http.StatusAccepted) + if err != nil { + return nil, err + } + result.api = api + return result, nil +} + +// GET /shared_storages/{id}/servers +func (api *API) ListSharedStorageServers(st_id string) ([]SharedStorageServer, error) { + result := []SharedStorageServer{} + url := createUrl(api, sharedStoragePathSegment, st_id, "servers") + err := api.Client.Get(url, &result, http.StatusOK) + if err != nil { + return nil, err + } + return result, nil +} + +// POST /shared_storages/{id}/servers +func (api *API) AddSharedStorageServers(st_id string, servers []SharedStorageServer) (*SharedStorage, error) { + result := new(SharedStorage) + req := struct { + Servers []SharedStorageServer `json:"servers"` + }{servers} + url := createUrl(api, sharedStoragePathSegment, st_id, "servers") + err := api.Client.Post(url, &req, &result, http.StatusAccepted) + if err != nil { + return nil, err + } + result.api = api + return result, nil +} + +// GET /shared_storages/{id}/servers/{id} +func (api *API) GetSharedStorageServer(st_id string, ser_id string) (*SharedStorageServer, error) { + result := new(SharedStorageServer) + url := createUrl(api, sharedStoragePathSegment, st_id, "servers", ser_id) + err := api.Client.Get(url, &result, http.StatusOK) + if err != nil { + return nil, err + } + return result, nil +} + +// DELETE /shared_storages/{id}/servers/{id} +func (api *API) DeleteSharedStorageServer(st_id string, ser_id string) (*SharedStorage, error) { + result := new(SharedStorage) + url := createUrl(api, sharedStoragePathSegment, st_id, "servers", ser_id) + err := api.Client.Delete(url, nil, &result, http.StatusAccepted) + if err != nil { + return nil, err + } + result.api = api + return result, nil +} + +// GET /shared_storages/access +func (api *API) GetSharedStorageCredentials() ([]SharedStorageAccess, error) { + result := []SharedStorageAccess{} + url := createUrl(api, sharedStoragePathSegment, "access") + err := api.Client.Get(url, &result, http.StatusOK) + if err != nil { + return nil, err + } + return result, nil +} + +// PUT /shared_storages/access +func (api *API) UpdateSharedStorageCredentials(new_pass string) ([]SharedStorageAccess, error) { + result := []SharedStorageAccess{} + req := struct { + Password string `json:"password"` + }{new_pass} + url := createUrl(api, sharedStoragePathSegment, "access") + err := api.Client.Put(url, &req, &result, http.StatusAccepted) + if err != nil { + return nil, err + } + return result, nil +} + +func (ss *SharedStorage) GetState() (string, error) { + in, err := ss.api.GetSharedStorage(ss.Id) + if in == nil { + return "", err + } + return in.State, err +} diff --git a/vendor/github.com/1and1/oneandone-cloudserver-sdk-go/usages.go b/vendor/github.com/1and1/oneandone-cloudserver-sdk-go/usages.go new file mode 100644 index 000000000..e56c9f2ef --- /dev/null +++ b/vendor/github.com/1and1/oneandone-cloudserver-sdk-go/usages.go @@ -0,0 +1,52 @@ +package oneandone + +import ( + "net/http" + "time" +) + +type Usages struct { + Images []usage `json:"IMAGES,omitempty"` + LoadBalancers []usage `json:"LOAD BALANCERS,omitempty"` + PublicIPs []usage `json:"PUBLIC IP,omitempty"` + Servers []usage `json:"SERVERS,omitempty"` + SharedStorages []usage `json:"SHARED STORAGE,omitempty"` + ApiPtr +} + +type usage struct { + Identity + Site int `json:"site"` + Services []usageService `json:"services,omitempty"` +} + +type usageService struct { + AverageAmmount string `json:"avg_amount,omitempty"` + Unit string `json:"unit,omitempty"` + Usage int `json:"usage"` + Details []usageDetails `json:"detail,omitempty"` + typeField +} + +type usageDetails struct { + AverageAmmount string `json:"avg_amount,omitempty"` + StartDate string `json:"start_date,omitempty"` + EndDate string `json:"end_date,omitempty"` + Unit string `json:"unit,omitempty"` + Usage int `json:"usage,omitempty"` +} + +// GET /usages +func (api *API) ListUsages(period string, sd *time.Time, ed *time.Time, args ...interface{}) (*Usages, error) { + result := new(Usages) + url, err := processQueryParamsExt(createUrl(api, usagePathSegment), period, sd, ed, args...) + if err != nil { + return nil, err + } + err = api.Client.Get(url, &result, http.StatusOK) + if err != nil { + return nil, err + } + result.api = api + return result, nil +} diff --git a/vendor/github.com/1and1/oneandone-cloudserver-sdk-go/users.go b/vendor/github.com/1and1/oneandone-cloudserver-sdk-go/users.go new file mode 100644 index 000000000..782d07a50 --- /dev/null +++ b/vendor/github.com/1and1/oneandone-cloudserver-sdk-go/users.go @@ -0,0 +1,205 @@ +package oneandone + +import "net/http" + +type User struct { + Identity + descField + CreationDate string `json:"creation_date,omitempty"` + Email string `json:"email,omitempty"` + State string `json:"state,omitempty"` + Role *Identity `json:"role,omitempty"` + Api *UserApi `json:"api,omitempty"` + ApiPtr +} + +type UserApi struct { + Active bool `json:"active"` + AllowedIps []string `json:"allowed_ips,omitempty"` + UserApiKey + ApiPtr +} + +type UserApiKey struct { + Key string `json:"key,omitempty"` +} + +type UserRequest struct { + Name string `json:"name,omitempty"` + Description string `json:"description,omitempty"` + Password string `json:"password,omitempty"` + Email string `json:"email,omitempty"` + State string `json:"state,omitempty"` +} + +// GET /users +func (api *API) ListUsers(args ...interface{}) ([]User, error) { + url, err := processQueryParams(createUrl(api, userPathSegment), args...) + if err != nil { + return nil, err + } + result := []User{} + err = api.Client.Get(url, &result, http.StatusOK) + if err != nil { + return nil, err + } + for index, _ := range result { + result[index].api = api + } + return result, nil +} + +// POST /users +func (api *API) CreateUser(user *UserRequest) (string, *User, error) { + result := new(User) + url := createUrl(api, userPathSegment) + err := api.Client.Post(url, &user, &result, http.StatusCreated) + if err != nil { + return "", nil, err + } + result.api = api + return result.Id, result, nil +} + +// GET /users/{id} +func (api *API) GetUser(user_id string) (*User, error) { + result := new(User) + url := createUrl(api, userPathSegment, user_id) + err := api.Client.Get(url, &result, http.StatusOK) + if err != nil { + return nil, err + } + result.api = api + return result, nil +} + +// DELETE /users/{id} +func (api *API) DeleteUser(user_id string) (*User, error) { + result := new(User) + url := createUrl(api, userPathSegment, user_id) + err := api.Client.Delete(url, nil, &result, http.StatusOK) + if err != nil { + return nil, err + } + result.api = api + return result, nil +} + +// PUT /users/{id} +func (api *API) ModifyUser(user_id string, user *UserRequest) (*User, error) { + result := new(User) + url := createUrl(api, userPathSegment, user_id) + err := api.Client.Put(url, &user, &result, http.StatusOK) + if err != nil { + return nil, err + } + result.api = api + return result, nil +} + +// GET /users/{id}/api +func (api *API) GetUserApi(user_id string) (*UserApi, error) { + result := new(UserApi) + url := createUrl(api, userPathSegment, user_id, "api") + err := api.Client.Get(url, &result, http.StatusOK) + if err != nil { + return nil, err + } + result.api = api + return result, nil +} + +// PUT /users/{id}/api +func (api *API) ModifyUserApi(user_id string, active bool) (*User, error) { + result := new(User) + req := struct { + Active bool `json:"active"` + }{active} + url := createUrl(api, userPathSegment, user_id, "api") + err := api.Client.Put(url, &req, &result, http.StatusOK) + if err != nil { + return nil, err + } + result.api = api + return result, nil +} + +// GET /users/{id}/api/key +func (api *API) GetUserApiKey(user_id string) (*UserApiKey, error) { + result := new(UserApiKey) + url := createUrl(api, userPathSegment, user_id, "api/key") + err := api.Client.Get(url, &result, http.StatusOK) + if err != nil { + return nil, err + } + return result, nil +} + +// PUT /users/{id}/api/key +func (api *API) RenewUserApiKey(user_id string) (*User, error) { + result := new(User) + url := createUrl(api, userPathSegment, user_id, "api/key") + err := api.Client.Put(url, nil, &result, http.StatusOK) + if err != nil { + return nil, err + } + result.api = api + return result, nil +} + +// GET /users/{id}/api/ips +func (api *API) ListUserApiAllowedIps(user_id string) ([]string, error) { + result := []string{} + url := createUrl(api, userPathSegment, user_id, "api/ips") + err := api.Client.Get(url, &result, http.StatusOK) + if err != nil { + return nil, err + } + return result, nil +} + +// POST /users/{id}/api/ips +func (api *API) AddUserApiAlowedIps(user_id string, ips []string) (*User, error) { + result := new(User) + req := struct { + Ips []string `json:"ips"` + }{ips} + url := createUrl(api, userPathSegment, user_id, "api/ips") + err := api.Client.Post(url, &req, &result, http.StatusCreated) + if err != nil { + return nil, err + } + result.api = api + return result, nil +} + +// DELETE /users/{id}/api/ips/{ip} +func (api *API) RemoveUserApiAllowedIp(user_id string, ip string) (*User, error) { + result := new(User) + url := createUrl(api, userPathSegment, user_id, "api/ips", ip) + err := api.Client.Delete(url, nil, &result, http.StatusOK) + if err != nil { + return nil, err + } + result.api = api + return result, nil +} + +// GET /users/{id}/api/ips +func (api *API) GetCurrentUserPermissions() (*Permissions, error) { + result := new(Permissions) + url := createUrl(api, userPathSegment, "current_user_permissions") + err := api.Client.Get(url, &result, http.StatusOK) + if err != nil { + return nil, err + } + return result, nil +} + +func (u *User) GetState() (string, error) { + in, err := u.api.GetUser(u.Id) + if in == nil { + return "", err + } + return in.State, err +} diff --git a/vendor/github.com/1and1/oneandone-cloudserver-sdk-go/vpns.go b/vendor/github.com/1and1/oneandone-cloudserver-sdk-go/vpns.go new file mode 100644 index 000000000..723a85459 --- /dev/null +++ b/vendor/github.com/1and1/oneandone-cloudserver-sdk-go/vpns.go @@ -0,0 +1,114 @@ +package oneandone + +import "net/http" + +type VPN struct { + Identity + descField + typeField + CloudPanelId string `json:"cloudpanel_id,omitempty"` + CreationDate string `json:"creation_date,omitempty"` + State string `json:"state,omitempty"` + IPs []string `json:"ips,omitempty"` + Datacenter *Datacenter `json:"datacenter,omitempty"` + ApiPtr +} + +type configZipFile struct { + Base64String string `json:"config_zip_file"` +} + +// GET /vpns +func (api *API) ListVPNs(args ...interface{}) ([]VPN, error) { + url, err := processQueryParams(createUrl(api, vpnPathSegment), args...) + if err != nil { + return nil, err + } + result := []VPN{} + err = api.Client.Get(url, &result, http.StatusOK) + if err != nil { + return nil, err + } + for _, vpn := range result { + vpn.api = api + } + return result, nil +} + +// POST /vpns +func (api *API) CreateVPN(name string, description string, datacenter_id string) (string, *VPN, error) { + res := new(VPN) + url := createUrl(api, vpnPathSegment) + req := struct { + Name string `json:"name"` + Description string `json:"description,omitempty"` + DatacenterId string `json:"datacenter_id,omitempty"` + }{Name: name, Description: description, DatacenterId: datacenter_id} + err := api.Client.Post(url, &req, &res, http.StatusAccepted) + if err != nil { + return "", nil, err + } + res.api = api + return res.Id, res, nil +} + +// GET /vpns/{vpn_id} +func (api *API) GetVPN(vpn_id string) (*VPN, error) { + result := new(VPN) + url := createUrl(api, vpnPathSegment, vpn_id) + err := api.Client.Get(url, &result, http.StatusOK) + if err != nil { + return nil, err + } + result.api = api + return result, nil +} + +// PUT /vpns/{vpn_id} +func (api *API) ModifyVPN(vpn_id string, name string, description string) (*VPN, error) { + result := new(VPN) + url := createUrl(api, vpnPathSegment, vpn_id) + req := struct { + Name string `json:"name,omitempty"` + Description string `json:"description,omitempty"` + }{Name: name, Description: description} + err := api.Client.Put(url, &req, &result, http.StatusOK) + if err != nil { + return nil, err + } + result.api = api + return result, nil +} + +// DELETE /vpns/{vpn_id} +func (api *API) DeleteVPN(vpn_id string) (*VPN, error) { + result := new(VPN) + url := createUrl(api, vpnPathSegment, vpn_id) + err := api.Client.Delete(url, nil, &result, http.StatusAccepted) + if err != nil { + return nil, err + } + result.api = api + return result, nil +} + +// GET /vpns/{vpn_id}/configuration_file +// Returns VPN configuration files (in a zip arhive) as a base64 encoded string +func (api *API) GetVPNConfigFile(vpn_id string) (string, error) { + result := new(configZipFile) + url := createUrl(api, vpnPathSegment, vpn_id, "configuration_file") + err := api.Client.Get(url, &result, http.StatusOK) + if err != nil { + return "", err + } + + return result.Base64String, nil +} + +func (vpn *VPN) GetState() (string, error) { + in, err := vpn.api.GetVPN(vpn.Id) + if in == nil { + return "", err + } + return in.State, err +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/arm/disk/client.go b/vendor/github.com/Azure/azure-sdk-for-go/arm/disk/client.go new file mode 100644 index 000000000..d64eb2287 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/arm/disk/client.go @@ -0,0 +1,58 @@ +// Package disk implements the Azure ARM Disk service API version +// 2016-04-30-preview. +// +// The Disk Resource Provider Client. +package disk + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0 +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. + +import ( + "github.com/Azure/go-autorest/autorest" +) + +const ( + // APIVersion is the version of the Disk + APIVersion = "2016-04-30-preview" + + // DefaultBaseURI is the default URI used for the service Disk + DefaultBaseURI = "https://management.azure.com" +) + +// ManagementClient is the base client for Disk. +type ManagementClient struct { + autorest.Client + BaseURI string + APIVersion string + SubscriptionID string +} + +// New creates an instance of the ManagementClient client. +func New(subscriptionID string) ManagementClient { + return NewWithBaseURI(DefaultBaseURI, subscriptionID) +} + +// NewWithBaseURI creates an instance of the ManagementClient client. +func NewWithBaseURI(baseURI string, subscriptionID string) ManagementClient { + return ManagementClient{ + Client: autorest.NewClientWithUserAgent(UserAgent()), + BaseURI: baseURI, + APIVersion: APIVersion, + SubscriptionID: subscriptionID, + } +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/arm/disk/disks.go b/vendor/github.com/Azure/azure-sdk-for-go/arm/disk/disks.go new file mode 100644 index 000000000..6fb03876f --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/arm/disk/disks.go @@ -0,0 +1,638 @@ +package disk + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0 +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. + +import ( + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "github.com/Azure/go-autorest/autorest/validation" + "net/http" +) + +// DisksClient is the the Disk Resource Provider Client. +type DisksClient struct { + ManagementClient +} + +// NewDisksClient creates an instance of the DisksClient client. +func NewDisksClient(subscriptionID string) DisksClient { + return NewDisksClientWithBaseURI(DefaultBaseURI, subscriptionID) +} + +// NewDisksClientWithBaseURI creates an instance of the DisksClient client. +func NewDisksClientWithBaseURI(baseURI string, subscriptionID string) DisksClient { + return DisksClient{NewWithBaseURI(baseURI, subscriptionID)} +} + +// CreateOrUpdate creates or updates a disk. This method may poll for +// completion. Polling can be canceled by passing the cancel channel argument. +// The channel will be used to cancel polling and any outstanding HTTP +// requests. +// +// resourceGroupName is the name of the resource group. diskName is the name of +// the disk within the given subscription and resource group. diskParameter is +// disk object supplied in the body of the Put disk operation. +func (client DisksClient) CreateOrUpdate(resourceGroupName string, diskName string, diskParameter Model, cancel <-chan struct{}) (result autorest.Response, err error) { + if err := validation.Validate([]validation.Validation{ + {TargetValue: diskParameter, + Constraints: []validation.Constraint{{Target: "diskParameter.Properties", Name: validation.Null, Rule: false, + Chain: []validation.Constraint{{Target: "diskParameter.Properties.CreationData", Name: validation.Null, Rule: true, + Chain: []validation.Constraint{{Target: "diskParameter.Properties.CreationData.ImageReference", Name: validation.Null, Rule: false, + Chain: []validation.Constraint{{Target: "diskParameter.Properties.CreationData.ImageReference.ID", Name: validation.Null, Rule: true, Chain: nil}}}, + }}, + {Target: "diskParameter.Properties.EncryptionSettings", Name: validation.Null, Rule: false, + Chain: []validation.Constraint{{Target: "diskParameter.Properties.EncryptionSettings.DiskEncryptionKey", Name: validation.Null, Rule: false, + Chain: []validation.Constraint{{Target: "diskParameter.Properties.EncryptionSettings.DiskEncryptionKey.SourceVault", Name: validation.Null, Rule: true, Chain: nil}, + {Target: "diskParameter.Properties.EncryptionSettings.DiskEncryptionKey.SecretURL", Name: validation.Null, Rule: true, Chain: nil}, + }}, + {Target: "diskParameter.Properties.EncryptionSettings.KeyEncryptionKey", Name: validation.Null, Rule: false, + Chain: []validation.Constraint{{Target: "diskParameter.Properties.EncryptionSettings.KeyEncryptionKey.SourceVault", Name: validation.Null, Rule: true, Chain: nil}, + {Target: "diskParameter.Properties.EncryptionSettings.KeyEncryptionKey.KeyURL", Name: validation.Null, Rule: true, Chain: nil}, + }}, + }}, + }}}}}); err != nil { + return result, validation.NewErrorWithValidationError(err, "disk.DisksClient", "CreateOrUpdate") + } + + req, err := client.CreateOrUpdatePreparer(resourceGroupName, diskName, diskParameter, cancel) + if err != nil { + return result, autorest.NewErrorWithError(err, "disk.DisksClient", "CreateOrUpdate", nil, "Failure preparing request") + } + + resp, err := client.CreateOrUpdateSender(req) + if err != nil { + result.Response = resp + return result, autorest.NewErrorWithError(err, "disk.DisksClient", "CreateOrUpdate", resp, "Failure sending request") + } + + result, err = client.CreateOrUpdateResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "disk.DisksClient", "CreateOrUpdate", resp, "Failure responding to request") + } + + return +} + +// CreateOrUpdatePreparer prepares the CreateOrUpdate request. +func (client DisksClient) CreateOrUpdatePreparer(resourceGroupName string, diskName string, diskParameter Model, cancel <-chan struct{}) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "diskName": autorest.Encode("path", diskName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsJSON(), + autorest.AsPut(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/disks/{diskName}", pathParameters), + autorest.WithJSON(diskParameter), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{Cancel: cancel}) +} + +// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the +// http.Response Body if it receives an error. +func (client DisksClient) CreateOrUpdateSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) +} + +// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always +// closes the http.Response Body. +func (client DisksClient) CreateOrUpdateResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + autorest.ByClosing()) + result.Response = resp + return +} + +// Delete deletes a disk. This method may poll for completion. Polling can be +// canceled by passing the cancel channel argument. The channel will be used to +// cancel polling and any outstanding HTTP requests. +// +// resourceGroupName is the name of the resource group. diskName is the name of +// the disk within the given subscription and resource group. +func (client DisksClient) Delete(resourceGroupName string, diskName string, cancel <-chan struct{}) (result autorest.Response, err error) { + req, err := client.DeletePreparer(resourceGroupName, diskName, cancel) + if err != nil { + return result, autorest.NewErrorWithError(err, "disk.DisksClient", "Delete", nil, "Failure preparing request") + } + + resp, err := client.DeleteSender(req) + if err != nil { + result.Response = resp + return result, autorest.NewErrorWithError(err, "disk.DisksClient", "Delete", resp, "Failure sending request") + } + + result, err = client.DeleteResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "disk.DisksClient", "Delete", resp, "Failure responding to request") + } + + return +} + +// DeletePreparer prepares the Delete request. +func (client DisksClient) DeletePreparer(resourceGroupName string, diskName string, cancel <-chan struct{}) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "diskName": autorest.Encode("path", diskName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsDelete(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/disks/{diskName}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{Cancel: cancel}) +} + +// DeleteSender sends the Delete request. The method will close the +// http.Response Body if it receives an error. +func (client DisksClient) DeleteSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) +} + +// DeleteResponder handles the response to the Delete request. The method always +// closes the http.Response Body. +func (client DisksClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), + autorest.ByClosing()) + result.Response = resp + return +} + +// Get gets information about a disk. +// +// resourceGroupName is the name of the resource group. diskName is the name of +// the disk within the given subscription and resource group. +func (client DisksClient) Get(resourceGroupName string, diskName string) (result Model, err error) { + req, err := client.GetPreparer(resourceGroupName, diskName) + if err != nil { + return result, autorest.NewErrorWithError(err, "disk.DisksClient", "Get", nil, "Failure preparing request") + } + + resp, err := client.GetSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "disk.DisksClient", "Get", resp, "Failure sending request") + } + + result, err = client.GetResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "disk.DisksClient", "Get", resp, "Failure responding to request") + } + + return +} + +// GetPreparer prepares the Get request. +func (client DisksClient) GetPreparer(resourceGroupName string, diskName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "diskName": autorest.Encode("path", diskName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/disks/{diskName}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// GetSender sends the Get request. The method will close the +// http.Response Body if it receives an error. +func (client DisksClient) GetSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// GetResponder handles the response to the Get request. The method always +// closes the http.Response Body. +func (client DisksClient) GetResponder(resp *http.Response) (result Model, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// GrantAccess grants access to a disk. This method may poll for completion. +// Polling can be canceled by passing the cancel channel argument. The channel +// will be used to cancel polling and any outstanding HTTP requests. +// +// resourceGroupName is the name of the resource group. diskName is the name of +// the disk within the given subscription and resource group. grantAccessData +// is access data object supplied in the body of the get disk access operation. +func (client DisksClient) GrantAccess(resourceGroupName string, diskName string, grantAccessData GrantAccessData, cancel <-chan struct{}) (result autorest.Response, err error) { + if err := validation.Validate([]validation.Validation{ + {TargetValue: grantAccessData, + Constraints: []validation.Constraint{{Target: "grantAccessData.DurationInSeconds", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil { + return result, validation.NewErrorWithValidationError(err, "disk.DisksClient", "GrantAccess") + } + + req, err := client.GrantAccessPreparer(resourceGroupName, diskName, grantAccessData, cancel) + if err != nil { + return result, autorest.NewErrorWithError(err, "disk.DisksClient", "GrantAccess", nil, "Failure preparing request") + } + + resp, err := client.GrantAccessSender(req) + if err != nil { + result.Response = resp + return result, autorest.NewErrorWithError(err, "disk.DisksClient", "GrantAccess", resp, "Failure sending request") + } + + result, err = client.GrantAccessResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "disk.DisksClient", "GrantAccess", resp, "Failure responding to request") + } + + return +} + +// GrantAccessPreparer prepares the GrantAccess request. +func (client DisksClient) GrantAccessPreparer(resourceGroupName string, diskName string, grantAccessData GrantAccessData, cancel <-chan struct{}) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "diskName": autorest.Encode("path", diskName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsJSON(), + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/disks/{diskName}/beginGetAccess", pathParameters), + autorest.WithJSON(grantAccessData), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{Cancel: cancel}) +} + +// GrantAccessSender sends the GrantAccess request. The method will close the +// http.Response Body if it receives an error. +func (client DisksClient) GrantAccessSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) +} + +// GrantAccessResponder handles the response to the GrantAccess request. The method always +// closes the http.Response Body. +func (client DisksClient) GrantAccessResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + autorest.ByClosing()) + result.Response = resp + return +} + +// List lists all the disks under a subscription. +func (client DisksClient) List() (result ListType, err error) { + req, err := client.ListPreparer() + if err != nil { + return result, autorest.NewErrorWithError(err, "disk.DisksClient", "List", nil, "Failure preparing request") + } + + resp, err := client.ListSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "disk.DisksClient", "List", resp, "Failure sending request") + } + + result, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "disk.DisksClient", "List", resp, "Failure responding to request") + } + + return +} + +// ListPreparer prepares the List request. +func (client DisksClient) ListPreparer() (*http.Request, error) { + pathParameters := map[string]interface{}{ + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Compute/disks", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// ListSender sends the List request. The method will close the +// http.Response Body if it receives an error. +func (client DisksClient) ListSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// ListResponder handles the response to the List request. The method always +// closes the http.Response Body. +func (client DisksClient) ListResponder(resp *http.Response) (result ListType, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// ListNextResults retrieves the next set of results, if any. +func (client DisksClient) ListNextResults(lastResults ListType) (result ListType, err error) { + req, err := lastResults.ListTypePreparer() + if err != nil { + return result, autorest.NewErrorWithError(err, "disk.DisksClient", "List", nil, "Failure preparing next results request") + } + if req == nil { + return + } + + resp, err := client.ListSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "disk.DisksClient", "List", resp, "Failure sending next results request") + } + + result, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "disk.DisksClient", "List", resp, "Failure responding to next results request") + } + + return +} + +// ListByResourceGroup lists all the disks under a resource group. +// +// resourceGroupName is the name of the resource group. +func (client DisksClient) ListByResourceGroup(resourceGroupName string) (result ListType, err error) { + req, err := client.ListByResourceGroupPreparer(resourceGroupName) + if err != nil { + return result, autorest.NewErrorWithError(err, "disk.DisksClient", "ListByResourceGroup", nil, "Failure preparing request") + } + + resp, err := client.ListByResourceGroupSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "disk.DisksClient", "ListByResourceGroup", resp, "Failure sending request") + } + + result, err = client.ListByResourceGroupResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "disk.DisksClient", "ListByResourceGroup", resp, "Failure responding to request") + } + + return +} + +// ListByResourceGroupPreparer prepares the ListByResourceGroup request. +func (client DisksClient) ListByResourceGroupPreparer(resourceGroupName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/disks", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// ListByResourceGroupSender sends the ListByResourceGroup request. The method will close the +// http.Response Body if it receives an error. +func (client DisksClient) ListByResourceGroupSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// ListByResourceGroupResponder handles the response to the ListByResourceGroup request. The method always +// closes the http.Response Body. +func (client DisksClient) ListByResourceGroupResponder(resp *http.Response) (result ListType, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// ListByResourceGroupNextResults retrieves the next set of results, if any. +func (client DisksClient) ListByResourceGroupNextResults(lastResults ListType) (result ListType, err error) { + req, err := lastResults.ListTypePreparer() + if err != nil { + return result, autorest.NewErrorWithError(err, "disk.DisksClient", "ListByResourceGroup", nil, "Failure preparing next results request") + } + if req == nil { + return + } + + resp, err := client.ListByResourceGroupSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "disk.DisksClient", "ListByResourceGroup", resp, "Failure sending next results request") + } + + result, err = client.ListByResourceGroupResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "disk.DisksClient", "ListByResourceGroup", resp, "Failure responding to next results request") + } + + return +} + +// RevokeAccess revokes access to a disk. This method may poll for completion. +// Polling can be canceled by passing the cancel channel argument. The channel +// will be used to cancel polling and any outstanding HTTP requests. +// +// resourceGroupName is the name of the resource group. diskName is the name of +// the disk within the given subscription and resource group. +func (client DisksClient) RevokeAccess(resourceGroupName string, diskName string, cancel <-chan struct{}) (result autorest.Response, err error) { + req, err := client.RevokeAccessPreparer(resourceGroupName, diskName, cancel) + if err != nil { + return result, autorest.NewErrorWithError(err, "disk.DisksClient", "RevokeAccess", nil, "Failure preparing request") + } + + resp, err := client.RevokeAccessSender(req) + if err != nil { + result.Response = resp + return result, autorest.NewErrorWithError(err, "disk.DisksClient", "RevokeAccess", resp, "Failure sending request") + } + + result, err = client.RevokeAccessResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "disk.DisksClient", "RevokeAccess", resp, "Failure responding to request") + } + + return +} + +// RevokeAccessPreparer prepares the RevokeAccess request. +func (client DisksClient) RevokeAccessPreparer(resourceGroupName string, diskName string, cancel <-chan struct{}) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "diskName": autorest.Encode("path", diskName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/disks/{diskName}/endGetAccess", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{Cancel: cancel}) +} + +// RevokeAccessSender sends the RevokeAccess request. The method will close the +// http.Response Body if it receives an error. +func (client DisksClient) RevokeAccessSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) +} + +// RevokeAccessResponder handles the response to the RevokeAccess request. The method always +// closes the http.Response Body. +func (client DisksClient) RevokeAccessResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + autorest.ByClosing()) + result.Response = resp + return +} + +// Update updates (patches) a disk. This method may poll for completion. +// Polling can be canceled by passing the cancel channel argument. The channel +// will be used to cancel polling and any outstanding HTTP requests. +// +// resourceGroupName is the name of the resource group. diskName is the name of +// the disk within the given subscription and resource group. diskParameter is +// disk object supplied in the body of the Patch disk operation. +func (client DisksClient) Update(resourceGroupName string, diskName string, diskParameter UpdateType, cancel <-chan struct{}) (result autorest.Response, err error) { + req, err := client.UpdatePreparer(resourceGroupName, diskName, diskParameter, cancel) + if err != nil { + return result, autorest.NewErrorWithError(err, "disk.DisksClient", "Update", nil, "Failure preparing request") + } + + resp, err := client.UpdateSender(req) + if err != nil { + result.Response = resp + return result, autorest.NewErrorWithError(err, "disk.DisksClient", "Update", resp, "Failure sending request") + } + + result, err = client.UpdateResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "disk.DisksClient", "Update", resp, "Failure responding to request") + } + + return +} + +// UpdatePreparer prepares the Update request. +func (client DisksClient) UpdatePreparer(resourceGroupName string, diskName string, diskParameter UpdateType, cancel <-chan struct{}) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "diskName": autorest.Encode("path", diskName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsJSON(), + autorest.AsPatch(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/disks/{diskName}", pathParameters), + autorest.WithJSON(diskParameter), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{Cancel: cancel}) +} + +// UpdateSender sends the Update request. The method will close the +// http.Response Body if it receives an error. +func (client DisksClient) UpdateSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) +} + +// UpdateResponder handles the response to the Update request. The method always +// closes the http.Response Body. +func (client DisksClient) UpdateResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + autorest.ByClosing()) + result.Response = resp + return +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/arm/disk/models.go b/vendor/github.com/Azure/azure-sdk-for-go/arm/disk/models.go new file mode 100644 index 000000000..e8118696a --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/arm/disk/models.go @@ -0,0 +1,278 @@ +package disk + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0 +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. + +import ( + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/date" + "github.com/Azure/go-autorest/autorest/to" + "net/http" +) + +// AccessLevel enumerates the values for access level. +type AccessLevel string + +const ( + // None specifies the none state for access level. + None AccessLevel = "None" + // Read specifies the read state for access level. + Read AccessLevel = "Read" +) + +// CreateOption enumerates the values for create option. +type CreateOption string + +const ( + // Attach specifies the attach state for create option. + Attach CreateOption = "Attach" + // Copy specifies the copy state for create option. + Copy CreateOption = "Copy" + // Empty specifies the empty state for create option. + Empty CreateOption = "Empty" + // FromImage specifies the from image state for create option. + FromImage CreateOption = "FromImage" + // Import specifies the import state for create option. + Import CreateOption = "Import" + // Restore specifies the restore state for create option. + Restore CreateOption = "Restore" +) + +// OperatingSystemTypes enumerates the values for operating system types. +type OperatingSystemTypes string + +const ( + // Linux specifies the linux state for operating system types. + Linux OperatingSystemTypes = "Linux" + // Windows specifies the windows state for operating system types. + Windows OperatingSystemTypes = "Windows" +) + +// StorageAccountTypes enumerates the values for storage account types. +type StorageAccountTypes string + +const ( + // PremiumLRS specifies the premium lrs state for storage account types. + PremiumLRS StorageAccountTypes = "Premium_LRS" + // StandardLRS specifies the standard lrs state for storage account types. + StandardLRS StorageAccountTypes = "Standard_LRS" +) + +// AccessURI is a disk access SAS uri. +type AccessURI struct { + autorest.Response `json:"-"` + *AccessURIOutput `json:"properties,omitempty"` +} + +// AccessURIOutput is azure properties, including output. +type AccessURIOutput struct { + *AccessURIRaw `json:"output,omitempty"` +} + +// AccessURIRaw is this object gets 'bubbled up' through flattening. +type AccessURIRaw struct { + AccessSAS *string `json:"accessSAS,omitempty"` +} + +// APIError is api error. +type APIError struct { + Details *[]APIErrorBase `json:"details,omitempty"` + Innererror *InnerError `json:"innererror,omitempty"` + Code *string `json:"code,omitempty"` + Target *string `json:"target,omitempty"` + Message *string `json:"message,omitempty"` +} + +// APIErrorBase is api error base. +type APIErrorBase struct { + Code *string `json:"code,omitempty"` + Target *string `json:"target,omitempty"` + Message *string `json:"message,omitempty"` +} + +// CreationData is data used when creating a disk. +type CreationData struct { + CreateOption CreateOption `json:"createOption,omitempty"` + StorageAccountID *string `json:"storageAccountId,omitempty"` + ImageReference *ImageDiskReference `json:"imageReference,omitempty"` + SourceURI *string `json:"sourceUri,omitempty"` + SourceResourceID *string `json:"sourceResourceId,omitempty"` +} + +// EncryptionSettings is encryption settings for disk or snapshot +type EncryptionSettings struct { + Enabled *bool `json:"enabled,omitempty"` + DiskEncryptionKey *KeyVaultAndSecretReference `json:"diskEncryptionKey,omitempty"` + KeyEncryptionKey *KeyVaultAndKeyReference `json:"keyEncryptionKey,omitempty"` +} + +// GrantAccessData is data used for requesting a SAS. +type GrantAccessData struct { + Access AccessLevel `json:"access,omitempty"` + DurationInSeconds *int32 `json:"durationInSeconds,omitempty"` +} + +// ImageDiskReference is the source image used for creating the disk. +type ImageDiskReference struct { + ID *string `json:"id,omitempty"` + Lun *int32 `json:"lun,omitempty"` +} + +// InnerError is inner error details. +type InnerError struct { + Exceptiontype *string `json:"exceptiontype,omitempty"` + Errordetail *string `json:"errordetail,omitempty"` +} + +// KeyVaultAndKeyReference is key Vault Key Url and vault id of KeK, KeK is +// optional and when provided is used to unwrap the encryptionKey +type KeyVaultAndKeyReference struct { + SourceVault *SourceVault `json:"sourceVault,omitempty"` + KeyURL *string `json:"keyUrl,omitempty"` +} + +// KeyVaultAndSecretReference is key Vault Secret Url and vault id of the +// encryption key +type KeyVaultAndSecretReference struct { + SourceVault *SourceVault `json:"sourceVault,omitempty"` + SecretURL *string `json:"secretUrl,omitempty"` +} + +// ListType is the List Disks operation response. +type ListType struct { + autorest.Response `json:"-"` + Value *[]Model `json:"value,omitempty"` + NextLink *string `json:"nextLink,omitempty"` +} + +// ListTypePreparer prepares a request to retrieve the next set of results. It returns +// nil if no more results exist. +func (client ListType) ListTypePreparer() (*http.Request, error) { + if client.NextLink == nil || len(to.String(client.NextLink)) <= 0 { + return nil, nil + } + return autorest.Prepare(&http.Request{}, + autorest.AsJSON(), + autorest.AsGet(), + autorest.WithBaseURL(to.String(client.NextLink))) +} + +// Model is disk resource. +type Model struct { + autorest.Response `json:"-"` + ID *string `json:"id,omitempty"` + Name *string `json:"name,omitempty"` + Type *string `json:"type,omitempty"` + Location *string `json:"location,omitempty"` + Tags *map[string]*string `json:"tags,omitempty"` + *Properties `json:"properties,omitempty"` +} + +// OperationStatusResponse is operation status response +type OperationStatusResponse struct { + autorest.Response `json:"-"` + Name *string `json:"name,omitempty"` + Status *string `json:"status,omitempty"` + StartTime *date.Time `json:"startTime,omitempty"` + EndTime *date.Time `json:"endTime,omitempty"` + Error *APIError `json:"error,omitempty"` +} + +// Properties is disk resource properties. +type Properties struct { + AccountType StorageAccountTypes `json:"accountType,omitempty"` + TimeCreated *date.Time `json:"timeCreated,omitempty"` + OsType OperatingSystemTypes `json:"osType,omitempty"` + CreationData *CreationData `json:"creationData,omitempty"` + DiskSizeGB *int32 `json:"diskSizeGB,omitempty"` + EncryptionSettings *EncryptionSettings `json:"encryptionSettings,omitempty"` + OwnerID *string `json:"ownerId,omitempty"` + ProvisioningState *string `json:"provisioningState,omitempty"` +} + +// Resource is the Resource model definition. +type Resource struct { + ID *string `json:"id,omitempty"` + Name *string `json:"name,omitempty"` + Type *string `json:"type,omitempty"` + Location *string `json:"location,omitempty"` + Tags *map[string]*string `json:"tags,omitempty"` +} + +// ResourceUpdate is the Resource model definition. +type ResourceUpdate struct { + Tags *map[string]*string `json:"tags,omitempty"` +} + +// Snapshot is snapshot resource. +type Snapshot struct { + autorest.Response `json:"-"` + ID *string `json:"id,omitempty"` + Name *string `json:"name,omitempty"` + Type *string `json:"type,omitempty"` + Location *string `json:"location,omitempty"` + Tags *map[string]*string `json:"tags,omitempty"` + *Properties `json:"properties,omitempty"` +} + +// SnapshotList is the List Snapshots operation response. +type SnapshotList struct { + autorest.Response `json:"-"` + Value *[]Snapshot `json:"value,omitempty"` + NextLink *string `json:"nextLink,omitempty"` +} + +// SnapshotListPreparer prepares a request to retrieve the next set of results. It returns +// nil if no more results exist. +func (client SnapshotList) SnapshotListPreparer() (*http.Request, error) { + if client.NextLink == nil || len(to.String(client.NextLink)) <= 0 { + return nil, nil + } + return autorest.Prepare(&http.Request{}, + autorest.AsJSON(), + autorest.AsGet(), + autorest.WithBaseURL(to.String(client.NextLink))) +} + +// SnapshotUpdate is snapshot update resource. +type SnapshotUpdate struct { + Tags *map[string]*string `json:"tags,omitempty"` + *UpdateProperties `json:"properties,omitempty"` +} + +// SourceVault is the vault id is an Azure Resource Manager Resoure id in the +// form +// /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.KeyVault/vaults/{vaultName} +type SourceVault struct { + ID *string `json:"id,omitempty"` +} + +// UpdateProperties is disk resource update properties. +type UpdateProperties struct { + AccountType StorageAccountTypes `json:"accountType,omitempty"` + OsType OperatingSystemTypes `json:"osType,omitempty"` + CreationData *CreationData `json:"creationData,omitempty"` + DiskSizeGB *int32 `json:"diskSizeGB,omitempty"` + EncryptionSettings *EncryptionSettings `json:"encryptionSettings,omitempty"` +} + +// UpdateType is disk update resource. +type UpdateType struct { + Tags *map[string]*string `json:"tags,omitempty"` + *UpdateProperties `json:"properties,omitempty"` +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/arm/disk/snapshots.go b/vendor/github.com/Azure/azure-sdk-for-go/arm/disk/snapshots.go new file mode 100644 index 000000000..20e6ec758 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/arm/disk/snapshots.go @@ -0,0 +1,643 @@ +package disk + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0 +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. + +import ( + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "github.com/Azure/go-autorest/autorest/validation" + "net/http" +) + +// SnapshotsClient is the the Disk Resource Provider Client. +type SnapshotsClient struct { + ManagementClient +} + +// NewSnapshotsClient creates an instance of the SnapshotsClient client. +func NewSnapshotsClient(subscriptionID string) SnapshotsClient { + return NewSnapshotsClientWithBaseURI(DefaultBaseURI, subscriptionID) +} + +// NewSnapshotsClientWithBaseURI creates an instance of the SnapshotsClient +// client. +func NewSnapshotsClientWithBaseURI(baseURI string, subscriptionID string) SnapshotsClient { + return SnapshotsClient{NewWithBaseURI(baseURI, subscriptionID)} +} + +// CreateOrUpdate creates or updates a snapshot. This method may poll for +// completion. Polling can be canceled by passing the cancel channel argument. +// The channel will be used to cancel polling and any outstanding HTTP +// requests. +// +// resourceGroupName is the name of the resource group. snapshotName is the +// name of the snapshot within the given subscription and resource group. +// snapshot is snapshot object supplied in the body of the Put disk operation. +func (client SnapshotsClient) CreateOrUpdate(resourceGroupName string, snapshotName string, snapshot Snapshot, cancel <-chan struct{}) (result autorest.Response, err error) { + if err := validation.Validate([]validation.Validation{ + {TargetValue: snapshot, + Constraints: []validation.Constraint{{Target: "snapshot.Properties", Name: validation.Null, Rule: false, + Chain: []validation.Constraint{{Target: "snapshot.Properties.CreationData", Name: validation.Null, Rule: true, + Chain: []validation.Constraint{{Target: "snapshot.Properties.CreationData.ImageReference", Name: validation.Null, Rule: false, + Chain: []validation.Constraint{{Target: "snapshot.Properties.CreationData.ImageReference.ID", Name: validation.Null, Rule: true, Chain: nil}}}, + }}, + {Target: "snapshot.Properties.EncryptionSettings", Name: validation.Null, Rule: false, + Chain: []validation.Constraint{{Target: "snapshot.Properties.EncryptionSettings.DiskEncryptionKey", Name: validation.Null, Rule: false, + Chain: []validation.Constraint{{Target: "snapshot.Properties.EncryptionSettings.DiskEncryptionKey.SourceVault", Name: validation.Null, Rule: true, Chain: nil}, + {Target: "snapshot.Properties.EncryptionSettings.DiskEncryptionKey.SecretURL", Name: validation.Null, Rule: true, Chain: nil}, + }}, + {Target: "snapshot.Properties.EncryptionSettings.KeyEncryptionKey", Name: validation.Null, Rule: false, + Chain: []validation.Constraint{{Target: "snapshot.Properties.EncryptionSettings.KeyEncryptionKey.SourceVault", Name: validation.Null, Rule: true, Chain: nil}, + {Target: "snapshot.Properties.EncryptionSettings.KeyEncryptionKey.KeyURL", Name: validation.Null, Rule: true, Chain: nil}, + }}, + }}, + }}}}}); err != nil { + return result, validation.NewErrorWithValidationError(err, "disk.SnapshotsClient", "CreateOrUpdate") + } + + req, err := client.CreateOrUpdatePreparer(resourceGroupName, snapshotName, snapshot, cancel) + if err != nil { + return result, autorest.NewErrorWithError(err, "disk.SnapshotsClient", "CreateOrUpdate", nil, "Failure preparing request") + } + + resp, err := client.CreateOrUpdateSender(req) + if err != nil { + result.Response = resp + return result, autorest.NewErrorWithError(err, "disk.SnapshotsClient", "CreateOrUpdate", resp, "Failure sending request") + } + + result, err = client.CreateOrUpdateResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "disk.SnapshotsClient", "CreateOrUpdate", resp, "Failure responding to request") + } + + return +} + +// CreateOrUpdatePreparer prepares the CreateOrUpdate request. +func (client SnapshotsClient) CreateOrUpdatePreparer(resourceGroupName string, snapshotName string, snapshot Snapshot, cancel <-chan struct{}) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "snapshotName": autorest.Encode("path", snapshotName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsJSON(), + autorest.AsPut(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/snapshots/{snapshotName}", pathParameters), + autorest.WithJSON(snapshot), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{Cancel: cancel}) +} + +// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the +// http.Response Body if it receives an error. +func (client SnapshotsClient) CreateOrUpdateSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) +} + +// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always +// closes the http.Response Body. +func (client SnapshotsClient) CreateOrUpdateResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + autorest.ByClosing()) + result.Response = resp + return +} + +// Delete deletes a snapshot. This method may poll for completion. Polling can +// be canceled by passing the cancel channel argument. The channel will be used +// to cancel polling and any outstanding HTTP requests. +// +// resourceGroupName is the name of the resource group. snapshotName is the +// name of the snapshot within the given subscription and resource group. +func (client SnapshotsClient) Delete(resourceGroupName string, snapshotName string, cancel <-chan struct{}) (result autorest.Response, err error) { + req, err := client.DeletePreparer(resourceGroupName, snapshotName, cancel) + if err != nil { + return result, autorest.NewErrorWithError(err, "disk.SnapshotsClient", "Delete", nil, "Failure preparing request") + } + + resp, err := client.DeleteSender(req) + if err != nil { + result.Response = resp + return result, autorest.NewErrorWithError(err, "disk.SnapshotsClient", "Delete", resp, "Failure sending request") + } + + result, err = client.DeleteResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "disk.SnapshotsClient", "Delete", resp, "Failure responding to request") + } + + return +} + +// DeletePreparer prepares the Delete request. +func (client SnapshotsClient) DeletePreparer(resourceGroupName string, snapshotName string, cancel <-chan struct{}) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "snapshotName": autorest.Encode("path", snapshotName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsDelete(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/snapshots/{snapshotName}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{Cancel: cancel}) +} + +// DeleteSender sends the Delete request. The method will close the +// http.Response Body if it receives an error. +func (client SnapshotsClient) DeleteSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) +} + +// DeleteResponder handles the response to the Delete request. The method always +// closes the http.Response Body. +func (client SnapshotsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), + autorest.ByClosing()) + result.Response = resp + return +} + +// Get gets information about a snapshot. +// +// resourceGroupName is the name of the resource group. snapshotName is the +// name of the snapshot within the given subscription and resource group. +func (client SnapshotsClient) Get(resourceGroupName string, snapshotName string) (result Snapshot, err error) { + req, err := client.GetPreparer(resourceGroupName, snapshotName) + if err != nil { + return result, autorest.NewErrorWithError(err, "disk.SnapshotsClient", "Get", nil, "Failure preparing request") + } + + resp, err := client.GetSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "disk.SnapshotsClient", "Get", resp, "Failure sending request") + } + + result, err = client.GetResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "disk.SnapshotsClient", "Get", resp, "Failure responding to request") + } + + return +} + +// GetPreparer prepares the Get request. +func (client SnapshotsClient) GetPreparer(resourceGroupName string, snapshotName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "snapshotName": autorest.Encode("path", snapshotName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/snapshots/{snapshotName}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// GetSender sends the Get request. The method will close the +// http.Response Body if it receives an error. +func (client SnapshotsClient) GetSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// GetResponder handles the response to the Get request. The method always +// closes the http.Response Body. +func (client SnapshotsClient) GetResponder(resp *http.Response) (result Snapshot, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// GrantAccess grants access to a snapshot. This method may poll for +// completion. Polling can be canceled by passing the cancel channel argument. +// The channel will be used to cancel polling and any outstanding HTTP +// requests. +// +// resourceGroupName is the name of the resource group. snapshotName is the +// name of the snapshot within the given subscription and resource group. +// grantAccessData is access data object supplied in the body of the get +// snapshot access operation. +func (client SnapshotsClient) GrantAccess(resourceGroupName string, snapshotName string, grantAccessData GrantAccessData, cancel <-chan struct{}) (result autorest.Response, err error) { + if err := validation.Validate([]validation.Validation{ + {TargetValue: grantAccessData, + Constraints: []validation.Constraint{{Target: "grantAccessData.DurationInSeconds", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil { + return result, validation.NewErrorWithValidationError(err, "disk.SnapshotsClient", "GrantAccess") + } + + req, err := client.GrantAccessPreparer(resourceGroupName, snapshotName, grantAccessData, cancel) + if err != nil { + return result, autorest.NewErrorWithError(err, "disk.SnapshotsClient", "GrantAccess", nil, "Failure preparing request") + } + + resp, err := client.GrantAccessSender(req) + if err != nil { + result.Response = resp + return result, autorest.NewErrorWithError(err, "disk.SnapshotsClient", "GrantAccess", resp, "Failure sending request") + } + + result, err = client.GrantAccessResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "disk.SnapshotsClient", "GrantAccess", resp, "Failure responding to request") + } + + return +} + +// GrantAccessPreparer prepares the GrantAccess request. +func (client SnapshotsClient) GrantAccessPreparer(resourceGroupName string, snapshotName string, grantAccessData GrantAccessData, cancel <-chan struct{}) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "snapshotName": autorest.Encode("path", snapshotName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsJSON(), + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/snapshots/{snapshotName}/beginGetAccess", pathParameters), + autorest.WithJSON(grantAccessData), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{Cancel: cancel}) +} + +// GrantAccessSender sends the GrantAccess request. The method will close the +// http.Response Body if it receives an error. +func (client SnapshotsClient) GrantAccessSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) +} + +// GrantAccessResponder handles the response to the GrantAccess request. The method always +// closes the http.Response Body. +func (client SnapshotsClient) GrantAccessResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + autorest.ByClosing()) + result.Response = resp + return +} + +// List lists snapshots under a subscription. +func (client SnapshotsClient) List() (result SnapshotList, err error) { + req, err := client.ListPreparer() + if err != nil { + return result, autorest.NewErrorWithError(err, "disk.SnapshotsClient", "List", nil, "Failure preparing request") + } + + resp, err := client.ListSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "disk.SnapshotsClient", "List", resp, "Failure sending request") + } + + result, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "disk.SnapshotsClient", "List", resp, "Failure responding to request") + } + + return +} + +// ListPreparer prepares the List request. +func (client SnapshotsClient) ListPreparer() (*http.Request, error) { + pathParameters := map[string]interface{}{ + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Compute/snapshots", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// ListSender sends the List request. The method will close the +// http.Response Body if it receives an error. +func (client SnapshotsClient) ListSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// ListResponder handles the response to the List request. The method always +// closes the http.Response Body. +func (client SnapshotsClient) ListResponder(resp *http.Response) (result SnapshotList, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// ListNextResults retrieves the next set of results, if any. +func (client SnapshotsClient) ListNextResults(lastResults SnapshotList) (result SnapshotList, err error) { + req, err := lastResults.SnapshotListPreparer() + if err != nil { + return result, autorest.NewErrorWithError(err, "disk.SnapshotsClient", "List", nil, "Failure preparing next results request") + } + if req == nil { + return + } + + resp, err := client.ListSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "disk.SnapshotsClient", "List", resp, "Failure sending next results request") + } + + result, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "disk.SnapshotsClient", "List", resp, "Failure responding to next results request") + } + + return +} + +// ListByResourceGroup lists snapshots under a resource group. +// +// resourceGroupName is the name of the resource group. +func (client SnapshotsClient) ListByResourceGroup(resourceGroupName string) (result SnapshotList, err error) { + req, err := client.ListByResourceGroupPreparer(resourceGroupName) + if err != nil { + return result, autorest.NewErrorWithError(err, "disk.SnapshotsClient", "ListByResourceGroup", nil, "Failure preparing request") + } + + resp, err := client.ListByResourceGroupSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "disk.SnapshotsClient", "ListByResourceGroup", resp, "Failure sending request") + } + + result, err = client.ListByResourceGroupResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "disk.SnapshotsClient", "ListByResourceGroup", resp, "Failure responding to request") + } + + return +} + +// ListByResourceGroupPreparer prepares the ListByResourceGroup request. +func (client SnapshotsClient) ListByResourceGroupPreparer(resourceGroupName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/snapshots", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// ListByResourceGroupSender sends the ListByResourceGroup request. The method will close the +// http.Response Body if it receives an error. +func (client SnapshotsClient) ListByResourceGroupSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// ListByResourceGroupResponder handles the response to the ListByResourceGroup request. The method always +// closes the http.Response Body. +func (client SnapshotsClient) ListByResourceGroupResponder(resp *http.Response) (result SnapshotList, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// ListByResourceGroupNextResults retrieves the next set of results, if any. +func (client SnapshotsClient) ListByResourceGroupNextResults(lastResults SnapshotList) (result SnapshotList, err error) { + req, err := lastResults.SnapshotListPreparer() + if err != nil { + return result, autorest.NewErrorWithError(err, "disk.SnapshotsClient", "ListByResourceGroup", nil, "Failure preparing next results request") + } + if req == nil { + return + } + + resp, err := client.ListByResourceGroupSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "disk.SnapshotsClient", "ListByResourceGroup", resp, "Failure sending next results request") + } + + result, err = client.ListByResourceGroupResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "disk.SnapshotsClient", "ListByResourceGroup", resp, "Failure responding to next results request") + } + + return +} + +// RevokeAccess revokes access to a snapshot. This method may poll for +// completion. Polling can be canceled by passing the cancel channel argument. +// The channel will be used to cancel polling and any outstanding HTTP +// requests. +// +// resourceGroupName is the name of the resource group. snapshotName is the +// name of the snapshot within the given subscription and resource group. +func (client SnapshotsClient) RevokeAccess(resourceGroupName string, snapshotName string, cancel <-chan struct{}) (result autorest.Response, err error) { + req, err := client.RevokeAccessPreparer(resourceGroupName, snapshotName, cancel) + if err != nil { + return result, autorest.NewErrorWithError(err, "disk.SnapshotsClient", "RevokeAccess", nil, "Failure preparing request") + } + + resp, err := client.RevokeAccessSender(req) + if err != nil { + result.Response = resp + return result, autorest.NewErrorWithError(err, "disk.SnapshotsClient", "RevokeAccess", resp, "Failure sending request") + } + + result, err = client.RevokeAccessResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "disk.SnapshotsClient", "RevokeAccess", resp, "Failure responding to request") + } + + return +} + +// RevokeAccessPreparer prepares the RevokeAccess request. +func (client SnapshotsClient) RevokeAccessPreparer(resourceGroupName string, snapshotName string, cancel <-chan struct{}) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "snapshotName": autorest.Encode("path", snapshotName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/snapshots/{snapshotName}/endGetAccess", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{Cancel: cancel}) +} + +// RevokeAccessSender sends the RevokeAccess request. The method will close the +// http.Response Body if it receives an error. +func (client SnapshotsClient) RevokeAccessSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) +} + +// RevokeAccessResponder handles the response to the RevokeAccess request. The method always +// closes the http.Response Body. +func (client SnapshotsClient) RevokeAccessResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + autorest.ByClosing()) + result.Response = resp + return +} + +// Update updates (patches) a snapshot. This method may poll for completion. +// Polling can be canceled by passing the cancel channel argument. The channel +// will be used to cancel polling and any outstanding HTTP requests. +// +// resourceGroupName is the name of the resource group. snapshotName is the +// name of the snapshot within the given subscription and resource group. +// snapshot is snapshot object supplied in the body of the Patch snapshot +// operation. +func (client SnapshotsClient) Update(resourceGroupName string, snapshotName string, snapshot SnapshotUpdate, cancel <-chan struct{}) (result autorest.Response, err error) { + req, err := client.UpdatePreparer(resourceGroupName, snapshotName, snapshot, cancel) + if err != nil { + return result, autorest.NewErrorWithError(err, "disk.SnapshotsClient", "Update", nil, "Failure preparing request") + } + + resp, err := client.UpdateSender(req) + if err != nil { + result.Response = resp + return result, autorest.NewErrorWithError(err, "disk.SnapshotsClient", "Update", resp, "Failure sending request") + } + + result, err = client.UpdateResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "disk.SnapshotsClient", "Update", resp, "Failure responding to request") + } + + return +} + +// UpdatePreparer prepares the Update request. +func (client SnapshotsClient) UpdatePreparer(resourceGroupName string, snapshotName string, snapshot SnapshotUpdate, cancel <-chan struct{}) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "snapshotName": autorest.Encode("path", snapshotName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsJSON(), + autorest.AsPatch(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/snapshots/{snapshotName}", pathParameters), + autorest.WithJSON(snapshot), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{Cancel: cancel}) +} + +// UpdateSender sends the Update request. The method will close the +// http.Response Body if it receives an error. +func (client SnapshotsClient) UpdateSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) +} + +// UpdateResponder handles the response to the Update request. The method always +// closes the http.Response Body. +func (client SnapshotsClient) UpdateResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + autorest.ByClosing()) + result.Response = resp + return +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/arm/disk/version.go b/vendor/github.com/Azure/azure-sdk-for-go/arm/disk/version.go new file mode 100644 index 000000000..9b5497d54 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/arm/disk/version.go @@ -0,0 +1,60 @@ +package disk + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0 +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. + +import ( + "bytes" + "fmt" + "strings" +) + +const ( + major = "8" + minor = "1" + patch = "0" + tag = "beta" + userAgentFormat = "Azure-SDK-For-Go/%s arm-%s/%s" +) + +// cached results of UserAgent and Version to prevent repeated operations. +var ( + userAgent string + version string +) + +// UserAgent returns the UserAgent string to use when sending http.Requests. +func UserAgent() string { + if userAgent == "" { + userAgent = fmt.Sprintf(userAgentFormat, Version(), "disk", "2016-04-30-preview") + } + return userAgent +} + +// Version returns the semantic version (see http://semver.org) of the client. +func Version() string { + if version == "" { + versionBuilder := bytes.NewBufferString(fmt.Sprintf("%s.%s.%s", major, minor, patch)) + if tag != "" { + versionBuilder.WriteRune('-') + versionBuilder.WriteString(strings.TrimPrefix(tag, "-")) + } + version = string(versionBuilder.Bytes()) + } + return version +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/arm/sql/client.go b/vendor/github.com/Azure/azure-sdk-for-go/arm/sql/client.go new file mode 100644 index 000000000..916cd5043 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/arm/sql/client.go @@ -0,0 +1,59 @@ +// Package sql implements the Azure ARM Sql service API version 2014-04-01. +// +// Provides create, read, update and delete functionality for Azure SQL +// resources including servers, databases, elastic pools, recommendations, +// operations, and usage metrics. +package sql + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0 +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. + +import ( + "github.com/Azure/go-autorest/autorest" +) + +const ( + // APIVersion is the version of the Sql + APIVersion = "2014-04-01" + + // DefaultBaseURI is the default URI used for the service Sql + DefaultBaseURI = "https://management.azure.com" +) + +// ManagementClient is the base client for Sql. +type ManagementClient struct { + autorest.Client + BaseURI string + APIVersion string + SubscriptionID string +} + +// New creates an instance of the ManagementClient client. +func New(subscriptionID string) ManagementClient { + return NewWithBaseURI(DefaultBaseURI, subscriptionID) +} + +// NewWithBaseURI creates an instance of the ManagementClient client. +func NewWithBaseURI(baseURI string, subscriptionID string) ManagementClient { + return ManagementClient{ + Client: autorest.NewClientWithUserAgent(UserAgent()), + BaseURI: baseURI, + APIVersion: APIVersion, + SubscriptionID: subscriptionID, + } +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/arm/sql/databases.go b/vendor/github.com/Azure/azure-sdk-for-go/arm/sql/databases.go new file mode 100644 index 000000000..70a13d619 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/arm/sql/databases.go @@ -0,0 +1,934 @@ +package sql + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0 +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. + +import ( + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "net/http" +) + +// DatabasesClient is the provides create, read, update and delete +// functionality for Azure SQL resources including servers, databases, +// elastic pools, recommendations, operations, and usage metrics. +type DatabasesClient struct { + ManagementClient +} + +// NewDatabasesClient creates an instance of the DatabasesClient client. +func NewDatabasesClient(subscriptionID string) DatabasesClient { + return NewDatabasesClientWithBaseURI(DefaultBaseURI, subscriptionID) +} + +// NewDatabasesClientWithBaseURI creates an instance of the DatabasesClient +// client. +func NewDatabasesClientWithBaseURI(baseURI string, subscriptionID string) DatabasesClient { + return DatabasesClient{NewWithBaseURI(baseURI, subscriptionID)} +} + +// CreateOrUpdate creates a new Azure SQL database or updates an existing +// Azure SQL database. Location is a required property in the request body, +// and it must be the same as the location of the SQL server. This method may +// poll for completion. Polling can be canceled by passing the cancel channel +// argument. The channel will be used to cancel polling and any outstanding +// HTTP requests. +// +// resourceGroupName is the name of the resource group that contains the +// resource. You can obtain this value from the Azure Resource Manager API or +// the portal. serverName is the name of the Azure SQL server. databaseName +// is the name of the Azure SQL database to be operated on (updated or +// created). parameters is the required parameters for creating or updating a +// database. +func (client DatabasesClient) CreateOrUpdate(resourceGroupName string, serverName string, databaseName string, parameters Database, cancel <-chan struct{}) (result autorest.Response, err error) { + req, err := client.CreateOrUpdatePreparer(resourceGroupName, serverName, databaseName, parameters, cancel) + if err != nil { + return result, autorest.NewErrorWithError(err, "sql.DatabasesClient", "CreateOrUpdate", nil, "Failure preparing request") + } + + resp, err := client.CreateOrUpdateSender(req) + if err != nil { + result.Response = resp + return result, autorest.NewErrorWithError(err, "sql.DatabasesClient", "CreateOrUpdate", resp, "Failure sending request") + } + + result, err = client.CreateOrUpdateResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.DatabasesClient", "CreateOrUpdate", resp, "Failure responding to request") + } + + return +} + +// CreateOrUpdatePreparer prepares the CreateOrUpdate request. +func (client DatabasesClient) CreateOrUpdatePreparer(resourceGroupName string, serverName string, databaseName string, parameters Database, cancel <-chan struct{}) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "databaseName": autorest.Encode("path", databaseName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serverName": autorest.Encode("path", serverName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsJSON(), + autorest.AsPut(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/databases/{databaseName}", pathParameters), + autorest.WithJSON(parameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{Cancel: cancel}) +} + +// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the +// http.Response Body if it receives an error. +func (client DatabasesClient) CreateOrUpdateSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) +} + +// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always +// closes the http.Response Body. +func (client DatabasesClient) CreateOrUpdateResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated, http.StatusAccepted), + autorest.ByClosing()) + result.Response = resp + return +} + +// CreateOrUpdateTransparentDataEncryptionConfiguration creates or updates an +// Azure SQL Database Transparent Data Encryption Operation. +// +// resourceGroupName is the name of the resource group that contains the +// resource. You can obtain this value from the Azure Resource Manager API or +// the portal. serverName is the name of the Azure SQL server. databaseName +// is the name of the Azure SQL database for which setting the Transparent +// Data Encryption applies. parameters is the required parameters for +// creating or updating transparent data encryption. +func (client DatabasesClient) CreateOrUpdateTransparentDataEncryptionConfiguration(resourceGroupName string, serverName string, databaseName string, parameters TransparentDataEncryption) (result TransparentDataEncryption, err error) { + req, err := client.CreateOrUpdateTransparentDataEncryptionConfigurationPreparer(resourceGroupName, serverName, databaseName, parameters) + if err != nil { + return result, autorest.NewErrorWithError(err, "sql.DatabasesClient", "CreateOrUpdateTransparentDataEncryptionConfiguration", nil, "Failure preparing request") + } + + resp, err := client.CreateOrUpdateTransparentDataEncryptionConfigurationSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "sql.DatabasesClient", "CreateOrUpdateTransparentDataEncryptionConfiguration", resp, "Failure sending request") + } + + result, err = client.CreateOrUpdateTransparentDataEncryptionConfigurationResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.DatabasesClient", "CreateOrUpdateTransparentDataEncryptionConfiguration", resp, "Failure responding to request") + } + + return +} + +// CreateOrUpdateTransparentDataEncryptionConfigurationPreparer prepares the CreateOrUpdateTransparentDataEncryptionConfiguration request. +func (client DatabasesClient) CreateOrUpdateTransparentDataEncryptionConfigurationPreparer(resourceGroupName string, serverName string, databaseName string, parameters TransparentDataEncryption) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "databaseName": autorest.Encode("path", databaseName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serverName": autorest.Encode("path", serverName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsJSON(), + autorest.AsPut(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/databases/{databaseName}/transparentDataEncryption/current", pathParameters), + autorest.WithJSON(parameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// CreateOrUpdateTransparentDataEncryptionConfigurationSender sends the CreateOrUpdateTransparentDataEncryptionConfiguration request. The method will close the +// http.Response Body if it receives an error. +func (client DatabasesClient) CreateOrUpdateTransparentDataEncryptionConfigurationSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// CreateOrUpdateTransparentDataEncryptionConfigurationResponder handles the response to the CreateOrUpdateTransparentDataEncryptionConfiguration request. The method always +// closes the http.Response Body. +func (client DatabasesClient) CreateOrUpdateTransparentDataEncryptionConfigurationResponder(resp *http.Response) (result TransparentDataEncryption, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// Delete deletes an Azure SQL database. +// +// resourceGroupName is the name of the resource group that contains the +// resource. You can obtain this value from the Azure Resource Manager API or +// the portal. serverName is the name of the Azure SQL server. databaseName +// is the name of the Azure SQL database to be deleted. +func (client DatabasesClient) Delete(resourceGroupName string, serverName string, databaseName string) (result autorest.Response, err error) { + req, err := client.DeletePreparer(resourceGroupName, serverName, databaseName) + if err != nil { + return result, autorest.NewErrorWithError(err, "sql.DatabasesClient", "Delete", nil, "Failure preparing request") + } + + resp, err := client.DeleteSender(req) + if err != nil { + result.Response = resp + return result, autorest.NewErrorWithError(err, "sql.DatabasesClient", "Delete", resp, "Failure sending request") + } + + result, err = client.DeleteResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.DatabasesClient", "Delete", resp, "Failure responding to request") + } + + return +} + +// DeletePreparer prepares the Delete request. +func (client DatabasesClient) DeletePreparer(resourceGroupName string, serverName string, databaseName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "databaseName": autorest.Encode("path", databaseName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serverName": autorest.Encode("path", serverName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsDelete(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/databases/{databaseName}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// DeleteSender sends the Delete request. The method will close the +// http.Response Body if it receives an error. +func (client DatabasesClient) DeleteSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// DeleteResponder handles the response to the Delete request. The method always +// closes the http.Response Body. +func (client DatabasesClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusNoContent), + autorest.ByClosing()) + result.Response = resp + return +} + +// Get gets information about an Azure SQL database. +// +// resourceGroupName is the name of the resource group that contains the +// resource. You can obtain this value from the Azure Resource Manager API or +// the portal. serverName is the name of the Azure SQL server. databaseName +// is the name of the Azure SQL database to be retrieved. expand is the comma +// separated list of child objects to expand in the response. Possible +// properties: serviceTierAdvisors, upgradeHint, transparentDataEncryption. +func (client DatabasesClient) Get(resourceGroupName string, serverName string, databaseName string, expand string) (result Database, err error) { + req, err := client.GetPreparer(resourceGroupName, serverName, databaseName, expand) + if err != nil { + return result, autorest.NewErrorWithError(err, "sql.DatabasesClient", "Get", nil, "Failure preparing request") + } + + resp, err := client.GetSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "sql.DatabasesClient", "Get", resp, "Failure sending request") + } + + result, err = client.GetResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.DatabasesClient", "Get", resp, "Failure responding to request") + } + + return +} + +// GetPreparer prepares the Get request. +func (client DatabasesClient) GetPreparer(resourceGroupName string, serverName string, databaseName string, expand string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "databaseName": autorest.Encode("path", databaseName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serverName": autorest.Encode("path", serverName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + if len(expand) > 0 { + queryParameters["$expand"] = autorest.Encode("query", expand) + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/databases/{databaseName}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// GetSender sends the Get request. The method will close the +// http.Response Body if it receives an error. +func (client DatabasesClient) GetSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// GetResponder handles the response to the Get request. The method always +// closes the http.Response Body. +func (client DatabasesClient) GetResponder(resp *http.Response) (result Database, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// GetServiceTierAdvisor gets information about a service tier advisor. +// +// resourceGroupName is the name of the resource group that contains the +// resource. You can obtain this value from the Azure Resource Manager API or +// the portal. serverName is the name of the Azure SQL server. databaseName +// is the name of database. serviceTierAdvisorName is the name of service +// tier advisor. +func (client DatabasesClient) GetServiceTierAdvisor(resourceGroupName string, serverName string, databaseName string, serviceTierAdvisorName string) (result ServiceTierAdvisor, err error) { + req, err := client.GetServiceTierAdvisorPreparer(resourceGroupName, serverName, databaseName, serviceTierAdvisorName) + if err != nil { + return result, autorest.NewErrorWithError(err, "sql.DatabasesClient", "GetServiceTierAdvisor", nil, "Failure preparing request") + } + + resp, err := client.GetServiceTierAdvisorSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "sql.DatabasesClient", "GetServiceTierAdvisor", resp, "Failure sending request") + } + + result, err = client.GetServiceTierAdvisorResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.DatabasesClient", "GetServiceTierAdvisor", resp, "Failure responding to request") + } + + return +} + +// GetServiceTierAdvisorPreparer prepares the GetServiceTierAdvisor request. +func (client DatabasesClient) GetServiceTierAdvisorPreparer(resourceGroupName string, serverName string, databaseName string, serviceTierAdvisorName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "databaseName": autorest.Encode("path", databaseName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serverName": autorest.Encode("path", serverName), + "serviceTierAdvisorName": autorest.Encode("path", serviceTierAdvisorName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/databases/{databaseName}/serviceTierAdvisors/{serviceTierAdvisorName}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// GetServiceTierAdvisorSender sends the GetServiceTierAdvisor request. The method will close the +// http.Response Body if it receives an error. +func (client DatabasesClient) GetServiceTierAdvisorSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// GetServiceTierAdvisorResponder handles the response to the GetServiceTierAdvisor request. The method always +// closes the http.Response Body. +func (client DatabasesClient) GetServiceTierAdvisorResponder(resp *http.Response) (result ServiceTierAdvisor, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// GetTransparentDataEncryptionConfiguration gets an Azure SQL Database +// Transparent Data Encryption Response. +// +// resourceGroupName is the name of the resource group that contains the +// resource. You can obtain this value from the Azure Resource Manager API or +// the portal. serverName is the name of the Azure SQL server. databaseName +// is the name of the Azure SQL database for which the Transparent Data +// Encryption applies. +func (client DatabasesClient) GetTransparentDataEncryptionConfiguration(resourceGroupName string, serverName string, databaseName string) (result TransparentDataEncryption, err error) { + req, err := client.GetTransparentDataEncryptionConfigurationPreparer(resourceGroupName, serverName, databaseName) + if err != nil { + return result, autorest.NewErrorWithError(err, "sql.DatabasesClient", "GetTransparentDataEncryptionConfiguration", nil, "Failure preparing request") + } + + resp, err := client.GetTransparentDataEncryptionConfigurationSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "sql.DatabasesClient", "GetTransparentDataEncryptionConfiguration", resp, "Failure sending request") + } + + result, err = client.GetTransparentDataEncryptionConfigurationResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.DatabasesClient", "GetTransparentDataEncryptionConfiguration", resp, "Failure responding to request") + } + + return +} + +// GetTransparentDataEncryptionConfigurationPreparer prepares the GetTransparentDataEncryptionConfiguration request. +func (client DatabasesClient) GetTransparentDataEncryptionConfigurationPreparer(resourceGroupName string, serverName string, databaseName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "databaseName": autorest.Encode("path", databaseName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serverName": autorest.Encode("path", serverName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/databases/{databaseName}/transparentDataEncryption/current", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// GetTransparentDataEncryptionConfigurationSender sends the GetTransparentDataEncryptionConfiguration request. The method will close the +// http.Response Body if it receives an error. +func (client DatabasesClient) GetTransparentDataEncryptionConfigurationSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// GetTransparentDataEncryptionConfigurationResponder handles the response to the GetTransparentDataEncryptionConfiguration request. The method always +// closes the http.Response Body. +func (client DatabasesClient) GetTransparentDataEncryptionConfigurationResponder(resp *http.Response) (result TransparentDataEncryption, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// ListByServer returns information about an Azure SQL database. +// +// resourceGroupName is the name of the resource group that contains the +// resource. You can obtain this value from the Azure Resource Manager API or +// the portal. serverName is the name of the Azure SQL server. +func (client DatabasesClient) ListByServer(resourceGroupName string, serverName string) (result DatabaseListResult, err error) { + req, err := client.ListByServerPreparer(resourceGroupName, serverName) + if err != nil { + return result, autorest.NewErrorWithError(err, "sql.DatabasesClient", "ListByServer", nil, "Failure preparing request") + } + + resp, err := client.ListByServerSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "sql.DatabasesClient", "ListByServer", resp, "Failure sending request") + } + + result, err = client.ListByServerResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.DatabasesClient", "ListByServer", resp, "Failure responding to request") + } + + return +} + +// ListByServerPreparer prepares the ListByServer request. +func (client DatabasesClient) ListByServerPreparer(resourceGroupName string, serverName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serverName": autorest.Encode("path", serverName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/databases", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// ListByServerSender sends the ListByServer request. The method will close the +// http.Response Body if it receives an error. +func (client DatabasesClient) ListByServerSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// ListByServerResponder handles the response to the ListByServer request. The method always +// closes the http.Response Body. +func (client DatabasesClient) ListByServerResponder(resp *http.Response) (result DatabaseListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// ListRestorePoints returns a list of Azure SQL database restore points. +// +// resourceGroupName is the name of the resource group that contains the +// resource. You can obtain this value from the Azure Resource Manager API or +// the portal. serverName is the name of the Azure SQL server. databaseName +// is the name of the Azure SQL database from which to retrieve available +// restore points. +func (client DatabasesClient) ListRestorePoints(resourceGroupName string, serverName string, databaseName string) (result RestorePointListResult, err error) { + req, err := client.ListRestorePointsPreparer(resourceGroupName, serverName, databaseName) + if err != nil { + return result, autorest.NewErrorWithError(err, "sql.DatabasesClient", "ListRestorePoints", nil, "Failure preparing request") + } + + resp, err := client.ListRestorePointsSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "sql.DatabasesClient", "ListRestorePoints", resp, "Failure sending request") + } + + result, err = client.ListRestorePointsResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.DatabasesClient", "ListRestorePoints", resp, "Failure responding to request") + } + + return +} + +// ListRestorePointsPreparer prepares the ListRestorePoints request. +func (client DatabasesClient) ListRestorePointsPreparer(resourceGroupName string, serverName string, databaseName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "databaseName": autorest.Encode("path", databaseName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serverName": autorest.Encode("path", serverName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/databases/{databaseName}/restorePoints", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// ListRestorePointsSender sends the ListRestorePoints request. The method will close the +// http.Response Body if it receives an error. +func (client DatabasesClient) ListRestorePointsSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// ListRestorePointsResponder handles the response to the ListRestorePoints request. The method always +// closes the http.Response Body. +func (client DatabasesClient) ListRestorePointsResponder(resp *http.Response) (result RestorePointListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// ListServiceTierAdvisors returns information about service tier advisors for +// specified database. +// +// resourceGroupName is the name of the resource group that contains the +// resource. You can obtain this value from the Azure Resource Manager API or +// the portal. serverName is the name of the Azure SQL server. databaseName +// is the name of database. +func (client DatabasesClient) ListServiceTierAdvisors(resourceGroupName string, serverName string, databaseName string) (result ServiceTierAdvisorListResult, err error) { + req, err := client.ListServiceTierAdvisorsPreparer(resourceGroupName, serverName, databaseName) + if err != nil { + return result, autorest.NewErrorWithError(err, "sql.DatabasesClient", "ListServiceTierAdvisors", nil, "Failure preparing request") + } + + resp, err := client.ListServiceTierAdvisorsSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "sql.DatabasesClient", "ListServiceTierAdvisors", resp, "Failure sending request") + } + + result, err = client.ListServiceTierAdvisorsResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.DatabasesClient", "ListServiceTierAdvisors", resp, "Failure responding to request") + } + + return +} + +// ListServiceTierAdvisorsPreparer prepares the ListServiceTierAdvisors request. +func (client DatabasesClient) ListServiceTierAdvisorsPreparer(resourceGroupName string, serverName string, databaseName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "databaseName": autorest.Encode("path", databaseName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serverName": autorest.Encode("path", serverName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/databases/{databaseName}/serviceTierAdvisors", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// ListServiceTierAdvisorsSender sends the ListServiceTierAdvisors request. The method will close the +// http.Response Body if it receives an error. +func (client DatabasesClient) ListServiceTierAdvisorsSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// ListServiceTierAdvisorsResponder handles the response to the ListServiceTierAdvisors request. The method always +// closes the http.Response Body. +func (client DatabasesClient) ListServiceTierAdvisorsResponder(resp *http.Response) (result ServiceTierAdvisorListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// ListTransparentDataEncryptionActivity returns an Azure SQL Database +// Transparent Data Encryption Activity Response. +// +// resourceGroupName is the name of the resource group that contains the +// resource. You can obtain this value from the Azure Resource Manager API or +// the portal. serverName is the name of the Azure SQL server. databaseName +// is the name of the Azure SQL database for which the Transparent Data +// Encryption applies. +func (client DatabasesClient) ListTransparentDataEncryptionActivity(resourceGroupName string, serverName string, databaseName string) (result TransparentDataEncryptionActivityListResult, err error) { + req, err := client.ListTransparentDataEncryptionActivityPreparer(resourceGroupName, serverName, databaseName) + if err != nil { + return result, autorest.NewErrorWithError(err, "sql.DatabasesClient", "ListTransparentDataEncryptionActivity", nil, "Failure preparing request") + } + + resp, err := client.ListTransparentDataEncryptionActivitySender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "sql.DatabasesClient", "ListTransparentDataEncryptionActivity", resp, "Failure sending request") + } + + result, err = client.ListTransparentDataEncryptionActivityResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.DatabasesClient", "ListTransparentDataEncryptionActivity", resp, "Failure responding to request") + } + + return +} + +// ListTransparentDataEncryptionActivityPreparer prepares the ListTransparentDataEncryptionActivity request. +func (client DatabasesClient) ListTransparentDataEncryptionActivityPreparer(resourceGroupName string, serverName string, databaseName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "databaseName": autorest.Encode("path", databaseName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serverName": autorest.Encode("path", serverName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/databases/{databaseName}/transparentDataEncryption/current/operationResults", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// ListTransparentDataEncryptionActivitySender sends the ListTransparentDataEncryptionActivity request. The method will close the +// http.Response Body if it receives an error. +func (client DatabasesClient) ListTransparentDataEncryptionActivitySender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// ListTransparentDataEncryptionActivityResponder handles the response to the ListTransparentDataEncryptionActivity request. The method always +// closes the http.Response Body. +func (client DatabasesClient) ListTransparentDataEncryptionActivityResponder(resp *http.Response) (result TransparentDataEncryptionActivityListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// ListUsages returns information about Azure SQL database usages. +// +// resourceGroupName is the name of the resource group that contains the +// resource. You can obtain this value from the Azure Resource Manager API or +// the portal. serverName is the name of the Azure SQL server. databaseName +// is the name of the Azure SQL database. +func (client DatabasesClient) ListUsages(resourceGroupName string, serverName string, databaseName string) (result DatabaseMetricListResult, err error) { + req, err := client.ListUsagesPreparer(resourceGroupName, serverName, databaseName) + if err != nil { + return result, autorest.NewErrorWithError(err, "sql.DatabasesClient", "ListUsages", nil, "Failure preparing request") + } + + resp, err := client.ListUsagesSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "sql.DatabasesClient", "ListUsages", resp, "Failure sending request") + } + + result, err = client.ListUsagesResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.DatabasesClient", "ListUsages", resp, "Failure responding to request") + } + + return +} + +// ListUsagesPreparer prepares the ListUsages request. +func (client DatabasesClient) ListUsagesPreparer(resourceGroupName string, serverName string, databaseName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "databaseName": autorest.Encode("path", databaseName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serverName": autorest.Encode("path", serverName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/databases/{databaseName}/usages", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// ListUsagesSender sends the ListUsages request. The method will close the +// http.Response Body if it receives an error. +func (client DatabasesClient) ListUsagesSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// ListUsagesResponder handles the response to the ListUsages request. The method always +// closes the http.Response Body. +func (client DatabasesClient) ListUsagesResponder(resp *http.Response) (result DatabaseMetricListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// PauseDataWarehouse pause an Azure SQL Data Warehouse database. This method +// may poll for completion. Polling can be canceled by passing the cancel +// channel argument. The channel will be used to cancel polling and any +// outstanding HTTP requests. +// +// resourceGroupName is the name of the resource group that contains the +// resource. You can obtain this value from the Azure Resource Manager API or +// the portal. serverName is the name of the Azure SQL server. databaseName +// is the name of the Azure SQL Data Warehouse database to pause. +func (client DatabasesClient) PauseDataWarehouse(resourceGroupName string, serverName string, databaseName string, cancel <-chan struct{}) (result autorest.Response, err error) { + req, err := client.PauseDataWarehousePreparer(resourceGroupName, serverName, databaseName, cancel) + if err != nil { + return result, autorest.NewErrorWithError(err, "sql.DatabasesClient", "PauseDataWarehouse", nil, "Failure preparing request") + } + + resp, err := client.PauseDataWarehouseSender(req) + if err != nil { + result.Response = resp + return result, autorest.NewErrorWithError(err, "sql.DatabasesClient", "PauseDataWarehouse", resp, "Failure sending request") + } + + result, err = client.PauseDataWarehouseResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.DatabasesClient", "PauseDataWarehouse", resp, "Failure responding to request") + } + + return +} + +// PauseDataWarehousePreparer prepares the PauseDataWarehouse request. +func (client DatabasesClient) PauseDataWarehousePreparer(resourceGroupName string, serverName string, databaseName string, cancel <-chan struct{}) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "databaseName": autorest.Encode("path", databaseName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serverName": autorest.Encode("path", serverName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/databases/{databaseName}/pause", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{Cancel: cancel}) +} + +// PauseDataWarehouseSender sends the PauseDataWarehouse request. The method will close the +// http.Response Body if it receives an error. +func (client DatabasesClient) PauseDataWarehouseSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) +} + +// PauseDataWarehouseResponder handles the response to the PauseDataWarehouse request. The method always +// closes the http.Response Body. +func (client DatabasesClient) PauseDataWarehouseResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + autorest.ByClosing()) + result.Response = resp + return +} + +// ResumeDataWarehouse resume an Azure SQL Data Warehouse database. This +// method may poll for completion. Polling can be canceled by passing the +// cancel channel argument. The channel will be used to cancel polling and +// any outstanding HTTP requests. +// +// resourceGroupName is the name of the resource group that contains the +// resource. You can obtain this value from the Azure Resource Manager API or +// the portal. serverName is the name of the Azure SQL server. databaseName +// is the name of the Azure SQL Data Warehouse database to resume. +func (client DatabasesClient) ResumeDataWarehouse(resourceGroupName string, serverName string, databaseName string, cancel <-chan struct{}) (result autorest.Response, err error) { + req, err := client.ResumeDataWarehousePreparer(resourceGroupName, serverName, databaseName, cancel) + if err != nil { + return result, autorest.NewErrorWithError(err, "sql.DatabasesClient", "ResumeDataWarehouse", nil, "Failure preparing request") + } + + resp, err := client.ResumeDataWarehouseSender(req) + if err != nil { + result.Response = resp + return result, autorest.NewErrorWithError(err, "sql.DatabasesClient", "ResumeDataWarehouse", resp, "Failure sending request") + } + + result, err = client.ResumeDataWarehouseResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.DatabasesClient", "ResumeDataWarehouse", resp, "Failure responding to request") + } + + return +} + +// ResumeDataWarehousePreparer prepares the ResumeDataWarehouse request. +func (client DatabasesClient) ResumeDataWarehousePreparer(resourceGroupName string, serverName string, databaseName string, cancel <-chan struct{}) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "databaseName": autorest.Encode("path", databaseName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serverName": autorest.Encode("path", serverName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/databases/{databaseName}/resume", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{Cancel: cancel}) +} + +// ResumeDataWarehouseSender sends the ResumeDataWarehouse request. The method will close the +// http.Response Body if it receives an error. +func (client DatabasesClient) ResumeDataWarehouseSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) +} + +// ResumeDataWarehouseResponder handles the response to the ResumeDataWarehouse request. The method always +// closes the http.Response Body. +func (client DatabasesClient) ResumeDataWarehouseResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusAccepted, http.StatusOK), + autorest.ByClosing()) + result.Response = resp + return +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/arm/sql/elasticpools.go b/vendor/github.com/Azure/azure-sdk-for-go/arm/sql/elasticpools.go new file mode 100644 index 000000000..e68d6674a --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/arm/sql/elasticpools.go @@ -0,0 +1,582 @@ +package sql + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0 +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. + +import ( + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "net/http" +) + +// ElasticPoolsClient is the provides create, read, update and delete +// functionality for Azure SQL resources including servers, databases, +// elastic pools, recommendations, operations, and usage metrics. +type ElasticPoolsClient struct { + ManagementClient +} + +// NewElasticPoolsClient creates an instance of the ElasticPoolsClient client. +func NewElasticPoolsClient(subscriptionID string) ElasticPoolsClient { + return NewElasticPoolsClientWithBaseURI(DefaultBaseURI, subscriptionID) +} + +// NewElasticPoolsClientWithBaseURI creates an instance of the +// ElasticPoolsClient client. +func NewElasticPoolsClientWithBaseURI(baseURI string, subscriptionID string) ElasticPoolsClient { + return ElasticPoolsClient{NewWithBaseURI(baseURI, subscriptionID)} +} + +// CreateOrUpdate creates a new Azure SQL elastic pool or updates an existing +// Azure SQL elastic pool. This method may poll for completion. Polling can +// be canceled by passing the cancel channel argument. The channel will be +// used to cancel polling and any outstanding HTTP requests. +// +// resourceGroupName is the name of the resource group that contains the +// resource. You can obtain this value from the Azure Resource Manager API or +// the portal. serverName is the name of the Azure SQL server. +// elasticPoolName is the name of the Azure SQL Elastic Pool to be operated +// on (Updated or created). parameters is the required parameters for +// creating or updating an Elastic Pool. +func (client ElasticPoolsClient) CreateOrUpdate(resourceGroupName string, serverName string, elasticPoolName string, parameters ElasticPool, cancel <-chan struct{}) (result autorest.Response, err error) { + req, err := client.CreateOrUpdatePreparer(resourceGroupName, serverName, elasticPoolName, parameters, cancel) + if err != nil { + return result, autorest.NewErrorWithError(err, "sql.ElasticPoolsClient", "CreateOrUpdate", nil, "Failure preparing request") + } + + resp, err := client.CreateOrUpdateSender(req) + if err != nil { + result.Response = resp + return result, autorest.NewErrorWithError(err, "sql.ElasticPoolsClient", "CreateOrUpdate", resp, "Failure sending request") + } + + result, err = client.CreateOrUpdateResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.ElasticPoolsClient", "CreateOrUpdate", resp, "Failure responding to request") + } + + return +} + +// CreateOrUpdatePreparer prepares the CreateOrUpdate request. +func (client ElasticPoolsClient) CreateOrUpdatePreparer(resourceGroupName string, serverName string, elasticPoolName string, parameters ElasticPool, cancel <-chan struct{}) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "elasticPoolName": autorest.Encode("path", elasticPoolName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serverName": autorest.Encode("path", serverName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsJSON(), + autorest.AsPut(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/elasticPools/{elasticPoolName}", pathParameters), + autorest.WithJSON(parameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{Cancel: cancel}) +} + +// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the +// http.Response Body if it receives an error. +func (client ElasticPoolsClient) CreateOrUpdateSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) +} + +// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always +// closes the http.Response Body. +func (client ElasticPoolsClient) CreateOrUpdateResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated, http.StatusAccepted), + autorest.ByClosing()) + result.Response = resp + return +} + +// Delete deletes the Azure SQL elastic pool. +// +// resourceGroupName is the name of the resource group that contains the +// resource. You can obtain this value from the Azure Resource Manager API or +// the portal. serverName is the name of the Azure SQL server. +// elasticPoolName is the name of the Azure SQL Elastic Pool to be deleted. +func (client ElasticPoolsClient) Delete(resourceGroupName string, serverName string, elasticPoolName string) (result autorest.Response, err error) { + req, err := client.DeletePreparer(resourceGroupName, serverName, elasticPoolName) + if err != nil { + return result, autorest.NewErrorWithError(err, "sql.ElasticPoolsClient", "Delete", nil, "Failure preparing request") + } + + resp, err := client.DeleteSender(req) + if err != nil { + result.Response = resp + return result, autorest.NewErrorWithError(err, "sql.ElasticPoolsClient", "Delete", resp, "Failure sending request") + } + + result, err = client.DeleteResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.ElasticPoolsClient", "Delete", resp, "Failure responding to request") + } + + return +} + +// DeletePreparer prepares the Delete request. +func (client ElasticPoolsClient) DeletePreparer(resourceGroupName string, serverName string, elasticPoolName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "elasticPoolName": autorest.Encode("path", elasticPoolName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serverName": autorest.Encode("path", serverName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsDelete(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/elasticPools/{elasticPoolName}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// DeleteSender sends the Delete request. The method will close the +// http.Response Body if it receives an error. +func (client ElasticPoolsClient) DeleteSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// DeleteResponder handles the response to the Delete request. The method always +// closes the http.Response Body. +func (client ElasticPoolsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusNoContent), + autorest.ByClosing()) + result.Response = resp + return +} + +// Get gets information about an Azure SQL elastic pool. +// +// resourceGroupName is the name of the resource group that contains the +// resource. You can obtain this value from the Azure Resource Manager API or +// the portal. serverName is the name of the Azure SQL server. +// elasticPoolName is the name of the Azure SQL Elastic Pool to be retrieved. +func (client ElasticPoolsClient) Get(resourceGroupName string, serverName string, elasticPoolName string) (result ElasticPool, err error) { + req, err := client.GetPreparer(resourceGroupName, serverName, elasticPoolName) + if err != nil { + return result, autorest.NewErrorWithError(err, "sql.ElasticPoolsClient", "Get", nil, "Failure preparing request") + } + + resp, err := client.GetSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "sql.ElasticPoolsClient", "Get", resp, "Failure sending request") + } + + result, err = client.GetResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.ElasticPoolsClient", "Get", resp, "Failure responding to request") + } + + return +} + +// GetPreparer prepares the Get request. +func (client ElasticPoolsClient) GetPreparer(resourceGroupName string, serverName string, elasticPoolName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "elasticPoolName": autorest.Encode("path", elasticPoolName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serverName": autorest.Encode("path", serverName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/elasticPools/{elasticPoolName}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// GetSender sends the Get request. The method will close the +// http.Response Body if it receives an error. +func (client ElasticPoolsClient) GetSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// GetResponder handles the response to the Get request. The method always +// closes the http.Response Body. +func (client ElasticPoolsClient) GetResponder(resp *http.Response) (result ElasticPool, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// GetDatabase gets information about an Azure SQL database inside of an Azure +// SQL elastic pool. +// +// resourceGroupName is the name of the resource group that contains the +// resource. You can obtain this value from the Azure Resource Manager API or +// the portal. serverName is the name of the Azure SQL server. +// elasticPoolName is the name of the Azure SQL Elastic Pool to be retrieved. +// databaseName is the name of the Azure SQL database to be retrieved. +func (client ElasticPoolsClient) GetDatabase(resourceGroupName string, serverName string, elasticPoolName string, databaseName string) (result Database, err error) { + req, err := client.GetDatabasePreparer(resourceGroupName, serverName, elasticPoolName, databaseName) + if err != nil { + return result, autorest.NewErrorWithError(err, "sql.ElasticPoolsClient", "GetDatabase", nil, "Failure preparing request") + } + + resp, err := client.GetDatabaseSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "sql.ElasticPoolsClient", "GetDatabase", resp, "Failure sending request") + } + + result, err = client.GetDatabaseResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.ElasticPoolsClient", "GetDatabase", resp, "Failure responding to request") + } + + return +} + +// GetDatabasePreparer prepares the GetDatabase request. +func (client ElasticPoolsClient) GetDatabasePreparer(resourceGroupName string, serverName string, elasticPoolName string, databaseName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "databaseName": autorest.Encode("path", databaseName), + "elasticPoolName": autorest.Encode("path", elasticPoolName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serverName": autorest.Encode("path", serverName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/elasticPools/{elasticPoolName}/databases/{databaseName}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// GetDatabaseSender sends the GetDatabase request. The method will close the +// http.Response Body if it receives an error. +func (client ElasticPoolsClient) GetDatabaseSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// GetDatabaseResponder handles the response to the GetDatabase request. The method always +// closes the http.Response Body. +func (client ElasticPoolsClient) GetDatabaseResponder(resp *http.Response) (result Database, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// ListActivity returns information about Azure SQL elastic pool activities. +// +// resourceGroupName is the name of the resource group that contains the +// resource. You can obtain this value from the Azure Resource Manager API or +// the portal. serverName is the name of the Azure SQL server. +// elasticPoolName is the name of the Azure SQL Elastic Pool for which to get +// the current activity. +func (client ElasticPoolsClient) ListActivity(resourceGroupName string, serverName string, elasticPoolName string) (result ElasticPoolActivityListResult, err error) { + req, err := client.ListActivityPreparer(resourceGroupName, serverName, elasticPoolName) + if err != nil { + return result, autorest.NewErrorWithError(err, "sql.ElasticPoolsClient", "ListActivity", nil, "Failure preparing request") + } + + resp, err := client.ListActivitySender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "sql.ElasticPoolsClient", "ListActivity", resp, "Failure sending request") + } + + result, err = client.ListActivityResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.ElasticPoolsClient", "ListActivity", resp, "Failure responding to request") + } + + return +} + +// ListActivityPreparer prepares the ListActivity request. +func (client ElasticPoolsClient) ListActivityPreparer(resourceGroupName string, serverName string, elasticPoolName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "elasticPoolName": autorest.Encode("path", elasticPoolName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serverName": autorest.Encode("path", serverName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/elasticPools/{elasticPoolName}/elasticPoolActivity", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// ListActivitySender sends the ListActivity request. The method will close the +// http.Response Body if it receives an error. +func (client ElasticPoolsClient) ListActivitySender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// ListActivityResponder handles the response to the ListActivity request. The method always +// closes the http.Response Body. +func (client ElasticPoolsClient) ListActivityResponder(resp *http.Response) (result ElasticPoolActivityListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// ListByServer returns information about Azure SQL elastic pools. +// +// resourceGroupName is the name of the resource group that contains the +// resource. You can obtain this value from the Azure Resource Manager API or +// the portal. serverName is the name of the Azure SQL server. +func (client ElasticPoolsClient) ListByServer(resourceGroupName string, serverName string) (result ElasticPoolListResult, err error) { + req, err := client.ListByServerPreparer(resourceGroupName, serverName) + if err != nil { + return result, autorest.NewErrorWithError(err, "sql.ElasticPoolsClient", "ListByServer", nil, "Failure preparing request") + } + + resp, err := client.ListByServerSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "sql.ElasticPoolsClient", "ListByServer", resp, "Failure sending request") + } + + result, err = client.ListByServerResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.ElasticPoolsClient", "ListByServer", resp, "Failure responding to request") + } + + return +} + +// ListByServerPreparer prepares the ListByServer request. +func (client ElasticPoolsClient) ListByServerPreparer(resourceGroupName string, serverName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serverName": autorest.Encode("path", serverName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/elasticPools", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// ListByServerSender sends the ListByServer request. The method will close the +// http.Response Body if it receives an error. +func (client ElasticPoolsClient) ListByServerSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// ListByServerResponder handles the response to the ListByServer request. The method always +// closes the http.Response Body. +func (client ElasticPoolsClient) ListByServerResponder(resp *http.Response) (result ElasticPoolListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// ListDatabaseActivity returns information about activity on Azure SQL +// databases inside of an Azure SQL elastic pool. +// +// elasticPoolName is the name of the Azure SQL Elastic Pool. +// resourceGroupName is the name of the resource group that contains the +// resource. You can obtain this value from the Azure Resource Manager API or +// the portal. serverName is the name of the Azure SQL server. +func (client ElasticPoolsClient) ListDatabaseActivity(elasticPoolName string, resourceGroupName string, serverName string) (result ElasticPoolDatabaseActivityListResult, err error) { + req, err := client.ListDatabaseActivityPreparer(elasticPoolName, resourceGroupName, serverName) + if err != nil { + return result, autorest.NewErrorWithError(err, "sql.ElasticPoolsClient", "ListDatabaseActivity", nil, "Failure preparing request") + } + + resp, err := client.ListDatabaseActivitySender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "sql.ElasticPoolsClient", "ListDatabaseActivity", resp, "Failure sending request") + } + + result, err = client.ListDatabaseActivityResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.ElasticPoolsClient", "ListDatabaseActivity", resp, "Failure responding to request") + } + + return +} + +// ListDatabaseActivityPreparer prepares the ListDatabaseActivity request. +func (client ElasticPoolsClient) ListDatabaseActivityPreparer(elasticPoolName string, resourceGroupName string, serverName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "elasticPoolName": autorest.Encode("path", elasticPoolName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serverName": autorest.Encode("path", serverName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/elasticPools/{elasticPoolName}/elasticPoolDatabaseActivity", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// ListDatabaseActivitySender sends the ListDatabaseActivity request. The method will close the +// http.Response Body if it receives an error. +func (client ElasticPoolsClient) ListDatabaseActivitySender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// ListDatabaseActivityResponder handles the response to the ListDatabaseActivity request. The method always +// closes the http.Response Body. +func (client ElasticPoolsClient) ListDatabaseActivityResponder(resp *http.Response) (result ElasticPoolDatabaseActivityListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// ListDatabases returns information about an Azure SQL database inside of an +// Azure SQL elastic pool. +// +// resourceGroupName is the name of the resource group that contains the +// resource. You can obtain this value from the Azure Resource Manager API or +// the portal. serverName is the name of the Azure SQL server. +// elasticPoolName is the name of the Azure SQL Elastic Pool to be retrieved. +func (client ElasticPoolsClient) ListDatabases(resourceGroupName string, serverName string, elasticPoolName string) (result DatabaseListResult, err error) { + req, err := client.ListDatabasesPreparer(resourceGroupName, serverName, elasticPoolName) + if err != nil { + return result, autorest.NewErrorWithError(err, "sql.ElasticPoolsClient", "ListDatabases", nil, "Failure preparing request") + } + + resp, err := client.ListDatabasesSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "sql.ElasticPoolsClient", "ListDatabases", resp, "Failure sending request") + } + + result, err = client.ListDatabasesResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.ElasticPoolsClient", "ListDatabases", resp, "Failure responding to request") + } + + return +} + +// ListDatabasesPreparer prepares the ListDatabases request. +func (client ElasticPoolsClient) ListDatabasesPreparer(resourceGroupName string, serverName string, elasticPoolName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "elasticPoolName": autorest.Encode("path", elasticPoolName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serverName": autorest.Encode("path", serverName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/elasticPools/{elasticPoolName}/databases", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// ListDatabasesSender sends the ListDatabases request. The method will close the +// http.Response Body if it receives an error. +func (client ElasticPoolsClient) ListDatabasesSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// ListDatabasesResponder handles the response to the ListDatabases request. The method always +// closes the http.Response Body. +func (client ElasticPoolsClient) ListDatabasesResponder(resp *http.Response) (result DatabaseListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/arm/sql/models.go b/vendor/github.com/Azure/azure-sdk-for-go/arm/sql/models.go new file mode 100644 index 000000000..497d7defb --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/arm/sql/models.go @@ -0,0 +1,810 @@ +package sql + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0 +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. + +import ( + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/date" + "github.com/satori/uuid" +) + +// CreateMode enumerates the values for create mode. +type CreateMode string + +const ( + // Copy specifies the copy state for create mode. + Copy CreateMode = "Copy" + // Default specifies the default state for create mode. + Default CreateMode = "Default" + // NonReadableSecondary specifies the non readable secondary state for + // create mode. + NonReadableSecondary CreateMode = "NonReadableSecondary" + // OnlineSecondary specifies the online secondary state for create mode. + OnlineSecondary CreateMode = "OnlineSecondary" + // PointInTimeRestore specifies the point in time restore state for create + // mode. + PointInTimeRestore CreateMode = "PointInTimeRestore" + // Recovery specifies the recovery state for create mode. + Recovery CreateMode = "Recovery" + // Restore specifies the restore state for create mode. + Restore CreateMode = "Restore" +) + +// DatabaseEditions enumerates the values for database editions. +type DatabaseEditions string + +const ( + // Basic specifies the basic state for database editions. + Basic DatabaseEditions = "Basic" + // Business specifies the business state for database editions. + Business DatabaseEditions = "Business" + // DataWarehouse specifies the data warehouse state for database editions. + DataWarehouse DatabaseEditions = "DataWarehouse" + // Free specifies the free state for database editions. + Free DatabaseEditions = "Free" + // Premium specifies the premium state for database editions. + Premium DatabaseEditions = "Premium" + // Standard specifies the standard state for database editions. + Standard DatabaseEditions = "Standard" + // Stretch specifies the stretch state for database editions. + Stretch DatabaseEditions = "Stretch" + // Web specifies the web state for database editions. + Web DatabaseEditions = "Web" +) + +// ElasticPoolEditions enumerates the values for elastic pool editions. +type ElasticPoolEditions string + +const ( + // ElasticPoolEditionsBasic specifies the elastic pool editions basic + // state for elastic pool editions. + ElasticPoolEditionsBasic ElasticPoolEditions = "Basic" + // ElasticPoolEditionsPremium specifies the elastic pool editions premium + // state for elastic pool editions. + ElasticPoolEditionsPremium ElasticPoolEditions = "Premium" + // ElasticPoolEditionsStandard specifies the elastic pool editions + // standard state for elastic pool editions. + ElasticPoolEditionsStandard ElasticPoolEditions = "Standard" +) + +// ElasticPoolState enumerates the values for elastic pool state. +type ElasticPoolState string + +const ( + // Creating specifies the creating state for elastic pool state. + Creating ElasticPoolState = "Creating" + // Disabled specifies the disabled state for elastic pool state. + Disabled ElasticPoolState = "Disabled" + // Ready specifies the ready state for elastic pool state. + Ready ElasticPoolState = "Ready" +) + +// RecommendedIndexActions enumerates the values for recommended index actions. +type RecommendedIndexActions string + +const ( + // Create specifies the create state for recommended index actions. + Create RecommendedIndexActions = "Create" + // Drop specifies the drop state for recommended index actions. + Drop RecommendedIndexActions = "Drop" + // Rebuild specifies the rebuild state for recommended index actions. + Rebuild RecommendedIndexActions = "Rebuild" +) + +// RecommendedIndexStates enumerates the values for recommended index states. +type RecommendedIndexStates string + +const ( + // Active specifies the active state for recommended index states. + Active RecommendedIndexStates = "Active" + // Blocked specifies the blocked state for recommended index states. + Blocked RecommendedIndexStates = "Blocked" + // Executing specifies the executing state for recommended index states. + Executing RecommendedIndexStates = "Executing" + // Expired specifies the expired state for recommended index states. + Expired RecommendedIndexStates = "Expired" + // Ignored specifies the ignored state for recommended index states. + Ignored RecommendedIndexStates = "Ignored" + // Pending specifies the pending state for recommended index states. + Pending RecommendedIndexStates = "Pending" + // PendingRevert specifies the pending revert state for recommended index + // states. + PendingRevert RecommendedIndexStates = "Pending Revert" + // Reverted specifies the reverted state for recommended index states. + Reverted RecommendedIndexStates = "Reverted" + // Reverting specifies the reverting state for recommended index states. + Reverting RecommendedIndexStates = "Reverting" + // Success specifies the success state for recommended index states. + Success RecommendedIndexStates = "Success" + // Verifying specifies the verifying state for recommended index states. + Verifying RecommendedIndexStates = "Verifying" +) + +// RecommendedIndexTypes enumerates the values for recommended index types. +type RecommendedIndexTypes string + +const ( + // CLUSTERED specifies the clustered state for recommended index types. + CLUSTERED RecommendedIndexTypes = "CLUSTERED" + // CLUSTEREDCOLUMNSTORE specifies the clusteredcolumnstore state for + // recommended index types. + CLUSTEREDCOLUMNSTORE RecommendedIndexTypes = "CLUSTERED COLUMNSTORE" + // COLUMNSTORE specifies the columnstore state for recommended index types. + COLUMNSTORE RecommendedIndexTypes = "COLUMNSTORE" + // NONCLUSTERED specifies the nonclustered state for recommended index + // types. + NONCLUSTERED RecommendedIndexTypes = "NONCLUSTERED" +) + +// RestorePointTypes enumerates the values for restore point types. +type RestorePointTypes string + +const ( + // CONTINUOUS specifies the continuous state for restore point types. + CONTINUOUS RestorePointTypes = "CONTINUOUS" + // DISCRETE specifies the discrete state for restore point types. + DISCRETE RestorePointTypes = "DISCRETE" +) + +// ServerVersion enumerates the values for server version. +type ServerVersion string + +const ( + // OneTwoFullStopZero specifies the one two full stop zero state for + // server version. + OneTwoFullStopZero ServerVersion = "12.0" + // TwoFullStopZero specifies the two full stop zero state for server + // version. + TwoFullStopZero ServerVersion = "2.0" +) + +// ServiceObjectiveName enumerates the values for service objective name. +type ServiceObjectiveName string + +const ( + // ServiceObjectiveNameBasic specifies the service objective name basic + // state for service objective name. + ServiceObjectiveNameBasic ServiceObjectiveName = "Basic" + // ServiceObjectiveNameP1 specifies the service objective name p1 state + // for service objective name. + ServiceObjectiveNameP1 ServiceObjectiveName = "P1" + // ServiceObjectiveNameP2 specifies the service objective name p2 state + // for service objective name. + ServiceObjectiveNameP2 ServiceObjectiveName = "P2" + // ServiceObjectiveNameP3 specifies the service objective name p3 state + // for service objective name. + ServiceObjectiveNameP3 ServiceObjectiveName = "P3" + // ServiceObjectiveNameS0 specifies the service objective name s0 state + // for service objective name. + ServiceObjectiveNameS0 ServiceObjectiveName = "S0" + // ServiceObjectiveNameS1 specifies the service objective name s1 state + // for service objective name. + ServiceObjectiveNameS1 ServiceObjectiveName = "S1" + // ServiceObjectiveNameS2 specifies the service objective name s2 state + // for service objective name. + ServiceObjectiveNameS2 ServiceObjectiveName = "S2" + // ServiceObjectiveNameS3 specifies the service objective name s3 state + // for service objective name. + ServiceObjectiveNameS3 ServiceObjectiveName = "S3" +) + +// TableType enumerates the values for table type. +type TableType string + +const ( + // BaseTable specifies the base table state for table type. + BaseTable TableType = "BaseTable" + // View specifies the view state for table type. + View TableType = "View" +) + +// TargetDatabaseEditions enumerates the values for target database editions. +type TargetDatabaseEditions string + +const ( + // TargetDatabaseEditionsBasic specifies the target database editions + // basic state for target database editions. + TargetDatabaseEditionsBasic TargetDatabaseEditions = "Basic" + // TargetDatabaseEditionsDataWarehouse specifies the target database + // editions data warehouse state for target database editions. + TargetDatabaseEditionsDataWarehouse TargetDatabaseEditions = "DataWarehouse" + // TargetDatabaseEditionsFree specifies the target database editions free + // state for target database editions. + TargetDatabaseEditionsFree TargetDatabaseEditions = "Free" + // TargetDatabaseEditionsPremium specifies the target database editions + // premium state for target database editions. + TargetDatabaseEditionsPremium TargetDatabaseEditions = "Premium" + // TargetDatabaseEditionsStandard specifies the target database editions + // standard state for target database editions. + TargetDatabaseEditionsStandard TargetDatabaseEditions = "Standard" + // TargetDatabaseEditionsStretch specifies the target database editions + // stretch state for target database editions. + TargetDatabaseEditionsStretch TargetDatabaseEditions = "Stretch" +) + +// TargetElasticPoolEditions enumerates the values for target elastic pool +// editions. +type TargetElasticPoolEditions string + +const ( + // TargetElasticPoolEditionsBasic specifies the target elastic pool + // editions basic state for target elastic pool editions. + TargetElasticPoolEditionsBasic TargetElasticPoolEditions = "Basic" + // TargetElasticPoolEditionsPremium specifies the target elastic pool + // editions premium state for target elastic pool editions. + TargetElasticPoolEditionsPremium TargetElasticPoolEditions = "Premium" + // TargetElasticPoolEditionsStandard specifies the target elastic pool + // editions standard state for target elastic pool editions. + TargetElasticPoolEditionsStandard TargetElasticPoolEditions = "Standard" +) + +// TransparentDataEncryptionActivityStates enumerates the values for +// transparent data encryption activity states. +type TransparentDataEncryptionActivityStates string + +const ( + // Decrypting specifies the decrypting state for transparent data + // encryption activity states. + Decrypting TransparentDataEncryptionActivityStates = "Decrypting" + // Encrypting specifies the encrypting state for transparent data + // encryption activity states. + Encrypting TransparentDataEncryptionActivityStates = "Encrypting" +) + +// TransparentDataEncryptionStates enumerates the values for transparent data +// encryption states. +type TransparentDataEncryptionStates string + +const ( + // TransparentDataEncryptionStatesDisabled specifies the transparent data + // encryption states disabled state for transparent data encryption + // states. + TransparentDataEncryptionStatesDisabled TransparentDataEncryptionStates = "Disabled" + // TransparentDataEncryptionStatesEnabled specifies the transparent data + // encryption states enabled state for transparent data encryption states. + TransparentDataEncryptionStatesEnabled TransparentDataEncryptionStates = "Enabled" +) + +// Column is represents an Azure SQL Database table column. +type Column struct { + Name *string `json:"name,omitempty"` + ID *string `json:"id,omitempty"` + Type *string `json:"type,omitempty"` + Location *string `json:"location,omitempty"` + Tags *map[string]*string `json:"tags,omitempty"` + *ColumnProperties `json:"properties,omitempty"` +} + +// ColumnProperties is represents the properties of an Azure SQL Database +// table column. +type ColumnProperties struct { + ColumnType *string `json:"columnType,omitempty"` +} + +// Database is represents an Azure SQL Database. +type Database struct { + autorest.Response `json:"-"` + Name *string `json:"name,omitempty"` + ID *string `json:"id,omitempty"` + Type *string `json:"type,omitempty"` + Location *string `json:"location,omitempty"` + Tags *map[string]*string `json:"tags,omitempty"` + *DatabaseProperties `json:"properties,omitempty"` +} + +// DatabaseListResult is represents the response to a List Azure SQL Database +// request. +type DatabaseListResult struct { + autorest.Response `json:"-"` + Value *[]Database `json:"value,omitempty"` +} + +// DatabaseMetric is represents Azure SQL Database metrics. +type DatabaseMetric struct { + ResourceName *string `json:"resourceName,omitempty"` + DisplayName *string `json:"displayName,omitempty"` + CurrentValue *float64 `json:"currentValue,omitempty"` + Limit *float64 `json:"limit,omitempty"` + Unit *string `json:"unit,omitempty"` + NextResetTime *date.Time `json:"nextResetTime,omitempty"` +} + +// DatabaseMetricListResult is represents the response to a List Azure SQL +// Database metrics request. +type DatabaseMetricListResult struct { + autorest.Response `json:"-"` + Value *[]DatabaseMetric `json:"value,omitempty"` +} + +// DatabaseProperties is represents the properties of an Azure SQL Database. +type DatabaseProperties struct { + Collation *string `json:"collation,omitempty"` + CreationDate *date.Time `json:"creationDate,omitempty"` + ContainmentState *int64 `json:"containmentState,omitempty"` + CurrentServiceObjectiveID *uuid.UUID `json:"currentServiceObjectiveId,omitempty"` + DatabaseID *string `json:"databaseId,omitempty"` + EarliestRestoreDate *date.Time `json:"earliestRestoreDate,omitempty"` + CreateMode CreateMode `json:"createMode,omitempty"` + SourceDatabaseID *string `json:"sourceDatabaseId,omitempty"` + Edition DatabaseEditions `json:"edition,omitempty"` + MaxSizeBytes *string `json:"maxSizeBytes,omitempty"` + RequestedServiceObjectiveID *uuid.UUID `json:"requestedServiceObjectiveId,omitempty"` + RequestedServiceObjectiveName ServiceObjectiveName `json:"requestedServiceObjectiveName,omitempty"` + ServiceLevelObjective ServiceObjectiveName `json:"serviceLevelObjective,omitempty"` + Status *string `json:"status,omitempty"` + ElasticPoolName *string `json:"elasticPoolName,omitempty"` + DefaultSecondaryLocation *string `json:"defaultSecondaryLocation,omitempty"` + ServiceTierAdvisors *[]ServiceTierAdvisor `json:"serviceTierAdvisors,omitempty"` + UpgradeHint *UpgradeHint `json:"upgradeHint,omitempty"` + Schemas *[]Schema `json:"schemas,omitempty"` + TransparentDataEncryption *[]TransparentDataEncryption `json:"transparentDataEncryption,omitempty"` + RecommendedIndex *[]RecommendedIndex `json:"recommendedIndex,omitempty"` +} + +// ElasticPool is represents an Azure SQL Database elastic pool. +type ElasticPool struct { + autorest.Response `json:"-"` + Name *string `json:"name,omitempty"` + ID *string `json:"id,omitempty"` + Type *string `json:"type,omitempty"` + Location *string `json:"location,omitempty"` + Tags *map[string]*string `json:"tags,omitempty"` + *ElasticPoolProperties `json:"properties,omitempty"` +} + +// ElasticPoolActivity is represents the activity on an Azure SQL Elastic Pool. +type ElasticPoolActivity struct { + Name *string `json:"name,omitempty"` + ID *string `json:"id,omitempty"` + Type *string `json:"type,omitempty"` + Location *string `json:"location,omitempty"` + Tags *map[string]*string `json:"tags,omitempty"` + *ElasticPoolActivityProperties `json:"properties,omitempty"` +} + +// ElasticPoolActivityListResult is represents the response to a List Azure +// SQL Elastic Pool Activity request. +type ElasticPoolActivityListResult struct { + autorest.Response `json:"-"` + Value *[]ElasticPoolActivity `json:"value,omitempty"` +} + +// ElasticPoolActivityProperties is represents the properties of an Azure SQL +// Elastic Pool. +type ElasticPoolActivityProperties struct { + EndTime *date.Time `json:"endTime,omitempty"` + ErrorCode *int32 `json:"errorCode,omitempty"` + ErrorMessage *string `json:"errorMessage,omitempty"` + ErrorSeverity *int32 `json:"errorSeverity,omitempty"` + Operation *string `json:"operation,omitempty"` + OperationID *string `json:"operationId,omitempty"` + PercentComplete *int32 `json:"percentComplete,omitempty"` + RequestedDatabaseDtuMax *int32 `json:"requestedDatabaseDtuMax,omitempty"` + RequestedDatabaseDtuMin *int32 `json:"requestedDatabaseDtuMin,omitempty"` + RequestedDtu *int32 `json:"requestedDtu,omitempty"` + RequestedElasticPoolName *string `json:"requestedElasticPoolName,omitempty"` + RequestedStorageLimitInGB *int64 `json:"requestedStorageLimitInGB,omitempty"` + ElasticPoolName *string `json:"elasticPoolName,omitempty"` + ServerName *string `json:"serverName,omitempty"` + StartTime *date.Time `json:"startTime,omitempty"` + State *string `json:"state,omitempty"` +} + +// ElasticPoolDatabaseActivity is represents the activity on an Azure SQL +// Elastic Pool. +type ElasticPoolDatabaseActivity struct { + Name *string `json:"name,omitempty"` + ID *string `json:"id,omitempty"` + Type *string `json:"type,omitempty"` + Location *string `json:"location,omitempty"` + Tags *map[string]*string `json:"tags,omitempty"` + *ElasticPoolDatabaseActivityProperties `json:"properties,omitempty"` +} + +// ElasticPoolDatabaseActivityListResult is represents the response to a List +// Azure SQL Elastic Pool Database Activity request. +type ElasticPoolDatabaseActivityListResult struct { + autorest.Response `json:"-"` + Value *[]ElasticPoolDatabaseActivity `json:"value,omitempty"` +} + +// ElasticPoolDatabaseActivityProperties is represents the properties of an +// Azure SQL Elastic Pool Database Activity. +type ElasticPoolDatabaseActivityProperties struct { + DatabaseName *string `json:"databaseName,omitempty"` + EndTime *date.Time `json:"endTime,omitempty"` + ErrorCode *int32 `json:"errorCode,omitempty"` + ErrorMessage *string `json:"errorMessage,omitempty"` + ErrorSeverity *int32 `json:"errorSeverity,omitempty"` + Operation *string `json:"operation,omitempty"` + OperationID *string `json:"operationId,omitempty"` + PercentComplete *int32 `json:"percentComplete,omitempty"` + RequestedElasticPoolName *string `json:"requestedElasticPoolName,omitempty"` + CurrentElasticPoolName *string `json:"currentElasticPoolName,omitempty"` + CurrentServiceObjective *string `json:"currentServiceObjective,omitempty"` + RequestedServiceObjective *string `json:"requestedServiceObjective,omitempty"` + ServerName *string `json:"serverName,omitempty"` + StartTime *date.Time `json:"startTime,omitempty"` + State *string `json:"state,omitempty"` +} + +// ElasticPoolListResult is represents the response to a List Azure SQL +// Elastic Pool request. +type ElasticPoolListResult struct { + autorest.Response `json:"-"` + Value *[]ElasticPool `json:"value,omitempty"` +} + +// ElasticPoolProperties is represents the properties of an Azure SQL Elastic +// Pool. +type ElasticPoolProperties struct { + CreationDate *date.Time `json:"creationDate,omitempty"` + State ElasticPoolState `json:"state,omitempty"` + Edition ElasticPoolEditions `json:"edition,omitempty"` + Dtu *int32 `json:"dtu,omitempty"` + DatabaseDtuMax *int32 `json:"databaseDtuMax,omitempty"` + DatabaseDtuMin *int32 `json:"databaseDtuMin,omitempty"` + StorageMB *int32 `json:"storageMB,omitempty"` +} + +// OperationImpact is represents impact of an operation, both in absolute and +// relative terms. +type OperationImpact struct { + Name *string `json:"name,omitempty"` + Unit *string `json:"unit,omitempty"` + ChangeValueAbsolute *float64 `json:"changeValueAbsolute,omitempty"` + ChangeValueRelative *float64 `json:"changeValueRelative,omitempty"` +} + +// RecommendedDatabaseProperties is represents the properties of a recommended +// Azure SQL Database being upgraded. +type RecommendedDatabaseProperties struct { + Name *string `json:"Name,omitempty"` + TargetEdition TargetDatabaseEditions `json:"TargetEdition,omitempty"` + TargetServiceLevelObjective *string `json:"TargetServiceLevelObjective,omitempty"` +} + +// RecommendedElasticPool is represents an Azure SQL Recommended Elastic Pool. +type RecommendedElasticPool struct { + autorest.Response `json:"-"` + Name *string `json:"name,omitempty"` + ID *string `json:"id,omitempty"` + Type *string `json:"type,omitempty"` + Location *string `json:"location,omitempty"` + Tags *map[string]*string `json:"tags,omitempty"` + *RecommendedElasticPoolProperties `json:"properties,omitempty"` +} + +// RecommendedElasticPoolListMetricsResult is represents the response to a +// List Azure SQL Recommended Elastic Pool metrics request. +type RecommendedElasticPoolListMetricsResult struct { + autorest.Response `json:"-"` + Value *[]RecommendedElasticPoolMetric `json:"value,omitempty"` +} + +// RecommendedElasticPoolListResult is represents the response to a List Azure +// SQL Recommended Elastic Pool request. +type RecommendedElasticPoolListResult struct { + autorest.Response `json:"-"` + Value *[]RecommendedElasticPool `json:"value,omitempty"` +} + +// RecommendedElasticPoolMetric is represents Azure SQL recommended elastic +// pool metric. +type RecommendedElasticPoolMetric struct { + DateTime *date.Time `json:"dateTime,omitempty"` + Dtu *float64 `json:"dtu,omitempty"` + SizeGB *float64 `json:"sizeGB,omitempty"` +} + +// RecommendedElasticPoolProperties is represents the properties of an Azure +// SQL Recommended Elastic Pool. +type RecommendedElasticPoolProperties struct { + DatabaseEdition ElasticPoolEditions `json:"databaseEdition,omitempty"` + Dtu *float64 `json:"dtu,omitempty"` + DatabaseDtuMin *float64 `json:"databaseDtuMin,omitempty"` + DatabaseDtuMax *float64 `json:"databaseDtuMax,omitempty"` + StorageMB *float64 `json:"storageMB,omitempty"` + ObservationPeriodStart *date.Time `json:"observationPeriodStart,omitempty"` + ObservationPeriodEnd *date.Time `json:"observationPeriodEnd,omitempty"` + MaxObservedDtu *float64 `json:"maxObservedDtu,omitempty"` + MaxObservedStorageMB *float64 `json:"maxObservedStorageMB,omitempty"` + Databases *[]Database `json:"databases,omitempty"` + Metrics *[]RecommendedElasticPoolMetric `json:"metrics,omitempty"` +} + +// RecommendedIndex is represents an Azure SQL Database recommended index. +type RecommendedIndex struct { + Name *string `json:"name,omitempty"` + ID *string `json:"id,omitempty"` + Type *string `json:"type,omitempty"` + Location *string `json:"location,omitempty"` + Tags *map[string]*string `json:"tags,omitempty"` + *RecommendedIndexProperties `json:"properties,omitempty"` +} + +// RecommendedIndexProperties is represents the properties of an Azure SQL +// Database recommended index. +type RecommendedIndexProperties struct { + Action RecommendedIndexActions `json:"action,omitempty"` + State RecommendedIndexStates `json:"state,omitempty"` + Created *date.Time `json:"created,omitempty"` + LastModified *date.Time `json:"lastModified,omitempty"` + IndexType RecommendedIndexTypes `json:"indexType,omitempty"` + Schema *string `json:"schema,omitempty"` + Table *string `json:"table,omitempty"` + Columns *[]string `json:"columns,omitempty"` + IncludedColumns *[]string `json:"includedColumns,omitempty"` + IndexScript *string `json:"indexScript,omitempty"` + EstimatedImpact *[]OperationImpact `json:"estimatedImpact,omitempty"` + ReportedImpact *[]OperationImpact `json:"reportedImpact,omitempty"` +} + +// Resource is resource properties +type Resource struct { + Name *string `json:"name,omitempty"` + ID *string `json:"id,omitempty"` + Type *string `json:"type,omitempty"` + Location *string `json:"location,omitempty"` + Tags *map[string]*string `json:"tags,omitempty"` +} + +// RestorePoint is represents an Azure SQL Database restore point. +type RestorePoint struct { + Name *string `json:"name,omitempty"` + ID *string `json:"id,omitempty"` + Type *string `json:"type,omitempty"` + Location *string `json:"location,omitempty"` + Tags *map[string]*string `json:"tags,omitempty"` + *RestorePointProperties `json:"properties,omitempty"` +} + +// RestorePointListResult is represents the response to a List Azure SQL +// Database restore points request. +type RestorePointListResult struct { + autorest.Response `json:"-"` + Value *[]RestorePoint `json:"value,omitempty"` +} + +// RestorePointProperties is represents the properties of an Azure SQL +// Database restore point. +type RestorePointProperties struct { + RestorePointType RestorePointTypes `json:"restorePointType,omitempty"` + RestorePointCreationDate *date.Time `json:"restorePointCreationDate,omitempty"` + EarliestRestoreDate *date.Time `json:"earliestRestoreDate,omitempty"` +} + +// Schema is represents an Azure SQL Database schema. +type Schema struct { + Name *string `json:"name,omitempty"` + ID *string `json:"id,omitempty"` + Type *string `json:"type,omitempty"` + Location *string `json:"location,omitempty"` + Tags *map[string]*string `json:"tags,omitempty"` + *SchemaProperties `json:"properties,omitempty"` +} + +// SchemaProperties is represents the properties of an Azure SQL Database +// schema. +type SchemaProperties struct { + Tables *[]Table `json:"tables,omitempty"` +} + +// Server is represents an Azure SQL server. +type Server struct { + autorest.Response `json:"-"` + Name *string `json:"name,omitempty"` + ID *string `json:"id,omitempty"` + Type *string `json:"type,omitempty"` + Location *string `json:"location,omitempty"` + Tags *map[string]*string `json:"tags,omitempty"` + *ServerProperties `json:"properties,omitempty"` +} + +// ServerListResult is represents the response to a Get Azure SQL server +// request. +type ServerListResult struct { + autorest.Response `json:"-"` + Value *[]Server `json:"value,omitempty"` +} + +// ServerMetric is represents Azure SQL server metrics. +type ServerMetric struct { + ResourceName *string `json:"resourceName,omitempty"` + DisplayName *string `json:"displayName,omitempty"` + CurrentValue *float64 `json:"currentValue,omitempty"` + Limit *float64 `json:"limit,omitempty"` + Unit *string `json:"unit,omitempty"` + NextResetTime *date.Time `json:"nextResetTime,omitempty"` +} + +// ServerMetricListResult is represents the response to a List Azure SQL +// server metrics request. +type ServerMetricListResult struct { + autorest.Response `json:"-"` + Value *[]ServerMetric `json:"value,omitempty"` +} + +// ServerProperties is represents the properties of an Azure SQL server. +type ServerProperties struct { + FullyQualifiedDomainName *string `json:"fullyQualifiedDomainName,omitempty"` + Version ServerVersion `json:"version,omitempty"` + AdministratorLogin *string `json:"administratorLogin,omitempty"` + AdministratorLoginPassword *string `json:"administratorLoginPassword,omitempty"` +} + +// ServiceObjective is represents an Azure SQL Database Service Objective. +type ServiceObjective struct { + autorest.Response `json:"-"` + Name *string `json:"name,omitempty"` + ID *string `json:"id,omitempty"` + *ServiceObjectiveProperties `json:"properties,omitempty"` +} + +// ServiceObjectiveListResult is represents the response to a Get Azure SQL +// Database Service Objectives request. +type ServiceObjectiveListResult struct { + autorest.Response `json:"-"` + Value *[]ServiceObjective `json:"value,omitempty"` +} + +// ServiceObjectiveProperties is represents the properties of an Azure SQL +// Database Service Objective. +type ServiceObjectiveProperties struct { + ServiceObjectiveName *string `json:"serviceObjectiveName,omitempty"` + IsDefault *bool `json:"isDefault,omitempty"` + IsSystem *bool `json:"isSystem,omitempty"` + Description *string `json:"description,omitempty"` + Enabled *bool `json:"enabled,omitempty"` +} + +// ServiceTierAdvisor is represents a Service Tier Advisor. +type ServiceTierAdvisor struct { + autorest.Response `json:"-"` + Name *string `json:"name,omitempty"` + ID *string `json:"id,omitempty"` + *ServiceTierAdvisorProperties `json:"properties,omitempty"` +} + +// ServiceTierAdvisorListResult is represents the response to a list service +// tier advisor request. +type ServiceTierAdvisorListResult struct { + autorest.Response `json:"-"` + Value *[]ServiceTierAdvisor `json:"value,omitempty"` +} + +// ServiceTierAdvisorProperties is represents the properties of a Service Tier +// Advisor. +type ServiceTierAdvisorProperties struct { + ObservationPeriodStart *date.Time `json:"observationPeriodStart,omitempty"` + ObservationPeriodEnd *date.Time `json:"observationPeriodEnd,omitempty"` + ActiveTimeRatio *float64 `json:"activeTimeRatio,omitempty"` + MinDtu *float64 `json:"minDtu,omitempty"` + AvgDtu *float64 `json:"avgDtu,omitempty"` + MaxDtu *float64 `json:"maxDtu,omitempty"` + MaxSizeInGB *float64 `json:"maxSizeInGB,omitempty"` + ServiceLevelObjectiveUsageMetrics *[]SloUsageMetric `json:"serviceLevelObjectiveUsageMetrics,omitempty"` + CurrentServiceLevelObjective *uuid.UUID `json:"currentServiceLevelObjective,omitempty"` + CurrentServiceLevelObjectiveID *uuid.UUID `json:"currentServiceLevelObjectiveId,omitempty"` + UsageBasedRecommendationServiceLevelObjective *string `json:"usageBasedRecommendationServiceLevelObjective,omitempty"` + UsageBasedRecommendationServiceLevelObjectiveID *uuid.UUID `json:"usageBasedRecommendationServiceLevelObjectiveId,omitempty"` + DatabaseSizeBasedRecommendationServiceLevelObjective *string `json:"databaseSizeBasedRecommendationServiceLevelObjective,omitempty"` + DatabaseSizeBasedRecommendationServiceLevelObjectiveID *uuid.UUID `json:"databaseSizeBasedRecommendationServiceLevelObjectiveId,omitempty"` + DisasterPlanBasedRecommendationServiceLevelObjective *string `json:"disasterPlanBasedRecommendationServiceLevelObjective,omitempty"` + DisasterPlanBasedRecommendationServiceLevelObjectiveID *uuid.UUID `json:"disasterPlanBasedRecommendationServiceLevelObjectiveId,omitempty"` + OverallRecommendationServiceLevelObjective *string `json:"overallRecommendationServiceLevelObjective,omitempty"` + OverallRecommendationServiceLevelObjectiveID *uuid.UUID `json:"overallRecommendationServiceLevelObjectiveId,omitempty"` + Confidence *float64 `json:"confidence,omitempty"` +} + +// SloUsageMetric is represents a Slo Usage Metric. +type SloUsageMetric struct { + Name *string `json:"name,omitempty"` + ID *string `json:"id,omitempty"` + Type *string `json:"type,omitempty"` + Location *string `json:"location,omitempty"` + Tags *map[string]*string `json:"tags,omitempty"` + ServiceLevelObjective ServiceObjectiveName `json:"serviceLevelObjective,omitempty"` + ServiceLevelObjectiveID *uuid.UUID `json:"serviceLevelObjectiveId,omitempty"` + InRangeTimeRatio *float64 `json:"inRangeTimeRatio,omitempty"` +} + +// SubResource is subresource properties +type SubResource struct { + Name *string `json:"name,omitempty"` + ID *string `json:"id,omitempty"` +} + +// Table is represents an Azure SQL Database table. +type Table struct { + Name *string `json:"name,omitempty"` + ID *string `json:"id,omitempty"` + Type *string `json:"type,omitempty"` + Location *string `json:"location,omitempty"` + Tags *map[string]*string `json:"tags,omitempty"` + *TableProperties `json:"properties,omitempty"` +} + +// TableProperties is represents the properties of an Azure SQL Database table. +type TableProperties struct { + TableType TableType `json:"tableType,omitempty"` + Columns *[]Column `json:"columns,omitempty"` + RecommendedIndexes *[]RecommendedIndex `json:"recommendedIndexes,omitempty"` +} + +// TransparentDataEncryption is represents an Azure SQL Database Transparent +// Data Encryption . +type TransparentDataEncryption struct { + autorest.Response `json:"-"` + Name *string `json:"name,omitempty"` + ID *string `json:"id,omitempty"` + *TransparentDataEncryptionProperties `json:"properties,omitempty"` +} + +// TransparentDataEncryptionActivity is represents an Azure SQL Database +// Transparent Data Encryption Scan. +type TransparentDataEncryptionActivity struct { + Name *string `json:"name,omitempty"` + ID *string `json:"id,omitempty"` + *TransparentDataEncryptionActivityProperties `json:"properties,omitempty"` +} + +// TransparentDataEncryptionActivityListResult is represents the response to a +// List Azure SQL Database Transparent Data Encryption Activity request. +type TransparentDataEncryptionActivityListResult struct { + autorest.Response `json:"-"` + Value *[]TransparentDataEncryptionActivity `json:"value,omitempty"` +} + +// TransparentDataEncryptionActivityProperties is represents the properties of +// an Azure SQL Database Transparent Data Encryption Scan. +type TransparentDataEncryptionActivityProperties struct { + Status TransparentDataEncryptionActivityStates `json:"status,omitempty"` + PercentComplete *float64 `json:"percentComplete,omitempty"` +} + +// TransparentDataEncryptionProperties is represents the properties of an +// Azure SQL Database Transparent Data Encryption. +type TransparentDataEncryptionProperties struct { + Status TransparentDataEncryptionStates `json:"status,omitempty"` +} + +// UpgradeHint is represents a Upgrade Hint. +type UpgradeHint struct { + Name *string `json:"name,omitempty"` + ID *string `json:"id,omitempty"` + Type *string `json:"type,omitempty"` + Location *string `json:"location,omitempty"` + Tags *map[string]*string `json:"tags,omitempty"` + TargetServiceLevelObjective *string `json:"targetServiceLevelObjective,omitempty"` + TargetServiceLevelObjectiveID *uuid.UUID `json:"targetServiceLevelObjectiveId,omitempty"` +} + +// UpgradeRecommendedElasticPoolProperties is represents the properties of a +// Azure SQL Recommended Elastic Pool being upgraded. +type UpgradeRecommendedElasticPoolProperties struct { + Name *string `json:"Name,omitempty"` + Edition TargetElasticPoolEditions `json:"Edition,omitempty"` + Dtu *int32 `json:"Dtu,omitempty"` + StorageMb *int32 `json:"StorageMb,omitempty"` + DatabaseDtuMin *int32 `json:"DatabaseDtuMin,omitempty"` + DatabaseDtuMax *int32 `json:"DatabaseDtuMax,omitempty"` + DatabaseCollection *[]string `json:"DatabaseCollection,omitempty"` + IncludeAllDatabases *bool `json:"IncludeAllDatabases,omitempty"` +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/arm/sql/recommendedelasticpools.go b/vendor/github.com/Azure/azure-sdk-for-go/arm/sql/recommendedelasticpools.go new file mode 100644 index 000000000..2dbe6611e --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/arm/sql/recommendedelasticpools.go @@ -0,0 +1,380 @@ +package sql + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0 +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. + +import ( + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "net/http" +) + +// RecommendedElasticPoolsClient is the provides create, read, update and +// delete functionality for Azure SQL resources including servers, databases, +// elastic pools, recommendations, operations, and usage metrics. +type RecommendedElasticPoolsClient struct { + ManagementClient +} + +// NewRecommendedElasticPoolsClient creates an instance of the +// RecommendedElasticPoolsClient client. +func NewRecommendedElasticPoolsClient(subscriptionID string) RecommendedElasticPoolsClient { + return NewRecommendedElasticPoolsClientWithBaseURI(DefaultBaseURI, subscriptionID) +} + +// NewRecommendedElasticPoolsClientWithBaseURI creates an instance of the +// RecommendedElasticPoolsClient client. +func NewRecommendedElasticPoolsClientWithBaseURI(baseURI string, subscriptionID string) RecommendedElasticPoolsClient { + return RecommendedElasticPoolsClient{NewWithBaseURI(baseURI, subscriptionID)} +} + +// Get gets information about an Azure SQL Recommended Elastic Pool. +// +// resourceGroupName is the name of the resource group that contains the +// resource. You can obtain this value from the Azure Resource Manager API or +// the portal. serverName is the name of the Azure SQL server. +// recommendedElasticPoolName is the name of the Azure SQL Recommended +// Elastic Pool to be retrieved. +func (client RecommendedElasticPoolsClient) Get(resourceGroupName string, serverName string, recommendedElasticPoolName string) (result RecommendedElasticPool, err error) { + req, err := client.GetPreparer(resourceGroupName, serverName, recommendedElasticPoolName) + if err != nil { + return result, autorest.NewErrorWithError(err, "sql.RecommendedElasticPoolsClient", "Get", nil, "Failure preparing request") + } + + resp, err := client.GetSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "sql.RecommendedElasticPoolsClient", "Get", resp, "Failure sending request") + } + + result, err = client.GetResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.RecommendedElasticPoolsClient", "Get", resp, "Failure responding to request") + } + + return +} + +// GetPreparer prepares the Get request. +func (client RecommendedElasticPoolsClient) GetPreparer(resourceGroupName string, serverName string, recommendedElasticPoolName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "recommendedElasticPoolName": autorest.Encode("path", recommendedElasticPoolName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serverName": autorest.Encode("path", serverName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/recommendedElasticPools/{recommendedElasticPoolName}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// GetSender sends the Get request. The method will close the +// http.Response Body if it receives an error. +func (client RecommendedElasticPoolsClient) GetSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// GetResponder handles the response to the Get request. The method always +// closes the http.Response Body. +func (client RecommendedElasticPoolsClient) GetResponder(resp *http.Response) (result RecommendedElasticPool, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// GetDatabases gets information about an Azure SQL database inside of an +// Azure SQL Recommended Elastic Pool. +// +// resourceGroupName is the name of the resource group that contains the +// resource. You can obtain this value from the Azure Resource Manager API or +// the portal. serverName is the name of the Azure SQL server. +// recommendedElasticPoolName is the name of the Azure SQL Elastic Pool to be +// retrieved. databaseName is the name of the Azure SQL database to be +// retrieved. +func (client RecommendedElasticPoolsClient) GetDatabases(resourceGroupName string, serverName string, recommendedElasticPoolName string, databaseName string) (result Database, err error) { + req, err := client.GetDatabasesPreparer(resourceGroupName, serverName, recommendedElasticPoolName, databaseName) + if err != nil { + return result, autorest.NewErrorWithError(err, "sql.RecommendedElasticPoolsClient", "GetDatabases", nil, "Failure preparing request") + } + + resp, err := client.GetDatabasesSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "sql.RecommendedElasticPoolsClient", "GetDatabases", resp, "Failure sending request") + } + + result, err = client.GetDatabasesResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.RecommendedElasticPoolsClient", "GetDatabases", resp, "Failure responding to request") + } + + return +} + +// GetDatabasesPreparer prepares the GetDatabases request. +func (client RecommendedElasticPoolsClient) GetDatabasesPreparer(resourceGroupName string, serverName string, recommendedElasticPoolName string, databaseName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "databaseName": autorest.Encode("path", databaseName), + "recommendedElasticPoolName": autorest.Encode("path", recommendedElasticPoolName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serverName": autorest.Encode("path", serverName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/recommendedElasticPools/{recommendedElasticPoolName}/databases/{databaseName}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// GetDatabasesSender sends the GetDatabases request. The method will close the +// http.Response Body if it receives an error. +func (client RecommendedElasticPoolsClient) GetDatabasesSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// GetDatabasesResponder handles the response to the GetDatabases request. The method always +// closes the http.Response Body. +func (client RecommendedElasticPoolsClient) GetDatabasesResponder(resp *http.Response) (result Database, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// List returns information about Azure SQL Recommended Elastic Pools. +// +// resourceGroupName is the name of the resource group that contains the +// resource. You can obtain this value from the Azure Resource Manager API or +// the portal. serverName is the name of the Azure SQL server. +func (client RecommendedElasticPoolsClient) List(resourceGroupName string, serverName string) (result RecommendedElasticPoolListResult, err error) { + req, err := client.ListPreparer(resourceGroupName, serverName) + if err != nil { + return result, autorest.NewErrorWithError(err, "sql.RecommendedElasticPoolsClient", "List", nil, "Failure preparing request") + } + + resp, err := client.ListSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "sql.RecommendedElasticPoolsClient", "List", resp, "Failure sending request") + } + + result, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.RecommendedElasticPoolsClient", "List", resp, "Failure responding to request") + } + + return +} + +// ListPreparer prepares the List request. +func (client RecommendedElasticPoolsClient) ListPreparer(resourceGroupName string, serverName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serverName": autorest.Encode("path", serverName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/recommendedElasticPools", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// ListSender sends the List request. The method will close the +// http.Response Body if it receives an error. +func (client RecommendedElasticPoolsClient) ListSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// ListResponder handles the response to the List request. The method always +// closes the http.Response Body. +func (client RecommendedElasticPoolsClient) ListResponder(resp *http.Response) (result RecommendedElasticPoolListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// ListDatabases returns information about an Azure SQL database inside of an +// Azure SQL Recommended Elastic Pool. +// +// resourceGroupName is the name of the resource group that contains the +// resource. You can obtain this value from the Azure Resource Manager API or +// the portal. serverName is the name of the Azure SQL server. +// recommendedElasticPoolName is the name of the Azure SQL Recommended +// Elastic Pool to be retrieved. +func (client RecommendedElasticPoolsClient) ListDatabases(resourceGroupName string, serverName string, recommendedElasticPoolName string) (result DatabaseListResult, err error) { + req, err := client.ListDatabasesPreparer(resourceGroupName, serverName, recommendedElasticPoolName) + if err != nil { + return result, autorest.NewErrorWithError(err, "sql.RecommendedElasticPoolsClient", "ListDatabases", nil, "Failure preparing request") + } + + resp, err := client.ListDatabasesSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "sql.RecommendedElasticPoolsClient", "ListDatabases", resp, "Failure sending request") + } + + result, err = client.ListDatabasesResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.RecommendedElasticPoolsClient", "ListDatabases", resp, "Failure responding to request") + } + + return +} + +// ListDatabasesPreparer prepares the ListDatabases request. +func (client RecommendedElasticPoolsClient) ListDatabasesPreparer(resourceGroupName string, serverName string, recommendedElasticPoolName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "recommendedElasticPoolName": autorest.Encode("path", recommendedElasticPoolName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serverName": autorest.Encode("path", serverName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/recommendedElasticPools/{recommendedElasticPoolName}/databases", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// ListDatabasesSender sends the ListDatabases request. The method will close the +// http.Response Body if it receives an error. +func (client RecommendedElasticPoolsClient) ListDatabasesSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// ListDatabasesResponder handles the response to the ListDatabases request. The method always +// closes the http.Response Body. +func (client RecommendedElasticPoolsClient) ListDatabasesResponder(resp *http.Response) (result DatabaseListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// ListMetrics returns information about an recommended elastic pool metrics. +// +// resourceGroupName is the name of the resource group that contains the +// resource. You can obtain this value from the Azure Resource Manager API or +// the portal. serverName is the name of the Azure SQL server. +// recommendedElasticPoolName is the name of the Azure SQL Recommended +// Elastic Pool to be retrieved. +func (client RecommendedElasticPoolsClient) ListMetrics(resourceGroupName string, serverName string, recommendedElasticPoolName string) (result RecommendedElasticPoolListMetricsResult, err error) { + req, err := client.ListMetricsPreparer(resourceGroupName, serverName, recommendedElasticPoolName) + if err != nil { + return result, autorest.NewErrorWithError(err, "sql.RecommendedElasticPoolsClient", "ListMetrics", nil, "Failure preparing request") + } + + resp, err := client.ListMetricsSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "sql.RecommendedElasticPoolsClient", "ListMetrics", resp, "Failure sending request") + } + + result, err = client.ListMetricsResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.RecommendedElasticPoolsClient", "ListMetrics", resp, "Failure responding to request") + } + + return +} + +// ListMetricsPreparer prepares the ListMetrics request. +func (client RecommendedElasticPoolsClient) ListMetricsPreparer(resourceGroupName string, serverName string, recommendedElasticPoolName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "recommendedElasticPoolName": autorest.Encode("path", recommendedElasticPoolName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serverName": autorest.Encode("path", serverName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/recommendedElasticPools/{recommendedElasticPoolName}/metrics", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// ListMetricsSender sends the ListMetrics request. The method will close the +// http.Response Body if it receives an error. +func (client RecommendedElasticPoolsClient) ListMetricsSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// ListMetricsResponder handles the response to the ListMetrics request. The method always +// closes the http.Response Body. +func (client RecommendedElasticPoolsClient) ListMetricsResponder(resp *http.Response) (result RecommendedElasticPoolListMetricsResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/arm/sql/servers.go b/vendor/github.com/Azure/azure-sdk-for-go/arm/sql/servers.go new file mode 100644 index 000000000..11e4a35e4 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/arm/sql/servers.go @@ -0,0 +1,553 @@ +package sql + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0 +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. + +import ( + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "net/http" +) + +// ServersClient is the provides create, read, update and delete functionality +// for Azure SQL resources including servers, databases, elastic pools, +// recommendations, operations, and usage metrics. +type ServersClient struct { + ManagementClient +} + +// NewServersClient creates an instance of the ServersClient client. +func NewServersClient(subscriptionID string) ServersClient { + return NewServersClientWithBaseURI(DefaultBaseURI, subscriptionID) +} + +// NewServersClientWithBaseURI creates an instance of the ServersClient client. +func NewServersClientWithBaseURI(baseURI string, subscriptionID string) ServersClient { + return ServersClient{NewWithBaseURI(baseURI, subscriptionID)} +} + +// CreateOrUpdate creates a new Azure SQL server. +// +// resourceGroupName is the name of the resource group that contains the +// resource. You can obtain this value from the Azure Resource Manager API or +// the portal. serverName is the name of the Azure SQL server. parameters is +// the required parameters for creating or updating a server. +func (client ServersClient) CreateOrUpdate(resourceGroupName string, serverName string, parameters Server) (result Server, err error) { + req, err := client.CreateOrUpdatePreparer(resourceGroupName, serverName, parameters) + if err != nil { + return result, autorest.NewErrorWithError(err, "sql.ServersClient", "CreateOrUpdate", nil, "Failure preparing request") + } + + resp, err := client.CreateOrUpdateSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "sql.ServersClient", "CreateOrUpdate", resp, "Failure sending request") + } + + result, err = client.CreateOrUpdateResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.ServersClient", "CreateOrUpdate", resp, "Failure responding to request") + } + + return +} + +// CreateOrUpdatePreparer prepares the CreateOrUpdate request. +func (client ServersClient) CreateOrUpdatePreparer(resourceGroupName string, serverName string, parameters Server) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serverName": autorest.Encode("path", serverName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsJSON(), + autorest.AsPut(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}", pathParameters), + autorest.WithJSON(parameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the +// http.Response Body if it receives an error. +func (client ServersClient) CreateOrUpdateSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always +// closes the http.Response Body. +func (client ServersClient) CreateOrUpdateResponder(resp *http.Response) (result Server, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// Delete deletes a SQL server. +// +// resourceGroupName is the name of the resource group that contains the +// resource. You can obtain this value from the Azure Resource Manager API or +// the portal. serverName is the name of the Azure SQL server. +func (client ServersClient) Delete(resourceGroupName string, serverName string) (result autorest.Response, err error) { + req, err := client.DeletePreparer(resourceGroupName, serverName) + if err != nil { + return result, autorest.NewErrorWithError(err, "sql.ServersClient", "Delete", nil, "Failure preparing request") + } + + resp, err := client.DeleteSender(req) + if err != nil { + result.Response = resp + return result, autorest.NewErrorWithError(err, "sql.ServersClient", "Delete", resp, "Failure sending request") + } + + result, err = client.DeleteResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.ServersClient", "Delete", resp, "Failure responding to request") + } + + return +} + +// DeletePreparer prepares the Delete request. +func (client ServersClient) DeletePreparer(resourceGroupName string, serverName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serverName": autorest.Encode("path", serverName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsDelete(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// DeleteSender sends the Delete request. The method will close the +// http.Response Body if it receives an error. +func (client ServersClient) DeleteSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// DeleteResponder handles the response to the Delete request. The method always +// closes the http.Response Body. +func (client ServersClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusNoContent), + autorest.ByClosing()) + result.Response = resp + return +} + +// GetByResourceGroup gets information about an Azure SQL server. +// +// resourceGroupName is the name of the resource group that contains the +// resource. You can obtain this value from the Azure Resource Manager API or +// the portal. serverName is the name of the Azure SQL server. +func (client ServersClient) GetByResourceGroup(resourceGroupName string, serverName string) (result Server, err error) { + req, err := client.GetByResourceGroupPreparer(resourceGroupName, serverName) + if err != nil { + return result, autorest.NewErrorWithError(err, "sql.ServersClient", "GetByResourceGroup", nil, "Failure preparing request") + } + + resp, err := client.GetByResourceGroupSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "sql.ServersClient", "GetByResourceGroup", resp, "Failure sending request") + } + + result, err = client.GetByResourceGroupResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.ServersClient", "GetByResourceGroup", resp, "Failure responding to request") + } + + return +} + +// GetByResourceGroupPreparer prepares the GetByResourceGroup request. +func (client ServersClient) GetByResourceGroupPreparer(resourceGroupName string, serverName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serverName": autorest.Encode("path", serverName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// GetByResourceGroupSender sends the GetByResourceGroup request. The method will close the +// http.Response Body if it receives an error. +func (client ServersClient) GetByResourceGroupSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// GetByResourceGroupResponder handles the response to the GetByResourceGroup request. The method always +// closes the http.Response Body. +func (client ServersClient) GetByResourceGroupResponder(resp *http.Response) (result Server, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// GetServiceObjective gets information about an Azure SQL database Service +// Objective. +// +// resourceGroupName is the name of the resource group that contains the +// resource. You can obtain this value from the Azure Resource Manager API or +// the portal. serverName is the name of the Azure SQL server. +// serviceObjectiveName is the name of the service objective to retrieve. +func (client ServersClient) GetServiceObjective(resourceGroupName string, serverName string, serviceObjectiveName string) (result ServiceObjective, err error) { + req, err := client.GetServiceObjectivePreparer(resourceGroupName, serverName, serviceObjectiveName) + if err != nil { + return result, autorest.NewErrorWithError(err, "sql.ServersClient", "GetServiceObjective", nil, "Failure preparing request") + } + + resp, err := client.GetServiceObjectiveSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "sql.ServersClient", "GetServiceObjective", resp, "Failure sending request") + } + + result, err = client.GetServiceObjectiveResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.ServersClient", "GetServiceObjective", resp, "Failure responding to request") + } + + return +} + +// GetServiceObjectivePreparer prepares the GetServiceObjective request. +func (client ServersClient) GetServiceObjectivePreparer(resourceGroupName string, serverName string, serviceObjectiveName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serverName": autorest.Encode("path", serverName), + "serviceObjectiveName": autorest.Encode("path", serviceObjectiveName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/serviceObjectives/{serviceObjectiveName}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// GetServiceObjectiveSender sends the GetServiceObjective request. The method will close the +// http.Response Body if it receives an error. +func (client ServersClient) GetServiceObjectiveSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// GetServiceObjectiveResponder handles the response to the GetServiceObjective request. The method always +// closes the http.Response Body. +func (client ServersClient) GetServiceObjectiveResponder(resp *http.Response) (result ServiceObjective, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// List returns information about an Azure SQL server. +func (client ServersClient) List() (result ServerListResult, err error) { + req, err := client.ListPreparer() + if err != nil { + return result, autorest.NewErrorWithError(err, "sql.ServersClient", "List", nil, "Failure preparing request") + } + + resp, err := client.ListSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "sql.ServersClient", "List", resp, "Failure sending request") + } + + result, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.ServersClient", "List", resp, "Failure responding to request") + } + + return +} + +// ListPreparer prepares the List request. +func (client ServersClient) ListPreparer() (*http.Request, error) { + pathParameters := map[string]interface{}{ + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Sql/servers", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// ListSender sends the List request. The method will close the +// http.Response Body if it receives an error. +func (client ServersClient) ListSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// ListResponder handles the response to the List request. The method always +// closes the http.Response Body. +func (client ServersClient) ListResponder(resp *http.Response) (result ServerListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// ListByResourceGroup returns information about an Azure SQL server. +// +// resourceGroupName is the name of the resource group that contains the +// resource. You can obtain this value from the Azure Resource Manager API or +// the portal. +func (client ServersClient) ListByResourceGroup(resourceGroupName string) (result ServerListResult, err error) { + req, err := client.ListByResourceGroupPreparer(resourceGroupName) + if err != nil { + return result, autorest.NewErrorWithError(err, "sql.ServersClient", "ListByResourceGroup", nil, "Failure preparing request") + } + + resp, err := client.ListByResourceGroupSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "sql.ServersClient", "ListByResourceGroup", resp, "Failure sending request") + } + + result, err = client.ListByResourceGroupResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.ServersClient", "ListByResourceGroup", resp, "Failure responding to request") + } + + return +} + +// ListByResourceGroupPreparer prepares the ListByResourceGroup request. +func (client ServersClient) ListByResourceGroupPreparer(resourceGroupName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// ListByResourceGroupSender sends the ListByResourceGroup request. The method will close the +// http.Response Body if it receives an error. +func (client ServersClient) ListByResourceGroupSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// ListByResourceGroupResponder handles the response to the ListByResourceGroup request. The method always +// closes the http.Response Body. +func (client ServersClient) ListByResourceGroupResponder(resp *http.Response) (result ServerListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// ListServiceObjectives returns information about Azure SQL database Service +// Objectives. +// +// resourceGroupName is the name of the resource group that contains the +// resource. You can obtain this value from the Azure Resource Manager API or +// the portal. serverName is the name of the Azure SQL server. +func (client ServersClient) ListServiceObjectives(resourceGroupName string, serverName string) (result ServiceObjectiveListResult, err error) { + req, err := client.ListServiceObjectivesPreparer(resourceGroupName, serverName) + if err != nil { + return result, autorest.NewErrorWithError(err, "sql.ServersClient", "ListServiceObjectives", nil, "Failure preparing request") + } + + resp, err := client.ListServiceObjectivesSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "sql.ServersClient", "ListServiceObjectives", resp, "Failure sending request") + } + + result, err = client.ListServiceObjectivesResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.ServersClient", "ListServiceObjectives", resp, "Failure responding to request") + } + + return +} + +// ListServiceObjectivesPreparer prepares the ListServiceObjectives request. +func (client ServersClient) ListServiceObjectivesPreparer(resourceGroupName string, serverName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serverName": autorest.Encode("path", serverName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/serviceObjectives", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// ListServiceObjectivesSender sends the ListServiceObjectives request. The method will close the +// http.Response Body if it receives an error. +func (client ServersClient) ListServiceObjectivesSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// ListServiceObjectivesResponder handles the response to the ListServiceObjectives request. The method always +// closes the http.Response Body. +func (client ServersClient) ListServiceObjectivesResponder(resp *http.Response) (result ServiceObjectiveListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// ListUsages returns information about Azure SQL server usage. +// +// resourceGroupName is the name of the resource group that contains the +// resource. You can obtain this value from the Azure Resource Manager API or +// the portal. serverName is the name of the Azure SQL server. +func (client ServersClient) ListUsages(resourceGroupName string, serverName string) (result ServerMetricListResult, err error) { + req, err := client.ListUsagesPreparer(resourceGroupName, serverName) + if err != nil { + return result, autorest.NewErrorWithError(err, "sql.ServersClient", "ListUsages", nil, "Failure preparing request") + } + + resp, err := client.ListUsagesSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "sql.ServersClient", "ListUsages", resp, "Failure sending request") + } + + result, err = client.ListUsagesResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.ServersClient", "ListUsages", resp, "Failure responding to request") + } + + return +} + +// ListUsagesPreparer prepares the ListUsages request. +func (client ServersClient) ListUsagesPreparer(resourceGroupName string, serverName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serverName": autorest.Encode("path", serverName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/usages", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// ListUsagesSender sends the ListUsages request. The method will close the +// http.Response Body if it receives an error. +func (client ServersClient) ListUsagesSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// ListUsagesResponder handles the response to the ListUsages request. The method always +// closes the http.Response Body. +func (client ServersClient) ListUsagesResponder(resp *http.Response) (result ServerMetricListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/arm/sql/version.go b/vendor/github.com/Azure/azure-sdk-for-go/arm/sql/version.go new file mode 100644 index 000000000..2fabb4531 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/arm/sql/version.go @@ -0,0 +1,60 @@ +package sql + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0 +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. + +import ( + "bytes" + "fmt" + "strings" +) + +const ( + major = "8" + minor = "1" + patch = "0" + tag = "beta" + userAgentFormat = "Azure-SDK-For-Go/%s arm-%s/%s" +) + +// cached results of UserAgent and Version to prevent repeated operations. +var ( + userAgent string + version string +) + +// UserAgent returns the UserAgent string to use when sending http.Requests. +func UserAgent() string { + if userAgent == "" { + userAgent = fmt.Sprintf(userAgentFormat, Version(), "sql", "2014-04-01") + } + return userAgent +} + +// Version returns the semantic version (see http://semver.org) of the client. +func Version() string { + if version == "" { + versionBuilder := bytes.NewBufferString(fmt.Sprintf("%s.%s.%s", major, minor, patch)) + if tag != "" { + versionBuilder.WriteRune('-') + versionBuilder.WriteString(strings.TrimPrefix(tag, "-")) + } + version = string(versionBuilder.Bytes()) + } + return version +} diff --git a/vendor/github.com/Azure/go-autorest/autorest/autorest.go b/vendor/github.com/Azure/go-autorest/autorest/autorest.go index 9804f401e..51f1c4bbc 100644 --- a/vendor/github.com/Azure/go-autorest/autorest/autorest.go +++ b/vendor/github.com/Azure/go-autorest/autorest/autorest.go @@ -16,6 +16,7 @@ and Responding. A typical pattern is: DoRetryForAttempts(5, time.Second)) err = Respond(resp, + ByDiscardingBody(), ByClosing()) Each phase relies on decorators to modify and / or manage processing. Decorators may first modify diff --git a/vendor/github.com/Azure/go-autorest/autorest/azure/async.go b/vendor/github.com/Azure/go-autorest/autorest/azure/async.go index 280d32a61..6e076981f 100644 --- a/vendor/github.com/Azure/go-autorest/autorest/azure/async.go +++ b/vendor/github.com/Azure/go-autorest/autorest/azure/async.go @@ -3,12 +3,13 @@ package azure import ( "bytes" "fmt" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/date" "io/ioutil" "net/http" "strings" "time" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/date" ) const ( diff --git a/vendor/github.com/Azure/go-autorest/autorest/azure/environments.go b/vendor/github.com/Azure/go-autorest/autorest/azure/environments.go index ebf754eab..4701b4376 100644 --- a/vendor/github.com/Azure/go-autorest/autorest/azure/environments.go +++ b/vendor/github.com/Azure/go-autorest/autorest/azure/environments.go @@ -19,93 +19,108 @@ var environments = map[string]Environment{ // Environment represents a set of endpoints for each of Azure's Clouds. type Environment struct { - Name string `json:"name"` - ManagementPortalURL string `json:"managementPortalURL"` - PublishSettingsURL string `json:"publishSettingsURL"` - ServiceManagementEndpoint string `json:"serviceManagementEndpoint"` - ResourceManagerEndpoint string `json:"resourceManagerEndpoint"` - ActiveDirectoryEndpoint string `json:"activeDirectoryEndpoint"` - GalleryEndpoint string `json:"galleryEndpoint"` - KeyVaultEndpoint string `json:"keyVaultEndpoint"` - GraphEndpoint string `json:"graphEndpoint"` - StorageEndpointSuffix string `json:"storageEndpointSuffix"` - SQLDatabaseDNSSuffix string `json:"sqlDatabaseDNSSuffix"` - TrafficManagerDNSSuffix string `json:"trafficManagerDNSSuffix"` - KeyVaultDNSSuffix string `json:"keyVaultDNSSuffix"` - ServiceBusEndpointSuffix string `json:"serviceBusEndpointSuffix"` + Name string `json:"name"` + ManagementPortalURL string `json:"managementPortalURL"` + PublishSettingsURL string `json:"publishSettingsURL"` + ServiceManagementEndpoint string `json:"serviceManagementEndpoint"` + ResourceManagerEndpoint string `json:"resourceManagerEndpoint"` + ActiveDirectoryEndpoint string `json:"activeDirectoryEndpoint"` + GalleryEndpoint string `json:"galleryEndpoint"` + KeyVaultEndpoint string `json:"keyVaultEndpoint"` + GraphEndpoint string `json:"graphEndpoint"` + StorageEndpointSuffix string `json:"storageEndpointSuffix"` + SQLDatabaseDNSSuffix string `json:"sqlDatabaseDNSSuffix"` + TrafficManagerDNSSuffix string `json:"trafficManagerDNSSuffix"` + KeyVaultDNSSuffix string `json:"keyVaultDNSSuffix"` + ServiceBusEndpointSuffix string `json:"serviceBusEndpointSuffix"` + ServiceManagementVMDNSSuffix string `json:"serviceManagementVMDNSSuffix"` + ResourceManagerVMDNSSuffix string `json:"resourceManagerVMDNSSuffix"` + ContainerRegistryDNSSuffix string `json:"containerRegistryDNSSuffix"` } var ( // PublicCloud is the default public Azure cloud environment PublicCloud = Environment{ - Name: "AzurePublicCloud", - ManagementPortalURL: "https://manage.windowsazure.com/", - PublishSettingsURL: "https://manage.windowsazure.com/publishsettings/index", - ServiceManagementEndpoint: "https://management.core.windows.net/", - ResourceManagerEndpoint: "https://management.azure.com/", - ActiveDirectoryEndpoint: "https://login.microsoftonline.com/", - GalleryEndpoint: "https://gallery.azure.com/", - KeyVaultEndpoint: "https://vault.azure.net/", - GraphEndpoint: "https://graph.windows.net/", - StorageEndpointSuffix: "core.windows.net", - SQLDatabaseDNSSuffix: "database.windows.net", - TrafficManagerDNSSuffix: "trafficmanager.net", - KeyVaultDNSSuffix: "vault.azure.net", - ServiceBusEndpointSuffix: "servicebus.azure.com", + Name: "AzurePublicCloud", + ManagementPortalURL: "https://manage.windowsazure.com/", + PublishSettingsURL: "https://manage.windowsazure.com/publishsettings/index", + ServiceManagementEndpoint: "https://management.core.windows.net/", + ResourceManagerEndpoint: "https://management.azure.com/", + ActiveDirectoryEndpoint: "https://login.microsoftonline.com/", + GalleryEndpoint: "https://gallery.azure.com/", + KeyVaultEndpoint: "https://vault.azure.net/", + GraphEndpoint: "https://graph.windows.net/", + StorageEndpointSuffix: "core.windows.net", + SQLDatabaseDNSSuffix: "database.windows.net", + TrafficManagerDNSSuffix: "trafficmanager.net", + KeyVaultDNSSuffix: "vault.azure.net", + ServiceBusEndpointSuffix: "servicebus.azure.com", + ServiceManagementVMDNSSuffix: "cloudapp.net", + ResourceManagerVMDNSSuffix: "cloudapp.azure.com", + ContainerRegistryDNSSuffix: "azurecr.io", } // USGovernmentCloud is the cloud environment for the US Government USGovernmentCloud = Environment{ - Name: "AzureUSGovernmentCloud", - ManagementPortalURL: "https://manage.windowsazure.us/", - PublishSettingsURL: "https://manage.windowsazure.us/publishsettings/index", - ServiceManagementEndpoint: "https://management.core.usgovcloudapi.net/", - ResourceManagerEndpoint: "https://management.usgovcloudapi.net/", - ActiveDirectoryEndpoint: "https://login.microsoftonline.com/", - GalleryEndpoint: "https://gallery.usgovcloudapi.net/", - KeyVaultEndpoint: "https://vault.usgovcloudapi.net/", - GraphEndpoint: "https://graph.usgovcloudapi.net/", - StorageEndpointSuffix: "core.usgovcloudapi.net", - SQLDatabaseDNSSuffix: "database.usgovcloudapi.net", - TrafficManagerDNSSuffix: "usgovtrafficmanager.net", - KeyVaultDNSSuffix: "vault.usgovcloudapi.net", - ServiceBusEndpointSuffix: "servicebus.usgovcloudapi.net", + Name: "AzureUSGovernmentCloud", + ManagementPortalURL: "https://manage.windowsazure.us/", + PublishSettingsURL: "https://manage.windowsazure.us/publishsettings/index", + ServiceManagementEndpoint: "https://management.core.usgovcloudapi.net/", + ResourceManagerEndpoint: "https://management.usgovcloudapi.net/", + ActiveDirectoryEndpoint: "https://login.microsoftonline.com/", + GalleryEndpoint: "https://gallery.usgovcloudapi.net/", + KeyVaultEndpoint: "https://vault.usgovcloudapi.net/", + GraphEndpoint: "https://graph.usgovcloudapi.net/", + StorageEndpointSuffix: "core.usgovcloudapi.net", + SQLDatabaseDNSSuffix: "database.usgovcloudapi.net", + TrafficManagerDNSSuffix: "usgovtrafficmanager.net", + KeyVaultDNSSuffix: "vault.usgovcloudapi.net", + ServiceBusEndpointSuffix: "servicebus.usgovcloudapi.net", + ServiceManagementVMDNSSuffix: "usgovcloudapp.net", + ResourceManagerVMDNSSuffix: "cloudapp.windowsazure.us", + ContainerRegistryDNSSuffix: "azurecr.io", } // ChinaCloud is the cloud environment operated in China ChinaCloud = Environment{ - Name: "AzureChinaCloud", - ManagementPortalURL: "https://manage.chinacloudapi.com/", - PublishSettingsURL: "https://manage.chinacloudapi.com/publishsettings/index", - ServiceManagementEndpoint: "https://management.core.chinacloudapi.cn/", - ResourceManagerEndpoint: "https://management.chinacloudapi.cn/", - ActiveDirectoryEndpoint: "https://login.chinacloudapi.cn/?api-version=1.0", - GalleryEndpoint: "https://gallery.chinacloudapi.cn/", - KeyVaultEndpoint: "https://vault.azure.cn/", - GraphEndpoint: "https://graph.chinacloudapi.cn/", - StorageEndpointSuffix: "core.chinacloudapi.cn", - SQLDatabaseDNSSuffix: "database.chinacloudapi.cn", - TrafficManagerDNSSuffix: "trafficmanager.cn", - KeyVaultDNSSuffix: "vault.azure.cn", - ServiceBusEndpointSuffix: "servicebus.chinacloudapi.net", + Name: "AzureChinaCloud", + ManagementPortalURL: "https://manage.chinacloudapi.com/", + PublishSettingsURL: "https://manage.chinacloudapi.com/publishsettings/index", + ServiceManagementEndpoint: "https://management.core.chinacloudapi.cn/", + ResourceManagerEndpoint: "https://management.chinacloudapi.cn/", + ActiveDirectoryEndpoint: "https://login.chinacloudapi.cn/", + GalleryEndpoint: "https://gallery.chinacloudapi.cn/", + KeyVaultEndpoint: "https://vault.azure.cn/", + GraphEndpoint: "https://graph.chinacloudapi.cn/", + StorageEndpointSuffix: "core.chinacloudapi.cn", + SQLDatabaseDNSSuffix: "database.chinacloudapi.cn", + TrafficManagerDNSSuffix: "trafficmanager.cn", + KeyVaultDNSSuffix: "vault.azure.cn", + ServiceBusEndpointSuffix: "servicebus.chinacloudapi.net", + ServiceManagementVMDNSSuffix: "chinacloudapp.cn", + ResourceManagerVMDNSSuffix: "cloudapp.azure.cn", + ContainerRegistryDNSSuffix: "azurecr.io", } // GermanCloud is the cloud environment operated in Germany GermanCloud = Environment{ - Name: "AzureGermanCloud", - ManagementPortalURL: "http://portal.microsoftazure.de/", - PublishSettingsURL: "https://manage.microsoftazure.de/publishsettings/index", - ServiceManagementEndpoint: "https://management.core.cloudapi.de/", - ResourceManagerEndpoint: "https://management.microsoftazure.de/", - ActiveDirectoryEndpoint: "https://login.microsoftonline.de/", - GalleryEndpoint: "https://gallery.cloudapi.de/", - KeyVaultEndpoint: "https://vault.microsoftazure.de/", - GraphEndpoint: "https://graph.cloudapi.de/", - StorageEndpointSuffix: "core.cloudapi.de", - SQLDatabaseDNSSuffix: "database.cloudapi.de", - TrafficManagerDNSSuffix: "azuretrafficmanager.de", - KeyVaultDNSSuffix: "vault.microsoftazure.de", - ServiceBusEndpointSuffix: "servicebus.cloudapi.de", + Name: "AzureGermanCloud", + ManagementPortalURL: "http://portal.microsoftazure.de/", + PublishSettingsURL: "https://manage.microsoftazure.de/publishsettings/index", + ServiceManagementEndpoint: "https://management.core.cloudapi.de/", + ResourceManagerEndpoint: "https://management.microsoftazure.de/", + ActiveDirectoryEndpoint: "https://login.microsoftonline.de/", + GalleryEndpoint: "https://gallery.cloudapi.de/", + KeyVaultEndpoint: "https://vault.microsoftazure.de/", + GraphEndpoint: "https://graph.cloudapi.de/", + StorageEndpointSuffix: "core.cloudapi.de", + SQLDatabaseDNSSuffix: "database.cloudapi.de", + TrafficManagerDNSSuffix: "azuretrafficmanager.de", + KeyVaultDNSSuffix: "vault.microsoftazure.de", + ServiceBusEndpointSuffix: "servicebus.cloudapi.de", + ServiceManagementVMDNSSuffix: "azurecloudapp.de", + ResourceManagerVMDNSSuffix: "cloudapp.microsoftazure.de", + ContainerRegistryDNSSuffix: "azurecr.io", } ) @@ -121,8 +136,13 @@ func EnvironmentFromName(name string) (Environment, error) { // OAuthConfigForTenant returns an OAuthConfig with tenant specific urls func (env Environment) OAuthConfigForTenant(tenantID string) (*OAuthConfig, error) { + return OAuthConfigForTenant(env.ActiveDirectoryEndpoint, tenantID) +} + +// OAuthConfigForTenant returns an OAuthConfig with tenant specific urls for target cloud auth endpoint +func OAuthConfigForTenant(activeDirectoryEndpoint, tenantID string) (*OAuthConfig, error) { template := "%s/oauth2/%s?api-version=%s" - u, err := url.Parse(env.ActiveDirectoryEndpoint) + u, err := url.Parse(activeDirectoryEndpoint) if err != nil { return nil, err } diff --git a/vendor/github.com/Azure/go-autorest/autorest/azure/token.go b/vendor/github.com/Azure/go-autorest/autorest/azure/token.go index db9a8fa02..cfcd03011 100644 --- a/vendor/github.com/Azure/go-autorest/autorest/azure/token.go +++ b/vendor/github.com/Azure/go-autorest/autorest/azure/token.go @@ -91,7 +91,7 @@ type ServicePrincipalNoSecret struct { // SetAuthenticationValues is a method of the interface ServicePrincipalSecret // It only returns an error for the ServicePrincipalNoSecret type func (noSecret *ServicePrincipalNoSecret) SetAuthenticationValues(spt *ServicePrincipalToken, v *url.Values) error { - return fmt.Errorf("Manually created ServicePrincipalToken does not contain secret material to retrieve a new access token.") + return fmt.Errorf("Manually created ServicePrincipalToken does not contain secret material to retrieve a new access token") } // ServicePrincipalSecret is an interface that allows various secret mechanism to fill the form @@ -138,7 +138,7 @@ func (secret *ServicePrincipalCertificateSecret) SignJwt(spt *ServicePrincipalTo token := jwt.New(jwt.SigningMethodRS256) token.Header["x5t"] = thumbprint token.Claims = jwt.MapClaims{ - "aud": spt.oauthConfig.TokenEndpoint, + "aud": spt.oauthConfig.TokenEndpoint.String(), "iss": spt.clientID, "sub": spt.clientID, "jti": base64.URLEncoding.EncodeToString(jti), @@ -302,7 +302,7 @@ func (spt *ServicePrincipalToken) refreshInternal(resource string) error { var newToken Token err = autorest.Respond(resp, - autorest.WithErrorUnlessOK(), + autorest.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&newToken), autorest.ByClosing()) if err != nil { diff --git a/vendor/github.com/Azure/go-autorest/autorest/client.go b/vendor/github.com/Azure/go-autorest/autorest/client.go index b55b3d103..b5f94b5c3 100644 --- a/vendor/github.com/Azure/go-autorest/autorest/client.go +++ b/vendor/github.com/Azure/go-autorest/autorest/client.go @@ -8,6 +8,7 @@ import ( "log" "net/http" "net/http/cookiejar" + "runtime" "time" ) @@ -22,13 +23,24 @@ const ( DefaultRetryAttempts = 3 ) -var statusCodesForRetry = []int{ - http.StatusRequestTimeout, // 408 - http.StatusInternalServerError, // 500 - http.StatusBadGateway, // 502 - http.StatusServiceUnavailable, // 503 - http.StatusGatewayTimeout, // 504 -} +var ( + // defaultUserAgent builds a string containing the Go version, system archityecture and OS, + // and the go-autorest version. + defaultUserAgent = fmt.Sprintf("Go/%s (%s-%s) go-autorest/%s", + runtime.Version(), + runtime.GOARCH, + runtime.GOOS, + Version(), + ) + + statusCodesForRetry = []int{ + http.StatusRequestTimeout, // 408 + http.StatusInternalServerError, // 500 + http.StatusBadGateway, // 502 + http.StatusServiceUnavailable, // 503 + http.StatusGatewayTimeout, // 504 + } +) const ( requestFormat = `HTTP Request Begin =================================================== @@ -140,13 +152,24 @@ type Client struct { // NewClientWithUserAgent returns an instance of a Client with the UserAgent set to the passed // string. func NewClientWithUserAgent(ua string) Client { - return Client{ + c := Client{ PollingDelay: DefaultPollingDelay, PollingDuration: DefaultPollingDuration, RetryAttempts: DefaultRetryAttempts, RetryDuration: 30 * time.Second, - UserAgent: ua, + UserAgent: defaultUserAgent, } + c.AddToUserAgent(ua) + return c +} + +// AddToUserAgent adds an extension to the current user agent +func (c *Client) AddToUserAgent(extension string) error { + if extension != "" { + c.UserAgent = fmt.Sprintf("%s %s", c.UserAgent, extension) + return nil + } + return fmt.Errorf("Extension was empty, User Agent stayed as %s", c.UserAgent) } // Do implements the Sender interface by invoking the active Sender after applying authorization. diff --git a/vendor/github.com/Azure/go-autorest/autorest/error.go b/vendor/github.com/Azure/go-autorest/autorest/error.go index 2e4fc79c1..4bcb8f27b 100644 --- a/vendor/github.com/Azure/go-autorest/autorest/error.go +++ b/vendor/github.com/Azure/go-autorest/autorest/error.go @@ -28,6 +28,9 @@ type DetailedError struct { // Message is the error message. Message string + + // Service Error is the response body of failed API in bytes + ServiceError []byte } // NewError creates a new Error conforming object from the passed packageType, method, and diff --git a/vendor/github.com/Azure/go-autorest/autorest/preparer.go b/vendor/github.com/Azure/go-autorest/autorest/preparer.go index 5b2c52704..c9deb261a 100644 --- a/vendor/github.com/Azure/go-autorest/autorest/preparer.go +++ b/vendor/github.com/Azure/go-autorest/autorest/preparer.go @@ -183,6 +183,16 @@ func WithBaseURL(baseURL string) PrepareDecorator { } } +// WithCustomBaseURL returns a PrepareDecorator that replaces brace-enclosed keys within the +// request base URL (i.e., http.Request.URL) with the corresponding values from the passed map. +func WithCustomBaseURL(baseURL string, urlParameters map[string]interface{}) PrepareDecorator { + parameters := ensureValueStrings(urlParameters) + for key, value := range parameters { + baseURL = strings.Replace(baseURL, "{"+key+"}", value, -1) + } + return WithBaseURL(baseURL) +} + // WithFormData returns a PrepareDecoratore that "URL encodes" (e.g., bar=baz&foo=quux) into the // http.Request body. func WithFormData(v url.Values) PrepareDecorator { diff --git a/vendor/github.com/Azure/go-autorest/autorest/responder.go b/vendor/github.com/Azure/go-autorest/autorest/responder.go index e377ad48a..87f71e585 100644 --- a/vendor/github.com/Azure/go-autorest/autorest/responder.go +++ b/vendor/github.com/Azure/go-autorest/autorest/responder.go @@ -5,6 +5,7 @@ import ( "encoding/json" "encoding/xml" "fmt" + "io" "io/ioutil" "net/http" "strings" @@ -87,6 +88,24 @@ func ByCopying(b *bytes.Buffer) RespondDecorator { } } +// ByDiscardingBody returns a RespondDecorator that first invokes the passed Responder after which +// it copies the remaining bytes (if any) in the response body to ioutil.Discard. Since the passed +// Responder is invoked prior to discarding the response body, the decorator may occur anywhere +// within the set. +func ByDiscardingBody() RespondDecorator { + return func(r Responder) Responder { + return ResponderFunc(func(resp *http.Response) error { + err := r.Respond(resp) + if err == nil && resp != nil && resp.Body != nil { + if _, err := io.Copy(ioutil.Discard, resp.Body); err != nil { + return fmt.Errorf("Error discarding the response body: %v", err) + } + } + return err + }) + } +} + // ByClosing returns a RespondDecorator that first invokes the passed Responder after which it // closes the response body. Since the passed Responder is invoked prior to closing the response // body, the decorator may occur anywhere within the set. @@ -128,6 +147,8 @@ func ByUnmarshallingJSON(v interface{}) RespondDecorator { err := r.Respond(resp) if err == nil { b, errInner := ioutil.ReadAll(resp.Body) + // Some responses might include a BOM, remove for successful unmarshalling + b = bytes.TrimPrefix(b, []byte("\xef\xbb\xbf")) if errInner != nil { err = fmt.Errorf("Error occurred reading http.Response#Body - Error = '%v'", errInner) } else if len(strings.Trim(string(b), " ")) > 0 { @@ -165,17 +186,24 @@ func ByUnmarshallingXML(v interface{}) RespondDecorator { } // WithErrorUnlessStatusCode returns a RespondDecorator that emits an error unless the response -// StatusCode is among the set passed. Since these are artificial errors, the response body -// may still require closing. +// StatusCode is among the set passed. On error, response body is fully read into a buffer and +// presented in the returned error, as well as in the response body. func WithErrorUnlessStatusCode(codes ...int) RespondDecorator { return func(r Responder) Responder { return ResponderFunc(func(resp *http.Response) error { err := r.Respond(resp) if err == nil && !ResponseHasStatusCode(resp, codes...) { - err = NewErrorWithResponse("autorest", "WithErrorUnlessStatusCode", resp, "%v %v failed with %s", + derr := NewErrorWithResponse("autorest", "WithErrorUnlessStatusCode", resp, "%v %v failed with %s", resp.Request.Method, resp.Request.URL, resp.Status) + if resp.Body != nil { + defer resp.Body.Close() + b, _ := ioutil.ReadAll(resp.Body) + derr.ServiceError = b + resp.Body = ioutil.NopCloser(bytes.NewReader(b)) + } + err = derr } return err }) diff --git a/vendor/github.com/Azure/go-autorest/autorest/sender.go b/vendor/github.com/Azure/go-autorest/autorest/sender.go index 93e6489e9..9c0697815 100644 --- a/vendor/github.com/Azure/go-autorest/autorest/sender.go +++ b/vendor/github.com/Azure/go-autorest/autorest/sender.go @@ -73,7 +73,7 @@ func SendWithSender(s Sender, r *http.Request, decorators ...SendDecorator) (*ht func AfterDelay(d time.Duration) SendDecorator { return func(s Sender) Sender { return SenderFunc(func(r *http.Request) (*http.Response, error) { - if !DelayForBackoff(d, 1, r.Cancel) { + if !DelayForBackoff(d, 0, r.Cancel) { return nil, fmt.Errorf("autorest: AfterDelay canceled before full delay") } return s.Do(r) @@ -97,7 +97,7 @@ func DoCloseIfError() SendDecorator { return SenderFunc(func(r *http.Request) (*http.Response, error) { resp, err := s.Do(r) if err != nil { - Respond(resp, ByClosing()) + Respond(resp, ByDiscardingBody(), ByClosing()) } return resp, err }) @@ -156,6 +156,7 @@ func DoPollForStatusCodes(duration time.Duration, delay time.Duration, codes ... for err == nil && ResponseHasStatusCode(resp, codes...) { Respond(resp, + ByDiscardingBody(), ByClosing()) resp, err = SendWithSender(s, r, AfterDelay(GetRetryAfter(resp, delay))) @@ -257,6 +258,8 @@ func WithLogging(logger *log.Logger) SendDecorator { // passed attempt (i.e., an exponential backoff delay). Backoff duration is in seconds and can set // to zero for no delay. The delay may be canceled by closing the passed channel. If terminated early, // returns false. +// Note: Passing attempt 1 will result in doubling "backoff" duration. Treat this as a zero-based attempt +// count. func DelayForBackoff(backoff time.Duration, attempt int, cancel <-chan struct{}) bool { select { case <-time.After(time.Duration(backoff.Seconds()*math.Pow(2, float64(attempt))) * time.Second): diff --git a/vendor/github.com/Azure/go-autorest/autorest/version.go b/vendor/github.com/Azure/go-autorest/autorest/version.go index 8031a332c..e325f4ce2 100644 --- a/vendor/github.com/Azure/go-autorest/autorest/version.go +++ b/vendor/github.com/Azure/go-autorest/autorest/version.go @@ -2,17 +2,28 @@ package autorest import ( "fmt" + "strings" + "sync" ) const ( - major = "7" - minor = "0" - patch = "0" - tag = "" - semVerFormat = "%s.%s.%s%s" + major = 7 + minor = 3 + patch = 1 + tag = "" ) +var versionLock sync.Once +var version string + // Version returns the semantic version (see http://semver.org). func Version() string { - return fmt.Sprintf(semVerFormat, major, minor, patch, tag) + versionLock.Do(func() { + version = fmt.Sprintf("v%d.%d.%d", major, minor, patch) + + if trimmed := strings.TrimPrefix(tag, "-"); trimmed != "" { + version = fmt.Sprintf("%s-%s", version, trimmed) + } + }) + return version } diff --git a/vendor/github.com/DreamItGetIT/statuscake/responses.go b/vendor/github.com/DreamItGetIT/statuscake/responses.go index 88affa0be..b9216b726 100644 --- a/vendor/github.com/DreamItGetIT/statuscake/responses.go +++ b/vendor/github.com/DreamItGetIT/statuscake/responses.go @@ -43,6 +43,7 @@ type detailResponse struct { ProcessingOn string `json:"ProcessingOn"` DownTimes int `json:"DownTimes,string"` Sensitive bool `json:"Sensitive"` + TriggerRate int `json:"TriggerRate,string"` } func (d *detailResponse) test() *Test { @@ -64,5 +65,6 @@ func (d *detailResponse) test() *Test { FindString: d.FindString, DoNotFind: d.DoNotFind, Port: d.Port, + TriggerRate: d.TriggerRate, } } diff --git a/vendor/github.com/ajg/form/README.md b/vendor/github.com/ajg/form/README.md index 7117f4812..ad99be4b1 100644 --- a/vendor/github.com/ajg/form/README.md +++ b/vendor/github.com/ajg/form/README.md @@ -28,6 +28,7 @@ Usage ```go import "github.com/ajg/form" +// or: "gopkg.in/ajg/form.v1" ``` Given a type like the following... @@ -126,6 +127,10 @@ While encouraged, it is not necessary to define a type (e.g. a `struct`) in orde - Composite values will be treated as a `map[string]interface{}`, itself able to contain nested values (both scalar and compound) ad infinitum. - However, if there is a value (of any supported type) already present in a map for a given key, then it will be used when possible, rather than being replaced with a generic value as specified above; this makes it possible to handle partially typed, dynamic or schema-less values. +### Zero Values + +By default, and without custom marshaling, zero values (also known as empty/default values) are encoded as the empty string. To disable this behavior, meaning to keep zero values in their literal form (e.g. `0` for integral types), `Encoder` offers a `KeepZeros` setter method, which will do just that when set to `true`. + ### Unsupported Values Values of the following kinds aren't supported and, if present, must be ignored. diff --git a/vendor/github.com/ajg/form/TODO.md b/vendor/github.com/ajg/form/TODO.md index 672fd4657..d34472798 100644 --- a/vendor/github.com/ajg/form/TODO.md +++ b/vendor/github.com/ajg/form/TODO.md @@ -2,4 +2,3 @@ TODO ==== - Document IgnoreCase and IgnoreUnknownKeys in README. - - Fix want/have newlines in tests. diff --git a/vendor/github.com/ajg/form/decode.go b/vendor/github.com/ajg/form/decode.go index 3346fffe5..dd8bd4f29 100644 --- a/vendor/github.com/ajg/form/decode.go +++ b/vendor/github.com/ajg/form/decode.go @@ -14,13 +14,13 @@ import ( "time" ) -// NewDecoder returns a new form decoder. -func NewDecoder(r io.Reader) *decoder { - return &decoder{r, defaultDelimiter, defaultEscape, false, false} +// NewDecoder returns a new form Decoder. +func NewDecoder(r io.Reader) *Decoder { + return &Decoder{r, defaultDelimiter, defaultEscape, false, false} } -// decoder decodes data from a form (application/x-www-form-urlencoded). -type decoder struct { +// Decoder decodes data from a form (application/x-www-form-urlencoded). +type Decoder struct { r io.Reader d rune e rune @@ -28,20 +28,20 @@ type decoder struct { ignoreCase bool } -// DelimitWith sets r as the delimiter used for composite keys by decoder d and returns the latter; it is '.' by default. -func (d *decoder) DelimitWith(r rune) *decoder { +// DelimitWith sets r as the delimiter used for composite keys by Decoder d and returns the latter; it is '.' by default. +func (d *Decoder) DelimitWith(r rune) *Decoder { d.d = r return d } -// EscapeWith sets r as the escape used for delimiters (and to escape itself) by decoder d and returns the latter; it is '\\' by default. -func (d *decoder) EscapeWith(r rune) *decoder { +// EscapeWith sets r as the escape used for delimiters (and to escape itself) by Decoder d and returns the latter; it is '\\' by default. +func (d *Decoder) EscapeWith(r rune) *Decoder { d.e = r return d } // Decode reads in and decodes form-encoded data into dst. -func (d decoder) Decode(dst interface{}) error { +func (d Decoder) Decode(dst interface{}) error { bs, err := ioutil.ReadAll(d.r) if err != nil { return err @@ -54,20 +54,20 @@ func (d decoder) Decode(dst interface{}) error { return d.decodeNode(v, parseValues(d.d, d.e, vs, canIndexOrdinally(v))) } -// IgnoreUnknownKeys if set to true it will make the decoder ignore values +// IgnoreUnknownKeys if set to true it will make the Decoder ignore values // that are not found in the destination object instead of returning an error. -func (d *decoder) IgnoreUnknownKeys(ignoreUnknown bool) { +func (d *Decoder) IgnoreUnknownKeys(ignoreUnknown bool) { d.ignoreUnknown = ignoreUnknown } -// IgnoreCase if set to true it will make the decoder try to set values in the +// IgnoreCase if set to true it will make the Decoder try to set values in the // destination object even if the case does not match. -func (d *decoder) IgnoreCase(ignoreCase bool) { +func (d *Decoder) IgnoreCase(ignoreCase bool) { d.ignoreCase = ignoreCase } // DecodeString decodes src into dst. -func (d decoder) DecodeString(dst interface{}, src string) error { +func (d Decoder) DecodeString(dst interface{}, src string) error { vs, err := url.ParseQuery(src) if err != nil { return err @@ -77,7 +77,7 @@ func (d decoder) DecodeString(dst interface{}, src string) error { } // DecodeValues decodes vs into dst. -func (d decoder) DecodeValues(dst interface{}, vs url.Values) error { +func (d Decoder) DecodeValues(dst interface{}, vs url.Values) error { v := reflect.ValueOf(dst) return d.decodeNode(v, parseValues(d.d, d.e, vs, canIndexOrdinally(v))) } @@ -92,7 +92,7 @@ func DecodeValues(dst interface{}, vs url.Values) error { return NewDecoder(nil).DecodeValues(dst, vs) } -func (d decoder) decodeNode(v reflect.Value, n node) (err error) { +func (d Decoder) decodeNode(v reflect.Value, n node) (err error) { defer func() { if e := recover(); e != nil { err = fmt.Errorf("%v", e) @@ -106,7 +106,7 @@ func (d decoder) decodeNode(v reflect.Value, n node) (err error) { return nil } -func (d decoder) decodeValue(v reflect.Value, x interface{}) { +func (d Decoder) decodeValue(v reflect.Value, x interface{}) { t := v.Type() k := v.Kind() @@ -163,7 +163,7 @@ func (d decoder) decodeValue(v reflect.Value, x interface{}) { } } -func (d decoder) decodeStruct(v reflect.Value, x interface{}) { +func (d Decoder) decodeStruct(v reflect.Value, x interface{}) { t := v.Type() for k, c := range getNode(x) { if f, ok := findField(v, k, d.ignoreCase); !ok && k == "" { @@ -180,7 +180,7 @@ func (d decoder) decodeStruct(v reflect.Value, x interface{}) { } } -func (d decoder) decodeMap(v reflect.Value, x interface{}) { +func (d Decoder) decodeMap(v reflect.Value, x interface{}) { t := v.Type() if v.IsNil() { v.Set(reflect.MakeMap(t)) @@ -216,7 +216,7 @@ func (d decoder) decodeMap(v reflect.Value, x interface{}) { } } -func (d decoder) decodeArray(v reflect.Value, x interface{}) { +func (d Decoder) decodeArray(v reflect.Value, x interface{}) { t := v.Type() for k, c := range getNode(x) { i, err := strconv.Atoi(k) @@ -230,7 +230,7 @@ func (d decoder) decodeArray(v reflect.Value, x interface{}) { } } -func (d decoder) decodeSlice(v reflect.Value, x interface{}) { +func (d Decoder) decodeSlice(v reflect.Value, x interface{}) { t := v.Type() if t.Elem().Kind() == reflect.Uint8 { // Allow, but don't require, byte slices to be encoded as a single string. @@ -265,7 +265,7 @@ func (d decoder) decodeSlice(v reflect.Value, x interface{}) { } } -func (d decoder) decodeBasic(v reflect.Value, x interface{}) { +func (d Decoder) decodeBasic(v reflect.Value, x interface{}) { t := v.Type() switch k, s := t.Kind(), getString(x); k { case reflect.Bool: @@ -316,7 +316,7 @@ func (d decoder) decodeBasic(v reflect.Value, x interface{}) { } } -func (d decoder) decodeTime(v reflect.Value, x interface{}) { +func (d Decoder) decodeTime(v reflect.Value, x interface{}) { t := v.Type() s := getString(x) // TODO: Find a more efficient way to do this. @@ -329,7 +329,7 @@ func (d decoder) decodeTime(v reflect.Value, x interface{}) { panic("cannot decode string `" + s + "` as " + t.String()) } -func (d decoder) decodeURL(v reflect.Value, x interface{}) { +func (d Decoder) decodeURL(v reflect.Value, x interface{}) { t := v.Type() s := getString(x) if u, err := url.Parse(s); err == nil { diff --git a/vendor/github.com/ajg/form/encode.go b/vendor/github.com/ajg/form/encode.go index 3e824c6c6..57a0d0a57 100644 --- a/vendor/github.com/ajg/form/encode.go +++ b/vendor/github.com/ajg/form/encode.go @@ -16,34 +16,41 @@ import ( "time" ) -// NewEncoder returns a new form encoder. -func NewEncoder(w io.Writer) *encoder { - return &encoder{w, defaultDelimiter, defaultEscape} +// NewEncoder returns a new form Encoder. +func NewEncoder(w io.Writer) *Encoder { + return &Encoder{w, defaultDelimiter, defaultEscape, false} } -// encoder provides a way to encode to a Writer. -type encoder struct { +// Encoder provides a way to encode to a Writer. +type Encoder struct { w io.Writer d rune e rune + z bool } -// DelimitWith sets r as the delimiter used for composite keys by encoder e and returns the latter; it is '.' by default. -func (e *encoder) DelimitWith(r rune) *encoder { +// DelimitWith sets r as the delimiter used for composite keys by Encoder e and returns the latter; it is '.' by default. +func (e *Encoder) DelimitWith(r rune) *Encoder { e.d = r return e } -// EscapeWith sets r as the escape used for delimiters (and to escape itself) by encoder e and returns the latter; it is '\\' by default. -func (e *encoder) EscapeWith(r rune) *encoder { +// EscapeWith sets r as the escape used for delimiters (and to escape itself) by Encoder e and returns the latter; it is '\\' by default. +func (e *Encoder) EscapeWith(r rune) *Encoder { e.e = r return e } -// Encode encodes dst as form and writes it out using the encoder's Writer. -func (e encoder) Encode(dst interface{}) error { +// KeepZeros sets whether Encoder e should keep zero (default) values in their literal form when encoding, and returns the former; by default zero values are not kept, but are rather encoded as the empty string. +func (e *Encoder) KeepZeros(z bool) *Encoder { + e.z = z + return e +} + +// Encode encodes dst as form and writes it out using the Encoder's Writer. +func (e Encoder) Encode(dst interface{}) error { v := reflect.ValueOf(dst) - n, err := encodeToNode(v) + n, err := encodeToNode(v, e.z) if err != nil { return err } @@ -61,7 +68,7 @@ func (e encoder) Encode(dst interface{}) error { // EncodeToString encodes dst as a form and returns it as a string. func EncodeToString(dst interface{}) (string, error) { v := reflect.ValueOf(dst) - n, err := encodeToNode(v) + n, err := encodeToNode(v, false) if err != nil { return "", err } @@ -72,7 +79,7 @@ func EncodeToString(dst interface{}) (string, error) { // EncodeToValues encodes dst as a form and returns it as Values. func EncodeToValues(dst interface{}) (url.Values, error) { v := reflect.ValueOf(dst) - n, err := encodeToNode(v) + n, err := encodeToNode(v, false) if err != nil { return nil, err } @@ -80,41 +87,41 @@ func EncodeToValues(dst interface{}) (url.Values, error) { return vs, nil } -func encodeToNode(v reflect.Value) (n node, err error) { +func encodeToNode(v reflect.Value, z bool) (n node, err error) { defer func() { if e := recover(); e != nil { err = fmt.Errorf("%v", e) } }() - return getNode(encodeValue(v)), nil + return getNode(encodeValue(v, z)), nil } -func encodeValue(v reflect.Value) interface{} { +func encodeValue(v reflect.Value, z bool) interface{} { t := v.Type() k := v.Kind() if s, ok := marshalValue(v); ok { return s - } else if isEmptyValue(v) { + } else if !z && isEmptyValue(v) { return "" // Treat the zero value as the empty string. } switch k { case reflect.Ptr, reflect.Interface: - return encodeValue(v.Elem()) + return encodeValue(v.Elem(), z) case reflect.Struct: if t.ConvertibleTo(timeType) { return encodeTime(v) } else if t.ConvertibleTo(urlType) { return encodeURL(v) } - return encodeStruct(v) + return encodeStruct(v, z) case reflect.Slice: - return encodeSlice(v) + return encodeSlice(v, z) case reflect.Array: - return encodeArray(v) + return encodeArray(v, z) case reflect.Map: - return encodeMap(v) + return encodeMap(v, z) case reflect.Invalid, reflect.Uintptr, reflect.UnsafePointer, reflect.Chan, reflect.Func: panic(t.String() + " has unsupported kind " + t.Kind().String()) default: @@ -122,7 +129,7 @@ func encodeValue(v reflect.Value) interface{} { } } -func encodeStruct(v reflect.Value) interface{} { +func encodeStruct(v reflect.Value, z bool) interface{} { t := v.Type() n := node{} for i := 0; i < t.NumField(); i++ { @@ -134,37 +141,37 @@ func encodeStruct(v reflect.Value) interface{} { } else if fv := v.Field(i); oe && isEmptyValue(fv) { delete(n, k) } else { - n[k] = encodeValue(fv) + n[k] = encodeValue(fv, z) } } return n } -func encodeMap(v reflect.Value) interface{} { +func encodeMap(v reflect.Value, z bool) interface{} { n := node{} for _, i := range v.MapKeys() { - k := getString(encodeValue(i)) - n[k] = encodeValue(v.MapIndex(i)) + k := getString(encodeValue(i, z)) + n[k] = encodeValue(v.MapIndex(i), z) } return n } -func encodeArray(v reflect.Value) interface{} { +func encodeArray(v reflect.Value, z bool) interface{} { n := node{} for i := 0; i < v.Len(); i++ { - n[strconv.Itoa(i)] = encodeValue(v.Index(i)) + n[strconv.Itoa(i)] = encodeValue(v.Index(i), z) } return n } -func encodeSlice(v reflect.Value) interface{} { +func encodeSlice(v reflect.Value, z bool) interface{} { t := v.Type() if t.Elem().Kind() == reflect.Uint8 { return string(v.Bytes()) // Encode byte slices as a single string by default. } n := node{} for i := 0; i < v.Len(); i++ { - n[strconv.Itoa(i)] = encodeValue(v.Index(i)) + n[strconv.Itoa(i)] = encodeValue(v.Index(i), z) } return n } diff --git a/vendor/github.com/apparentlymart/go-cidr/cidr/cidr.go b/vendor/github.com/apparentlymart/go-cidr/cidr/cidr.go index 1583d6382..a31cdec77 100644 --- a/vendor/github.com/apparentlymart/go-cidr/cidr/cidr.go +++ b/vendor/github.com/apparentlymart/go-cidr/cidr/cidr.go @@ -61,7 +61,14 @@ func Host(base *net.IPNet, num int) (net.IP, error) { hostLen := addrLen - parentLen maxHostNum := uint64(1< maxHostNum { + + numUint64 := uint64(num) + if num < 0 { + numUint64 = uint64(-num) - 1 + num = int(maxHostNum - numUint64) + } + + if numUint64 > maxHostNum { return nil, fmt.Errorf("prefix of %d does not accommodate a host numbered %d", parentLen, num) } diff --git a/vendor/github.com/aws/aws-sdk-go/CHANGELOG.md b/vendor/github.com/aws/aws-sdk-go/CHANGELOG.md index ebacd5ba4..1925193fd 100644 --- a/vendor/github.com/aws/aws-sdk-go/CHANGELOG.md +++ b/vendor/github.com/aws/aws-sdk-go/CHANGELOG.md @@ -1,3 +1,306 @@ +Release v1.8.21 (2017-05-09) +=== + +### Service Client Updates +* `service/codestar`: Updates service documentation + * Updated documentation for AWS CodeStar. +* `service/workspaces`: Updates service API, documentation, and paginators + * Doc-only Update for WorkSpaces + +Release v1.8.20 (2017-05-04) +=== + +### Service Client Updates +* `service/ecs`: Updates service API, documentation, and paginators + * Exposes container instance registration time in ECS:DescribeContainerInstances. +* `aws/endpoints`: Updated Regions and Endpoints metadata. +* `service/marketplaceentitlementservice`: Adds new service +* `service/lambda`: Updates service API and documentation + * Support for UpdateFunctionCode DryRun option + +Release v1.8.19 (2017-04-28) +=== + +### Service Client Updates +* `service/cloudformation`: Updates service waiters and paginators + * Adding back the removed waiters and paginators. + +Release v1.8.18 (2017-04-28) +=== + +### Service Client Updates +* `service/cloudformation`: Updates service API, documentation, waiters, paginators, and examples + * API update for CloudFormation: New optional parameter ClientRequestToken which can be used as an idempotency token to safely retry certain operations as well as tagging StackEvents. +* `service/rds`: Updates service API, documentation, and examples + * The DescribeDBClusterSnapshots API now returns a SourceDBClusterSnapshotArn field which identifies the source DB cluster snapshot of a copied snapshot. +* `service/rekognition`: Updates service API + * Fix for missing file type check +* `service/snowball`: Updates service API, documentation, and paginators + * The Snowball API has a new exception that can be thrown for list operation requests. +* `service/sqs`: Updates service API, documentation, and paginators + * Adding server-side encryption (SSE) support to SQS by integrating with AWS KMS; adding new queue attributes to SQS CreateQueue, SetQueueAttributes and GetQueueAttributes APIs to support SSE. + +Release v1.8.17 (2017-04-26) +=== + +### Service Client Updates +* `aws/endpoints`: Updated Regions and Endpoints metadata. +* `service/rds`: Updates service API and documentation + * With Amazon Relational Database Service (Amazon RDS) running MySQL or Amazon Aurora, you can now authenticate to your DB instance using IAM database authentication. + +Release v1.8.16 (2017-04-21) +=== + +### Service Client Updates +* `service/appstream`: Updates service API, documentation, and paginators + * The new feature named "Default Internet Access" will enable Internet access from AppStream 2.0 instances - image builders and fleet instances. Admins will check a flag either through AWS management console for AppStream 2.0 or through API while creating an image builder or while creating/updating a fleet. +* `service/kinesis`: Updates service API, documentation, waiters, and paginators + * Adds a new waiter, StreamNotExists, to Kinesis. + +### SDK Enhancements +* `aws/endpoints`: Add utilities improving endpoints lookup (#1218) + * Adds several utilities to the endpoints packages to make looking up partitions, regions, and services easier. + * Fixes #994 + +### SDK Bugs +* `private/protocol/xml/xmlutil`: Fix unmarshaling dropping errors (#1219) + * The XML unmarshaler would drop any serialization or body read error that occurred on the floor effectively hiding any errors that would occur. + * Fixes #1205 +Release v1.8.15 (2017-04-20) +=== + +### Service Client Updates +* `service/devicefarm`: Updates service API and documentation + * API Update for AWS Device Farm: Support for Deals and Promotions +* `service/directconnect`: Updates service documentation + * Documentation updates for AWS Direct Connect. +* `service/elbv2`: Updates service waiters +* `service/kms`: Updates service documentation and examples + * Doc-only update for Key Management Service (KMS): Update docs for GrantConstraints and GenerateRandom +* `service/route53`: Updates service documentation + * Release notes: SDK documentation now includes examples for ChangeResourceRecordSets for all types of resource record set, such as weighted, alias, and failover. +* `service/route53domains`: Updates service API, documentation, and paginators + * Adding examples and other documentation updates. + +### SDK Enhancements +* `service/s3`: Add utilities to make getting a bucket's region easier (#1207) + * Adds two features which make it easier to get a bucket's region, `s3.NormalizeBucketLocation` and `s3manager.GetBucketRegion`. + +### SDK Bugs +* `service/s3`: Fix HeadObject's incorrect documented error codes (#1213) + * The HeadObject's model incorrectly states that the operation can return the NoSuchKey error code. + * Fixes #1208 + +Release v1.8.14 (2017-04-19) +=== + +### Service Client Updates +* `service/apigateway`: Updates service API and documentation + * Add support for "embed" property. +* `service/codestar`: Adds new service + * AWS CodeStar is a cloud-based service for creating, managing, and working with software development projects on AWS. An AWS CodeStar project creates and integrates AWS services for your project development toolchain. AWS CodeStar also manages the permissions required for project users. +* `service/ec2`: Updates service API and documentation + * Adds support for creating an Amazon FPGA Image (AFI) from a specified design checkpoint (DCP). +* `service/iam`: Updates service API and documentation + * This changes introduces a new IAM role type, Service Linked Role, which works like a normal role but must be managed via services' control. +* `service/lambda`: Updates service API and documentation + * Lambda integration with CloudDebugger service to enable customers to enable tracing for the Lambda functions and send trace information to the CloudDebugger service. +* `service/lexmodelbuildingservice`: Adds new service +* `service/polly`: Updates service API, documentation, and paginators + * API Update for Amazon Polly: Add support for speech marks +* `service/rekognition`: Updates service API and documentation + * Given an image, the API detects explicit or suggestive adult content in the image and returns a list of corresponding labels with confidence scores, as well as a taxonomy (parent-child relation) for each label. + +Release v1.8.13 (2017-04-18) +=== + +### Service Client Updates +* `service/lambda`: Updates service API and documentation + * You can use tags to group and filter your Lambda functions, making it easier to analyze them for billing allocation purposes. For more information, see Tagging Lambda Functions. You can now write or upgrade your Lambda functions using Python version 3.6. For more information, see Programming Model for Authoring Lambda Functions in Python. Note: Features will be rolled out in the US regions on 4/19. + +### SDK Enhancements +* `aws/request`: add support for appengine's custom standard library (#1190) + * Remove syscall error checking on appengine platforms. + +Release v1.8.12 (2017-04-11) +=== + +### Service Client Updates +* `service/apigateway`: Updates service API and documentation + * API Gateway request validators +* `service/batch`: Updates service API and documentation + * API Update for AWS Batch: Customer provided AMI for MANAGED Compute Environment +* `service/gamelift`: Updates service API and documentation + * Allows developers to utilize an improved workflow when calling our Queues API and introduces a new feature that allows developers to specify a maximum allowable latency per Queue. +* `service/opsworks`: Updates service API, documentation, and paginators + * Cloudwatch Logs agent configuration can now be attached to OpsWorks Layers using CreateLayer and UpdateLayer. OpsWorks will then automatically install and manage the CloudWatch Logs agent on the instances part of the OpsWorks Layer. + +### SDK Bugs +* `aws/client`: Fix clients polluting handler list (#1197) + * Fixes the clients potentially polluting the passed in handler list with the client's customizations. This change ensures every client always works with a clean copy of the request handlers and it cannot pollute the handlers back upstream. + * Fixes #1184 +* `aws/request`: Fix waiter error match condition (#1195) + * Fixes the waiters's matching overwriting the request's err, effectively ignoring the error condition. This broke waiters with the FailureWaiterState matcher state. +Release v1.8.11 (2017-04-07) +=== + +### Service Client Updates +* `service/redshift`: Updates service API, documentation, and paginators + * This update adds the GetClusterCredentials API which is used to get temporary login credentials to the cluster. AccountWithRestoreAccess now has a new member AccountAlias, this is the identifier of the AWS support account authorized to restore the specified snapshot. This is added to support the feature where the customer can share their snapshot with the Amazon Redshift Support Account without having to manually specify the AWS Redshift Service account ID on the AWS Console/API. + +Release v1.8.10 (2017-04-06) +=== + +### Service Client Updates +* `service/elbv2`: Updates service documentation + +Release v1.8.9 (2017-04-05) +=== + +### Service Client Updates +* `service/elasticache`: Updates service API, documentation, paginators, and examples + * ElastiCache added support for testing the Elasticache Multi-AZ feature with Automatic Failover. + +Release v1.8.8 (2017-04-04) +=== + +### Service Client Updates +* `service/cloudwatch`: Updates service API, documentation, and paginators + * Amazon Web Services announced the immediate availability of two additional alarm configuration rules for Amazon CloudWatch Alarms. The first rule is for configuring missing data treatment. Customers have the options to treat missing data as alarm threshold breached, alarm threshold not breached, maintain alarm state and the current default treatment. The second rule is for alarms based on percentiles metrics that can trigger unnecassarily if the percentile is calculated from a small number of samples. The new rule can treat percentiles with low sample counts as same as missing data. If the first rule is enabled, the same treatment will be applied when an alarm encounters a percentile with low sample counts. + +Release v1.8.7 (2017-04-03) +=== + +### Service Client Updates +* `service/lexruntimeservice`: Updates service API and documentation + * Adds support to PostContent for speech input + +### SDK Enhancements +* `aws/request`: Improve handler copy, push back, push front performance (#1171) + * Minor optimization to the handler list's handling of copying and pushing request handlers to the handler list. +* Update codegen header to use Go std wording (#1172) + * Go recently accepted the proposal for standard generated file header wording in, https://golang.org/s/generatedcode. + +### SDK Bugs +* `service/dynamodb`: Fix DynamoDB using custom retryer (#1170) + * Fixes (#1139) the DynamoDB service client clobbering any custom retryer that was passed into the service client or Session's config. +Release v1.8.6 (2017-04-01) +=== + +### Service Client Updates +* `service/clouddirectory`: Updates service API and documentation + * ListObjectAttributes now supports filtering by facet. +* `aws/endpoints`: Updated Regions and Endpoints metadata. + +Release v1.8.5 (2017-03-30) +=== + +### Service Client Updates +* `service/cloudformation`: Updates service waiters and paginators + * Adding paginators for ListExports and ListImports +* `service/cloudfront`: Adds new service + * Amazon CloudFront now supports user configurable HTTP Read and Keep-Alive Idle Timeouts for your Custom Origin Servers +* `service/configservice`: Updates service documentation +* `aws/endpoints`: Updated Regions and Endpoints metadata. +* `service/resourcegroupstaggingapi`: Adds new service +* `service/storagegateway`: Updates service API and documentation + * File gateway mode in AWS Storage gateway provides access to objects in S3 as files on a Network File System (NFS) mount point. Once a file share is created, any changes made externally to the S3 bucket will not be reflected by the gateway. Using the cache refresh feature in this update, the customer can trigger an on-demand scan of the keys in their S3 bucket and refresh the file namespace cached on the gateway. It takes as an input the fileShare ARN and refreshes the cache for only that file share. Additionally there is new functionality on file gateway that allows you configure what squash options they would like on their file share, this allows a customer to configure their gateway to not squash root permissions. This can be done by setting options in NfsOptions for CreateNfsFileShare and UpdateNfsFileShare APIs. + +Release v1.8.4 (2017-03-28) +=== + +### Service Client Updates +* `service/batch`: Updates service API, documentation, and paginators + * Customers can now provide a retryStrategy as part of the RegisterJobDefinition and SubmitJob API calls. The retryStrategy object has a number value for attempts. This is the number of non successful executions before a job is considered FAILED. In addition, the JobDetail object now has an attempts field and shows all execution attempts. +* `service/ec2`: Updates service API and documentation + * Customers can now tag their Amazon EC2 Instances and Amazon EBS Volumes at + the time of their creation. You can do this from the EC2 Instance launch + wizard or through the RunInstances or CreateVolume APIs. By tagging + resources at the time of creation, you can eliminate the need to run custom + tagging scripts after resource creation. In addition, you can now set + resource-level permissions on the CreateVolume, CreateTags, DeleteTags, and + the RunInstances APIs. This allows you to implement stronger security + policies by giving you more granular control over which users and groups + have access to these APIs. You can also enforce the use of tagging and + control what tag keys and values are set on your resources. When you combine + tag usage and resource-level IAM policies together, you can ensure your + instances and volumes are properly secured upon creation and achieve more + accurate cost allocation reporting. These new features are provided at no + additional cost. + +### SDK Enhancements +* `aws/request`: Add retry support for RequestTimeoutException (#1158) + * Adds support for retrying RequestTimeoutException error code that is returned by some services. + +### SDK Bugs +* `private/model/api`: Fix Waiter and Paginators panic on nil param inputs (#1157) + * Corrects the code generation for Paginators and waiters that caused a panic if nil input parameters were used with the operations. +Release v1.8.3 (2017-03-27) +=== + +## Service Client Updates +* `service/ssm`: Updates service API, documentation, and paginators + * Updated validation rules for SendCommand and RegisterTaskWithMaintenanceWindow APIs. +Release v1.8.2 (2017-03-24) +=== + +Service Client Updates +--- +* `service/applicationautoscaling`: Updates service API, documentation, and paginators + * Application AutoScaling is launching support for a new target resource (AppStream 2.0 Fleets) as a scalable target. +* `service/cloudtrail`: Updates service API and documentation + * Doc-only Update for CloudTrail: Add required parameters for GetEventSelectors and PutEventSelectors + +Release v1.8.1 (2017-03-23) +=== + +Service Client Updates +--- +* `service/applicationdiscoveryservice`: Updates service API, documentation, and paginators + * Adds export configuration options to the AWS Discovery Service API. +* `service/elbv2`: Updates waiters +* `aws/endpoints`: Updated Regions and Endpoints metadata. +* `service/lambda`: Updates service API and paginators + * Adds support for new runtime Node.js v6.10 for AWS Lambda service + +Release v1.8.0 (2017-03-22) +=== + +Service Client Updates +--- +* `service/codebuild`: Updates service documentation +* `service/directconnect`: Updates service API + * Deprecated DescribeConnectionLoa, DescribeInterconnectLoa, AllocateConnectionOnInterconnect and DescribeConnectionsOnInterconnect operations in favor of DescribeLoa, DescribeLoa, AllocateHostedConnection and DescribeHostedConnections respectively. +* `service/marketplacecommerceanalytics`: Updates service API, documentation, and paginators + * This update adds a new data set, us_sales_and_use_tax_records, which enables AWS Marketplace sellers to programmatically access to their U.S. Sales and Use Tax report data. +* `service/pinpoint`: Updates service API and documentation + * Amazon Pinpoint User Segmentation + * Added ability to segment endpoints by user attributes in addition to endpoint attributes. Amazon Pinpoint Event Stream Preview + * Added functionality to publish raw app analytics and campaign events data as events streams to Kinesis and Kinesis Firehose + * The feature provides developers with increased flexibility of exporting raw events to S3, Redshift, Elasticsearch using a Kinesis Firehose stream or enable real time event processing use cases using a Kinesis stream +* `service/rekognition`: Updates service documentation. + +SDK Features +--- +* `aws/request`: Add support for context.Context to SDK API operation requests (#1132) + * Adds support for context.Context to the SDK by adding `WithContext` methods for each API operation, Paginators and Waiters. e.g `PutObjectWithContext`. This change also adds the ability to provide request functional options to the method calls instead of requiring you to use the `Request` API operation method (e.g `PutObjectRequest`). + * Adds a `Complete` Request handler list that will be called ever time a request is completed. This includes both success and failure. Complete will only be called once per API operation request. + * `private/waiter` package moved from the private group to `aws/request/waiter` and made publicly available. + * Adds Context support to all API operations, Waiters(WaitUntil) and Paginators(Pages) methods. + * Adds Context support for s3manager and s3crypto clients. + +SDK Enhancements +--- +* `aws/signer/v4`: Adds support for unsigned payload signer config (#1130) + * Adds configuration option to the v4.Signer to specify the request's body should not be signed. This will only correclty function on services that support unsigned payload. e.g. S3, Glacier. + +SDK Bug Fixes +--- +* `service/s3`: Fix S3 HostID to be available in S3 request error message (#1131) + * Adds a new type s3.RequestFailure which exposes the S3 HostID value from a S3 API operation response. This is helpful when you have an error with S3, and need to contact support. Both RequestID and HostID are needed. +* `private/model/api`: Do not return a link if uid is empty (#1133) + * Fixes SDK's doc generation to not generate API reference doc links if the SDK us unable to create a valid link. +* `aws/request`: Optimization to handler list copy to prevent multiple alloc calls. (#1134) Release v1.7.9 (2017-03-13) === diff --git a/vendor/github.com/aws/aws-sdk-go/CHANGELOG_PENDING.md b/vendor/github.com/aws/aws-sdk-go/CHANGELOG_PENDING.md index e69de29bb..8a1927a39 100644 --- a/vendor/github.com/aws/aws-sdk-go/CHANGELOG_PENDING.md +++ b/vendor/github.com/aws/aws-sdk-go/CHANGELOG_PENDING.md @@ -0,0 +1,5 @@ +### SDK Features + +### SDK Enhancements + +### SDK Bugs diff --git a/vendor/github.com/aws/aws-sdk-go/CONTRIBUTING.md b/vendor/github.com/aws/aws-sdk-go/CONTRIBUTING.md index 81edbfaeb..7c0186f0c 100644 --- a/vendor/github.com/aws/aws-sdk-go/CONTRIBUTING.md +++ b/vendor/github.com/aws/aws-sdk-go/CONTRIBUTING.md @@ -64,6 +64,11 @@ Please be aware of the following notes prior to opening a pull request: SDK's test coverage percentage are unlikely to be merged until tests have been added. +5. The JSON files under the SDK's `models` folder are sourced from outside the SDK. + Such as `models/apis/ec2/2016-11-15/api.json`. We will not accept pull requests + directly on these models. If you discover an issue with the models please + create a Github [issue](issues) describing the issue. + ### Testing To run the tests locally, running the `make unit` command will `go get` the diff --git a/vendor/github.com/aws/aws-sdk-go/Makefile b/vendor/github.com/aws/aws-sdk-go/Makefile index fc2bc0cef..e73585b78 100644 --- a/vendor/github.com/aws/aws-sdk-go/Makefile +++ b/vendor/github.com/aws/aws-sdk-go/Makefile @@ -5,6 +5,7 @@ LINTIGNORESTUTTER='service/[^/]+/(api|service)\.go:.+(and that stutters)' LINTIGNOREINFLECT='service/[^/]+/(api|errors|service)\.go:.+(method|const) .+ should be ' LINTIGNOREINFLECTS3UPLOAD='service/s3/s3manager/upload\.go:.+struct field SSEKMSKeyId should be ' LINTIGNOREDEPS='vendor/.+\.go' +LINTIGNOREPKGCOMMENT='service/[^/]+/doc_custom.go:.+package comment should be of the form' UNIT_TEST_TAGS="example codegen" SDK_WITH_VENDOR_PKGS=$(shell go list -tags ${UNIT_TEST_TAGS} ./... | grep -v "/vendor/src") @@ -64,6 +65,9 @@ integration: get-deps-tests integ-custom smoke-tests performance integ-custom: go test -tags "integration" ./awstesting/integration/customizations/... +cleanup-integ: + go run -tags "integration" ./awstesting/cmd/bucket_cleanup/main.go "aws-sdk-go-integration" + smoke-tests: get-deps-tests gucumber -go-tags "integration" ./awstesting/integration/smoke @@ -123,7 +127,7 @@ verify: get-deps-verify lint vet lint: @echo "go lint SDK and vendor packages" @lint=`if [ \( -z "${SDK_GO_1_4}" \) -a \( -z "${SDK_GO_1_5}" \) ]; then golint ./...; else echo "skipping golint"; fi`; \ - lint=`echo "$$lint" | grep -E -v -e ${LINTIGNOREDOT} -e ${LINTIGNOREDOC} -e ${LINTIGNORECONST} -e ${LINTIGNORESTUTTER} -e ${LINTIGNOREINFLECT} -e ${LINTIGNOREDEPS} -e ${LINTIGNOREINFLECTS3UPLOAD}`; \ + lint=`echo "$$lint" | grep -E -v -e ${LINTIGNOREDOT} -e ${LINTIGNOREDOC} -e ${LINTIGNORECONST} -e ${LINTIGNORESTUTTER} -e ${LINTIGNOREINFLECT} -e ${LINTIGNOREDEPS} -e ${LINTIGNOREINFLECTS3UPLOAD} -e ${LINTIGNOREPKGCOMMENT}`; \ echo "$$lint"; \ if [ "$$lint" != "" ] && [ "$$lint" != "skipping golint" ]; then exit 1; fi diff --git a/vendor/github.com/aws/aws-sdk-go/README.md b/vendor/github.com/aws/aws-sdk-go/README.md index 8247981b7..9c8718479 100644 --- a/vendor/github.com/aws/aws-sdk-go/README.md +++ b/vendor/github.com/aws/aws-sdk-go/README.md @@ -1,11 +1,6 @@ -# AWS SDK for Go +[![API Reference](http://img.shields.io/badge/api-reference-blue.svg)](http://docs.aws.amazon.com/sdk-for-go/api) [![Join the chat at https://gitter.im/aws/aws-sdk-go](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/aws/aws-sdk-go?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) [![Build Status](https://img.shields.io/travis/aws/aws-sdk-go.svg)](https://travis-ci.org/aws/aws-sdk-go) [![Apache V2 License](http://img.shields.io/badge/license-Apache%20V2-blue.svg)](https://github.com/aws/aws-sdk-go/blob/master/LICENSE.txt) - -[![API Reference](http://img.shields.io/badge/api-reference-blue.svg)](http://docs.aws.amazon.com/sdk-for-go/api) -[![Join the chat at https://gitter.im/aws/aws-sdk-go](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/aws/aws-sdk-go?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) -[![Build Status](https://img.shields.io/travis/aws/aws-sdk-go.svg)](https://travis-ci.org/aws/aws-sdk-go) -[![Apache V2 License](http://img.shields.io/badge/license-Apache%20V2-blue.svg)](https://github.com/aws/aws-sdk-go/blob/master/LICENSE.txt) - +# AWS SDK for Go aws-sdk-go is the official AWS SDK for the Go programming language. @@ -33,6 +28,7 @@ These two processes will still include the `vendor` folder and it should be dele ## Getting Help Please use these community resources for getting help. We use the GitHub issues for tracking bugs and feature requests. + * Ask a question on [StackOverflow](http://stackoverflow.com/) and tag it with the [`aws-sdk-go`](http://stackoverflow.com/questions/tagged/aws-sdk-go) tag. * Come join the AWS SDK for Go community chat on [gitter](https://gitter.im/aws/aws-sdk-go). * Open a support ticket with [AWS Support](http://docs.aws.amazon.com/awssupport/latest/user/getting-started.html). @@ -40,9 +36,9 @@ Please use these community resources for getting help. We use the GitHub issues ## Opening Issues -If you encounter a bug with the AWS SDK for Go we would like to hear about it. Search the [existing issues]( https://github.com/aws/aws-sdk-go/issues) and see if others are also experiencing the issue before opening a new issue. Please include the version of AWS SDK for Go, Go language, and OS you’re using. Please also include repro case when appropriate. +If you encounter a bug with the AWS SDK for Go we would like to hear about it. Search the [existing issues](https://github.com/aws/aws-sdk-go/issues) and see if others are also experiencing the issue before opening a new issue. Please include the version of AWS SDK for Go, Go language, and OS you’re using. Please also include repro case when appropriate. -The GitHub issues are intended for bug reports and feature requests. For help and questions with using AWS SDK for GO please make use of the resources listed in the [Getting Help]( https://github.com/aws/aws-sdk-go#getting-help) section. Keeping the list of open issues lean will help us respond in a timely manner. +The GitHub issues are intended for bug reports and feature requests. For help and questions with using AWS SDK for GO please make use of the resources listed in the [Getting Help](https://github.com/aws/aws-sdk-go#getting-help) section. Keeping the list of open issues lean will help us respond in a timely manner. ## Reference Documentation @@ -54,80 +50,397 @@ The GitHub issues are intended for bug reports and feature requests. For help an [`SDK Examples`](https://github.com/aws/aws-sdk-go/tree/master/example) - Included in the SDK's repo are a several hand crafted examples using the SDK features and AWS services. -## Configuring Credentials +## Overview of SDK's Packages -Before using the SDK, ensure that you've configured credentials. The best -way to configure credentials on a development machine is to use the -`~/.aws/credentials` file, which might look like: +The SDK is composed of two main components, SDK core, and service clients. +The SDK core packages are all available under the aws package at the root of +the SDK. Each client for a supported AWS service is available within its own +package under the service folder at the root of the SDK. -``` -[default] -aws_access_key_id = AKID1234567890 -aws_secret_access_key = MY-SECRET-KEY -``` + * aws - SDK core, provides common shared types such as Config, Logger, + and utilities to make working with API parameters easier. -You can learn more about the credentials file from this -[blog post](http://blogs.aws.amazon.com/security/post/Tx3D6U6WSFGOK2H/A-New-and-Standardized-Way-to-Manage-Credentials-in-the-AWS-SDKs). + * awserr - Provides the error interface that the SDK will use for all + errors that occur in the SDK's processing. This includes service API + response errors as well. The Error type is made up of a code and message. + Cast the SDK's returned error type to awserr.Error and call the Code + method to compare returned error to specific error codes. See the package's + documentation for additional values that can be extracted such as RequestID. -Alternatively, you can set the following environment variables: + * credentials - Provides the types and built in credentials providers + the SDK will use to retrieve AWS credentials to make API requests with. + Nested under this folder are also additional credentials providers such as + stscreds for assuming IAM roles, and ec2rolecreds for EC2 Instance roles. -``` -AWS_ACCESS_KEY_ID=AKID1234567890 -AWS_SECRET_ACCESS_KEY=MY-SECRET-KEY -``` + * endpoints - Provides the AWS Regions and Endpoints metadata for the SDK. + Use this to lookup AWS service endpoint information such as which services + are in a region, and what regions a service is in. Constants are also provided + for all region identifiers, e.g UsWest2RegionID for "us-west-2". -### AWS shared config file (`~/.aws/config`) -The AWS SDK for Go added support the shared config file in release [v1.3.0](https://github.com/aws/aws-sdk-go/releases/tag/v1.3.0). You can opt into enabling support for the shared config by setting the environment variable `AWS_SDK_LOAD_CONFIG` to a truthy value. See the [Session](https://github.com/aws/aws-sdk-go/wiki/sessions) wiki for more information about this feature. + * session - Provides initial default configuration, and load + configuration from external sources such as environment and shared + credentials file. -## Using the Go SDK + * request - Provides the API request sending, and retry logic for the SDK. + This package also includes utilities for defining your own request + retryer, and configuring how the SDK processes the request. -To use a service in the SDK, create a service variable by calling the `New()` -function. Once you have a service client, you can call API operations which each -return response data and a possible error. + * service - Clients for AWS services. All services supported by the SDK are + available under this folder. -To list a set of instance IDs from EC2, you could run: +## How to Use the SDK's AWS Service Clients + +The SDK includes the Go types and utilities you can use to make requests to +AWS service APIs. Within the service folder at the root of the SDK you'll find +a package for each AWS service the SDK supports. All service clients follows +a common pattern of creation and usage. + +When creating a client for an AWS service you'll first need to have a Session +value constructed. The Session provides shared configuration that can be shared +between your service clients. When service clients are created you can pass +in additional configuration via the aws.Config type to override configuration +provided by in the Session to create service client instances with custom +configuration. + +Once the service's client is created you can use it to make API requests the +AWS service. These clients are safe to use concurrently. + +## Configuring the SDK + +In the AWS SDK for Go, you can configure settings for service clients, such +as the log level and maximum number of retries. Most settings are optional; +however, for each service client, you must specify a region and your credentials. +The SDK uses these values to send requests to the correct AWS region and sign +requests with the correct credentials. You can specify these values as part +of a session or as environment variables. + +See the SDK's [configuration guide][config_guide] for more information. + +See the [session][session_pkg] package documentation for more information on how to use Session +with the SDK. + +See the [Config][config_typ] type in the [aws][aws_pkg] package for more information on configuration +options. + +[config_guide]: https://docs.aws.amazon.com/sdk-for-go/v1/developer-guide/configuring-sdk.html +[session_pkg]: https://docs.aws.amazon.com/sdk-for-go/api/aws/session/ +[config_typ]: https://docs.aws.amazon.com/sdk-for-go/api/aws/#Config +[aws_pkg]: https://docs.aws.amazon.com/sdk-for-go/api/aws/ + +### Configuring Credentials + +When using the SDK you'll generally need your AWS credentials to authenticate +with AWS services. The SDK supports multiple methods of supporting these +credentials. By default the SDK will source credentials automatically from +its default credential chain. See the session package for more information +on this chain, and how to configure it. The common items in the credential +chain are the following: + + * Environment Credentials - Set of environment variables that are useful + when sub processes are created for specific roles. + + * Shared Credentials file (~/.aws/credentials) - This file stores your + credentials based on a profile name and is useful for local development. + + * EC2 Instance Role Credentials - Use EC2 Instance Role to assign credentials + to application running on an EC2 instance. This removes the need to manage + credential files in production. + +Credentials can be configured in code as well by setting the Config's Credentials +value to a custom provider or using one of the providers included with the +SDK to bypass the default credential chain and use a custom one. This is +helpful when you want to instruct the SDK to only use a specific set of +credentials or providers. + +This example creates a credential provider for assuming an IAM role, "myRoleARN" +and configures the S3 service client to use that role for API requests. ```go -package main + // Initial credentials loaded from SDK's default credential chain. Such as + // the environment, shared credentials (~/.aws/credentials), or EC2 Instance + // Role. These credentials will be used to to make the STS Assume Role API. + sess := session.Must(session.NewSession()) -import ( - "fmt" + // Create the credentials from AssumeRoleProvider to assume the role + // referenced by the "myRoleARN" ARN. + creds := stscreds.NewCredentials(sess, "myRoleArn") - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/ec2" -) - -func main() { - sess, err := session.NewSession() - if err != nil { - panic(err) - } - - // Create an EC2 service object in the "us-west-2" region - // Note that you can also configure your region globally by - // exporting the AWS_REGION environment variable - svc := ec2.New(sess, &aws.Config{Region: aws.String("us-west-2")}) - - // Call the DescribeInstances Operation - resp, err := svc.DescribeInstances(nil) - if err != nil { - panic(err) - } - - // resp has all of the response data, pull out instance IDs: - fmt.Println("> Number of reservation sets: ", len(resp.Reservations)) - for idx, res := range resp.Reservations { - fmt.Println(" > Number of instances: ", len(res.Instances)) - for _, inst := range resp.Reservations[idx].Instances { - fmt.Println(" - Instance ID: ", *inst.InstanceId) - } - } -} + // Create service client value configured for credentials + // from assumed role. + svc := s3.New(sess, &aws.Config{Credentials: creds})/ ``` -You can find more information and operations in our -[API documentation](http://docs.aws.amazon.com/sdk-for-go/api/). +See the [credentials][credentials_pkg] package documentation for more information on credential +providers included with the SDK, and how to customize the SDK's usage of +credentials. + +The SDK has support for the shared configuration file (~/.aws/config). This +support can be enabled by setting the environment variable, "AWS_SDK_LOAD_CONFIG=1", +or enabling the feature in code when creating a Session via the +Option's SharedConfigState parameter. + +```go + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) +``` + +[credentials_pkg]: ttps://docs.aws.amazon.com/sdk-for-go/api/aws/credentials + +### Configuring AWS Region + +In addition to the credentials you'll need to specify the region the SDK +will use to make AWS API requests to. In the SDK you can specify the region +either with an environment variable, or directly in code when a Session or +service client is created. The last value specified in code wins if the region +is specified multiple ways. + +To set the region via the environment variable set the "AWS_REGION" to the +region you want to the SDK to use. Using this method to set the region will +allow you to run your application in multiple regions without needing additional +code in the application to select the region. + + AWS_REGION=us-west-2 + +The endpoints package includes constants for all regions the SDK knows. The +values are all suffixed with RegionID. These values are helpful, because they +reduce the need to type the region string manually. + +To set the region on a Session use the aws package's Config struct parameter +Region to the AWS region you want the service clients created from the session to +use. This is helpful when you want to create multiple service clients, and +all of the clients make API requests to the same region. + +```go + sess := session.Must(session.NewSession(&aws.Config{ + Region: aws.String(endpoints.UsWest2RegionID), + })) +``` + +See the [endpoints][endpoints_pkg] package for the AWS Regions and Endpoints metadata. + +In addition to setting the region when creating a Session you can also set +the region on a per service client bases. This overrides the region of a +Session. This is helpful when you want to create service clients in specific +regions different from the Session's region. + +```go + svc := s3.New(sess, &aws.Config{ + Region: aws.String(endpoints.UsWest2RegionID), + }) +``` + +See the [Config][config_typ] type in the [aws][aws_pkg] package for more information and additional +options such as setting the Endpoint, and other service client configuration options. + +[endpoints_pkg]: https://docs.aws.amazon.com/sdk-for-go/api/aws/endpoints/ + +## Making API Requests + +Once the client is created you can make an API request to the service. +Each API method takes a input parameter, and returns the service response +and an error. The SDK provides methods for making the API call in multiple ways. + +In this list we'll use the S3 ListObjects API as an example for the different +ways of making API requests. + + * ListObjects - Base API operation that will make the API request to the service. + + * ListObjectsRequest - API methods suffixed with Request will construct the + API request, but not send it. This is also helpful when you want to get a + presigned URL for a request, and share the presigned URL instead of your + application making the request directly. + + * ListObjectsPages - Same as the base API operation, but uses a callback to + automatically handle pagination of the API's response. + + * ListObjectsWithContext - Same as base API operation, but adds support for + the Context pattern. This is helpful for controlling the canceling of in + flight requests. See the Go standard library context package for more + information. This method also takes request package's Option functional + options as the variadic argument for modifying how the request will be + made, or extracting information from the raw HTTP response. + + * ListObjectsPagesWithContext - same as ListObjectsPages, but adds support for + the Context pattern. Similar to ListObjectsWithContext this method also + takes the request package's Option function option types as the variadic + argument. + +In addition to the API operations the SDK also includes several higher level +methods that abstract checking for and waiting for an AWS resource to be in +a desired state. In this list we'll use WaitUntilBucketExists to demonstrate +the different forms of waiters. + + * WaitUntilBucketExists. - Method to make API request to query an AWS service for + a resource's state. Will return successfully when that state is accomplished. + + * WaitUntilBucketExistsWithContext - Same as WaitUntilBucketExists, but adds + support for the Context pattern. In addition these methods take request + package's WaiterOptions to configure the waiter, and how underlying request + will be made by the SDK. + +The API method will document which error codes the service might return for +the operation. These errors will also be available as const strings prefixed +with "ErrCode" in the service client's package. If there are no errors listed +in the API's SDK documentation you'll need to consult the AWS service's API +documentation for the errors that could be returned. + +```go + ctx := context.Background() + + result, err := svc.GetObjectWithContext(ctx, &s3.GetObjectInput{ + Bucket: aws.String("my-bucket"), + Key: aws.String("my-key"), + }) + if err != nil { + // Cast err to awserr.Error to handle specific error codes. + aerr, ok := err.(awserr.Error) + if ok && aerr.Code() == s3.ErrCodeNoSuchKey { + // Specific error code handling + } + return err + } + + // Make sure to close the body when done with it for S3 GetObject APIs or + // will leak connections. + defer result.Body.Close() + + fmt.Println("Object Size:", aws.StringValue(result.ContentLength)) +``` + +### API Request Pagination and Resource Waiters + +Pagination helper methods are suffixed with "Pages", and provide the +functionality needed to round trip API page requests. Pagination methods +take a callback function that will be called for each page of the API's response. + +```go + objects := []string{} + err := svc.ListObjectsPagesWithContext(ctx, &s3.ListObjectsInput{ + Bucket: aws.String(myBucket), + }, func(p *s3.ListObjectsOutput, lastPage bool) bool { + for _, o := range p.Contents { + objects = append(objects, aws.StringValue(o.Key)) + } + return true // continue paging + }) + if err != nil { + panic(fmt.Sprintf("failed to list objects for bucket, %s, %v", myBucket, err)) + } + + fmt.Println("Objects in bucket:", objects) +``` + +Waiter helper methods provide the functionality to wait for an AWS resource +state. These methods abstract the logic needed to to check the state of an +AWS resource, and wait until that resource is in a desired state. The waiter +will block until the resource is in the state that is desired, an error occurs, +or the waiter times out. If a resource times out the error code returned will +be request.WaiterResourceNotReadyErrorCode. + +```go + err := svc.WaitUntilBucketExistsWithContext(ctx, &s3.HeadBucketInput{ + Bucket: aws.String(myBucket), + }) + if err != nil { + aerr, ok := err.(awserr.Error) + if ok && aerr.Code() == request.WaiterResourceNotReadyErrorCode { + fmt.Fprintf(os.Stderr, "timed out while waiting for bucket to exist") + } + panic(fmt.Errorf("failed to wait for bucket to exist, %v", err)) + } + fmt.Println("Bucket", myBucket, "exists") +``` + +## Complete SDK Example + +This example shows a complete working Go file which will upload a file to S3 +and use the Context pattern to implement timeout logic that will cancel the +request if it takes too long. This example highlights how to use sessions, +create a service client, make a request, handle the error, and process the +response. + +```go + package main + + import ( + "context" + "flag" + "fmt" + "os" + "time" + + "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/aws/session" + "github.com/aws/aws-sdk-go/service/s3" + ) + + // Uploads a file to S3 given a bucket and object key. Also takes a duration + // value to terminate the update if it doesn't complete within that time. + // + // The AWS Region needs to be provided in the AWS shared config or on the + // environment variable as `AWS_REGION`. Credentials also must be provided + // Will default to shared config file, but can load from environment if provided. + // + // Usage: + // # Upload myfile.txt to myBucket/myKey. Must complete within 10 minutes or will fail + // go run withContext.go -b mybucket -k myKey -d 10m < myfile.txt + func main() { + var bucket, key string + var timeout time.Duration + + flag.StringVar(&bucket, "b", "", "Bucket name.") + flag.StringVar(&key, "k", "", "Object key name.") + flag.DurationVar(&timeout, "d", 0, "Upload timeout.") + flag.Parse() + + // All clients require a Session. The Session provides the client with + // shared configuration such as region, endpoint, and credentials. A + // Session should be shared where possible to take advantage of + // configuration and credential caching. See the session package for + // more information. + sess := session.Must(session.NewSession()) + + // Create a new instance of the service's client with a Session. + // Optional aws.Config values can also be provided as variadic arguments + // to the New function. This option allows you to provide service + // specific configuration. + svc := s3.New(sess) + + // Create a context with a timeout that will abort the upload if it takes + // more than the passed in timeout. + ctx := context.Background() + var cancelFn func() + if timeout > 0 { + ctx, cancelFn = context.WithTimeout(ctx, timeout) + } + // Ensure the context is canceled to prevent leaking. + // See context package for more information, https://golang.org/pkg/context/ + defer cancelFn() + + // Uploads the object to S3. The Context will interrupt the request if the + // timeout expires. + _, err := svc.PutObjectWithContext(ctx, &s3.PutObjectInput{ + Bucket: aws.String(bucket), + Key: aws.String(key), + Body: os.Stdin, + }) + if err != nil { + if aerr, ok := err.(awserr.Error); ok && aerr.Code() == request.CanceledErrorCode { + // If the SDK can determine the request or retry delay was canceled + // by a context the CanceledErrorCode error code will be returned. + fmt.Fprintf(os.Stderr, "upload canceled due to timeout, %v\n", err) + } else { + fmt.Fprintf(os.Stderr, "failed to upload object, %v\n", err) + } + os.Exit(1) + } + + fmt.Printf("successfully uploaded file to %s/%s\n", bucket, key) + } +``` ## License diff --git a/vendor/github.com/aws/aws-sdk-go/aws/client/client.go b/vendor/github.com/aws/aws-sdk-go/aws/client/client.go index 17fc76a0f..48b0fbd93 100644 --- a/vendor/github.com/aws/aws-sdk-go/aws/client/client.go +++ b/vendor/github.com/aws/aws-sdk-go/aws/client/client.go @@ -5,6 +5,7 @@ import ( "net/http/httputil" "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/aws/client/metadata" "github.com/aws/aws-sdk-go/aws/request" ) @@ -46,7 +47,7 @@ func New(cfg aws.Config, info metadata.ClientInfo, handlers request.Handlers, op svc := &Client{ Config: cfg, ClientInfo: info, - Handlers: handlers, + Handlers: handlers.Copy(), } switch retryer, ok := cfg.Retryer.(request.Retryer); { @@ -86,8 +87,8 @@ func (c *Client) AddDebugHandlers() { return } - c.Handlers.Send.PushFront(logRequest) - c.Handlers.Send.PushBack(logResponse) + c.Handlers.Send.PushFrontNamed(request.NamedHandler{Name: "awssdk.client.LogRequest", Fn: logRequest}) + c.Handlers.Send.PushBackNamed(request.NamedHandler{Name: "awssdk.client.LogResponse", Fn: logResponse}) } const logReqMsg = `DEBUG: Request %s/%s Details: @@ -105,6 +106,7 @@ func logRequest(r *request.Request) { dumpedBody, err := httputil.DumpRequestOut(r.HTTPRequest, logBody) if err != nil { r.Config.Logger.Log(fmt.Sprintf(logReqErrMsg, r.ClientInfo.ServiceName, r.Operation.Name, err)) + r.Error = awserr.New(request.ErrCodeRead, "an error occurred during request body reading", err) return } @@ -135,6 +137,7 @@ func logResponse(r *request.Request) { dumpedBody, err := httputil.DumpResponse(r.HTTPResponse, logBody) if err != nil { r.Config.Logger.Log(fmt.Sprintf(logRespErrMsg, r.ClientInfo.ServiceName, r.Operation.Name, err)) + r.Error = awserr.New(request.ErrCodeRead, "an error occurred during response body reading", err) return } diff --git a/vendor/github.com/aws/aws-sdk-go/aws/client/default_retryer.go b/vendor/github.com/aws/aws-sdk-go/aws/client/default_retryer.go index 43a3676b7..1313478f2 100644 --- a/vendor/github.com/aws/aws-sdk-go/aws/client/default_retryer.go +++ b/vendor/github.com/aws/aws-sdk-go/aws/client/default_retryer.go @@ -54,6 +54,12 @@ func (d DefaultRetryer) RetryRules(r *request.Request) time.Duration { // ShouldRetry returns true if the request should be retried. func (d DefaultRetryer) ShouldRetry(r *request.Request) bool { + // If one of the other handlers already set the retry state + // we don't want to override it based on the service's state + if r.Retryable != nil { + return *r.Retryable + } + if r.HTTPResponse.StatusCode >= 500 { return true } 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 f5a7c3792..d1f31f1c6 100644 --- a/vendor/github.com/aws/aws-sdk-go/aws/config.go +++ b/vendor/github.com/aws/aws-sdk-go/aws/config.go @@ -53,6 +53,13 @@ type Config struct { // to use based on region. EndpointResolver endpoints.Resolver + // EnforceShouldRetryCheck is used in the AfterRetryHandler to always call + // ShouldRetry regardless of whether or not if request.Retryable is set. + // This will utilize ShouldRetry method of custom retryers. If EnforceShouldRetryCheck + // is not set, then ShouldRetry will only be called if request.Retryable is nil. + // Proper handling of the request.Retryable field is important when setting this field. + EnforceShouldRetryCheck *bool + // The region to send requests to. This parameter is required and must // be configured globally or on a per-client basis unless otherwise // noted. A full list of regions is found in the "Regions and Endpoints" @@ -187,6 +194,10 @@ type Config struct { // request delays. This value should only be used for testing. To adjust // the delay of a request see the aws/client.DefaultRetryer and // aws/request.Retryer. + // + // SleepDelay will prevent any Context from being used for canceling retry + // delay of an API operation. It is recommended to not use SleepDelay at all + // and specify a Retryer instead. SleepDelay func(time.Duration) // DisableRestProtocolURICleaning will not clean the URL path when making rest protocol requests. @@ -439,6 +450,10 @@ func mergeInConfig(dst *Config, other *Config) { if other.DisableRestProtocolURICleaning != nil { dst.DisableRestProtocolURICleaning = other.DisableRestProtocolURICleaning } + + if other.EnforceShouldRetryCheck != nil { + dst.EnforceShouldRetryCheck = other.EnforceShouldRetryCheck + } } // Copy will return a shallow copy of the Config object. If any additional diff --git a/vendor/github.com/aws/aws-sdk-go/aws/context.go b/vendor/github.com/aws/aws-sdk-go/aws/context.go new file mode 100644 index 000000000..79f426853 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/aws/context.go @@ -0,0 +1,71 @@ +package aws + +import ( + "time" +) + +// Context is an copy of the Go v1.7 stdlib's context.Context interface. +// It is represented as a SDK interface to enable you to use the "WithContext" +// API methods with Go v1.6 and a Context type such as golang.org/x/net/context. +// +// See https://golang.org/pkg/context on how to use contexts. +type Context interface { + // Deadline returns the time when work done on behalf of this context + // should be canceled. Deadline returns ok==false when no deadline is + // set. Successive calls to Deadline return the same results. + Deadline() (deadline time.Time, ok bool) + + // Done returns a channel that's closed when work done on behalf of this + // context should be canceled. Done may return nil if this context can + // never be canceled. Successive calls to Done return the same value. + Done() <-chan struct{} + + // Err returns a non-nil error value after Done is closed. Err returns + // Canceled if the context was canceled or DeadlineExceeded if the + // context's deadline passed. No other values for Err are defined. + // After Done is closed, successive calls to Err return the same value. + Err() error + + // Value returns the value associated with this context for key, or nil + // if no value is associated with key. Successive calls to Value with + // the same key returns the same result. + // + // Use context values only for request-scoped data that transits + // processes and API boundaries, not for passing optional parameters to + // functions. + Value(key interface{}) interface{} +} + +// BackgroundContext returns a context that will never be canceled, has no +// values, and no deadline. This context is used by the SDK to provide +// backwards compatibility with non-context API operations and functionality. +// +// Go 1.6 and before: +// This context function is equivalent to context.Background in the Go stdlib. +// +// Go 1.7 and later: +// The context returned will be the value returned by context.Background() +// +// See https://golang.org/pkg/context for more information on Contexts. +func BackgroundContext() Context { + return backgroundCtx +} + +// SleepWithContext will wait for the timer duration to expire, or the context +// is canceled. Which ever happens first. If the context is canceled the Context's +// error will be returned. +// +// Expects Context to always return a non-nil error if the Done channel is closed. +func SleepWithContext(ctx Context, dur time.Duration) error { + t := time.NewTimer(dur) + defer t.Stop() + + select { + case <-t.C: + break + case <-ctx.Done(): + return ctx.Err() + } + + return nil +} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/context_1_6.go b/vendor/github.com/aws/aws-sdk-go/aws/context_1_6.go new file mode 100644 index 000000000..e8cf93d26 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/aws/context_1_6.go @@ -0,0 +1,41 @@ +// +build !go1.7 + +package aws + +import "time" + +// An emptyCtx is a copy of the the Go 1.7 context.emptyCtx type. This +// is copied to provide a 1.6 and 1.5 safe version of context that is compatible +// with Go 1.7's Context. +// +// An emptyCtx is never canceled, has no values, and has no deadline. It is not +// struct{}, since vars of this type must have distinct addresses. +type emptyCtx int + +func (*emptyCtx) Deadline() (deadline time.Time, ok bool) { + return +} + +func (*emptyCtx) Done() <-chan struct{} { + return nil +} + +func (*emptyCtx) Err() error { + return nil +} + +func (*emptyCtx) Value(key interface{}) interface{} { + return nil +} + +func (e *emptyCtx) String() string { + switch e { + case backgroundCtx: + return "aws.BackgroundContext" + } + return "unknown empty Context" +} + +var ( + backgroundCtx = new(emptyCtx) +) diff --git a/vendor/github.com/aws/aws-sdk-go/aws/context_1_7.go b/vendor/github.com/aws/aws-sdk-go/aws/context_1_7.go new file mode 100644 index 000000000..064f75c92 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/aws/context_1_7.go @@ -0,0 +1,9 @@ +// +build go1.7 + +package aws + +import "context" + +var ( + backgroundCtx = context.Background() +) diff --git a/vendor/github.com/aws/aws-sdk-go/aws/corehandlers/handlers.go b/vendor/github.com/aws/aws-sdk-go/aws/corehandlers/handlers.go index 8a7bafc78..25b461c31 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 @@ -27,7 +27,7 @@ type lener interface { // or will use the HTTPRequest.Header's "Content-Length" if defined. If unable // to determine request body length and no "Content-Length" was specified it will panic. // -// The Content-Length will only be aded to the request if the length of the body +// The Content-Length will only be added to the request if the length of the body // is greater than 0. If the body is empty or the current `Content-Length` // header is <= 0, the header will also be stripped. var BuildContentLengthHandler = request.NamedHandler{Name: "core.BuildContentLengthHandler", Fn: func(r *request.Request) { @@ -71,8 +71,8 @@ var reStatusCode = regexp.MustCompile(`^(\d{3})`) // ValidateReqSigHandler is a request handler to ensure that the request's // signature doesn't expire before it is sent. This can happen when a request -// is built and signed signficantly before it is sent. Or significant delays -// occur whne retrying requests that would cause the signature to expire. +// is built and signed significantly before it is sent. Or significant delays +// occur when retrying requests that would cause the signature to expire. var ValidateReqSigHandler = request.NamedHandler{ Name: "core.ValidateReqSigHandler", Fn: func(r *request.Request) { @@ -98,44 +98,79 @@ var ValidateReqSigHandler = request.NamedHandler{ } // SendHandler is a request handler to send service request using HTTP client. -var SendHandler = request.NamedHandler{Name: "core.SendHandler", Fn: func(r *request.Request) { - var err error - r.HTTPResponse, err = r.Config.HTTPClient.Do(r.HTTPRequest) - if err != nil { - // Prevent leaking if an HTTPResponse was returned. Clean up - // the body. - if r.HTTPResponse != nil { - r.HTTPResponse.Body.Close() +var SendHandler = request.NamedHandler{ + Name: "core.SendHandler", + Fn: func(r *request.Request) { + sender := sendFollowRedirects + if r.DisableFollowRedirects { + sender = sendWithoutFollowRedirects } - // Capture the case where url.Error is returned for error processing - // response. e.g. 301 without location header comes back as string - // error and r.HTTPResponse is nil. Other url redirect errors will - // comeback in a similar method. - if e, ok := err.(*url.Error); ok && e.Err != nil { - if s := reStatusCode.FindStringSubmatch(e.Err.Error()); s != nil { - code, _ := strconv.ParseInt(s[1], 10, 64) - r.HTTPResponse = &http.Response{ - StatusCode: int(code), - Status: http.StatusText(int(code)), - Body: ioutil.NopCloser(bytes.NewReader([]byte{})), - } - return - } + + var err error + r.HTTPResponse, err = sender(r) + if err != nil { + handleSendError(r, err) } - if r.HTTPResponse == nil { - // Add a dummy request response object to ensure the HTTPResponse - // value is consistent. + }, +} + +func sendFollowRedirects(r *request.Request) (*http.Response, error) { + return r.Config.HTTPClient.Do(r.HTTPRequest) +} + +func sendWithoutFollowRedirects(r *request.Request) (*http.Response, error) { + transport := r.Config.HTTPClient.Transport + if transport == nil { + transport = http.DefaultTransport + } + + return transport.RoundTrip(r.HTTPRequest) +} + +func handleSendError(r *request.Request, err error) { + // Prevent leaking if an HTTPResponse was returned. Clean up + // the body. + if r.HTTPResponse != nil { + r.HTTPResponse.Body.Close() + } + // Capture the case where url.Error is returned for error processing + // response. e.g. 301 without location header comes back as string + // error and r.HTTPResponse is nil. Other URL redirect errors will + // comeback in a similar method. + if e, ok := err.(*url.Error); ok && e.Err != nil { + if s := reStatusCode.FindStringSubmatch(e.Err.Error()); s != nil { + code, _ := strconv.ParseInt(s[1], 10, 64) r.HTTPResponse = &http.Response{ - StatusCode: int(0), - Status: http.StatusText(int(0)), + StatusCode: int(code), + Status: http.StatusText(int(code)), Body: ioutil.NopCloser(bytes.NewReader([]byte{})), } + return } - // Catch all other request errors. - r.Error = awserr.New("RequestError", "send request failed", err) - r.Retryable = aws.Bool(true) // network errors are retryable } -}} + if r.HTTPResponse == nil { + // Add a dummy request response object to ensure the HTTPResponse + // value is consistent. + r.HTTPResponse = &http.Response{ + StatusCode: int(0), + Status: http.StatusText(int(0)), + Body: ioutil.NopCloser(bytes.NewReader([]byte{})), + } + } + // Catch all other request errors. + r.Error = awserr.New("RequestError", "send request failed", err) + r.Retryable = aws.Bool(true) // network errors are retryable + + // Override the error with a context canceled error, if that was canceled. + ctx := r.Context() + select { + case <-ctx.Done(): + r.Error = awserr.New(request.CanceledErrorCode, + "request context canceled", ctx.Err()) + r.Retryable = aws.Bool(false) + default: + } +} // ValidateResponseHandler is a request handler to validate service response. var ValidateResponseHandler = request.NamedHandler{Name: "core.ValidateResponseHandler", Fn: func(r *request.Request) { @@ -150,13 +185,22 @@ var ValidateResponseHandler = request.NamedHandler{Name: "core.ValidateResponseH var AfterRetryHandler = request.NamedHandler{Name: "core.AfterRetryHandler", Fn: func(r *request.Request) { // If one of the other handlers already set the retry state // we don't want to override it based on the service's state - if r.Retryable == nil { + if r.Retryable == nil || aws.BoolValue(r.Config.EnforceShouldRetryCheck) { r.Retryable = aws.Bool(r.ShouldRetry(r)) } if r.WillRetry() { r.RetryDelay = r.RetryRules(r) - r.Config.SleepDelay(r.RetryDelay) + + if sleepFn := r.Config.SleepDelay; sleepFn != nil { + // Support SleepDelay for backwards compatibility and testing + sleepFn(r.RetryDelay) + } else if err := aws.SleepWithContext(r.Context(), r.RetryDelay); err != nil { + r.Error = awserr.New(request.CanceledErrorCode, + "request context canceled", err) + r.Retryable = aws.Bool(false) + return + } // when the expired token exception occurs the credentials // need to be expired locally so that the next request to diff --git a/vendor/github.com/aws/aws-sdk-go/aws/credentials/chain_provider.go b/vendor/github.com/aws/aws-sdk-go/aws/credentials/chain_provider.go index 6efc77bf0..f298d6596 100644 --- a/vendor/github.com/aws/aws-sdk-go/aws/credentials/chain_provider.go +++ b/vendor/github.com/aws/aws-sdk-go/aws/credentials/chain_provider.go @@ -13,7 +13,7 @@ var ( // // @readonly ErrNoValidProvidersFoundInChain = awserr.New("NoCredentialProviders", - `no valid providers in chain. Deprecated. + `no valid providers in chain. Deprecated. For verbose messaging see aws.Config.CredentialsChainVerboseErrors`, nil) ) @@ -39,16 +39,18 @@ var ( // does not return any credentials ChainProvider will return the error // ErrNoValidProvidersFoundInChain // -// creds := NewChainCredentials( -// []Provider{ -// &EnvProvider{}, -// &EC2RoleProvider{ +// creds := credentials.NewChainCredentials( +// []credentials.Provider{ +// &credentials.EnvProvider{}, +// &ec2rolecreds.EC2RoleProvider{ // Client: ec2metadata.New(sess), // }, // }) // // // Usage of ChainCredentials with aws.Config -// svc := ec2.New(&aws.Config{Credentials: creds}) +// svc := ec2.New(session.Must(session.NewSession(&aws.Config{ +// Credentials: creds, +// }))) // type ChainProvider struct { Providers []Provider diff --git a/vendor/github.com/aws/aws-sdk-go/aws/credentials/credentials.go b/vendor/github.com/aws/aws-sdk-go/aws/credentials/credentials.go index 7b8ebf5f9..42416fc2f 100644 --- a/vendor/github.com/aws/aws-sdk-go/aws/credentials/credentials.go +++ b/vendor/github.com/aws/aws-sdk-go/aws/credentials/credentials.go @@ -14,7 +14,7 @@ // // Example of using the environment variable credentials. // -// creds := NewEnvCredentials() +// creds := credentials.NewEnvCredentials() // // // Retrieve the credentials value // credValue, err := creds.Get() @@ -26,7 +26,7 @@ // This may be helpful to proactively expire credentials and refresh them sooner // than they would naturally expire on their own. // -// creds := NewCredentials(&EC2RoleProvider{}) +// creds := credentials.NewCredentials(&ec2rolecreds.EC2RoleProvider{}) // creds.Expire() // credsValue, err := creds.Get() // // New credentials will be retrieved instead of from cache. @@ -43,7 +43,7 @@ // func (m *MyProvider) Retrieve() (Value, error) {...} // func (m *MyProvider) IsExpired() bool {...} // -// creds := NewCredentials(&MyProvider{}) +// creds := credentials.NewCredentials(&MyProvider{}) // credValue, err := creds.Get() // package credentials @@ -60,7 +60,9 @@ import ( // when making service API calls. For example, when accessing public // s3 buckets. // -// svc := s3.New(&aws.Config{Credentials: AnonymousCredentials}) +// svc := s3.New(session.Must(session.NewSession(&aws.Config{ +// Credentials: credentials.AnonymousCredentials, +// }))) // // Access public S3 buckets. // // @readonly @@ -88,7 +90,7 @@ type Value struct { // The Provider should not need to implement its own mutexes, because // that will be managed by Credentials. type Provider interface { - // Refresh returns nil if it successfully retrieved the value. + // Retrieve returns nil if it successfully retrieved the value. // Error is returned if the value were not obtainable, or empty. Retrieve() (Value, error) @@ -97,6 +99,27 @@ type Provider interface { IsExpired() bool } +// An ErrorProvider is a stub credentials provider that always returns an error +// this is used by the SDK when construction a known provider is not possible +// due to an error. +type ErrorProvider struct { + // The error to be returned from Retrieve + Err error + + // The provider name to set on the Retrieved returned Value + ProviderName string +} + +// Retrieve will always return the error that the ErrorProvider was created with. +func (p ErrorProvider) Retrieve() (Value, error) { + return Value{ProviderName: p.ProviderName}, p.Err +} + +// IsExpired will always return not expired. +func (p ErrorProvider) IsExpired() bool { + return false +} + // A Expiry provides shared expiration logic to be used by credentials // providers to implement expiry functionality. // diff --git a/vendor/github.com/aws/aws-sdk-go/aws/credentials/env_provider.go b/vendor/github.com/aws/aws-sdk-go/aws/credentials/env_provider.go index 96655bc46..c14231a16 100644 --- a/vendor/github.com/aws/aws-sdk-go/aws/credentials/env_provider.go +++ b/vendor/github.com/aws/aws-sdk-go/aws/credentials/env_provider.go @@ -29,6 +29,7 @@ var ( // Environment variables used: // // * Access Key ID: AWS_ACCESS_KEY_ID or AWS_ACCESS_KEY +// // * Secret Access Key: AWS_SECRET_ACCESS_KEY or AWS_SECRET_KEY type EnvProvider struct { retrieved bool 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 b84062332..4108e433e 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 @@ -12,7 +12,7 @@ between multiple Credentials, Sessions or service clients. Assume Role To assume an IAM role using STS with the SDK you can create a new Credentials -with the SDKs's stscreds package. +with the SDKs's stscreds package. // Initial credentials loaded from SDK's default credential chain. Such as // the environment, shared credentials (~/.aws/credentials), or EC2 Instance diff --git a/vendor/github.com/aws/aws-sdk-go/aws/defaults/defaults.go b/vendor/github.com/aws/aws-sdk-go/aws/defaults/defaults.go index 0ef55040a..07afe3b8e 100644 --- a/vendor/github.com/aws/aws-sdk-go/aws/defaults/defaults.go +++ b/vendor/github.com/aws/aws-sdk-go/aws/defaults/defaults.go @@ -10,10 +10,12 @@ package defaults import ( "fmt" "net/http" + "net/url" "os" "time" "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/aws/corehandlers" "github.com/aws/aws-sdk-go/aws/credentials" "github.com/aws/aws-sdk-go/aws/credentials/ec2rolecreds" @@ -56,7 +58,6 @@ func Config() *aws.Config { WithMaxRetries(aws.UseServiceDefaultRetries). WithLogger(aws.NewDefaultLogger()). WithLogLevel(aws.LogOff). - WithSleepDelay(time.Sleep). WithEndpointResolver(endpoints.DefaultResolver()) } @@ -97,23 +98,51 @@ func CredChain(cfg *aws.Config, handlers request.Handlers) *credentials.Credenti }) } -// RemoteCredProvider returns a credenitials provider for the default remote +const ( + httpProviderEnvVar = "AWS_CONTAINER_CREDENTIALS_FULL_URI" + ecsCredsProviderEnvVar = "AWS_CONTAINER_CREDENTIALS_RELATIVE_URI" +) + +// RemoteCredProvider returns a credentials provider for the default remote // endpoints such as EC2 or ECS Roles. func RemoteCredProvider(cfg aws.Config, handlers request.Handlers) credentials.Provider { - ecsCredURI := os.Getenv("AWS_CONTAINER_CREDENTIALS_RELATIVE_URI") + if u := os.Getenv(httpProviderEnvVar); len(u) > 0 { + return localHTTPCredProvider(cfg, handlers, u) + } - if len(ecsCredURI) > 0 { - return ecsCredProvider(cfg, handlers, ecsCredURI) + if uri := os.Getenv(ecsCredsProviderEnvVar); len(uri) > 0 { + u := fmt.Sprintf("http://169.254.170.2%s", uri) + return httpCredProvider(cfg, handlers, u) } return ec2RoleProvider(cfg, handlers) } -func ecsCredProvider(cfg aws.Config, handlers request.Handlers, uri string) credentials.Provider { - const host = `169.254.170.2` +func localHTTPCredProvider(cfg aws.Config, handlers request.Handlers, u string) credentials.Provider { + var errMsg string - return endpointcreds.NewProviderClient(cfg, handlers, - fmt.Sprintf("http://%s%s", host, uri), + parsed, err := url.Parse(u) + if err != nil { + errMsg = fmt.Sprintf("invalid URL, %v", err) + } else if host := aws.URLHostname(parsed); !(host == "localhost" || host == "127.0.0.1") { + errMsg = fmt.Sprintf("invalid host address, %q, only localhost and 127.0.0.1 are valid.", host) + } + + if len(errMsg) > 0 { + if cfg.Logger != nil { + cfg.Logger.Log("Ignoring, HTTP credential provider", errMsg, err) + } + return credentials.ErrorProvider{ + Err: awserr.New("CredentialsEndpointError", errMsg, err), + ProviderName: endpointcreds.ProviderName, + } + } + + return httpCredProvider(cfg, handlers, u) +} + +func httpCredProvider(cfg aws.Config, handlers request.Handlers, u string) credentials.Provider { + return endpointcreds.NewProviderClient(cfg, handlers, u, func(p *endpointcreds.Provider) { p.ExpiryWindow = 5 * time.Minute }, diff --git a/vendor/github.com/aws/aws-sdk-go/aws/doc.go b/vendor/github.com/aws/aws-sdk-go/aws/doc.go new file mode 100644 index 000000000..4fcb61618 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/aws/doc.go @@ -0,0 +1,56 @@ +// Package aws provides the core SDK's utilities and shared types. Use this package's +// utilities to simplify setting and reading API operations parameters. +// +// Value and Pointer Conversion Utilities +// +// This package includes a helper conversion utility for each scalar type the SDK's +// API use. These utilities make getting a pointer of the scalar, and dereferencing +// a pointer easier. +// +// Each conversion utility comes in two forms. Value to Pointer and Pointer to Value. +// The Pointer to value will safely dereference the pointer and return its value. +// If the pointer was nil, the scalar's zero value will be returned. +// +// The value to pointer functions will be named after the scalar type. So get a +// *string from a string value use the "String" function. This makes it easy to +// to get pointer of a literal string value, because getting the address of a +// literal requires assigning the value to a variable first. +// +// var strPtr *string +// +// // Without the SDK's conversion functions +// str := "my string" +// strPtr = &str +// +// // With the SDK's conversion functions +// strPtr = aws.String("my string") +// +// // Convert *string to string value +// str = aws.StringValue(strPtr) +// +// In addition to scalars the aws package also includes conversion utilities for +// map and slice for commonly types used in API parameters. The map and slice +// conversion functions use similar naming pattern as the scalar conversion +// functions. +// +// var strPtrs []*string +// var strs []string = []string{"Go", "Gophers", "Go"} +// +// // Convert []string to []*string +// strPtrs = aws.StringSlice(strs) +// +// // Convert []*string to []string +// strs = aws.StringValueSlice(strPtrs) +// +// SDK Default HTTP Client +// +// The SDK will use the http.DefaultClient if a HTTP client is not provided to +// the SDK's Session, or service client constructor. This means that if the +// http.DefaultClient is modified by other components of your application the +// modifications will be picked up by the SDK as well. +// +// In some cases this might be intended, but it is a better practice to create +// a custom HTTP Client to share explicitly through your application. You can +// configure the SDK to use the custom HTTP Client by setting the HTTPClient +// value of the SDK's Config type when creating a Session or service client. +package aws 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 5f0f6dd37..e6d7ede6d 100644 --- a/vendor/github.com/aws/aws-sdk-go/aws/endpoints/defaults.go +++ b/vendor/github.com/aws/aws-sdk-go/aws/endpoints/defaults.go @@ -1,4 +1,4 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by aws/endpoints/v3model_codegen.go. DO NOT EDIT. package endpoints @@ -60,6 +60,7 @@ const ( CodecommitServiceID = "codecommit" // Codecommit. CodedeployServiceID = "codedeploy" // Codedeploy. CodepipelineServiceID = "codepipeline" // Codepipeline. + CodestarServiceID = "codestar" // Codestar. CognitoIdentityServiceID = "cognito-identity" // CognitoIdentity. CognitoIdpServiceID = "cognito-idp" // CognitoIdp. CognitoSyncServiceID = "cognito-sync" // CognitoSync. @@ -83,6 +84,7 @@ const ( ElasticmapreduceServiceID = "elasticmapreduce" // Elasticmapreduce. ElastictranscoderServiceID = "elastictranscoder" // Elastictranscoder. EmailServiceID = "email" // Email. + EntitlementMarketplaceServiceID = "entitlement.marketplace" // EntitlementMarketplace. EsServiceID = "es" // Es. EventsServiceID = "events" // Events. FirehoseServiceID = "firehose" // Firehose. @@ -103,6 +105,7 @@ const ( MarketplacecommerceanalyticsServiceID = "marketplacecommerceanalytics" // Marketplacecommerceanalytics. MeteringMarketplaceServiceID = "metering.marketplace" // MeteringMarketplace. MobileanalyticsServiceID = "mobileanalytics" // Mobileanalytics. + ModelsLexServiceID = "models.lex" // ModelsLex. MonitoringServiceID = "monitoring" // Monitoring. MturkRequesterServiceID = "mturk-requester" // MturkRequester. OpsworksServiceID = "opsworks" // Opsworks. @@ -131,6 +134,7 @@ const ( StsServiceID = "sts" // Sts. SupportServiceID = "support" // Support. SwfServiceID = "swf" // Swf. + TaggingServiceID = "tagging" // Tagging. WafServiceID = "waf" // Waf. WafRegionalServiceID = "waf-regional" // WafRegional. WorkdocsServiceID = "workdocs" // Workdocs. @@ -141,17 +145,20 @@ const ( // DefaultResolver returns an Endpoint resolver that will be able // to resolve endpoints for: AWS Standard, AWS China, and AWS GovCloud (US). // -// Casting the return value of this func to a EnumPartitions will -// allow you to get a list of the partitions in the order the endpoints -// will be resolved in. +// Use DefaultPartitions() to get the list of the default partitions. +func DefaultResolver() Resolver { + return defaultPartitions +} + +// DefaultPartitions returns a list of the partitions the SDK is bundled +// with. The available partitions are: AWS Standard, AWS China, and AWS GovCloud (US). // -// resolver := endpoints.DefaultResolver() -// partitions := resolver.(endpoints.EnumPartitions).Partitions() +// partitions := endpoints.DefaultPartitions // for _, p := range partitions { // // ... inspect partitions // } -func DefaultResolver() Resolver { - return defaultPartitions +func DefaultPartitions() []Partition { + return defaultPartitions.Partitions() } var defaultPartitions = partitions{ @@ -249,6 +256,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{}, @@ -345,6 +353,7 @@ var awsPartition = partition{ "ap-southeast-1": endpoint{}, "ap-southeast-2": endpoint{}, "eu-west-1": endpoint{}, + "eu-west-2": endpoint{}, "us-east-1": endpoint{}, "us-east-2": endpoint{}, "us-west-2": endpoint{}, @@ -435,10 +444,14 @@ var awsPartition = partition{ "codebuild": service{ Endpoints: endpoints{ - "eu-west-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-2": endpoint{}, + "ap-northeast-1": endpoint{}, + "ap-southeast-1": endpoint{}, + "ap-southeast-2": endpoint{}, + "eu-central-1": endpoint{}, + "eu-west-1": endpoint{}, + "us-east-1": endpoint{}, + "us-east-2": endpoint{}, + "us-west-2": endpoint{}, }, }, "codecommit": service{ @@ -483,11 +496,21 @@ var awsPartition = partition{ "us-west-2": endpoint{}, }, }, + "codestar": service{ + + Endpoints: endpoints{ + "eu-west-1": endpoint{}, + "us-east-1": endpoint{}, + "us-east-2": endpoint{}, + "us-west-2": endpoint{}, + }, + }, "cognito-identity": service{ Endpoints: endpoints{ "ap-northeast-1": endpoint{}, "ap-northeast-2": endpoint{}, + "ap-south-1": endpoint{}, "ap-southeast-2": endpoint{}, "eu-central-1": endpoint{}, "eu-west-1": endpoint{}, @@ -502,6 +525,7 @@ var awsPartition = partition{ Endpoints: endpoints{ "ap-northeast-1": endpoint{}, "ap-northeast-2": endpoint{}, + "ap-south-1": endpoint{}, "ap-southeast-2": endpoint{}, "eu-central-1": endpoint{}, "eu-west-1": endpoint{}, @@ -516,6 +540,7 @@ var awsPartition = partition{ Endpoints: endpoints{ "ap-northeast-1": endpoint{}, "ap-northeast-2": endpoint{}, + "ap-south-1": endpoint{}, "ap-southeast-2": endpoint{}, "eu-central-1": endpoint{}, "eu-west-1": endpoint{}, @@ -755,10 +780,11 @@ var awsPartition = partition{ "elasticfilesystem": service{ Endpoints: endpoints{ - "eu-west-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-2": endpoint{}, + "ap-southeast-2": endpoint{}, + "eu-west-1": endpoint{}, + "us-east-1": endpoint{}, + "us-east-2": endpoint{}, + "us-west-2": endpoint{}, }, }, "elasticloadbalancing": service{ @@ -829,6 +855,16 @@ var awsPartition = partition{ "us-west-2": endpoint{}, }, }, + "entitlement.marketplace": service{ + Defaults: endpoint{ + CredentialScope: credentialScope{ + Service: "aws-marketplace", + }, + }, + Endpoints: endpoints{ + "us-east-1": endpoint{}, + }, + }, "es": service{ Endpoints: endpoints{ @@ -837,8 +873,10 @@ var awsPartition = partition{ "ap-south-1": endpoint{}, "ap-southeast-1": endpoint{}, "ap-southeast-2": endpoint{}, + "ca-central-1": endpoint{}, "eu-central-1": endpoint{}, "eu-west-1": endpoint{}, + "eu-west-2": endpoint{}, "sa-east-1": endpoint{}, "us-east-1": endpoint{}, "us-east-2": endpoint{}, @@ -1022,6 +1060,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{}, @@ -1100,6 +1139,16 @@ var awsPartition = partition{ "us-east-1": endpoint{}, }, }, + "models.lex": service{ + Defaults: endpoint{ + CredentialScope: credentialScope{ + Service: "lex", + }, + }, + Endpoints: endpoints{ + "us-east-1": endpoint{}, + }, + }, "monitoring": service{ Defaults: endpoint{ Protocols: []string{"http", "https"}, @@ -1380,7 +1429,6 @@ var awsPartition = partition{ Endpoints: endpoints{ "ap-south-1": endpoint{}, "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, "eu-central-1": endpoint{}, "eu-west-1": endpoint{}, "eu-west-2": endpoint{}, @@ -1467,6 +1515,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{}, "ca-central-1": endpoint{}, @@ -1567,6 +1616,25 @@ var awsPartition = partition{ "us-west-2": endpoint{}, }, }, + "tagging": service{ + + Endpoints: endpoints{ + "ap-northeast-1": endpoint{}, + "ap-northeast-2": endpoint{}, + "ap-south-1": endpoint{}, + "ap-southeast-1": endpoint{}, + "ap-southeast-2": endpoint{}, + "ca-central-1": endpoint{}, + "eu-central-1": endpoint{}, + "eu-west-1": endpoint{}, + "eu-west-2": endpoint{}, + "sa-east-1": endpoint{}, + "us-east-1": endpoint{}, + "us-east-2": endpoint{}, + "us-west-1": endpoint{}, + "us-west-2": endpoint{}, + }, + }, "waf": service{ PartitionEndpoint: "aws-global", IsRegionalized: boxedFalse, @@ -1678,6 +1746,12 @@ var awscnPartition = partition{ "cn-north-1": endpoint{}, }, }, + "codedeploy": service{ + + Endpoints: endpoints{ + "cn-north-1": endpoint{}, + }, + }, "config": service{ Endpoints: endpoints{ @@ -1855,6 +1929,12 @@ var awscnPartition = partition{ }, "swf": service{ + Endpoints: endpoints{ + "cn-north-1": endpoint{}, + }, + }, + "tagging": service{ + Endpoints: endpoints{ "cn-north-1": endpoint{}, }, diff --git a/vendor/github.com/aws/aws-sdk-go/aws/endpoints/endpoints.go b/vendor/github.com/aws/aws-sdk-go/aws/endpoints/endpoints.go index 37e19ab00..9c3eedb48 100644 --- a/vendor/github.com/aws/aws-sdk-go/aws/endpoints/endpoints.go +++ b/vendor/github.com/aws/aws-sdk-go/aws/endpoints/endpoints.go @@ -124,6 +124,49 @@ type EnumPartitions interface { Partitions() []Partition } +// RegionsForService returns a map of regions for the partition and service. +// If either the partition or service does not exist false will be returned +// as the second parameter. +// +// This example shows how to get the regions for DynamoDB in the AWS partition. +// rs, exists := endpoints.RegionsForService(endpoints.DefaultPartitions(), endpoints.AwsPartitionID, endpoints.DynamodbServiceID) +// +// This is equivalent to using the partition directly. +// rs := endpoints.AwsPartition().Services()[endpoints.DynamodbServiceID].Regions() +func RegionsForService(ps []Partition, partitionID, serviceID string) (map[string]Region, bool) { + for _, p := range ps { + if p.ID() != partitionID { + continue + } + if _, ok := p.p.Services[serviceID]; !ok { + break + } + + s := Service{ + id: serviceID, + p: p.p, + } + return s.Regions(), true + } + + return map[string]Region{}, false +} + +// PartitionForRegion returns the first partition which includes the region +// passed in. This includes both known regions and regions which match +// a pattern supported by the partition which may include regions that are +// not explicitly known by the partition. Use the Regions method of the +// returned Partition if explicit support is needed. +func PartitionForRegion(ps []Partition, regionID string) (Partition, bool) { + for _, p := range ps { + if _, ok := p.p.Regions[regionID]; ok || p.p.RegionRegex.MatchString(regionID) { + return p, true + } + } + + return Partition{}, false +} + // A Partition provides the ability to enumerate the partition's regions // and services. type Partition struct { @@ -132,7 +175,7 @@ type Partition struct { } // ID returns the identifier of the partition. -func (p *Partition) ID() string { return p.id } +func (p Partition) ID() string { return p.id } // EndpointFor attempts to resolve the endpoint based on service and region. // See Options for information on configuring how the endpoint is resolved. @@ -155,13 +198,13 @@ func (p *Partition) ID() string { return p.id } // Errors that can be returned. // * UnknownServiceError // * UnknownEndpointError -func (p *Partition) EndpointFor(service, region string, opts ...func(*Options)) (ResolvedEndpoint, error) { +func (p Partition) EndpointFor(service, region string, opts ...func(*Options)) (ResolvedEndpoint, error) { return p.p.EndpointFor(service, region, opts...) } // Regions returns a map of Regions indexed by their ID. This is useful for // enumerating over the regions in a partition. -func (p *Partition) Regions() map[string]Region { +func (p Partition) Regions() map[string]Region { rs := map[string]Region{} for id := range p.p.Regions { rs[id] = Region{ @@ -175,7 +218,7 @@ func (p *Partition) Regions() map[string]Region { // Services returns a map of Service indexed by their ID. This is useful for // enumerating over the services in a partition. -func (p *Partition) Services() map[string]Service { +func (p Partition) Services() map[string]Service { ss := map[string]Service{} for id := range p.p.Services { ss[id] = Service{ @@ -195,16 +238,16 @@ type Region struct { } // ID returns the region's identifier. -func (r *Region) ID() string { return r.id } +func (r Region) ID() string { return r.id } // ResolveEndpoint resolves an endpoint from the context of the region given // a service. See Partition.EndpointFor for usage and errors that can be returned. -func (r *Region) ResolveEndpoint(service string, opts ...func(*Options)) (ResolvedEndpoint, error) { +func (r Region) ResolveEndpoint(service string, opts ...func(*Options)) (ResolvedEndpoint, error) { return r.p.EndpointFor(service, r.id, opts...) } // Services returns a list of all services that are known to be in this region. -func (r *Region) Services() map[string]Service { +func (r Region) Services() map[string]Service { ss := map[string]Service{} for id, s := range r.p.Services { if _, ok := s.Endpoints[r.id]; ok { @@ -226,17 +269,38 @@ type Service struct { } // ID returns the identifier for the service. -func (s *Service) ID() string { return s.id } +func (s Service) ID() string { return s.id } // ResolveEndpoint resolves an endpoint from the context of a service given // a region. See Partition.EndpointFor for usage and errors that can be returned. -func (s *Service) ResolveEndpoint(region string, opts ...func(*Options)) (ResolvedEndpoint, error) { +func (s Service) ResolveEndpoint(region string, opts ...func(*Options)) (ResolvedEndpoint, error) { return s.p.EndpointFor(s.id, region, opts...) } +// Regions returns a map of Regions that the service is present in. +// +// A region is the AWS region the service exists in. Whereas a Endpoint is +// an URL that can be resolved to a instance of a service. +func (s Service) Regions() map[string]Region { + rs := map[string]Region{} + for id := range s.p.Services[s.id].Endpoints { + if _, ok := s.p.Regions[id]; ok { + rs[id] = Region{ + id: id, + p: s.p, + } + } + } + + return rs +} + // Endpoints returns a map of Endpoints indexed by their ID for all known // endpoints for a service. -func (s *Service) Endpoints() map[string]Endpoint { +// +// A region is the AWS region the service exists in. Whereas a Endpoint is +// an URL that can be resolved to a instance of a service. +func (s Service) Endpoints() map[string]Endpoint { es := map[string]Endpoint{} for id := range s.p.Services[s.id].Endpoints { es[id] = Endpoint{ @@ -259,15 +323,15 @@ type Endpoint struct { } // ID returns the identifier for an endpoint. -func (e *Endpoint) ID() string { return e.id } +func (e Endpoint) ID() string { return e.id } // ServiceID returns the identifier the endpoint belongs to. -func (e *Endpoint) ServiceID() string { return e.serviceID } +func (e Endpoint) ServiceID() string { return e.serviceID } // ResolveEndpoint resolves an endpoint from the context of a service and // region the endpoint represents. See Partition.EndpointFor for usage and // errors that can be returned. -func (e *Endpoint) ResolveEndpoint(opts ...func(*Options)) (ResolvedEndpoint, error) { +func (e Endpoint) ResolveEndpoint(opts ...func(*Options)) (ResolvedEndpoint, error) { return e.p.EndpointFor(e.serviceID, e.id, opts...) } @@ -300,28 +364,6 @@ type EndpointNotFoundError struct { Region string } -//// NewEndpointNotFoundError builds and returns NewEndpointNotFoundError. -//func NewEndpointNotFoundError(p, s, r string) EndpointNotFoundError { -// return EndpointNotFoundError{ -// awsError: awserr.New("EndpointNotFoundError", "unable to find endpoint", nil), -// Partition: p, -// Service: s, -// Region: r, -// } -//} -// -//// Error returns string representation of the error. -//func (e EndpointNotFoundError) Error() string { -// extra := fmt.Sprintf("partition: %q, service: %q, region: %q", -// e.Partition, e.Service, e.Region) -// return awserr.SprintError(e.Code(), e.Message(), extra, e.OrigErr()) -//} -// -//// String returns the string representation of the error. -//func (e EndpointNotFoundError) String() string { -// return e.Error() -//} - // A UnknownServiceError is returned when the service does not resolve to an // endpoint. Includes a list of all known services for the partition. Returned // when a partition does not support the service. diff --git a/vendor/github.com/aws/aws-sdk-go/aws/endpoints/v3model_codegen.go b/vendor/github.com/aws/aws-sdk-go/aws/endpoints/v3model_codegen.go index 1e7369dbf..05e92df22 100644 --- a/vendor/github.com/aws/aws-sdk-go/aws/endpoints/v3model_codegen.go +++ b/vendor/github.com/aws/aws-sdk-go/aws/endpoints/v3model_codegen.go @@ -158,7 +158,7 @@ var funcMap = template.FuncMap{ const v3Tmpl = ` {{ define "defaults" -}} -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by aws/endpoints/v3model_codegen.go. DO NOT EDIT. package endpoints @@ -209,17 +209,20 @@ import ( // DefaultResolver returns an Endpoint resolver that will be able // to resolve endpoints for: {{ ListPartitionNames . }}. // - // Casting the return value of this func to a EnumPartitions will - // allow you to get a list of the partitions in the order the endpoints - // will be resolved in. + // Use DefaultPartitions() to get the list of the default partitions. + func DefaultResolver() Resolver { + return defaultPartitions + } + + // DefaultPartitions returns a list of the partitions the SDK is bundled + // with. The available partitions are: {{ ListPartitionNames . }}. // - // resolver := endpoints.DefaultResolver() - // partitions := resolver.(endpoints.EnumPartitions).Partitions() + // partitions := endpoints.DefaultPartitions // for _, p := range partitions { // // ... inspect partitions // } - func DefaultResolver() Resolver { - return defaultPartitions + func DefaultPartitions() []Partition { + return defaultPartitions.Partitions() } var defaultPartitions = partitions{ diff --git a/vendor/github.com/aws/aws-sdk-go/aws/jsonvalue.go b/vendor/github.com/aws/aws-sdk-go/aws/jsonvalue.go new file mode 100644 index 000000000..91a6f277a --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/aws/jsonvalue.go @@ -0,0 +1,12 @@ +package aws + +// JSONValue is a representation of a grab bag type that will be marshaled +// into a json string. This type can be used just like any other map. +// +// Example: +// +// values := aws.JSONValue{ +// "Foo": "Bar", +// } +// values["Baz"] = "Qux" +type JSONValue map[string]interface{} 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 new file mode 100644 index 000000000..10fc8cb24 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/aws/request/connection_reset_error.go @@ -0,0 +1,19 @@ +// +build !appengine + +package request + +import ( + "net" + "os" + "syscall" +) + +func isErrConnectionReset(err error) bool { + if opErr, ok := err.(*net.OpError); ok { + if sysErr, ok := opErr.Err.(*os.SyscallError); ok { + return sysErr.Err == syscall.ECONNRESET + } + } + + return false +} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/request/handlers.go b/vendor/github.com/aws/aws-sdk-go/aws/request/handlers.go index 5279c19c0..6c14336f6 100644 --- a/vendor/github.com/aws/aws-sdk-go/aws/request/handlers.go +++ b/vendor/github.com/aws/aws-sdk-go/aws/request/handlers.go @@ -18,6 +18,7 @@ type Handlers struct { UnmarshalError HandlerList Retry HandlerList AfterRetry HandlerList + Complete HandlerList } // Copy returns of this handler's lists. @@ -33,6 +34,7 @@ func (h *Handlers) Copy() Handlers { UnmarshalMeta: h.UnmarshalMeta.copy(), Retry: h.Retry.copy(), AfterRetry: h.AfterRetry.copy(), + Complete: h.Complete.copy(), } } @@ -48,6 +50,7 @@ func (h *Handlers) Clear() { h.ValidateResponse.Clear() h.Retry.Clear() h.AfterRetry.Clear() + h.Complete.Clear() } // A HandlerListRunItem represents an entry in the HandlerList which @@ -85,13 +88,17 @@ func (l *HandlerList) copy() HandlerList { n := HandlerList{ AfterEachFn: l.AfterEachFn, } - n.list = append([]NamedHandler{}, l.list...) + if len(l.list) == 0 { + return n + } + + n.list = append(make([]NamedHandler, 0, len(l.list)), l.list...) return n } // Clear clears the handler list. func (l *HandlerList) Clear() { - l.list = []NamedHandler{} + l.list = l.list[0:0] } // Len returns the number of handlers in the list. @@ -101,33 +108,54 @@ func (l *HandlerList) Len() int { // PushBack pushes handler f to the back of the handler list. func (l *HandlerList) PushBack(f func(*Request)) { - l.list = append(l.list, NamedHandler{"__anonymous", f}) -} - -// PushFront pushes handler f to the front of the handler list. -func (l *HandlerList) PushFront(f func(*Request)) { - l.list = append([]NamedHandler{{"__anonymous", f}}, l.list...) + l.PushBackNamed(NamedHandler{"__anonymous", f}) } // PushBackNamed pushes named handler f to the back of the handler list. func (l *HandlerList) PushBackNamed(n NamedHandler) { + if cap(l.list) == 0 { + l.list = make([]NamedHandler, 0, 5) + } l.list = append(l.list, n) } +// PushFront pushes handler f to the front of the handler list. +func (l *HandlerList) PushFront(f func(*Request)) { + l.PushFrontNamed(NamedHandler{"__anonymous", f}) +} + // PushFrontNamed pushes named handler f to the front of the handler list. func (l *HandlerList) PushFrontNamed(n NamedHandler) { - l.list = append([]NamedHandler{n}, l.list...) + if cap(l.list) == len(l.list) { + // Allocating new list required + l.list = append([]NamedHandler{n}, l.list...) + } else { + // Enough room to prepend into list. + l.list = append(l.list, NamedHandler{}) + copy(l.list[1:], l.list) + l.list[0] = n + } } // Remove removes a NamedHandler n func (l *HandlerList) Remove(n NamedHandler) { - newlist := []NamedHandler{} - for _, m := range l.list { - if m.Name != n.Name { - newlist = append(newlist, m) + l.RemoveByName(n.Name) +} + +// RemoveByName removes a NamedHandler by name. +func (l *HandlerList) RemoveByName(name string) { + for i := 0; i < len(l.list); i++ { + m := l.list[i] + if m.Name == name { + // Shift array preventing creating new arrays + copy(l.list[i:], l.list[i+1:]) + l.list[len(l.list)-1] = NamedHandler{} + l.list = l.list[:len(l.list)-1] + + // decrement list so next check to length is correct + i-- } } - l.list = newlist } // Run executes all handlers in the list with a given request object. @@ -163,6 +191,16 @@ func HandlerListStopOnError(item HandlerListRunItem) bool { return item.Request.Error == nil } +// WithAppendUserAgent will add a string to the user agent prefixed with a +// single white space. +func WithAppendUserAgent(s string) Option { + return func(r *Request) { + r.Handlers.Build.PushBack(func(r2 *Request) { + AddToUserAgent(r, s) + }) + } +} + // MakeAddToUserAgentHandler will add the name/version pair to the User-Agent request // header. If the extra parameters are provided they will be added as metadata to the // name/version pair resulting in the following format. diff --git a/vendor/github.com/aws/aws-sdk-go/aws/request/request.go b/vendor/github.com/aws/aws-sdk-go/aws/request/request.go index 77312bb66..4f4f1123a 100644 --- a/vendor/github.com/aws/aws-sdk-go/aws/request/request.go +++ b/vendor/github.com/aws/aws-sdk-go/aws/request/request.go @@ -16,6 +16,24 @@ import ( "github.com/aws/aws-sdk-go/aws/client/metadata" ) +const ( + // ErrCodeSerialization is the serialization error code that is received + // during protocol unmarshaling. + ErrCodeSerialization = "SerializationError" + + // ErrCodeRead is an error that is returned during HTTP reads. + ErrCodeRead = "ReadError" + + // ErrCodeResponseTimeout is the connection timeout error that is recieved + // during body reads. + ErrCodeResponseTimeout = "ResponseTimeout" + + // CanceledErrorCode is the error code that will be returned by an + // API request that was canceled. Requests given a aws.Context may + // return this error when canceled. + CanceledErrorCode = "RequestCanceled" +) + // A Request is the service request to be made. type Request struct { Config aws.Config @@ -23,30 +41,33 @@ type Request struct { Handlers Handlers Retryer - Time time.Time - ExpireTime time.Duration - Operation *Operation - HTTPRequest *http.Request - HTTPResponse *http.Response - Body io.ReadSeeker - BodyStart int64 // offset from beginning of Body that the request body starts - Params interface{} - Error error - Data interface{} - RequestID string - RetryCount int - Retryable *bool - RetryDelay time.Duration - NotHoist bool - SignedHeaderVals http.Header - LastSignedAt time.Time + Time time.Time + ExpireTime time.Duration + Operation *Operation + HTTPRequest *http.Request + HTTPResponse *http.Response + Body io.ReadSeeker + BodyStart int64 // offset from beginning of Body that the request body starts + Params interface{} + Error error + Data interface{} + RequestID string + RetryCount int + Retryable *bool + RetryDelay time.Duration + NotHoist bool + SignedHeaderVals http.Header + LastSignedAt time.Time + DisableFollowRedirects bool + + context aws.Context built bool - // Need to persist an intermideant body betweend the input Body and HTTP + // Need to persist an intermediate body between the input Body and HTTP // request body because the HTTP Client's transport can maintain a reference // to the HTTP request's body after the client has returned. This value is - // safe to use concurrently and rewraps the input Body for each HTTP request. + // safe to use concurrently and wrap the input Body for each HTTP request. safeBody *offsetReader } @@ -60,14 +81,6 @@ type Operation struct { BeforePresignFn func(r *Request) error } -// Paginator keeps track of pagination configuration for an API operation. -type Paginator struct { - InputTokens []string - OutputTokens []string - LimitToken string - TruncationToken string -} - // New returns a new Request pointer for the service API // operation and parameters. // @@ -111,6 +124,94 @@ func New(cfg aws.Config, clientInfo metadata.ClientInfo, handlers Handlers, return r } +// A Option is a functional option that can augment or modify a request when +// using a WithContext API operation method. +type Option func(*Request) + +// WithGetResponseHeader builds a request Option which will retrieve a single +// header value from the HTTP Response. If there are multiple values for the +// header key use WithGetResponseHeaders instead to access the http.Header +// map directly. The passed in val pointer must be non-nil. +// +// This Option can be used multiple times with a single API operation. +// +// var id2, versionID string +// svc.PutObjectWithContext(ctx, params, +// request.WithGetResponseHeader("x-amz-id-2", &id2), +// request.WithGetResponseHeader("x-amz-version-id", &versionID), +// ) +func WithGetResponseHeader(key string, val *string) Option { + return func(r *Request) { + r.Handlers.Complete.PushBack(func(req *Request) { + *val = req.HTTPResponse.Header.Get(key) + }) + } +} + +// WithGetResponseHeaders builds a request Option which will retrieve the +// headers from the HTTP response and assign them to the passed in headers +// variable. The passed in headers pointer must be non-nil. +// +// var headers http.Header +// svc.PutObjectWithContext(ctx, params, request.WithGetResponseHeaders(&headers)) +func WithGetResponseHeaders(headers *http.Header) Option { + return func(r *Request) { + r.Handlers.Complete.PushBack(func(req *Request) { + *headers = req.HTTPResponse.Header + }) + } +} + +// WithLogLevel is a request option that will set the request to use a specific +// log level when the request is made. +// +// svc.PutObjectWithContext(ctx, params, request.WithLogLevel(aws.LogDebugWithHTTPBody) +func WithLogLevel(l aws.LogLevelType) Option { + return func(r *Request) { + r.Config.LogLevel = aws.LogLevel(l) + } +} + +// ApplyOptions will apply each option to the request calling them in the order +// the were provided. +func (r *Request) ApplyOptions(opts ...Option) { + for _, opt := range opts { + opt(r) + } +} + +// Context will always returns a non-nil context. If Request does not have a +// context aws.BackgroundContext will be returned. +func (r *Request) Context() aws.Context { + if r.context != nil { + return r.context + } + return aws.BackgroundContext() +} + +// SetContext adds a Context to the current request that can be used to cancel +// a in-flight request. The Context value must not be nil, or this method will +// panic. +// +// Unlike http.Request.WithContext, SetContext does not return a copy of the +// Request. It is not safe to use use a single Request value for multiple +// requests. A new Request should be created for each API operation request. +// +// Go 1.6 and below: +// The http.Request's Cancel field will be set to the Done() value of +// the context. This will overwrite the Cancel field's value. +// +// Go 1.7 and above: +// The http.Request.WithContext will be used to set the context on the underlying +// http.Request. This will create a shallow copy of the http.Request. The SDK +// may create sub contexts in the future for nested requests such as retries. +func (r *Request) SetContext(ctx aws.Context) { + if ctx == nil { + panic("context cannot be nil") + } + setRequestContext(r, ctx) +} + // WillRetry returns if the request's can be retried. func (r *Request) WillRetry() bool { return r.Error != nil && aws.BoolValue(r.Retryable) && r.RetryCount < r.MaxRetries() @@ -262,7 +363,7 @@ func (r *Request) ResetBody() { // Related golang/go#18257 l, err := computeBodyLength(r.Body) if err != nil { - r.Error = awserr.New("SerializationError", "failed to compute request body size", err) + r.Error = awserr.New(ErrCodeSerialization, "failed to compute request body size", err) return } @@ -344,6 +445,12 @@ func (r *Request) GetBody() io.ReadSeeker { // // Send will not close the request.Request's body. func (r *Request) Send() error { + defer func() { + // Regardless of success or failure of the request trigger the Complete + // request handlers. + r.Handlers.Complete.Run(r) + }() + for { if aws.BoolValue(r.Retryable) { if r.Config.LogLevel.Matches(aws.LogDebugWithRequestRetries) { @@ -446,6 +553,9 @@ func shouldRetryCancel(r *Request) bool { timeoutErr := false errStr := r.Error.Error() if ok { + if awsErr.Code() == CanceledErrorCode { + return false + } err := awsErr.OrigErr() netErr, netOK := err.(net.Error) timeoutErr = netOK && netErr.Temporary() diff --git a/vendor/github.com/aws/aws-sdk-go/aws/request/request_context.go b/vendor/github.com/aws/aws-sdk-go/aws/request/request_context.go new file mode 100644 index 000000000..a7365cd1e --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/aws/request/request_context.go @@ -0,0 +1,14 @@ +// +build go1.7 + +package request + +import "github.com/aws/aws-sdk-go/aws" + +// setContext updates the Request to use the passed in context for cancellation. +// Context will also be used for request retry delay. +// +// Creates shallow copy of the http.Request with the WithContext method. +func setRequestContext(r *Request, ctx aws.Context) { + r.context = ctx + r.HTTPRequest = r.HTTPRequest.WithContext(ctx) +} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/request/request_context_1_6.go b/vendor/github.com/aws/aws-sdk-go/aws/request/request_context_1_6.go new file mode 100644 index 000000000..307fa0705 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/aws/request/request_context_1_6.go @@ -0,0 +1,14 @@ +// +build !go1.7 + +package request + +import "github.com/aws/aws-sdk-go/aws" + +// setContext updates the Request to use the passed in context for cancellation. +// Context will also be used for request retry delay. +// +// Creates shallow copy of the http.Request with the WithContext method. +func setRequestContext(r *Request, ctx aws.Context) { + r.context = ctx + r.HTTPRequest.Cancel = ctx.Done() +} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/request/request_pagination.go b/vendor/github.com/aws/aws-sdk-go/aws/request/request_pagination.go index 2939ec473..59de6736b 100644 --- a/vendor/github.com/aws/aws-sdk-go/aws/request/request_pagination.go +++ b/vendor/github.com/aws/aws-sdk-go/aws/request/request_pagination.go @@ -2,29 +2,125 @@ package request import ( "reflect" + "sync/atomic" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awsutil" ) -//type Paginater interface { -// HasNextPage() bool -// NextPage() *Request -// EachPage(fn func(data interface{}, isLastPage bool) (shouldContinue bool)) error -//} +// A Pagination provides paginating of SDK API operations which are paginatable. +// Generally you should not use this type directly, but use the "Pages" API +// operations method to automatically perform pagination for you. Such as, +// "S3.ListObjectsPages", and "S3.ListObjectsPagesWithContext" methods. +// +// Pagination differs from a Paginator type in that pagination is the type that +// does the pagination between API operations, and Paginator defines the +// configuration that will be used per page request. +// +// cont := true +// for p.Next() && cont { +// data := p.Page().(*s3.ListObjectsOutput) +// // process the page's data +// } +// return p.Err() +// +// See service client API operation Pages methods for examples how the SDK will +// use the Pagination type. +type Pagination struct { + // Function to return a Request value for each pagination request. + // Any configuration or handlers that need to be applied to the request + // prior to getting the next page should be done here before the request + // returned. + // + // NewRequest should always be built from the same API operations. It is + // undefined if different API operations are returned on subsequent calls. + NewRequest func() (*Request, error) -// HasNextPage returns true if this request has more pages of data available. -func (r *Request) HasNextPage() bool { - return len(r.nextPageTokens()) > 0 + started bool + nextTokens []interface{} + + err error + curPage interface{} } -// nextPageTokens returns the tokens to use when asking for the next page of -// data. +// HasNextPage will return true if Pagination is able to determine that the API +// operation has additional pages. False will be returned if there are no more +// pages remaining. +// +// Will always return true if Next has not been called yet. +func (p *Pagination) HasNextPage() bool { + return !(p.started && len(p.nextTokens) == 0) +} + +// Err returns the error Pagination encountered when retrieving the next page. +func (p *Pagination) Err() error { + return p.err +} + +// Page returns the current page. Page should only be called after a successful +// call to Next. It is undefined what Page will return if Page is called after +// Next returns false. +func (p *Pagination) Page() interface{} { + return p.curPage +} + +// Next will attempt to retrieve the next page for the API operation. When a page +// is retrieved true will be returned. If the page cannot be retrieved, or there +// are no more pages false will be returned. +// +// Use the Page method to retrieve the current page data. The data will need +// to be cast to the API operation's output type. +// +// Use the Err method to determine if an error occurred if Page returns false. +func (p *Pagination) Next() bool { + if !p.HasNextPage() { + return false + } + + req, err := p.NewRequest() + if err != nil { + p.err = err + return false + } + + if p.started { + for i, intok := range req.Operation.InputTokens { + awsutil.SetValueAtPath(req.Params, intok, p.nextTokens[i]) + } + } + p.started = true + + err = req.Send() + if err != nil { + p.err = err + return false + } + + p.nextTokens = req.nextPageTokens() + p.curPage = req.Data + + return true +} + +// A Paginator is the configuration data that defines how an API operation +// should be paginated. This type is used by the API service models to define +// the generated pagination config for service APIs. +// +// The Pagination type is what provides iterating between pages of an API. It +// is only used to store the token metadata the SDK should use for performing +// pagination. +type Paginator struct { + InputTokens []string + OutputTokens []string + LimitToken string + TruncationToken string +} + +// nextPageTokens returns the tokens to use when asking for the next page of data. func (r *Request) nextPageTokens() []interface{} { if r.Operation.Paginator == nil { return nil } - if r.Operation.TruncationToken != "" { tr, _ := awsutil.ValuesAtPath(r.Data, r.Operation.TruncationToken) if len(tr) == 0 { @@ -61,9 +157,40 @@ func (r *Request) nextPageTokens() []interface{} { return tokens } +// Ensure a deprecated item is only logged once instead of each time its used. +func logDeprecatedf(logger aws.Logger, flag *int32, msg string) { + if logger == nil { + return + } + if atomic.CompareAndSwapInt32(flag, 0, 1) { + logger.Log(msg) + } +} + +var ( + logDeprecatedHasNextPage int32 + logDeprecatedNextPage int32 + logDeprecatedEachPage int32 +) + +// HasNextPage returns true if this request has more pages of data available. +// +// Deprecated Use Pagination type for configurable pagination of API operations +func (r *Request) HasNextPage() bool { + logDeprecatedf(r.Config.Logger, &logDeprecatedHasNextPage, + "Request.HasNextPage deprecated. Use Pagination type for configurable pagination of API operations") + + return len(r.nextPageTokens()) > 0 +} + // NextPage returns a new Request that can be executed to return the next // page of result data. Call .Send() on this request to execute it. +// +// Deprecated Use Pagination type for configurable pagination of API operations func (r *Request) NextPage() *Request { + logDeprecatedf(r.Config.Logger, &logDeprecatedNextPage, + "Request.NextPage deprecated. Use Pagination type for configurable pagination of API operations") + tokens := r.nextPageTokens() if len(tokens) == 0 { return nil @@ -90,7 +217,12 @@ func (r *Request) NextPage() *Request { // as the structure "T". The lastPage value represents whether the page is // the last page of data or not. The return value of this function should // return true to keep iterating or false to stop. +// +// Deprecated Use Pagination type for configurable pagination of API operations func (r *Request) EachPage(fn func(data interface{}, isLastPage bool) (shouldContinue bool)) error { + logDeprecatedf(r.Config.Logger, &logDeprecatedEachPage, + "Request.EachPage deprecated. Use Pagination type for configurable pagination of API operations") + for page := r; page != nil; page = page.NextPage() { if err := page.Send(); err != nil { return err diff --git a/vendor/github.com/aws/aws-sdk-go/aws/request/retryer.go b/vendor/github.com/aws/aws-sdk-go/aws/request/retryer.go index ebd60ccc4..7af81de2a 100644 --- a/vendor/github.com/aws/aws-sdk-go/aws/request/retryer.go +++ b/vendor/github.com/aws/aws-sdk-go/aws/request/retryer.go @@ -26,8 +26,10 @@ func WithRetryer(cfg *aws.Config, retryer Retryer) *aws.Config { // retryableCodes is a collection of service response codes which are retry-able // without any further action. var retryableCodes = map[string]struct{}{ - "RequestError": {}, - "RequestTimeout": {}, + "RequestError": {}, + "RequestTimeout": {}, + ErrCodeResponseTimeout: {}, + "RequestTimeoutException": {}, // Glacier's flavor of RequestTimeout } var throttleCodes = map[string]struct{}{ @@ -68,35 +70,85 @@ func isCodeExpiredCreds(code string) bool { return ok } +var validParentCodes = map[string]struct{}{ + ErrCodeSerialization: struct{}{}, + ErrCodeRead: struct{}{}, +} + +func isNestedErrorRetryable(parentErr awserr.Error) bool { + if parentErr == nil { + return false + } + + if _, ok := validParentCodes[parentErr.Code()]; !ok { + return false + } + + err := parentErr.OrigErr() + if err == nil { + return false + } + + if aerr, ok := err.(awserr.Error); ok { + return isCodeRetryable(aerr.Code()) + } + + return isErrConnectionReset(err) +} + // IsErrorRetryable returns whether the error is retryable, based on its Code. -// Returns false if the request has no Error set. -func (r *Request) IsErrorRetryable() bool { - if r.Error != nil { - if err, ok := r.Error.(awserr.Error); ok { - return isCodeRetryable(err.Code()) +// Returns false if error is nil. +func IsErrorRetryable(err error) bool { + if err != nil { + if aerr, ok := err.(awserr.Error); ok { + return isCodeRetryable(aerr.Code()) || isNestedErrorRetryable(aerr) } } return false } // IsErrorThrottle returns whether the error is to be throttled based on its code. -// Returns false if the request has no Error set -func (r *Request) IsErrorThrottle() bool { - if r.Error != nil { - if err, ok := r.Error.(awserr.Error); ok { - return isCodeThrottle(err.Code()) +// Returns false if error is nil. +func IsErrorThrottle(err error) bool { + if err != nil { + if aerr, ok := err.(awserr.Error); ok { + return isCodeThrottle(aerr.Code()) } } return false } -// IsErrorExpired returns whether the error code is a credential expiry error. -// Returns false if the request has no Error set. -func (r *Request) IsErrorExpired() bool { - if r.Error != nil { - if err, ok := r.Error.(awserr.Error); ok { - return isCodeExpiredCreds(err.Code()) +// IsErrorExpiredCreds returns whether the error code is a credential expiry error. +// Returns false if error is nil. +func IsErrorExpiredCreds(err error) bool { + if err != nil { + if aerr, ok := err.(awserr.Error); ok { + return isCodeExpiredCreds(aerr.Code()) } } return false } + +// IsErrorRetryable returns whether the error is retryable, based on its Code. +// Returns false if the request has no Error set. +// +// Alias for the utility function IsErrorRetryable +func (r *Request) IsErrorRetryable() bool { + return IsErrorRetryable(r.Error) +} + +// IsErrorThrottle returns whether the error is to be throttled based on its code. +// Returns false if the request has no Error set +// +// Alias for the utility function IsErrorThrottle +func (r *Request) IsErrorThrottle() bool { + return IsErrorThrottle(r.Error) +} + +// IsErrorExpired returns whether the error code is a credential expiry error. +// Returns false if the request has no Error set. +// +// Alias for the utility function IsErrorExpiredCreds +func (r *Request) IsErrorExpired() bool { + return IsErrorExpiredCreds(r.Error) +} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/request/timeout_read_closer.go b/vendor/github.com/aws/aws-sdk-go/aws/request/timeout_read_closer.go new file mode 100644 index 000000000..09a44eb98 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/aws/request/timeout_read_closer.go @@ -0,0 +1,94 @@ +package request + +import ( + "io" + "time" + + "github.com/aws/aws-sdk-go/aws/awserr" +) + +var timeoutErr = awserr.New( + ErrCodeResponseTimeout, + "read on body has reached the timeout limit", + nil, +) + +type readResult struct { + n int + err error +} + +// timeoutReadCloser will handle body reads that take too long. +// We will return a ErrReadTimeout error if a timeout occurs. +type timeoutReadCloser struct { + reader io.ReadCloser + duration time.Duration +} + +// Read will spin off a goroutine to call the reader's Read method. We will +// select on the timer's channel or the read's channel. Whoever completes first +// will be returned. +func (r *timeoutReadCloser) Read(b []byte) (int, error) { + timer := time.NewTimer(r.duration) + c := make(chan readResult, 1) + + go func() { + n, err := r.reader.Read(b) + timer.Stop() + c <- readResult{n: n, err: err} + }() + + select { + case data := <-c: + return data.n, data.err + case <-timer.C: + return 0, timeoutErr + } +} + +func (r *timeoutReadCloser) Close() error { + return r.reader.Close() +} + +const ( + // HandlerResponseTimeout is what we use to signify the name of the + // response timeout handler. + HandlerResponseTimeout = "ResponseTimeoutHandler" +) + +// adaptToResponseTimeoutError is a handler that will replace any top level error +// to a ErrCodeResponseTimeout, if its child is that. +func adaptToResponseTimeoutError(req *Request) { + if err, ok := req.Error.(awserr.Error); ok { + aerr, ok := err.OrigErr().(awserr.Error) + if ok && aerr.Code() == ErrCodeResponseTimeout { + req.Error = aerr + } + } +} + +// WithResponseReadTimeout is a request option that will wrap the body in a timeout read closer. +// This will allow for per read timeouts. If a timeout occurred, we will return the +// ErrCodeResponseTimeout. +// +// svc.PutObjectWithContext(ctx, params, request.WithTimeoutReadCloser(30 * time.Second) +func WithResponseReadTimeout(duration time.Duration) Option { + return func(r *Request) { + + var timeoutHandler = NamedHandler{ + HandlerResponseTimeout, + func(req *Request) { + req.HTTPResponse.Body = &timeoutReadCloser{ + reader: req.HTTPResponse.Body, + duration: duration, + } + }} + + // remove the handler so we are not stomping over any new durations. + r.Handlers.Send.RemoveByName(HandlerResponseTimeout) + r.Handlers.Send.PushBackNamed(timeoutHandler) + + r.Handlers.Unmarshal.PushBack(adaptToResponseTimeoutError) + r.Handlers.UnmarshalError.PushBack(adaptToResponseTimeoutError) + } +} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/request/waiter.go b/vendor/github.com/aws/aws-sdk-go/aws/request/waiter.go new file mode 100644 index 000000000..22d2f8098 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/aws/request/waiter.go @@ -0,0 +1,287 @@ +package request + +import ( + "fmt" + "time" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/awserr" + "github.com/aws/aws-sdk-go/aws/awsutil" +) + +// WaiterResourceNotReadyErrorCode is the error code returned by a waiter when +// the waiter's max attempts have been exhausted. +const WaiterResourceNotReadyErrorCode = "ResourceNotReady" + +// A WaiterOption is a function that will update the Waiter value's fields to +// configure the waiter. +type WaiterOption func(*Waiter) + +// WithWaiterMaxAttempts returns the maximum number of times the waiter should +// attempt to check the resource for the target state. +func WithWaiterMaxAttempts(max int) WaiterOption { + return func(w *Waiter) { + w.MaxAttempts = max + } +} + +// WaiterDelay will return a delay the waiter should pause between attempts to +// check the resource state. The passed in attempt is the number of times the +// Waiter has checked the resource state. +// +// Attempt is the number of attempts the Waiter has made checking the resource +// state. +type WaiterDelay func(attempt int) time.Duration + +// ConstantWaiterDelay returns a WaiterDelay that will always return a constant +// delay the waiter should use between attempts. It ignores the number of +// attempts made. +func ConstantWaiterDelay(delay time.Duration) WaiterDelay { + return func(attempt int) time.Duration { + return delay + } +} + +// WithWaiterDelay will set the Waiter to use the WaiterDelay passed in. +func WithWaiterDelay(delayer WaiterDelay) WaiterOption { + return func(w *Waiter) { + w.Delay = delayer + } +} + +// WithWaiterLogger returns a waiter option to set the logger a waiter +// should use to log warnings and errors to. +func WithWaiterLogger(logger aws.Logger) WaiterOption { + return func(w *Waiter) { + w.Logger = logger + } +} + +// WithWaiterRequestOptions returns a waiter option setting the request +// options for each request the waiter makes. Appends to waiter's request +// options already set. +func WithWaiterRequestOptions(opts ...Option) WaiterOption { + return func(w *Waiter) { + w.RequestOptions = append(w.RequestOptions, opts...) + } +} + +// A Waiter provides the functionality to perform a blocking call which will +// wait for a resource state to be satisfied by a service. +// +// This type should not be used directly. The API operations provided in the +// service packages prefixed with "WaitUntil" should be used instead. +type Waiter struct { + Name string + Acceptors []WaiterAcceptor + Logger aws.Logger + + MaxAttempts int + Delay WaiterDelay + + RequestOptions []Option + NewRequest func([]Option) (*Request, error) +} + +// ApplyOptions updates the waiter with the list of waiter options provided. +func (w *Waiter) ApplyOptions(opts ...WaiterOption) { + for _, fn := range opts { + fn(w) + } +} + +// WaiterState are states the waiter uses based on WaiterAcceptor definitions +// to identify if the resource state the waiter is waiting on has occurred. +type WaiterState int + +// String returns the string representation of the waiter state. +func (s WaiterState) String() string { + switch s { + case SuccessWaiterState: + return "success" + case FailureWaiterState: + return "failure" + case RetryWaiterState: + return "retry" + default: + return "unknown waiter state" + } +} + +// States the waiter acceptors will use to identify target resource states. +const ( + SuccessWaiterState WaiterState = iota // waiter successful + FailureWaiterState // waiter failed + RetryWaiterState // waiter needs to be retried +) + +// WaiterMatchMode is the mode that the waiter will use to match the WaiterAcceptor +// definition's Expected attribute. +type WaiterMatchMode int + +// Modes the waiter will use when inspecting API response to identify target +// resource states. +const ( + PathAllWaiterMatch WaiterMatchMode = iota // match on all paths + PathWaiterMatch // match on specific path + PathAnyWaiterMatch // match on any path + PathListWaiterMatch // match on list of paths + StatusWaiterMatch // match on status code + ErrorWaiterMatch // match on error +) + +// String returns the string representation of the waiter match mode. +func (m WaiterMatchMode) String() string { + switch m { + case PathAllWaiterMatch: + return "pathAll" + case PathWaiterMatch: + return "path" + case PathAnyWaiterMatch: + return "pathAny" + case PathListWaiterMatch: + return "pathList" + case StatusWaiterMatch: + return "status" + case ErrorWaiterMatch: + return "error" + default: + return "unknown waiter match mode" + } +} + +// WaitWithContext will make requests for the API operation using NewRequest to +// build API requests. The request's response will be compared against the +// Waiter's Acceptors to determine the successful state of the resource the +// waiter is inspecting. +// +// The passed in context must not be nil. If it is nil a panic will occur. The +// Context will be used to cancel the waiter's pending requests and retry delays. +// Use aws.BackgroundContext if no context is available. +// +// The waiter will continue until the target state defined by the Acceptors, +// or the max attempts expires. +// +// Will return the WaiterResourceNotReadyErrorCode error code if the waiter's +// retryer ShouldRetry returns false. This normally will happen when the max +// wait attempts expires. +func (w Waiter) WaitWithContext(ctx aws.Context) error { + + for attempt := 1; ; attempt++ { + req, err := w.NewRequest(w.RequestOptions) + if err != nil { + waiterLogf(w.Logger, "unable to create request %v", err) + return err + } + req.Handlers.Build.PushBack(MakeAddToUserAgentFreeFormHandler("Waiter")) + err = req.Send() + + // See if any of the acceptors match the request's response, or error + for _, a := range w.Acceptors { + if matched, matchErr := a.match(w.Name, w.Logger, req, err); matched { + return matchErr + } + } + + // The Waiter should only check the resource state MaxAttempts times + // This is here instead of in the for loop above to prevent delaying + // unnecessary when the waiter will not retry. + if attempt == w.MaxAttempts { + break + } + + // Delay to wait before inspecting the resource again + delay := w.Delay(attempt) + if sleepFn := req.Config.SleepDelay; sleepFn != nil { + // Support SleepDelay for backwards compatibility and testing + sleepFn(delay) + } else if err := aws.SleepWithContext(ctx, delay); err != nil { + return awserr.New(CanceledErrorCode, "waiter context canceled", err) + } + } + + return awserr.New(WaiterResourceNotReadyErrorCode, "exceeded wait attempts", nil) +} + +// A WaiterAcceptor provides the information needed to wait for an API operation +// to complete. +type WaiterAcceptor struct { + State WaiterState + Matcher WaiterMatchMode + Argument string + Expected interface{} +} + +// match returns if the acceptor found a match with the passed in request +// or error. True is returned if the acceptor made a match, error is returned +// if there was an error attempting to perform the match. +func (a *WaiterAcceptor) match(name string, l aws.Logger, req *Request, err error) (bool, error) { + result := false + var vals []interface{} + + switch a.Matcher { + case PathAllWaiterMatch, PathWaiterMatch: + // Require all matches to be equal for result to match + vals, _ = awsutil.ValuesAtPath(req.Data, a.Argument) + if len(vals) == 0 { + break + } + result = true + for _, val := range vals { + if !awsutil.DeepEqual(val, a.Expected) { + result = false + break + } + } + case PathAnyWaiterMatch: + // Only a single match needs to equal for the result to match + vals, _ = awsutil.ValuesAtPath(req.Data, a.Argument) + for _, val := range vals { + if awsutil.DeepEqual(val, a.Expected) { + result = true + break + } + } + case PathListWaiterMatch: + // ignored matcher + case StatusWaiterMatch: + s := a.Expected.(int) + result = s == req.HTTPResponse.StatusCode + case ErrorWaiterMatch: + if aerr, ok := err.(awserr.Error); ok { + result = aerr.Code() == a.Expected.(string) + } + default: + waiterLogf(l, "WARNING: Waiter %s encountered unexpected matcher: %s", + name, a.Matcher) + } + + if !result { + // If there was no matching result found there is nothing more to do + // for this response, retry the request. + return false, nil + } + + switch a.State { + case SuccessWaiterState: + // waiter completed + return true, nil + case FailureWaiterState: + // Waiter failure state triggered + return true, awserr.New(WaiterResourceNotReadyErrorCode, + "failed waiting for successful resource state", err) + case RetryWaiterState: + // clear the error and retry the operation + return false, nil + default: + waiterLogf(l, "WARNING: Waiter %s encountered unexpected state: %s", + name, a.State) + return false, nil + } +} + +func waiterLogf(logger aws.Logger, msg string, args ...interface{}) { + if logger != nil { + logger.Log(fmt.Sprintf(msg, args...)) + } +} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/session/doc.go b/vendor/github.com/aws/aws-sdk-go/aws/session/doc.go index 660d9bef9..ea7b886f8 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 @@ -23,7 +23,7 @@ additional config if the AWS_SDK_LOAD_CONFIG environment variable is set. Alternatively you can explicitly create a Session with shared config enabled. To do this you can use NewSessionWithOptions to configure how the Session will be created. Using the NewSessionWithOptions with SharedConfigState set to -SharedConfigEnabled will create the session as if the AWS_SDK_LOAD_CONFIG +SharedConfigEnable will create the session as if the AWS_SDK_LOAD_CONFIG environment variable was set. Creating Sessions @@ -84,7 +84,7 @@ override the shared config state (AWS_SDK_LOAD_CONFIG). // Force enable Shared Config support sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: SharedConfigEnable, + SharedConfigState: session.SharedConfigEnable, })) Adding Handlers @@ -124,9 +124,8 @@ file (~/.aws/config) and shared credentials file (~/.aws/credentials). Both files have the same format. If both config files are present the configuration from both files will be -read. The Session will be created from configuration values from the shared -credentials file (~/.aws/credentials) over those in the shared credentials -file (~/.aws/config). +read. The Session will be created from configuration values from the shared +credentials file (~/.aws/credentials) over those in the shared config file (~/.aws/config). Credentials are the values the SDK should use for authenticating requests with AWS Services. They arfrom a configuration file will need to include both 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 96c740d00..4792d3ae8 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 @@ -218,7 +218,7 @@ type Options struct { // // // Force enable Shared Config support // sess := session.Must(session.NewSessionWithOptions(session.Options{ -// SharedConfigState: SharedConfigEnable, +// SharedConfigState: session.SharedConfigEnable, // })) func NewSessionWithOptions(opts Options) (*Session, error) { var envCfg envConfig diff --git a/vendor/github.com/aws/aws-sdk-go/aws/signer/v4/options.go b/vendor/github.com/aws/aws-sdk-go/aws/signer/v4/options.go new file mode 100644 index 000000000..6aa2ed241 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/aws/signer/v4/options.go @@ -0,0 +1,7 @@ +package v4 + +// WithUnsignedPayload will enable and set the UnsignedPayload field to +// true of the signer. +func WithUnsignedPayload(v4 *Signer) { + v4.UnsignedPayload = true +} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/signer/v4/v4.go b/vendor/github.com/aws/aws-sdk-go/aws/signer/v4/v4.go index 98bfe742b..434ac872d 100644 --- a/vendor/github.com/aws/aws-sdk-go/aws/signer/v4/v4.go +++ b/vendor/github.com/aws/aws-sdk-go/aws/signer/v4/v4.go @@ -194,6 +194,10 @@ type Signer struct { // This value should only be used for testing. If it is nil the default // time.Now will be used. currentTimeFn func() time.Time + + // UnsignedPayload will prevent signing of the payload. This will only + // work for services that have support for this. + UnsignedPayload bool } // NewSigner returns a Signer pointer configured with the credentials and optional @@ -227,6 +231,7 @@ type signingCtx struct { isPresign bool formattedTime string formattedShortTime string + unsignedPayload bool bodyDigest string signedHeaders string @@ -317,6 +322,7 @@ func (v4 Signer) signWithBody(r *http.Request, body io.ReadSeeker, service, regi ServiceName: service, Region: region, DisableURIPathEscaping: v4.DisableURIPathEscaping, + unsignedPayload: v4.UnsignedPayload, } for key := range ctx.Query { @@ -409,7 +415,18 @@ var SignRequestHandler = request.NamedHandler{ func SignSDKRequest(req *request.Request) { signSDKRequestWithCurrTime(req, time.Now) } -func signSDKRequestWithCurrTime(req *request.Request, curTimeFn func() time.Time) { + +// BuildNamedHandler will build a generic handler for signing. +func BuildNamedHandler(name string, opts ...func(*Signer)) request.NamedHandler { + return request.NamedHandler{ + Name: name, + Fn: func(req *request.Request) { + signSDKRequestWithCurrTime(req, time.Now, opts...) + }, + } +} + +func signSDKRequestWithCurrTime(req *request.Request, curTimeFn func() time.Time, opts ...func(*Signer)) { // If the request does not need to be signed ignore the signing of the // request if the AnonymousCredentials object is used. if req.Config.Credentials == credentials.AnonymousCredentials { @@ -441,6 +458,10 @@ func signSDKRequestWithCurrTime(req *request.Request, curTimeFn func() time.Time v4.DisableRequestBodyOverwrite = true }) + for _, opt := range opts { + opt(v4) + } + signingTime := req.Time if !req.LastSignedAt.IsZero() { signingTime = req.LastSignedAt @@ -634,14 +655,14 @@ func (ctx *signingCtx) buildSignature() { func (ctx *signingCtx) buildBodyDigest() { hash := ctx.Request.Header.Get("X-Amz-Content-Sha256") if hash == "" { - if ctx.isPresign && ctx.ServiceName == "s3" { + if ctx.unsignedPayload || (ctx.isPresign && ctx.ServiceName == "s3") { hash = "UNSIGNED-PAYLOAD" } else if ctx.Body == nil { hash = emptyStringSHA256 } else { hash = hex.EncodeToString(makeSha256Reader(ctx.Body)) } - if ctx.ServiceName == "s3" || ctx.ServiceName == "glacier" { + if ctx.unsignedPayload || ctx.ServiceName == "s3" || ctx.ServiceName == "glacier" { ctx.Request.Header.Set("X-Amz-Content-Sha256", hash) } } diff --git a/vendor/github.com/aws/aws-sdk-go/aws/url.go b/vendor/github.com/aws/aws-sdk-go/aws/url.go new file mode 100644 index 000000000..6192b2455 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/aws/url.go @@ -0,0 +1,12 @@ +// +build go1.8 + +package aws + +import "net/url" + +// URLHostname will extract the Hostname without port from the URL value. +// +// Wrapper of net/url#URL.Hostname for backwards Go version compatibility. +func URLHostname(url *url.URL) string { + return url.Hostname() +} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/url_1_7.go b/vendor/github.com/aws/aws-sdk-go/aws/url_1_7.go new file mode 100644 index 000000000..0210d2720 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/aws/url_1_7.go @@ -0,0 +1,29 @@ +// +build !go1.8 + +package aws + +import ( + "net/url" + "strings" +) + +// URLHostname will extract the Hostname without port from the URL value. +// +// Copy of Go 1.8's net/url#URL.Hostname functionality. +func URLHostname(url *url.URL) string { + return stripPort(url.Host) + +} + +// stripPort is copy of Go 1.8 url#URL.Hostname functionality. +// https://golang.org/src/net/url/url.go +func stripPort(hostport string) string { + colon := strings.IndexByte(hostport, ':') + if colon == -1 { + return hostport + } + if i := strings.IndexByte(hostport, ']'); i != -1 { + return strings.TrimPrefix(hostport[:i], "[") + } + return hostport[:colon] +} 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 438506bf4..129dad95d 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.7.9" +const SDKVersion = "1.8.21" diff --git a/vendor/github.com/aws/aws-sdk-go/doc.go b/vendor/github.com/aws/aws-sdk-go/doc.go new file mode 100644 index 000000000..3e077e51d --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/doc.go @@ -0,0 +1,405 @@ +// Package sdk is the official AWS SDK for the Go programming language. +// +// The AWS SDK for Go provides APIs and utilities that developers can use to +// build Go applications that use AWS services, such as Amazon Elastic Compute +// Cloud (Amazon EC2) and Amazon Simple Storage Service (Amazon S3). +// +// The SDK removes the complexity of coding directly against a web service +// interface. It hides a lot of the lower-level plumbing, such as authentication, +// request retries, and error handling. +// +// The SDK also includes helpful utilities on top of the AWS APIs that add additional +// capabilities and functionality. For example, the Amazon S3 Download and Upload +// Manager will automatically split up large objects into multiple parts and +// transfer them concurrently. +// +// See the s3manager package documentation for more information. +// https://docs.aws.amazon.com/sdk-for-go/api/service/s3/s3manager/ +// +// Getting More Information +// +// Checkout the Getting Started Guide and API Reference Docs detailed the SDK's +// components and details on each AWS client the SDK supports. +// +// The Getting Started Guide provides examples and detailed description of how +// to get setup with the SDK. +// https://docs.aws.amazon.com/sdk-for-go/v1/developer-guide/welcome.html +// +// The API Reference Docs include a detailed breakdown of the SDK's components +// such as utilities and AWS clients. Use this as a reference of the Go types +// included with the SDK, such as AWS clients, API operations, and API parameters. +// https://docs.aws.amazon.com/sdk-for-go/api/ +// +// Overview of SDK's Packages +// +// The SDK is composed of two main components, SDK core, and service clients. +// The SDK core packages are all available under the aws package at the root of +// the SDK. Each client for a supported AWS service is available within its own +// package under the service folder at the root of the SDK. +// +// * aws - SDK core, provides common shared types such as Config, Logger, +// and utilities to make working with API parameters easier. +// +// * awserr - Provides the error interface that the SDK will use for all +// errors that occur in the SDK's processing. This includes service API +// response errors as well. The Error type is made up of a code and message. +// Cast the SDK's returned error type to awserr.Error and call the Code +// method to compare returned error to specific error codes. See the package's +// documentation for additional values that can be extracted such as RequestId. +// +// * credentials - Provides the types and built in credentials providers +// the SDK will use to retrieve AWS credentials to make API requests with. +// Nested under this folder are also additional credentials providers such as +// stscreds for assuming IAM roles, and ec2rolecreds for EC2 Instance roles. +// +// * endpoints - Provides the AWS Regions and Endpoints metadata for the SDK. +// Use this to lookup AWS service endpoint information such as which services +// are in a region, and what regions a service is in. Constants are also provided +// for all region identifiers, e.g UsWest2RegionID for "us-west-2". +// +// * session - Provides initial default configuration, and load +// configuration from external sources such as environment and shared +// credentials file. +// +// * request - Provides the API request sending, and retry logic for the SDK. +// This package also includes utilities for defining your own request +// retryer, and configuring how the SDK processes the request. +// +// * service - Clients for AWS services. All services supported by the SDK are +// available under this folder. +// +// How to Use the SDK's AWS Service Clients +// +// The SDK includes the Go types and utilities you can use to make requests to +// AWS service APIs. Within the service folder at the root of the SDK you'll find +// a package for each AWS service the SDK supports. All service clients follows +// a common pattern of creation and usage. +// +// When creating a client for an AWS service you'll first need to have a Session +// value constructed. The Session provides shared configuration that can be shared +// between your service clients. When service clients are created you can pass +// in additional configuration via the aws.Config type to override configuration +// provided by in the Session to create service client instances with custom +// configuration. +// +// Once the service's client is created you can use it to make API requests the +// AWS service. These clients are safe to use concurrently. +// +// Configuring the SDK +// +// In the AWS SDK for Go, you can configure settings for service clients, such +// as the log level and maximum number of retries. Most settings are optional; +// however, for each service client, you must specify a region and your credentials. +// The SDK uses these values to send requests to the correct AWS region and sign +// requests with the correct credentials. You can specify these values as part +// of a session or as environment variables. +// +// See the SDK's configuration guide for more information. +// https://docs.aws.amazon.com/sdk-for-go/v1/developer-guide/configuring-sdk.html +// +// See the session package documentation for more information on how to use Session +// with the SDK. +// https://docs.aws.amazon.com/sdk-for-go/api/aws/session/ +// +// See the Config type in the aws package for more information on configuration +// options. +// https://docs.aws.amazon.com/sdk-for-go/api/aws/#Config +// +// Configuring Credentials +// +// When using the SDK you'll generally need your AWS credentials to authenticate +// with AWS services. The SDK supports multiple methods of supporting these +// credentials. By default the SDK will source credentials automatically from +// its default credential chain. See the session package for more information +// on this chain, and how to configure it. The common items in the credential +// chain are the following: +// +// * Environment Credentials - Set of environment variables that are useful +// when sub processes are created for specific roles. +// +// * Shared Credentials file (~/.aws/credentials) - This file stores your +// credentials based on a profile name and is useful for local development. +// +// * EC2 Instance Role Credentials - Use EC2 Instance Role to assign credentials +// to application running on an EC2 instance. This removes the need to manage +// credential files in production. +// +// Credentials can be configured in code as well by setting the Config's Credentials +// value to a custom provider or using one of the providers included with the +// SDK to bypass the default credential chain and use a custom one. This is +// helpful when you want to instruct the SDK to only use a specific set of +// credentials or providers. +// +// This example creates a credential provider for assuming an IAM role, "myRoleARN" +// and configures the S3 service client to use that role for API requests. +// +// // Initial credentials loaded from SDK's default credential chain. Such as +// // the environment, shared credentials (~/.aws/credentials), or EC2 Instance +// // Role. These credentials will be used to to make the STS Assume Role API. +// sess := session.Must(session.NewSession()) +// +// // Create the credentials from AssumeRoleProvider to assume the role +// // referenced by the "myRoleARN" ARN. +// creds := stscreds.NewCredentials(sess, "myRoleArn") +// +// // Create service client value configured for credentials +// // from assumed role. +// svc := s3.New(sess, &aws.Config{Credentials: creds})/ +// +// See the credentials package documentation for more information on credential +// providers included with the SDK, and how to customize the SDK's usage of +// credentials. +// https://docs.aws.amazon.com/sdk-for-go/api/aws/credentials +// +// The SDK has support for the shared configuration file (~/.aws/config). This +// support can be enabled by setting the environment variable, "AWS_SDK_LOAD_CONFIG=1", +// or enabling the feature in code when creating a Session via the +// Option's SharedConfigState parameter. +// +// sess := session.Must(session.NewSessionWithOptions(session.Options{ +// SharedConfigState: session.SharedConfigEnable, +// })) +// +// Configuring AWS Region +// +// In addition to the credentials you'll need to specify the region the SDK +// will use to make AWS API requests to. In the SDK you can specify the region +// either with an environment variable, or directly in code when a Session or +// service client is created. The last value specified in code wins if the region +// is specified multiple ways. +// +// To set the region via the environment variable set the "AWS_REGION" to the +// region you want to the SDK to use. Using this method to set the region will +// allow you to run your application in multiple regions without needing additional +// code in the application to select the region. +// +// AWS_REGION=us-west-2 +// +// The endpoints package includes constants for all regions the SDK knows. The +// values are all suffixed with RegionID. These values are helpful, because they +// reduce the need to type the region string manually. +// +// To set the region on a Session use the aws package's Config struct parameter +// Region to the AWS region you want the service clients created from the session to +// use. This is helpful when you want to create multiple service clients, and +// all of the clients make API requests to the same region. +// +// sess := session.Must(session.NewSession(&aws.Config{ +// Region: aws.String(endpoints.UsWest2RegionID), +// })) +// +// See the endpoints package for the AWS Regions and Endpoints metadata. +// https://docs.aws.amazon.com/sdk-for-go/api/aws/endpoints/ +// +// In addition to setting the region when creating a Session you can also set +// the region on a per service client bases. This overrides the region of a +// Session. This is helpful when you want to create service clients in specific +// regions different from the Session's region. +// +// svc := s3.New(sess, &aws.Config{ +// Region: aws.String(ednpoints.UsWest2RegionID), +// }) +// +// See the Config type in the aws package for more information and additional +// options such as setting the Endpoint, and other service client configuration options. +// https://docs.aws.amazon.com/sdk-for-go/api/aws/#Config +// +// Making API Requests +// +// Once the client is created you can make an API request to the service. +// Each API method takes a input parameter, and returns the service response +// and an error. The SDK provides methods for making the API call in multiple ways. +// +// In this list we'll use the S3 ListObjects API as an example for the different +// ways of making API requests. +// +// * ListObjects - Base API operation that will make the API request to the service. +// +// * ListObjectsRequest - API methods suffixed with Request will construct the +// API request, but not send it. This is also helpful when you want to get a +// presigned URL for a request, and share the presigned URL instead of your +// application making the request directly. +// +// * ListObjectsPages - Same as the base API operation, but uses a callback to +// automatically handle pagination of the API's response. +// +// * ListObjectsWithContext - Same as base API operation, but adds support for +// the Context pattern. This is helpful for controlling the canceling of in +// flight requests. See the Go standard library context package for more +// information. This method also takes request package's Option functional +// options as the variadic argument for modifying how the request will be +// made, or extracting information from the raw HTTP response. +// +// * ListObjectsPagesWithContext - same as ListObjectsPages, but adds support for +// the Context pattern. Similar to ListObjectsWithContext this method also +// takes the request package's Option function option types as the variadic +// argument. +// +// In addition to the API operations the SDK also includes several higher level +// methods that abstract checking for and waiting for an AWS resource to be in +// a desired state. In this list we'll use WaitUntilBucketExists to demonstrate +// the different forms of waiters. +// +// * WaitUntilBucketExists. - Method to make API request to query an AWS service for +// a resource's state. Will return successfully when that state is accomplished. +// +// * WaitUntilBucketExistsWithContext - Same as WaitUntilBucketExists, but adds +// support for the Context pattern. In addition these methods take request +// package's WaiterOptions to configure the waiter, and how underlying request +// will be made by the SDK. +// +// The API method will document which error codes the service might return for +// the operation. These errors will also be available as const strings prefixed +// with "ErrCode" in the service client's package. If there are no errors listed +// in the API's SDK documentation you'll need to consult the AWS service's API +// documentation for the errors that could be returned. +// +// ctx := context.Background() +// +// result, err := svc.GetObjectWithContext(ctx, &s3.GetObjectInput{ +// Bucket: aws.String("my-bucket"), +// Key: aws.String("my-key"), +// }) +// if err != nil { +// // Cast err to awserr.Error to handle specific error codes. +// aerr, ok := err.(awserr.Error) +// if ok && aerr.Code() == s3.ErrCodeNoSuchKey { +// // Specific error code handling +// } +// return err +// } +// +// // Make sure to close the body when done with it for S3 GetObject APIs or +// // will leak connections. +// defer result.Body.Close() +// +// fmt.Println("Object Size:", aws.StringValue(result.ContentLength)) +// +// API Request Pagination and Resource Waiters +// +// Pagination helper methods are suffixed with "Pages", and provide the +// functionality needed to round trip API page requests. Pagination methods +// take a callback function that will be called for each page of the API's response. +// +// objects := []string{} +// err := svc.ListObjectsPagesWithContext(ctx, &s3.ListObjectsInput{ +// Bucket: aws.String(myBucket), +// }, func(p *s3.ListObjectsOutput, lastPage bool) bool { +// for _, o := range p.Contents { +// objects = append(objects, aws.StringValue(o.Key)) +// } +// return true // continue paging +// }) +// if err != nil { +// panic(fmt.Sprintf("failed to list objects for bucket, %s, %v", myBucket, err)) +// } +// +// fmt.Println("Objects in bucket:", objects) +// +// Waiter helper methods provide the functionality to wait for an AWS resource +// state. These methods abstract the logic needed to to check the state of an +// AWS resource, and wait until that resource is in a desired state. The waiter +// will block until the resource is in the state that is desired, an error occurs, +// or the waiter times out. If a resource times out the error code returned will +// be request.WaiterResourceNotReadyErrorCode. +// +// err := svc.WaitUntilBucketExistsWithContext(ctx, &s3.HeadBucketInput{ +// Bucket: aws.String(myBucket), +// }) +// if err != nil { +// aerr, ok := err.(awserr.Error) +// if ok && aerr.Code() == request.WaiterResourceNotReadyErrorCode { +// fmt.Fprintf(os.Stderr, "timed out while waiting for bucket to exist") +// } +// panic(fmt.Errorf("failed to wait for bucket to exist, %v", err)) +// } +// fmt.Println("Bucket", myBucket, "exists") +// +// Complete SDK Example +// +// This example shows a complete working Go file which will upload a file to S3 +// and use the Context pattern to implement timeout logic that will cancel the +// request if it takes too long. This example highlights how to use sessions, +// create a service client, make a request, handle the error, and process the +// response. +// +// package main +// +// import ( +// "context" +// "flag" +// "fmt" +// "os" +// "time" +// +// "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/aws/session" +// "github.com/aws/aws-sdk-go/service/s3" +// ) +// +// // Uploads a file to S3 given a bucket and object key. Also takes a duration +// // value to terminate the update if it doesn't complete within that time. +// // +// // The AWS Region needs to be provided in the AWS shared config or on the +// // environment variable as `AWS_REGION`. Credentials also must be provided +// // Will default to shared config file, but can load from environment if provided. +// // +// // Usage: +// // # Upload myfile.txt to myBucket/myKey. Must complete within 10 minutes or will fail +// // go run withContext.go -b mybucket -k myKey -d 10m < myfile.txt +// func main() { +// var bucket, key string +// var timeout time.Duration +// +// flag.StringVar(&bucket, "b", "", "Bucket name.") +// flag.StringVar(&key, "k", "", "Object key name.") +// flag.DurationVar(&timeout, "d", 0, "Upload timeout.") +// flag.Parse() +// +// // All clients require a Session. The Session provides the client with +// // shared configuration such as region, endpoint, and credentials. A +// // Session should be shared where possible to take advantage of +// // configuration and credential caching. See the session package for +// // more information. +// sess := session.Must(session.NewSession()) +// +// // Create a new instance of the service's client with a Session. +// // Optional aws.Config values can also be provided as variadic arguments +// // to the New function. This option allows you to provide service +// // specific configuration. +// svc := s3.New(sess) +// +// // Create a context with a timeout that will abort the upload if it takes +// // more than the passed in timeout. +// ctx := context.Background() +// var cancelFn func() +// if timeout > 0 { +// ctx, cancelFn = context.WithTimeout(ctx, timeout) +// } +// // Ensure the context is canceled to prevent leaking. +// // See context package for more information, https://golang.org/pkg/context/ +// defer cancelFn() +// +// // Uploads the object to S3. The Context will interrupt the request if the +// // timeout expires. +// _, err := svc.PutObjectWithContext(ctx, &s3.PutObjectInput{ +// Bucket: aws.String(bucket), +// Key: aws.String(key), +// Body: os.Stdin, +// }) +// if err != nil { +// if aerr, ok := err.(awserr.Error); ok && aerr.Code() == request.CanceledErrorCode { +// // If the SDK can determine the request or retry delay was canceled +// // by a context the CanceledErrorCode error code will be returned. +// fmt.Fprintf(os.Stderr, "upload canceled due to timeout, %v\n", err) +// } else { +// fmt.Fprintf(os.Stderr, "failed to upload object, %v\n", err) +// } +// os.Exit(1) +// } +// +// fmt.Printf("successfully uploaded file to %s/%s\n", bucket, key) +// } +package sdk diff --git a/vendor/github.com/aws/aws-sdk-go/private/protocol/rest/build.go b/vendor/github.com/aws/aws-sdk-go/private/protocol/rest/build.go index 20a41d462..716183564 100644 --- a/vendor/github.com/aws/aws-sdk-go/private/protocol/rest/build.go +++ b/vendor/github.com/aws/aws-sdk-go/private/protocol/rest/build.go @@ -4,6 +4,7 @@ package rest import ( "bytes" "encoding/base64" + "encoding/json" "fmt" "io" "net/http" @@ -82,8 +83,12 @@ func buildLocationElements(r *request.Request, v reflect.Value, buildGETQuery bo if name == "" { name = field.Name } - if m.Kind() == reflect.Ptr { + if kind := m.Kind(); kind == reflect.Ptr { m = m.Elem() + } else if kind == reflect.Interface { + if !m.Elem().IsValid() { + continue + } } if !m.IsValid() { continue @@ -95,16 +100,16 @@ func buildLocationElements(r *request.Request, v reflect.Value, buildGETQuery bo var err error switch field.Tag.Get("location") { case "headers": // header maps - err = buildHeaderMap(&r.HTTPRequest.Header, m, field.Tag.Get("locationName")) + err = buildHeaderMap(&r.HTTPRequest.Header, m, field.Tag) case "header": - err = buildHeader(&r.HTTPRequest.Header, m, name) + err = buildHeader(&r.HTTPRequest.Header, m, name, field.Tag) case "uri": - err = buildURI(r.HTTPRequest.URL, m, name) + err = buildURI(r.HTTPRequest.URL, m, name, field.Tag) case "querystring": - err = buildQueryString(query, m, name) + err = buildQueryString(query, m, name, field.Tag) default: if buildGETQuery { - err = buildQueryString(query, m, name) + err = buildQueryString(query, m, name, field.Tag) } } r.Error = err @@ -145,8 +150,8 @@ func buildBody(r *request.Request, v reflect.Value) { } } -func buildHeader(header *http.Header, v reflect.Value, name string) error { - str, err := convertType(v) +func buildHeader(header *http.Header, v reflect.Value, name string, tag reflect.StructTag) error { + str, err := convertType(v, tag) if err == errValueNotSet { return nil } else if err != nil { @@ -158,9 +163,10 @@ func buildHeader(header *http.Header, v reflect.Value, name string) error { return nil } -func buildHeaderMap(header *http.Header, v reflect.Value, prefix string) error { +func buildHeaderMap(header *http.Header, v reflect.Value, tag reflect.StructTag) error { + prefix := tag.Get("locationName") for _, key := range v.MapKeys() { - str, err := convertType(v.MapIndex(key)) + str, err := convertType(v.MapIndex(key), tag) if err == errValueNotSet { continue } else if err != nil { @@ -173,8 +179,8 @@ func buildHeaderMap(header *http.Header, v reflect.Value, prefix string) error { return nil } -func buildURI(u *url.URL, v reflect.Value, name string) error { - value, err := convertType(v) +func buildURI(u *url.URL, v reflect.Value, name string, tag reflect.StructTag) error { + value, err := convertType(v, tag) if err == errValueNotSet { return nil } else if err != nil { @@ -190,7 +196,7 @@ func buildURI(u *url.URL, v reflect.Value, name string) error { return nil } -func buildQueryString(query url.Values, v reflect.Value, name string) error { +func buildQueryString(query url.Values, v reflect.Value, name string, tag reflect.StructTag) error { switch value := v.Interface().(type) { case []*string: for _, item := range value { @@ -207,7 +213,7 @@ func buildQueryString(query url.Values, v reflect.Value, name string) error { } } default: - str, err := convertType(v) + str, err := convertType(v, tag) if err == errValueNotSet { return nil } else if err != nil { @@ -246,7 +252,7 @@ func EscapePath(path string, encodeSep bool) string { return buf.String() } -func convertType(v reflect.Value) (string, error) { +func convertType(v reflect.Value, tag reflect.StructTag) (string, error) { v = reflect.Indirect(v) if !v.IsValid() { return "", errValueNotSet @@ -266,6 +272,16 @@ func convertType(v reflect.Value) (string, error) { str = strconv.FormatFloat(value, 'f', -1, 64) case time.Time: str = value.UTC().Format(RFC822) + case aws.JSONValue: + b, err := json.Marshal(value) + if err != nil { + return "", err + } + if tag.Get("location") == "header" { + str = base64.StdEncoding.EncodeToString(b) + } else { + str = string(b) + } default: err := fmt.Errorf("Unsupported value for param %v (%s)", v.Interface(), v.Type()) return "", err diff --git a/vendor/github.com/aws/aws-sdk-go/private/protocol/rest/unmarshal.go b/vendor/github.com/aws/aws-sdk-go/private/protocol/rest/unmarshal.go index 9c00921c0..7a779ee22 100644 --- a/vendor/github.com/aws/aws-sdk-go/private/protocol/rest/unmarshal.go +++ b/vendor/github.com/aws/aws-sdk-go/private/protocol/rest/unmarshal.go @@ -3,6 +3,7 @@ package rest import ( "bytes" "encoding/base64" + "encoding/json" "fmt" "io" "io/ioutil" @@ -12,6 +13,7 @@ import ( "strings" "time" + "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/aws/request" ) @@ -111,7 +113,7 @@ func unmarshalLocationElements(r *request.Request, v reflect.Value) { case "statusCode": unmarshalStatusCode(m, r.HTTPResponse.StatusCode) case "header": - err := unmarshalHeader(m, r.HTTPResponse.Header.Get(name)) + err := unmarshalHeader(m, r.HTTPResponse.Header.Get(name), field.Tag) if err != nil { r.Error = awserr.New("SerializationError", "failed to decode REST response", err) break @@ -158,8 +160,13 @@ func unmarshalHeaderMap(r reflect.Value, headers http.Header, prefix string) err return nil } -func unmarshalHeader(v reflect.Value, header string) error { - if !v.IsValid() || (header == "" && v.Elem().Kind() != reflect.String) { +func unmarshalHeader(v reflect.Value, header string, tag reflect.StructTag) error { + isJSONValue := tag.Get("type") == "jsonvalue" + if isJSONValue { + if len(header) == 0 { + return nil + } + } else if !v.IsValid() || (header == "" && v.Elem().Kind() != reflect.String) { return nil } @@ -196,6 +203,22 @@ func unmarshalHeader(v reflect.Value, header string) error { return err } v.Set(reflect.ValueOf(&t)) + case aws.JSONValue: + b := []byte(header) + var err error + if tag.Get("location") == "header" { + b, err = base64.StdEncoding.DecodeString(header) + if err != nil { + return err + } + } + + m := aws.JSONValue{} + err = json.Unmarshal(b, &m) + if err != nil { + return err + } + v.Set(reflect.ValueOf(m)) default: err := fmt.Errorf("Unsupported value for param %v (%s)", v.Interface(), v.Type()) return err diff --git a/vendor/github.com/aws/aws-sdk-go/private/protocol/xml/xmlutil/build.go b/vendor/github.com/aws/aws-sdk-go/private/protocol/xml/xmlutil/build.go index c74c19196..7091b456d 100644 --- a/vendor/github.com/aws/aws-sdk-go/private/protocol/xml/xmlutil/build.go +++ b/vendor/github.com/aws/aws-sdk-go/private/protocol/xml/xmlutil/build.go @@ -131,7 +131,6 @@ func (b *xmlBuilder) buildStruct(value reflect.Value, current *XMLNode, tag refl continue } - mTag := field.Tag if mTag.Get("location") != "" { // skip non-body members continue diff --git a/vendor/github.com/aws/aws-sdk-go/private/protocol/xml/xmlutil/unmarshal.go b/vendor/github.com/aws/aws-sdk-go/private/protocol/xml/xmlutil/unmarshal.go index 64b6ddd3e..87584628a 100644 --- a/vendor/github.com/aws/aws-sdk-go/private/protocol/xml/xmlutil/unmarshal.go +++ b/vendor/github.com/aws/aws-sdk-go/private/protocol/xml/xmlutil/unmarshal.go @@ -15,7 +15,10 @@ import ( // needs to match the shape of the XML expected to be decoded. // If the shape doesn't match unmarshaling will fail. func UnmarshalXML(v interface{}, d *xml.Decoder, wrapper string) error { - n, _ := XMLToStruct(d, nil) + n, err := XMLToStruct(d, nil) + if err != nil { + return err + } if n.Children != nil { for _, root := range n.Children { for _, c := range root { @@ -23,7 +26,7 @@ func UnmarshalXML(v interface{}, d *xml.Decoder, wrapper string) error { c = wrappedChild[0] // pull out wrapped element } - err := parse(reflect.ValueOf(v), c, "") + err = parse(reflect.ValueOf(v), c, "") if err != nil { if err == io.EOF { return nil diff --git a/vendor/github.com/aws/aws-sdk-go/private/protocol/xml/xmlutil/xml_to_struct.go b/vendor/github.com/aws/aws-sdk-go/private/protocol/xml/xmlutil/xml_to_struct.go index 3112512a2..3e970b629 100644 --- a/vendor/github.com/aws/aws-sdk-go/private/protocol/xml/xmlutil/xml_to_struct.go +++ b/vendor/github.com/aws/aws-sdk-go/private/protocol/xml/xmlutil/xml_to_struct.go @@ -40,11 +40,16 @@ func XMLToStruct(d *xml.Decoder, s *xml.StartElement) (*XMLNode, error) { out := &XMLNode{} for { tok, err := d.Token() - if tok == nil || err == io.EOF { - break - } if err != nil { - return out, err + if err == io.EOF { + break + } else { + return out, err + } + } + + if tok == nil { + break } switch typed := tok.(type) { diff --git a/vendor/github.com/aws/aws-sdk-go/private/waiter/waiter.go b/vendor/github.com/aws/aws-sdk-go/private/waiter/waiter.go deleted file mode 100644 index b51e9449c..000000000 --- a/vendor/github.com/aws/aws-sdk-go/private/waiter/waiter.go +++ /dev/null @@ -1,134 +0,0 @@ -package waiter - -import ( - "fmt" - "reflect" - "time" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/awsutil" - "github.com/aws/aws-sdk-go/aws/request" -) - -// A Config provides a collection of configuration values to setup a generated -// waiter code with. -type Config struct { - Name string - Delay int - MaxAttempts int - Operation string - Acceptors []WaitAcceptor -} - -// A WaitAcceptor provides the information needed to wait for an API operation -// to complete. -type WaitAcceptor struct { - Expected interface{} - Matcher string - State string - Argument string -} - -// A Waiter provides waiting for an operation to complete. -type Waiter struct { - Config - Client interface{} - Input interface{} -} - -// Wait waits for an operation to complete, expire max attempts, or fail. Error -// is returned if the operation fails. -func (w *Waiter) Wait() error { - client := reflect.ValueOf(w.Client) - in := reflect.ValueOf(w.Input) - method := client.MethodByName(w.Config.Operation + "Request") - - for i := 0; i < w.MaxAttempts; i++ { - res := method.Call([]reflect.Value{in}) - req := res[0].Interface().(*request.Request) - req.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Waiter")) - - err := req.Send() - for _, a := range w.Acceptors { - result := false - var vals []interface{} - switch a.Matcher { - case "pathAll", "path": - // Require all matches to be equal for result to match - vals, _ = awsutil.ValuesAtPath(req.Data, a.Argument) - if len(vals) == 0 { - break - } - result = true - for _, val := range vals { - if !awsutil.DeepEqual(val, a.Expected) { - result = false - break - } - } - case "pathAny": - // Only a single match needs to equal for the result to match - vals, _ = awsutil.ValuesAtPath(req.Data, a.Argument) - for _, val := range vals { - if awsutil.DeepEqual(val, a.Expected) { - result = true - break - } - } - case "status": - s := a.Expected.(int) - result = s == req.HTTPResponse.StatusCode - case "error": - if aerr, ok := err.(awserr.Error); ok { - result = aerr.Code() == a.Expected.(string) - } - case "pathList": - // ignored matcher - default: - logf(client, "WARNING: Waiter for %s encountered unexpected matcher: %s", - w.Config.Operation, a.Matcher) - } - - if !result { - // If there was no matching result found there is nothing more to do - // for this response, retry the request. - continue - } - - switch a.State { - case "success": - // waiter completed - return nil - case "failure": - // Waiter failure state triggered - return awserr.New("ResourceNotReady", - fmt.Sprintf("failed waiting for successful resource state"), err) - case "retry": - // clear the error and retry the operation - err = nil - default: - logf(client, "WARNING: Waiter for %s encountered unexpected state: %s", - w.Config.Operation, a.State) - } - } - if err != nil { - return err - } - - time.Sleep(time.Second * time.Duration(w.Delay)) - } - - return awserr.New("ResourceNotReady", - fmt.Sprintf("exceeded %d wait attempts", w.MaxAttempts), nil) -} - -func logf(client reflect.Value, msg string, args ...interface{}) { - cfgVal := client.FieldByName("Config") - if !cfgVal.IsValid() { - return - } - if cfg, ok := cfgVal.Interface().(*aws.Config); ok && cfg.Logger != nil { - cfg.Logger.Log(fmt.Sprintf(msg, args...)) - } -} diff --git a/vendor/github.com/aws/aws-sdk-go/sdk.go b/vendor/github.com/aws/aws-sdk-go/sdk.go deleted file mode 100644 index afa465a22..000000000 --- a/vendor/github.com/aws/aws-sdk-go/sdk.go +++ /dev/null @@ -1,7 +0,0 @@ -// Package sdk is the official AWS SDK for the Go programming language. -// -// See our Developer Guide for information for on getting started and using -// the SDK. -// -// https://github.com/aws/aws-sdk-go/wiki -package sdk diff --git a/vendor/github.com/aws/aws-sdk-go/service/acm/api.go b/vendor/github.com/aws/aws-sdk-go/service/acm/api.go index d17990db4..daaab1501 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/acm/api.go +++ b/vendor/github.com/aws/aws-sdk-go/service/acm/api.go @@ -1,12 +1,12 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. -// Package acm provides a client for AWS Certificate Manager. package acm import ( "fmt" "time" + "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awsutil" "github.com/aws/aws-sdk-go/aws/request" "github.com/aws/aws-sdk-go/private/protocol" @@ -103,8 +103,23 @@ func (c *ACM) AddTagsToCertificateRequest(input *AddTagsToCertificateInput) (req // Please also see https://docs.aws.amazon.com/goto/WebAPI/acm-2015-12-08/AddTagsToCertificate func (c *ACM) AddTagsToCertificate(input *AddTagsToCertificateInput) (*AddTagsToCertificateOutput, error) { req, out := c.AddTagsToCertificateRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// AddTagsToCertificateWithContext is the same as AddTagsToCertificate with the addition of +// the ability to pass a context and additional request options. +// +// See AddTagsToCertificate 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 *ACM) AddTagsToCertificateWithContext(ctx aws.Context, input *AddTagsToCertificateInput, opts ...request.Option) (*AddTagsToCertificateOutput, error) { + req, out := c.AddTagsToCertificateRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteCertificate = "DeleteCertificate" @@ -186,8 +201,23 @@ func (c *ACM) DeleteCertificateRequest(input *DeleteCertificateInput) (req *requ // Please also see https://docs.aws.amazon.com/goto/WebAPI/acm-2015-12-08/DeleteCertificate func (c *ACM) DeleteCertificate(input *DeleteCertificateInput) (*DeleteCertificateOutput, error) { req, out := c.DeleteCertificateRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteCertificateWithContext is the same as DeleteCertificate with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteCertificate 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 *ACM) DeleteCertificateWithContext(ctx aws.Context, input *DeleteCertificateInput, opts ...request.Option) (*DeleteCertificateOutput, error) { + req, out := c.DeleteCertificateRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeCertificate = "DescribeCertificate" @@ -255,8 +285,23 @@ func (c *ACM) DescribeCertificateRequest(input *DescribeCertificateInput) (req * // Please also see https://docs.aws.amazon.com/goto/WebAPI/acm-2015-12-08/DescribeCertificate func (c *ACM) DescribeCertificate(input *DescribeCertificateInput) (*DescribeCertificateOutput, error) { req, out := c.DescribeCertificateRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeCertificateWithContext is the same as DescribeCertificate with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeCertificate 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 *ACM) DescribeCertificateWithContext(ctx aws.Context, input *DescribeCertificateInput, opts ...request.Option) (*DescribeCertificateOutput, error) { + req, out := c.DescribeCertificateRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetCertificate = "GetCertificate" @@ -336,8 +381,23 @@ func (c *ACM) GetCertificateRequest(input *GetCertificateInput) (req *request.Re // Please also see https://docs.aws.amazon.com/goto/WebAPI/acm-2015-12-08/GetCertificate func (c *ACM) GetCertificate(input *GetCertificateInput) (*GetCertificateOutput, error) { req, out := c.GetCertificateRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetCertificateWithContext is the same as GetCertificate with the addition of +// the ability to pass a context and additional request options. +// +// See GetCertificate 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 *ACM) GetCertificateWithContext(ctx aws.Context, input *GetCertificateInput, opts ...request.Option) (*GetCertificateOutput, error) { + req, out := c.GetCertificateRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opImportCertificate = "ImportCertificate" @@ -434,8 +494,23 @@ func (c *ACM) ImportCertificateRequest(input *ImportCertificateInput) (req *requ // Please also see https://docs.aws.amazon.com/goto/WebAPI/acm-2015-12-08/ImportCertificate func (c *ACM) ImportCertificate(input *ImportCertificateInput) (*ImportCertificateOutput, error) { req, out := c.ImportCertificateRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ImportCertificateWithContext is the same as ImportCertificate with the addition of +// the ability to pass a context and additional request options. +// +// See ImportCertificate 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 *ACM) ImportCertificateWithContext(ctx aws.Context, input *ImportCertificateInput, opts ...request.Option) (*ImportCertificateOutput, error) { + req, out := c.ImportCertificateRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opListCertificates = "ListCertificates" @@ -502,8 +577,23 @@ func (c *ACM) ListCertificatesRequest(input *ListCertificatesInput) (req *reques // Please also see https://docs.aws.amazon.com/goto/WebAPI/acm-2015-12-08/ListCertificates func (c *ACM) ListCertificates(input *ListCertificatesInput) (*ListCertificatesOutput, error) { req, out := c.ListCertificatesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListCertificatesWithContext is the same as ListCertificates with the addition of +// the ability to pass a context and additional request options. +// +// See ListCertificates 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 *ACM) ListCertificatesWithContext(ctx aws.Context, input *ListCertificatesInput, opts ...request.Option) (*ListCertificatesOutput, error) { + req, out := c.ListCertificatesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // ListCertificatesPages iterates over the pages of a ListCertificates operation, @@ -523,12 +613,37 @@ func (c *ACM) ListCertificates(input *ListCertificatesInput) (*ListCertificatesO // return pageNum <= 3 // }) // -func (c *ACM) ListCertificatesPages(input *ListCertificatesInput, fn func(p *ListCertificatesOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.ListCertificatesRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*ListCertificatesOutput), lastPage) - }) +func (c *ACM) ListCertificatesPages(input *ListCertificatesInput, fn func(*ListCertificatesOutput, bool) bool) error { + return c.ListCertificatesPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListCertificatesPagesWithContext same as ListCertificatesPages 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 *ACM) ListCertificatesPagesWithContext(ctx aws.Context, input *ListCertificatesInput, fn func(*ListCertificatesOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListCertificatesInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListCertificatesRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*ListCertificatesOutput), !p.HasNextPage()) + } + return p.Err() } const opListTagsForCertificate = "ListTagsForCertificate" @@ -599,8 +714,23 @@ func (c *ACM) ListTagsForCertificateRequest(input *ListTagsForCertificateInput) // Please also see https://docs.aws.amazon.com/goto/WebAPI/acm-2015-12-08/ListTagsForCertificate func (c *ACM) ListTagsForCertificate(input *ListTagsForCertificateInput) (*ListTagsForCertificateOutput, error) { req, out := c.ListTagsForCertificateRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListTagsForCertificateWithContext is the same as ListTagsForCertificate with the addition of +// the ability to pass a context and additional request options. +// +// See ListTagsForCertificate 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 *ACM) ListTagsForCertificateWithContext(ctx aws.Context, input *ListTagsForCertificateInput, opts ...request.Option) (*ListTagsForCertificateOutput, error) { + req, out := c.ListTagsForCertificateRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opRemoveTagsFromCertificate = "RemoveTagsFromCertificate" @@ -681,8 +811,23 @@ func (c *ACM) RemoveTagsFromCertificateRequest(input *RemoveTagsFromCertificateI // Please also see https://docs.aws.amazon.com/goto/WebAPI/acm-2015-12-08/RemoveTagsFromCertificate func (c *ACM) RemoveTagsFromCertificate(input *RemoveTagsFromCertificateInput) (*RemoveTagsFromCertificateOutput, error) { req, out := c.RemoveTagsFromCertificateRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// RemoveTagsFromCertificateWithContext is the same as RemoveTagsFromCertificate with the addition of +// the ability to pass a context and additional request options. +// +// See RemoveTagsFromCertificate 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 *ACM) RemoveTagsFromCertificateWithContext(ctx aws.Context, input *RemoveTagsFromCertificateInput, opts ...request.Option) (*RemoveTagsFromCertificateOutput, error) { + req, out := c.RemoveTagsFromCertificateRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opRequestCertificate = "RequestCertificate" @@ -759,8 +904,23 @@ func (c *ACM) RequestCertificateRequest(input *RequestCertificateInput) (req *re // Please also see https://docs.aws.amazon.com/goto/WebAPI/acm-2015-12-08/RequestCertificate func (c *ACM) RequestCertificate(input *RequestCertificateInput) (*RequestCertificateOutput, error) { req, out := c.RequestCertificateRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// RequestCertificateWithContext is the same as RequestCertificate with the addition of +// the ability to pass a context and additional request options. +// +// See RequestCertificate 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 *ACM) RequestCertificateWithContext(ctx aws.Context, input *RequestCertificateInput, opts ...request.Option) (*RequestCertificateOutput, error) { + req, out := c.RequestCertificateRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opResendValidationEmail = "ResendValidationEmail" @@ -847,8 +1007,23 @@ func (c *ACM) ResendValidationEmailRequest(input *ResendValidationEmailInput) (r // Please also see https://docs.aws.amazon.com/goto/WebAPI/acm-2015-12-08/ResendValidationEmail func (c *ACM) ResendValidationEmail(input *ResendValidationEmailInput) (*ResendValidationEmailOutput, error) { req, out := c.ResendValidationEmailRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ResendValidationEmailWithContext is the same as ResendValidationEmail with the addition of +// the ability to pass a context and additional request options. +// +// See ResendValidationEmail 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 *ACM) ResendValidationEmailWithContext(ctx aws.Context, input *ResendValidationEmailInput, opts ...request.Option) (*ResendValidationEmailOutput, error) { + req, out := c.ResendValidationEmailRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // Please also see https://docs.aws.amazon.com/goto/WebAPI/acm-2015-12-08/AddTagsToCertificateRequest diff --git a/vendor/github.com/aws/aws-sdk-go/service/acm/doc.go b/vendor/github.com/aws/aws-sdk-go/service/acm/doc.go new file mode 100644 index 000000000..4cf6ffba3 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/service/acm/doc.go @@ -0,0 +1,84 @@ +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. + +// Package acm provides the client and types for making API +// requests to AWS Certificate Manager. +// +// Welcome to the AWS Certificate Manager (ACM) API documentation. +// +// You can use ACM to manage SSL/TLS certificates for your AWS-based websites +// and applications. For general information about using ACM, see the AWS Certificate +// Manager User Guide (http://docs.aws.amazon.com/acm/latest/userguide/). +// +// See https://docs.aws.amazon.com/goto/WebAPI/acm-2015-12-08 for more information on this service. +// +// See acm package documentation for more information. +// https://docs.aws.amazon.com/sdk-for-go/api/service/acm/ +// +// Using the Client +// +// To use the client for AWS Certificate Manager you will first need +// to create a new instance of it. +// +// When creating a client for an AWS service you'll first need to have a Session +// already created. The Session provides configuration that can be shared +// between multiple service clients. Additional configuration can be applied to +// the Session and service's client when they are constructed. The aws package's +// Config type contains several fields such as Region for the AWS Region the +// client should make API requests too. The optional Config value can be provided +// as the variadic argument for Sessions and client creation. +// +// Once the service's client is created you can use it to make API requests the +// AWS service. These clients are safe to use concurrently. +// +// // Create a session to share configuration, and load external configuration. +// sess := session.Must(session.NewSession()) +// +// // Create the service's client with the session. +// svc := acm.New(sess) +// +// See the SDK's documentation for more information on how to use service clients. +// https://docs.aws.amazon.com/sdk-for-go/api/ +// +// See aws package's Config type for more information on configuration options. +// https://docs.aws.amazon.com/sdk-for-go/api/aws/#Config +// +// See the AWS Certificate Manager client ACM for more +// information on creating the service's client. +// https://docs.aws.amazon.com/sdk-for-go/api/service/acm/#New +// +// Once the client is created you can make an API request to the service. +// Each API method takes a input parameter, and returns the service response +// and an error. +// +// The API method will document which error codes the service can be returned +// by the operation if the service models the API operation's errors. These +// errors will also be available as const strings prefixed with "ErrCode". +// +// result, err := svc.AddTagsToCertificate(params) +// if err != nil { +// // Cast err to awserr.Error to handle specific error codes. +// aerr, ok := err.(awserr.Error) +// if ok && aerr.Code() == { +// // Specific error code handling +// } +// return err +// } +// +// fmt.Println("AddTagsToCertificate result:") +// fmt.Println(result) +// +// Using the Client with Context +// +// The service's client also provides methods to make API requests with a Context +// value. This allows you to control the timeout, and cancellation of pending +// requests. These methods also take request Option as variadic parameter to apply +// additional configuration to the API request. +// +// ctx := context.Background() +// +// result, err := svc.AddTagsToCertificateWithContext(ctx, params) +// +// See the request package documentation for more information on using Context pattern +// with the SDK. +// https://docs.aws.amazon.com/sdk-for-go/api/aws/request/ +package acm diff --git a/vendor/github.com/aws/aws-sdk-go/service/acm/errors.go b/vendor/github.com/aws/aws-sdk-go/service/acm/errors.go index 73093d1c5..d09bda760 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/acm/errors.go +++ b/vendor/github.com/aws/aws-sdk-go/service/acm/errors.go @@ -1,4 +1,4 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. package acm diff --git a/vendor/github.com/aws/aws-sdk-go/service/acm/service.go b/vendor/github.com/aws/aws-sdk-go/service/acm/service.go index 0c1d69a59..b083c37d6 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/acm/service.go +++ b/vendor/github.com/aws/aws-sdk-go/service/acm/service.go @@ -1,4 +1,4 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. package acm @@ -11,14 +11,12 @@ import ( "github.com/aws/aws-sdk-go/private/protocol/jsonrpc" ) -// Welcome to the AWS Certificate Manager (ACM) API documentation. +// ACM provides the API operation methods for making requests to +// AWS Certificate Manager. See this package's package overview docs +// for details on the service. // -// You can use ACM to manage SSL/TLS certificates for your AWS-based websites -// and applications. For general information about using ACM, see the AWS Certificate -// Manager User Guide (http://docs.aws.amazon.com/acm/latest/userguide/). -// The service client's operations are safe to be used concurrently. -// It is not safe to mutate any of the client's properties though. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/acm-2015-12-08 +// ACM methods are safe to use concurrently. It is not safe to +// modify mutate any of the struct's properties though. type ACM struct { *client.Client } diff --git a/vendor/github.com/aws/aws-sdk-go/service/apigateway/api.go b/vendor/github.com/aws/aws-sdk-go/service/apigateway/api.go index e0af3861b..e12ed7058 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/apigateway/api.go +++ b/vendor/github.com/aws/aws-sdk-go/service/apigateway/api.go @@ -1,11 +1,11 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. -// Package apigateway provides a client for Amazon API Gateway. package apigateway import ( "time" + "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awsutil" "github.com/aws/aws-sdk-go/aws/request" "github.com/aws/aws-sdk-go/private/protocol" @@ -81,8 +81,23 @@ func (c *APIGateway) CreateApiKeyRequest(input *CreateApiKeyInput) (req *request // func (c *APIGateway) CreateApiKey(input *CreateApiKeyInput) (*ApiKey, error) { req, out := c.CreateApiKeyRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateApiKeyWithContext is the same as CreateApiKey with the addition of +// the ability to pass a context and additional request options. +// +// See CreateApiKey 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 *APIGateway) CreateApiKeyWithContext(ctx aws.Context, input *CreateApiKeyInput, opts ...request.Option) (*ApiKey, error) { + req, out := c.CreateApiKeyRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateAuthorizer = "CreateAuthorizer" @@ -152,8 +167,23 @@ func (c *APIGateway) CreateAuthorizerRequest(input *CreateAuthorizerInput) (req // func (c *APIGateway) CreateAuthorizer(input *CreateAuthorizerInput) (*Authorizer, error) { req, out := c.CreateAuthorizerRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateAuthorizerWithContext is the same as CreateAuthorizer with the addition of +// the ability to pass a context and additional request options. +// +// See CreateAuthorizer 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 *APIGateway) CreateAuthorizerWithContext(ctx aws.Context, input *CreateAuthorizerInput, opts ...request.Option) (*Authorizer, error) { + req, out := c.CreateAuthorizerRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateBasePathMapping = "CreateBasePathMapping" @@ -221,8 +251,23 @@ func (c *APIGateway) CreateBasePathMappingRequest(input *CreateBasePathMappingIn // func (c *APIGateway) CreateBasePathMapping(input *CreateBasePathMappingInput) (*BasePathMapping, error) { req, out := c.CreateBasePathMappingRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateBasePathMappingWithContext is the same as CreateBasePathMapping with the addition of +// the ability to pass a context and additional request options. +// +// See CreateBasePathMapping 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 *APIGateway) CreateBasePathMappingWithContext(ctx aws.Context, input *CreateBasePathMappingInput, opts ...request.Option) (*BasePathMapping, error) { + req, out := c.CreateBasePathMappingRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateDeployment = "CreateDeployment" @@ -295,8 +340,23 @@ func (c *APIGateway) CreateDeploymentRequest(input *CreateDeploymentInput) (req // func (c *APIGateway) CreateDeployment(input *CreateDeploymentInput) (*Deployment, error) { req, out := c.CreateDeploymentRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateDeploymentWithContext is the same as CreateDeployment with the addition of +// the ability to pass a context and additional request options. +// +// See CreateDeployment 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 *APIGateway) CreateDeploymentWithContext(ctx aws.Context, input *CreateDeploymentInput, opts ...request.Option) (*Deployment, error) { + req, out := c.CreateDeploymentRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateDocumentationPart = "CreateDocumentationPart" @@ -364,8 +424,23 @@ func (c *APIGateway) CreateDocumentationPartRequest(input *CreateDocumentationPa // func (c *APIGateway) CreateDocumentationPart(input *CreateDocumentationPartInput) (*DocumentationPart, error) { req, out := c.CreateDocumentationPartRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateDocumentationPartWithContext is the same as CreateDocumentationPart with the addition of +// the ability to pass a context and additional request options. +// +// See CreateDocumentationPart 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 *APIGateway) CreateDocumentationPartWithContext(ctx aws.Context, input *CreateDocumentationPartInput, opts ...request.Option) (*DocumentationPart, error) { + req, out := c.CreateDocumentationPartRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateDocumentationVersion = "CreateDocumentationVersion" @@ -433,8 +508,23 @@ func (c *APIGateway) CreateDocumentationVersionRequest(input *CreateDocumentatio // func (c *APIGateway) CreateDocumentationVersion(input *CreateDocumentationVersionInput) (*DocumentationVersion, error) { req, out := c.CreateDocumentationVersionRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateDocumentationVersionWithContext is the same as CreateDocumentationVersion with the addition of +// the ability to pass a context and additional request options. +// +// See CreateDocumentationVersion 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 *APIGateway) CreateDocumentationVersionWithContext(ctx aws.Context, input *CreateDocumentationVersionInput, opts ...request.Option) (*DocumentationVersion, error) { + req, out := c.CreateDocumentationVersionRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateDomainName = "CreateDomainName" @@ -500,8 +590,23 @@ func (c *APIGateway) CreateDomainNameRequest(input *CreateDomainNameInput) (req // func (c *APIGateway) CreateDomainName(input *CreateDomainNameInput) (*DomainName, error) { req, out := c.CreateDomainNameRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateDomainNameWithContext is the same as CreateDomainName with the addition of +// the ability to pass a context and additional request options. +// +// See CreateDomainName 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 *APIGateway) CreateDomainNameWithContext(ctx aws.Context, input *CreateDomainNameInput, opts ...request.Option) (*DomainName, error) { + req, out := c.CreateDomainNameRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateModel = "CreateModel" @@ -571,8 +676,107 @@ func (c *APIGateway) CreateModelRequest(input *CreateModelInput) (req *request.R // func (c *APIGateway) CreateModel(input *CreateModelInput) (*Model, error) { req, out := c.CreateModelRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateModelWithContext is the same as CreateModel with the addition of +// the ability to pass a context and additional request options. +// +// See CreateModel 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 *APIGateway) CreateModelWithContext(ctx aws.Context, input *CreateModelInput, opts ...request.Option) (*Model, error) { + req, out := c.CreateModelRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opCreateRequestValidator = "CreateRequestValidator" + +// CreateRequestValidatorRequest generates a "aws/request.Request" representing the +// client's request for the CreateRequestValidator operation. The "output" return +// value can be used to capture response data after the request's "Send" method +// is called. +// +// See CreateRequestValidator for usage and error information. +// +// Creating a request object using this method should be used when you want to inject +// custom logic into the request's lifecycle using a custom handler, or if you want to +// access properties on the request object before or after sending the request. If +// you just want the service response, call the CreateRequestValidator method directly +// instead. +// +// Note: You must call the "Send" method on the returned request object in order +// to execute the request. +// +// // Example sending a request using the CreateRequestValidatorRequest method. +// req, resp := client.CreateRequestValidatorRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +func (c *APIGateway) CreateRequestValidatorRequest(input *CreateRequestValidatorInput) (req *request.Request, output *UpdateRequestValidatorOutput) { + op := &request.Operation{ + Name: opCreateRequestValidator, + HTTPMethod: "POST", + HTTPPath: "/restapis/{restapi_id}/requestvalidators", + } + + if input == nil { + input = &CreateRequestValidatorInput{} + } + + output = &UpdateRequestValidatorOutput{} + req = c.newRequest(op, input, output) + return +} + +// CreateRequestValidator API operation for Amazon API Gateway. +// +// Creates a ReqeustValidator of a given RestApi. +// +// 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 API Gateway's +// API operation CreateRequestValidator for usage and error information. +// +// Returned Error Codes: +// * ErrCodeBadRequestException "BadRequestException" +// +// * ErrCodeUnauthorizedException "UnauthorizedException" +// +// * ErrCodeNotFoundException "NotFoundException" +// +// * ErrCodeLimitExceededException "LimitExceededException" +// +// * ErrCodeTooManyRequestsException "TooManyRequestsException" +// +func (c *APIGateway) CreateRequestValidator(input *CreateRequestValidatorInput) (*UpdateRequestValidatorOutput, error) { + req, out := c.CreateRequestValidatorRequest(input) + return out, req.Send() +} + +// CreateRequestValidatorWithContext is the same as CreateRequestValidator with the addition of +// the ability to pass a context and additional request options. +// +// See CreateRequestValidator 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 *APIGateway) CreateRequestValidatorWithContext(ctx aws.Context, input *CreateRequestValidatorInput, opts ...request.Option) (*UpdateRequestValidatorOutput, error) { + req, out := c.CreateRequestValidatorRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateResource = "CreateResource" @@ -642,8 +846,23 @@ func (c *APIGateway) CreateResourceRequest(input *CreateResourceInput) (req *req // func (c *APIGateway) CreateResource(input *CreateResourceInput) (*Resource, error) { req, out := c.CreateResourceRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateResourceWithContext is the same as CreateResource with the addition of +// the ability to pass a context and additional request options. +// +// See CreateResource 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 *APIGateway) CreateResourceWithContext(ctx aws.Context, input *CreateResourceInput, opts ...request.Option) (*Resource, error) { + req, out := c.CreateResourceRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateRestApi = "CreateRestApi" @@ -709,8 +928,23 @@ func (c *APIGateway) CreateRestApiRequest(input *CreateRestApiInput) (req *reque // func (c *APIGateway) CreateRestApi(input *CreateRestApiInput) (*RestApi, error) { req, out := c.CreateRestApiRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateRestApiWithContext is the same as CreateRestApi with the addition of +// the ability to pass a context and additional request options. +// +// See CreateRestApi 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 *APIGateway) CreateRestApiWithContext(ctx aws.Context, input *CreateRestApiInput, opts ...request.Option) (*RestApi, error) { + req, out := c.CreateRestApiRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateStage = "CreateStage" @@ -781,8 +1015,23 @@ func (c *APIGateway) CreateStageRequest(input *CreateStageInput) (req *request.R // func (c *APIGateway) CreateStage(input *CreateStageInput) (*Stage, error) { req, out := c.CreateStageRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateStageWithContext is the same as CreateStage with the addition of +// the ability to pass a context and additional request options. +// +// See CreateStage 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 *APIGateway) CreateStageWithContext(ctx aws.Context, input *CreateStageInput, opts ...request.Option) (*Stage, error) { + req, out := c.CreateStageRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateUsagePlan = "CreateUsagePlan" @@ -853,8 +1102,23 @@ func (c *APIGateway) CreateUsagePlanRequest(input *CreateUsagePlanInput) (req *r // func (c *APIGateway) CreateUsagePlan(input *CreateUsagePlanInput) (*UsagePlan, error) { req, out := c.CreateUsagePlanRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateUsagePlanWithContext is the same as CreateUsagePlan with the addition of +// the ability to pass a context and additional request options. +// +// See CreateUsagePlan 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 *APIGateway) CreateUsagePlanWithContext(ctx aws.Context, input *CreateUsagePlanInput, opts ...request.Option) (*UsagePlan, error) { + req, out := c.CreateUsagePlanRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateUsagePlanKey = "CreateUsagePlanKey" @@ -922,8 +1186,23 @@ func (c *APIGateway) CreateUsagePlanKeyRequest(input *CreateUsagePlanKeyInput) ( // func (c *APIGateway) CreateUsagePlanKey(input *CreateUsagePlanKeyInput) (*UsagePlanKey, error) { req, out := c.CreateUsagePlanKeyRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateUsagePlanKeyWithContext is the same as CreateUsagePlanKey with the addition of +// the ability to pass a context and additional request options. +// +// See CreateUsagePlanKey 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 *APIGateway) CreateUsagePlanKeyWithContext(ctx aws.Context, input *CreateUsagePlanKeyInput, opts ...request.Option) (*UsagePlanKey, error) { + req, out := c.CreateUsagePlanKeyRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteApiKey = "DeleteApiKey" @@ -989,8 +1268,23 @@ func (c *APIGateway) DeleteApiKeyRequest(input *DeleteApiKeyInput) (req *request // func (c *APIGateway) DeleteApiKey(input *DeleteApiKeyInput) (*DeleteApiKeyOutput, error) { req, out := c.DeleteApiKeyRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteApiKeyWithContext is the same as DeleteApiKey with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteApiKey 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 *APIGateway) DeleteApiKeyWithContext(ctx aws.Context, input *DeleteApiKeyInput, opts ...request.Option) (*DeleteApiKeyOutput, error) { + req, out := c.DeleteApiKeyRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteAuthorizer = "DeleteAuthorizer" @@ -1062,8 +1356,23 @@ func (c *APIGateway) DeleteAuthorizerRequest(input *DeleteAuthorizerInput) (req // func (c *APIGateway) DeleteAuthorizer(input *DeleteAuthorizerInput) (*DeleteAuthorizerOutput, error) { req, out := c.DeleteAuthorizerRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteAuthorizerWithContext is the same as DeleteAuthorizer with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteAuthorizer 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 *APIGateway) DeleteAuthorizerWithContext(ctx aws.Context, input *DeleteAuthorizerInput, opts ...request.Option) (*DeleteAuthorizerOutput, error) { + req, out := c.DeleteAuthorizerRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteBasePathMapping = "DeleteBasePathMapping" @@ -1129,8 +1438,23 @@ func (c *APIGateway) DeleteBasePathMappingRequest(input *DeleteBasePathMappingIn // func (c *APIGateway) DeleteBasePathMapping(input *DeleteBasePathMappingInput) (*DeleteBasePathMappingOutput, error) { req, out := c.DeleteBasePathMappingRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteBasePathMappingWithContext is the same as DeleteBasePathMapping with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteBasePathMapping 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 *APIGateway) DeleteBasePathMappingWithContext(ctx aws.Context, input *DeleteBasePathMappingInput, opts ...request.Option) (*DeleteBasePathMappingOutput, error) { + req, out := c.DeleteBasePathMappingRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteClientCertificate = "DeleteClientCertificate" @@ -1198,8 +1522,23 @@ func (c *APIGateway) DeleteClientCertificateRequest(input *DeleteClientCertifica // func (c *APIGateway) DeleteClientCertificate(input *DeleteClientCertificateInput) (*DeleteClientCertificateOutput, error) { req, out := c.DeleteClientCertificateRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteClientCertificateWithContext is the same as DeleteClientCertificate with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteClientCertificate 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 *APIGateway) DeleteClientCertificateWithContext(ctx aws.Context, input *DeleteClientCertificateInput, opts ...request.Option) (*DeleteClientCertificateOutput, error) { + req, out := c.DeleteClientCertificateRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteDeployment = "DeleteDeployment" @@ -1268,8 +1607,23 @@ func (c *APIGateway) DeleteDeploymentRequest(input *DeleteDeploymentInput) (req // func (c *APIGateway) DeleteDeployment(input *DeleteDeploymentInput) (*DeleteDeploymentOutput, error) { req, out := c.DeleteDeploymentRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteDeploymentWithContext is the same as DeleteDeployment with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteDeployment 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 *APIGateway) DeleteDeploymentWithContext(ctx aws.Context, input *DeleteDeploymentInput, opts ...request.Option) (*DeleteDeploymentOutput, error) { + req, out := c.DeleteDeploymentRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteDocumentationPart = "DeleteDocumentationPart" @@ -1337,8 +1691,23 @@ func (c *APIGateway) DeleteDocumentationPartRequest(input *DeleteDocumentationPa // func (c *APIGateway) DeleteDocumentationPart(input *DeleteDocumentationPartInput) (*DeleteDocumentationPartOutput, error) { req, out := c.DeleteDocumentationPartRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteDocumentationPartWithContext is the same as DeleteDocumentationPart with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteDocumentationPart 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 *APIGateway) DeleteDocumentationPartWithContext(ctx aws.Context, input *DeleteDocumentationPartInput, opts ...request.Option) (*DeleteDocumentationPartOutput, error) { + req, out := c.DeleteDocumentationPartRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteDocumentationVersion = "DeleteDocumentationVersion" @@ -1406,8 +1775,23 @@ func (c *APIGateway) DeleteDocumentationVersionRequest(input *DeleteDocumentatio // func (c *APIGateway) DeleteDocumentationVersion(input *DeleteDocumentationVersionInput) (*DeleteDocumentationVersionOutput, error) { req, out := c.DeleteDocumentationVersionRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteDocumentationVersionWithContext is the same as DeleteDocumentationVersion with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteDocumentationVersion 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 *APIGateway) DeleteDocumentationVersionWithContext(ctx aws.Context, input *DeleteDocumentationVersionInput, opts ...request.Option) (*DeleteDocumentationVersionOutput, error) { + req, out := c.DeleteDocumentationVersionRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteDomainName = "DeleteDomainName" @@ -1473,8 +1857,23 @@ func (c *APIGateway) DeleteDomainNameRequest(input *DeleteDomainNameInput) (req // func (c *APIGateway) DeleteDomainName(input *DeleteDomainNameInput) (*DeleteDomainNameOutput, error) { req, out := c.DeleteDomainNameRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteDomainNameWithContext is the same as DeleteDomainName with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteDomainName 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 *APIGateway) DeleteDomainNameWithContext(ctx aws.Context, input *DeleteDomainNameInput, opts ...request.Option) (*DeleteDomainNameOutput, error) { + req, out := c.DeleteDomainNameRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteIntegration = "DeleteIntegration" @@ -1542,8 +1941,23 @@ func (c *APIGateway) DeleteIntegrationRequest(input *DeleteIntegrationInput) (re // func (c *APIGateway) DeleteIntegration(input *DeleteIntegrationInput) (*DeleteIntegrationOutput, error) { req, out := c.DeleteIntegrationRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteIntegrationWithContext is the same as DeleteIntegration with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteIntegration 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 *APIGateway) DeleteIntegrationWithContext(ctx aws.Context, input *DeleteIntegrationInput, opts ...request.Option) (*DeleteIntegrationOutput, error) { + req, out := c.DeleteIntegrationRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteIntegrationResponse = "DeleteIntegrationResponse" @@ -1613,8 +2027,23 @@ func (c *APIGateway) DeleteIntegrationResponseRequest(input *DeleteIntegrationRe // func (c *APIGateway) DeleteIntegrationResponse(input *DeleteIntegrationResponseInput) (*DeleteIntegrationResponseOutput, error) { req, out := c.DeleteIntegrationResponseRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteIntegrationResponseWithContext is the same as DeleteIntegrationResponse with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteIntegrationResponse 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 *APIGateway) DeleteIntegrationResponseWithContext(ctx aws.Context, input *DeleteIntegrationResponseInput, opts ...request.Option) (*DeleteIntegrationResponseOutput, error) { + req, out := c.DeleteIntegrationResponseRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteMethod = "DeleteMethod" @@ -1682,8 +2111,23 @@ func (c *APIGateway) DeleteMethodRequest(input *DeleteMethodInput) (req *request // func (c *APIGateway) DeleteMethod(input *DeleteMethodInput) (*DeleteMethodOutput, error) { req, out := c.DeleteMethodRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteMethodWithContext is the same as DeleteMethod with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteMethod 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 *APIGateway) DeleteMethodWithContext(ctx aws.Context, input *DeleteMethodInput, opts ...request.Option) (*DeleteMethodOutput, error) { + req, out := c.DeleteMethodRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteMethodResponse = "DeleteMethodResponse" @@ -1753,8 +2197,23 @@ func (c *APIGateway) DeleteMethodResponseRequest(input *DeleteMethodResponseInpu // func (c *APIGateway) DeleteMethodResponse(input *DeleteMethodResponseInput) (*DeleteMethodResponseOutput, error) { req, out := c.DeleteMethodResponseRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteMethodResponseWithContext is the same as DeleteMethodResponse with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteMethodResponse 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 *APIGateway) DeleteMethodResponseWithContext(ctx aws.Context, input *DeleteMethodResponseInput, opts ...request.Option) (*DeleteMethodResponseOutput, error) { + req, out := c.DeleteMethodResponseRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteModel = "DeleteModel" @@ -1824,8 +2283,109 @@ func (c *APIGateway) DeleteModelRequest(input *DeleteModelInput) (req *request.R // func (c *APIGateway) DeleteModel(input *DeleteModelInput) (*DeleteModelOutput, error) { req, out := c.DeleteModelRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteModelWithContext is the same as DeleteModel with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteModel 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 *APIGateway) DeleteModelWithContext(ctx aws.Context, input *DeleteModelInput, opts ...request.Option) (*DeleteModelOutput, error) { + req, out := c.DeleteModelRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opDeleteRequestValidator = "DeleteRequestValidator" + +// DeleteRequestValidatorRequest generates a "aws/request.Request" representing the +// client's request for the DeleteRequestValidator operation. The "output" return +// value can be used to capture response data after the request's "Send" method +// is called. +// +// See DeleteRequestValidator for usage and error information. +// +// Creating a request object using this method should be used when you want to inject +// custom logic into the request's lifecycle using a custom handler, or if you want to +// access properties on the request object before or after sending the request. If +// you just want the service response, call the DeleteRequestValidator method directly +// instead. +// +// Note: You must call the "Send" method on the returned request object in order +// to execute the request. +// +// // Example sending a request using the DeleteRequestValidatorRequest method. +// req, resp := client.DeleteRequestValidatorRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +func (c *APIGateway) DeleteRequestValidatorRequest(input *DeleteRequestValidatorInput) (req *request.Request, output *DeleteRequestValidatorOutput) { + op := &request.Operation{ + Name: opDeleteRequestValidator, + HTTPMethod: "DELETE", + HTTPPath: "/restapis/{restapi_id}/requestvalidators/{requestvalidator_id}", + } + + if input == nil { + input = &DeleteRequestValidatorInput{} + } + + output = &DeleteRequestValidatorOutput{} + req = c.newRequest(op, input, output) + req.Handlers.Unmarshal.Remove(restjson.UnmarshalHandler) + req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) + return +} + +// DeleteRequestValidator API operation for Amazon API Gateway. +// +// Deletes a RequestValidator of a given RestApi. +// +// 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 API Gateway's +// API operation DeleteRequestValidator for usage and error information. +// +// Returned Error Codes: +// * ErrCodeUnauthorizedException "UnauthorizedException" +// +// * ErrCodeNotFoundException "NotFoundException" +// +// * ErrCodeTooManyRequestsException "TooManyRequestsException" +// +// * ErrCodeBadRequestException "BadRequestException" +// +// * ErrCodeConflictException "ConflictException" +// +func (c *APIGateway) DeleteRequestValidator(input *DeleteRequestValidatorInput) (*DeleteRequestValidatorOutput, error) { + req, out := c.DeleteRequestValidatorRequest(input) + return out, req.Send() +} + +// DeleteRequestValidatorWithContext is the same as DeleteRequestValidator with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteRequestValidator 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 *APIGateway) DeleteRequestValidatorWithContext(ctx aws.Context, input *DeleteRequestValidatorInput, opts ...request.Option) (*DeleteRequestValidatorOutput, error) { + req, out := c.DeleteRequestValidatorRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteResource = "DeleteResource" @@ -1895,8 +2455,23 @@ func (c *APIGateway) DeleteResourceRequest(input *DeleteResourceInput) (req *req // func (c *APIGateway) DeleteResource(input *DeleteResourceInput) (*DeleteResourceOutput, error) { req, out := c.DeleteResourceRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteResourceWithContext is the same as DeleteResource with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteResource 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 *APIGateway) DeleteResourceWithContext(ctx aws.Context, input *DeleteResourceInput, opts ...request.Option) (*DeleteResourceOutput, error) { + req, out := c.DeleteResourceRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteRestApi = "DeleteRestApi" @@ -1964,8 +2539,23 @@ func (c *APIGateway) DeleteRestApiRequest(input *DeleteRestApiInput) (req *reque // func (c *APIGateway) DeleteRestApi(input *DeleteRestApiInput) (*DeleteRestApiOutput, error) { req, out := c.DeleteRestApiRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteRestApiWithContext is the same as DeleteRestApi with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteRestApi 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 *APIGateway) DeleteRestApiWithContext(ctx aws.Context, input *DeleteRestApiInput, opts ...request.Option) (*DeleteRestApiOutput, error) { + req, out := c.DeleteRestApiRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteStage = "DeleteStage" @@ -2033,8 +2623,23 @@ func (c *APIGateway) DeleteStageRequest(input *DeleteStageInput) (req *request.R // func (c *APIGateway) DeleteStage(input *DeleteStageInput) (*DeleteStageOutput, error) { req, out := c.DeleteStageRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteStageWithContext is the same as DeleteStage with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteStage 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 *APIGateway) DeleteStageWithContext(ctx aws.Context, input *DeleteStageInput, opts ...request.Option) (*DeleteStageOutput, error) { + req, out := c.DeleteStageRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteUsagePlan = "DeleteUsagePlan" @@ -2102,8 +2707,23 @@ func (c *APIGateway) DeleteUsagePlanRequest(input *DeleteUsagePlanInput) (req *r // func (c *APIGateway) DeleteUsagePlan(input *DeleteUsagePlanInput) (*DeleteUsagePlanOutput, error) { req, out := c.DeleteUsagePlanRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteUsagePlanWithContext is the same as DeleteUsagePlan with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteUsagePlan 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 *APIGateway) DeleteUsagePlanWithContext(ctx aws.Context, input *DeleteUsagePlanInput, opts ...request.Option) (*DeleteUsagePlanOutput, error) { + req, out := c.DeleteUsagePlanRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteUsagePlanKey = "DeleteUsagePlanKey" @@ -2174,8 +2794,23 @@ func (c *APIGateway) DeleteUsagePlanKeyRequest(input *DeleteUsagePlanKeyInput) ( // func (c *APIGateway) DeleteUsagePlanKey(input *DeleteUsagePlanKeyInput) (*DeleteUsagePlanKeyOutput, error) { req, out := c.DeleteUsagePlanKeyRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteUsagePlanKeyWithContext is the same as DeleteUsagePlanKey with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteUsagePlanKey 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 *APIGateway) DeleteUsagePlanKeyWithContext(ctx aws.Context, input *DeleteUsagePlanKeyInput, opts ...request.Option) (*DeleteUsagePlanKeyOutput, error) { + req, out := c.DeleteUsagePlanKeyRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opFlushStageAuthorizersCache = "FlushStageAuthorizersCache" @@ -2243,8 +2878,23 @@ func (c *APIGateway) FlushStageAuthorizersCacheRequest(input *FlushStageAuthoriz // func (c *APIGateway) FlushStageAuthorizersCache(input *FlushStageAuthorizersCacheInput) (*FlushStageAuthorizersCacheOutput, error) { req, out := c.FlushStageAuthorizersCacheRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// FlushStageAuthorizersCacheWithContext is the same as FlushStageAuthorizersCache with the addition of +// the ability to pass a context and additional request options. +// +// See FlushStageAuthorizersCache 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 *APIGateway) FlushStageAuthorizersCacheWithContext(ctx aws.Context, input *FlushStageAuthorizersCacheInput, opts ...request.Option) (*FlushStageAuthorizersCacheOutput, error) { + req, out := c.FlushStageAuthorizersCacheRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opFlushStageCache = "FlushStageCache" @@ -2312,8 +2962,23 @@ func (c *APIGateway) FlushStageCacheRequest(input *FlushStageCacheInput) (req *r // func (c *APIGateway) FlushStageCache(input *FlushStageCacheInput) (*FlushStageCacheOutput, error) { req, out := c.FlushStageCacheRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// FlushStageCacheWithContext is the same as FlushStageCache with the addition of +// the ability to pass a context and additional request options. +// +// See FlushStageCache 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 *APIGateway) FlushStageCacheWithContext(ctx aws.Context, input *FlushStageCacheInput, opts ...request.Option) (*FlushStageCacheOutput, error) { + req, out := c.FlushStageCacheRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGenerateClientCertificate = "GenerateClientCertificate" @@ -2377,8 +3042,23 @@ func (c *APIGateway) GenerateClientCertificateRequest(input *GenerateClientCerti // func (c *APIGateway) GenerateClientCertificate(input *GenerateClientCertificateInput) (*ClientCertificate, error) { req, out := c.GenerateClientCertificateRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GenerateClientCertificateWithContext is the same as GenerateClientCertificate with the addition of +// the ability to pass a context and additional request options. +// +// See GenerateClientCertificate 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 *APIGateway) GenerateClientCertificateWithContext(ctx aws.Context, input *GenerateClientCertificateInput, opts ...request.Option) (*ClientCertificate, error) { + req, out := c.GenerateClientCertificateRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetAccount = "GetAccount" @@ -2442,8 +3122,23 @@ func (c *APIGateway) GetAccountRequest(input *GetAccountInput) (req *request.Req // func (c *APIGateway) GetAccount(input *GetAccountInput) (*Account, error) { req, out := c.GetAccountRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetAccountWithContext is the same as GetAccount with the addition of +// the ability to pass a context and additional request options. +// +// See GetAccount 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 *APIGateway) GetAccountWithContext(ctx aws.Context, input *GetAccountInput, opts ...request.Option) (*Account, error) { + req, out := c.GetAccountRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetApiKey = "GetApiKey" @@ -2507,8 +3202,23 @@ func (c *APIGateway) GetApiKeyRequest(input *GetApiKeyInput) (req *request.Reque // func (c *APIGateway) GetApiKey(input *GetApiKeyInput) (*ApiKey, error) { req, out := c.GetApiKeyRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetApiKeyWithContext is the same as GetApiKey with the addition of +// the ability to pass a context and additional request options. +// +// See GetApiKey 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 *APIGateway) GetApiKeyWithContext(ctx aws.Context, input *GetApiKeyInput, opts ...request.Option) (*ApiKey, error) { + req, out := c.GetApiKeyRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetApiKeys = "GetApiKeys" @@ -2578,8 +3288,23 @@ func (c *APIGateway) GetApiKeysRequest(input *GetApiKeysInput) (req *request.Req // func (c *APIGateway) GetApiKeys(input *GetApiKeysInput) (*GetApiKeysOutput, error) { req, out := c.GetApiKeysRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetApiKeysWithContext is the same as GetApiKeys with the addition of +// the ability to pass a context and additional request options. +// +// See GetApiKeys 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 *APIGateway) GetApiKeysWithContext(ctx aws.Context, input *GetApiKeysInput, opts ...request.Option) (*GetApiKeysOutput, error) { + req, out := c.GetApiKeysRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // GetApiKeysPages iterates over the pages of a GetApiKeys operation, @@ -2599,12 +3324,37 @@ func (c *APIGateway) GetApiKeys(input *GetApiKeysInput) (*GetApiKeysOutput, erro // return pageNum <= 3 // }) // -func (c *APIGateway) GetApiKeysPages(input *GetApiKeysInput, fn func(p *GetApiKeysOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.GetApiKeysRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*GetApiKeysOutput), lastPage) - }) +func (c *APIGateway) GetApiKeysPages(input *GetApiKeysInput, fn func(*GetApiKeysOutput, bool) bool) error { + return c.GetApiKeysPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// GetApiKeysPagesWithContext same as GetApiKeysPages 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 *APIGateway) GetApiKeysPagesWithContext(ctx aws.Context, input *GetApiKeysInput, fn func(*GetApiKeysOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *GetApiKeysInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.GetApiKeysRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*GetApiKeysOutput), !p.HasNextPage()) + } + return p.Err() } const opGetAuthorizer = "GetAuthorizer" @@ -2670,8 +3420,23 @@ func (c *APIGateway) GetAuthorizerRequest(input *GetAuthorizerInput) (req *reque // func (c *APIGateway) GetAuthorizer(input *GetAuthorizerInput) (*Authorizer, error) { req, out := c.GetAuthorizerRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetAuthorizerWithContext is the same as GetAuthorizer with the addition of +// the ability to pass a context and additional request options. +// +// See GetAuthorizer 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 *APIGateway) GetAuthorizerWithContext(ctx aws.Context, input *GetAuthorizerInput, opts ...request.Option) (*Authorizer, error) { + req, out := c.GetAuthorizerRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetAuthorizers = "GetAuthorizers" @@ -2739,8 +3504,23 @@ func (c *APIGateway) GetAuthorizersRequest(input *GetAuthorizersInput) (req *req // func (c *APIGateway) GetAuthorizers(input *GetAuthorizersInput) (*GetAuthorizersOutput, error) { req, out := c.GetAuthorizersRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetAuthorizersWithContext is the same as GetAuthorizers with the addition of +// the ability to pass a context and additional request options. +// +// See GetAuthorizers 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 *APIGateway) GetAuthorizersWithContext(ctx aws.Context, input *GetAuthorizersInput, opts ...request.Option) (*GetAuthorizersOutput, error) { + req, out := c.GetAuthorizersRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetBasePathMapping = "GetBasePathMapping" @@ -2804,8 +3584,23 @@ func (c *APIGateway) GetBasePathMappingRequest(input *GetBasePathMappingInput) ( // func (c *APIGateway) GetBasePathMapping(input *GetBasePathMappingInput) (*BasePathMapping, error) { req, out := c.GetBasePathMappingRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetBasePathMappingWithContext is the same as GetBasePathMapping with the addition of +// the ability to pass a context and additional request options. +// +// See GetBasePathMapping 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 *APIGateway) GetBasePathMappingWithContext(ctx aws.Context, input *GetBasePathMappingInput, opts ...request.Option) (*BasePathMapping, error) { + req, out := c.GetBasePathMappingRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetBasePathMappings = "GetBasePathMappings" @@ -2875,8 +3670,23 @@ func (c *APIGateway) GetBasePathMappingsRequest(input *GetBasePathMappingsInput) // func (c *APIGateway) GetBasePathMappings(input *GetBasePathMappingsInput) (*GetBasePathMappingsOutput, error) { req, out := c.GetBasePathMappingsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetBasePathMappingsWithContext is the same as GetBasePathMappings with the addition of +// the ability to pass a context and additional request options. +// +// See GetBasePathMappings 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 *APIGateway) GetBasePathMappingsWithContext(ctx aws.Context, input *GetBasePathMappingsInput, opts ...request.Option) (*GetBasePathMappingsOutput, error) { + req, out := c.GetBasePathMappingsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // GetBasePathMappingsPages iterates over the pages of a GetBasePathMappings operation, @@ -2896,12 +3706,37 @@ func (c *APIGateway) GetBasePathMappings(input *GetBasePathMappingsInput) (*GetB // return pageNum <= 3 // }) // -func (c *APIGateway) GetBasePathMappingsPages(input *GetBasePathMappingsInput, fn func(p *GetBasePathMappingsOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.GetBasePathMappingsRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*GetBasePathMappingsOutput), lastPage) - }) +func (c *APIGateway) GetBasePathMappingsPages(input *GetBasePathMappingsInput, fn func(*GetBasePathMappingsOutput, bool) bool) error { + return c.GetBasePathMappingsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// GetBasePathMappingsPagesWithContext same as GetBasePathMappingsPages 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 *APIGateway) GetBasePathMappingsPagesWithContext(ctx aws.Context, input *GetBasePathMappingsInput, fn func(*GetBasePathMappingsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *GetBasePathMappingsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.GetBasePathMappingsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*GetBasePathMappingsOutput), !p.HasNextPage()) + } + return p.Err() } const opGetClientCertificate = "GetClientCertificate" @@ -2965,8 +3800,23 @@ func (c *APIGateway) GetClientCertificateRequest(input *GetClientCertificateInpu // func (c *APIGateway) GetClientCertificate(input *GetClientCertificateInput) (*ClientCertificate, error) { req, out := c.GetClientCertificateRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetClientCertificateWithContext is the same as GetClientCertificate with the addition of +// the ability to pass a context and additional request options. +// +// See GetClientCertificate 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 *APIGateway) GetClientCertificateWithContext(ctx aws.Context, input *GetClientCertificateInput, opts ...request.Option) (*ClientCertificate, error) { + req, out := c.GetClientCertificateRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetClientCertificates = "GetClientCertificates" @@ -3036,8 +3886,23 @@ func (c *APIGateway) GetClientCertificatesRequest(input *GetClientCertificatesIn // func (c *APIGateway) GetClientCertificates(input *GetClientCertificatesInput) (*GetClientCertificatesOutput, error) { req, out := c.GetClientCertificatesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetClientCertificatesWithContext is the same as GetClientCertificates with the addition of +// the ability to pass a context and additional request options. +// +// See GetClientCertificates 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 *APIGateway) GetClientCertificatesWithContext(ctx aws.Context, input *GetClientCertificatesInput, opts ...request.Option) (*GetClientCertificatesOutput, error) { + req, out := c.GetClientCertificatesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // GetClientCertificatesPages iterates over the pages of a GetClientCertificates operation, @@ -3057,12 +3922,37 @@ func (c *APIGateway) GetClientCertificates(input *GetClientCertificatesInput) (* // return pageNum <= 3 // }) // -func (c *APIGateway) GetClientCertificatesPages(input *GetClientCertificatesInput, fn func(p *GetClientCertificatesOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.GetClientCertificatesRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*GetClientCertificatesOutput), lastPage) - }) +func (c *APIGateway) GetClientCertificatesPages(input *GetClientCertificatesInput, fn func(*GetClientCertificatesOutput, bool) bool) error { + return c.GetClientCertificatesPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// GetClientCertificatesPagesWithContext same as GetClientCertificatesPages 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 *APIGateway) GetClientCertificatesPagesWithContext(ctx aws.Context, input *GetClientCertificatesInput, fn func(*GetClientCertificatesOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *GetClientCertificatesInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.GetClientCertificatesRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*GetClientCertificatesOutput), !p.HasNextPage()) + } + return p.Err() } const opGetDeployment = "GetDeployment" @@ -3128,8 +4018,23 @@ func (c *APIGateway) GetDeploymentRequest(input *GetDeploymentInput) (req *reque // func (c *APIGateway) GetDeployment(input *GetDeploymentInput) (*Deployment, error) { req, out := c.GetDeploymentRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetDeploymentWithContext is the same as GetDeployment with the addition of +// the ability to pass a context and additional request options. +// +// See GetDeployment 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 *APIGateway) GetDeploymentWithContext(ctx aws.Context, input *GetDeploymentInput, opts ...request.Option) (*Deployment, error) { + req, out := c.GetDeploymentRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetDeployments = "GetDeployments" @@ -3201,8 +4106,23 @@ func (c *APIGateway) GetDeploymentsRequest(input *GetDeploymentsInput) (req *req // func (c *APIGateway) GetDeployments(input *GetDeploymentsInput) (*GetDeploymentsOutput, error) { req, out := c.GetDeploymentsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetDeploymentsWithContext is the same as GetDeployments with the addition of +// the ability to pass a context and additional request options. +// +// See GetDeployments 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 *APIGateway) GetDeploymentsWithContext(ctx aws.Context, input *GetDeploymentsInput, opts ...request.Option) (*GetDeploymentsOutput, error) { + req, out := c.GetDeploymentsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // GetDeploymentsPages iterates over the pages of a GetDeployments operation, @@ -3222,12 +4142,37 @@ func (c *APIGateway) GetDeployments(input *GetDeploymentsInput) (*GetDeployments // return pageNum <= 3 // }) // -func (c *APIGateway) GetDeploymentsPages(input *GetDeploymentsInput, fn func(p *GetDeploymentsOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.GetDeploymentsRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*GetDeploymentsOutput), lastPage) - }) +func (c *APIGateway) GetDeploymentsPages(input *GetDeploymentsInput, fn func(*GetDeploymentsOutput, bool) bool) error { + return c.GetDeploymentsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// GetDeploymentsPagesWithContext same as GetDeploymentsPages 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 *APIGateway) GetDeploymentsPagesWithContext(ctx aws.Context, input *GetDeploymentsInput, fn func(*GetDeploymentsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *GetDeploymentsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.GetDeploymentsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*GetDeploymentsOutput), !p.HasNextPage()) + } + return p.Err() } const opGetDocumentationPart = "GetDocumentationPart" @@ -3289,8 +4234,23 @@ func (c *APIGateway) GetDocumentationPartRequest(input *GetDocumentationPartInpu // func (c *APIGateway) GetDocumentationPart(input *GetDocumentationPartInput) (*DocumentationPart, error) { req, out := c.GetDocumentationPartRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetDocumentationPartWithContext is the same as GetDocumentationPart with the addition of +// the ability to pass a context and additional request options. +// +// See GetDocumentationPart 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 *APIGateway) GetDocumentationPartWithContext(ctx aws.Context, input *GetDocumentationPartInput, opts ...request.Option) (*DocumentationPart, error) { + req, out := c.GetDocumentationPartRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetDocumentationParts = "GetDocumentationParts" @@ -3354,8 +4314,23 @@ func (c *APIGateway) GetDocumentationPartsRequest(input *GetDocumentationPartsIn // func (c *APIGateway) GetDocumentationParts(input *GetDocumentationPartsInput) (*GetDocumentationPartsOutput, error) { req, out := c.GetDocumentationPartsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetDocumentationPartsWithContext is the same as GetDocumentationParts with the addition of +// the ability to pass a context and additional request options. +// +// See GetDocumentationParts 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 *APIGateway) GetDocumentationPartsWithContext(ctx aws.Context, input *GetDocumentationPartsInput, opts ...request.Option) (*GetDocumentationPartsOutput, error) { + req, out := c.GetDocumentationPartsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetDocumentationVersion = "GetDocumentationVersion" @@ -3417,8 +4392,23 @@ func (c *APIGateway) GetDocumentationVersionRequest(input *GetDocumentationVersi // func (c *APIGateway) GetDocumentationVersion(input *GetDocumentationVersionInput) (*DocumentationVersion, error) { req, out := c.GetDocumentationVersionRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetDocumentationVersionWithContext is the same as GetDocumentationVersion with the addition of +// the ability to pass a context and additional request options. +// +// See GetDocumentationVersion 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 *APIGateway) GetDocumentationVersionWithContext(ctx aws.Context, input *GetDocumentationVersionInput, opts ...request.Option) (*DocumentationVersion, error) { + req, out := c.GetDocumentationVersionRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetDocumentationVersions = "GetDocumentationVersions" @@ -3482,8 +4472,23 @@ func (c *APIGateway) GetDocumentationVersionsRequest(input *GetDocumentationVers // func (c *APIGateway) GetDocumentationVersions(input *GetDocumentationVersionsInput) (*GetDocumentationVersionsOutput, error) { req, out := c.GetDocumentationVersionsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetDocumentationVersionsWithContext is the same as GetDocumentationVersions with the addition of +// the ability to pass a context and additional request options. +// +// See GetDocumentationVersions 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 *APIGateway) GetDocumentationVersionsWithContext(ctx aws.Context, input *GetDocumentationVersionsInput, opts ...request.Option) (*GetDocumentationVersionsOutput, error) { + req, out := c.GetDocumentationVersionsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetDomainName = "GetDomainName" @@ -3550,8 +4555,23 @@ func (c *APIGateway) GetDomainNameRequest(input *GetDomainNameInput) (req *reque // func (c *APIGateway) GetDomainName(input *GetDomainNameInput) (*DomainName, error) { req, out := c.GetDomainNameRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetDomainNameWithContext is the same as GetDomainName with the addition of +// the ability to pass a context and additional request options. +// +// See GetDomainName 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 *APIGateway) GetDomainNameWithContext(ctx aws.Context, input *GetDomainNameInput, opts ...request.Option) (*DomainName, error) { + req, out := c.GetDomainNameRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetDomainNames = "GetDomainNames" @@ -3621,8 +4641,23 @@ func (c *APIGateway) GetDomainNamesRequest(input *GetDomainNamesInput) (req *req // func (c *APIGateway) GetDomainNames(input *GetDomainNamesInput) (*GetDomainNamesOutput, error) { req, out := c.GetDomainNamesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetDomainNamesWithContext is the same as GetDomainNames with the addition of +// the ability to pass a context and additional request options. +// +// See GetDomainNames 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 *APIGateway) GetDomainNamesWithContext(ctx aws.Context, input *GetDomainNamesInput, opts ...request.Option) (*GetDomainNamesOutput, error) { + req, out := c.GetDomainNamesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // GetDomainNamesPages iterates over the pages of a GetDomainNames operation, @@ -3642,12 +4677,37 @@ func (c *APIGateway) GetDomainNames(input *GetDomainNamesInput) (*GetDomainNames // return pageNum <= 3 // }) // -func (c *APIGateway) GetDomainNamesPages(input *GetDomainNamesInput, fn func(p *GetDomainNamesOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.GetDomainNamesRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*GetDomainNamesOutput), lastPage) - }) +func (c *APIGateway) GetDomainNamesPages(input *GetDomainNamesInput, fn func(*GetDomainNamesOutput, bool) bool) error { + return c.GetDomainNamesPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// GetDomainNamesPagesWithContext same as GetDomainNamesPages 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 *APIGateway) GetDomainNamesPagesWithContext(ctx aws.Context, input *GetDomainNamesInput, fn func(*GetDomainNamesOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *GetDomainNamesInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.GetDomainNamesRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*GetDomainNamesOutput), !p.HasNextPage()) + } + return p.Err() } const opGetExport = "GetExport" @@ -3713,8 +4773,23 @@ func (c *APIGateway) GetExportRequest(input *GetExportInput) (req *request.Reque // func (c *APIGateway) GetExport(input *GetExportInput) (*GetExportOutput, error) { req, out := c.GetExportRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetExportWithContext is the same as GetExport with the addition of +// the ability to pass a context and additional request options. +// +// See GetExport 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 *APIGateway) GetExportWithContext(ctx aws.Context, input *GetExportInput, opts ...request.Option) (*GetExportOutput, error) { + req, out := c.GetExportRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetIntegration = "GetIntegration" @@ -3778,8 +4853,23 @@ func (c *APIGateway) GetIntegrationRequest(input *GetIntegrationInput) (req *req // func (c *APIGateway) GetIntegration(input *GetIntegrationInput) (*Integration, error) { req, out := c.GetIntegrationRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetIntegrationWithContext is the same as GetIntegration with the addition of +// the ability to pass a context and additional request options. +// +// See GetIntegration 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 *APIGateway) GetIntegrationWithContext(ctx aws.Context, input *GetIntegrationInput, opts ...request.Option) (*Integration, error) { + req, out := c.GetIntegrationRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetIntegrationResponse = "GetIntegrationResponse" @@ -3843,8 +4933,23 @@ func (c *APIGateway) GetIntegrationResponseRequest(input *GetIntegrationResponse // func (c *APIGateway) GetIntegrationResponse(input *GetIntegrationResponseInput) (*IntegrationResponse, error) { req, out := c.GetIntegrationResponseRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetIntegrationResponseWithContext is the same as GetIntegrationResponse with the addition of +// the ability to pass a context and additional request options. +// +// See GetIntegrationResponse 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 *APIGateway) GetIntegrationResponseWithContext(ctx aws.Context, input *GetIntegrationResponseInput, opts ...request.Option) (*IntegrationResponse, error) { + req, out := c.GetIntegrationResponseRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetMethod = "GetMethod" @@ -3908,8 +5013,23 @@ func (c *APIGateway) GetMethodRequest(input *GetMethodInput) (req *request.Reque // func (c *APIGateway) GetMethod(input *GetMethodInput) (*Method, error) { req, out := c.GetMethodRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetMethodWithContext is the same as GetMethod with the addition of +// the ability to pass a context and additional request options. +// +// See GetMethod 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 *APIGateway) GetMethodWithContext(ctx aws.Context, input *GetMethodInput, opts ...request.Option) (*Method, error) { + req, out := c.GetMethodRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetMethodResponse = "GetMethodResponse" @@ -3973,8 +5093,23 @@ func (c *APIGateway) GetMethodResponseRequest(input *GetMethodResponseInput) (re // func (c *APIGateway) GetMethodResponse(input *GetMethodResponseInput) (*MethodResponse, error) { req, out := c.GetMethodResponseRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetMethodResponseWithContext is the same as GetMethodResponse with the addition of +// the ability to pass a context and additional request options. +// +// See GetMethodResponse 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 *APIGateway) GetMethodResponseWithContext(ctx aws.Context, input *GetMethodResponseInput, opts ...request.Option) (*MethodResponse, error) { + req, out := c.GetMethodResponseRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetModel = "GetModel" @@ -4038,8 +5173,23 @@ func (c *APIGateway) GetModelRequest(input *GetModelInput) (req *request.Request // func (c *APIGateway) GetModel(input *GetModelInput) (*Model, error) { req, out := c.GetModelRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetModelWithContext is the same as GetModel with the addition of +// the ability to pass a context and additional request options. +// +// See GetModel 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 *APIGateway) GetModelWithContext(ctx aws.Context, input *GetModelInput, opts ...request.Option) (*Model, error) { + req, out := c.GetModelRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetModelTemplate = "GetModelTemplate" @@ -4106,8 +5256,23 @@ func (c *APIGateway) GetModelTemplateRequest(input *GetModelTemplateInput) (req // func (c *APIGateway) GetModelTemplate(input *GetModelTemplateInput) (*GetModelTemplateOutput, error) { req, out := c.GetModelTemplateRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetModelTemplateWithContext is the same as GetModelTemplate with the addition of +// the ability to pass a context and additional request options. +// +// See GetModelTemplate 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 *APIGateway) GetModelTemplateWithContext(ctx aws.Context, input *GetModelTemplateInput, opts ...request.Option) (*GetModelTemplateOutput, error) { + req, out := c.GetModelTemplateRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetModels = "GetModels" @@ -4179,8 +5344,23 @@ func (c *APIGateway) GetModelsRequest(input *GetModelsInput) (req *request.Reque // func (c *APIGateway) GetModels(input *GetModelsInput) (*GetModelsOutput, error) { req, out := c.GetModelsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetModelsWithContext is the same as GetModels with the addition of +// the ability to pass a context and additional request options. +// +// See GetModels 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 *APIGateway) GetModelsWithContext(ctx aws.Context, input *GetModelsInput, opts ...request.Option) (*GetModelsOutput, error) { + req, out := c.GetModelsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // GetModelsPages iterates over the pages of a GetModels operation, @@ -4200,12 +5380,199 @@ func (c *APIGateway) GetModels(input *GetModelsInput) (*GetModelsOutput, error) // return pageNum <= 3 // }) // -func (c *APIGateway) GetModelsPages(input *GetModelsInput, fn func(p *GetModelsOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.GetModelsRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*GetModelsOutput), lastPage) - }) +func (c *APIGateway) GetModelsPages(input *GetModelsInput, fn func(*GetModelsOutput, bool) bool) error { + return c.GetModelsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// GetModelsPagesWithContext same as GetModelsPages 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 *APIGateway) GetModelsPagesWithContext(ctx aws.Context, input *GetModelsInput, fn func(*GetModelsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *GetModelsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.GetModelsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*GetModelsOutput), !p.HasNextPage()) + } + return p.Err() +} + +const opGetRequestValidator = "GetRequestValidator" + +// GetRequestValidatorRequest generates a "aws/request.Request" representing the +// client's request for the GetRequestValidator operation. The "output" return +// value can be used to capture response data after the request's "Send" method +// is called. +// +// See GetRequestValidator for usage and error information. +// +// Creating a request object using this method should be used when you want to inject +// custom logic into the request's lifecycle using a custom handler, or if you want to +// access properties on the request object before or after sending the request. If +// you just want the service response, call the GetRequestValidator method directly +// instead. +// +// Note: You must call the "Send" method on the returned request object in order +// to execute the request. +// +// // Example sending a request using the GetRequestValidatorRequest method. +// req, resp := client.GetRequestValidatorRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +func (c *APIGateway) GetRequestValidatorRequest(input *GetRequestValidatorInput) (req *request.Request, output *UpdateRequestValidatorOutput) { + op := &request.Operation{ + Name: opGetRequestValidator, + HTTPMethod: "GET", + HTTPPath: "/restapis/{restapi_id}/requestvalidators/{requestvalidator_id}", + } + + if input == nil { + input = &GetRequestValidatorInput{} + } + + output = &UpdateRequestValidatorOutput{} + req = c.newRequest(op, input, output) + return +} + +// GetRequestValidator API operation for Amazon API Gateway. +// +// Gets a RequestValidator of a given RestApi. +// +// 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 API Gateway's +// API operation GetRequestValidator for usage and error information. +// +// Returned Error Codes: +// * ErrCodeUnauthorizedException "UnauthorizedException" +// +// * ErrCodeNotFoundException "NotFoundException" +// +// * ErrCodeTooManyRequestsException "TooManyRequestsException" +// +func (c *APIGateway) GetRequestValidator(input *GetRequestValidatorInput) (*UpdateRequestValidatorOutput, error) { + req, out := c.GetRequestValidatorRequest(input) + return out, req.Send() +} + +// GetRequestValidatorWithContext is the same as GetRequestValidator with the addition of +// the ability to pass a context and additional request options. +// +// See GetRequestValidator 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 *APIGateway) GetRequestValidatorWithContext(ctx aws.Context, input *GetRequestValidatorInput, opts ...request.Option) (*UpdateRequestValidatorOutput, error) { + req, out := c.GetRequestValidatorRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opGetRequestValidators = "GetRequestValidators" + +// GetRequestValidatorsRequest generates a "aws/request.Request" representing the +// client's request for the GetRequestValidators operation. The "output" return +// value can be used to capture response data after the request's "Send" method +// is called. +// +// See GetRequestValidators for usage and error information. +// +// Creating a request object using this method should be used when you want to inject +// custom logic into the request's lifecycle using a custom handler, or if you want to +// access properties on the request object before or after sending the request. If +// you just want the service response, call the GetRequestValidators method directly +// instead. +// +// Note: You must call the "Send" method on the returned request object in order +// to execute the request. +// +// // Example sending a request using the GetRequestValidatorsRequest method. +// req, resp := client.GetRequestValidatorsRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +func (c *APIGateway) GetRequestValidatorsRequest(input *GetRequestValidatorsInput) (req *request.Request, output *GetRequestValidatorsOutput) { + op := &request.Operation{ + Name: opGetRequestValidators, + HTTPMethod: "GET", + HTTPPath: "/restapis/{restapi_id}/requestvalidators", + } + + if input == nil { + input = &GetRequestValidatorsInput{} + } + + output = &GetRequestValidatorsOutput{} + req = c.newRequest(op, input, output) + return +} + +// GetRequestValidators API operation for Amazon API Gateway. +// +// Gets the RequestValidators collection of a given RestApi. +// +// 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 API Gateway's +// API operation GetRequestValidators for usage and error information. +// +// Returned Error Codes: +// * ErrCodeBadRequestException "BadRequestException" +// +// * ErrCodeUnauthorizedException "UnauthorizedException" +// +// * ErrCodeNotFoundException "NotFoundException" +// +// * ErrCodeTooManyRequestsException "TooManyRequestsException" +// +func (c *APIGateway) GetRequestValidators(input *GetRequestValidatorsInput) (*GetRequestValidatorsOutput, error) { + req, out := c.GetRequestValidatorsRequest(input) + return out, req.Send() +} + +// GetRequestValidatorsWithContext is the same as GetRequestValidators with the addition of +// the ability to pass a context and additional request options. +// +// See GetRequestValidators 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 *APIGateway) GetRequestValidatorsWithContext(ctx aws.Context, input *GetRequestValidatorsInput, opts ...request.Option) (*GetRequestValidatorsOutput, error) { + req, out := c.GetRequestValidatorsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetResource = "GetResource" @@ -4269,8 +5636,23 @@ func (c *APIGateway) GetResourceRequest(input *GetResourceInput) (req *request.R // func (c *APIGateway) GetResource(input *GetResourceInput) (*Resource, error) { req, out := c.GetResourceRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetResourceWithContext is the same as GetResource with the addition of +// the ability to pass a context and additional request options. +// +// See GetResource 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 *APIGateway) GetResourceWithContext(ctx aws.Context, input *GetResourceInput, opts ...request.Option) (*Resource, error) { + req, out := c.GetResourceRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetResources = "GetResources" @@ -4342,8 +5724,23 @@ func (c *APIGateway) GetResourcesRequest(input *GetResourcesInput) (req *request // func (c *APIGateway) GetResources(input *GetResourcesInput) (*GetResourcesOutput, error) { req, out := c.GetResourcesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetResourcesWithContext is the same as GetResources with the addition of +// the ability to pass a context and additional request options. +// +// See GetResources 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 *APIGateway) GetResourcesWithContext(ctx aws.Context, input *GetResourcesInput, opts ...request.Option) (*GetResourcesOutput, error) { + req, out := c.GetResourcesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // GetResourcesPages iterates over the pages of a GetResources operation, @@ -4363,12 +5760,37 @@ func (c *APIGateway) GetResources(input *GetResourcesInput) (*GetResourcesOutput // return pageNum <= 3 // }) // -func (c *APIGateway) GetResourcesPages(input *GetResourcesInput, fn func(p *GetResourcesOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.GetResourcesRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*GetResourcesOutput), lastPage) - }) +func (c *APIGateway) GetResourcesPages(input *GetResourcesInput, fn func(*GetResourcesOutput, bool) bool) error { + return c.GetResourcesPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// GetResourcesPagesWithContext same as GetResourcesPages 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 *APIGateway) GetResourcesPagesWithContext(ctx aws.Context, input *GetResourcesInput, fn func(*GetResourcesOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *GetResourcesInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.GetResourcesRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*GetResourcesOutput), !p.HasNextPage()) + } + return p.Err() } const opGetRestApi = "GetRestApi" @@ -4432,8 +5854,23 @@ func (c *APIGateway) GetRestApiRequest(input *GetRestApiInput) (req *request.Req // func (c *APIGateway) GetRestApi(input *GetRestApiInput) (*RestApi, error) { req, out := c.GetRestApiRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetRestApiWithContext is the same as GetRestApi with the addition of +// the ability to pass a context and additional request options. +// +// See GetRestApi 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 *APIGateway) GetRestApiWithContext(ctx aws.Context, input *GetRestApiInput, opts ...request.Option) (*RestApi, error) { + req, out := c.GetRestApiRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetRestApis = "GetRestApis" @@ -4503,8 +5940,23 @@ func (c *APIGateway) GetRestApisRequest(input *GetRestApisInput) (req *request.R // func (c *APIGateway) GetRestApis(input *GetRestApisInput) (*GetRestApisOutput, error) { req, out := c.GetRestApisRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetRestApisWithContext is the same as GetRestApis with the addition of +// the ability to pass a context and additional request options. +// +// See GetRestApis 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 *APIGateway) GetRestApisWithContext(ctx aws.Context, input *GetRestApisInput, opts ...request.Option) (*GetRestApisOutput, error) { + req, out := c.GetRestApisRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // GetRestApisPages iterates over the pages of a GetRestApis operation, @@ -4524,12 +5976,37 @@ func (c *APIGateway) GetRestApis(input *GetRestApisInput) (*GetRestApisOutput, e // return pageNum <= 3 // }) // -func (c *APIGateway) GetRestApisPages(input *GetRestApisInput, fn func(p *GetRestApisOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.GetRestApisRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*GetRestApisOutput), lastPage) - }) +func (c *APIGateway) GetRestApisPages(input *GetRestApisInput, fn func(*GetRestApisOutput, bool) bool) error { + return c.GetRestApisPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// GetRestApisPagesWithContext same as GetRestApisPages 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 *APIGateway) GetRestApisPagesWithContext(ctx aws.Context, input *GetRestApisInput, fn func(*GetRestApisOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *GetRestApisInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.GetRestApisRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*GetRestApisOutput), !p.HasNextPage()) + } + return p.Err() } const opGetSdk = "GetSdk" @@ -4595,8 +6072,23 @@ func (c *APIGateway) GetSdkRequest(input *GetSdkInput) (req *request.Request, ou // func (c *APIGateway) GetSdk(input *GetSdkInput) (*GetSdkOutput, error) { req, out := c.GetSdkRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetSdkWithContext is the same as GetSdk with the addition of +// the ability to pass a context and additional request options. +// +// See GetSdk 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 *APIGateway) GetSdkWithContext(ctx aws.Context, input *GetSdkInput, opts ...request.Option) (*GetSdkOutput, error) { + req, out := c.GetSdkRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetSdkType = "GetSdkType" @@ -4658,8 +6150,23 @@ func (c *APIGateway) GetSdkTypeRequest(input *GetSdkTypeInput) (req *request.Req // func (c *APIGateway) GetSdkType(input *GetSdkTypeInput) (*SdkType, error) { req, out := c.GetSdkTypeRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetSdkTypeWithContext is the same as GetSdkType with the addition of +// the ability to pass a context and additional request options. +// +// See GetSdkType 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 *APIGateway) GetSdkTypeWithContext(ctx aws.Context, input *GetSdkTypeInput, opts ...request.Option) (*SdkType, error) { + req, out := c.GetSdkTypeRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetSdkTypes = "GetSdkTypes" @@ -4719,8 +6226,23 @@ func (c *APIGateway) GetSdkTypesRequest(input *GetSdkTypesInput) (req *request.R // func (c *APIGateway) GetSdkTypes(input *GetSdkTypesInput) (*GetSdkTypesOutput, error) { req, out := c.GetSdkTypesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetSdkTypesWithContext is the same as GetSdkTypes with the addition of +// the ability to pass a context and additional request options. +// +// See GetSdkTypes 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 *APIGateway) GetSdkTypesWithContext(ctx aws.Context, input *GetSdkTypesInput, opts ...request.Option) (*GetSdkTypesOutput, error) { + req, out := c.GetSdkTypesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetStage = "GetStage" @@ -4784,8 +6306,23 @@ func (c *APIGateway) GetStageRequest(input *GetStageInput) (req *request.Request // func (c *APIGateway) GetStage(input *GetStageInput) (*Stage, error) { req, out := c.GetStageRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetStageWithContext is the same as GetStage with the addition of +// the ability to pass a context and additional request options. +// +// See GetStage 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 *APIGateway) GetStageWithContext(ctx aws.Context, input *GetStageInput, opts ...request.Option) (*Stage, error) { + req, out := c.GetStageRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetStages = "GetStages" @@ -4849,8 +6386,23 @@ func (c *APIGateway) GetStagesRequest(input *GetStagesInput) (req *request.Reque // func (c *APIGateway) GetStages(input *GetStagesInput) (*GetStagesOutput, error) { req, out := c.GetStagesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetStagesWithContext is the same as GetStages with the addition of +// the ability to pass a context and additional request options. +// +// See GetStages 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 *APIGateway) GetStagesWithContext(ctx aws.Context, input *GetStagesInput, opts ...request.Option) (*GetStagesOutput, error) { + req, out := c.GetStagesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetUsage = "GetUsage" @@ -4922,8 +6474,23 @@ func (c *APIGateway) GetUsageRequest(input *GetUsageInput) (req *request.Request // func (c *APIGateway) GetUsage(input *GetUsageInput) (*Usage, error) { req, out := c.GetUsageRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetUsageWithContext is the same as GetUsage with the addition of +// the ability to pass a context and additional request options. +// +// See GetUsage 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 *APIGateway) GetUsageWithContext(ctx aws.Context, input *GetUsageInput, opts ...request.Option) (*Usage, error) { + req, out := c.GetUsageRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // GetUsagePages iterates over the pages of a GetUsage operation, @@ -4943,12 +6510,37 @@ func (c *APIGateway) GetUsage(input *GetUsageInput) (*Usage, error) { // return pageNum <= 3 // }) // -func (c *APIGateway) GetUsagePages(input *GetUsageInput, fn func(p *Usage, lastPage bool) (shouldContinue bool)) error { - page, _ := c.GetUsageRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*Usage), lastPage) - }) +func (c *APIGateway) GetUsagePages(input *GetUsageInput, fn func(*Usage, bool) bool) error { + return c.GetUsagePagesWithContext(aws.BackgroundContext(), input, fn) +} + +// GetUsagePagesWithContext same as GetUsagePages 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 *APIGateway) GetUsagePagesWithContext(ctx aws.Context, input *GetUsageInput, fn func(*Usage, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *GetUsageInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.GetUsageRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*Usage), !p.HasNextPage()) + } + return p.Err() } const opGetUsagePlan = "GetUsagePlan" @@ -5014,8 +6606,23 @@ func (c *APIGateway) GetUsagePlanRequest(input *GetUsagePlanInput) (req *request // func (c *APIGateway) GetUsagePlan(input *GetUsagePlanInput) (*UsagePlan, error) { req, out := c.GetUsagePlanRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetUsagePlanWithContext is the same as GetUsagePlan with the addition of +// the ability to pass a context and additional request options. +// +// See GetUsagePlan 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 *APIGateway) GetUsagePlanWithContext(ctx aws.Context, input *GetUsagePlanInput, opts ...request.Option) (*UsagePlan, error) { + req, out := c.GetUsagePlanRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetUsagePlanKey = "GetUsagePlanKey" @@ -5081,8 +6688,23 @@ func (c *APIGateway) GetUsagePlanKeyRequest(input *GetUsagePlanKeyInput) (req *r // func (c *APIGateway) GetUsagePlanKey(input *GetUsagePlanKeyInput) (*UsagePlanKey, error) { req, out := c.GetUsagePlanKeyRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetUsagePlanKeyWithContext is the same as GetUsagePlanKey with the addition of +// the ability to pass a context and additional request options. +// +// See GetUsagePlanKey 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 *APIGateway) GetUsagePlanKeyWithContext(ctx aws.Context, input *GetUsagePlanKeyInput, opts ...request.Option) (*UsagePlanKey, error) { + req, out := c.GetUsagePlanKeyRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetUsagePlanKeys = "GetUsagePlanKeys" @@ -5155,8 +6777,23 @@ func (c *APIGateway) GetUsagePlanKeysRequest(input *GetUsagePlanKeysInput) (req // func (c *APIGateway) GetUsagePlanKeys(input *GetUsagePlanKeysInput) (*GetUsagePlanKeysOutput, error) { req, out := c.GetUsagePlanKeysRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetUsagePlanKeysWithContext is the same as GetUsagePlanKeys with the addition of +// the ability to pass a context and additional request options. +// +// See GetUsagePlanKeys 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 *APIGateway) GetUsagePlanKeysWithContext(ctx aws.Context, input *GetUsagePlanKeysInput, opts ...request.Option) (*GetUsagePlanKeysOutput, error) { + req, out := c.GetUsagePlanKeysRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // GetUsagePlanKeysPages iterates over the pages of a GetUsagePlanKeys operation, @@ -5176,12 +6813,37 @@ func (c *APIGateway) GetUsagePlanKeys(input *GetUsagePlanKeysInput) (*GetUsagePl // return pageNum <= 3 // }) // -func (c *APIGateway) GetUsagePlanKeysPages(input *GetUsagePlanKeysInput, fn func(p *GetUsagePlanKeysOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.GetUsagePlanKeysRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*GetUsagePlanKeysOutput), lastPage) - }) +func (c *APIGateway) GetUsagePlanKeysPages(input *GetUsagePlanKeysInput, fn func(*GetUsagePlanKeysOutput, bool) bool) error { + return c.GetUsagePlanKeysPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// GetUsagePlanKeysPagesWithContext same as GetUsagePlanKeysPages 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 *APIGateway) GetUsagePlanKeysPagesWithContext(ctx aws.Context, input *GetUsagePlanKeysInput, fn func(*GetUsagePlanKeysOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *GetUsagePlanKeysInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.GetUsagePlanKeysRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*GetUsagePlanKeysOutput), !p.HasNextPage()) + } + return p.Err() } const opGetUsagePlans = "GetUsagePlans" @@ -5255,8 +6917,23 @@ func (c *APIGateway) GetUsagePlansRequest(input *GetUsagePlansInput) (req *reque // func (c *APIGateway) GetUsagePlans(input *GetUsagePlansInput) (*GetUsagePlansOutput, error) { req, out := c.GetUsagePlansRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetUsagePlansWithContext is the same as GetUsagePlans with the addition of +// the ability to pass a context and additional request options. +// +// See GetUsagePlans 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 *APIGateway) GetUsagePlansWithContext(ctx aws.Context, input *GetUsagePlansInput, opts ...request.Option) (*GetUsagePlansOutput, error) { + req, out := c.GetUsagePlansRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // GetUsagePlansPages iterates over the pages of a GetUsagePlans operation, @@ -5276,12 +6953,37 @@ func (c *APIGateway) GetUsagePlans(input *GetUsagePlansInput) (*GetUsagePlansOut // return pageNum <= 3 // }) // -func (c *APIGateway) GetUsagePlansPages(input *GetUsagePlansInput, fn func(p *GetUsagePlansOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.GetUsagePlansRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*GetUsagePlansOutput), lastPage) - }) +func (c *APIGateway) GetUsagePlansPages(input *GetUsagePlansInput, fn func(*GetUsagePlansOutput, bool) bool) error { + return c.GetUsagePlansPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// GetUsagePlansPagesWithContext same as GetUsagePlansPages 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 *APIGateway) GetUsagePlansPagesWithContext(ctx aws.Context, input *GetUsagePlansInput, fn func(*GetUsagePlansOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *GetUsagePlansInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.GetUsagePlansRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*GetUsagePlansOutput), !p.HasNextPage()) + } + return p.Err() } const opImportApiKeys = "ImportApiKeys" @@ -5351,8 +7053,23 @@ func (c *APIGateway) ImportApiKeysRequest(input *ImportApiKeysInput) (req *reque // func (c *APIGateway) ImportApiKeys(input *ImportApiKeysInput) (*ImportApiKeysOutput, error) { req, out := c.ImportApiKeysRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ImportApiKeysWithContext is the same as ImportApiKeys with the addition of +// the ability to pass a context and additional request options. +// +// See ImportApiKeys 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 *APIGateway) ImportApiKeysWithContext(ctx aws.Context, input *ImportApiKeysInput, opts ...request.Option) (*ImportApiKeysOutput, error) { + req, out := c.ImportApiKeysRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opImportDocumentationParts = "ImportDocumentationParts" @@ -5418,8 +7135,23 @@ func (c *APIGateway) ImportDocumentationPartsRequest(input *ImportDocumentationP // func (c *APIGateway) ImportDocumentationParts(input *ImportDocumentationPartsInput) (*ImportDocumentationPartsOutput, error) { req, out := c.ImportDocumentationPartsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ImportDocumentationPartsWithContext is the same as ImportDocumentationParts with the addition of +// the ability to pass a context and additional request options. +// +// See ImportDocumentationParts 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 *APIGateway) ImportDocumentationPartsWithContext(ctx aws.Context, input *ImportDocumentationPartsInput, opts ...request.Option) (*ImportDocumentationPartsOutput, error) { + req, out := c.ImportDocumentationPartsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opImportRestApi = "ImportRestApi" @@ -5488,8 +7220,23 @@ func (c *APIGateway) ImportRestApiRequest(input *ImportRestApiInput) (req *reque // func (c *APIGateway) ImportRestApi(input *ImportRestApiInput) (*RestApi, error) { req, out := c.ImportRestApiRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ImportRestApiWithContext is the same as ImportRestApi with the addition of +// the ability to pass a context and additional request options. +// +// See ImportRestApi 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 *APIGateway) ImportRestApiWithContext(ctx aws.Context, input *ImportRestApiInput, opts ...request.Option) (*RestApi, error) { + req, out := c.ImportRestApiRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opPutIntegration = "PutIntegration" @@ -5557,8 +7304,23 @@ func (c *APIGateway) PutIntegrationRequest(input *PutIntegrationInput) (req *req // func (c *APIGateway) PutIntegration(input *PutIntegrationInput) (*Integration, error) { req, out := c.PutIntegrationRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// PutIntegrationWithContext is the same as PutIntegration with the addition of +// the ability to pass a context and additional request options. +// +// See PutIntegration 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 *APIGateway) PutIntegrationWithContext(ctx aws.Context, input *PutIntegrationInput, opts ...request.Option) (*Integration, error) { + req, out := c.PutIntegrationRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opPutIntegrationResponse = "PutIntegrationResponse" @@ -5628,8 +7390,23 @@ func (c *APIGateway) PutIntegrationResponseRequest(input *PutIntegrationResponse // func (c *APIGateway) PutIntegrationResponse(input *PutIntegrationResponseInput) (*IntegrationResponse, error) { req, out := c.PutIntegrationResponseRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// PutIntegrationResponseWithContext is the same as PutIntegrationResponse with the addition of +// the ability to pass a context and additional request options. +// +// See PutIntegrationResponse 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 *APIGateway) PutIntegrationResponseWithContext(ctx aws.Context, input *PutIntegrationResponseInput, opts ...request.Option) (*IntegrationResponse, error) { + req, out := c.PutIntegrationResponseRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opPutMethod = "PutMethod" @@ -5699,8 +7476,23 @@ func (c *APIGateway) PutMethodRequest(input *PutMethodInput) (req *request.Reque // func (c *APIGateway) PutMethod(input *PutMethodInput) (*Method, error) { req, out := c.PutMethodRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// PutMethodWithContext is the same as PutMethod with the addition of +// the ability to pass a context and additional request options. +// +// See PutMethod 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 *APIGateway) PutMethodWithContext(ctx aws.Context, input *PutMethodInput, opts ...request.Option) (*Method, error) { + req, out := c.PutMethodRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opPutMethodResponse = "PutMethodResponse" @@ -5770,8 +7562,23 @@ func (c *APIGateway) PutMethodResponseRequest(input *PutMethodResponseInput) (re // func (c *APIGateway) PutMethodResponse(input *PutMethodResponseInput) (*MethodResponse, error) { req, out := c.PutMethodResponseRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// PutMethodResponseWithContext is the same as PutMethodResponse with the addition of +// the ability to pass a context and additional request options. +// +// See PutMethodResponse 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 *APIGateway) PutMethodResponseWithContext(ctx aws.Context, input *PutMethodResponseInput, opts ...request.Option) (*MethodResponse, error) { + req, out := c.PutMethodResponseRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opPutRestApi = "PutRestApi" @@ -5844,8 +7651,23 @@ func (c *APIGateway) PutRestApiRequest(input *PutRestApiInput) (req *request.Req // func (c *APIGateway) PutRestApi(input *PutRestApiInput) (*RestApi, error) { req, out := c.PutRestApiRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// PutRestApiWithContext is the same as PutRestApi with the addition of +// the ability to pass a context and additional request options. +// +// See PutRestApi 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 *APIGateway) PutRestApiWithContext(ctx aws.Context, input *PutRestApiInput, opts ...request.Option) (*RestApi, error) { + req, out := c.PutRestApiRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opTestInvokeAuthorizer = "TestInvokeAuthorizer" @@ -5914,8 +7736,23 @@ func (c *APIGateway) TestInvokeAuthorizerRequest(input *TestInvokeAuthorizerInpu // func (c *APIGateway) TestInvokeAuthorizer(input *TestInvokeAuthorizerInput) (*TestInvokeAuthorizerOutput, error) { req, out := c.TestInvokeAuthorizerRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// TestInvokeAuthorizerWithContext is the same as TestInvokeAuthorizer with the addition of +// the ability to pass a context and additional request options. +// +// See TestInvokeAuthorizer 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 *APIGateway) TestInvokeAuthorizerWithContext(ctx aws.Context, input *TestInvokeAuthorizerInput, opts ...request.Option) (*TestInvokeAuthorizerOutput, error) { + req, out := c.TestInvokeAuthorizerRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opTestInvokeMethod = "TestInvokeMethod" @@ -5982,8 +7819,23 @@ func (c *APIGateway) TestInvokeMethodRequest(input *TestInvokeMethodInput) (req // func (c *APIGateway) TestInvokeMethod(input *TestInvokeMethodInput) (*TestInvokeMethodOutput, error) { req, out := c.TestInvokeMethodRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// TestInvokeMethodWithContext is the same as TestInvokeMethod with the addition of +// the ability to pass a context and additional request options. +// +// See TestInvokeMethod 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 *APIGateway) TestInvokeMethodWithContext(ctx aws.Context, input *TestInvokeMethodInput, opts ...request.Option) (*TestInvokeMethodOutput, error) { + req, out := c.TestInvokeMethodRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opUpdateAccount = "UpdateAccount" @@ -6049,8 +7901,23 @@ func (c *APIGateway) UpdateAccountRequest(input *UpdateAccountInput) (req *reque // func (c *APIGateway) UpdateAccount(input *UpdateAccountInput) (*Account, error) { req, out := c.UpdateAccountRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// UpdateAccountWithContext is the same as UpdateAccount with the addition of +// the ability to pass a context and additional request options. +// +// See UpdateAccount 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 *APIGateway) UpdateAccountWithContext(ctx aws.Context, input *UpdateAccountInput, opts ...request.Option) (*Account, error) { + req, out := c.UpdateAccountRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opUpdateApiKey = "UpdateApiKey" @@ -6118,8 +7985,23 @@ func (c *APIGateway) UpdateApiKeyRequest(input *UpdateApiKeyInput) (req *request // func (c *APIGateway) UpdateApiKey(input *UpdateApiKeyInput) (*ApiKey, error) { req, out := c.UpdateApiKeyRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// UpdateApiKeyWithContext is the same as UpdateApiKey with the addition of +// the ability to pass a context and additional request options. +// +// See UpdateApiKey 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 *APIGateway) UpdateApiKeyWithContext(ctx aws.Context, input *UpdateApiKeyInput, opts ...request.Option) (*ApiKey, error) { + req, out := c.UpdateApiKeyRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opUpdateAuthorizer = "UpdateAuthorizer" @@ -6187,8 +8069,23 @@ func (c *APIGateway) UpdateAuthorizerRequest(input *UpdateAuthorizerInput) (req // func (c *APIGateway) UpdateAuthorizer(input *UpdateAuthorizerInput) (*Authorizer, error) { req, out := c.UpdateAuthorizerRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// UpdateAuthorizerWithContext is the same as UpdateAuthorizer with the addition of +// the ability to pass a context and additional request options. +// +// See UpdateAuthorizer 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 *APIGateway) UpdateAuthorizerWithContext(ctx aws.Context, input *UpdateAuthorizerInput, opts ...request.Option) (*Authorizer, error) { + req, out := c.UpdateAuthorizerRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opUpdateBasePathMapping = "UpdateBasePathMapping" @@ -6256,8 +8153,23 @@ func (c *APIGateway) UpdateBasePathMappingRequest(input *UpdateBasePathMappingIn // func (c *APIGateway) UpdateBasePathMapping(input *UpdateBasePathMappingInput) (*BasePathMapping, error) { req, out := c.UpdateBasePathMappingRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// UpdateBasePathMappingWithContext is the same as UpdateBasePathMapping with the addition of +// the ability to pass a context and additional request options. +// +// See UpdateBasePathMapping 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 *APIGateway) UpdateBasePathMappingWithContext(ctx aws.Context, input *UpdateBasePathMappingInput, opts ...request.Option) (*BasePathMapping, error) { + req, out := c.UpdateBasePathMappingRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opUpdateClientCertificate = "UpdateClientCertificate" @@ -6323,8 +8235,23 @@ func (c *APIGateway) UpdateClientCertificateRequest(input *UpdateClientCertifica // func (c *APIGateway) UpdateClientCertificate(input *UpdateClientCertificateInput) (*ClientCertificate, error) { req, out := c.UpdateClientCertificateRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// UpdateClientCertificateWithContext is the same as UpdateClientCertificate with the addition of +// the ability to pass a context and additional request options. +// +// See UpdateClientCertificate 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 *APIGateway) UpdateClientCertificateWithContext(ctx aws.Context, input *UpdateClientCertificateInput, opts ...request.Option) (*ClientCertificate, error) { + req, out := c.UpdateClientCertificateRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opUpdateDeployment = "UpdateDeployment" @@ -6392,8 +8319,23 @@ func (c *APIGateway) UpdateDeploymentRequest(input *UpdateDeploymentInput) (req // func (c *APIGateway) UpdateDeployment(input *UpdateDeploymentInput) (*Deployment, error) { req, out := c.UpdateDeploymentRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// UpdateDeploymentWithContext is the same as UpdateDeployment with the addition of +// the ability to pass a context and additional request options. +// +// See UpdateDeployment 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 *APIGateway) UpdateDeploymentWithContext(ctx aws.Context, input *UpdateDeploymentInput, opts ...request.Option) (*Deployment, error) { + req, out := c.UpdateDeploymentRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opUpdateDocumentationPart = "UpdateDocumentationPart" @@ -6461,8 +8403,23 @@ func (c *APIGateway) UpdateDocumentationPartRequest(input *UpdateDocumentationPa // func (c *APIGateway) UpdateDocumentationPart(input *UpdateDocumentationPartInput) (*DocumentationPart, error) { req, out := c.UpdateDocumentationPartRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// UpdateDocumentationPartWithContext is the same as UpdateDocumentationPart with the addition of +// the ability to pass a context and additional request options. +// +// See UpdateDocumentationPart 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 *APIGateway) UpdateDocumentationPartWithContext(ctx aws.Context, input *UpdateDocumentationPartInput, opts ...request.Option) (*DocumentationPart, error) { + req, out := c.UpdateDocumentationPartRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opUpdateDocumentationVersion = "UpdateDocumentationVersion" @@ -6528,8 +8485,23 @@ func (c *APIGateway) UpdateDocumentationVersionRequest(input *UpdateDocumentatio // func (c *APIGateway) UpdateDocumentationVersion(input *UpdateDocumentationVersionInput) (*DocumentationVersion, error) { req, out := c.UpdateDocumentationVersionRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// UpdateDocumentationVersionWithContext is the same as UpdateDocumentationVersion with the addition of +// the ability to pass a context and additional request options. +// +// See UpdateDocumentationVersion 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 *APIGateway) UpdateDocumentationVersionWithContext(ctx aws.Context, input *UpdateDocumentationVersionInput, opts ...request.Option) (*DocumentationVersion, error) { + req, out := c.UpdateDocumentationVersionRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opUpdateDomainName = "UpdateDomainName" @@ -6597,8 +8569,23 @@ func (c *APIGateway) UpdateDomainNameRequest(input *UpdateDomainNameInput) (req // func (c *APIGateway) UpdateDomainName(input *UpdateDomainNameInput) (*DomainName, error) { req, out := c.UpdateDomainNameRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// UpdateDomainNameWithContext is the same as UpdateDomainName with the addition of +// the ability to pass a context and additional request options. +// +// See UpdateDomainName 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 *APIGateway) UpdateDomainNameWithContext(ctx aws.Context, input *UpdateDomainNameInput, opts ...request.Option) (*DomainName, error) { + req, out := c.UpdateDomainNameRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opUpdateIntegration = "UpdateIntegration" @@ -6666,8 +8653,23 @@ func (c *APIGateway) UpdateIntegrationRequest(input *UpdateIntegrationInput) (re // func (c *APIGateway) UpdateIntegration(input *UpdateIntegrationInput) (*Integration, error) { req, out := c.UpdateIntegrationRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// UpdateIntegrationWithContext is the same as UpdateIntegration with the addition of +// the ability to pass a context and additional request options. +// +// See UpdateIntegration 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 *APIGateway) UpdateIntegrationWithContext(ctx aws.Context, input *UpdateIntegrationInput, opts ...request.Option) (*Integration, error) { + req, out := c.UpdateIntegrationRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opUpdateIntegrationResponse = "UpdateIntegrationResponse" @@ -6735,8 +8737,23 @@ func (c *APIGateway) UpdateIntegrationResponseRequest(input *UpdateIntegrationRe // func (c *APIGateway) UpdateIntegrationResponse(input *UpdateIntegrationResponseInput) (*IntegrationResponse, error) { req, out := c.UpdateIntegrationResponseRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// UpdateIntegrationResponseWithContext is the same as UpdateIntegrationResponse with the addition of +// the ability to pass a context and additional request options. +// +// See UpdateIntegrationResponse 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 *APIGateway) UpdateIntegrationResponseWithContext(ctx aws.Context, input *UpdateIntegrationResponseInput, opts ...request.Option) (*IntegrationResponse, error) { + req, out := c.UpdateIntegrationResponseRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opUpdateMethod = "UpdateMethod" @@ -6804,8 +8821,23 @@ func (c *APIGateway) UpdateMethodRequest(input *UpdateMethodInput) (req *request // func (c *APIGateway) UpdateMethod(input *UpdateMethodInput) (*Method, error) { req, out := c.UpdateMethodRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// UpdateMethodWithContext is the same as UpdateMethod with the addition of +// the ability to pass a context and additional request options. +// +// See UpdateMethod 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 *APIGateway) UpdateMethodWithContext(ctx aws.Context, input *UpdateMethodInput, opts ...request.Option) (*Method, error) { + req, out := c.UpdateMethodRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opUpdateMethodResponse = "UpdateMethodResponse" @@ -6875,8 +8907,23 @@ func (c *APIGateway) UpdateMethodResponseRequest(input *UpdateMethodResponseInpu // func (c *APIGateway) UpdateMethodResponse(input *UpdateMethodResponseInput) (*MethodResponse, error) { req, out := c.UpdateMethodResponseRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// UpdateMethodResponseWithContext is the same as UpdateMethodResponse with the addition of +// the ability to pass a context and additional request options. +// +// See UpdateMethodResponse 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 *APIGateway) UpdateMethodResponseWithContext(ctx aws.Context, input *UpdateMethodResponseInput, opts ...request.Option) (*MethodResponse, error) { + req, out := c.UpdateMethodResponseRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opUpdateModel = "UpdateModel" @@ -6944,8 +8991,105 @@ func (c *APIGateway) UpdateModelRequest(input *UpdateModelInput) (req *request.R // func (c *APIGateway) UpdateModel(input *UpdateModelInput) (*Model, error) { req, out := c.UpdateModelRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// UpdateModelWithContext is the same as UpdateModel with the addition of +// the ability to pass a context and additional request options. +// +// See UpdateModel 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 *APIGateway) UpdateModelWithContext(ctx aws.Context, input *UpdateModelInput, opts ...request.Option) (*Model, error) { + req, out := c.UpdateModelRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opUpdateRequestValidator = "UpdateRequestValidator" + +// UpdateRequestValidatorRequest generates a "aws/request.Request" representing the +// client's request for the UpdateRequestValidator operation. The "output" return +// value can be used to capture response data after the request's "Send" method +// is called. +// +// See UpdateRequestValidator for usage and error information. +// +// Creating a request object using this method should be used when you want to inject +// custom logic into the request's lifecycle using a custom handler, or if you want to +// access properties on the request object before or after sending the request. If +// you just want the service response, call the UpdateRequestValidator method directly +// instead. +// +// Note: You must call the "Send" method on the returned request object in order +// to execute the request. +// +// // Example sending a request using the UpdateRequestValidatorRequest method. +// req, resp := client.UpdateRequestValidatorRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +func (c *APIGateway) UpdateRequestValidatorRequest(input *UpdateRequestValidatorInput) (req *request.Request, output *UpdateRequestValidatorOutput) { + op := &request.Operation{ + Name: opUpdateRequestValidator, + HTTPMethod: "PATCH", + HTTPPath: "/restapis/{restapi_id}/requestvalidators/{requestvalidator_id}", + } + + if input == nil { + input = &UpdateRequestValidatorInput{} + } + + output = &UpdateRequestValidatorOutput{} + req = c.newRequest(op, input, output) + return +} + +// UpdateRequestValidator API operation for Amazon API Gateway. +// +// Updates a RequestValidator of a given RestApi. +// +// 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 API Gateway's +// API operation UpdateRequestValidator for usage and error information. +// +// Returned Error Codes: +// * ErrCodeUnauthorizedException "UnauthorizedException" +// +// * ErrCodeNotFoundException "NotFoundException" +// +// * ErrCodeBadRequestException "BadRequestException" +// +// * ErrCodeTooManyRequestsException "TooManyRequestsException" +// +func (c *APIGateway) UpdateRequestValidator(input *UpdateRequestValidatorInput) (*UpdateRequestValidatorOutput, error) { + req, out := c.UpdateRequestValidatorRequest(input) + return out, req.Send() +} + +// UpdateRequestValidatorWithContext is the same as UpdateRequestValidator with the addition of +// the ability to pass a context and additional request options. +// +// See UpdateRequestValidator 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 *APIGateway) UpdateRequestValidatorWithContext(ctx aws.Context, input *UpdateRequestValidatorInput, opts ...request.Option) (*UpdateRequestValidatorOutput, error) { + req, out := c.UpdateRequestValidatorRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opUpdateResource = "UpdateResource" @@ -7013,8 +9157,23 @@ func (c *APIGateway) UpdateResourceRequest(input *UpdateResourceInput) (req *req // func (c *APIGateway) UpdateResource(input *UpdateResourceInput) (*Resource, error) { req, out := c.UpdateResourceRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// UpdateResourceWithContext is the same as UpdateResource with the addition of +// the ability to pass a context and additional request options. +// +// See UpdateResource 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 *APIGateway) UpdateResourceWithContext(ctx aws.Context, input *UpdateResourceInput, opts ...request.Option) (*Resource, error) { + req, out := c.UpdateResourceRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opUpdateRestApi = "UpdateRestApi" @@ -7082,8 +9241,23 @@ func (c *APIGateway) UpdateRestApiRequest(input *UpdateRestApiInput) (req *reque // func (c *APIGateway) UpdateRestApi(input *UpdateRestApiInput) (*RestApi, error) { req, out := c.UpdateRestApiRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// UpdateRestApiWithContext is the same as UpdateRestApi with the addition of +// the ability to pass a context and additional request options. +// +// See UpdateRestApi 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 *APIGateway) UpdateRestApiWithContext(ctx aws.Context, input *UpdateRestApiInput, opts ...request.Option) (*RestApi, error) { + req, out := c.UpdateRestApiRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opUpdateStage = "UpdateStage" @@ -7151,8 +9325,23 @@ func (c *APIGateway) UpdateStageRequest(input *UpdateStageInput) (req *request.R // func (c *APIGateway) UpdateStage(input *UpdateStageInput) (*Stage, error) { req, out := c.UpdateStageRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// UpdateStageWithContext is the same as UpdateStage with the addition of +// the ability to pass a context and additional request options. +// +// See UpdateStage 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 *APIGateway) UpdateStageWithContext(ctx aws.Context, input *UpdateStageInput, opts ...request.Option) (*Stage, error) { + req, out := c.UpdateStageRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opUpdateUsage = "UpdateUsage" @@ -7219,8 +9408,23 @@ func (c *APIGateway) UpdateUsageRequest(input *UpdateUsageInput) (req *request.R // func (c *APIGateway) UpdateUsage(input *UpdateUsageInput) (*Usage, error) { req, out := c.UpdateUsageRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// UpdateUsageWithContext is the same as UpdateUsage with the addition of +// the ability to pass a context and additional request options. +// +// See UpdateUsage 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 *APIGateway) UpdateUsageWithContext(ctx aws.Context, input *UpdateUsageInput, opts ...request.Option) (*Usage, error) { + req, out := c.UpdateUsageRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opUpdateUsagePlan = "UpdateUsagePlan" @@ -7288,8 +9492,23 @@ func (c *APIGateway) UpdateUsagePlanRequest(input *UpdateUsagePlanInput) (req *r // func (c *APIGateway) UpdateUsagePlan(input *UpdateUsagePlanInput) (*UsagePlan, error) { req, out := c.UpdateUsagePlanRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// UpdateUsagePlanWithContext is the same as UpdateUsagePlan with the addition of +// the ability to pass a context and additional request options. +// +// See UpdateUsagePlan 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 *APIGateway) UpdateUsagePlanWithContext(ctx aws.Context, input *UpdateUsagePlanInput, opts ...request.Option) (*UsagePlan, error) { + req, out := c.UpdateUsagePlanRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // Represents an AWS account that is associated with Amazon API Gateway. @@ -8472,6 +10691,75 @@ func (s *CreateModelInput) SetSchema(v string) *CreateModelInput { return s } +// Creates a RequestValidator of a given RestApi. +type CreateRequestValidatorInput struct { + _ struct{} `type:"structure"` + + // The name of the to-be-created RequestValidator. + Name *string `locationName:"name" type:"string"` + + // [Required] The identifier of the RestApi for which the RequestValidator is + // created. + // + // RestApiId is a required field + RestApiId *string `location:"uri" locationName:"restapi_id" type:"string" required:"true"` + + // A Boolean flag to indicate whether to validate request body according to + // the configured model schema for the method (true) or not (false). + ValidateRequestBody *bool `locationName:"validateRequestBody" type:"boolean"` + + // A Boolean flag to indicate whether to validate request parameters, true, + // or not false. + ValidateRequestParameters *bool `locationName:"validateRequestParameters" type:"boolean"` +} + +// String returns the string representation +func (s CreateRequestValidatorInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s CreateRequestValidatorInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *CreateRequestValidatorInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "CreateRequestValidatorInput"} + if s.RestApiId == nil { + invalidParams.Add(request.NewErrParamRequired("RestApiId")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetName sets the Name field's value. +func (s *CreateRequestValidatorInput) SetName(v string) *CreateRequestValidatorInput { + s.Name = &v + return s +} + +// SetRestApiId sets the RestApiId field's value. +func (s *CreateRequestValidatorInput) SetRestApiId(v string) *CreateRequestValidatorInput { + s.RestApiId = &v + return s +} + +// SetValidateRequestBody sets the ValidateRequestBody field's value. +func (s *CreateRequestValidatorInput) SetValidateRequestBody(v bool) *CreateRequestValidatorInput { + s.ValidateRequestBody = &v + return s +} + +// SetValidateRequestParameters sets the ValidateRequestParameters field's value. +func (s *CreateRequestValidatorInput) SetValidateRequestParameters(v bool) *CreateRequestValidatorInput { + s.ValidateRequestParameters = &v + return s +} + // Requests Amazon API Gateway to create a Resource resource. type CreateResourceInput struct { _ struct{} `type:"structure"` @@ -9789,6 +12077,74 @@ func (s DeleteModelOutput) GoString() string { return s.String() } +// Deletes a specified RequestValidator of a given RestApi. +type DeleteRequestValidatorInput struct { + _ struct{} `type:"structure"` + + // [Required] The identifier of the RequestValidator to be deleted. + // + // RequestValidatorId is a required field + RequestValidatorId *string `location:"uri" locationName:"requestvalidator_id" type:"string" required:"true"` + + // [Required] The identifier of the RestApi from which the given RequestValidator + // is deleted. + // + // RestApiId is a required field + RestApiId *string `location:"uri" locationName:"restapi_id" type:"string" required:"true"` +} + +// String returns the string representation +func (s DeleteRequestValidatorInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DeleteRequestValidatorInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *DeleteRequestValidatorInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DeleteRequestValidatorInput"} + if s.RequestValidatorId == nil { + invalidParams.Add(request.NewErrParamRequired("RequestValidatorId")) + } + if s.RestApiId == nil { + invalidParams.Add(request.NewErrParamRequired("RestApiId")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetRequestValidatorId sets the RequestValidatorId field's value. +func (s *DeleteRequestValidatorInput) SetRequestValidatorId(v string) *DeleteRequestValidatorInput { + s.RequestValidatorId = &v + return s +} + +// SetRestApiId sets the RestApiId field's value. +func (s *DeleteRequestValidatorInput) SetRestApiId(v string) *DeleteRequestValidatorInput { + s.RestApiId = &v + return s +} + +type DeleteRequestValidatorOutput struct { + _ struct{} `type:"structure"` +} + +// String returns the string representation +func (s DeleteRequestValidatorOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DeleteRequestValidatorOutput) GoString() string { + return s.String() +} + // Request to delete a Resource. type DeleteResourceInput struct { _ struct{} `type:"structure"` @@ -10681,7 +13037,7 @@ type GetApiKeysInput struct { // The name of queried API keys. NameQuery *string `location:"querystring" locationName:"name" type:"string"` - // The position of the current ApiKeys resource to get information about. + // The current pagination position in the paged result set. Position *string `location:"querystring" locationName:"position" type:"string"` } @@ -10826,11 +13182,10 @@ func (s *GetAuthorizerInput) SetRestApiId(v string) *GetAuthorizerInput { type GetAuthorizersInput struct { _ struct{} `type:"structure"` - // Limit the number of Authorizer resources in the response. + // The maximum number of returned results per page. Limit *int64 `location:"querystring" locationName:"limit" type:"integer"` - // If not all Authorizer resources in the response were present, the position - // will specify where to start the next page of results. + // The current pagination position in the paged result set. Position *string `location:"querystring" locationName:"position" type:"string"` // The RestApi identifier for the Authorizers resource. @@ -10979,13 +13334,11 @@ type GetBasePathMappingsInput struct { // DomainName is a required field DomainName *string `location:"uri" locationName:"domain_name" type:"string" required:"true"` - // The maximum number of BasePathMapping resources in the collection to get - // information about. The default limit is 25. It should be an integer between - // 1 - 500. + // The maximum number of returned results per page. The value is 25 by default + // and could be between 1 - 500. Limit *int64 `location:"querystring" locationName:"limit" type:"integer"` - // The position of the current BasePathMapping resource in the collection to - // get information about. + // The current pagination position in the paged result set. Position *string `location:"querystring" locationName:"position" type:"string"` } @@ -11108,13 +13461,11 @@ func (s *GetClientCertificateInput) SetClientCertificateId(v string) *GetClientC type GetClientCertificatesInput struct { _ struct{} `type:"structure"` - // The maximum number of ClientCertificate resources in the collection to get - // information about. The default limit is 25. It should be an integer between - // 1 - 500. + // The maximum number of returned results per page. The value is 25 by default + // and could be between 1 - 500. Limit *int64 `location:"querystring" locationName:"limit" type:"integer"` - // The position of the current ClientCertificate resource in the collection - // to get information about. + // The current pagination position in the paged result set. Position *string `location:"querystring" locationName:"position" type:"string"` } @@ -11184,6 +13535,15 @@ type GetDeploymentInput struct { // DeploymentId is a required field DeploymentId *string `location:"uri" locationName:"deployment_id" type:"string" required:"true"` + // A query parameter to retrieve the specified embedded resources of the returned + // Deployment resource in the response. In a REST API call, this embed parameter + // value is a list of comma-separated strings, as in GET /restapis/{restapi_id}/deployments/{deployment_id}?embed=var1,var2. + // The SDK and other platform-dependent libraries might use a different format + // for the list. Currently, this request supports only retrieval of the embedded + // API summary this way. Hence, the parameter value must be a single-valued + // list containing only the "apisummary" string. For example, GET /restapis/{restapi_id}/deployments/{deployment_id}?embed=apisummary. + Embed []*string `location:"querystring" locationName:"embed" type:"list"` + // The identifier of the RestApi resource for the Deployment resource to get // information about. // @@ -11223,6 +13583,12 @@ func (s *GetDeploymentInput) SetDeploymentId(v string) *GetDeploymentInput { return s } +// SetEmbed sets the Embed field's value. +func (s *GetDeploymentInput) SetEmbed(v []*string) *GetDeploymentInput { + s.Embed = v + return s +} + // SetRestApiId sets the RestApiId field's value. func (s *GetDeploymentInput) SetRestApiId(v string) *GetDeploymentInput { s.RestApiId = &v @@ -11233,12 +13599,11 @@ func (s *GetDeploymentInput) SetRestApiId(v string) *GetDeploymentInput { type GetDeploymentsInput struct { _ struct{} `type:"structure"` - // The maximum number of Deployment resources in the collection to get information - // about. The default limit is 25. It should be an integer between 1 - 500. + // The maximum number of returned results per page. The value is 25 by default + // and could be between 1 - 500. Limit *int64 `location:"querystring" locationName:"limit" type:"integer"` - // The position of the current Deployment resource in the collection to get - // information about. + // The current pagination position in the paged result set. Position *string `location:"querystring" locationName:"position" type:"string"` // The identifier of the RestApi resource for the collection of Deployment resources @@ -11392,7 +13757,7 @@ func (s *GetDocumentationPartInput) SetRestApiId(v string) *GetDocumentationPart type GetDocumentationPartsInput struct { _ struct{} `type:"structure"` - // The size of the paged results. + // The maximum number of returned results per page. Limit *int64 `location:"querystring" locationName:"limit" type:"integer"` // The name of API entities of the to-be-retrieved documentation parts. @@ -11401,8 +13766,7 @@ type GetDocumentationPartsInput struct { // The path of API entities of the to-be-retrieved documentation parts. Path *string `location:"querystring" locationName:"path" type:"string"` - // The position of the to-be-retrieved documentation part in the DocumentationParts - // collection. + // The current pagination position in the paged result set. Position *string `location:"querystring" locationName:"position" type:"string"` // [Required] The identifier of the API of the to-be-retrieved documentation @@ -11567,11 +13931,10 @@ func (s *GetDocumentationVersionInput) SetRestApiId(v string) *GetDocumentationV type GetDocumentationVersionsInput struct { _ struct{} `type:"structure"` - // The page size of the returned documentation versions. + // The maximum number of returned results per page. Limit *int64 `location:"querystring" locationName:"limit" type:"integer"` - // The position of the returned DocumentationVersion in the DocumentationVersions - // collection. + // The current pagination position in the paged result set. Position *string `location:"querystring" locationName:"position" type:"string"` // [Required] The identifier of an API of the to-be-retrieved documentation @@ -11704,11 +14067,11 @@ func (s *GetDomainNameInput) SetDomainName(v string) *GetDomainNameInput { type GetDomainNamesInput struct { _ struct{} `type:"structure"` - // The maximum number of DomainName resources in the collection to get information - // about. The default limit is 25. It should be an integer between 1 - 500. + // The maximum number of returned results per page. The value is 25 by default + // and could be between 1 - 500. Limit *int64 `location:"querystring" locationName:"limit" type:"integer"` - // The position of the current domain names to get information about. + // The current pagination position in the paged result set. Position *string `location:"querystring" locationName:"position" type:"string"` } @@ -12349,12 +14712,11 @@ func (s *GetModelTemplateOutput) SetValue(v string) *GetModelTemplateOutput { type GetModelsInput struct { _ struct{} `type:"structure"` - // The maximum number of models in the collection to get information about. - // The default limit is 25. It should be an integer between 1 - 500. + // The maximum number of returned results per page. The value is 25 by default + // and could be between 1 - 500. Limit *int64 `location:"querystring" locationName:"limit" type:"integer"` - // The position of the next set of results in the Models resource to get information - // about. + // The current pagination position in the paged result set. Position *string `location:"querystring" locationName:"position" type:"string"` // The RestApi identifier. @@ -12438,10 +14800,168 @@ func (s *GetModelsOutput) SetPosition(v string) *GetModelsOutput { return s } +// Gets a RequestValidator of a given RestApi. +type GetRequestValidatorInput struct { + _ struct{} `type:"structure"` + + // [Required] The identifier of the RequestValidator to be retrieved. + // + // RequestValidatorId is a required field + RequestValidatorId *string `location:"uri" locationName:"requestvalidator_id" type:"string" required:"true"` + + // [Required] The identifier of the RestApi to which the specified RequestValidator + // belongs. + // + // RestApiId is a required field + RestApiId *string `location:"uri" locationName:"restapi_id" type:"string" required:"true"` +} + +// String returns the string representation +func (s GetRequestValidatorInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s GetRequestValidatorInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *GetRequestValidatorInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "GetRequestValidatorInput"} + if s.RequestValidatorId == nil { + invalidParams.Add(request.NewErrParamRequired("RequestValidatorId")) + } + if s.RestApiId == nil { + invalidParams.Add(request.NewErrParamRequired("RestApiId")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetRequestValidatorId sets the RequestValidatorId field's value. +func (s *GetRequestValidatorInput) SetRequestValidatorId(v string) *GetRequestValidatorInput { + s.RequestValidatorId = &v + return s +} + +// SetRestApiId sets the RestApiId field's value. +func (s *GetRequestValidatorInput) SetRestApiId(v string) *GetRequestValidatorInput { + s.RestApiId = &v + return s +} + +// Gets the RequestValidators collection of a given RestApi. +type GetRequestValidatorsInput struct { + _ struct{} `type:"structure"` + + // The maximum number of returned results per page. + Limit *int64 `location:"querystring" locationName:"limit" type:"integer"` + + // The current pagination position in the paged result set. + Position *string `location:"querystring" locationName:"position" type:"string"` + + // [Required] The identifier of a RestApi to which the RequestValidators collection + // belongs. + // + // RestApiId is a required field + RestApiId *string `location:"uri" locationName:"restapi_id" type:"string" required:"true"` +} + +// String returns the string representation +func (s GetRequestValidatorsInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s GetRequestValidatorsInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *GetRequestValidatorsInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "GetRequestValidatorsInput"} + if s.RestApiId == nil { + invalidParams.Add(request.NewErrParamRequired("RestApiId")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetLimit sets the Limit field's value. +func (s *GetRequestValidatorsInput) SetLimit(v int64) *GetRequestValidatorsInput { + s.Limit = &v + return s +} + +// SetPosition sets the Position field's value. +func (s *GetRequestValidatorsInput) SetPosition(v string) *GetRequestValidatorsInput { + s.Position = &v + return s +} + +// SetRestApiId sets the RestApiId field's value. +func (s *GetRequestValidatorsInput) SetRestApiId(v string) *GetRequestValidatorsInput { + s.RestApiId = &v + return s +} + +// A collection of RequestValidator resources of a given RestApi. +// +// In Swagger, the RequestValidators of an API is defined by the x-amazon-apigateway-request-validators +// (http://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-swagger-extensions.html#api-gateway-swagger-extensions-request-validators.html) +// extension. +// +// Enable Basic Request Validation in API Gateway (http://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-method-request-validation.html) +type GetRequestValidatorsOutput struct { + _ struct{} `type:"structure"` + + // The current page of RequestValidator resources in the RequestValidators collection. + Items []*UpdateRequestValidatorOutput `locationName:"item" type:"list"` + + Position *string `locationName:"position" type:"string"` +} + +// String returns the string representation +func (s GetRequestValidatorsOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s GetRequestValidatorsOutput) GoString() string { + return s.String() +} + +// SetItems sets the Items field's value. +func (s *GetRequestValidatorsOutput) SetItems(v []*UpdateRequestValidatorOutput) *GetRequestValidatorsOutput { + s.Items = v + return s +} + +// SetPosition sets the Position field's value. +func (s *GetRequestValidatorsOutput) SetPosition(v string) *GetRequestValidatorsOutput { + s.Position = &v + return s +} + // Request to list information about a resource. type GetResourceInput struct { _ struct{} `type:"structure"` + // A query parameter to retrieve the specified resources embedded in the returned + // Resource representation in the response. This embed parameter value is a + // list of comma-separated strings. Currently, the request supports only retrieval + // of the embedded Method resources this way. The query parameter value must + // be a single-valued list and contain the "methods" string. For example, GET + // /restapis/{restapi_id}/resources/{resource_id}?embed=methods. + Embed []*string `location:"querystring" locationName:"embed" type:"list"` + // The identifier for the Resource resource. // // ResourceId is a required field @@ -12479,6 +14999,12 @@ func (s *GetResourceInput) Validate() error { return nil } +// SetEmbed sets the Embed field's value. +func (s *GetResourceInput) SetEmbed(v []*string) *GetResourceInput { + s.Embed = v + return s +} + // SetResourceId sets the ResourceId field's value. func (s *GetResourceInput) SetResourceId(v string) *GetResourceInput { s.ResourceId = &v @@ -12495,12 +15021,19 @@ func (s *GetResourceInput) SetRestApiId(v string) *GetResourceInput { type GetResourcesInput struct { _ struct{} `type:"structure"` - // The maximum number of Resource resources in the collection to get information - // about. The default limit is 25. It should be an integer between 1 - 500. + // A query parameter used to retrieve the specified resources embedded in the + // returned Resources resource in the response. This embed parameter value is + // a list of comma-separated strings. Currently, the request supports only retrieval + // of the embedded Method resources this way. The query parameter value must + // be a single-valued list and contain the "methods" string. For example, GET + // /restapis/{restapi_id}/resources?embed=methods. + Embed []*string `location:"querystring" locationName:"embed" type:"list"` + + // The maximum number of returned results per page. The value is 25 by default + // and could be between 1 - 500. Limit *int64 `location:"querystring" locationName:"limit" type:"integer"` - // The position of the next set of results in the current Resources resource - // to get information about. + // The current pagination position in the paged result set. Position *string `location:"querystring" locationName:"position" type:"string"` // The RestApi identifier for the Resource. @@ -12532,6 +15065,12 @@ func (s *GetResourcesInput) Validate() error { return nil } +// SetEmbed sets the Embed field's value. +func (s *GetResourcesInput) SetEmbed(v []*string) *GetResourcesInput { + s.Embed = v + return s +} + // SetLimit sets the Limit field's value. func (s *GetResourcesInput) SetLimit(v int64) *GetResourcesInput { s.Limit = &v @@ -12627,12 +15166,11 @@ func (s *GetRestApiInput) SetRestApiId(v string) *GetRestApiInput { type GetRestApisInput struct { _ struct{} `type:"structure"` - // The maximum number of RestApi resources in the collection to get information - // about. The default limit is 25. It should be an integer between 1 - 500. + // The maximum number of returned results per page. The value is 25 by default + // and could be between 1 - 500. Limit *int64 `location:"querystring" locationName:"limit" type:"integer"` - // The position of the current RestApis resource in the collection to get information - // about. + // The current pagination position in the paged result set. Position *string `location:"querystring" locationName:"position" type:"string"` } @@ -12858,10 +15396,10 @@ func (s *GetSdkTypeInput) SetId(v string) *GetSdkTypeInput { type GetSdkTypesInput struct { _ struct{} `type:"structure"` - // The maximum number of SdkType instances to be returned. + // The maximum number of returned results per page. Limit *int64 `location:"querystring" locationName:"limit" type:"integer"` - // The position of the last fetched element in the SdkTypes collection. + // The current pagination position in the paged result set. Position *string `location:"querystring" locationName:"position" type:"string"` } @@ -13060,10 +15598,10 @@ type GetUsageInput struct { // The Id of the API key associated with the resultant usage data. KeyId *string `location:"querystring" locationName:"keyId" type:"string"` - // The maximum number of results to be returned. + // The maximum number of returned results per page. Limit *int64 `location:"querystring" locationName:"limit" type:"integer"` - // Position + // The current pagination position in the paged result set. Position *string `location:"querystring" locationName:"position" type:"string"` // The starting date (e.g., 2016-01-01) of the usage data. @@ -13241,15 +15779,13 @@ func (s *GetUsagePlanKeyInput) SetUsagePlanId(v string) *GetUsagePlanKeyInput { type GetUsagePlanKeysInput struct { _ struct{} `type:"structure"` - // A query parameter specifying the maximum number usage plan keys returned - // by the GET request. + // The maximum number of returned results per page. Limit *int64 `location:"querystring" locationName:"limit" type:"integer"` // A query parameter specifying the name of the to-be-returned usage plan keys. NameQuery *string `location:"querystring" locationName:"name" type:"string"` - // A query parameter specifying the zero-based index specifying the position - // of a usage plan key. + // The current pagination position in the paged result set. Position *string `location:"querystring" locationName:"position" type:"string"` // The Id of the UsagePlan resource representing the usage plan containing the @@ -13348,11 +15884,10 @@ type GetUsagePlansInput struct { // The identifier of the API key associated with the usage plans. KeyId *string `location:"querystring" locationName:"keyId" type:"string"` - // The number of UsagePlan resources to be returned as the result. + // The maximum number of returned results per page. Limit *int64 `location:"querystring" locationName:"limit" type:"integer"` - // The zero-based array index specifying the position of the to-be-retrieved - // UsagePlan resource. + // The current pagination position in the paged result set. Position *string `location:"querystring" locationName:"position" type:"string"` } @@ -14058,7 +16593,9 @@ type Method struct { // method. ApiKeyRequired *bool `locationName:"apiKeyRequired" type:"boolean"` - // The method's authorization type. + // The method's authorization type. Valid values are NONE for open access, AWS_IAM + // for using AWS IAM permissions, CUSTOM for using a custom authorizer, or COGNITO_USER_POOLS + // for using a Cognito user pool. AuthorizationType *string `locationName:"authorizationType" type:"string"` // The identifier of an Authorizer to use on this method. The authorizationType @@ -14159,6 +16696,9 @@ type Method struct { // parameter names defined here are available in Integration to be mapped to // integration request parameters or templates. RequestParameters map[string]*bool `locationName:"requestParameters" type:"map"` + + // The identifier of a RequestValidator for request validation. + RequestValidatorId *string `locationName:"requestValidatorId" type:"string"` } // String returns the string representation @@ -14225,6 +16765,12 @@ func (s *Method) SetRequestParameters(v map[string]*bool) *Method { return s } +// SetRequestValidatorId sets the RequestValidatorId field's value. +func (s *Method) SetRequestValidatorId(v string) *Method { + s.RequestValidatorId = &v + return s +} + // Represents a method response of a given HTTP status code returned to the // client. The method response is passed from the back end through the associated // integration response that can be transformed using a mapping template. @@ -14437,7 +16983,9 @@ type MethodSnapshot struct { // Specifies whether the method requires a valid ApiKey. ApiKeyRequired *bool `locationName:"apiKeyRequired" type:"boolean"` - // Specifies the type of authorization used for the method. + // The method's authorization type. Valid values are NONE for open access, AWS_IAM + // for using AWS IAM permissions, CUSTOM for using a custom authorizer, or COGNITO_USER_POOLS + // for using a Cognito user pool. AuthorizationType *string `locationName:"authorizationType" type:"string"` } @@ -14564,7 +17112,10 @@ type PatchOperation struct { // op operation can have only one path associated with it. Path *string `locationName:"path" type:"string"` - // The new target value of the update operation. + // The new target value of the update operation. When using AWS CLI to update + // a property of a JSON value, enclose the JSON object with a pair of single + // quotes in a Linux shell, e.g., '{"a": ...}'. In a Windows shell, see Using + // JSON for Parameters (http://docs.aws.amazon.com/cli/latest/userguide/cli-using-param.html#cli-using-param-json). Value *string `locationName:"value" type:"string"` } @@ -14945,7 +17496,9 @@ type PutMethodInput struct { // Specifies whether the method required a valid ApiKey. ApiKeyRequired *bool `locationName:"apiKeyRequired" type:"boolean"` - // Specifies the type of authorization used for the method. + // The method's authorization type. Valid values are NONE for open access, AWS_IAM + // for using AWS IAM permissions, CUSTOM for using a custom authorizer, or COGNITO_USER_POOLS + // for using a Cognito user pool. // // AuthorizationType is a required field AuthorizationType *string `locationName:"authorizationType" type:"string" required:"true"` @@ -14979,6 +17532,9 @@ type PutMethodInput struct { // integration request parameters or body-mapping templates. RequestParameters map[string]*bool `locationName:"requestParameters" type:"map"` + // The identifier of a RequestValidator for validating the method request. + RequestValidatorId *string `locationName:"requestValidatorId" type:"string"` + // The Resource identifier for the new Method resource. // // ResourceId is a required field @@ -15064,6 +17620,12 @@ func (s *PutMethodInput) SetRequestParameters(v map[string]*bool) *PutMethodInpu return s } +// SetRequestValidatorId sets the RequestValidatorId field's value. +func (s *PutMethodInput) SetRequestValidatorId(v string) *PutMethodInput { + s.RequestValidatorId = &v + return s +} + // SetResourceId sets the ResourceId field's value. func (s *PutMethodInput) SetResourceId(v string) *PutMethodInput { s.ResourceId = &v @@ -15345,8 +17907,8 @@ type Resource struct { // Request // // GET /restapis/fugvjdxtri/resources/3kzxbg5sa2/methods/GET HTTP/1.1 Content-Type: - // application/json Host: apigateway.us-east-1.amazonaws.com X-Amz-Date: 20160608T031827Z - // Authorization: AWS4-HMAC-SHA256 Credential={access_key_ID}/20160608/us-east-1/apigateway/aws4_request, + // application/json Host: apigateway.us-east-1.amazonaws.com X-Amz-Date: 20170223T031827Z + // Authorization: AWS4-HMAC-SHA256 Credential={access_key_ID}/20170223/us-east-1/apigateway/aws4_request, // SignedHeaders=content-type;host;x-amz-date, Signature={sig4_hash} // Response // @@ -17077,6 +19639,131 @@ func (s *UpdateModelInput) SetRestApiId(v string) *UpdateModelInput { return s } +// Updates a RequestValidator of a given RestApi. +type UpdateRequestValidatorInput struct { + _ struct{} `type:"structure"` + + // A list of update operations to be applied to the specified resource and in + // the order specified in this list. + PatchOperations []*PatchOperation `locationName:"patchOperations" type:"list"` + + // [Required] The identifier of RequestValidator to be updated. + // + // RequestValidatorId is a required field + RequestValidatorId *string `location:"uri" locationName:"requestvalidator_id" type:"string" required:"true"` + + // [Required] The identifier of the RestApi for which the given RequestValidator + // is updated. + // + // RestApiId is a required field + RestApiId *string `location:"uri" locationName:"restapi_id" type:"string" required:"true"` +} + +// String returns the string representation +func (s UpdateRequestValidatorInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s UpdateRequestValidatorInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *UpdateRequestValidatorInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "UpdateRequestValidatorInput"} + if s.RequestValidatorId == nil { + invalidParams.Add(request.NewErrParamRequired("RequestValidatorId")) + } + if s.RestApiId == nil { + invalidParams.Add(request.NewErrParamRequired("RestApiId")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetPatchOperations sets the PatchOperations field's value. +func (s *UpdateRequestValidatorInput) SetPatchOperations(v []*PatchOperation) *UpdateRequestValidatorInput { + s.PatchOperations = v + return s +} + +// SetRequestValidatorId sets the RequestValidatorId field's value. +func (s *UpdateRequestValidatorInput) SetRequestValidatorId(v string) *UpdateRequestValidatorInput { + s.RequestValidatorId = &v + return s +} + +// SetRestApiId sets the RestApiId field's value. +func (s *UpdateRequestValidatorInput) SetRestApiId(v string) *UpdateRequestValidatorInput { + s.RestApiId = &v + return s +} + +// A set of validation rules for incoming Method requests. +// +// In Swagger, a RequestValidator of an API is defined by the x-amazon-apigateway-request-validators.requestValidator +// (http://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-swagger-extensions.html#api-gateway-swagger-extensions-request-validators.requestValidator.html) +// object. It the referenced using the x-amazon-apigateway-request-validator +// (http://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-swagger-extensions.html#api-gateway-swagger-extensions-request-validator) +// property. +// +// Enable Basic Request Validation in API Gateway (http://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-method-request-validation.html) +type UpdateRequestValidatorOutput struct { + _ struct{} `type:"structure"` + + // The identifier of this RequestValidator. + Id *string `locationName:"id" type:"string"` + + // The name of this RequestValidator + Name *string `locationName:"name" type:"string"` + + // A Boolean flag to indicate whether to validate a request body according to + // the configured Model schema. + ValidateRequestBody *bool `locationName:"validateRequestBody" type:"boolean"` + + // A Boolean flag to indicate whether to validate request parameters (true) + // or not (false). + ValidateRequestParameters *bool `locationName:"validateRequestParameters" type:"boolean"` +} + +// String returns the string representation +func (s UpdateRequestValidatorOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s UpdateRequestValidatorOutput) GoString() string { + return s.String() +} + +// SetId sets the Id field's value. +func (s *UpdateRequestValidatorOutput) SetId(v string) *UpdateRequestValidatorOutput { + s.Id = &v + return s +} + +// SetName sets the Name field's value. +func (s *UpdateRequestValidatorOutput) SetName(v string) *UpdateRequestValidatorOutput { + s.Name = &v + return s +} + +// SetValidateRequestBody sets the ValidateRequestBody field's value. +func (s *UpdateRequestValidatorOutput) SetValidateRequestBody(v bool) *UpdateRequestValidatorOutput { + s.ValidateRequestBody = &v + return s +} + +// SetValidateRequestParameters sets the ValidateRequestParameters field's value. +func (s *UpdateRequestValidatorOutput) SetValidateRequestParameters(v bool) *UpdateRequestValidatorOutput { + s.ValidateRequestParameters = &v + return s +} + // Request to change information about a Resource resource. type UpdateResourceInput struct { _ struct{} `type:"structure"` diff --git a/vendor/github.com/aws/aws-sdk-go/service/apigateway/doc.go b/vendor/github.com/aws/aws-sdk-go/service/apigateway/doc.go new file mode 100644 index 000000000..c05d3cdc3 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/service/apigateway/doc.go @@ -0,0 +1,82 @@ +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. + +// Package apigateway provides the client and types for making API +// requests to Amazon API Gateway. +// +// Amazon API Gateway helps developers deliver robust, secure, and scalable +// mobile and web application back ends. Amazon API Gateway allows developers +// to securely connect mobile and web applications to APIs that run on AWS Lambda, +// Amazon EC2, or other publicly addressable web services that are hosted outside +// of AWS. +// +// See apigateway package documentation for more information. +// https://docs.aws.amazon.com/sdk-for-go/api/service/apigateway/ +// +// Using the Client +// +// To use the client for Amazon API Gateway you will first need +// to create a new instance of it. +// +// When creating a client for an AWS service you'll first need to have a Session +// already created. The Session provides configuration that can be shared +// between multiple service clients. Additional configuration can be applied to +// the Session and service's client when they are constructed. The aws package's +// Config type contains several fields such as Region for the AWS Region the +// client should make API requests too. The optional Config value can be provided +// as the variadic argument for Sessions and client creation. +// +// Once the service's client is created you can use it to make API requests the +// AWS service. These clients are safe to use concurrently. +// +// // Create a session to share configuration, and load external configuration. +// sess := session.Must(session.NewSession()) +// +// // Create the service's client with the session. +// svc := apigateway.New(sess) +// +// See the SDK's documentation for more information on how to use service clients. +// https://docs.aws.amazon.com/sdk-for-go/api/ +// +// See aws package's Config type for more information on configuration options. +// https://docs.aws.amazon.com/sdk-for-go/api/aws/#Config +// +// See the Amazon API Gateway client APIGateway for more +// information on creating the service's client. +// https://docs.aws.amazon.com/sdk-for-go/api/service/apigateway/#New +// +// Once the client is created you can make an API request to the service. +// Each API method takes a input parameter, and returns the service response +// and an error. +// +// The API method will document which error codes the service can be returned +// by the operation if the service models the API operation's errors. These +// errors will also be available as const strings prefixed with "ErrCode". +// +// result, err := svc.CreateApiKey(params) +// if err != nil { +// // Cast err to awserr.Error to handle specific error codes. +// aerr, ok := err.(awserr.Error) +// if ok && aerr.Code() == { +// // Specific error code handling +// } +// return err +// } +// +// fmt.Println("CreateApiKey result:") +// fmt.Println(result) +// +// Using the Client with Context +// +// The service's client also provides methods to make API requests with a Context +// value. This allows you to control the timeout, and cancellation of pending +// requests. These methods also take request Option as variadic parameter to apply +// additional configuration to the API request. +// +// ctx := context.Background() +// +// result, err := svc.CreateApiKeyWithContext(ctx, params) +// +// See the request package documentation for more information on using Context pattern +// with the SDK. +// https://docs.aws.amazon.com/sdk-for-go/api/aws/request/ +package apigateway diff --git a/vendor/github.com/aws/aws-sdk-go/service/apigateway/errors.go b/vendor/github.com/aws/aws-sdk-go/service/apigateway/errors.go index b06644b71..b8f2efc29 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/apigateway/errors.go +++ b/vendor/github.com/aws/aws-sdk-go/service/apigateway/errors.go @@ -1,4 +1,4 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. package apigateway diff --git a/vendor/github.com/aws/aws-sdk-go/service/apigateway/service.go b/vendor/github.com/aws/aws-sdk-go/service/apigateway/service.go index 052f84a69..690b6b2f3 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/apigateway/service.go +++ b/vendor/github.com/aws/aws-sdk-go/service/apigateway/service.go @@ -1,4 +1,4 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. package apigateway @@ -11,13 +11,12 @@ import ( "github.com/aws/aws-sdk-go/private/protocol/restjson" ) -// Amazon API Gateway helps developers deliver robust, secure, and scalable -// mobile and web application back ends. Amazon API Gateway allows developers -// to securely connect mobile and web applications to APIs that run on AWS Lambda, -// Amazon EC2, or other publicly addressable web services that are hosted outside -// of AWS. -// The service client's operations are safe to be used concurrently. -// It is not safe to mutate any of the client's properties though. +// APIGateway provides the API operation methods for making requests to +// Amazon API Gateway. See this package's package overview docs +// for details on the service. +// +// APIGateway methods are safe to use concurrently. It is not safe to +// modify mutate any of the struct's properties though. type APIGateway struct { *client.Client } diff --git a/vendor/github.com/aws/aws-sdk-go/service/applicationautoscaling/api.go b/vendor/github.com/aws/aws-sdk-go/service/applicationautoscaling/api.go index ba6abe54f..a40f52ca5 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/applicationautoscaling/api.go +++ b/vendor/github.com/aws/aws-sdk-go/service/applicationautoscaling/api.go @@ -1,12 +1,12 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. -// Package applicationautoscaling provides a client for Application Auto Scaling. package applicationautoscaling import ( "fmt" "time" + "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awsutil" "github.com/aws/aws-sdk-go/aws/request" ) @@ -94,8 +94,23 @@ func (c *ApplicationAutoScaling) DeleteScalingPolicyRequest(input *DeleteScaling // Please also see https://docs.aws.amazon.com/goto/WebAPI/application-autoscaling-2016-02-06/DeleteScalingPolicy func (c *ApplicationAutoScaling) DeleteScalingPolicy(input *DeleteScalingPolicyInput) (*DeleteScalingPolicyOutput, error) { req, out := c.DeleteScalingPolicyRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteScalingPolicyWithContext is the same as DeleteScalingPolicy with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteScalingPolicy 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 *ApplicationAutoScaling) DeleteScalingPolicyWithContext(ctx aws.Context, input *DeleteScalingPolicyInput, opts ...request.Option) (*DeleteScalingPolicyOutput, error) { + req, out := c.DeleteScalingPolicyRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeregisterScalableTarget = "DeregisterScalableTarget" @@ -180,8 +195,23 @@ func (c *ApplicationAutoScaling) DeregisterScalableTargetRequest(input *Deregist // Please also see https://docs.aws.amazon.com/goto/WebAPI/application-autoscaling-2016-02-06/DeregisterScalableTarget func (c *ApplicationAutoScaling) DeregisterScalableTarget(input *DeregisterScalableTargetInput) (*DeregisterScalableTargetOutput, error) { req, out := c.DeregisterScalableTargetRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeregisterScalableTargetWithContext is the same as DeregisterScalableTarget with the addition of +// the ability to pass a context and additional request options. +// +// See DeregisterScalableTarget 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 *ApplicationAutoScaling) DeregisterScalableTargetWithContext(ctx aws.Context, input *DeregisterScalableTargetInput, opts ...request.Option) (*DeregisterScalableTargetOutput, error) { + req, out := c.DeregisterScalableTargetRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeScalableTargets = "DescribeScalableTargets" @@ -269,8 +299,23 @@ func (c *ApplicationAutoScaling) DescribeScalableTargetsRequest(input *DescribeS // Please also see https://docs.aws.amazon.com/goto/WebAPI/application-autoscaling-2016-02-06/DescribeScalableTargets func (c *ApplicationAutoScaling) DescribeScalableTargets(input *DescribeScalableTargetsInput) (*DescribeScalableTargetsOutput, error) { req, out := c.DescribeScalableTargetsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeScalableTargetsWithContext is the same as DescribeScalableTargets with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeScalableTargets 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 *ApplicationAutoScaling) DescribeScalableTargetsWithContext(ctx aws.Context, input *DescribeScalableTargetsInput, opts ...request.Option) (*DescribeScalableTargetsOutput, error) { + req, out := c.DescribeScalableTargetsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // DescribeScalableTargetsPages iterates over the pages of a DescribeScalableTargets operation, @@ -290,12 +335,37 @@ func (c *ApplicationAutoScaling) DescribeScalableTargets(input *DescribeScalable // return pageNum <= 3 // }) // -func (c *ApplicationAutoScaling) DescribeScalableTargetsPages(input *DescribeScalableTargetsInput, fn func(p *DescribeScalableTargetsOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.DescribeScalableTargetsRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*DescribeScalableTargetsOutput), lastPage) - }) +func (c *ApplicationAutoScaling) DescribeScalableTargetsPages(input *DescribeScalableTargetsInput, fn func(*DescribeScalableTargetsOutput, bool) bool) error { + return c.DescribeScalableTargetsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// DescribeScalableTargetsPagesWithContext same as DescribeScalableTargetsPages 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 *ApplicationAutoScaling) DescribeScalableTargetsPagesWithContext(ctx aws.Context, input *DescribeScalableTargetsInput, fn func(*DescribeScalableTargetsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *DescribeScalableTargetsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeScalableTargetsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*DescribeScalableTargetsOutput), !p.HasNextPage()) + } + return p.Err() } const opDescribeScalingActivities = "DescribeScalingActivities" @@ -384,8 +454,23 @@ func (c *ApplicationAutoScaling) DescribeScalingActivitiesRequest(input *Describ // Please also see https://docs.aws.amazon.com/goto/WebAPI/application-autoscaling-2016-02-06/DescribeScalingActivities func (c *ApplicationAutoScaling) DescribeScalingActivities(input *DescribeScalingActivitiesInput) (*DescribeScalingActivitiesOutput, error) { req, out := c.DescribeScalingActivitiesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeScalingActivitiesWithContext is the same as DescribeScalingActivities with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeScalingActivities 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 *ApplicationAutoScaling) DescribeScalingActivitiesWithContext(ctx aws.Context, input *DescribeScalingActivitiesInput, opts ...request.Option) (*DescribeScalingActivitiesOutput, error) { + req, out := c.DescribeScalingActivitiesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // DescribeScalingActivitiesPages iterates over the pages of a DescribeScalingActivities operation, @@ -405,12 +490,37 @@ func (c *ApplicationAutoScaling) DescribeScalingActivities(input *DescribeScalin // return pageNum <= 3 // }) // -func (c *ApplicationAutoScaling) DescribeScalingActivitiesPages(input *DescribeScalingActivitiesInput, fn func(p *DescribeScalingActivitiesOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.DescribeScalingActivitiesRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*DescribeScalingActivitiesOutput), lastPage) - }) +func (c *ApplicationAutoScaling) DescribeScalingActivitiesPages(input *DescribeScalingActivitiesInput, fn func(*DescribeScalingActivitiesOutput, bool) bool) error { + return c.DescribeScalingActivitiesPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// DescribeScalingActivitiesPagesWithContext same as DescribeScalingActivitiesPages 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 *ApplicationAutoScaling) DescribeScalingActivitiesPagesWithContext(ctx aws.Context, input *DescribeScalingActivitiesInput, fn func(*DescribeScalingActivitiesOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *DescribeScalingActivitiesInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeScalingActivitiesRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*DescribeScalingActivitiesOutput), !p.HasNextPage()) + } + return p.Err() } const opDescribeScalingPolicies = "DescribeScalingPolicies" @@ -507,8 +617,23 @@ func (c *ApplicationAutoScaling) DescribeScalingPoliciesRequest(input *DescribeS // Please also see https://docs.aws.amazon.com/goto/WebAPI/application-autoscaling-2016-02-06/DescribeScalingPolicies func (c *ApplicationAutoScaling) DescribeScalingPolicies(input *DescribeScalingPoliciesInput) (*DescribeScalingPoliciesOutput, error) { req, out := c.DescribeScalingPoliciesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeScalingPoliciesWithContext is the same as DescribeScalingPolicies with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeScalingPolicies 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 *ApplicationAutoScaling) DescribeScalingPoliciesWithContext(ctx aws.Context, input *DescribeScalingPoliciesInput, opts ...request.Option) (*DescribeScalingPoliciesOutput, error) { + req, out := c.DescribeScalingPoliciesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // DescribeScalingPoliciesPages iterates over the pages of a DescribeScalingPolicies operation, @@ -528,12 +653,37 @@ func (c *ApplicationAutoScaling) DescribeScalingPolicies(input *DescribeScalingP // return pageNum <= 3 // }) // -func (c *ApplicationAutoScaling) DescribeScalingPoliciesPages(input *DescribeScalingPoliciesInput, fn func(p *DescribeScalingPoliciesOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.DescribeScalingPoliciesRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*DescribeScalingPoliciesOutput), lastPage) - }) +func (c *ApplicationAutoScaling) DescribeScalingPoliciesPages(input *DescribeScalingPoliciesInput, fn func(*DescribeScalingPoliciesOutput, bool) bool) error { + return c.DescribeScalingPoliciesPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// DescribeScalingPoliciesPagesWithContext same as DescribeScalingPoliciesPages 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 *ApplicationAutoScaling) DescribeScalingPoliciesPagesWithContext(ctx aws.Context, input *DescribeScalingPoliciesInput, fn func(*DescribeScalingPoliciesOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *DescribeScalingPoliciesInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeScalingPoliciesRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*DescribeScalingPoliciesOutput), !p.HasNextPage()) + } + return p.Err() } const opPutScalingPolicy = "PutScalingPolicy" @@ -630,8 +780,23 @@ func (c *ApplicationAutoScaling) PutScalingPolicyRequest(input *PutScalingPolicy // Please also see https://docs.aws.amazon.com/goto/WebAPI/application-autoscaling-2016-02-06/PutScalingPolicy func (c *ApplicationAutoScaling) PutScalingPolicy(input *PutScalingPolicyInput) (*PutScalingPolicyOutput, error) { req, out := c.PutScalingPolicyRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// PutScalingPolicyWithContext is the same as PutScalingPolicy with the addition of +// the ability to pass a context and additional request options. +// +// See PutScalingPolicy 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 *ApplicationAutoScaling) PutScalingPolicyWithContext(ctx aws.Context, input *PutScalingPolicyInput, opts ...request.Option) (*PutScalingPolicyOutput, error) { + req, out := c.PutScalingPolicyRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opRegisterScalableTarget = "RegisterScalableTarget" @@ -716,8 +881,23 @@ func (c *ApplicationAutoScaling) RegisterScalableTargetRequest(input *RegisterSc // Please also see https://docs.aws.amazon.com/goto/WebAPI/application-autoscaling-2016-02-06/RegisterScalableTarget func (c *ApplicationAutoScaling) RegisterScalableTarget(input *RegisterScalableTargetInput) (*RegisterScalableTargetOutput, error) { req, out := c.RegisterScalableTargetRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// RegisterScalableTargetWithContext is the same as RegisterScalableTarget with the addition of +// the ability to pass a context and additional request options. +// +// See RegisterScalableTarget 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 *ApplicationAutoScaling) RegisterScalableTargetWithContext(ctx aws.Context, input *RegisterScalableTargetInput, opts ...request.Option) (*RegisterScalableTargetOutput, error) { + req, out := c.RegisterScalableTargetRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // Represents a CloudWatch alarm associated with a scaling policy. @@ -779,6 +959,9 @@ type DeleteScalingPolicyInput struct { // * EMR cluster - The resource type is instancegroup and the unique identifier // is the cluster ID and instance group ID. Example: instancegroup/j-2EEZNYKUA1NTV/ig-1791Y4E1L8YI0. // + // * AppStream 2.0 fleet - The resource type is fleet and the unique identifier + // is the fleet name. Example: fleet/sample-fleet. + // // ResourceId is a required field ResourceId *string `min:"1" type:"string" required:"true"` @@ -793,6 +976,9 @@ type DeleteScalingPolicyInput struct { // * elasticmapreduce:instancegroup:InstanceCount - The instance count of // an EMR Instance Group. // + // * appstream:fleet:DesiredCapacity - The desired capacity of an AppStream + // 2.0 fleet. + // // ScalableDimension is a required field ScalableDimension *string `type:"string" required:"true" enum:"ScalableDimension"` @@ -897,6 +1083,9 @@ type DeregisterScalableTargetInput struct { // * EMR cluster - The resource type is instancegroup and the unique identifier // is the cluster ID and instance group ID. Example: instancegroup/j-2EEZNYKUA1NTV/ig-1791Y4E1L8YI0. // + // * AppStream 2.0 fleet - The resource type is fleet and the unique identifier + // is the fleet name. Example: fleet/sample-fleet. + // // ResourceId is a required field ResourceId *string `min:"1" type:"string" required:"true"` @@ -911,6 +1100,9 @@ type DeregisterScalableTargetInput struct { // * elasticmapreduce:instancegroup:InstanceCount - The instance count of // an EMR Instance Group. // + // * appstream:fleet:DesiredCapacity - The desired capacity of an AppStream + // 2.0 fleet. + // // ScalableDimension is a required field ScalableDimension *string `type:"string" required:"true" enum:"ScalableDimension"` @@ -1015,6 +1207,9 @@ type DescribeScalableTargetsInput struct { // // * EMR cluster - The resource type is instancegroup and the unique identifier // is the cluster ID and instance group ID. Example: instancegroup/j-2EEZNYKUA1NTV/ig-1791Y4E1L8YI0. + // + // * AppStream 2.0 fleet - The resource type is fleet and the unique identifier + // is the fleet name. Example: fleet/sample-fleet. ResourceIds []*string `type:"list"` // The scalable dimension associated with the scalable target. This string consists @@ -1028,6 +1223,9 @@ type DescribeScalableTargetsInput struct { // // * elasticmapreduce:instancegroup:InstanceCount - The instance count of // an EMR Instance Group. + // + // * appstream:fleet:DesiredCapacity - The desired capacity of an AppStream + // 2.0 fleet. ScalableDimension *string `type:"string" enum:"ScalableDimension"` // The namespace of the AWS service. For more information, see AWS Service Namespaces @@ -1153,6 +1351,9 @@ type DescribeScalingActivitiesInput struct { // // * EMR cluster - The resource type is instancegroup and the unique identifier // is the cluster ID and instance group ID. Example: instancegroup/j-2EEZNYKUA1NTV/ig-1791Y4E1L8YI0. + // + // * AppStream 2.0 fleet - The resource type is fleet and the unique identifier + // is the fleet name. Example: fleet/sample-fleet. ResourceId *string `min:"1" type:"string"` // The scalable dimension. This string consists of the service namespace, resource @@ -1166,6 +1367,9 @@ type DescribeScalingActivitiesInput struct { // // * elasticmapreduce:instancegroup:InstanceCount - The instance count of // an EMR Instance Group. + // + // * appstream:fleet:DesiredCapacity - The desired capacity of an AppStream + // 2.0 fleet. ScalableDimension *string `type:"string" enum:"ScalableDimension"` // The namespace of the AWS service. For more information, see AWS Service Namespaces @@ -1297,6 +1501,9 @@ type DescribeScalingPoliciesInput struct { // // * EMR cluster - The resource type is instancegroup and the unique identifier // is the cluster ID and instance group ID. Example: instancegroup/j-2EEZNYKUA1NTV/ig-1791Y4E1L8YI0. + // + // * AppStream 2.0 fleet - The resource type is fleet and the unique identifier + // is the fleet name. Example: fleet/sample-fleet. ResourceId *string `min:"1" type:"string"` // The scalable dimension. This string consists of the service namespace, resource @@ -1310,6 +1517,9 @@ type DescribeScalingPoliciesInput struct { // // * elasticmapreduce:instancegroup:InstanceCount - The instance count of // an EMR Instance Group. + // + // * appstream:fleet:DesiredCapacity - The desired capacity of an AppStream + // 2.0 fleet. ScalableDimension *string `type:"string" enum:"ScalableDimension"` // The namespace of the AWS service. For more information, see AWS Service Namespaces @@ -1441,6 +1651,9 @@ type PutScalingPolicyInput struct { // * EMR cluster - The resource type is instancegroup and the unique identifier // is the cluster ID and instance group ID. Example: instancegroup/j-2EEZNYKUA1NTV/ig-1791Y4E1L8YI0. // + // * AppStream 2.0 fleet - The resource type is fleet and the unique identifier + // is the fleet name. Example: fleet/sample-fleet. + // // ResourceId is a required field ResourceId *string `min:"1" type:"string" required:"true"` @@ -1455,6 +1668,9 @@ type PutScalingPolicyInput struct { // * elasticmapreduce:instancegroup:InstanceCount - The instance count of // an EMR Instance Group. // + // * appstream:fleet:DesiredCapacity - The desired capacity of an AppStream + // 2.0 fleet. + // // ScalableDimension is a required field ScalableDimension *string `type:"string" required:"true" enum:"ScalableDimension"` @@ -1603,6 +1819,9 @@ type RegisterScalableTargetInput struct { // * EMR cluster - The resource type is instancegroup and the unique identifier // is the cluster ID and instance group ID. Example: instancegroup/j-2EEZNYKUA1NTV/ig-1791Y4E1L8YI0. // + // * AppStream 2.0 fleet - The resource type is fleet and the unique identifier + // is the fleet name. Example: fleet/sample-fleet. + // // ResourceId is a required field ResourceId *string `min:"1" type:"string" required:"true"` @@ -1622,6 +1841,9 @@ type RegisterScalableTargetInput struct { // * elasticmapreduce:instancegroup:InstanceCount - The instance count of // an EMR Instance Group. // + // * appstream:fleet:DesiredCapacity - The desired capacity of an AppStream + // 2.0 fleet. + // // ScalableDimension is a required field ScalableDimension *string `type:"string" required:"true" enum:"ScalableDimension"` @@ -1751,6 +1973,9 @@ type ScalableTarget struct { // * EMR cluster - The resource type is instancegroup and the unique identifier // is the cluster ID and instance group ID. Example: instancegroup/j-2EEZNYKUA1NTV/ig-1791Y4E1L8YI0. // + // * AppStream 2.0 fleet - The resource type is fleet and the unique identifier + // is the fleet name. Example: fleet/sample-fleet. + // // ResourceId is a required field ResourceId *string `min:"1" type:"string" required:"true"` @@ -1771,6 +1996,9 @@ type ScalableTarget struct { // * elasticmapreduce:instancegroup:InstanceCount - The instance count of // an EMR Instance Group. // + // * appstream:fleet:DesiredCapacity - The desired capacity of an AppStream + // 2.0 fleet. + // // ScalableDimension is a required field ScalableDimension *string `type:"string" required:"true" enum:"ScalableDimension"` @@ -1872,6 +2100,9 @@ type ScalingActivity struct { // * EMR cluster - The resource type is instancegroup and the unique identifier // is the cluster ID and instance group ID. Example: instancegroup/j-2EEZNYKUA1NTV/ig-1791Y4E1L8YI0. // + // * AppStream 2.0 fleet - The resource type is fleet and the unique identifier + // is the fleet name. Example: fleet/sample-fleet. + // // ResourceId is a required field ResourceId *string `min:"1" type:"string" required:"true"` @@ -1886,6 +2117,9 @@ type ScalingActivity struct { // * elasticmapreduce:instancegroup:InstanceCount - The instance count of // an EMR Instance Group. // + // * appstream:fleet:DesiredCapacity - The desired capacity of an AppStream + // 2.0 fleet. + // // ScalableDimension is a required field ScalableDimension *string `type:"string" required:"true" enum:"ScalableDimension"` @@ -2026,6 +2260,9 @@ type ScalingPolicy struct { // * EMR cluster - The resource type is instancegroup and the unique identifier // is the cluster ID and instance group ID. Example: instancegroup/j-2EEZNYKUA1NTV/ig-1791Y4E1L8YI0. // + // * AppStream 2.0 fleet - The resource type is fleet and the unique identifier + // is the fleet name. Example: fleet/sample-fleet. + // // ResourceId is a required field ResourceId *string `min:"1" type:"string" required:"true"` @@ -2040,6 +2277,9 @@ type ScalingPolicy struct { // * elasticmapreduce:instancegroup:InstanceCount - The instance count of // an EMR Instance Group. // + // * appstream:fleet:DesiredCapacity - The desired capacity of an AppStream + // 2.0 fleet. + // // ScalableDimension is a required field ScalableDimension *string `type:"string" required:"true" enum:"ScalableDimension"` @@ -2358,6 +2598,9 @@ const ( // ScalableDimensionElasticmapreduceInstancegroupInstanceCount is a ScalableDimension enum value ScalableDimensionElasticmapreduceInstancegroupInstanceCount = "elasticmapreduce:instancegroup:InstanceCount" + + // ScalableDimensionAppstreamFleetDesiredCapacity is a ScalableDimension enum value + ScalableDimensionAppstreamFleetDesiredCapacity = "appstream:fleet:DesiredCapacity" ) const ( @@ -2389,4 +2632,7 @@ const ( // ServiceNamespaceEc2 is a ServiceNamespace enum value ServiceNamespaceEc2 = "ec2" + + // ServiceNamespaceAppstream is a ServiceNamespace enum value + ServiceNamespaceAppstream = "appstream" ) diff --git a/vendor/github.com/aws/aws-sdk-go/service/applicationautoscaling/doc.go b/vendor/github.com/aws/aws-sdk-go/service/applicationautoscaling/doc.go new file mode 100644 index 000000000..12a3ae3a9 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/service/applicationautoscaling/doc.go @@ -0,0 +1,110 @@ +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. + +// Package applicationautoscaling provides the client and types for making API +// requests to Application Auto Scaling. +// +// With Application Auto Scaling, you can automatically scale your AWS resources. +// The experience similar to that of Auto Scaling (https://aws.amazon.com/autoscaling/). +// You can use Application Auto Scaling to accomplish the following tasks: +// +// * Define scaling policies to automatically scale your AWS resources +// +// * Scale your resources in response to CloudWatch alarms +// +// * View the history of your scaling events +// +// Application Auto Scaling can scale the following AWS resources: +// +// * Amazon ECS services. For more information, see Service Auto Scaling +// (http://docs.aws.amazon.com/AmazonECS/latest/developerguide/service-auto-scaling.html) +// in the Amazon EC2 Container Service Developer Guide. +// +// * Amazon EC2 Spot fleets. For more information, see Automatic Scaling +// for Spot Fleet (http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/fleet-auto-scaling.html) +// in the Amazon EC2 User Guide. +// +// * Amazon EMR clusters. For more information, see Using Automatic Scaling +// in Amazon EMR (http://docs.aws.amazon.com/ElasticMapReduce/latest/ManagementGuide/emr-automatic-scaling.html) +// in the Amazon EMR Management Guide. +// +// * AppStream 2.0 fleets. For more information, see Autoscaling Amazon AppStream +// 2.0 Resources (http://docs.aws.amazon.com/appstream2/latest/developerguide/autoscaling.html) +// in the Amazon AppStream 2.0 Developer Guide. +// +// For a list of supported regions, see AWS Regions and Endpoints: Application +// Auto Scaling (http://docs.aws.amazon.com/general/latest/gr/rande.html#as-app_region) +// in the AWS General Reference. +// +// See https://docs.aws.amazon.com/goto/WebAPI/application-autoscaling-2016-02-06 for more information on this service. +// +// See applicationautoscaling package documentation for more information. +// https://docs.aws.amazon.com/sdk-for-go/api/service/applicationautoscaling/ +// +// Using the Client +// +// To use the client for Application Auto Scaling you will first need +// to create a new instance of it. +// +// When creating a client for an AWS service you'll first need to have a Session +// already created. The Session provides configuration that can be shared +// between multiple service clients. Additional configuration can be applied to +// the Session and service's client when they are constructed. The aws package's +// Config type contains several fields such as Region for the AWS Region the +// client should make API requests too. The optional Config value can be provided +// as the variadic argument for Sessions and client creation. +// +// Once the service's client is created you can use it to make API requests the +// AWS service. These clients are safe to use concurrently. +// +// // Create a session to share configuration, and load external configuration. +// sess := session.Must(session.NewSession()) +// +// // Create the service's client with the session. +// svc := applicationautoscaling.New(sess) +// +// See the SDK's documentation for more information on how to use service clients. +// https://docs.aws.amazon.com/sdk-for-go/api/ +// +// See aws package's Config type for more information on configuration options. +// https://docs.aws.amazon.com/sdk-for-go/api/aws/#Config +// +// See the Application Auto Scaling client ApplicationAutoScaling for more +// information on creating the service's client. +// https://docs.aws.amazon.com/sdk-for-go/api/service/applicationautoscaling/#New +// +// Once the client is created you can make an API request to the service. +// Each API method takes a input parameter, and returns the service response +// and an error. +// +// The API method will document which error codes the service can be returned +// by the operation if the service models the API operation's errors. These +// errors will also be available as const strings prefixed with "ErrCode". +// +// result, err := svc.DeleteScalingPolicy(params) +// if err != nil { +// // Cast err to awserr.Error to handle specific error codes. +// aerr, ok := err.(awserr.Error) +// if ok && aerr.Code() == { +// // Specific error code handling +// } +// return err +// } +// +// fmt.Println("DeleteScalingPolicy result:") +// fmt.Println(result) +// +// Using the Client with Context +// +// The service's client also provides methods to make API requests with a Context +// value. This allows you to control the timeout, and cancellation of pending +// requests. These methods also take request Option as variadic parameter to apply +// additional configuration to the API request. +// +// ctx := context.Background() +// +// result, err := svc.DeleteScalingPolicyWithContext(ctx, params) +// +// See the request package documentation for more information on using Context pattern +// with the SDK. +// https://docs.aws.amazon.com/sdk-for-go/api/aws/request/ +package applicationautoscaling diff --git a/vendor/github.com/aws/aws-sdk-go/service/applicationautoscaling/errors.go b/vendor/github.com/aws/aws-sdk-go/service/applicationautoscaling/errors.go index 019a4bfc4..a028955cc 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/applicationautoscaling/errors.go +++ b/vendor/github.com/aws/aws-sdk-go/service/applicationautoscaling/errors.go @@ -1,4 +1,4 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. package applicationautoscaling diff --git a/vendor/github.com/aws/aws-sdk-go/service/applicationautoscaling/service.go b/vendor/github.com/aws/aws-sdk-go/service/applicationautoscaling/service.go index 80a749856..56103ee27 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/applicationautoscaling/service.go +++ b/vendor/github.com/aws/aws-sdk-go/service/applicationautoscaling/service.go @@ -1,4 +1,4 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. package applicationautoscaling @@ -11,36 +11,12 @@ import ( "github.com/aws/aws-sdk-go/private/protocol/jsonrpc" ) -// With Application Auto Scaling, you can automatically scale your AWS resources. -// The experience similar to that of Auto Scaling (https://aws.amazon.com/autoscaling/). -// You can use Application Auto Scaling to accomplish the following tasks: +// ApplicationAutoScaling provides the API operation methods for making requests to +// Application Auto Scaling. See this package's package overview docs +// for details on the service. // -// * Define scaling policies to automatically scale your AWS resources -// -// * Scale your resources in response to CloudWatch alarms -// -// * View the history of your scaling events -// -// Application Auto Scaling can scale the following AWS resources: -// -// * Amazon ECS services. For more information, see Service Auto Scaling -// (http://docs.aws.amazon.com/AmazonECS/latest/developerguide/service-auto-scaling.html) -// in the Amazon EC2 Container Service Developer Guide. -// -// * Amazon EC2 Spot fleets. For more information, see Automatic Scaling -// for Spot Fleet (http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/fleet-auto-scaling.html) -// in the Amazon EC2 User Guide. -// -// * Amazon EMR clusters. For more information, see Using Automatic Scaling -// in Amazon EMR (http://docs.aws.amazon.com/ElasticMapReduce/latest/ManagementGuide/emr-automatic-scaling.html) -// in the Amazon EMR Management Guide. -// -// For a list of supported regions, see AWS Regions and Endpoints: Application -// Auto Scaling (http://docs.aws.amazon.com/general/latest/gr/rande.html#as-app_region) -// in the AWS General Reference. -// The service client's operations are safe to be used concurrently. -// It is not safe to mutate any of the client's properties though. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/application-autoscaling-2016-02-06 +// ApplicationAutoScaling methods are safe to use concurrently. It is not safe to +// modify mutate any of the struct's properties though. type ApplicationAutoScaling struct { *client.Client } diff --git a/vendor/github.com/aws/aws-sdk-go/service/autoscaling/api.go b/vendor/github.com/aws/aws-sdk-go/service/autoscaling/api.go index 64bb6017f..49dd0bf2e 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/autoscaling/api.go +++ b/vendor/github.com/aws/aws-sdk-go/service/autoscaling/api.go @@ -1,12 +1,12 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. -// Package autoscaling provides a client for Auto Scaling. package autoscaling import ( "fmt" "time" + "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awsutil" "github.com/aws/aws-sdk-go/aws/request" "github.com/aws/aws-sdk-go/private/protocol" @@ -91,8 +91,23 @@ func (c *AutoScaling) AttachInstancesRequest(input *AttachInstancesInput) (req * // Please also see https://docs.aws.amazon.com/goto/WebAPI/autoscaling-2011-01-01/AttachInstances func (c *AutoScaling) AttachInstances(input *AttachInstancesInput) (*AttachInstancesOutput, error) { req, out := c.AttachInstancesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// AttachInstancesWithContext is the same as AttachInstances with the addition of +// the ability to pass a context and additional request options. +// +// See AttachInstances 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 *AutoScaling) AttachInstancesWithContext(ctx aws.Context, input *AttachInstancesInput, opts ...request.Option) (*AttachInstancesOutput, error) { + req, out := c.AttachInstancesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opAttachLoadBalancerTargetGroups = "AttachLoadBalancerTargetGroups" @@ -164,8 +179,23 @@ func (c *AutoScaling) AttachLoadBalancerTargetGroupsRequest(input *AttachLoadBal // Please also see https://docs.aws.amazon.com/goto/WebAPI/autoscaling-2011-01-01/AttachLoadBalancerTargetGroups func (c *AutoScaling) AttachLoadBalancerTargetGroups(input *AttachLoadBalancerTargetGroupsInput) (*AttachLoadBalancerTargetGroupsOutput, error) { req, out := c.AttachLoadBalancerTargetGroupsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// AttachLoadBalancerTargetGroupsWithContext is the same as AttachLoadBalancerTargetGroups with the addition of +// the ability to pass a context and additional request options. +// +// See AttachLoadBalancerTargetGroups 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 *AutoScaling) AttachLoadBalancerTargetGroupsWithContext(ctx aws.Context, input *AttachLoadBalancerTargetGroupsInput, opts ...request.Option) (*AttachLoadBalancerTargetGroupsOutput, error) { + req, out := c.AttachLoadBalancerTargetGroupsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opAttachLoadBalancers = "AttachLoadBalancers" @@ -240,8 +270,23 @@ func (c *AutoScaling) AttachLoadBalancersRequest(input *AttachLoadBalancersInput // Please also see https://docs.aws.amazon.com/goto/WebAPI/autoscaling-2011-01-01/AttachLoadBalancers func (c *AutoScaling) AttachLoadBalancers(input *AttachLoadBalancersInput) (*AttachLoadBalancersOutput, error) { req, out := c.AttachLoadBalancersRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// AttachLoadBalancersWithContext is the same as AttachLoadBalancers with the addition of +// the ability to pass a context and additional request options. +// +// See AttachLoadBalancers 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 *AutoScaling) AttachLoadBalancersWithContext(ctx aws.Context, input *AttachLoadBalancersInput, opts ...request.Option) (*AttachLoadBalancersOutput, error) { + req, out := c.AttachLoadBalancersRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCompleteLifecycleAction = "CompleteLifecycleAction" @@ -328,8 +373,23 @@ func (c *AutoScaling) CompleteLifecycleActionRequest(input *CompleteLifecycleAct // Please also see https://docs.aws.amazon.com/goto/WebAPI/autoscaling-2011-01-01/CompleteLifecycleAction func (c *AutoScaling) CompleteLifecycleAction(input *CompleteLifecycleActionInput) (*CompleteLifecycleActionOutput, error) { req, out := c.CompleteLifecycleActionRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CompleteLifecycleActionWithContext is the same as CompleteLifecycleAction with the addition of +// the ability to pass a context and additional request options. +// +// See CompleteLifecycleAction 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 *AutoScaling) CompleteLifecycleActionWithContext(ctx aws.Context, input *CompleteLifecycleActionInput, opts ...request.Option) (*CompleteLifecycleActionOutput, error) { + req, out := c.CompleteLifecycleActionRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateAutoScalingGroup = "CreateAutoScalingGroup" @@ -412,8 +472,23 @@ func (c *AutoScaling) CreateAutoScalingGroupRequest(input *CreateAutoScalingGrou // Please also see https://docs.aws.amazon.com/goto/WebAPI/autoscaling-2011-01-01/CreateAutoScalingGroup func (c *AutoScaling) CreateAutoScalingGroup(input *CreateAutoScalingGroupInput) (*CreateAutoScalingGroupOutput, error) { req, out := c.CreateAutoScalingGroupRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateAutoScalingGroupWithContext is the same as CreateAutoScalingGroup with the addition of +// the ability to pass a context and additional request options. +// +// See CreateAutoScalingGroup 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 *AutoScaling) CreateAutoScalingGroupWithContext(ctx aws.Context, input *CreateAutoScalingGroupInput, opts ...request.Option) (*CreateAutoScalingGroupOutput, error) { + req, out := c.CreateAutoScalingGroupRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateLaunchConfiguration = "CreateLaunchConfiguration" @@ -496,8 +571,23 @@ func (c *AutoScaling) CreateLaunchConfigurationRequest(input *CreateLaunchConfig // Please also see https://docs.aws.amazon.com/goto/WebAPI/autoscaling-2011-01-01/CreateLaunchConfiguration func (c *AutoScaling) CreateLaunchConfiguration(input *CreateLaunchConfigurationInput) (*CreateLaunchConfigurationOutput, error) { req, out := c.CreateLaunchConfigurationRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateLaunchConfigurationWithContext is the same as CreateLaunchConfiguration with the addition of +// the ability to pass a context and additional request options. +// +// See CreateLaunchConfiguration 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 *AutoScaling) CreateLaunchConfigurationWithContext(ctx aws.Context, input *CreateLaunchConfigurationInput, opts ...request.Option) (*CreateLaunchConfigurationOutput, error) { + req, out := c.CreateLaunchConfigurationRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateOrUpdateTags = "CreateOrUpdateTags" @@ -579,8 +669,23 @@ func (c *AutoScaling) CreateOrUpdateTagsRequest(input *CreateOrUpdateTagsInput) // Please also see https://docs.aws.amazon.com/goto/WebAPI/autoscaling-2011-01-01/CreateOrUpdateTags func (c *AutoScaling) CreateOrUpdateTags(input *CreateOrUpdateTagsInput) (*CreateOrUpdateTagsOutput, error) { req, out := c.CreateOrUpdateTagsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateOrUpdateTagsWithContext is the same as CreateOrUpdateTags with the addition of +// the ability to pass a context and additional request options. +// +// See CreateOrUpdateTags 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 *AutoScaling) CreateOrUpdateTagsWithContext(ctx aws.Context, input *CreateOrUpdateTagsInput, opts ...request.Option) (*CreateOrUpdateTagsOutput, error) { + req, out := c.CreateOrUpdateTagsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteAutoScalingGroup = "DeleteAutoScalingGroup" @@ -668,8 +773,23 @@ func (c *AutoScaling) DeleteAutoScalingGroupRequest(input *DeleteAutoScalingGrou // Please also see https://docs.aws.amazon.com/goto/WebAPI/autoscaling-2011-01-01/DeleteAutoScalingGroup func (c *AutoScaling) DeleteAutoScalingGroup(input *DeleteAutoScalingGroupInput) (*DeleteAutoScalingGroupOutput, error) { req, out := c.DeleteAutoScalingGroupRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteAutoScalingGroupWithContext is the same as DeleteAutoScalingGroup with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteAutoScalingGroup 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 *AutoScaling) DeleteAutoScalingGroupWithContext(ctx aws.Context, input *DeleteAutoScalingGroupInput, opts ...request.Option) (*DeleteAutoScalingGroupOutput, error) { + req, out := c.DeleteAutoScalingGroupRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteLaunchConfiguration = "DeleteLaunchConfiguration" @@ -743,8 +863,23 @@ func (c *AutoScaling) DeleteLaunchConfigurationRequest(input *DeleteLaunchConfig // Please also see https://docs.aws.amazon.com/goto/WebAPI/autoscaling-2011-01-01/DeleteLaunchConfiguration func (c *AutoScaling) DeleteLaunchConfiguration(input *DeleteLaunchConfigurationInput) (*DeleteLaunchConfigurationOutput, error) { req, out := c.DeleteLaunchConfigurationRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteLaunchConfigurationWithContext is the same as DeleteLaunchConfiguration with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteLaunchConfiguration 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 *AutoScaling) DeleteLaunchConfigurationWithContext(ctx aws.Context, input *DeleteLaunchConfigurationInput, opts ...request.Option) (*DeleteLaunchConfigurationOutput, error) { + req, out := c.DeleteLaunchConfigurationRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteLifecycleHook = "DeleteLifecycleHook" @@ -812,8 +947,23 @@ func (c *AutoScaling) DeleteLifecycleHookRequest(input *DeleteLifecycleHookInput // Please also see https://docs.aws.amazon.com/goto/WebAPI/autoscaling-2011-01-01/DeleteLifecycleHook func (c *AutoScaling) DeleteLifecycleHook(input *DeleteLifecycleHookInput) (*DeleteLifecycleHookOutput, error) { req, out := c.DeleteLifecycleHookRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteLifecycleHookWithContext is the same as DeleteLifecycleHook with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteLifecycleHook 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 *AutoScaling) DeleteLifecycleHookWithContext(ctx aws.Context, input *DeleteLifecycleHookInput, opts ...request.Option) (*DeleteLifecycleHookOutput, error) { + req, out := c.DeleteLifecycleHookRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteNotificationConfiguration = "DeleteNotificationConfiguration" @@ -880,8 +1030,23 @@ func (c *AutoScaling) DeleteNotificationConfigurationRequest(input *DeleteNotifi // Please also see https://docs.aws.amazon.com/goto/WebAPI/autoscaling-2011-01-01/DeleteNotificationConfiguration func (c *AutoScaling) DeleteNotificationConfiguration(input *DeleteNotificationConfigurationInput) (*DeleteNotificationConfigurationOutput, error) { req, out := c.DeleteNotificationConfigurationRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteNotificationConfigurationWithContext is the same as DeleteNotificationConfiguration with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteNotificationConfiguration 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 *AutoScaling) DeleteNotificationConfigurationWithContext(ctx aws.Context, input *DeleteNotificationConfigurationInput, opts ...request.Option) (*DeleteNotificationConfigurationOutput, error) { + req, out := c.DeleteNotificationConfigurationRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeletePolicy = "DeletePolicy" @@ -951,8 +1116,23 @@ func (c *AutoScaling) DeletePolicyRequest(input *DeletePolicyInput) (req *reques // Please also see https://docs.aws.amazon.com/goto/WebAPI/autoscaling-2011-01-01/DeletePolicy func (c *AutoScaling) DeletePolicy(input *DeletePolicyInput) (*DeletePolicyOutput, error) { req, out := c.DeletePolicyRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeletePolicyWithContext is the same as DeletePolicy with the addition of +// the ability to pass a context and additional request options. +// +// See DeletePolicy 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 *AutoScaling) DeletePolicyWithContext(ctx aws.Context, input *DeletePolicyInput, opts ...request.Option) (*DeletePolicyOutput, error) { + req, out := c.DeletePolicyRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteScheduledAction = "DeleteScheduledAction" @@ -1019,8 +1199,23 @@ func (c *AutoScaling) DeleteScheduledActionRequest(input *DeleteScheduledActionI // Please also see https://docs.aws.amazon.com/goto/WebAPI/autoscaling-2011-01-01/DeleteScheduledAction func (c *AutoScaling) DeleteScheduledAction(input *DeleteScheduledActionInput) (*DeleteScheduledActionOutput, error) { req, out := c.DeleteScheduledActionRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteScheduledActionWithContext is the same as DeleteScheduledAction with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteScheduledAction 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 *AutoScaling) DeleteScheduledActionWithContext(ctx aws.Context, input *DeleteScheduledActionInput, opts ...request.Option) (*DeleteScheduledActionOutput, error) { + req, out := c.DeleteScheduledActionRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteTags = "DeleteTags" @@ -1087,8 +1282,23 @@ func (c *AutoScaling) DeleteTagsRequest(input *DeleteTagsInput) (req *request.Re // Please also see https://docs.aws.amazon.com/goto/WebAPI/autoscaling-2011-01-01/DeleteTags func (c *AutoScaling) DeleteTags(input *DeleteTagsInput) (*DeleteTagsOutput, error) { req, out := c.DeleteTagsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteTagsWithContext is the same as DeleteTags with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteTags 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 *AutoScaling) DeleteTagsWithContext(ctx aws.Context, input *DeleteTagsInput, opts ...request.Option) (*DeleteTagsOutput, error) { + req, out := c.DeleteTagsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeAccountLimits = "DescribeAccountLimits" @@ -1157,8 +1367,23 @@ func (c *AutoScaling) DescribeAccountLimitsRequest(input *DescribeAccountLimitsI // Please also see https://docs.aws.amazon.com/goto/WebAPI/autoscaling-2011-01-01/DescribeAccountLimits func (c *AutoScaling) DescribeAccountLimits(input *DescribeAccountLimitsInput) (*DescribeAccountLimitsOutput, error) { req, out := c.DescribeAccountLimitsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeAccountLimitsWithContext is the same as DescribeAccountLimits with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeAccountLimits 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 *AutoScaling) DescribeAccountLimitsWithContext(ctx aws.Context, input *DescribeAccountLimitsInput, opts ...request.Option) (*DescribeAccountLimitsOutput, error) { + req, out := c.DescribeAccountLimitsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeAdjustmentTypes = "DescribeAdjustmentTypes" @@ -1223,8 +1448,23 @@ func (c *AutoScaling) DescribeAdjustmentTypesRequest(input *DescribeAdjustmentTy // Please also see https://docs.aws.amazon.com/goto/WebAPI/autoscaling-2011-01-01/DescribeAdjustmentTypes func (c *AutoScaling) DescribeAdjustmentTypes(input *DescribeAdjustmentTypesInput) (*DescribeAdjustmentTypesOutput, error) { req, out := c.DescribeAdjustmentTypesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeAdjustmentTypesWithContext is the same as DescribeAdjustmentTypes with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeAdjustmentTypes 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 *AutoScaling) DescribeAdjustmentTypesWithContext(ctx aws.Context, input *DescribeAdjustmentTypesInput, opts ...request.Option) (*DescribeAdjustmentTypesOutput, error) { + req, out := c.DescribeAdjustmentTypesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeAutoScalingGroups = "DescribeAutoScalingGroups" @@ -1298,8 +1538,23 @@ func (c *AutoScaling) DescribeAutoScalingGroupsRequest(input *DescribeAutoScalin // Please also see https://docs.aws.amazon.com/goto/WebAPI/autoscaling-2011-01-01/DescribeAutoScalingGroups func (c *AutoScaling) DescribeAutoScalingGroups(input *DescribeAutoScalingGroupsInput) (*DescribeAutoScalingGroupsOutput, error) { req, out := c.DescribeAutoScalingGroupsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeAutoScalingGroupsWithContext is the same as DescribeAutoScalingGroups with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeAutoScalingGroups 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 *AutoScaling) DescribeAutoScalingGroupsWithContext(ctx aws.Context, input *DescribeAutoScalingGroupsInput, opts ...request.Option) (*DescribeAutoScalingGroupsOutput, error) { + req, out := c.DescribeAutoScalingGroupsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // DescribeAutoScalingGroupsPages iterates over the pages of a DescribeAutoScalingGroups operation, @@ -1319,12 +1574,37 @@ func (c *AutoScaling) DescribeAutoScalingGroups(input *DescribeAutoScalingGroups // return pageNum <= 3 // }) // -func (c *AutoScaling) DescribeAutoScalingGroupsPages(input *DescribeAutoScalingGroupsInput, fn func(p *DescribeAutoScalingGroupsOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.DescribeAutoScalingGroupsRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*DescribeAutoScalingGroupsOutput), lastPage) - }) +func (c *AutoScaling) DescribeAutoScalingGroupsPages(input *DescribeAutoScalingGroupsInput, fn func(*DescribeAutoScalingGroupsOutput, bool) bool) error { + return c.DescribeAutoScalingGroupsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// DescribeAutoScalingGroupsPagesWithContext same as DescribeAutoScalingGroupsPages 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 *AutoScaling) DescribeAutoScalingGroupsPagesWithContext(ctx aws.Context, input *DescribeAutoScalingGroupsInput, fn func(*DescribeAutoScalingGroupsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *DescribeAutoScalingGroupsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeAutoScalingGroupsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*DescribeAutoScalingGroupsOutput), !p.HasNextPage()) + } + return p.Err() } const opDescribeAutoScalingInstances = "DescribeAutoScalingInstances" @@ -1398,8 +1678,23 @@ func (c *AutoScaling) DescribeAutoScalingInstancesRequest(input *DescribeAutoSca // Please also see https://docs.aws.amazon.com/goto/WebAPI/autoscaling-2011-01-01/DescribeAutoScalingInstances func (c *AutoScaling) DescribeAutoScalingInstances(input *DescribeAutoScalingInstancesInput) (*DescribeAutoScalingInstancesOutput, error) { req, out := c.DescribeAutoScalingInstancesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeAutoScalingInstancesWithContext is the same as DescribeAutoScalingInstances with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeAutoScalingInstances 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 *AutoScaling) DescribeAutoScalingInstancesWithContext(ctx aws.Context, input *DescribeAutoScalingInstancesInput, opts ...request.Option) (*DescribeAutoScalingInstancesOutput, error) { + req, out := c.DescribeAutoScalingInstancesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // DescribeAutoScalingInstancesPages iterates over the pages of a DescribeAutoScalingInstances operation, @@ -1419,12 +1714,37 @@ func (c *AutoScaling) DescribeAutoScalingInstances(input *DescribeAutoScalingIns // return pageNum <= 3 // }) // -func (c *AutoScaling) DescribeAutoScalingInstancesPages(input *DescribeAutoScalingInstancesInput, fn func(p *DescribeAutoScalingInstancesOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.DescribeAutoScalingInstancesRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*DescribeAutoScalingInstancesOutput), lastPage) - }) +func (c *AutoScaling) DescribeAutoScalingInstancesPages(input *DescribeAutoScalingInstancesInput, fn func(*DescribeAutoScalingInstancesOutput, bool) bool) error { + return c.DescribeAutoScalingInstancesPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// DescribeAutoScalingInstancesPagesWithContext same as DescribeAutoScalingInstancesPages 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 *AutoScaling) DescribeAutoScalingInstancesPagesWithContext(ctx aws.Context, input *DescribeAutoScalingInstancesInput, fn func(*DescribeAutoScalingInstancesOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *DescribeAutoScalingInstancesInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeAutoScalingInstancesRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*DescribeAutoScalingInstancesOutput), !p.HasNextPage()) + } + return p.Err() } const opDescribeAutoScalingNotificationTypes = "DescribeAutoScalingNotificationTypes" @@ -1489,8 +1809,23 @@ func (c *AutoScaling) DescribeAutoScalingNotificationTypesRequest(input *Describ // Please also see https://docs.aws.amazon.com/goto/WebAPI/autoscaling-2011-01-01/DescribeAutoScalingNotificationTypes func (c *AutoScaling) DescribeAutoScalingNotificationTypes(input *DescribeAutoScalingNotificationTypesInput) (*DescribeAutoScalingNotificationTypesOutput, error) { req, out := c.DescribeAutoScalingNotificationTypesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeAutoScalingNotificationTypesWithContext is the same as DescribeAutoScalingNotificationTypes with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeAutoScalingNotificationTypes 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 *AutoScaling) DescribeAutoScalingNotificationTypesWithContext(ctx aws.Context, input *DescribeAutoScalingNotificationTypesInput, opts ...request.Option) (*DescribeAutoScalingNotificationTypesOutput, error) { + req, out := c.DescribeAutoScalingNotificationTypesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeLaunchConfigurations = "DescribeLaunchConfigurations" @@ -1564,8 +1899,23 @@ func (c *AutoScaling) DescribeLaunchConfigurationsRequest(input *DescribeLaunchC // Please also see https://docs.aws.amazon.com/goto/WebAPI/autoscaling-2011-01-01/DescribeLaunchConfigurations func (c *AutoScaling) DescribeLaunchConfigurations(input *DescribeLaunchConfigurationsInput) (*DescribeLaunchConfigurationsOutput, error) { req, out := c.DescribeLaunchConfigurationsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeLaunchConfigurationsWithContext is the same as DescribeLaunchConfigurations with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeLaunchConfigurations 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 *AutoScaling) DescribeLaunchConfigurationsWithContext(ctx aws.Context, input *DescribeLaunchConfigurationsInput, opts ...request.Option) (*DescribeLaunchConfigurationsOutput, error) { + req, out := c.DescribeLaunchConfigurationsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // DescribeLaunchConfigurationsPages iterates over the pages of a DescribeLaunchConfigurations operation, @@ -1585,12 +1935,37 @@ func (c *AutoScaling) DescribeLaunchConfigurations(input *DescribeLaunchConfigur // return pageNum <= 3 // }) // -func (c *AutoScaling) DescribeLaunchConfigurationsPages(input *DescribeLaunchConfigurationsInput, fn func(p *DescribeLaunchConfigurationsOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.DescribeLaunchConfigurationsRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*DescribeLaunchConfigurationsOutput), lastPage) - }) +func (c *AutoScaling) DescribeLaunchConfigurationsPages(input *DescribeLaunchConfigurationsInput, fn func(*DescribeLaunchConfigurationsOutput, bool) bool) error { + return c.DescribeLaunchConfigurationsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// DescribeLaunchConfigurationsPagesWithContext same as DescribeLaunchConfigurationsPages 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 *AutoScaling) DescribeLaunchConfigurationsPagesWithContext(ctx aws.Context, input *DescribeLaunchConfigurationsInput, fn func(*DescribeLaunchConfigurationsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *DescribeLaunchConfigurationsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeLaunchConfigurationsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*DescribeLaunchConfigurationsOutput), !p.HasNextPage()) + } + return p.Err() } const opDescribeLifecycleHookTypes = "DescribeLifecycleHookTypes" @@ -1655,8 +2030,23 @@ func (c *AutoScaling) DescribeLifecycleHookTypesRequest(input *DescribeLifecycle // Please also see https://docs.aws.amazon.com/goto/WebAPI/autoscaling-2011-01-01/DescribeLifecycleHookTypes func (c *AutoScaling) DescribeLifecycleHookTypes(input *DescribeLifecycleHookTypesInput) (*DescribeLifecycleHookTypesOutput, error) { req, out := c.DescribeLifecycleHookTypesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeLifecycleHookTypesWithContext is the same as DescribeLifecycleHookTypes with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeLifecycleHookTypes 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 *AutoScaling) DescribeLifecycleHookTypesWithContext(ctx aws.Context, input *DescribeLifecycleHookTypesInput, opts ...request.Option) (*DescribeLifecycleHookTypesOutput, error) { + req, out := c.DescribeLifecycleHookTypesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeLifecycleHooks = "DescribeLifecycleHooks" @@ -1721,8 +2111,23 @@ func (c *AutoScaling) DescribeLifecycleHooksRequest(input *DescribeLifecycleHook // Please also see https://docs.aws.amazon.com/goto/WebAPI/autoscaling-2011-01-01/DescribeLifecycleHooks func (c *AutoScaling) DescribeLifecycleHooks(input *DescribeLifecycleHooksInput) (*DescribeLifecycleHooksOutput, error) { req, out := c.DescribeLifecycleHooksRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeLifecycleHooksWithContext is the same as DescribeLifecycleHooks with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeLifecycleHooks 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 *AutoScaling) DescribeLifecycleHooksWithContext(ctx aws.Context, input *DescribeLifecycleHooksInput, opts ...request.Option) (*DescribeLifecycleHooksOutput, error) { + req, out := c.DescribeLifecycleHooksRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeLoadBalancerTargetGroups = "DescribeLoadBalancerTargetGroups" @@ -1787,8 +2192,23 @@ func (c *AutoScaling) DescribeLoadBalancerTargetGroupsRequest(input *DescribeLoa // Please also see https://docs.aws.amazon.com/goto/WebAPI/autoscaling-2011-01-01/DescribeLoadBalancerTargetGroups func (c *AutoScaling) DescribeLoadBalancerTargetGroups(input *DescribeLoadBalancerTargetGroupsInput) (*DescribeLoadBalancerTargetGroupsOutput, error) { req, out := c.DescribeLoadBalancerTargetGroupsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeLoadBalancerTargetGroupsWithContext is the same as DescribeLoadBalancerTargetGroups with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeLoadBalancerTargetGroups 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 *AutoScaling) DescribeLoadBalancerTargetGroupsWithContext(ctx aws.Context, input *DescribeLoadBalancerTargetGroupsInput, opts ...request.Option) (*DescribeLoadBalancerTargetGroupsOutput, error) { + req, out := c.DescribeLoadBalancerTargetGroupsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeLoadBalancers = "DescribeLoadBalancers" @@ -1856,8 +2276,23 @@ func (c *AutoScaling) DescribeLoadBalancersRequest(input *DescribeLoadBalancersI // Please also see https://docs.aws.amazon.com/goto/WebAPI/autoscaling-2011-01-01/DescribeLoadBalancers func (c *AutoScaling) DescribeLoadBalancers(input *DescribeLoadBalancersInput) (*DescribeLoadBalancersOutput, error) { req, out := c.DescribeLoadBalancersRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeLoadBalancersWithContext is the same as DescribeLoadBalancers with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeLoadBalancers 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 *AutoScaling) DescribeLoadBalancersWithContext(ctx aws.Context, input *DescribeLoadBalancersInput, opts ...request.Option) (*DescribeLoadBalancersOutput, error) { + req, out := c.DescribeLoadBalancersRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeMetricCollectionTypes = "DescribeMetricCollectionTypes" @@ -1925,8 +2360,23 @@ func (c *AutoScaling) DescribeMetricCollectionTypesRequest(input *DescribeMetric // Please also see https://docs.aws.amazon.com/goto/WebAPI/autoscaling-2011-01-01/DescribeMetricCollectionTypes func (c *AutoScaling) DescribeMetricCollectionTypes(input *DescribeMetricCollectionTypesInput) (*DescribeMetricCollectionTypesOutput, error) { req, out := c.DescribeMetricCollectionTypesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeMetricCollectionTypesWithContext is the same as DescribeMetricCollectionTypes with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeMetricCollectionTypes 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 *AutoScaling) DescribeMetricCollectionTypesWithContext(ctx aws.Context, input *DescribeMetricCollectionTypesInput, opts ...request.Option) (*DescribeMetricCollectionTypesOutput, error) { + req, out := c.DescribeMetricCollectionTypesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeNotificationConfigurations = "DescribeNotificationConfigurations" @@ -2001,8 +2451,23 @@ func (c *AutoScaling) DescribeNotificationConfigurationsRequest(input *DescribeN // Please also see https://docs.aws.amazon.com/goto/WebAPI/autoscaling-2011-01-01/DescribeNotificationConfigurations func (c *AutoScaling) DescribeNotificationConfigurations(input *DescribeNotificationConfigurationsInput) (*DescribeNotificationConfigurationsOutput, error) { req, out := c.DescribeNotificationConfigurationsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeNotificationConfigurationsWithContext is the same as DescribeNotificationConfigurations with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeNotificationConfigurations 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 *AutoScaling) DescribeNotificationConfigurationsWithContext(ctx aws.Context, input *DescribeNotificationConfigurationsInput, opts ...request.Option) (*DescribeNotificationConfigurationsOutput, error) { + req, out := c.DescribeNotificationConfigurationsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // DescribeNotificationConfigurationsPages iterates over the pages of a DescribeNotificationConfigurations operation, @@ -2022,12 +2487,37 @@ func (c *AutoScaling) DescribeNotificationConfigurations(input *DescribeNotifica // return pageNum <= 3 // }) // -func (c *AutoScaling) DescribeNotificationConfigurationsPages(input *DescribeNotificationConfigurationsInput, fn func(p *DescribeNotificationConfigurationsOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.DescribeNotificationConfigurationsRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*DescribeNotificationConfigurationsOutput), lastPage) - }) +func (c *AutoScaling) DescribeNotificationConfigurationsPages(input *DescribeNotificationConfigurationsInput, fn func(*DescribeNotificationConfigurationsOutput, bool) bool) error { + return c.DescribeNotificationConfigurationsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// DescribeNotificationConfigurationsPagesWithContext same as DescribeNotificationConfigurationsPages 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 *AutoScaling) DescribeNotificationConfigurationsPagesWithContext(ctx aws.Context, input *DescribeNotificationConfigurationsInput, fn func(*DescribeNotificationConfigurationsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *DescribeNotificationConfigurationsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeNotificationConfigurationsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*DescribeNotificationConfigurationsOutput), !p.HasNextPage()) + } + return p.Err() } const opDescribePolicies = "DescribePolicies" @@ -2101,8 +2591,23 @@ func (c *AutoScaling) DescribePoliciesRequest(input *DescribePoliciesInput) (req // Please also see https://docs.aws.amazon.com/goto/WebAPI/autoscaling-2011-01-01/DescribePolicies func (c *AutoScaling) DescribePolicies(input *DescribePoliciesInput) (*DescribePoliciesOutput, error) { req, out := c.DescribePoliciesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribePoliciesWithContext is the same as DescribePolicies with the addition of +// the ability to pass a context and additional request options. +// +// See DescribePolicies 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 *AutoScaling) DescribePoliciesWithContext(ctx aws.Context, input *DescribePoliciesInput, opts ...request.Option) (*DescribePoliciesOutput, error) { + req, out := c.DescribePoliciesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // DescribePoliciesPages iterates over the pages of a DescribePolicies operation, @@ -2122,12 +2627,37 @@ func (c *AutoScaling) DescribePolicies(input *DescribePoliciesInput) (*DescribeP // return pageNum <= 3 // }) // -func (c *AutoScaling) DescribePoliciesPages(input *DescribePoliciesInput, fn func(p *DescribePoliciesOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.DescribePoliciesRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*DescribePoliciesOutput), lastPage) - }) +func (c *AutoScaling) DescribePoliciesPages(input *DescribePoliciesInput, fn func(*DescribePoliciesOutput, bool) bool) error { + return c.DescribePoliciesPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// DescribePoliciesPagesWithContext same as DescribePoliciesPages 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 *AutoScaling) DescribePoliciesPagesWithContext(ctx aws.Context, input *DescribePoliciesInput, fn func(*DescribePoliciesOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *DescribePoliciesInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribePoliciesRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*DescribePoliciesOutput), !p.HasNextPage()) + } + return p.Err() } const opDescribeScalingActivities = "DescribeScalingActivities" @@ -2201,8 +2731,23 @@ func (c *AutoScaling) DescribeScalingActivitiesRequest(input *DescribeScalingAct // Please also see https://docs.aws.amazon.com/goto/WebAPI/autoscaling-2011-01-01/DescribeScalingActivities func (c *AutoScaling) DescribeScalingActivities(input *DescribeScalingActivitiesInput) (*DescribeScalingActivitiesOutput, error) { req, out := c.DescribeScalingActivitiesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeScalingActivitiesWithContext is the same as DescribeScalingActivities with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeScalingActivities 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 *AutoScaling) DescribeScalingActivitiesWithContext(ctx aws.Context, input *DescribeScalingActivitiesInput, opts ...request.Option) (*DescribeScalingActivitiesOutput, error) { + req, out := c.DescribeScalingActivitiesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // DescribeScalingActivitiesPages iterates over the pages of a DescribeScalingActivities operation, @@ -2222,12 +2767,37 @@ func (c *AutoScaling) DescribeScalingActivities(input *DescribeScalingActivities // return pageNum <= 3 // }) // -func (c *AutoScaling) DescribeScalingActivitiesPages(input *DescribeScalingActivitiesInput, fn func(p *DescribeScalingActivitiesOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.DescribeScalingActivitiesRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*DescribeScalingActivitiesOutput), lastPage) - }) +func (c *AutoScaling) DescribeScalingActivitiesPages(input *DescribeScalingActivitiesInput, fn func(*DescribeScalingActivitiesOutput, bool) bool) error { + return c.DescribeScalingActivitiesPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// DescribeScalingActivitiesPagesWithContext same as DescribeScalingActivitiesPages 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 *AutoScaling) DescribeScalingActivitiesPagesWithContext(ctx aws.Context, input *DescribeScalingActivitiesInput, fn func(*DescribeScalingActivitiesOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *DescribeScalingActivitiesInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeScalingActivitiesRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*DescribeScalingActivitiesOutput), !p.HasNextPage()) + } + return p.Err() } const opDescribeScalingProcessTypes = "DescribeScalingProcessTypes" @@ -2292,8 +2862,23 @@ func (c *AutoScaling) DescribeScalingProcessTypesRequest(input *DescribeScalingP // Please also see https://docs.aws.amazon.com/goto/WebAPI/autoscaling-2011-01-01/DescribeScalingProcessTypes func (c *AutoScaling) DescribeScalingProcessTypes(input *DescribeScalingProcessTypesInput) (*DescribeScalingProcessTypesOutput, error) { req, out := c.DescribeScalingProcessTypesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeScalingProcessTypesWithContext is the same as DescribeScalingProcessTypes with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeScalingProcessTypes 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 *AutoScaling) DescribeScalingProcessTypesWithContext(ctx aws.Context, input *DescribeScalingProcessTypesInput, opts ...request.Option) (*DescribeScalingProcessTypesOutput, error) { + req, out := c.DescribeScalingProcessTypesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeScheduledActions = "DescribeScheduledActions" @@ -2368,8 +2953,23 @@ func (c *AutoScaling) DescribeScheduledActionsRequest(input *DescribeScheduledAc // Please also see https://docs.aws.amazon.com/goto/WebAPI/autoscaling-2011-01-01/DescribeScheduledActions func (c *AutoScaling) DescribeScheduledActions(input *DescribeScheduledActionsInput) (*DescribeScheduledActionsOutput, error) { req, out := c.DescribeScheduledActionsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeScheduledActionsWithContext is the same as DescribeScheduledActions with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeScheduledActions 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 *AutoScaling) DescribeScheduledActionsWithContext(ctx aws.Context, input *DescribeScheduledActionsInput, opts ...request.Option) (*DescribeScheduledActionsOutput, error) { + req, out := c.DescribeScheduledActionsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // DescribeScheduledActionsPages iterates over the pages of a DescribeScheduledActions operation, @@ -2389,12 +2989,37 @@ func (c *AutoScaling) DescribeScheduledActions(input *DescribeScheduledActionsIn // return pageNum <= 3 // }) // -func (c *AutoScaling) DescribeScheduledActionsPages(input *DescribeScheduledActionsInput, fn func(p *DescribeScheduledActionsOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.DescribeScheduledActionsRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*DescribeScheduledActionsOutput), lastPage) - }) +func (c *AutoScaling) DescribeScheduledActionsPages(input *DescribeScheduledActionsInput, fn func(*DescribeScheduledActionsOutput, bool) bool) error { + return c.DescribeScheduledActionsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// DescribeScheduledActionsPagesWithContext same as DescribeScheduledActionsPages 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 *AutoScaling) DescribeScheduledActionsPagesWithContext(ctx aws.Context, input *DescribeScheduledActionsInput, fn func(*DescribeScheduledActionsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *DescribeScheduledActionsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeScheduledActionsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*DescribeScheduledActionsOutput), !p.HasNextPage()) + } + return p.Err() } const opDescribeTags = "DescribeTags" @@ -2477,8 +3102,23 @@ func (c *AutoScaling) DescribeTagsRequest(input *DescribeTagsInput) (req *reques // Please also see https://docs.aws.amazon.com/goto/WebAPI/autoscaling-2011-01-01/DescribeTags func (c *AutoScaling) DescribeTags(input *DescribeTagsInput) (*DescribeTagsOutput, error) { req, out := c.DescribeTagsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeTagsWithContext is the same as DescribeTags with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeTags 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 *AutoScaling) DescribeTagsWithContext(ctx aws.Context, input *DescribeTagsInput, opts ...request.Option) (*DescribeTagsOutput, error) { + req, out := c.DescribeTagsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // DescribeTagsPages iterates over the pages of a DescribeTags operation, @@ -2498,12 +3138,37 @@ func (c *AutoScaling) DescribeTags(input *DescribeTagsInput) (*DescribeTagsOutpu // return pageNum <= 3 // }) // -func (c *AutoScaling) DescribeTagsPages(input *DescribeTagsInput, fn func(p *DescribeTagsOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.DescribeTagsRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*DescribeTagsOutput), lastPage) - }) +func (c *AutoScaling) DescribeTagsPages(input *DescribeTagsInput, fn func(*DescribeTagsOutput, bool) bool) error { + return c.DescribeTagsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// DescribeTagsPagesWithContext same as DescribeTagsPages 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 *AutoScaling) DescribeTagsPagesWithContext(ctx aws.Context, input *DescribeTagsInput, fn func(*DescribeTagsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *DescribeTagsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeTagsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*DescribeTagsOutput), !p.HasNextPage()) + } + return p.Err() } const opDescribeTerminationPolicyTypes = "DescribeTerminationPolicyTypes" @@ -2568,8 +3233,23 @@ func (c *AutoScaling) DescribeTerminationPolicyTypesRequest(input *DescribeTermi // Please also see https://docs.aws.amazon.com/goto/WebAPI/autoscaling-2011-01-01/DescribeTerminationPolicyTypes func (c *AutoScaling) DescribeTerminationPolicyTypes(input *DescribeTerminationPolicyTypesInput) (*DescribeTerminationPolicyTypesOutput, error) { req, out := c.DescribeTerminationPolicyTypesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeTerminationPolicyTypesWithContext is the same as DescribeTerminationPolicyTypes with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeTerminationPolicyTypes 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 *AutoScaling) DescribeTerminationPolicyTypesWithContext(ctx aws.Context, input *DescribeTerminationPolicyTypesInput, opts ...request.Option) (*DescribeTerminationPolicyTypesOutput, error) { + req, out := c.DescribeTerminationPolicyTypesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDetachInstances = "DetachInstances" @@ -2649,8 +3329,23 @@ func (c *AutoScaling) DetachInstancesRequest(input *DetachInstancesInput) (req * // Please also see https://docs.aws.amazon.com/goto/WebAPI/autoscaling-2011-01-01/DetachInstances func (c *AutoScaling) DetachInstances(input *DetachInstancesInput) (*DetachInstancesOutput, error) { req, out := c.DetachInstancesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DetachInstancesWithContext is the same as DetachInstances with the addition of +// the ability to pass a context and additional request options. +// +// See DetachInstances 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 *AutoScaling) DetachInstancesWithContext(ctx aws.Context, input *DetachInstancesInput, opts ...request.Option) (*DetachInstancesOutput, error) { + req, out := c.DetachInstancesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDetachLoadBalancerTargetGroups = "DetachLoadBalancerTargetGroups" @@ -2715,8 +3410,23 @@ func (c *AutoScaling) DetachLoadBalancerTargetGroupsRequest(input *DetachLoadBal // Please also see https://docs.aws.amazon.com/goto/WebAPI/autoscaling-2011-01-01/DetachLoadBalancerTargetGroups func (c *AutoScaling) DetachLoadBalancerTargetGroups(input *DetachLoadBalancerTargetGroupsInput) (*DetachLoadBalancerTargetGroupsOutput, error) { req, out := c.DetachLoadBalancerTargetGroupsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DetachLoadBalancerTargetGroupsWithContext is the same as DetachLoadBalancerTargetGroups with the addition of +// the ability to pass a context and additional request options. +// +// See DetachLoadBalancerTargetGroups 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 *AutoScaling) DetachLoadBalancerTargetGroupsWithContext(ctx aws.Context, input *DetachLoadBalancerTargetGroupsInput, opts ...request.Option) (*DetachLoadBalancerTargetGroupsOutput, error) { + req, out := c.DetachLoadBalancerTargetGroupsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDetachLoadBalancers = "DetachLoadBalancers" @@ -2790,8 +3500,23 @@ func (c *AutoScaling) DetachLoadBalancersRequest(input *DetachLoadBalancersInput // Please also see https://docs.aws.amazon.com/goto/WebAPI/autoscaling-2011-01-01/DetachLoadBalancers func (c *AutoScaling) DetachLoadBalancers(input *DetachLoadBalancersInput) (*DetachLoadBalancersOutput, error) { req, out := c.DetachLoadBalancersRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DetachLoadBalancersWithContext is the same as DetachLoadBalancers with the addition of +// the ability to pass a context and additional request options. +// +// See DetachLoadBalancers 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 *AutoScaling) DetachLoadBalancersWithContext(ctx aws.Context, input *DetachLoadBalancersInput, opts ...request.Option) (*DetachLoadBalancersOutput, error) { + req, out := c.DetachLoadBalancersRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDisableMetricsCollection = "DisableMetricsCollection" @@ -2858,8 +3583,23 @@ func (c *AutoScaling) DisableMetricsCollectionRequest(input *DisableMetricsColle // Please also see https://docs.aws.amazon.com/goto/WebAPI/autoscaling-2011-01-01/DisableMetricsCollection func (c *AutoScaling) DisableMetricsCollection(input *DisableMetricsCollectionInput) (*DisableMetricsCollectionOutput, error) { req, out := c.DisableMetricsCollectionRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DisableMetricsCollectionWithContext is the same as DisableMetricsCollection with the addition of +// the ability to pass a context and additional request options. +// +// See DisableMetricsCollection 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 *AutoScaling) DisableMetricsCollectionWithContext(ctx aws.Context, input *DisableMetricsCollectionInput, opts ...request.Option) (*DisableMetricsCollectionOutput, error) { + req, out := c.DisableMetricsCollectionRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opEnableMetricsCollection = "EnableMetricsCollection" @@ -2928,8 +3668,23 @@ func (c *AutoScaling) EnableMetricsCollectionRequest(input *EnableMetricsCollect // Please also see https://docs.aws.amazon.com/goto/WebAPI/autoscaling-2011-01-01/EnableMetricsCollection func (c *AutoScaling) EnableMetricsCollection(input *EnableMetricsCollectionInput) (*EnableMetricsCollectionOutput, error) { req, out := c.EnableMetricsCollectionRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// EnableMetricsCollectionWithContext is the same as EnableMetricsCollection with the addition of +// the ability to pass a context and additional request options. +// +// See EnableMetricsCollection 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 *AutoScaling) EnableMetricsCollectionWithContext(ctx aws.Context, input *EnableMetricsCollectionInput, opts ...request.Option) (*EnableMetricsCollectionOutput, error) { + req, out := c.EnableMetricsCollectionRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opEnterStandby = "EnterStandby" @@ -2997,8 +3752,23 @@ func (c *AutoScaling) EnterStandbyRequest(input *EnterStandbyInput) (req *reques // Please also see https://docs.aws.amazon.com/goto/WebAPI/autoscaling-2011-01-01/EnterStandby func (c *AutoScaling) EnterStandby(input *EnterStandbyInput) (*EnterStandbyOutput, error) { req, out := c.EnterStandbyRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// EnterStandbyWithContext is the same as EnterStandby with the addition of +// the ability to pass a context and additional request options. +// +// See EnterStandby 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 *AutoScaling) EnterStandbyWithContext(ctx aws.Context, input *EnterStandbyInput, opts ...request.Option) (*EnterStandbyOutput, error) { + req, out := c.EnterStandbyRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opExecutePolicy = "ExecutePolicy" @@ -3069,8 +3839,23 @@ func (c *AutoScaling) ExecutePolicyRequest(input *ExecutePolicyInput) (req *requ // Please also see https://docs.aws.amazon.com/goto/WebAPI/autoscaling-2011-01-01/ExecutePolicy func (c *AutoScaling) ExecutePolicy(input *ExecutePolicyInput) (*ExecutePolicyOutput, error) { req, out := c.ExecutePolicyRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ExecutePolicyWithContext is the same as ExecutePolicy with the addition of +// the ability to pass a context and additional request options. +// +// See ExecutePolicy 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 *AutoScaling) ExecutePolicyWithContext(ctx aws.Context, input *ExecutePolicyInput, opts ...request.Option) (*ExecutePolicyOutput, error) { + req, out := c.ExecutePolicyRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opExitStandby = "ExitStandby" @@ -3138,8 +3923,23 @@ func (c *AutoScaling) ExitStandbyRequest(input *ExitStandbyInput) (req *request. // Please also see https://docs.aws.amazon.com/goto/WebAPI/autoscaling-2011-01-01/ExitStandby func (c *AutoScaling) ExitStandby(input *ExitStandbyInput) (*ExitStandbyOutput, error) { req, out := c.ExitStandbyRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ExitStandbyWithContext is the same as ExitStandby with the addition of +// the ability to pass a context and additional request options. +// +// See ExitStandby 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 *AutoScaling) ExitStandbyWithContext(ctx aws.Context, input *ExitStandbyInput, opts ...request.Option) (*ExitStandbyOutput, error) { + req, out := c.ExitStandbyRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opPutLifecycleHook = "PutLifecycleHook" @@ -3239,8 +4039,23 @@ func (c *AutoScaling) PutLifecycleHookRequest(input *PutLifecycleHookInput) (req // Please also see https://docs.aws.amazon.com/goto/WebAPI/autoscaling-2011-01-01/PutLifecycleHook func (c *AutoScaling) PutLifecycleHook(input *PutLifecycleHookInput) (*PutLifecycleHookOutput, error) { req, out := c.PutLifecycleHookRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// PutLifecycleHookWithContext is the same as PutLifecycleHook with the addition of +// the ability to pass a context and additional request options. +// +// See PutLifecycleHook 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 *AutoScaling) PutLifecycleHookWithContext(ctx aws.Context, input *PutLifecycleHookInput, opts ...request.Option) (*PutLifecycleHookOutput, error) { + req, out := c.PutLifecycleHookRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opPutNotificationConfiguration = "PutNotificationConfiguration" @@ -3320,8 +4135,23 @@ func (c *AutoScaling) PutNotificationConfigurationRequest(input *PutNotification // Please also see https://docs.aws.amazon.com/goto/WebAPI/autoscaling-2011-01-01/PutNotificationConfiguration func (c *AutoScaling) PutNotificationConfiguration(input *PutNotificationConfigurationInput) (*PutNotificationConfigurationOutput, error) { req, out := c.PutNotificationConfigurationRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// PutNotificationConfigurationWithContext is the same as PutNotificationConfiguration with the addition of +// the ability to pass a context and additional request options. +// +// See PutNotificationConfiguration 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 *AutoScaling) PutNotificationConfigurationWithContext(ctx aws.Context, input *PutNotificationConfigurationInput, opts ...request.Option) (*PutNotificationConfigurationOutput, error) { + req, out := c.PutNotificationConfigurationRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opPutScalingPolicy = "PutScalingPolicy" @@ -3399,8 +4229,23 @@ func (c *AutoScaling) PutScalingPolicyRequest(input *PutScalingPolicyInput) (req // Please also see https://docs.aws.amazon.com/goto/WebAPI/autoscaling-2011-01-01/PutScalingPolicy func (c *AutoScaling) PutScalingPolicy(input *PutScalingPolicyInput) (*PutScalingPolicyOutput, error) { req, out := c.PutScalingPolicyRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// PutScalingPolicyWithContext is the same as PutScalingPolicy with the addition of +// the ability to pass a context and additional request options. +// +// See PutScalingPolicy 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 *AutoScaling) PutScalingPolicyWithContext(ctx aws.Context, input *PutScalingPolicyInput, opts ...request.Option) (*PutScalingPolicyOutput, error) { + req, out := c.PutScalingPolicyRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opPutScheduledUpdateGroupAction = "PutScheduledUpdateGroupAction" @@ -3481,8 +4326,23 @@ func (c *AutoScaling) PutScheduledUpdateGroupActionRequest(input *PutScheduledUp // Please also see https://docs.aws.amazon.com/goto/WebAPI/autoscaling-2011-01-01/PutScheduledUpdateGroupAction func (c *AutoScaling) PutScheduledUpdateGroupAction(input *PutScheduledUpdateGroupActionInput) (*PutScheduledUpdateGroupActionOutput, error) { req, out := c.PutScheduledUpdateGroupActionRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// PutScheduledUpdateGroupActionWithContext is the same as PutScheduledUpdateGroupAction with the addition of +// the ability to pass a context and additional request options. +// +// See PutScheduledUpdateGroupAction 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 *AutoScaling) PutScheduledUpdateGroupActionWithContext(ctx aws.Context, input *PutScheduledUpdateGroupActionInput, opts ...request.Option) (*PutScheduledUpdateGroupActionOutput, error) { + req, out := c.PutScheduledUpdateGroupActionRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opRecordLifecycleActionHeartbeat = "RecordLifecycleActionHeartbeat" @@ -3570,8 +4430,23 @@ func (c *AutoScaling) RecordLifecycleActionHeartbeatRequest(input *RecordLifecyc // Please also see https://docs.aws.amazon.com/goto/WebAPI/autoscaling-2011-01-01/RecordLifecycleActionHeartbeat func (c *AutoScaling) RecordLifecycleActionHeartbeat(input *RecordLifecycleActionHeartbeatInput) (*RecordLifecycleActionHeartbeatOutput, error) { req, out := c.RecordLifecycleActionHeartbeatRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// RecordLifecycleActionHeartbeatWithContext is the same as RecordLifecycleActionHeartbeat with the addition of +// the ability to pass a context and additional request options. +// +// See RecordLifecycleActionHeartbeat 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 *AutoScaling) RecordLifecycleActionHeartbeatWithContext(ctx aws.Context, input *RecordLifecycleActionHeartbeatInput, opts ...request.Option) (*RecordLifecycleActionHeartbeatOutput, error) { + req, out := c.RecordLifecycleActionHeartbeatRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opResumeProcesses = "ResumeProcesses" @@ -3646,8 +4521,23 @@ func (c *AutoScaling) ResumeProcessesRequest(input *ScalingProcessQuery) (req *r // Please also see https://docs.aws.amazon.com/goto/WebAPI/autoscaling-2011-01-01/ResumeProcesses func (c *AutoScaling) ResumeProcesses(input *ScalingProcessQuery) (*ResumeProcessesOutput, error) { req, out := c.ResumeProcessesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ResumeProcessesWithContext is the same as ResumeProcesses with the addition of +// the ability to pass a context and additional request options. +// +// See ResumeProcesses 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 *AutoScaling) ResumeProcessesWithContext(ctx aws.Context, input *ScalingProcessQuery, opts ...request.Option) (*ResumeProcessesOutput, error) { + req, out := c.ResumeProcessesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opSetDesiredCapacity = "SetDesiredCapacity" @@ -3721,8 +4611,23 @@ func (c *AutoScaling) SetDesiredCapacityRequest(input *SetDesiredCapacityInput) // Please also see https://docs.aws.amazon.com/goto/WebAPI/autoscaling-2011-01-01/SetDesiredCapacity func (c *AutoScaling) SetDesiredCapacity(input *SetDesiredCapacityInput) (*SetDesiredCapacityOutput, error) { req, out := c.SetDesiredCapacityRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// SetDesiredCapacityWithContext is the same as SetDesiredCapacity with the addition of +// the ability to pass a context and additional request options. +// +// See SetDesiredCapacity 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 *AutoScaling) SetDesiredCapacityWithContext(ctx aws.Context, input *SetDesiredCapacityInput, opts ...request.Option) (*SetDesiredCapacityOutput, error) { + req, out := c.SetDesiredCapacityRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opSetInstanceHealth = "SetInstanceHealth" @@ -3792,8 +4697,23 @@ func (c *AutoScaling) SetInstanceHealthRequest(input *SetInstanceHealthInput) (r // Please also see https://docs.aws.amazon.com/goto/WebAPI/autoscaling-2011-01-01/SetInstanceHealth func (c *AutoScaling) SetInstanceHealth(input *SetInstanceHealthInput) (*SetInstanceHealthOutput, error) { req, out := c.SetInstanceHealthRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// SetInstanceHealthWithContext is the same as SetInstanceHealth with the addition of +// the ability to pass a context and additional request options. +// +// See SetInstanceHealth 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 *AutoScaling) SetInstanceHealthWithContext(ctx aws.Context, input *SetInstanceHealthInput, opts ...request.Option) (*SetInstanceHealthOutput, error) { + req, out := c.SetInstanceHealthRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opSetInstanceProtection = "SetInstanceProtection" @@ -3866,8 +4786,23 @@ func (c *AutoScaling) SetInstanceProtectionRequest(input *SetInstanceProtectionI // Please also see https://docs.aws.amazon.com/goto/WebAPI/autoscaling-2011-01-01/SetInstanceProtection func (c *AutoScaling) SetInstanceProtection(input *SetInstanceProtectionInput) (*SetInstanceProtectionOutput, error) { req, out := c.SetInstanceProtectionRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// SetInstanceProtectionWithContext is the same as SetInstanceProtection with the addition of +// the ability to pass a context and additional request options. +// +// See SetInstanceProtection 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 *AutoScaling) SetInstanceProtectionWithContext(ctx aws.Context, input *SetInstanceProtectionInput, opts ...request.Option) (*SetInstanceProtectionOutput, error) { + req, out := c.SetInstanceProtectionRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opSuspendProcesses = "SuspendProcesses" @@ -3947,8 +4882,23 @@ func (c *AutoScaling) SuspendProcessesRequest(input *ScalingProcessQuery) (req * // Please also see https://docs.aws.amazon.com/goto/WebAPI/autoscaling-2011-01-01/SuspendProcesses func (c *AutoScaling) SuspendProcesses(input *ScalingProcessQuery) (*SuspendProcessesOutput, error) { req, out := c.SuspendProcessesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// SuspendProcessesWithContext is the same as SuspendProcesses with the addition of +// the ability to pass a context and additional request options. +// +// See SuspendProcesses 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 *AutoScaling) SuspendProcessesWithContext(ctx aws.Context, input *ScalingProcessQuery, opts ...request.Option) (*SuspendProcessesOutput, error) { + req, out := c.SuspendProcessesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opTerminateInstanceInAutoScalingGroup = "TerminateInstanceInAutoScalingGroup" @@ -4021,8 +4971,23 @@ func (c *AutoScaling) TerminateInstanceInAutoScalingGroupRequest(input *Terminat // Please also see https://docs.aws.amazon.com/goto/WebAPI/autoscaling-2011-01-01/TerminateInstanceInAutoScalingGroup func (c *AutoScaling) TerminateInstanceInAutoScalingGroup(input *TerminateInstanceInAutoScalingGroupInput) (*TerminateInstanceInAutoScalingGroupOutput, error) { req, out := c.TerminateInstanceInAutoScalingGroupRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// TerminateInstanceInAutoScalingGroupWithContext is the same as TerminateInstanceInAutoScalingGroup with the addition of +// the ability to pass a context and additional request options. +// +// See TerminateInstanceInAutoScalingGroup 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 *AutoScaling) TerminateInstanceInAutoScalingGroupWithContext(ctx aws.Context, input *TerminateInstanceInAutoScalingGroupInput, opts ...request.Option) (*TerminateInstanceInAutoScalingGroupOutput, error) { + req, out := c.TerminateInstanceInAutoScalingGroupRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opUpdateAutoScalingGroup = "UpdateAutoScalingGroup" @@ -4116,8 +5081,23 @@ func (c *AutoScaling) UpdateAutoScalingGroupRequest(input *UpdateAutoScalingGrou // Please also see https://docs.aws.amazon.com/goto/WebAPI/autoscaling-2011-01-01/UpdateAutoScalingGroup func (c *AutoScaling) UpdateAutoScalingGroup(input *UpdateAutoScalingGroupInput) (*UpdateAutoScalingGroupOutput, error) { req, out := c.UpdateAutoScalingGroupRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// UpdateAutoScalingGroupWithContext is the same as UpdateAutoScalingGroup with the addition of +// the ability to pass a context and additional request options. +// +// See UpdateAutoScalingGroup 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 *AutoScaling) UpdateAutoScalingGroupWithContext(ctx aws.Context, input *UpdateAutoScalingGroupInput, opts ...request.Option) (*UpdateAutoScalingGroupOutput, error) { + req, out := c.UpdateAutoScalingGroupRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // Describes scaling activity, which is a long-running process that represents diff --git a/vendor/github.com/aws/aws-sdk-go/service/autoscaling/doc.go b/vendor/github.com/aws/aws-sdk-go/service/autoscaling/doc.go new file mode 100644 index 000000000..a5c51a514 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/service/autoscaling/doc.go @@ -0,0 +1,82 @@ +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. + +// Package autoscaling provides the client and types for making API +// requests to Auto Scaling. +// +// Auto Scaling is designed to automatically launch or terminate EC2 instances +// based on user-defined policies, schedules, and health checks. Use this service +// in conjunction with the Amazon CloudWatch and Elastic Load Balancing services. +// +// See https://docs.aws.amazon.com/goto/WebAPI/autoscaling-2011-01-01 for more information on this service. +// +// See autoscaling package documentation for more information. +// https://docs.aws.amazon.com/sdk-for-go/api/service/autoscaling/ +// +// Using the Client +// +// To use the client for Auto Scaling you will first need +// to create a new instance of it. +// +// When creating a client for an AWS service you'll first need to have a Session +// already created. The Session provides configuration that can be shared +// between multiple service clients. Additional configuration can be applied to +// the Session and service's client when they are constructed. The aws package's +// Config type contains several fields such as Region for the AWS Region the +// client should make API requests too. The optional Config value can be provided +// as the variadic argument for Sessions and client creation. +// +// Once the service's client is created you can use it to make API requests the +// AWS service. These clients are safe to use concurrently. +// +// // Create a session to share configuration, and load external configuration. +// sess := session.Must(session.NewSession()) +// +// // Create the service's client with the session. +// svc := autoscaling.New(sess) +// +// See the SDK's documentation for more information on how to use service clients. +// https://docs.aws.amazon.com/sdk-for-go/api/ +// +// See aws package's Config type for more information on configuration options. +// https://docs.aws.amazon.com/sdk-for-go/api/aws/#Config +// +// See the Auto Scaling client AutoScaling for more +// information on creating the service's client. +// https://docs.aws.amazon.com/sdk-for-go/api/service/autoscaling/#New +// +// Once the client is created you can make an API request to the service. +// Each API method takes a input parameter, and returns the service response +// and an error. +// +// The API method will document which error codes the service can be returned +// by the operation if the service models the API operation's errors. These +// errors will also be available as const strings prefixed with "ErrCode". +// +// result, err := svc.AttachInstances(params) +// if err != nil { +// // Cast err to awserr.Error to handle specific error codes. +// aerr, ok := err.(awserr.Error) +// if ok && aerr.Code() == { +// // Specific error code handling +// } +// return err +// } +// +// fmt.Println("AttachInstances result:") +// fmt.Println(result) +// +// Using the Client with Context +// +// The service's client also provides methods to make API requests with a Context +// value. This allows you to control the timeout, and cancellation of pending +// requests. These methods also take request Option as variadic parameter to apply +// additional configuration to the API request. +// +// ctx := context.Background() +// +// result, err := svc.AttachInstancesWithContext(ctx, params) +// +// See the request package documentation for more information on using Context pattern +// with the SDK. +// https://docs.aws.amazon.com/sdk-for-go/api/aws/request/ +package autoscaling diff --git a/vendor/github.com/aws/aws-sdk-go/service/autoscaling/errors.go b/vendor/github.com/aws/aws-sdk-go/service/autoscaling/errors.go index 227e6b3b3..68ab1e3c1 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/autoscaling/errors.go +++ b/vendor/github.com/aws/aws-sdk-go/service/autoscaling/errors.go @@ -1,4 +1,4 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. package autoscaling diff --git a/vendor/github.com/aws/aws-sdk-go/service/autoscaling/service.go b/vendor/github.com/aws/aws-sdk-go/service/autoscaling/service.go index 98e1bb4ad..5e63d1c03 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/autoscaling/service.go +++ b/vendor/github.com/aws/aws-sdk-go/service/autoscaling/service.go @@ -1,4 +1,4 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. package autoscaling @@ -11,12 +11,12 @@ import ( "github.com/aws/aws-sdk-go/private/protocol/query" ) -// Auto Scaling is designed to automatically launch or terminate EC2 instances -// based on user-defined policies, schedules, and health checks. Use this service -// in conjunction with the Amazon CloudWatch and Elastic Load Balancing services. -// The service client's operations are safe to be used concurrently. -// It is not safe to mutate any of the client's properties though. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/autoscaling-2011-01-01 +// AutoScaling provides the API operation methods for making requests to +// Auto Scaling. See this package's package overview docs +// for details on the service. +// +// AutoScaling methods are safe to use concurrently. It is not safe to +// modify mutate any of the struct's properties though. type AutoScaling struct { *client.Client } diff --git a/vendor/github.com/aws/aws-sdk-go/service/autoscaling/waiters.go b/vendor/github.com/aws/aws-sdk-go/service/autoscaling/waiters.go index 15a9fd86e..1b1c5a3a1 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/autoscaling/waiters.go +++ b/vendor/github.com/aws/aws-sdk-go/service/autoscaling/waiters.go @@ -1,9 +1,12 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. package autoscaling import ( - "github.com/aws/aws-sdk-go/private/waiter" + "time" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/request" ) // WaitUntilGroupExists uses the Auto Scaling API operation @@ -11,32 +14,50 @@ import ( // If the condition is not meet within the max attempt window an error will // be returned. func (c *AutoScaling) WaitUntilGroupExists(input *DescribeAutoScalingGroupsInput) error { - waiterCfg := waiter.Config{ - Operation: "DescribeAutoScalingGroups", - Delay: 5, + return c.WaitUntilGroupExistsWithContext(aws.BackgroundContext(), input) +} + +// WaitUntilGroupExistsWithContext is an extended version of WaitUntilGroupExists. +// 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 *AutoScaling) WaitUntilGroupExistsWithContext(ctx aws.Context, input *DescribeAutoScalingGroupsInput, opts ...request.WaiterOption) error { + w := request.Waiter{ + Name: "WaitUntilGroupExists", MaxAttempts: 10, - Acceptors: []waiter.WaitAcceptor{ + Delay: request.ConstantWaiterDelay(5 * time.Second), + Acceptors: []request.WaiterAcceptor{ { - State: "success", - Matcher: "path", - Argument: "length(AutoScalingGroups) > `0`", + State: request.SuccessWaiterState, + Matcher: request.PathWaiterMatch, Argument: "length(AutoScalingGroups) > `0`", Expected: true, }, { - State: "retry", - Matcher: "path", - Argument: "length(AutoScalingGroups) > `0`", + State: request.RetryWaiterState, + Matcher: request.PathWaiterMatch, Argument: "length(AutoScalingGroups) > `0`", Expected: false, }, }, + Logger: c.Config.Logger, + NewRequest: func(opts []request.Option) (*request.Request, error) { + var inCpy *DescribeAutoScalingGroupsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeAutoScalingGroupsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, } + w.ApplyOptions(opts...) - w := waiter.Waiter{ - Client: c, - Input: input, - Config: waiterCfg, - } - return w.Wait() + return w.WaitWithContext(ctx) } // WaitUntilGroupInService uses the Auto Scaling API operation @@ -44,32 +65,50 @@ func (c *AutoScaling) WaitUntilGroupExists(input *DescribeAutoScalingGroupsInput // If the condition is not meet within the max attempt window an error will // be returned. func (c *AutoScaling) WaitUntilGroupInService(input *DescribeAutoScalingGroupsInput) error { - waiterCfg := waiter.Config{ - Operation: "DescribeAutoScalingGroups", - Delay: 15, + return c.WaitUntilGroupInServiceWithContext(aws.BackgroundContext(), input) +} + +// WaitUntilGroupInServiceWithContext is an extended version of WaitUntilGroupInService. +// 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 *AutoScaling) WaitUntilGroupInServiceWithContext(ctx aws.Context, input *DescribeAutoScalingGroupsInput, opts ...request.WaiterOption) error { + w := request.Waiter{ + Name: "WaitUntilGroupInService", MaxAttempts: 40, - Acceptors: []waiter.WaitAcceptor{ + Delay: request.ConstantWaiterDelay(15 * time.Second), + Acceptors: []request.WaiterAcceptor{ { - State: "success", - Matcher: "path", - Argument: "contains(AutoScalingGroups[].[length(Instances[?LifecycleState=='InService']) >= MinSize][], `false`)", + State: request.SuccessWaiterState, + Matcher: request.PathWaiterMatch, Argument: "contains(AutoScalingGroups[].[length(Instances[?LifecycleState=='InService']) >= MinSize][], `false`)", Expected: false, }, { - State: "retry", - Matcher: "path", - Argument: "contains(AutoScalingGroups[].[length(Instances[?LifecycleState=='InService']) >= MinSize][], `false`)", + State: request.RetryWaiterState, + Matcher: request.PathWaiterMatch, Argument: "contains(AutoScalingGroups[].[length(Instances[?LifecycleState=='InService']) >= MinSize][], `false`)", Expected: true, }, }, + Logger: c.Config.Logger, + NewRequest: func(opts []request.Option) (*request.Request, error) { + var inCpy *DescribeAutoScalingGroupsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeAutoScalingGroupsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, } + w.ApplyOptions(opts...) - w := waiter.Waiter{ - Client: c, - Input: input, - Config: waiterCfg, - } - return w.Wait() + return w.WaitWithContext(ctx) } // WaitUntilGroupNotExists uses the Auto Scaling API operation @@ -77,30 +116,48 @@ func (c *AutoScaling) WaitUntilGroupInService(input *DescribeAutoScalingGroupsIn // If the condition is not meet within the max attempt window an error will // be returned. func (c *AutoScaling) WaitUntilGroupNotExists(input *DescribeAutoScalingGroupsInput) error { - waiterCfg := waiter.Config{ - Operation: "DescribeAutoScalingGroups", - Delay: 15, + return c.WaitUntilGroupNotExistsWithContext(aws.BackgroundContext(), input) +} + +// WaitUntilGroupNotExistsWithContext is an extended version of WaitUntilGroupNotExists. +// 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 *AutoScaling) WaitUntilGroupNotExistsWithContext(ctx aws.Context, input *DescribeAutoScalingGroupsInput, opts ...request.WaiterOption) error { + w := request.Waiter{ + Name: "WaitUntilGroupNotExists", MaxAttempts: 40, - Acceptors: []waiter.WaitAcceptor{ + Delay: request.ConstantWaiterDelay(15 * time.Second), + Acceptors: []request.WaiterAcceptor{ { - State: "success", - Matcher: "path", - Argument: "length(AutoScalingGroups) > `0`", + State: request.SuccessWaiterState, + Matcher: request.PathWaiterMatch, Argument: "length(AutoScalingGroups) > `0`", Expected: false, }, { - State: "retry", - Matcher: "path", - Argument: "length(AutoScalingGroups) > `0`", + State: request.RetryWaiterState, + Matcher: request.PathWaiterMatch, Argument: "length(AutoScalingGroups) > `0`", Expected: true, }, }, + Logger: c.Config.Logger, + NewRequest: func(opts []request.Option) (*request.Request, error) { + var inCpy *DescribeAutoScalingGroupsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeAutoScalingGroupsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, } + w.ApplyOptions(opts...) - w := waiter.Waiter{ - Client: c, - Input: input, - Config: waiterCfg, - } - return w.Wait() + return w.WaitWithContext(ctx) } diff --git a/vendor/github.com/aws/aws-sdk-go/service/cloudformation/api.go b/vendor/github.com/aws/aws-sdk-go/service/cloudformation/api.go index be60e851f..8b3470774 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/cloudformation/api.go +++ b/vendor/github.com/aws/aws-sdk-go/service/cloudformation/api.go @@ -1,11 +1,11 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. -// Package cloudformation provides a client for AWS CloudFormation. package cloudformation import ( "time" + "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awsutil" "github.com/aws/aws-sdk-go/aws/request" "github.com/aws/aws-sdk-go/private/protocol" @@ -70,11 +70,31 @@ func (c *CloudFormation) CancelUpdateStackRequest(input *CancelUpdateStackInput) // // See the AWS API reference guide for AWS CloudFormation's // API operation CancelUpdateStack for usage and error information. +// +// Returned Error Codes: +// * ErrCodeTokenAlreadyExistsException "TokenAlreadyExistsException" +// A client request token already exists. +// // Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudformation-2010-05-15/CancelUpdateStack func (c *CloudFormation) CancelUpdateStack(input *CancelUpdateStackInput) (*CancelUpdateStackOutput, error) { req, out := c.CancelUpdateStackRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CancelUpdateStackWithContext is the same as CancelUpdateStack with the addition of +// the ability to pass a context and additional request options. +// +// See CancelUpdateStack 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 *CloudFormation) CancelUpdateStackWithContext(ctx aws.Context, input *CancelUpdateStackInput, opts ...request.Option) (*CancelUpdateStackOutput, error) { + req, out := c.CancelUpdateStackRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opContinueUpdateRollback = "ContinueUpdateRollback" @@ -142,11 +162,31 @@ func (c *CloudFormation) ContinueUpdateRollbackRequest(input *ContinueUpdateRoll // // See the AWS API reference guide for AWS CloudFormation's // API operation ContinueUpdateRollback for usage and error information. +// +// Returned Error Codes: +// * ErrCodeTokenAlreadyExistsException "TokenAlreadyExistsException" +// A client request token already exists. +// // Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudformation-2010-05-15/ContinueUpdateRollback func (c *CloudFormation) ContinueUpdateRollback(input *ContinueUpdateRollbackInput) (*ContinueUpdateRollbackOutput, error) { req, out := c.ContinueUpdateRollbackRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ContinueUpdateRollbackWithContext is the same as ContinueUpdateRollback with the addition of +// the ability to pass a context and additional request options. +// +// See ContinueUpdateRollback 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 *CloudFormation) ContinueUpdateRollbackWithContext(ctx aws.Context, input *ContinueUpdateRollbackInput, opts ...request.Option) (*ContinueUpdateRollbackOutput, error) { + req, out := c.ContinueUpdateRollbackRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateChangeSet = "CreateChangeSet" @@ -194,21 +234,28 @@ func (c *CloudFormation) CreateChangeSetRequest(input *CreateChangeSetInput) (re // CreateChangeSet API operation for AWS CloudFormation. // -// Creates a list of changes for a stack. AWS CloudFormation generates the change -// set by comparing the template's information with the information that you -// submit. A change set can help you understand which resources AWS CloudFormation -// will change, and how it will change them, before you update your stack. Change -// sets allow you to check before making a change to avoid deleting or replacing -// critical resources. +// Creates a list of changes that will be applied to a stack so that you can +// review the changes before executing them. You can create a change set for +// a stack that doesn't exist or an existing stack. If you create a change set +// for a stack that doesn't exist, the change set shows all of the resources +// that AWS CloudFormation will create. If you create a change set for an existing +// stack, AWS CloudFormation compares the stack's information with the information +// that you submit in the change set and lists the differences. Use change sets +// to understand which resources AWS CloudFormation will create or change, and +// how it will change resources in an existing stack, before you create or update +// a stack. // -// AWS CloudFormation doesn't make any changes to the stack when you create -// a change set. To make the specified changes, you must execute the change -// set by using the ExecuteChangeSet action. -// -// After the call successfully completes, AWS CloudFormation starts creating -// the change set. To check the status of the change set, use the DescribeChangeSet +// To create a change set for a stack that doesn't exist, for the ChangeSetType +// parameter, specify CREATE. To create a change set for an existing stack, +// specify UPDATE for the ChangeSetType parameter. After the CreateChangeSet +// call successfully completes, AWS CloudFormation starts creating the change +// set. To check the status of the change set or to review it, use the DescribeChangeSet // action. // +// When you are satisfied with the changes the change set will make, execute +// the change set by using the ExecuteChangeSet action. AWS CloudFormation doesn't +// make changes until you execute the change set. +// // 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. @@ -230,8 +277,23 @@ func (c *CloudFormation) CreateChangeSetRequest(input *CreateChangeSetInput) (re // Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudformation-2010-05-15/CreateChangeSet func (c *CloudFormation) CreateChangeSet(input *CreateChangeSetInput) (*CreateChangeSetOutput, error) { req, out := c.CreateChangeSetRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateChangeSetWithContext is the same as CreateChangeSet with the addition of +// the ability to pass a context and additional request options. +// +// See CreateChangeSet 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 *CloudFormation) CreateChangeSetWithContext(ctx aws.Context, input *CreateChangeSetInput, opts ...request.Option) (*CreateChangeSetOutput, error) { + req, out := c.CreateChangeSetRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateStack = "CreateStack" @@ -297,6 +359,9 @@ func (c *CloudFormation) CreateStackRequest(input *CreateStackInput) (req *reque // * ErrCodeAlreadyExistsException "AlreadyExistsException" // Resource with the name requested already exists. // +// * ErrCodeTokenAlreadyExistsException "TokenAlreadyExistsException" +// A client request token already exists. +// // * ErrCodeInsufficientCapabilitiesException "InsufficientCapabilitiesException" // The template contains resources with capabilities that were not specified // in the Capabilities parameter. @@ -304,8 +369,23 @@ func (c *CloudFormation) CreateStackRequest(input *CreateStackInput) (req *reque // Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudformation-2010-05-15/CreateStack func (c *CloudFormation) CreateStack(input *CreateStackInput) (*CreateStackOutput, error) { req, out := c.CreateStackRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateStackWithContext is the same as CreateStack with the addition of +// the ability to pass a context and additional request options. +// +// See CreateStack 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 *CloudFormation) CreateStackWithContext(ctx aws.Context, input *CreateStackInput, opts ...request.Option) (*CreateStackOutput, error) { + req, out := c.CreateStackRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteChangeSet = "DeleteChangeSet" @@ -375,8 +455,23 @@ func (c *CloudFormation) DeleteChangeSetRequest(input *DeleteChangeSetInput) (re // Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudformation-2010-05-15/DeleteChangeSet func (c *CloudFormation) DeleteChangeSet(input *DeleteChangeSetInput) (*DeleteChangeSetOutput, error) { req, out := c.DeleteChangeSetRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteChangeSetWithContext is the same as DeleteChangeSet with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteChangeSet 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 *CloudFormation) DeleteChangeSetWithContext(ctx aws.Context, input *DeleteChangeSetInput, opts ...request.Option) (*DeleteChangeSetOutput, error) { + req, out := c.DeleteChangeSetRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteStack = "DeleteStack" @@ -436,11 +531,31 @@ func (c *CloudFormation) DeleteStackRequest(input *DeleteStackInput) (req *reque // // See the AWS API reference guide for AWS CloudFormation's // API operation DeleteStack for usage and error information. +// +// Returned Error Codes: +// * ErrCodeTokenAlreadyExistsException "TokenAlreadyExistsException" +// A client request token already exists. +// // Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudformation-2010-05-15/DeleteStack func (c *CloudFormation) DeleteStack(input *DeleteStackInput) (*DeleteStackOutput, error) { req, out := c.DeleteStackRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteStackWithContext is the same as DeleteStack with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteStack 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 *CloudFormation) DeleteStackWithContext(ctx aws.Context, input *DeleteStackInput, opts ...request.Option) (*DeleteStackOutput, error) { + req, out := c.DeleteStackRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeAccountLimits = "DescribeAccountLimits" @@ -500,8 +615,23 @@ func (c *CloudFormation) DescribeAccountLimitsRequest(input *DescribeAccountLimi // Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudformation-2010-05-15/DescribeAccountLimits func (c *CloudFormation) DescribeAccountLimits(input *DescribeAccountLimitsInput) (*DescribeAccountLimitsOutput, error) { req, out := c.DescribeAccountLimitsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeAccountLimitsWithContext is the same as DescribeAccountLimits with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeAccountLimits 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 *CloudFormation) DescribeAccountLimitsWithContext(ctx aws.Context, input *DescribeAccountLimitsInput, opts ...request.Option) (*DescribeAccountLimitsOutput, error) { + req, out := c.DescribeAccountLimitsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeChangeSet = "DescribeChangeSet" @@ -569,8 +699,23 @@ func (c *CloudFormation) DescribeChangeSetRequest(input *DescribeChangeSetInput) // Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudformation-2010-05-15/DescribeChangeSet func (c *CloudFormation) DescribeChangeSet(input *DescribeChangeSetInput) (*DescribeChangeSetOutput, error) { req, out := c.DescribeChangeSetRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeChangeSetWithContext is the same as DescribeChangeSet with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeChangeSet 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 *CloudFormation) DescribeChangeSetWithContext(ctx aws.Context, input *DescribeChangeSetInput, opts ...request.Option) (*DescribeChangeSetOutput, error) { + req, out := c.DescribeChangeSetRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeStackEvents = "DescribeStackEvents" @@ -640,8 +785,23 @@ func (c *CloudFormation) DescribeStackEventsRequest(input *DescribeStackEventsIn // Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudformation-2010-05-15/DescribeStackEvents func (c *CloudFormation) DescribeStackEvents(input *DescribeStackEventsInput) (*DescribeStackEventsOutput, error) { req, out := c.DescribeStackEventsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeStackEventsWithContext is the same as DescribeStackEvents with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeStackEvents 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 *CloudFormation) DescribeStackEventsWithContext(ctx aws.Context, input *DescribeStackEventsInput, opts ...request.Option) (*DescribeStackEventsOutput, error) { + req, out := c.DescribeStackEventsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // DescribeStackEventsPages iterates over the pages of a DescribeStackEvents operation, @@ -661,12 +821,37 @@ func (c *CloudFormation) DescribeStackEvents(input *DescribeStackEventsInput) (* // return pageNum <= 3 // }) // -func (c *CloudFormation) DescribeStackEventsPages(input *DescribeStackEventsInput, fn func(p *DescribeStackEventsOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.DescribeStackEventsRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*DescribeStackEventsOutput), lastPage) - }) +func (c *CloudFormation) DescribeStackEventsPages(input *DescribeStackEventsInput, fn func(*DescribeStackEventsOutput, bool) bool) error { + return c.DescribeStackEventsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// DescribeStackEventsPagesWithContext same as DescribeStackEventsPages 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 *CloudFormation) DescribeStackEventsPagesWithContext(ctx aws.Context, input *DescribeStackEventsInput, fn func(*DescribeStackEventsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *DescribeStackEventsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeStackEventsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*DescribeStackEventsOutput), !p.HasNextPage()) + } + return p.Err() } const opDescribeStackResource = "DescribeStackResource" @@ -728,8 +913,23 @@ func (c *CloudFormation) DescribeStackResourceRequest(input *DescribeStackResour // Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudformation-2010-05-15/DescribeStackResource func (c *CloudFormation) DescribeStackResource(input *DescribeStackResourceInput) (*DescribeStackResourceOutput, error) { req, out := c.DescribeStackResourceRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeStackResourceWithContext is the same as DescribeStackResource with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeStackResource 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 *CloudFormation) DescribeStackResourceWithContext(ctx aws.Context, input *DescribeStackResourceInput, opts ...request.Option) (*DescribeStackResourceOutput, error) { + req, out := c.DescribeStackResourceRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeStackResources = "DescribeStackResources" @@ -805,8 +1005,23 @@ func (c *CloudFormation) DescribeStackResourcesRequest(input *DescribeStackResou // Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudformation-2010-05-15/DescribeStackResources func (c *CloudFormation) DescribeStackResources(input *DescribeStackResourcesInput) (*DescribeStackResourcesOutput, error) { req, out := c.DescribeStackResourcesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeStackResourcesWithContext is the same as DescribeStackResources with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeStackResources 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 *CloudFormation) DescribeStackResourcesWithContext(ctx aws.Context, input *DescribeStackResourcesInput, opts ...request.Option) (*DescribeStackResourcesOutput, error) { + req, out := c.DescribeStackResourcesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeStacks = "DescribeStacks" @@ -874,8 +1089,23 @@ func (c *CloudFormation) DescribeStacksRequest(input *DescribeStacksInput) (req // Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudformation-2010-05-15/DescribeStacks func (c *CloudFormation) DescribeStacks(input *DescribeStacksInput) (*DescribeStacksOutput, error) { req, out := c.DescribeStacksRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeStacksWithContext is the same as DescribeStacks with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeStacks 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 *CloudFormation) DescribeStacksWithContext(ctx aws.Context, input *DescribeStacksInput, opts ...request.Option) (*DescribeStacksOutput, error) { + req, out := c.DescribeStacksRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // DescribeStacksPages iterates over the pages of a DescribeStacks operation, @@ -895,12 +1125,37 @@ func (c *CloudFormation) DescribeStacks(input *DescribeStacksInput) (*DescribeSt // return pageNum <= 3 // }) // -func (c *CloudFormation) DescribeStacksPages(input *DescribeStacksInput, fn func(p *DescribeStacksOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.DescribeStacksRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*DescribeStacksOutput), lastPage) - }) +func (c *CloudFormation) DescribeStacksPages(input *DescribeStacksInput, fn func(*DescribeStacksOutput, bool) bool) error { + return c.DescribeStacksPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// DescribeStacksPagesWithContext same as DescribeStacksPages 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 *CloudFormation) DescribeStacksPagesWithContext(ctx aws.Context, input *DescribeStacksInput, fn func(*DescribeStacksOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *DescribeStacksInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeStacksRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*DescribeStacksOutput), !p.HasNextPage()) + } + return p.Err() } const opEstimateTemplateCost = "EstimateTemplateCost" @@ -961,8 +1216,23 @@ func (c *CloudFormation) EstimateTemplateCostRequest(input *EstimateTemplateCost // Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudformation-2010-05-15/EstimateTemplateCost func (c *CloudFormation) EstimateTemplateCost(input *EstimateTemplateCostInput) (*EstimateTemplateCostOutput, error) { req, out := c.EstimateTemplateCostRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// EstimateTemplateCostWithContext is the same as EstimateTemplateCost with the addition of +// the ability to pass a context and additional request options. +// +// See EstimateTemplateCost 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 *CloudFormation) EstimateTemplateCostWithContext(ctx aws.Context, input *EstimateTemplateCostInput, opts ...request.Option) (*EstimateTemplateCostOutput, error) { + req, out := c.EstimateTemplateCostRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opExecuteChangeSet = "ExecuteChangeSet" @@ -1044,11 +1314,29 @@ func (c *CloudFormation) ExecuteChangeSetRequest(input *ExecuteChangeSetInput) ( // The template contains resources with capabilities that were not specified // in the Capabilities parameter. // +// * ErrCodeTokenAlreadyExistsException "TokenAlreadyExistsException" +// A client request token already exists. +// // Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudformation-2010-05-15/ExecuteChangeSet func (c *CloudFormation) ExecuteChangeSet(input *ExecuteChangeSetInput) (*ExecuteChangeSetOutput, error) { req, out := c.ExecuteChangeSetRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ExecuteChangeSetWithContext is the same as ExecuteChangeSet with the addition of +// the ability to pass a context and additional request options. +// +// See ExecuteChangeSet 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 *CloudFormation) ExecuteChangeSetWithContext(ctx aws.Context, input *ExecuteChangeSetInput, opts ...request.Option) (*ExecuteChangeSetOutput, error) { + req, out := c.ExecuteChangeSetRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetStackPolicy = "GetStackPolicy" @@ -1108,8 +1396,23 @@ func (c *CloudFormation) GetStackPolicyRequest(input *GetStackPolicyInput) (req // Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudformation-2010-05-15/GetStackPolicy func (c *CloudFormation) GetStackPolicy(input *GetStackPolicyInput) (*GetStackPolicyOutput, error) { req, out := c.GetStackPolicyRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetStackPolicyWithContext is the same as GetStackPolicy with the addition of +// the ability to pass a context and additional request options. +// +// See GetStackPolicy 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 *CloudFormation) GetStackPolicyWithContext(ctx aws.Context, input *GetStackPolicyInput, opts ...request.Option) (*GetStackPolicyOutput, error) { + req, out := c.GetStackPolicyRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetTemplate = "GetTemplate" @@ -1180,8 +1483,23 @@ func (c *CloudFormation) GetTemplateRequest(input *GetTemplateInput) (req *reque // Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudformation-2010-05-15/GetTemplate func (c *CloudFormation) GetTemplate(input *GetTemplateInput) (*GetTemplateOutput, error) { req, out := c.GetTemplateRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetTemplateWithContext is the same as GetTemplate with the addition of +// the ability to pass a context and additional request options. +// +// See GetTemplate 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 *CloudFormation) GetTemplateWithContext(ctx aws.Context, input *GetTemplateInput, opts ...request.Option) (*GetTemplateOutput, error) { + req, out := c.GetTemplateRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetTemplateSummary = "GetTemplateSummary" @@ -1249,8 +1567,23 @@ func (c *CloudFormation) GetTemplateSummaryRequest(input *GetTemplateSummaryInpu // Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudformation-2010-05-15/GetTemplateSummary func (c *CloudFormation) GetTemplateSummary(input *GetTemplateSummaryInput) (*GetTemplateSummaryOutput, error) { req, out := c.GetTemplateSummaryRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetTemplateSummaryWithContext is the same as GetTemplateSummary with the addition of +// the ability to pass a context and additional request options. +// +// See GetTemplateSummary 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 *CloudFormation) GetTemplateSummaryWithContext(ctx aws.Context, input *GetTemplateSummaryInput, opts ...request.Option) (*GetTemplateSummaryOutput, error) { + req, out := c.GetTemplateSummaryRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opListChangeSets = "ListChangeSets" @@ -1311,8 +1644,23 @@ func (c *CloudFormation) ListChangeSetsRequest(input *ListChangeSetsInput) (req // Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudformation-2010-05-15/ListChangeSets func (c *CloudFormation) ListChangeSets(input *ListChangeSetsInput) (*ListChangeSetsOutput, error) { req, out := c.ListChangeSetsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListChangeSetsWithContext is the same as ListChangeSets with the addition of +// the ability to pass a context and additional request options. +// +// See ListChangeSets 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 *CloudFormation) ListChangeSetsWithContext(ctx aws.Context, input *ListChangeSetsInput, opts ...request.Option) (*ListChangeSetsOutput, error) { + req, out := c.ListChangeSetsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opListExports = "ListExports" @@ -1347,6 +1695,12 @@ func (c *CloudFormation) ListExportsRequest(input *ListExportsInput) (req *reque Name: opListExports, HTTPMethod: "POST", HTTPPath: "/", + Paginator: &request.Paginator{ + InputTokens: []string{"NextToken"}, + OutputTokens: []string{"NextToken"}, + LimitToken: "", + TruncationToken: "", + }, } if input == nil { @@ -1377,8 +1731,73 @@ func (c *CloudFormation) ListExportsRequest(input *ListExportsInput) (req *reque // Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudformation-2010-05-15/ListExports func (c *CloudFormation) ListExports(input *ListExportsInput) (*ListExportsOutput, error) { req, out := c.ListExportsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListExportsWithContext is the same as ListExports with the addition of +// the ability to pass a context and additional request options. +// +// See ListExports 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 *CloudFormation) ListExportsWithContext(ctx aws.Context, input *ListExportsInput, opts ...request.Option) (*ListExportsOutput, error) { + req, out := c.ListExportsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +// ListExportsPages iterates over the pages of a ListExports operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See ListExports 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 ListExports operation. +// pageNum := 0 +// err := client.ListExportsPages(params, +// func(page *ListExportsOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *CloudFormation) ListExportsPages(input *ListExportsInput, fn func(*ListExportsOutput, bool) bool) error { + return c.ListExportsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListExportsPagesWithContext same as ListExportsPages 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 *CloudFormation) ListExportsPagesWithContext(ctx aws.Context, input *ListExportsInput, fn func(*ListExportsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListExportsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListExportsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*ListExportsOutput), !p.HasNextPage()) + } + return p.Err() } const opListImports = "ListImports" @@ -1413,6 +1832,12 @@ func (c *CloudFormation) ListImportsRequest(input *ListImportsInput) (req *reque Name: opListImports, HTTPMethod: "POST", HTTPPath: "/", + Paginator: &request.Paginator{ + InputTokens: []string{"NextToken"}, + OutputTokens: []string{"NextToken"}, + LimitToken: "", + TruncationToken: "", + }, } if input == nil { @@ -1443,8 +1868,73 @@ func (c *CloudFormation) ListImportsRequest(input *ListImportsInput) (req *reque // Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudformation-2010-05-15/ListImports func (c *CloudFormation) ListImports(input *ListImportsInput) (*ListImportsOutput, error) { req, out := c.ListImportsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListImportsWithContext is the same as ListImports with the addition of +// the ability to pass a context and additional request options. +// +// See ListImports 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 *CloudFormation) ListImportsWithContext(ctx aws.Context, input *ListImportsInput, opts ...request.Option) (*ListImportsOutput, error) { + req, out := c.ListImportsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +// ListImportsPages iterates over the pages of a ListImports operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See ListImports 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 ListImports operation. +// pageNum := 0 +// err := client.ListImportsPages(params, +// func(page *ListImportsOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *CloudFormation) ListImportsPages(input *ListImportsInput, fn func(*ListImportsOutput, bool) bool) error { + return c.ListImportsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListImportsPagesWithContext same as ListImportsPages 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 *CloudFormation) ListImportsPagesWithContext(ctx aws.Context, input *ListImportsInput, fn func(*ListImportsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListImportsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListImportsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*ListImportsOutput), !p.HasNextPage()) + } + return p.Err() } const opListStackResources = "ListStackResources" @@ -1512,8 +2002,23 @@ func (c *CloudFormation) ListStackResourcesRequest(input *ListStackResourcesInpu // Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudformation-2010-05-15/ListStackResources func (c *CloudFormation) ListStackResources(input *ListStackResourcesInput) (*ListStackResourcesOutput, error) { req, out := c.ListStackResourcesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListStackResourcesWithContext is the same as ListStackResources with the addition of +// the ability to pass a context and additional request options. +// +// See ListStackResources 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 *CloudFormation) ListStackResourcesWithContext(ctx aws.Context, input *ListStackResourcesInput, opts ...request.Option) (*ListStackResourcesOutput, error) { + req, out := c.ListStackResourcesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // ListStackResourcesPages iterates over the pages of a ListStackResources operation, @@ -1533,12 +2038,37 @@ func (c *CloudFormation) ListStackResources(input *ListStackResourcesInput) (*Li // return pageNum <= 3 // }) // -func (c *CloudFormation) ListStackResourcesPages(input *ListStackResourcesInput, fn func(p *ListStackResourcesOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.ListStackResourcesRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*ListStackResourcesOutput), lastPage) - }) +func (c *CloudFormation) ListStackResourcesPages(input *ListStackResourcesInput, fn func(*ListStackResourcesOutput, bool) bool) error { + return c.ListStackResourcesPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListStackResourcesPagesWithContext same as ListStackResourcesPages 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 *CloudFormation) ListStackResourcesPagesWithContext(ctx aws.Context, input *ListStackResourcesInput, fn func(*ListStackResourcesOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListStackResourcesInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListStackResourcesRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*ListStackResourcesOutput), !p.HasNextPage()) + } + return p.Err() } const opListStacks = "ListStacks" @@ -1607,8 +2137,23 @@ func (c *CloudFormation) ListStacksRequest(input *ListStacksInput) (req *request // Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudformation-2010-05-15/ListStacks func (c *CloudFormation) ListStacks(input *ListStacksInput) (*ListStacksOutput, error) { req, out := c.ListStacksRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListStacksWithContext is the same as ListStacks with the addition of +// the ability to pass a context and additional request options. +// +// See ListStacks 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 *CloudFormation) ListStacksWithContext(ctx aws.Context, input *ListStacksInput, opts ...request.Option) (*ListStacksOutput, error) { + req, out := c.ListStacksRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // ListStacksPages iterates over the pages of a ListStacks operation, @@ -1628,12 +2173,37 @@ func (c *CloudFormation) ListStacks(input *ListStacksInput) (*ListStacksOutput, // return pageNum <= 3 // }) // -func (c *CloudFormation) ListStacksPages(input *ListStacksInput, fn func(p *ListStacksOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.ListStacksRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*ListStacksOutput), lastPage) - }) +func (c *CloudFormation) ListStacksPages(input *ListStacksInput, fn func(*ListStacksOutput, bool) bool) error { + return c.ListStacksPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListStacksPagesWithContext same as ListStacksPages 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 *CloudFormation) ListStacksPagesWithContext(ctx aws.Context, input *ListStacksInput, fn func(*ListStacksOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListStacksInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListStacksRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*ListStacksOutput), !p.HasNextPage()) + } + return p.Err() } const opSetStackPolicy = "SetStackPolicy" @@ -1694,8 +2264,23 @@ func (c *CloudFormation) SetStackPolicyRequest(input *SetStackPolicyInput) (req // Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudformation-2010-05-15/SetStackPolicy func (c *CloudFormation) SetStackPolicy(input *SetStackPolicyInput) (*SetStackPolicyOutput, error) { req, out := c.SetStackPolicyRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// SetStackPolicyWithContext is the same as SetStackPolicy with the addition of +// the ability to pass a context and additional request options. +// +// See SetStackPolicy 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 *CloudFormation) SetStackPolicyWithContext(ctx aws.Context, input *SetStackPolicyInput, opts ...request.Option) (*SetStackPolicyOutput, error) { + req, out := c.SetStackPolicyRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opSignalResource = "SignalResource" @@ -1761,8 +2346,23 @@ func (c *CloudFormation) SignalResourceRequest(input *SignalResourceInput) (req // Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudformation-2010-05-15/SignalResource func (c *CloudFormation) SignalResource(input *SignalResourceInput) (*SignalResourceOutput, error) { req, out := c.SignalResourceRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// SignalResourceWithContext is the same as SignalResource with the addition of +// the ability to pass a context and additional request options. +// +// See SignalResource 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 *CloudFormation) SignalResourceWithContext(ctx aws.Context, input *SignalResourceInput, opts ...request.Option) (*SignalResourceOutput, error) { + req, out := c.SignalResourceRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opUpdateStack = "UpdateStack" @@ -1832,11 +2432,29 @@ func (c *CloudFormation) UpdateStackRequest(input *UpdateStackInput) (req *reque // The template contains resources with capabilities that were not specified // in the Capabilities parameter. // +// * ErrCodeTokenAlreadyExistsException "TokenAlreadyExistsException" +// A client request token already exists. +// // Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudformation-2010-05-15/UpdateStack func (c *CloudFormation) UpdateStack(input *UpdateStackInput) (*UpdateStackOutput, error) { req, out := c.UpdateStackRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// UpdateStackWithContext is the same as UpdateStack with the addition of +// the ability to pass a context and additional request options. +// +// See UpdateStack 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 *CloudFormation) UpdateStackWithContext(ctx aws.Context, input *UpdateStackInput, opts ...request.Option) (*UpdateStackOutput, error) { + req, out := c.UpdateStackRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opValidateTemplate = "ValidateTemplate" @@ -1898,8 +2516,23 @@ func (c *CloudFormation) ValidateTemplateRequest(input *ValidateTemplateInput) ( // Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudformation-2010-05-15/ValidateTemplate func (c *CloudFormation) ValidateTemplate(input *ValidateTemplateInput) (*ValidateTemplateOutput, error) { req, out := c.ValidateTemplateRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ValidateTemplateWithContext is the same as ValidateTemplate with the addition of +// the ability to pass a context and additional request options. +// +// See ValidateTemplate 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 *CloudFormation) ValidateTemplateWithContext(ctx aws.Context, input *ValidateTemplateInput, opts ...request.Option) (*ValidateTemplateOutput, error) { + req, out := c.ValidateTemplateRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // The AccountLimit data type. @@ -1941,6 +2574,13 @@ func (s *AccountLimit) SetValue(v int64) *AccountLimit { type CancelUpdateStackInput struct { _ struct{} `type:"structure"` + // A unique identifier for this CancelUpdateStack request. Specify this token + // if you plan to retry requests so that AWS CloudFormation knows that you're + // not attempting to cancel an update on a stack with the same name. You might + // retry CancelUpdateStack requests to ensure that AWS CloudFormation successfully + // received them. + ClientRequestToken *string `min:"1" type:"string"` + // The name or the unique stack ID that is associated with the stack. // // StackName is a required field @@ -1960,6 +2600,9 @@ func (s CancelUpdateStackInput) GoString() string { // Validate inspects the fields of the type to determine if they are valid. func (s *CancelUpdateStackInput) Validate() error { invalidParams := request.ErrInvalidParams{Context: "CancelUpdateStackInput"} + if s.ClientRequestToken != nil && len(*s.ClientRequestToken) < 1 { + invalidParams.Add(request.NewErrParamMinLen("ClientRequestToken", 1)) + } if s.StackName == nil { invalidParams.Add(request.NewErrParamRequired("StackName")) } @@ -1970,6 +2613,12 @@ func (s *CancelUpdateStackInput) Validate() error { return nil } +// SetClientRequestToken sets the ClientRequestToken field's value. +func (s *CancelUpdateStackInput) SetClientRequestToken(v string) *CancelUpdateStackInput { + s.ClientRequestToken = &v + return s +} + // SetStackName sets the StackName field's value. func (s *CancelUpdateStackInput) SetStackName(v string) *CancelUpdateStackInput { s.StackName = &v @@ -2137,6 +2786,13 @@ func (s *ChangeSetSummary) SetStatusReason(v string) *ChangeSetSummary { type ContinueUpdateRollbackInput struct { _ struct{} `type:"structure"` + // A unique identifier for this ContinueUpdateRollback request. Specify this + // token if you plan to retry requests so that AWS CloudFormation knows that + // you're not attempting to continue the rollback to a stack with the same name. + // You might retry ContinueUpdateRollback requests to ensure that AWS CloudFormation + // successfully received them. + ClientRequestToken *string `min:"1" type:"string"` + // A list of the logical IDs of the resources that AWS CloudFormation skips // during the continue update rollback operation. You can specify only resources // that are in the UPDATE_FAILED state because a rollback failed. You can't @@ -2160,9 +2816,9 @@ type ContinueUpdateRollbackInput struct { // to fail. In this case, it might not be necessary to skip the dependent resources. // // To specify resources in a nested stack, use the following format: NestedStackName.ResourceLogicalID. - // You can specify a nested stack resource (the logical ID of an AWS::CloudFormation::Stack - // resource) only if it's in one of the following states: DELETE_IN_PROGRESS, - // DELETE_COMPLETE, or DELETE_FAILED. + // If the ResourceLogicalID is a stack resource (Type: AWS::CloudFormation::Stack), + // it must be in one of the following states: DELETE_IN_PROGRESS, DELETE_COMPLETE, + // or DELETE_FAILED. ResourcesToSkip []*string `type:"list"` // The Amazon Resource Name (ARN) of an AWS Identity and Access Management (IAM) @@ -2203,6 +2859,9 @@ func (s ContinueUpdateRollbackInput) GoString() string { // Validate inspects the fields of the type to determine if they are valid. func (s *ContinueUpdateRollbackInput) Validate() error { invalidParams := request.ErrInvalidParams{Context: "ContinueUpdateRollbackInput"} + if s.ClientRequestToken != nil && len(*s.ClientRequestToken) < 1 { + invalidParams.Add(request.NewErrParamMinLen("ClientRequestToken", 1)) + } if s.RoleARN != nil && len(*s.RoleARN) < 20 { invalidParams.Add(request.NewErrParamMinLen("RoleARN", 20)) } @@ -2219,6 +2878,12 @@ func (s *ContinueUpdateRollbackInput) Validate() error { return nil } +// SetClientRequestToken sets the ClientRequestToken field's value. +func (s *ContinueUpdateRollbackInput) SetClientRequestToken(v string) *ContinueUpdateRollbackInput { + s.ClientRequestToken = &v + return s +} + // SetResourcesToSkip sets the ResourcesToSkip field's value. func (s *ContinueUpdateRollbackInput) SetResourcesToSkip(v []*string) *ContinueUpdateRollbackInput { s.ResourcesToSkip = v @@ -2581,6 +3246,12 @@ type CreateStackInput struct { // Templates (http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-iam-template.html#capabilities). Capabilities []*string `type:"list"` + // A unique identifier for this CreateStack request. Specify this token if you + // plan to retry requests so that AWS CloudFormation knows that you're not attempting + // to create a stack with the same name. You might retry CreateStack requests + // to ensure that AWS CloudFormation successfully received them. + ClientRequestToken *string `min:"1" type:"string"` + // Set to true to disable rollback of the stack if stack creation failed. You // can specify either DisableRollback or OnFailure, but not both. // @@ -2588,8 +3259,8 @@ type CreateStackInput struct { DisableRollback *bool `type:"boolean"` // The Simple Notification Service (SNS) topic ARNs to publish stack related - // events. You can find your SNS topic ARNs using the SNS console (https://console.aws.amazon.com/sns) - // or your Command Line Interface (CLI). + // events. You can find your SNS topic ARNs using the SNS console or your Command + // Line Interface (CLI). NotificationARNs []*string `type:"list"` // Determines what action will be taken if stack creation fails. This must be @@ -2697,6 +3368,9 @@ func (s CreateStackInput) GoString() string { // Validate inspects the fields of the type to determine if they are valid. func (s *CreateStackInput) Validate() error { invalidParams := request.ErrInvalidParams{Context: "CreateStackInput"} + if s.ClientRequestToken != nil && len(*s.ClientRequestToken) < 1 { + invalidParams.Add(request.NewErrParamMinLen("ClientRequestToken", 1)) + } if s.RoleARN != nil && len(*s.RoleARN) < 20 { invalidParams.Add(request.NewErrParamMinLen("RoleARN", 20)) } @@ -2731,6 +3405,12 @@ func (s *CreateStackInput) SetCapabilities(v []*string) *CreateStackInput { return s } +// SetClientRequestToken sets the ClientRequestToken field's value. +func (s *CreateStackInput) SetClientRequestToken(v string) *CreateStackInput { + s.ClientRequestToken = &v + return s +} + // SetDisableRollback sets the DisableRollback field's value. func (s *CreateStackInput) SetDisableRollback(v bool) *CreateStackInput { s.DisableRollback = &v @@ -2912,6 +3592,12 @@ func (s DeleteChangeSetOutput) GoString() string { type DeleteStackInput struct { _ struct{} `type:"structure"` + // A unique identifier for this DeleteStack request. Specify this token if you + // plan to retry requests so that AWS CloudFormation knows that you're not attempting + // to delete a stack with the same name. You might retry DeleteStack requests + // to ensure that AWS CloudFormation successfully received them. + ClientRequestToken *string `min:"1" type:"string"` + // For stacks in the DELETE_FAILED state, a list of resource logical IDs that // are associated with the resources you want to retain. During deletion, AWS // CloudFormation deletes the stack but does not delete the retained resources. @@ -2948,6 +3634,9 @@ func (s DeleteStackInput) GoString() string { // Validate inspects the fields of the type to determine if they are valid. func (s *DeleteStackInput) Validate() error { invalidParams := request.ErrInvalidParams{Context: "DeleteStackInput"} + if s.ClientRequestToken != nil && len(*s.ClientRequestToken) < 1 { + invalidParams.Add(request.NewErrParamMinLen("ClientRequestToken", 1)) + } if s.RoleARN != nil && len(*s.RoleARN) < 20 { invalidParams.Add(request.NewErrParamMinLen("RoleARN", 20)) } @@ -2961,6 +3650,12 @@ func (s *DeleteStackInput) Validate() error { return nil } +// SetClientRequestToken sets the ClientRequestToken field's value. +func (s *DeleteStackInput) SetClientRequestToken(v string) *DeleteStackInput { + s.ClientRequestToken = &v + return s +} + // SetRetainResources sets the RetainResources field's value. func (s *DeleteStackInput) SetRetainResources(v []*string) *DeleteStackInput { s.RetainResources = v @@ -3773,6 +4468,13 @@ type ExecuteChangeSetInput struct { // ChangeSetName is a required field ChangeSetName *string `min:"1" type:"string" required:"true"` + // A unique identifier for this ExecuteChangeSet request. Specify this token + // if you plan to retry requests so that AWS CloudFormation knows that you're + // not attempting to execute a change set to update a stack with the same name. + // You might retry ExecuteChangeSet requests to ensure that AWS CloudFormation + // successfully received them. + ClientRequestToken *string `min:"1" type:"string"` + // If you specified the name of a change set, specify the stack name or ID (ARN) // that is associated with the change set you want to execute. StackName *string `min:"1" type:"string"` @@ -3797,6 +4499,9 @@ func (s *ExecuteChangeSetInput) Validate() error { if s.ChangeSetName != nil && len(*s.ChangeSetName) < 1 { invalidParams.Add(request.NewErrParamMinLen("ChangeSetName", 1)) } + if s.ClientRequestToken != nil && len(*s.ClientRequestToken) < 1 { + invalidParams.Add(request.NewErrParamMinLen("ClientRequestToken", 1)) + } if s.StackName != nil && len(*s.StackName) < 1 { invalidParams.Add(request.NewErrParamMinLen("StackName", 1)) } @@ -3813,6 +4518,12 @@ func (s *ExecuteChangeSetInput) SetChangeSetName(v string) *ExecuteChangeSetInpu return s } +// SetClientRequestToken sets the ClientRequestToken field's value. +func (s *ExecuteChangeSetInput) SetClientRequestToken(v string) *ExecuteChangeSetInput { + s.ClientRequestToken = &v + return s +} + // SetStackName sets the StackName field's value. func (s *ExecuteChangeSetInput) SetStackName(v string) *ExecuteChangeSetInput { s.StackName = &v @@ -5474,6 +6185,13 @@ func (s *Stack) SetTimeoutInMinutes(v int64) *Stack { type StackEvent struct { _ struct{} `type:"structure"` + // The token passed to the operation that generated this event. + // + // For example, if you execute a CreateStack operation with the token token1, + // then all the StackEvents generated by that operation will have ClientRequestToken + // set as token1. + ClientRequestToken *string `min:"1" type:"string"` + // The unique ID of this event. // // EventId is a required field @@ -5526,6 +6244,12 @@ func (s StackEvent) GoString() string { return s.String() } +// SetClientRequestToken sets the ClientRequestToken field's value. +func (s *StackEvent) SetClientRequestToken(v string) *StackEvent { + s.ClientRequestToken = &v + return s +} + // SetEventId sets the EventId field's value. func (s *StackEvent) SetEventId(v string) *StackEvent { s.EventId = &v @@ -6111,6 +6835,12 @@ type UpdateStackInput struct { // Templates (http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-iam-template.html#capabilities). Capabilities []*string `type:"list"` + // A unique identifier for this UpdateStack request. Specify this token if you + // plan to retry requests so that AWS CloudFormation knows that you're not attempting + // to update a stack with the same name. You might retry UpdateStack requests + // to ensure that AWS CloudFormation successfully received them. + ClientRequestToken *string `min:"1" type:"string"` + // Amazon Simple Notification Service topic Amazon Resource Names (ARNs) that // AWS CloudFormation associates with the stack. Specify an empty list to remove // all notification topics. @@ -6201,8 +6931,8 @@ type UpdateStackInput struct { // (http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/template-anatomy.html) // in the AWS CloudFormation User Guide.) // - // Conditional: You must specify either the TemplateBody or the TemplateURL - // parameter, but not both. + // Conditional: You must specify only one of the following parameters: TemplateBody, + // TemplateURL, or set the UsePreviousTemplate to true. TemplateBody *string `min:"1" type:"string"` // Location of file containing the template body. The URL must point to a template @@ -6210,12 +6940,15 @@ type UpdateStackInput struct { // Anatomy (http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/template-anatomy.html) // in the AWS CloudFormation User Guide. // - // Conditional: You must specify either the TemplateBody or the TemplateURL - // parameter, but not both. + // Conditional: You must specify only one of the following parameters: TemplateBody, + // TemplateURL, or set the UsePreviousTemplate to true. TemplateURL *string `min:"1" type:"string"` // Reuse the existing template that is associated with the stack that you are // updating. + // + // Conditional: You must specify only one of the following parameters: TemplateBody, + // TemplateURL, or set the UsePreviousTemplate to true. UsePreviousTemplate *bool `type:"boolean"` } @@ -6232,6 +6965,9 @@ func (s UpdateStackInput) GoString() string { // Validate inspects the fields of the type to determine if they are valid. func (s *UpdateStackInput) Validate() error { invalidParams := request.ErrInvalidParams{Context: "UpdateStackInput"} + if s.ClientRequestToken != nil && len(*s.ClientRequestToken) < 1 { + invalidParams.Add(request.NewErrParamMinLen("ClientRequestToken", 1)) + } if s.RoleARN != nil && len(*s.RoleARN) < 20 { invalidParams.Add(request.NewErrParamMinLen("RoleARN", 20)) } @@ -6269,6 +7005,12 @@ func (s *UpdateStackInput) SetCapabilities(v []*string) *UpdateStackInput { return s } +// SetClientRequestToken sets the ClientRequestToken field's value. +func (s *UpdateStackInput) SetClientRequestToken(v string) *UpdateStackInput { + s.ClientRequestToken = &v + return s +} + // SetNotificationARNs sets the NotificationARNs field's value. func (s *UpdateStackInput) SetNotificationARNs(v []*string) *UpdateStackInput { s.NotificationARNs = v diff --git a/vendor/github.com/aws/aws-sdk-go/service/cloudformation/doc.go b/vendor/github.com/aws/aws-sdk-go/service/cloudformation/doc.go new file mode 100644 index 000000000..83600619a --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/service/cloudformation/doc.go @@ -0,0 +1,98 @@ +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. + +// Package cloudformation provides the client and types for making API +// requests to AWS CloudFormation. +// +// AWS CloudFormation allows you to create and manage AWS infrastructure deployments +// predictably and repeatedly. You can use AWS CloudFormation to leverage AWS +// products, such as Amazon Elastic Compute Cloud, Amazon Elastic Block Store, +// Amazon Simple Notification Service, Elastic Load Balancing, and Auto Scaling +// to build highly-reliable, highly scalable, cost-effective applications without +// creating or configuring the underlying AWS infrastructure. +// +// With AWS CloudFormation, you declare all of your resources and dependencies +// in a template file. The template defines a collection of resources as a single +// unit called a stack. AWS CloudFormation creates and deletes all member resources +// of the stack together and manages all dependencies between the resources +// for you. +// +// For more information about AWS CloudFormation, see the AWS CloudFormation +// Product Page (http://aws.amazon.com/cloudformation/). +// +// Amazon CloudFormation makes use of other AWS products. If you need additional +// technical information about a specific AWS product, you can find the product's +// technical documentation at docs.aws.amazon.com (http://docs.aws.amazon.com/). +// +// See https://docs.aws.amazon.com/goto/WebAPI/cloudformation-2010-05-15 for more information on this service. +// +// See cloudformation package documentation for more information. +// https://docs.aws.amazon.com/sdk-for-go/api/service/cloudformation/ +// +// Using the Client +// +// To use the client for AWS CloudFormation you will first need +// to create a new instance of it. +// +// When creating a client for an AWS service you'll first need to have a Session +// already created. The Session provides configuration that can be shared +// between multiple service clients. Additional configuration can be applied to +// the Session and service's client when they are constructed. The aws package's +// Config type contains several fields such as Region for the AWS Region the +// client should make API requests too. The optional Config value can be provided +// as the variadic argument for Sessions and client creation. +// +// Once the service's client is created you can use it to make API requests the +// AWS service. These clients are safe to use concurrently. +// +// // Create a session to share configuration, and load external configuration. +// sess := session.Must(session.NewSession()) +// +// // Create the service's client with the session. +// svc := cloudformation.New(sess) +// +// See the SDK's documentation for more information on how to use service clients. +// https://docs.aws.amazon.com/sdk-for-go/api/ +// +// See aws package's Config type for more information on configuration options. +// https://docs.aws.amazon.com/sdk-for-go/api/aws/#Config +// +// See the AWS CloudFormation client CloudFormation for more +// information on creating the service's client. +// https://docs.aws.amazon.com/sdk-for-go/api/service/cloudformation/#New +// +// Once the client is created you can make an API request to the service. +// Each API method takes a input parameter, and returns the service response +// and an error. +// +// The API method will document which error codes the service can be returned +// by the operation if the service models the API operation's errors. These +// errors will also be available as const strings prefixed with "ErrCode". +// +// result, err := svc.CancelUpdateStack(params) +// if err != nil { +// // Cast err to awserr.Error to handle specific error codes. +// aerr, ok := err.(awserr.Error) +// if ok && aerr.Code() == { +// // Specific error code handling +// } +// return err +// } +// +// fmt.Println("CancelUpdateStack result:") +// fmt.Println(result) +// +// Using the Client with Context +// +// The service's client also provides methods to make API requests with a Context +// value. This allows you to control the timeout, and cancellation of pending +// requests. These methods also take request Option as variadic parameter to apply +// additional configuration to the API request. +// +// ctx := context.Background() +// +// result, err := svc.CancelUpdateStackWithContext(ctx, params) +// +// See the request package documentation for more information on using Context pattern +// with the SDK. +// https://docs.aws.amazon.com/sdk-for-go/api/aws/request/ +package cloudformation diff --git a/vendor/github.com/aws/aws-sdk-go/service/cloudformation/errors.go b/vendor/github.com/aws/aws-sdk-go/service/cloudformation/errors.go index 29fae9221..8bcf9482c 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/cloudformation/errors.go +++ b/vendor/github.com/aws/aws-sdk-go/service/cloudformation/errors.go @@ -1,4 +1,4 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. package cloudformation @@ -37,4 +37,10 @@ const ( // // Quota for the resource has already been reached. ErrCodeLimitExceededException = "LimitExceededException" + + // ErrCodeTokenAlreadyExistsException for service response error code + // "TokenAlreadyExistsException". + // + // A client request token already exists. + ErrCodeTokenAlreadyExistsException = "TokenAlreadyExistsException" ) diff --git a/vendor/github.com/aws/aws-sdk-go/service/cloudformation/service.go b/vendor/github.com/aws/aws-sdk-go/service/cloudformation/service.go index 0591a3204..0115c5bb0 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/cloudformation/service.go +++ b/vendor/github.com/aws/aws-sdk-go/service/cloudformation/service.go @@ -1,4 +1,4 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. package cloudformation @@ -11,28 +11,12 @@ import ( "github.com/aws/aws-sdk-go/private/protocol/query" ) -// AWS CloudFormation allows you to create and manage AWS infrastructure deployments -// predictably and repeatedly. You can use AWS CloudFormation to leverage AWS -// products, such as Amazon Elastic Compute Cloud, Amazon Elastic Block Store, -// Amazon Simple Notification Service, Elastic Load Balancing, and Auto Scaling -// to build highly-reliable, highly scalable, cost-effective applications without -// creating or configuring the underlying AWS infrastructure. +// CloudFormation provides the API operation methods for making requests to +// AWS CloudFormation. See this package's package overview docs +// for details on the service. // -// With AWS CloudFormation, you declare all of your resources and dependencies -// in a template file. The template defines a collection of resources as a single -// unit called a stack. AWS CloudFormation creates and deletes all member resources -// of the stack together and manages all dependencies between the resources -// for you. -// -// For more information about AWS CloudFormation, see the AWS CloudFormation -// Product Page (http://aws.amazon.com/cloudformation/). -// -// Amazon CloudFormation makes use of other AWS products. For additional technical -// information about a specific AWS product, see its technical documentation -// (http://docs.aws.amazon.com/). -// The service client's operations are safe to be used concurrently. -// It is not safe to mutate any of the client's properties though. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudformation-2010-05-15 +// CloudFormation methods are safe to use concurrently. It is not safe to +// modify mutate any of the struct's properties though. type CloudFormation struct { *client.Client } diff --git a/vendor/github.com/aws/aws-sdk-go/service/cloudformation/waiters.go b/vendor/github.com/aws/aws-sdk-go/service/cloudformation/waiters.go index 5960e9443..e4454d381 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/cloudformation/waiters.go +++ b/vendor/github.com/aws/aws-sdk-go/service/cloudformation/waiters.go @@ -1,72 +1,144 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. package cloudformation import ( - "github.com/aws/aws-sdk-go/private/waiter" + "time" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/request" ) +// WaitUntilChangeSetCreateComplete uses the AWS CloudFormation API operation +// DescribeChangeSet to wait for a condition to be met before returning. +// If the condition is not meet within the max attempt window an error will +// be returned. +func (c *CloudFormation) WaitUntilChangeSetCreateComplete(input *DescribeChangeSetInput) error { + return c.WaitUntilChangeSetCreateCompleteWithContext(aws.BackgroundContext(), input) +} + +// WaitUntilChangeSetCreateCompleteWithContext is an extended version of WaitUntilChangeSetCreateComplete. +// 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 *CloudFormation) WaitUntilChangeSetCreateCompleteWithContext(ctx aws.Context, input *DescribeChangeSetInput, opts ...request.WaiterOption) error { + w := request.Waiter{ + Name: "WaitUntilChangeSetCreateComplete", + MaxAttempts: 120, + Delay: request.ConstantWaiterDelay(30 * time.Second), + Acceptors: []request.WaiterAcceptor{ + { + State: request.SuccessWaiterState, + Matcher: request.PathWaiterMatch, Argument: "Status", + Expected: "CREATE_COMPLETE", + }, + { + State: request.FailureWaiterState, + Matcher: request.PathWaiterMatch, Argument: "Status", + Expected: "FAILED", + }, + { + State: request.FailureWaiterState, + Matcher: request.ErrorWaiterMatch, + Expected: "ValidationError", + }, + }, + Logger: c.Config.Logger, + NewRequest: func(opts []request.Option) (*request.Request, error) { + var inCpy *DescribeChangeSetInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeChangeSetRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + w.ApplyOptions(opts...) + + return w.WaitWithContext(ctx) +} + // WaitUntilStackCreateComplete uses the AWS CloudFormation API operation // DescribeStacks to wait for a condition to be met before returning. // If the condition is not meet within the max attempt window an error will // be returned. func (c *CloudFormation) WaitUntilStackCreateComplete(input *DescribeStacksInput) error { - waiterCfg := waiter.Config{ - Operation: "DescribeStacks", - Delay: 30, + return c.WaitUntilStackCreateCompleteWithContext(aws.BackgroundContext(), input) +} + +// WaitUntilStackCreateCompleteWithContext is an extended version of WaitUntilStackCreateComplete. +// 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 *CloudFormation) WaitUntilStackCreateCompleteWithContext(ctx aws.Context, input *DescribeStacksInput, opts ...request.WaiterOption) error { + w := request.Waiter{ + Name: "WaitUntilStackCreateComplete", MaxAttempts: 120, - Acceptors: []waiter.WaitAcceptor{ + Delay: request.ConstantWaiterDelay(30 * time.Second), + Acceptors: []request.WaiterAcceptor{ { - State: "success", - Matcher: "pathAll", - Argument: "Stacks[].StackStatus", + State: request.SuccessWaiterState, + Matcher: request.PathAllWaiterMatch, Argument: "Stacks[].StackStatus", Expected: "CREATE_COMPLETE", }, { - State: "failure", - Matcher: "pathAny", - Argument: "Stacks[].StackStatus", + State: request.FailureWaiterState, + Matcher: request.PathAnyWaiterMatch, Argument: "Stacks[].StackStatus", Expected: "CREATE_FAILED", }, { - State: "failure", - Matcher: "pathAny", - Argument: "Stacks[].StackStatus", + State: request.FailureWaiterState, + Matcher: request.PathAnyWaiterMatch, Argument: "Stacks[].StackStatus", Expected: "DELETE_COMPLETE", }, { - State: "failure", - Matcher: "pathAny", - Argument: "Stacks[].StackStatus", + State: request.FailureWaiterState, + Matcher: request.PathAnyWaiterMatch, Argument: "Stacks[].StackStatus", Expected: "DELETE_FAILED", }, { - State: "failure", - Matcher: "pathAny", - Argument: "Stacks[].StackStatus", + State: request.FailureWaiterState, + Matcher: request.PathAnyWaiterMatch, Argument: "Stacks[].StackStatus", Expected: "ROLLBACK_FAILED", }, { - State: "failure", - Matcher: "pathAny", - Argument: "Stacks[].StackStatus", + State: request.FailureWaiterState, + Matcher: request.PathAnyWaiterMatch, Argument: "Stacks[].StackStatus", Expected: "ROLLBACK_COMPLETE", }, { - State: "failure", - Matcher: "error", - Argument: "", + State: request.FailureWaiterState, + Matcher: request.ErrorWaiterMatch, Expected: "ValidationError", }, }, + Logger: c.Config.Logger, + NewRequest: func(opts []request.Option) (*request.Request, error) { + var inCpy *DescribeStacksInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeStacksRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, } + w.ApplyOptions(opts...) - w := waiter.Waiter{ - Client: c, - Input: input, - Config: waiterCfg, - } - return w.Wait() + return w.WaitWithContext(ctx) } // WaitUntilStackDeleteComplete uses the AWS CloudFormation API operation @@ -74,62 +146,75 @@ func (c *CloudFormation) WaitUntilStackCreateComplete(input *DescribeStacksInput // If the condition is not meet within the max attempt window an error will // be returned. func (c *CloudFormation) WaitUntilStackDeleteComplete(input *DescribeStacksInput) error { - waiterCfg := waiter.Config{ - Operation: "DescribeStacks", - Delay: 30, + return c.WaitUntilStackDeleteCompleteWithContext(aws.BackgroundContext(), input) +} + +// WaitUntilStackDeleteCompleteWithContext is an extended version of WaitUntilStackDeleteComplete. +// 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 *CloudFormation) WaitUntilStackDeleteCompleteWithContext(ctx aws.Context, input *DescribeStacksInput, opts ...request.WaiterOption) error { + w := request.Waiter{ + Name: "WaitUntilStackDeleteComplete", MaxAttempts: 120, - Acceptors: []waiter.WaitAcceptor{ + Delay: request.ConstantWaiterDelay(30 * time.Second), + Acceptors: []request.WaiterAcceptor{ { - State: "success", - Matcher: "pathAll", - Argument: "Stacks[].StackStatus", + State: request.SuccessWaiterState, + Matcher: request.PathAllWaiterMatch, Argument: "Stacks[].StackStatus", Expected: "DELETE_COMPLETE", }, { - State: "success", - Matcher: "error", - Argument: "", + State: request.SuccessWaiterState, + Matcher: request.ErrorWaiterMatch, Expected: "ValidationError", }, { - State: "failure", - Matcher: "pathAny", - Argument: "Stacks[].StackStatus", + State: request.FailureWaiterState, + Matcher: request.PathAnyWaiterMatch, Argument: "Stacks[].StackStatus", Expected: "DELETE_FAILED", }, { - State: "failure", - Matcher: "pathAny", - Argument: "Stacks[].StackStatus", + State: request.FailureWaiterState, + Matcher: request.PathAnyWaiterMatch, Argument: "Stacks[].StackStatus", Expected: "CREATE_FAILED", }, { - State: "failure", - Matcher: "pathAny", - Argument: "Stacks[].StackStatus", + State: request.FailureWaiterState, + Matcher: request.PathAnyWaiterMatch, Argument: "Stacks[].StackStatus", Expected: "ROLLBACK_FAILED", }, { - State: "failure", - Matcher: "pathAny", - Argument: "Stacks[].StackStatus", + State: request.FailureWaiterState, + Matcher: request.PathAnyWaiterMatch, Argument: "Stacks[].StackStatus", Expected: "UPDATE_ROLLBACK_FAILED", }, { - State: "failure", - Matcher: "pathAny", - Argument: "Stacks[].StackStatus", + State: request.FailureWaiterState, + Matcher: request.PathAnyWaiterMatch, Argument: "Stacks[].StackStatus", Expected: "UPDATE_ROLLBACK_IN_PROGRESS", }, }, + Logger: c.Config.Logger, + NewRequest: func(opts []request.Option) (*request.Request, error) { + var inCpy *DescribeStacksInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeStacksRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, } + w.ApplyOptions(opts...) - w := waiter.Waiter{ - Client: c, - Input: input, - Config: waiterCfg, - } - return w.Wait() + return w.WaitWithContext(ctx) } // WaitUntilStackExists uses the AWS CloudFormation API operation @@ -137,32 +222,50 @@ func (c *CloudFormation) WaitUntilStackDeleteComplete(input *DescribeStacksInput // If the condition is not meet within the max attempt window an error will // be returned. func (c *CloudFormation) WaitUntilStackExists(input *DescribeStacksInput) error { - waiterCfg := waiter.Config{ - Operation: "DescribeStacks", - Delay: 5, + return c.WaitUntilStackExistsWithContext(aws.BackgroundContext(), input) +} + +// WaitUntilStackExistsWithContext is an extended version of WaitUntilStackExists. +// 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 *CloudFormation) WaitUntilStackExistsWithContext(ctx aws.Context, input *DescribeStacksInput, opts ...request.WaiterOption) error { + w := request.Waiter{ + Name: "WaitUntilStackExists", MaxAttempts: 20, - Acceptors: []waiter.WaitAcceptor{ + Delay: request.ConstantWaiterDelay(5 * time.Second), + Acceptors: []request.WaiterAcceptor{ { - State: "success", - Matcher: "status", - Argument: "", + State: request.SuccessWaiterState, + Matcher: request.StatusWaiterMatch, Expected: 200, }, { - State: "retry", - Matcher: "error", - Argument: "", + State: request.RetryWaiterState, + Matcher: request.ErrorWaiterMatch, Expected: "ValidationError", }, }, + Logger: c.Config.Logger, + NewRequest: func(opts []request.Option) (*request.Request, error) { + var inCpy *DescribeStacksInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeStacksRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, } + w.ApplyOptions(opts...) - w := waiter.Waiter{ - Client: c, - Input: input, - Config: waiterCfg, - } - return w.Wait() + return w.WaitWithContext(ctx) } // WaitUntilStackUpdateComplete uses the AWS CloudFormation API operation @@ -170,48 +273,63 @@ func (c *CloudFormation) WaitUntilStackExists(input *DescribeStacksInput) error // If the condition is not meet within the max attempt window an error will // be returned. func (c *CloudFormation) WaitUntilStackUpdateComplete(input *DescribeStacksInput) error { - waiterCfg := waiter.Config{ - Operation: "DescribeStacks", - Delay: 30, + return c.WaitUntilStackUpdateCompleteWithContext(aws.BackgroundContext(), input) +} + +// WaitUntilStackUpdateCompleteWithContext is an extended version of WaitUntilStackUpdateComplete. +// 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 *CloudFormation) WaitUntilStackUpdateCompleteWithContext(ctx aws.Context, input *DescribeStacksInput, opts ...request.WaiterOption) error { + w := request.Waiter{ + Name: "WaitUntilStackUpdateComplete", MaxAttempts: 120, - Acceptors: []waiter.WaitAcceptor{ + Delay: request.ConstantWaiterDelay(30 * time.Second), + Acceptors: []request.WaiterAcceptor{ { - State: "success", - Matcher: "pathAll", - Argument: "Stacks[].StackStatus", + State: request.SuccessWaiterState, + Matcher: request.PathAllWaiterMatch, Argument: "Stacks[].StackStatus", Expected: "UPDATE_COMPLETE", }, { - State: "failure", - Matcher: "pathAny", - Argument: "Stacks[].StackStatus", + State: request.FailureWaiterState, + Matcher: request.PathAnyWaiterMatch, Argument: "Stacks[].StackStatus", Expected: "UPDATE_FAILED", }, { - State: "failure", - Matcher: "pathAny", - Argument: "Stacks[].StackStatus", + State: request.FailureWaiterState, + Matcher: request.PathAnyWaiterMatch, Argument: "Stacks[].StackStatus", Expected: "UPDATE_ROLLBACK_FAILED", }, { - State: "failure", - Matcher: "pathAny", - Argument: "Stacks[].StackStatus", + State: request.FailureWaiterState, + Matcher: request.PathAnyWaiterMatch, Argument: "Stacks[].StackStatus", Expected: "UPDATE_ROLLBACK_COMPLETE", }, { - State: "failure", - Matcher: "error", - Argument: "", + State: request.FailureWaiterState, + Matcher: request.ErrorWaiterMatch, Expected: "ValidationError", }, }, + Logger: c.Config.Logger, + NewRequest: func(opts []request.Option) (*request.Request, error) { + var inCpy *DescribeStacksInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeStacksRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, } + w.ApplyOptions(opts...) - w := waiter.Waiter{ - Client: c, - Input: input, - Config: waiterCfg, - } - return w.Wait() + return w.WaitWithContext(ctx) } diff --git a/vendor/github.com/aws/aws-sdk-go/service/cloudfront/api.go b/vendor/github.com/aws/aws-sdk-go/service/cloudfront/api.go index 17a7eb51a..465240b06 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/cloudfront/api.go +++ b/vendor/github.com/aws/aws-sdk-go/service/cloudfront/api.go @@ -1,19 +1,19 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. -// Package cloudfront provides a client for Amazon CloudFront. package cloudfront import ( "fmt" "time" + "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awsutil" "github.com/aws/aws-sdk-go/aws/request" "github.com/aws/aws-sdk-go/private/protocol" "github.com/aws/aws-sdk-go/private/protocol/restxml" ) -const opCreateCloudFrontOriginAccessIdentity = "CreateCloudFrontOriginAccessIdentity2016_11_25" +const opCreateCloudFrontOriginAccessIdentity = "CreateCloudFrontOriginAccessIdentity2017_03_25" // CreateCloudFrontOriginAccessIdentityRequest generates a "aws/request.Request" representing the // client's request for the CreateCloudFrontOriginAccessIdentity operation. The "output" return @@ -39,12 +39,12 @@ const opCreateCloudFrontOriginAccessIdentity = "CreateCloudFrontOriginAccessIden // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2016-11-25/CreateCloudFrontOriginAccessIdentity +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2017-03-25/CreateCloudFrontOriginAccessIdentity func (c *CloudFront) CreateCloudFrontOriginAccessIdentityRequest(input *CreateCloudFrontOriginAccessIdentityInput) (req *request.Request, output *CreateCloudFrontOriginAccessIdentityOutput) { op := &request.Operation{ Name: opCreateCloudFrontOriginAccessIdentity, HTTPMethod: "POST", - HTTPPath: "/2016-11-25/origin-access-identity/cloudfront", + HTTPPath: "/2017-03-25/origin-access-identity/cloudfront", } if input == nil { @@ -93,14 +93,29 @@ func (c *CloudFront) CreateCloudFrontOriginAccessIdentityRequest(input *CreateCl // * ErrCodeInconsistentQuantities "InconsistentQuantities" // The value of Quantity and the size of Items do not match. // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2016-11-25/CreateCloudFrontOriginAccessIdentity +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2017-03-25/CreateCloudFrontOriginAccessIdentity func (c *CloudFront) CreateCloudFrontOriginAccessIdentity(input *CreateCloudFrontOriginAccessIdentityInput) (*CreateCloudFrontOriginAccessIdentityOutput, error) { req, out := c.CreateCloudFrontOriginAccessIdentityRequest(input) - err := req.Send() - return out, err + return out, req.Send() } -const opCreateDistribution = "CreateDistribution2016_11_25" +// CreateCloudFrontOriginAccessIdentityWithContext is the same as CreateCloudFrontOriginAccessIdentity with the addition of +// the ability to pass a context and additional request options. +// +// See CreateCloudFrontOriginAccessIdentity 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 *CloudFront) CreateCloudFrontOriginAccessIdentityWithContext(ctx aws.Context, input *CreateCloudFrontOriginAccessIdentityInput, opts ...request.Option) (*CreateCloudFrontOriginAccessIdentityOutput, error) { + req, out := c.CreateCloudFrontOriginAccessIdentityRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opCreateDistribution = "CreateDistribution2017_03_25" // CreateDistributionRequest generates a "aws/request.Request" representing the // client's request for the CreateDistribution operation. The "output" return @@ -126,12 +141,12 @@ const opCreateDistribution = "CreateDistribution2016_11_25" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2016-11-25/CreateDistribution +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2017-03-25/CreateDistribution func (c *CloudFront) CreateDistributionRequest(input *CreateDistributionInput) (req *request.Request, output *CreateDistributionOutput) { op := &request.Operation{ Name: opCreateDistribution, HTTPMethod: "POST", - HTTPPath: "/2016-11-25/distribution", + HTTPPath: "/2017-03-25/distribution", } if input == nil { @@ -145,7 +160,7 @@ func (c *CloudFront) CreateDistributionRequest(input *CreateDistributionInput) ( // CreateDistribution API operation for Amazon CloudFront. // -// Creates a new web distribution. Send a GET request to the /CloudFront API +// Creates a new web distribution. Send a POST request to the /CloudFront API // version/distribution/distribution ID resource. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions @@ -270,14 +285,33 @@ func (c *CloudFront) CreateDistributionRequest(input *CreateDistributionInput) ( // * ErrCodeInvalidLambdaFunctionAssociation "InvalidLambdaFunctionAssociation" // The specified Lambda function association is invalid. // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2016-11-25/CreateDistribution +// * ErrCodeInvalidOriginReadTimeout "InvalidOriginReadTimeout" +// +// * ErrCodeInvalidOriginKeepaliveTimeout "InvalidOriginKeepaliveTimeout" +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2017-03-25/CreateDistribution func (c *CloudFront) CreateDistribution(input *CreateDistributionInput) (*CreateDistributionOutput, error) { req, out := c.CreateDistributionRequest(input) - err := req.Send() - return out, err + return out, req.Send() } -const opCreateDistributionWithTags = "CreateDistributionWithTags2016_11_25" +// CreateDistributionWithContext is the same as CreateDistribution with the addition of +// the ability to pass a context and additional request options. +// +// See CreateDistribution 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 *CloudFront) CreateDistributionWithContext(ctx aws.Context, input *CreateDistributionInput, opts ...request.Option) (*CreateDistributionOutput, error) { + req, out := c.CreateDistributionRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opCreateDistributionWithTags = "CreateDistributionWithTags2017_03_25" // CreateDistributionWithTagsRequest generates a "aws/request.Request" representing the // client's request for the CreateDistributionWithTags operation. The "output" return @@ -303,12 +337,12 @@ const opCreateDistributionWithTags = "CreateDistributionWithTags2016_11_25" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2016-11-25/CreateDistributionWithTags +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2017-03-25/CreateDistributionWithTags func (c *CloudFront) CreateDistributionWithTagsRequest(input *CreateDistributionWithTagsInput) (req *request.Request, output *CreateDistributionWithTagsOutput) { op := &request.Operation{ Name: opCreateDistributionWithTags, HTTPMethod: "POST", - HTTPPath: "/2016-11-25/distribution?WithTags", + HTTPPath: "/2017-03-25/distribution?WithTags", } if input == nil { @@ -448,14 +482,33 @@ func (c *CloudFront) CreateDistributionWithTagsRequest(input *CreateDistribution // * ErrCodeInvalidLambdaFunctionAssociation "InvalidLambdaFunctionAssociation" // The specified Lambda function association is invalid. // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2016-11-25/CreateDistributionWithTags +// * ErrCodeInvalidOriginReadTimeout "InvalidOriginReadTimeout" +// +// * ErrCodeInvalidOriginKeepaliveTimeout "InvalidOriginKeepaliveTimeout" +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2017-03-25/CreateDistributionWithTags func (c *CloudFront) CreateDistributionWithTags(input *CreateDistributionWithTagsInput) (*CreateDistributionWithTagsOutput, error) { req, out := c.CreateDistributionWithTagsRequest(input) - err := req.Send() - return out, err + return out, req.Send() } -const opCreateInvalidation = "CreateInvalidation2016_11_25" +// CreateDistributionWithTagsWithContext is the same as CreateDistributionWithTags with the addition of +// the ability to pass a context and additional request options. +// +// See CreateDistributionWithTags 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 *CloudFront) CreateDistributionWithTagsWithContext(ctx aws.Context, input *CreateDistributionWithTagsInput, opts ...request.Option) (*CreateDistributionWithTagsOutput, error) { + req, out := c.CreateDistributionWithTagsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opCreateInvalidation = "CreateInvalidation2017_03_25" // CreateInvalidationRequest generates a "aws/request.Request" representing the // client's request for the CreateInvalidation operation. The "output" return @@ -481,12 +534,12 @@ const opCreateInvalidation = "CreateInvalidation2016_11_25" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2016-11-25/CreateInvalidation +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2017-03-25/CreateInvalidation func (c *CloudFront) CreateInvalidationRequest(input *CreateInvalidationInput) (req *request.Request, output *CreateInvalidationOutput) { op := &request.Operation{ Name: opCreateInvalidation, HTTPMethod: "POST", - HTTPPath: "/2016-11-25/distribution/{DistributionId}/invalidation", + HTTPPath: "/2017-03-25/distribution/{DistributionId}/invalidation", } if input == nil { @@ -532,14 +585,29 @@ func (c *CloudFront) CreateInvalidationRequest(input *CreateInvalidationInput) ( // * ErrCodeInconsistentQuantities "InconsistentQuantities" // The value of Quantity and the size of Items do not match. // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2016-11-25/CreateInvalidation +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2017-03-25/CreateInvalidation func (c *CloudFront) CreateInvalidation(input *CreateInvalidationInput) (*CreateInvalidationOutput, error) { req, out := c.CreateInvalidationRequest(input) - err := req.Send() - return out, err + return out, req.Send() } -const opCreateStreamingDistribution = "CreateStreamingDistribution2016_11_25" +// CreateInvalidationWithContext is the same as CreateInvalidation with the addition of +// the ability to pass a context and additional request options. +// +// See CreateInvalidation 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 *CloudFront) CreateInvalidationWithContext(ctx aws.Context, input *CreateInvalidationInput, opts ...request.Option) (*CreateInvalidationOutput, error) { + req, out := c.CreateInvalidationRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opCreateStreamingDistribution = "CreateStreamingDistribution2017_03_25" // CreateStreamingDistributionRequest generates a "aws/request.Request" representing the // client's request for the CreateStreamingDistribution operation. The "output" return @@ -565,12 +633,12 @@ const opCreateStreamingDistribution = "CreateStreamingDistribution2016_11_25" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2016-11-25/CreateStreamingDistribution +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2017-03-25/CreateStreamingDistribution func (c *CloudFront) CreateStreamingDistributionRequest(input *CreateStreamingDistributionInput) (req *request.Request, output *CreateStreamingDistributionOutput) { op := &request.Operation{ Name: opCreateStreamingDistribution, HTTPMethod: "POST", - HTTPPath: "/2016-11-25/streaming-distribution", + HTTPPath: "/2017-03-25/streaming-distribution", } if input == nil { @@ -657,14 +725,29 @@ func (c *CloudFront) CreateStreamingDistributionRequest(input *CreateStreamingDi // * ErrCodeInconsistentQuantities "InconsistentQuantities" // The value of Quantity and the size of Items do not match. // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2016-11-25/CreateStreamingDistribution +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2017-03-25/CreateStreamingDistribution func (c *CloudFront) CreateStreamingDistribution(input *CreateStreamingDistributionInput) (*CreateStreamingDistributionOutput, error) { req, out := c.CreateStreamingDistributionRequest(input) - err := req.Send() - return out, err + return out, req.Send() } -const opCreateStreamingDistributionWithTags = "CreateStreamingDistributionWithTags2016_11_25" +// CreateStreamingDistributionWithContext is the same as CreateStreamingDistribution with the addition of +// the ability to pass a context and additional request options. +// +// See CreateStreamingDistribution 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 *CloudFront) CreateStreamingDistributionWithContext(ctx aws.Context, input *CreateStreamingDistributionInput, opts ...request.Option) (*CreateStreamingDistributionOutput, error) { + req, out := c.CreateStreamingDistributionRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opCreateStreamingDistributionWithTags = "CreateStreamingDistributionWithTags2017_03_25" // CreateStreamingDistributionWithTagsRequest generates a "aws/request.Request" representing the // client's request for the CreateStreamingDistributionWithTags operation. The "output" return @@ -690,12 +773,12 @@ const opCreateStreamingDistributionWithTags = "CreateStreamingDistributionWithTa // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2016-11-25/CreateStreamingDistributionWithTags +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2017-03-25/CreateStreamingDistributionWithTags func (c *CloudFront) CreateStreamingDistributionWithTagsRequest(input *CreateStreamingDistributionWithTagsInput) (req *request.Request, output *CreateStreamingDistributionWithTagsOutput) { op := &request.Operation{ Name: opCreateStreamingDistributionWithTags, HTTPMethod: "POST", - HTTPPath: "/2016-11-25/streaming-distribution?WithTags", + HTTPPath: "/2017-03-25/streaming-distribution?WithTags", } if input == nil { @@ -757,14 +840,29 @@ func (c *CloudFront) CreateStreamingDistributionWithTagsRequest(input *CreateStr // // * ErrCodeInvalidTagging "InvalidTagging" // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2016-11-25/CreateStreamingDistributionWithTags +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2017-03-25/CreateStreamingDistributionWithTags func (c *CloudFront) CreateStreamingDistributionWithTags(input *CreateStreamingDistributionWithTagsInput) (*CreateStreamingDistributionWithTagsOutput, error) { req, out := c.CreateStreamingDistributionWithTagsRequest(input) - err := req.Send() - return out, err + return out, req.Send() } -const opDeleteCloudFrontOriginAccessIdentity = "DeleteCloudFrontOriginAccessIdentity2016_11_25" +// CreateStreamingDistributionWithTagsWithContext is the same as CreateStreamingDistributionWithTags with the addition of +// the ability to pass a context and additional request options. +// +// See CreateStreamingDistributionWithTags 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 *CloudFront) CreateStreamingDistributionWithTagsWithContext(ctx aws.Context, input *CreateStreamingDistributionWithTagsInput, opts ...request.Option) (*CreateStreamingDistributionWithTagsOutput, error) { + req, out := c.CreateStreamingDistributionWithTagsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opDeleteCloudFrontOriginAccessIdentity = "DeleteCloudFrontOriginAccessIdentity2017_03_25" // DeleteCloudFrontOriginAccessIdentityRequest generates a "aws/request.Request" representing the // client's request for the DeleteCloudFrontOriginAccessIdentity operation. The "output" return @@ -790,12 +888,12 @@ const opDeleteCloudFrontOriginAccessIdentity = "DeleteCloudFrontOriginAccessIden // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2016-11-25/DeleteCloudFrontOriginAccessIdentity +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2017-03-25/DeleteCloudFrontOriginAccessIdentity func (c *CloudFront) DeleteCloudFrontOriginAccessIdentityRequest(input *DeleteCloudFrontOriginAccessIdentityInput) (req *request.Request, output *DeleteCloudFrontOriginAccessIdentityOutput) { op := &request.Operation{ Name: opDeleteCloudFrontOriginAccessIdentity, HTTPMethod: "DELETE", - HTTPPath: "/2016-11-25/origin-access-identity/cloudfront/{Id}", + HTTPPath: "/2017-03-25/origin-access-identity/cloudfront/{Id}", } if input == nil { @@ -836,14 +934,29 @@ func (c *CloudFront) DeleteCloudFrontOriginAccessIdentityRequest(input *DeleteCl // // * ErrCodeOriginAccessIdentityInUse "OriginAccessIdentityInUse" // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2016-11-25/DeleteCloudFrontOriginAccessIdentity +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2017-03-25/DeleteCloudFrontOriginAccessIdentity func (c *CloudFront) DeleteCloudFrontOriginAccessIdentity(input *DeleteCloudFrontOriginAccessIdentityInput) (*DeleteCloudFrontOriginAccessIdentityOutput, error) { req, out := c.DeleteCloudFrontOriginAccessIdentityRequest(input) - err := req.Send() - return out, err + return out, req.Send() } -const opDeleteDistribution = "DeleteDistribution2016_11_25" +// DeleteCloudFrontOriginAccessIdentityWithContext is the same as DeleteCloudFrontOriginAccessIdentity with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteCloudFrontOriginAccessIdentity 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 *CloudFront) DeleteCloudFrontOriginAccessIdentityWithContext(ctx aws.Context, input *DeleteCloudFrontOriginAccessIdentityInput, opts ...request.Option) (*DeleteCloudFrontOriginAccessIdentityOutput, error) { + req, out := c.DeleteCloudFrontOriginAccessIdentityRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opDeleteDistribution = "DeleteDistribution2017_03_25" // DeleteDistributionRequest generates a "aws/request.Request" representing the // client's request for the DeleteDistribution operation. The "output" return @@ -869,12 +982,12 @@ const opDeleteDistribution = "DeleteDistribution2016_11_25" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2016-11-25/DeleteDistribution +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2017-03-25/DeleteDistribution func (c *CloudFront) DeleteDistributionRequest(input *DeleteDistributionInput) (req *request.Request, output *DeleteDistributionOutput) { op := &request.Operation{ Name: opDeleteDistribution, HTTPMethod: "DELETE", - HTTPPath: "/2016-11-25/distribution/{Id}", + HTTPPath: "/2017-03-25/distribution/{Id}", } if input == nil { @@ -915,14 +1028,29 @@ func (c *CloudFront) DeleteDistributionRequest(input *DeleteDistributionInput) ( // The precondition given in one or more of the request-header fields evaluated // to false. // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2016-11-25/DeleteDistribution +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2017-03-25/DeleteDistribution func (c *CloudFront) DeleteDistribution(input *DeleteDistributionInput) (*DeleteDistributionOutput, error) { req, out := c.DeleteDistributionRequest(input) - err := req.Send() - return out, err + return out, req.Send() } -const opDeleteStreamingDistribution = "DeleteStreamingDistribution2016_11_25" +// DeleteDistributionWithContext is the same as DeleteDistribution with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteDistribution 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 *CloudFront) DeleteDistributionWithContext(ctx aws.Context, input *DeleteDistributionInput, opts ...request.Option) (*DeleteDistributionOutput, error) { + req, out := c.DeleteDistributionRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opDeleteStreamingDistribution = "DeleteStreamingDistribution2017_03_25" // DeleteStreamingDistributionRequest generates a "aws/request.Request" representing the // client's request for the DeleteStreamingDistribution operation. The "output" return @@ -948,12 +1076,12 @@ const opDeleteStreamingDistribution = "DeleteStreamingDistribution2016_11_25" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2016-11-25/DeleteStreamingDistribution +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2017-03-25/DeleteStreamingDistribution func (c *CloudFront) DeleteStreamingDistributionRequest(input *DeleteStreamingDistributionInput) (req *request.Request, output *DeleteStreamingDistributionOutput) { op := &request.Operation{ Name: opDeleteStreamingDistribution, HTTPMethod: "DELETE", - HTTPPath: "/2016-11-25/streaming-distribution/{Id}", + HTTPPath: "/2017-03-25/streaming-distribution/{Id}", } if input == nil { @@ -1029,14 +1157,29 @@ func (c *CloudFront) DeleteStreamingDistributionRequest(input *DeleteStreamingDi // The precondition given in one or more of the request-header fields evaluated // to false. // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2016-11-25/DeleteStreamingDistribution +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2017-03-25/DeleteStreamingDistribution func (c *CloudFront) DeleteStreamingDistribution(input *DeleteStreamingDistributionInput) (*DeleteStreamingDistributionOutput, error) { req, out := c.DeleteStreamingDistributionRequest(input) - err := req.Send() - return out, err + return out, req.Send() } -const opGetCloudFrontOriginAccessIdentity = "GetCloudFrontOriginAccessIdentity2016_11_25" +// DeleteStreamingDistributionWithContext is the same as DeleteStreamingDistribution with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteStreamingDistribution 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 *CloudFront) DeleteStreamingDistributionWithContext(ctx aws.Context, input *DeleteStreamingDistributionInput, opts ...request.Option) (*DeleteStreamingDistributionOutput, error) { + req, out := c.DeleteStreamingDistributionRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opGetCloudFrontOriginAccessIdentity = "GetCloudFrontOriginAccessIdentity2017_03_25" // GetCloudFrontOriginAccessIdentityRequest generates a "aws/request.Request" representing the // client's request for the GetCloudFrontOriginAccessIdentity operation. The "output" return @@ -1062,12 +1205,12 @@ const opGetCloudFrontOriginAccessIdentity = "GetCloudFrontOriginAccessIdentity20 // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2016-11-25/GetCloudFrontOriginAccessIdentity +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2017-03-25/GetCloudFrontOriginAccessIdentity func (c *CloudFront) GetCloudFrontOriginAccessIdentityRequest(input *GetCloudFrontOriginAccessIdentityInput) (req *request.Request, output *GetCloudFrontOriginAccessIdentityOutput) { op := &request.Operation{ Name: opGetCloudFrontOriginAccessIdentity, HTTPMethod: "GET", - HTTPPath: "/2016-11-25/origin-access-identity/cloudfront/{Id}", + HTTPPath: "/2017-03-25/origin-access-identity/cloudfront/{Id}", } if input == nil { @@ -1097,14 +1240,29 @@ func (c *CloudFront) GetCloudFrontOriginAccessIdentityRequest(input *GetCloudFro // * ErrCodeAccessDenied "AccessDenied" // Access denied. // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2016-11-25/GetCloudFrontOriginAccessIdentity +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2017-03-25/GetCloudFrontOriginAccessIdentity func (c *CloudFront) GetCloudFrontOriginAccessIdentity(input *GetCloudFrontOriginAccessIdentityInput) (*GetCloudFrontOriginAccessIdentityOutput, error) { req, out := c.GetCloudFrontOriginAccessIdentityRequest(input) - err := req.Send() - return out, err + return out, req.Send() } -const opGetCloudFrontOriginAccessIdentityConfig = "GetCloudFrontOriginAccessIdentityConfig2016_11_25" +// GetCloudFrontOriginAccessIdentityWithContext is the same as GetCloudFrontOriginAccessIdentity with the addition of +// the ability to pass a context and additional request options. +// +// See GetCloudFrontOriginAccessIdentity 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 *CloudFront) GetCloudFrontOriginAccessIdentityWithContext(ctx aws.Context, input *GetCloudFrontOriginAccessIdentityInput, opts ...request.Option) (*GetCloudFrontOriginAccessIdentityOutput, error) { + req, out := c.GetCloudFrontOriginAccessIdentityRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opGetCloudFrontOriginAccessIdentityConfig = "GetCloudFrontOriginAccessIdentityConfig2017_03_25" // GetCloudFrontOriginAccessIdentityConfigRequest generates a "aws/request.Request" representing the // client's request for the GetCloudFrontOriginAccessIdentityConfig operation. The "output" return @@ -1130,12 +1288,12 @@ const opGetCloudFrontOriginAccessIdentityConfig = "GetCloudFrontOriginAccessIden // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2016-11-25/GetCloudFrontOriginAccessIdentityConfig +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2017-03-25/GetCloudFrontOriginAccessIdentityConfig func (c *CloudFront) GetCloudFrontOriginAccessIdentityConfigRequest(input *GetCloudFrontOriginAccessIdentityConfigInput) (req *request.Request, output *GetCloudFrontOriginAccessIdentityConfigOutput) { op := &request.Operation{ Name: opGetCloudFrontOriginAccessIdentityConfig, HTTPMethod: "GET", - HTTPPath: "/2016-11-25/origin-access-identity/cloudfront/{Id}/config", + HTTPPath: "/2017-03-25/origin-access-identity/cloudfront/{Id}/config", } if input == nil { @@ -1165,14 +1323,29 @@ func (c *CloudFront) GetCloudFrontOriginAccessIdentityConfigRequest(input *GetCl // * ErrCodeAccessDenied "AccessDenied" // Access denied. // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2016-11-25/GetCloudFrontOriginAccessIdentityConfig +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2017-03-25/GetCloudFrontOriginAccessIdentityConfig func (c *CloudFront) GetCloudFrontOriginAccessIdentityConfig(input *GetCloudFrontOriginAccessIdentityConfigInput) (*GetCloudFrontOriginAccessIdentityConfigOutput, error) { req, out := c.GetCloudFrontOriginAccessIdentityConfigRequest(input) - err := req.Send() - return out, err + return out, req.Send() } -const opGetDistribution = "GetDistribution2016_11_25" +// GetCloudFrontOriginAccessIdentityConfigWithContext is the same as GetCloudFrontOriginAccessIdentityConfig with the addition of +// the ability to pass a context and additional request options. +// +// See GetCloudFrontOriginAccessIdentityConfig 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 *CloudFront) GetCloudFrontOriginAccessIdentityConfigWithContext(ctx aws.Context, input *GetCloudFrontOriginAccessIdentityConfigInput, opts ...request.Option) (*GetCloudFrontOriginAccessIdentityConfigOutput, error) { + req, out := c.GetCloudFrontOriginAccessIdentityConfigRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opGetDistribution = "GetDistribution2017_03_25" // GetDistributionRequest generates a "aws/request.Request" representing the // client's request for the GetDistribution operation. The "output" return @@ -1198,12 +1371,12 @@ const opGetDistribution = "GetDistribution2016_11_25" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2016-11-25/GetDistribution +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2017-03-25/GetDistribution func (c *CloudFront) GetDistributionRequest(input *GetDistributionInput) (req *request.Request, output *GetDistributionOutput) { op := &request.Operation{ Name: opGetDistribution, HTTPMethod: "GET", - HTTPPath: "/2016-11-25/distribution/{Id}", + HTTPPath: "/2017-03-25/distribution/{Id}", } if input == nil { @@ -1233,14 +1406,29 @@ func (c *CloudFront) GetDistributionRequest(input *GetDistributionInput) (req *r // * ErrCodeAccessDenied "AccessDenied" // Access denied. // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2016-11-25/GetDistribution +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2017-03-25/GetDistribution func (c *CloudFront) GetDistribution(input *GetDistributionInput) (*GetDistributionOutput, error) { req, out := c.GetDistributionRequest(input) - err := req.Send() - return out, err + return out, req.Send() } -const opGetDistributionConfig = "GetDistributionConfig2016_11_25" +// GetDistributionWithContext is the same as GetDistribution with the addition of +// the ability to pass a context and additional request options. +// +// See GetDistribution 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 *CloudFront) GetDistributionWithContext(ctx aws.Context, input *GetDistributionInput, opts ...request.Option) (*GetDistributionOutput, error) { + req, out := c.GetDistributionRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opGetDistributionConfig = "GetDistributionConfig2017_03_25" // GetDistributionConfigRequest generates a "aws/request.Request" representing the // client's request for the GetDistributionConfig operation. The "output" return @@ -1266,12 +1454,12 @@ const opGetDistributionConfig = "GetDistributionConfig2016_11_25" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2016-11-25/GetDistributionConfig +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2017-03-25/GetDistributionConfig func (c *CloudFront) GetDistributionConfigRequest(input *GetDistributionConfigInput) (req *request.Request, output *GetDistributionConfigOutput) { op := &request.Operation{ Name: opGetDistributionConfig, HTTPMethod: "GET", - HTTPPath: "/2016-11-25/distribution/{Id}/config", + HTTPPath: "/2017-03-25/distribution/{Id}/config", } if input == nil { @@ -1301,14 +1489,29 @@ func (c *CloudFront) GetDistributionConfigRequest(input *GetDistributionConfigIn // * ErrCodeAccessDenied "AccessDenied" // Access denied. // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2016-11-25/GetDistributionConfig +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2017-03-25/GetDistributionConfig func (c *CloudFront) GetDistributionConfig(input *GetDistributionConfigInput) (*GetDistributionConfigOutput, error) { req, out := c.GetDistributionConfigRequest(input) - err := req.Send() - return out, err + return out, req.Send() } -const opGetInvalidation = "GetInvalidation2016_11_25" +// GetDistributionConfigWithContext is the same as GetDistributionConfig with the addition of +// the ability to pass a context and additional request options. +// +// See GetDistributionConfig 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 *CloudFront) GetDistributionConfigWithContext(ctx aws.Context, input *GetDistributionConfigInput, opts ...request.Option) (*GetDistributionConfigOutput, error) { + req, out := c.GetDistributionConfigRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opGetInvalidation = "GetInvalidation2017_03_25" // GetInvalidationRequest generates a "aws/request.Request" representing the // client's request for the GetInvalidation operation. The "output" return @@ -1334,12 +1537,12 @@ const opGetInvalidation = "GetInvalidation2016_11_25" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2016-11-25/GetInvalidation +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2017-03-25/GetInvalidation func (c *CloudFront) GetInvalidationRequest(input *GetInvalidationInput) (req *request.Request, output *GetInvalidationOutput) { op := &request.Operation{ Name: opGetInvalidation, HTTPMethod: "GET", - HTTPPath: "/2016-11-25/distribution/{DistributionId}/invalidation/{Id}", + HTTPPath: "/2017-03-25/distribution/{DistributionId}/invalidation/{Id}", } if input == nil { @@ -1372,14 +1575,29 @@ func (c *CloudFront) GetInvalidationRequest(input *GetInvalidationInput) (req *r // * ErrCodeAccessDenied "AccessDenied" // Access denied. // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2016-11-25/GetInvalidation +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2017-03-25/GetInvalidation func (c *CloudFront) GetInvalidation(input *GetInvalidationInput) (*GetInvalidationOutput, error) { req, out := c.GetInvalidationRequest(input) - err := req.Send() - return out, err + return out, req.Send() } -const opGetStreamingDistribution = "GetStreamingDistribution2016_11_25" +// GetInvalidationWithContext is the same as GetInvalidation with the addition of +// the ability to pass a context and additional request options. +// +// See GetInvalidation 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 *CloudFront) GetInvalidationWithContext(ctx aws.Context, input *GetInvalidationInput, opts ...request.Option) (*GetInvalidationOutput, error) { + req, out := c.GetInvalidationRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opGetStreamingDistribution = "GetStreamingDistribution2017_03_25" // GetStreamingDistributionRequest generates a "aws/request.Request" representing the // client's request for the GetStreamingDistribution operation. The "output" return @@ -1405,12 +1623,12 @@ const opGetStreamingDistribution = "GetStreamingDistribution2016_11_25" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2016-11-25/GetStreamingDistribution +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2017-03-25/GetStreamingDistribution func (c *CloudFront) GetStreamingDistributionRequest(input *GetStreamingDistributionInput) (req *request.Request, output *GetStreamingDistributionOutput) { op := &request.Operation{ Name: opGetStreamingDistribution, HTTPMethod: "GET", - HTTPPath: "/2016-11-25/streaming-distribution/{Id}", + HTTPPath: "/2017-03-25/streaming-distribution/{Id}", } if input == nil { @@ -1441,14 +1659,29 @@ func (c *CloudFront) GetStreamingDistributionRequest(input *GetStreamingDistribu // * ErrCodeAccessDenied "AccessDenied" // Access denied. // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2016-11-25/GetStreamingDistribution +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2017-03-25/GetStreamingDistribution func (c *CloudFront) GetStreamingDistribution(input *GetStreamingDistributionInput) (*GetStreamingDistributionOutput, error) { req, out := c.GetStreamingDistributionRequest(input) - err := req.Send() - return out, err + return out, req.Send() } -const opGetStreamingDistributionConfig = "GetStreamingDistributionConfig2016_11_25" +// GetStreamingDistributionWithContext is the same as GetStreamingDistribution with the addition of +// the ability to pass a context and additional request options. +// +// See GetStreamingDistribution 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 *CloudFront) GetStreamingDistributionWithContext(ctx aws.Context, input *GetStreamingDistributionInput, opts ...request.Option) (*GetStreamingDistributionOutput, error) { + req, out := c.GetStreamingDistributionRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opGetStreamingDistributionConfig = "GetStreamingDistributionConfig2017_03_25" // GetStreamingDistributionConfigRequest generates a "aws/request.Request" representing the // client's request for the GetStreamingDistributionConfig operation. The "output" return @@ -1474,12 +1707,12 @@ const opGetStreamingDistributionConfig = "GetStreamingDistributionConfig2016_11_ // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2016-11-25/GetStreamingDistributionConfig +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2017-03-25/GetStreamingDistributionConfig func (c *CloudFront) GetStreamingDistributionConfigRequest(input *GetStreamingDistributionConfigInput) (req *request.Request, output *GetStreamingDistributionConfigOutput) { op := &request.Operation{ Name: opGetStreamingDistributionConfig, HTTPMethod: "GET", - HTTPPath: "/2016-11-25/streaming-distribution/{Id}/config", + HTTPPath: "/2017-03-25/streaming-distribution/{Id}/config", } if input == nil { @@ -1509,14 +1742,29 @@ func (c *CloudFront) GetStreamingDistributionConfigRequest(input *GetStreamingDi // * ErrCodeAccessDenied "AccessDenied" // Access denied. // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2016-11-25/GetStreamingDistributionConfig +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2017-03-25/GetStreamingDistributionConfig func (c *CloudFront) GetStreamingDistributionConfig(input *GetStreamingDistributionConfigInput) (*GetStreamingDistributionConfigOutput, error) { req, out := c.GetStreamingDistributionConfigRequest(input) - err := req.Send() - return out, err + return out, req.Send() } -const opListCloudFrontOriginAccessIdentities = "ListCloudFrontOriginAccessIdentities2016_11_25" +// GetStreamingDistributionConfigWithContext is the same as GetStreamingDistributionConfig with the addition of +// the ability to pass a context and additional request options. +// +// See GetStreamingDistributionConfig 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 *CloudFront) GetStreamingDistributionConfigWithContext(ctx aws.Context, input *GetStreamingDistributionConfigInput, opts ...request.Option) (*GetStreamingDistributionConfigOutput, error) { + req, out := c.GetStreamingDistributionConfigRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opListCloudFrontOriginAccessIdentities = "ListCloudFrontOriginAccessIdentities2017_03_25" // ListCloudFrontOriginAccessIdentitiesRequest generates a "aws/request.Request" representing the // client's request for the ListCloudFrontOriginAccessIdentities operation. The "output" return @@ -1542,12 +1790,12 @@ const opListCloudFrontOriginAccessIdentities = "ListCloudFrontOriginAccessIdenti // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2016-11-25/ListCloudFrontOriginAccessIdentities +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2017-03-25/ListCloudFrontOriginAccessIdentities func (c *CloudFront) ListCloudFrontOriginAccessIdentitiesRequest(input *ListCloudFrontOriginAccessIdentitiesInput) (req *request.Request, output *ListCloudFrontOriginAccessIdentitiesOutput) { op := &request.Operation{ Name: opListCloudFrontOriginAccessIdentities, HTTPMethod: "GET", - HTTPPath: "/2016-11-25/origin-access-identity/cloudfront", + HTTPPath: "/2017-03-25/origin-access-identity/cloudfront", Paginator: &request.Paginator{ InputTokens: []string{"Marker"}, OutputTokens: []string{"CloudFrontOriginAccessIdentityList.NextMarker"}, @@ -1580,11 +1828,26 @@ func (c *CloudFront) ListCloudFrontOriginAccessIdentitiesRequest(input *ListClou // * ErrCodeInvalidArgument "InvalidArgument" // The argument is invalid. // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2016-11-25/ListCloudFrontOriginAccessIdentities +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2017-03-25/ListCloudFrontOriginAccessIdentities func (c *CloudFront) ListCloudFrontOriginAccessIdentities(input *ListCloudFrontOriginAccessIdentitiesInput) (*ListCloudFrontOriginAccessIdentitiesOutput, error) { req, out := c.ListCloudFrontOriginAccessIdentitiesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListCloudFrontOriginAccessIdentitiesWithContext is the same as ListCloudFrontOriginAccessIdentities with the addition of +// the ability to pass a context and additional request options. +// +// See ListCloudFrontOriginAccessIdentities 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 *CloudFront) ListCloudFrontOriginAccessIdentitiesWithContext(ctx aws.Context, input *ListCloudFrontOriginAccessIdentitiesInput, opts ...request.Option) (*ListCloudFrontOriginAccessIdentitiesOutput, error) { + req, out := c.ListCloudFrontOriginAccessIdentitiesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // ListCloudFrontOriginAccessIdentitiesPages iterates over the pages of a ListCloudFrontOriginAccessIdentities operation, @@ -1604,15 +1867,40 @@ func (c *CloudFront) ListCloudFrontOriginAccessIdentities(input *ListCloudFrontO // return pageNum <= 3 // }) // -func (c *CloudFront) ListCloudFrontOriginAccessIdentitiesPages(input *ListCloudFrontOriginAccessIdentitiesInput, fn func(p *ListCloudFrontOriginAccessIdentitiesOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.ListCloudFrontOriginAccessIdentitiesRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*ListCloudFrontOriginAccessIdentitiesOutput), lastPage) - }) +func (c *CloudFront) ListCloudFrontOriginAccessIdentitiesPages(input *ListCloudFrontOriginAccessIdentitiesInput, fn func(*ListCloudFrontOriginAccessIdentitiesOutput, bool) bool) error { + return c.ListCloudFrontOriginAccessIdentitiesPagesWithContext(aws.BackgroundContext(), input, fn) } -const opListDistributions = "ListDistributions2016_11_25" +// ListCloudFrontOriginAccessIdentitiesPagesWithContext same as ListCloudFrontOriginAccessIdentitiesPages 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 *CloudFront) ListCloudFrontOriginAccessIdentitiesPagesWithContext(ctx aws.Context, input *ListCloudFrontOriginAccessIdentitiesInput, fn func(*ListCloudFrontOriginAccessIdentitiesOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListCloudFrontOriginAccessIdentitiesInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListCloudFrontOriginAccessIdentitiesRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*ListCloudFrontOriginAccessIdentitiesOutput), !p.HasNextPage()) + } + return p.Err() +} + +const opListDistributions = "ListDistributions2017_03_25" // ListDistributionsRequest generates a "aws/request.Request" representing the // client's request for the ListDistributions operation. The "output" return @@ -1638,12 +1926,12 @@ const opListDistributions = "ListDistributions2016_11_25" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2016-11-25/ListDistributions +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2017-03-25/ListDistributions func (c *CloudFront) ListDistributionsRequest(input *ListDistributionsInput) (req *request.Request, output *ListDistributionsOutput) { op := &request.Operation{ Name: opListDistributions, HTTPMethod: "GET", - HTTPPath: "/2016-11-25/distribution", + HTTPPath: "/2017-03-25/distribution", Paginator: &request.Paginator{ InputTokens: []string{"Marker"}, OutputTokens: []string{"DistributionList.NextMarker"}, @@ -1676,11 +1964,26 @@ func (c *CloudFront) ListDistributionsRequest(input *ListDistributionsInput) (re // * ErrCodeInvalidArgument "InvalidArgument" // The argument is invalid. // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2016-11-25/ListDistributions +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2017-03-25/ListDistributions func (c *CloudFront) ListDistributions(input *ListDistributionsInput) (*ListDistributionsOutput, error) { req, out := c.ListDistributionsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListDistributionsWithContext is the same as ListDistributions with the addition of +// the ability to pass a context and additional request options. +// +// See ListDistributions 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 *CloudFront) ListDistributionsWithContext(ctx aws.Context, input *ListDistributionsInput, opts ...request.Option) (*ListDistributionsOutput, error) { + req, out := c.ListDistributionsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // ListDistributionsPages iterates over the pages of a ListDistributions operation, @@ -1700,15 +2003,40 @@ func (c *CloudFront) ListDistributions(input *ListDistributionsInput) (*ListDist // return pageNum <= 3 // }) // -func (c *CloudFront) ListDistributionsPages(input *ListDistributionsInput, fn func(p *ListDistributionsOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.ListDistributionsRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*ListDistributionsOutput), lastPage) - }) +func (c *CloudFront) ListDistributionsPages(input *ListDistributionsInput, fn func(*ListDistributionsOutput, bool) bool) error { + return c.ListDistributionsPagesWithContext(aws.BackgroundContext(), input, fn) } -const opListDistributionsByWebACLId = "ListDistributionsByWebACLId2016_11_25" +// ListDistributionsPagesWithContext same as ListDistributionsPages 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 *CloudFront) ListDistributionsPagesWithContext(ctx aws.Context, input *ListDistributionsInput, fn func(*ListDistributionsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListDistributionsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListDistributionsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*ListDistributionsOutput), !p.HasNextPage()) + } + return p.Err() +} + +const opListDistributionsByWebACLId = "ListDistributionsByWebACLId2017_03_25" // ListDistributionsByWebACLIdRequest generates a "aws/request.Request" representing the // client's request for the ListDistributionsByWebACLId operation. The "output" return @@ -1734,12 +2062,12 @@ const opListDistributionsByWebACLId = "ListDistributionsByWebACLId2016_11_25" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2016-11-25/ListDistributionsByWebACLId +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2017-03-25/ListDistributionsByWebACLId func (c *CloudFront) ListDistributionsByWebACLIdRequest(input *ListDistributionsByWebACLIdInput) (req *request.Request, output *ListDistributionsByWebACLIdOutput) { op := &request.Operation{ Name: opListDistributionsByWebACLId, HTTPMethod: "GET", - HTTPPath: "/2016-11-25/distributionsByWebACLId/{WebACLId}", + HTTPPath: "/2017-03-25/distributionsByWebACLId/{WebACLId}", } if input == nil { @@ -1768,14 +2096,29 @@ func (c *CloudFront) ListDistributionsByWebACLIdRequest(input *ListDistributions // // * ErrCodeInvalidWebACLId "InvalidWebACLId" // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2016-11-25/ListDistributionsByWebACLId +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2017-03-25/ListDistributionsByWebACLId func (c *CloudFront) ListDistributionsByWebACLId(input *ListDistributionsByWebACLIdInput) (*ListDistributionsByWebACLIdOutput, error) { req, out := c.ListDistributionsByWebACLIdRequest(input) - err := req.Send() - return out, err + return out, req.Send() } -const opListInvalidations = "ListInvalidations2016_11_25" +// ListDistributionsByWebACLIdWithContext is the same as ListDistributionsByWebACLId with the addition of +// the ability to pass a context and additional request options. +// +// See ListDistributionsByWebACLId 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 *CloudFront) ListDistributionsByWebACLIdWithContext(ctx aws.Context, input *ListDistributionsByWebACLIdInput, opts ...request.Option) (*ListDistributionsByWebACLIdOutput, error) { + req, out := c.ListDistributionsByWebACLIdRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opListInvalidations = "ListInvalidations2017_03_25" // ListInvalidationsRequest generates a "aws/request.Request" representing the // client's request for the ListInvalidations operation. The "output" return @@ -1801,12 +2144,12 @@ const opListInvalidations = "ListInvalidations2016_11_25" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2016-11-25/ListInvalidations +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2017-03-25/ListInvalidations func (c *CloudFront) ListInvalidationsRequest(input *ListInvalidationsInput) (req *request.Request, output *ListInvalidationsOutput) { op := &request.Operation{ Name: opListInvalidations, HTTPMethod: "GET", - HTTPPath: "/2016-11-25/distribution/{DistributionId}/invalidation", + HTTPPath: "/2017-03-25/distribution/{DistributionId}/invalidation", Paginator: &request.Paginator{ InputTokens: []string{"Marker"}, OutputTokens: []string{"InvalidationList.NextMarker"}, @@ -1845,11 +2188,26 @@ func (c *CloudFront) ListInvalidationsRequest(input *ListInvalidationsInput) (re // * ErrCodeAccessDenied "AccessDenied" // Access denied. // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2016-11-25/ListInvalidations +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2017-03-25/ListInvalidations func (c *CloudFront) ListInvalidations(input *ListInvalidationsInput) (*ListInvalidationsOutput, error) { req, out := c.ListInvalidationsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListInvalidationsWithContext is the same as ListInvalidations with the addition of +// the ability to pass a context and additional request options. +// +// See ListInvalidations 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 *CloudFront) ListInvalidationsWithContext(ctx aws.Context, input *ListInvalidationsInput, opts ...request.Option) (*ListInvalidationsOutput, error) { + req, out := c.ListInvalidationsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // ListInvalidationsPages iterates over the pages of a ListInvalidations operation, @@ -1869,15 +2227,40 @@ func (c *CloudFront) ListInvalidations(input *ListInvalidationsInput) (*ListInva // return pageNum <= 3 // }) // -func (c *CloudFront) ListInvalidationsPages(input *ListInvalidationsInput, fn func(p *ListInvalidationsOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.ListInvalidationsRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*ListInvalidationsOutput), lastPage) - }) +func (c *CloudFront) ListInvalidationsPages(input *ListInvalidationsInput, fn func(*ListInvalidationsOutput, bool) bool) error { + return c.ListInvalidationsPagesWithContext(aws.BackgroundContext(), input, fn) } -const opListStreamingDistributions = "ListStreamingDistributions2016_11_25" +// ListInvalidationsPagesWithContext same as ListInvalidationsPages 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 *CloudFront) ListInvalidationsPagesWithContext(ctx aws.Context, input *ListInvalidationsInput, fn func(*ListInvalidationsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListInvalidationsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListInvalidationsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*ListInvalidationsOutput), !p.HasNextPage()) + } + return p.Err() +} + +const opListStreamingDistributions = "ListStreamingDistributions2017_03_25" // ListStreamingDistributionsRequest generates a "aws/request.Request" representing the // client's request for the ListStreamingDistributions operation. The "output" return @@ -1903,12 +2286,12 @@ const opListStreamingDistributions = "ListStreamingDistributions2016_11_25" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2016-11-25/ListStreamingDistributions +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2017-03-25/ListStreamingDistributions func (c *CloudFront) ListStreamingDistributionsRequest(input *ListStreamingDistributionsInput) (req *request.Request, output *ListStreamingDistributionsOutput) { op := &request.Operation{ Name: opListStreamingDistributions, HTTPMethod: "GET", - HTTPPath: "/2016-11-25/streaming-distribution", + HTTPPath: "/2017-03-25/streaming-distribution", Paginator: &request.Paginator{ InputTokens: []string{"Marker"}, OutputTokens: []string{"StreamingDistributionList.NextMarker"}, @@ -1941,11 +2324,26 @@ func (c *CloudFront) ListStreamingDistributionsRequest(input *ListStreamingDistr // * ErrCodeInvalidArgument "InvalidArgument" // The argument is invalid. // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2016-11-25/ListStreamingDistributions +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2017-03-25/ListStreamingDistributions func (c *CloudFront) ListStreamingDistributions(input *ListStreamingDistributionsInput) (*ListStreamingDistributionsOutput, error) { req, out := c.ListStreamingDistributionsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListStreamingDistributionsWithContext is the same as ListStreamingDistributions with the addition of +// the ability to pass a context and additional request options. +// +// See ListStreamingDistributions 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 *CloudFront) ListStreamingDistributionsWithContext(ctx aws.Context, input *ListStreamingDistributionsInput, opts ...request.Option) (*ListStreamingDistributionsOutput, error) { + req, out := c.ListStreamingDistributionsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // ListStreamingDistributionsPages iterates over the pages of a ListStreamingDistributions operation, @@ -1965,15 +2363,40 @@ func (c *CloudFront) ListStreamingDistributions(input *ListStreamingDistribution // return pageNum <= 3 // }) // -func (c *CloudFront) ListStreamingDistributionsPages(input *ListStreamingDistributionsInput, fn func(p *ListStreamingDistributionsOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.ListStreamingDistributionsRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*ListStreamingDistributionsOutput), lastPage) - }) +func (c *CloudFront) ListStreamingDistributionsPages(input *ListStreamingDistributionsInput, fn func(*ListStreamingDistributionsOutput, bool) bool) error { + return c.ListStreamingDistributionsPagesWithContext(aws.BackgroundContext(), input, fn) } -const opListTagsForResource = "ListTagsForResource2016_11_25" +// ListStreamingDistributionsPagesWithContext same as ListStreamingDistributionsPages 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 *CloudFront) ListStreamingDistributionsPagesWithContext(ctx aws.Context, input *ListStreamingDistributionsInput, fn func(*ListStreamingDistributionsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListStreamingDistributionsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListStreamingDistributionsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*ListStreamingDistributionsOutput), !p.HasNextPage()) + } + return p.Err() +} + +const opListTagsForResource = "ListTagsForResource2017_03_25" // ListTagsForResourceRequest generates a "aws/request.Request" representing the // client's request for the ListTagsForResource operation. The "output" return @@ -1999,12 +2422,12 @@ const opListTagsForResource = "ListTagsForResource2016_11_25" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2016-11-25/ListTagsForResource +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2017-03-25/ListTagsForResource func (c *CloudFront) ListTagsForResourceRequest(input *ListTagsForResourceInput) (req *request.Request, output *ListTagsForResourceOutput) { op := &request.Operation{ Name: opListTagsForResource, HTTPMethod: "GET", - HTTPPath: "/2016-11-25/tagging", + HTTPPath: "/2017-03-25/tagging", } if input == nil { @@ -2038,14 +2461,29 @@ func (c *CloudFront) ListTagsForResourceRequest(input *ListTagsForResourceInput) // // * ErrCodeNoSuchResource "NoSuchResource" // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2016-11-25/ListTagsForResource +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2017-03-25/ListTagsForResource func (c *CloudFront) ListTagsForResource(input *ListTagsForResourceInput) (*ListTagsForResourceOutput, error) { req, out := c.ListTagsForResourceRequest(input) - err := req.Send() - return out, err + return out, req.Send() } -const opTagResource = "TagResource2016_11_25" +// ListTagsForResourceWithContext is the same as ListTagsForResource with the addition of +// the ability to pass a context and additional request options. +// +// See ListTagsForResource 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 *CloudFront) ListTagsForResourceWithContext(ctx aws.Context, input *ListTagsForResourceInput, opts ...request.Option) (*ListTagsForResourceOutput, error) { + req, out := c.ListTagsForResourceRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opTagResource = "TagResource2017_03_25" // TagResourceRequest generates a "aws/request.Request" representing the // client's request for the TagResource operation. The "output" return @@ -2071,12 +2509,12 @@ const opTagResource = "TagResource2016_11_25" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2016-11-25/TagResource +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2017-03-25/TagResource func (c *CloudFront) TagResourceRequest(input *TagResourceInput) (req *request.Request, output *TagResourceOutput) { op := &request.Operation{ Name: opTagResource, HTTPMethod: "POST", - HTTPPath: "/2016-11-25/tagging?Operation=Tag", + HTTPPath: "/2017-03-25/tagging?Operation=Tag", } if input == nil { @@ -2112,14 +2550,29 @@ func (c *CloudFront) TagResourceRequest(input *TagResourceInput) (req *request.R // // * ErrCodeNoSuchResource "NoSuchResource" // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2016-11-25/TagResource +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2017-03-25/TagResource func (c *CloudFront) TagResource(input *TagResourceInput) (*TagResourceOutput, error) { req, out := c.TagResourceRequest(input) - err := req.Send() - return out, err + return out, req.Send() } -const opUntagResource = "UntagResource2016_11_25" +// TagResourceWithContext is the same as TagResource with the addition of +// the ability to pass a context and additional request options. +// +// See TagResource for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *CloudFront) TagResourceWithContext(ctx aws.Context, input *TagResourceInput, opts ...request.Option) (*TagResourceOutput, error) { + req, out := c.TagResourceRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opUntagResource = "UntagResource2017_03_25" // UntagResourceRequest generates a "aws/request.Request" representing the // client's request for the UntagResource operation. The "output" return @@ -2145,12 +2598,12 @@ const opUntagResource = "UntagResource2016_11_25" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2016-11-25/UntagResource +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2017-03-25/UntagResource func (c *CloudFront) UntagResourceRequest(input *UntagResourceInput) (req *request.Request, output *UntagResourceOutput) { op := &request.Operation{ Name: opUntagResource, HTTPMethod: "POST", - HTTPPath: "/2016-11-25/tagging?Operation=Untag", + HTTPPath: "/2017-03-25/tagging?Operation=Untag", } if input == nil { @@ -2186,14 +2639,29 @@ func (c *CloudFront) UntagResourceRequest(input *UntagResourceInput) (req *reque // // * ErrCodeNoSuchResource "NoSuchResource" // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2016-11-25/UntagResource +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2017-03-25/UntagResource func (c *CloudFront) UntagResource(input *UntagResourceInput) (*UntagResourceOutput, error) { req, out := c.UntagResourceRequest(input) - err := req.Send() - return out, err + return out, req.Send() } -const opUpdateCloudFrontOriginAccessIdentity = "UpdateCloudFrontOriginAccessIdentity2016_11_25" +// UntagResourceWithContext is the same as UntagResource with the addition of +// the ability to pass a context and additional request options. +// +// See UntagResource for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *CloudFront) UntagResourceWithContext(ctx aws.Context, input *UntagResourceInput, opts ...request.Option) (*UntagResourceOutput, error) { + req, out := c.UntagResourceRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opUpdateCloudFrontOriginAccessIdentity = "UpdateCloudFrontOriginAccessIdentity2017_03_25" // UpdateCloudFrontOriginAccessIdentityRequest generates a "aws/request.Request" representing the // client's request for the UpdateCloudFrontOriginAccessIdentity operation. The "output" return @@ -2219,12 +2687,12 @@ const opUpdateCloudFrontOriginAccessIdentity = "UpdateCloudFrontOriginAccessIden // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2016-11-25/UpdateCloudFrontOriginAccessIdentity +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2017-03-25/UpdateCloudFrontOriginAccessIdentity func (c *CloudFront) UpdateCloudFrontOriginAccessIdentityRequest(input *UpdateCloudFrontOriginAccessIdentityInput) (req *request.Request, output *UpdateCloudFrontOriginAccessIdentityOutput) { op := &request.Operation{ Name: opUpdateCloudFrontOriginAccessIdentity, HTTPMethod: "PUT", - HTTPPath: "/2016-11-25/origin-access-identity/cloudfront/{Id}/config", + HTTPPath: "/2017-03-25/origin-access-identity/cloudfront/{Id}/config", } if input == nil { @@ -2274,14 +2742,29 @@ func (c *CloudFront) UpdateCloudFrontOriginAccessIdentityRequest(input *UpdateCl // * ErrCodeInconsistentQuantities "InconsistentQuantities" // The value of Quantity and the size of Items do not match. // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2016-11-25/UpdateCloudFrontOriginAccessIdentity +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2017-03-25/UpdateCloudFrontOriginAccessIdentity func (c *CloudFront) UpdateCloudFrontOriginAccessIdentity(input *UpdateCloudFrontOriginAccessIdentityInput) (*UpdateCloudFrontOriginAccessIdentityOutput, error) { req, out := c.UpdateCloudFrontOriginAccessIdentityRequest(input) - err := req.Send() - return out, err + return out, req.Send() } -const opUpdateDistribution = "UpdateDistribution2016_11_25" +// UpdateCloudFrontOriginAccessIdentityWithContext is the same as UpdateCloudFrontOriginAccessIdentity with the addition of +// the ability to pass a context and additional request options. +// +// See UpdateCloudFrontOriginAccessIdentity 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 *CloudFront) UpdateCloudFrontOriginAccessIdentityWithContext(ctx aws.Context, input *UpdateCloudFrontOriginAccessIdentityInput, opts ...request.Option) (*UpdateCloudFrontOriginAccessIdentityOutput, error) { + req, out := c.UpdateCloudFrontOriginAccessIdentityRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opUpdateDistribution = "UpdateDistribution2017_03_25" // UpdateDistributionRequest generates a "aws/request.Request" representing the // client's request for the UpdateDistribution operation. The "output" return @@ -2307,12 +2790,12 @@ const opUpdateDistribution = "UpdateDistribution2016_11_25" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2016-11-25/UpdateDistribution +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2017-03-25/UpdateDistribution func (c *CloudFront) UpdateDistributionRequest(input *UpdateDistributionInput) (req *request.Request, output *UpdateDistributionOutput) { op := &request.Operation{ Name: opUpdateDistribution, HTTPMethod: "PUT", - HTTPPath: "/2016-11-25/distribution/{Id}/config", + HTTPPath: "/2017-03-25/distribution/{Id}/config", } if input == nil { @@ -2447,14 +2930,33 @@ func (c *CloudFront) UpdateDistributionRequest(input *UpdateDistributionInput) ( // * ErrCodeInvalidLambdaFunctionAssociation "InvalidLambdaFunctionAssociation" // The specified Lambda function association is invalid. // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2016-11-25/UpdateDistribution +// * ErrCodeInvalidOriginReadTimeout "InvalidOriginReadTimeout" +// +// * ErrCodeInvalidOriginKeepaliveTimeout "InvalidOriginKeepaliveTimeout" +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2017-03-25/UpdateDistribution func (c *CloudFront) UpdateDistribution(input *UpdateDistributionInput) (*UpdateDistributionOutput, error) { req, out := c.UpdateDistributionRequest(input) - err := req.Send() - return out, err + return out, req.Send() } -const opUpdateStreamingDistribution = "UpdateStreamingDistribution2016_11_25" +// UpdateDistributionWithContext is the same as UpdateDistribution with the addition of +// the ability to pass a context and additional request options. +// +// See UpdateDistribution 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 *CloudFront) UpdateDistributionWithContext(ctx aws.Context, input *UpdateDistributionInput, opts ...request.Option) (*UpdateDistributionOutput, error) { + req, out := c.UpdateDistributionRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opUpdateStreamingDistribution = "UpdateStreamingDistribution2017_03_25" // UpdateStreamingDistributionRequest generates a "aws/request.Request" representing the // client's request for the UpdateStreamingDistribution operation. The "output" return @@ -2480,12 +2982,12 @@ const opUpdateStreamingDistribution = "UpdateStreamingDistribution2016_11_25" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2016-11-25/UpdateStreamingDistribution +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2017-03-25/UpdateStreamingDistribution func (c *CloudFront) UpdateStreamingDistributionRequest(input *UpdateStreamingDistributionInput) (req *request.Request, output *UpdateStreamingDistributionOutput) { op := &request.Operation{ Name: opUpdateStreamingDistribution, HTTPMethod: "PUT", - HTTPPath: "/2016-11-25/streaming-distribution/{Id}/config", + HTTPPath: "/2017-03-25/streaming-distribution/{Id}/config", } if input == nil { @@ -2548,11 +3050,26 @@ func (c *CloudFront) UpdateStreamingDistributionRequest(input *UpdateStreamingDi // * ErrCodeInconsistentQuantities "InconsistentQuantities" // The value of Quantity and the size of Items do not match. // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2016-11-25/UpdateStreamingDistribution +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2017-03-25/UpdateStreamingDistribution func (c *CloudFront) UpdateStreamingDistribution(input *UpdateStreamingDistributionInput) (*UpdateStreamingDistributionOutput, error) { req, out := c.UpdateStreamingDistributionRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// UpdateStreamingDistributionWithContext is the same as UpdateStreamingDistribution with the addition of +// the ability to pass a context and additional request options. +// +// See UpdateStreamingDistribution 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 *CloudFront) UpdateStreamingDistributionWithContext(ctx aws.Context, input *UpdateStreamingDistributionInput, opts ...request.Option) (*UpdateStreamingDistributionOutput, error) { + req, out := c.UpdateStreamingDistributionRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // A complex type that lists the AWS accounts, if any, that you included in @@ -2567,7 +3084,7 @@ func (c *CloudFront) UpdateStreamingDistribution(input *UpdateStreamingDistribut // // For more information, see Serving Private Content through CloudFront (http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/PrivateContent.html) // in the Amazon CloudFront Developer Guide. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2016-11-25/ActiveTrustedSigners +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2017-03-25/ActiveTrustedSigners type ActiveTrustedSigners struct { _ struct{} `type:"structure"` @@ -2625,7 +3142,7 @@ func (s *ActiveTrustedSigners) SetQuantity(v int64) *ActiveTrustedSigners { // A complex type that contains information about CNAMEs (alternate domain names), // if any, for this distribution. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2016-11-25/Aliases +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2017-03-25/Aliases type Aliases struct { _ struct{} `type:"structure"` @@ -2690,7 +3207,7 @@ func (s *Aliases) SetQuantity(v int64) *Aliases { // S3 bucket or to your custom origin so users can't perform operations that // you don't want them to. For example, you might not want users to have permissions // to delete objects from your origin. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2016-11-25/AllowedMethods +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2017-03-25/AllowedMethods type AllowedMethods struct { _ struct{} `type:"structure"` @@ -2795,7 +3312,7 @@ func (s *AllowedMethods) SetQuantity(v int64) *AllowedMethods { // // For more information about cache behaviors, see Cache Behaviors (http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/distribution-web-values-specify.html#DownloadDistValuesCacheBehavior) // in the Amazon CloudFront Developer Guide. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2016-11-25/CacheBehavior +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2017-03-25/CacheBehavior type CacheBehavior struct { _ struct{} `type:"structure"` @@ -3077,7 +3594,7 @@ func (s *CacheBehavior) SetViewerProtocolPolicy(v string) *CacheBehavior { } // A complex type that contains zero or more CacheBehavior elements. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2016-11-25/CacheBehaviors +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2017-03-25/CacheBehaviors type CacheBehaviors struct { _ struct{} `type:"structure"` @@ -3146,7 +3663,7 @@ func (s *CacheBehaviors) SetQuantity(v int64) *CacheBehaviors { // If you pick the second choice for your Amazon S3 Origin, you may need to // forward Access-Control-Request-Method, Access-Control-Request-Headers, and // Origin headers for the responses to be cached correctly. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2016-11-25/CachedMethods +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2017-03-25/CachedMethods type CachedMethods struct { _ struct{} `type:"structure"` @@ -3207,7 +3724,7 @@ func (s *CachedMethods) SetQuantity(v int64) *CachedMethods { // cookies to the origin, see How CloudFront Forwards, Caches, and Logs Cookies // (http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/Cookies.html) // in the Amazon CloudFront Developer Guide. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2016-11-25/CookieNames +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2017-03-25/CookieNames type CookieNames struct { _ struct{} `type:"structure"` @@ -3262,7 +3779,7 @@ func (s *CookieNames) SetQuantity(v int64) *CookieNames { // cookies to the origin, see How CloudFront Forwards, Caches, and Logs Cookies // (http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/Cookies.html) // in the Amazon CloudFront Developer Guide. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2016-11-25/CookiePreference +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2017-03-25/CookiePreference type CookiePreference struct { _ struct{} `type:"structure"` @@ -3333,7 +3850,7 @@ func (s *CookiePreference) SetWhitelistedNames(v *CookieNames) *CookiePreference } // The request to create a new origin access identity. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2016-11-25/CreateCloudFrontOriginAccessIdentityRequest +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2017-03-25/CreateCloudFrontOriginAccessIdentityRequest type CreateCloudFrontOriginAccessIdentityInput struct { _ struct{} `type:"structure" payload:"CloudFrontOriginAccessIdentityConfig"` @@ -3378,7 +3895,7 @@ func (s *CreateCloudFrontOriginAccessIdentityInput) SetCloudFrontOriginAccessIde } // The returned result of the corresponding request. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2016-11-25/CreateCloudFrontOriginAccessIdentityResult +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2017-03-25/CreateCloudFrontOriginAccessIdentityResult type CreateCloudFrontOriginAccessIdentityOutput struct { _ struct{} `type:"structure" payload:"CloudFrontOriginAccessIdentity"` @@ -3422,7 +3939,7 @@ func (s *CreateCloudFrontOriginAccessIdentityOutput) SetLocation(v string) *Crea } // The request to create a new distribution. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2016-11-25/CreateDistributionRequest +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2017-03-25/CreateDistributionRequest type CreateDistributionInput struct { _ struct{} `type:"structure" payload:"DistributionConfig"` @@ -3467,7 +3984,7 @@ func (s *CreateDistributionInput) SetDistributionConfig(v *DistributionConfig) * } // The returned result of the corresponding request. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2016-11-25/CreateDistributionResult +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2017-03-25/CreateDistributionResult type CreateDistributionOutput struct { _ struct{} `type:"structure" payload:"Distribution"` @@ -3511,7 +4028,7 @@ func (s *CreateDistributionOutput) SetLocation(v string) *CreateDistributionOutp } // The request to create a new distribution with tags. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2016-11-25/CreateDistributionWithTagsRequest +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2017-03-25/CreateDistributionWithTagsRequest type CreateDistributionWithTagsInput struct { _ struct{} `type:"structure" payload:"DistributionConfigWithTags"` @@ -3556,7 +4073,7 @@ func (s *CreateDistributionWithTagsInput) SetDistributionConfigWithTags(v *Distr } // The returned result of the corresponding request. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2016-11-25/CreateDistributionWithTagsResult +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2017-03-25/CreateDistributionWithTagsResult type CreateDistributionWithTagsOutput struct { _ struct{} `type:"structure" payload:"Distribution"` @@ -3600,7 +4117,7 @@ func (s *CreateDistributionWithTagsOutput) SetLocation(v string) *CreateDistribu } // The request to create an invalidation. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2016-11-25/CreateInvalidationRequest +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2017-03-25/CreateInvalidationRequest type CreateInvalidationInput struct { _ struct{} `type:"structure" payload:"InvalidationBatch"` @@ -3659,7 +4176,7 @@ func (s *CreateInvalidationInput) SetInvalidationBatch(v *InvalidationBatch) *Cr } // The returned result of the corresponding request. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2016-11-25/CreateInvalidationResult +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2017-03-25/CreateInvalidationResult type CreateInvalidationOutput struct { _ struct{} `type:"structure" payload:"Invalidation"` @@ -3694,7 +4211,7 @@ func (s *CreateInvalidationOutput) SetLocation(v string) *CreateInvalidationOutp } // The request to create a new streaming distribution. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2016-11-25/CreateStreamingDistributionRequest +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2017-03-25/CreateStreamingDistributionRequest type CreateStreamingDistributionInput struct { _ struct{} `type:"structure" payload:"StreamingDistributionConfig"` @@ -3739,7 +4256,7 @@ func (s *CreateStreamingDistributionInput) SetStreamingDistributionConfig(v *Str } // The returned result of the corresponding request. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2016-11-25/CreateStreamingDistributionResult +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2017-03-25/CreateStreamingDistributionResult type CreateStreamingDistributionOutput struct { _ struct{} `type:"structure" payload:"StreamingDistribution"` @@ -3783,7 +4300,7 @@ func (s *CreateStreamingDistributionOutput) SetStreamingDistribution(v *Streamin } // The request to create a new streaming distribution with tags. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2016-11-25/CreateStreamingDistributionWithTagsRequest +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2017-03-25/CreateStreamingDistributionWithTagsRequest type CreateStreamingDistributionWithTagsInput struct { _ struct{} `type:"structure" payload:"StreamingDistributionConfigWithTags"` @@ -3828,7 +4345,7 @@ func (s *CreateStreamingDistributionWithTagsInput) SetStreamingDistributionConfi } // The returned result of the corresponding request. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2016-11-25/CreateStreamingDistributionWithTagsResult +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2017-03-25/CreateStreamingDistributionWithTagsResult type CreateStreamingDistributionWithTagsOutput struct { _ struct{} `type:"structure" payload:"StreamingDistribution"` @@ -3881,7 +4398,7 @@ func (s *CreateStreamingDistributionWithTagsOutput) SetStreamingDistribution(v * // For more information about custom error pages, see Customizing Error Responses // (http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/custom-error-pages.html) // in the Amazon CloudFront Developer Guide. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2016-11-25/CustomErrorResponse +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2017-03-25/CustomErrorResponse type CustomErrorResponse struct { _ struct{} `type:"structure"` @@ -4009,7 +4526,7 @@ func (s *CustomErrorResponse) SetResponsePagePath(v string) *CustomErrorResponse // For more information about custom error pages, see Customizing Error Responses // (http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/custom-error-pages.html) // in the Amazon CloudFront Developer Guide. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2016-11-25/CustomErrorResponses +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2017-03-25/CustomErrorResponses type CustomErrorResponses struct { _ struct{} `type:"structure"` @@ -4071,7 +4588,7 @@ func (s *CustomErrorResponses) SetQuantity(v int64) *CustomErrorResponses { } // A complex type that contains the list of Custom Headers for each origin. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2016-11-25/CustomHeaders +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2017-03-25/CustomHeaders type CustomHeaders struct { _ struct{} `type:"structure"` @@ -4132,7 +4649,7 @@ func (s *CustomHeaders) SetQuantity(v int64) *CustomHeaders { } // A customer origin. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2016-11-25/CustomOriginConfig +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2017-03-25/CustomOriginConfig type CustomOriginConfig struct { _ struct{} `type:"structure"` @@ -4146,11 +4663,29 @@ type CustomOriginConfig struct { // HTTPSPort is a required field HTTPSPort *int64 `type:"integer" required:"true"` + // You can create a custom keep-alive timeout. All timeout units are in seconds. + // The default keep-alive timeout is 5 seconds, but you can configure custom + // timeout lengths using the CloudFront API. The minimum timeout length is 1 + // second; the maximum is 60 seconds. + // + // If you need to increase the maximum time limit, contact the AWS Support Center + // (https://console.aws.amazon.com/support/home#/). + OriginKeepaliveTimeout *int64 `type:"integer"` + // The origin protocol policy to apply to your origin. // // OriginProtocolPolicy is a required field OriginProtocolPolicy *string `type:"string" required:"true" enum:"OriginProtocolPolicy"` + // You can create a custom origin read timeout. All timeout units are in seconds. + // The default origin read timeout is 30 seconds, but you can configure custom + // timeout lengths using the CloudFront API. The minimum timeout length is 4 + // seconds; the maximum is 60 seconds. + // + // If you need to increase the maximum time limit, contact the AWS Support Center + // (https://console.aws.amazon.com/support/home#/). + OriginReadTimeout *int64 `type:"integer"` + // The SSL/TLS protocols that you want CloudFront to use when communicating // with your origin over HTTPS. OriginSslProtocols *OriginSslProtocols `type:"structure"` @@ -4202,12 +4737,24 @@ func (s *CustomOriginConfig) SetHTTPSPort(v int64) *CustomOriginConfig { return s } +// SetOriginKeepaliveTimeout sets the OriginKeepaliveTimeout field's value. +func (s *CustomOriginConfig) SetOriginKeepaliveTimeout(v int64) *CustomOriginConfig { + s.OriginKeepaliveTimeout = &v + return s +} + // SetOriginProtocolPolicy sets the OriginProtocolPolicy field's value. func (s *CustomOriginConfig) SetOriginProtocolPolicy(v string) *CustomOriginConfig { s.OriginProtocolPolicy = &v return s } +// SetOriginReadTimeout sets the OriginReadTimeout field's value. +func (s *CustomOriginConfig) SetOriginReadTimeout(v int64) *CustomOriginConfig { + s.OriginReadTimeout = &v + return s +} + // SetOriginSslProtocols sets the OriginSslProtocols field's value. func (s *CustomOriginConfig) SetOriginSslProtocols(v *OriginSslProtocols) *CustomOriginConfig { s.OriginSslProtocols = v @@ -4217,7 +4764,7 @@ func (s *CustomOriginConfig) SetOriginSslProtocols(v *OriginSslProtocols) *Custo // A complex type that describes the default cache behavior if you do not specify // a CacheBehavior element or if files don't match any of the values of PathPattern // in CacheBehavior elements. You must create exactly one default cache behavior. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2016-11-25/DefaultCacheBehavior +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2017-03-25/DefaultCacheBehavior type DefaultCacheBehavior struct { _ struct{} `type:"structure"` @@ -4463,7 +5010,7 @@ func (s *DefaultCacheBehavior) SetViewerProtocolPolicy(v string) *DefaultCacheBe } // Deletes a origin access identity. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2016-11-25/DeleteCloudFrontOriginAccessIdentityRequest +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2017-03-25/DeleteCloudFrontOriginAccessIdentityRequest type DeleteCloudFrontOriginAccessIdentityInput struct { _ struct{} `type:"structure"` @@ -4512,7 +5059,7 @@ func (s *DeleteCloudFrontOriginAccessIdentityInput) SetIfMatch(v string) *Delete return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2016-11-25/DeleteCloudFrontOriginAccessIdentityOutput +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2017-03-25/DeleteCloudFrontOriginAccessIdentityOutput type DeleteCloudFrontOriginAccessIdentityOutput struct { _ struct{} `type:"structure"` } @@ -4562,7 +5109,7 @@ func (s DeleteCloudFrontOriginAccessIdentityOutput) GoString() string { // For information about deleting a distribution using the CloudFront console, // see Deleting a Distribution (http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/HowToDeleteDistribution.html) // in the Amazon CloudFront Developer Guide. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2016-11-25/DeleteDistributionRequest +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2017-03-25/DeleteDistributionRequest type DeleteDistributionInput struct { _ struct{} `type:"structure"` @@ -4611,7 +5158,7 @@ func (s *DeleteDistributionInput) SetIfMatch(v string) *DeleteDistributionInput return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2016-11-25/DeleteDistributionOutput +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2017-03-25/DeleteDistributionOutput type DeleteDistributionOutput struct { _ struct{} `type:"structure"` } @@ -4627,7 +5174,7 @@ func (s DeleteDistributionOutput) GoString() string { } // The request to delete a streaming distribution. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2016-11-25/DeleteStreamingDistributionRequest +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2017-03-25/DeleteStreamingDistributionRequest type DeleteStreamingDistributionInput struct { _ struct{} `type:"structure"` @@ -4676,7 +5223,7 @@ func (s *DeleteStreamingDistributionInput) SetIfMatch(v string) *DeleteStreaming return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2016-11-25/DeleteStreamingDistributionOutput +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2017-03-25/DeleteStreamingDistributionOutput type DeleteStreamingDistributionOutput struct { _ struct{} `type:"structure"` } @@ -4692,7 +5239,7 @@ func (s DeleteStreamingDistributionOutput) GoString() string { } // The distribution's information. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2016-11-25/Distribution +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2017-03-25/Distribution type Distribution struct { _ struct{} `type:"structure"` @@ -4807,7 +5354,7 @@ func (s *Distribution) SetStatus(v string) *Distribution { } // A distribution configuration. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2016-11-25/DistributionConfig +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2017-03-25/DistributionConfig type DistributionConfig struct { _ struct{} `type:"structure"` @@ -4890,12 +5437,7 @@ type DistributionConfig struct { // in the Amazon CloudFront Developer Guide. DefaultRootObject *string `type:"string"` - // Specifies whether you want CloudFront to save access logs to an Amazon S3 - // bucket. - // - // If you do not want to enable logging when you create a distribution, or if - // you want to disable logging for an existing distribution, specify false for - // Enabled, and specify empty Bucket and Prefix elements. + // From this field, you can enable or disable the selected distribution. // // If you specify false for Enabled but you specify values for Bucket and Prefix, // the values are automatically deleted. @@ -5180,7 +5722,7 @@ func (s *DistributionConfig) SetWebACLId(v string) *DistributionConfig { // A distribution Configuration and a list of tags to be associated with the // distribution. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2016-11-25/DistributionConfigWithTags +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2017-03-25/DistributionConfigWithTags type DistributionConfigWithTags struct { _ struct{} `type:"structure"` @@ -5244,7 +5786,7 @@ func (s *DistributionConfigWithTags) SetTags(v *Tags) *DistributionConfigWithTag } // A distribution list. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2016-11-25/DistributionList +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2017-03-25/DistributionList type DistributionList struct { _ struct{} `type:"structure"` @@ -5328,7 +5870,7 @@ func (s *DistributionList) SetQuantity(v int64) *DistributionList { } // A summary of the information about a CloudFront distribution. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2016-11-25/DistributionSummary +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2017-03-25/DistributionSummary type DistributionSummary struct { _ struct{} `type:"structure"` @@ -5562,7 +6104,7 @@ func (s *DistributionSummary) SetWebACLId(v string) *DistributionSummary { } // A complex type that specifies how CloudFront handles query strings and cookies. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2016-11-25/ForwardedValues +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2017-03-25/ForwardedValues type ForwardedValues struct { _ struct{} `type:"structure"` @@ -5678,7 +6220,7 @@ func (s *ForwardedValues) SetQueryStringCacheKeys(v *QueryStringCacheKeys) *Forw // A complex type that controls the countries in which your content is distributed. // CloudFront determines the location of your users using MaxMind GeoIP databases. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2016-11-25/GeoRestriction +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2017-03-25/GeoRestriction type GeoRestriction struct { _ struct{} `type:"structure"` @@ -5766,7 +6308,7 @@ func (s *GeoRestriction) SetRestrictionType(v string) *GeoRestriction { // The origin access identity's configuration information. For more information, // see CloudFrontOriginAccessIdentityConfigComplexType. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2016-11-25/GetCloudFrontOriginAccessIdentityConfigRequest +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2017-03-25/GetCloudFrontOriginAccessIdentityConfigRequest type GetCloudFrontOriginAccessIdentityConfigInput struct { _ struct{} `type:"structure"` @@ -5806,7 +6348,7 @@ func (s *GetCloudFrontOriginAccessIdentityConfigInput) SetId(v string) *GetCloud } // The returned result of the corresponding request. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2016-11-25/GetCloudFrontOriginAccessIdentityConfigResult +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2017-03-25/GetCloudFrontOriginAccessIdentityConfigResult type GetCloudFrontOriginAccessIdentityConfigOutput struct { _ struct{} `type:"structure" payload:"CloudFrontOriginAccessIdentityConfig"` @@ -5840,7 +6382,7 @@ func (s *GetCloudFrontOriginAccessIdentityConfigOutput) SetETag(v string) *GetCl } // The request to get an origin access identity's information. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2016-11-25/GetCloudFrontOriginAccessIdentityRequest +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2017-03-25/GetCloudFrontOriginAccessIdentityRequest type GetCloudFrontOriginAccessIdentityInput struct { _ struct{} `type:"structure"` @@ -5880,7 +6422,7 @@ func (s *GetCloudFrontOriginAccessIdentityInput) SetId(v string) *GetCloudFrontO } // The returned result of the corresponding request. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2016-11-25/GetCloudFrontOriginAccessIdentityResult +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2017-03-25/GetCloudFrontOriginAccessIdentityResult type GetCloudFrontOriginAccessIdentityOutput struct { _ struct{} `type:"structure" payload:"CloudFrontOriginAccessIdentity"` @@ -5915,7 +6457,7 @@ func (s *GetCloudFrontOriginAccessIdentityOutput) SetETag(v string) *GetCloudFro } // The request to get a distribution configuration. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2016-11-25/GetDistributionConfigRequest +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2017-03-25/GetDistributionConfigRequest type GetDistributionConfigInput struct { _ struct{} `type:"structure"` @@ -5955,7 +6497,7 @@ func (s *GetDistributionConfigInput) SetId(v string) *GetDistributionConfigInput } // The returned result of the corresponding request. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2016-11-25/GetDistributionConfigResult +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2017-03-25/GetDistributionConfigResult type GetDistributionConfigOutput struct { _ struct{} `type:"structure" payload:"DistributionConfig"` @@ -5989,7 +6531,7 @@ func (s *GetDistributionConfigOutput) SetETag(v string) *GetDistributionConfigOu } // The request to get a distribution's information. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2016-11-25/GetDistributionRequest +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2017-03-25/GetDistributionRequest type GetDistributionInput struct { _ struct{} `type:"structure"` @@ -6029,7 +6571,7 @@ func (s *GetDistributionInput) SetId(v string) *GetDistributionInput { } // The returned result of the corresponding request. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2016-11-25/GetDistributionResult +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2017-03-25/GetDistributionResult type GetDistributionOutput struct { _ struct{} `type:"structure" payload:"Distribution"` @@ -6063,7 +6605,7 @@ func (s *GetDistributionOutput) SetETag(v string) *GetDistributionOutput { } // The request to get an invalidation's information. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2016-11-25/GetInvalidationRequest +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2017-03-25/GetInvalidationRequest type GetInvalidationInput struct { _ struct{} `type:"structure"` @@ -6117,7 +6659,7 @@ func (s *GetInvalidationInput) SetId(v string) *GetInvalidationInput { } // The returned result of the corresponding request. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2016-11-25/GetInvalidationResult +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2017-03-25/GetInvalidationResult type GetInvalidationOutput struct { _ struct{} `type:"structure" payload:"Invalidation"` @@ -6143,7 +6685,7 @@ func (s *GetInvalidationOutput) SetInvalidation(v *Invalidation) *GetInvalidatio } // To request to get a streaming distribution configuration. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2016-11-25/GetStreamingDistributionConfigRequest +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2017-03-25/GetStreamingDistributionConfigRequest type GetStreamingDistributionConfigInput struct { _ struct{} `type:"structure"` @@ -6183,7 +6725,7 @@ func (s *GetStreamingDistributionConfigInput) SetId(v string) *GetStreamingDistr } // The returned result of the corresponding request. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2016-11-25/GetStreamingDistributionConfigResult +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2017-03-25/GetStreamingDistributionConfigResult type GetStreamingDistributionConfigOutput struct { _ struct{} `type:"structure" payload:"StreamingDistributionConfig"` @@ -6217,7 +6759,7 @@ func (s *GetStreamingDistributionConfigOutput) SetStreamingDistributionConfig(v } // The request to get a streaming distribution's information. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2016-11-25/GetStreamingDistributionRequest +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2017-03-25/GetStreamingDistributionRequest type GetStreamingDistributionInput struct { _ struct{} `type:"structure"` @@ -6257,7 +6799,7 @@ func (s *GetStreamingDistributionInput) SetId(v string) *GetStreamingDistributio } // The returned result of the corresponding request. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2016-11-25/GetStreamingDistributionResult +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2017-03-25/GetStreamingDistributionResult type GetStreamingDistributionOutput struct { _ struct{} `type:"structure" payload:"StreamingDistribution"` @@ -6303,7 +6845,7 @@ func (s *GetStreamingDistributionOutput) SetStreamingDistribution(v *StreamingDi // once for each header value. For more information about caching based on header // values, see How CloudFront Forwards and Caches Headers (http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/header-caching.html) // in the Amazon CloudFront Developer Guide. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2016-11-25/Headers +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2017-03-25/Headers type Headers struct { _ struct{} `type:"structure"` @@ -6374,7 +6916,7 @@ func (s *Headers) SetQuantity(v int64) *Headers { } // An invalidation. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2016-11-25/Invalidation +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2017-03-25/Invalidation type Invalidation struct { _ struct{} `type:"structure"` @@ -6435,7 +6977,7 @@ func (s *Invalidation) SetStatus(v string) *Invalidation { } // An invalidation batch. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2016-11-25/InvalidationBatch +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2017-03-25/InvalidationBatch type InvalidationBatch struct { _ struct{} `type:"structure"` @@ -6514,7 +7056,7 @@ func (s *InvalidationBatch) SetPaths(v *Paths) *InvalidationBatch { // For more information about invalidation, see Invalidating Objects (Web Distributions // Only) (http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/Invalidation.html) // in the Amazon CloudFront Developer Guide. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2016-11-25/InvalidationList +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2017-03-25/InvalidationList type InvalidationList struct { _ struct{} `type:"structure"` @@ -6598,7 +7140,7 @@ func (s *InvalidationList) SetQuantity(v int64) *InvalidationList { } // A summary of an invalidation request. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2016-11-25/InvalidationSummary +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2017-03-25/InvalidationSummary type InvalidationSummary struct { _ struct{} `type:"structure"` @@ -6648,7 +7190,7 @@ func (s *InvalidationSummary) SetStatus(v string) *InvalidationSummary { // associated with AwsAccountNumber. // // For more information, see ActiveTrustedSigners. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2016-11-25/KeyPairIds +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2017-03-25/KeyPairIds type KeyPairIds struct { _ struct{} `type:"structure"` @@ -6689,7 +7231,7 @@ func (s *KeyPairIds) SetQuantity(v int64) *KeyPairIds { } // A complex type that contains a Lambda function association. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2016-11-25/LambdaFunctionAssociation +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2017-03-25/LambdaFunctionAssociation type LambdaFunctionAssociation struct { _ struct{} `type:"structure"` @@ -6742,7 +7284,7 @@ func (s *LambdaFunctionAssociation) SetLambdaFunctionARN(v string) *LambdaFuncti // // If you don't want to invoke any Lambda functions for the requests that match // PathPattern, specify 0 for Quantity and omit Items. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2016-11-25/LambdaFunctionAssociations +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2017-03-25/LambdaFunctionAssociations type LambdaFunctionAssociations struct { _ struct{} `type:"structure"` @@ -6792,7 +7334,7 @@ func (s *LambdaFunctionAssociations) SetQuantity(v int64) *LambdaFunctionAssocia } // The request to list origin access identities. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2016-11-25/ListCloudFrontOriginAccessIdentitiesRequest +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2017-03-25/ListCloudFrontOriginAccessIdentitiesRequest type ListCloudFrontOriginAccessIdentitiesInput struct { _ struct{} `type:"structure"` @@ -6830,7 +7372,7 @@ func (s *ListCloudFrontOriginAccessIdentitiesInput) SetMaxItems(v int64) *ListCl } // The returned result of the corresponding request. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2016-11-25/ListCloudFrontOriginAccessIdentitiesResult +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2017-03-25/ListCloudFrontOriginAccessIdentitiesResult type ListCloudFrontOriginAccessIdentitiesOutput struct { _ struct{} `type:"structure" payload:"CloudFrontOriginAccessIdentityList"` @@ -6856,7 +7398,7 @@ func (s *ListCloudFrontOriginAccessIdentitiesOutput) SetCloudFrontOriginAccessId // The request to list distributions that are associated with a specified AWS // WAF web ACL. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2016-11-25/ListDistributionsByWebACLIdRequest +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2017-03-25/ListDistributionsByWebACLIdRequest type ListDistributionsByWebACLIdInput struct { _ struct{} `type:"structure"` @@ -6922,7 +7464,7 @@ func (s *ListDistributionsByWebACLIdInput) SetWebACLId(v string) *ListDistributi // The response to a request to list the distributions that are associated with // a specified AWS WAF web ACL. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2016-11-25/ListDistributionsByWebACLIdResult +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2017-03-25/ListDistributionsByWebACLIdResult type ListDistributionsByWebACLIdOutput struct { _ struct{} `type:"structure" payload:"DistributionList"` @@ -6947,7 +7489,7 @@ func (s *ListDistributionsByWebACLIdOutput) SetDistributionList(v *DistributionL } // The request to list your distributions. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2016-11-25/ListDistributionsRequest +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2017-03-25/ListDistributionsRequest type ListDistributionsInput struct { _ struct{} `type:"structure"` @@ -6985,7 +7527,7 @@ func (s *ListDistributionsInput) SetMaxItems(v int64) *ListDistributionsInput { } // The returned result of the corresponding request. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2016-11-25/ListDistributionsResult +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2017-03-25/ListDistributionsResult type ListDistributionsOutput struct { _ struct{} `type:"structure" payload:"DistributionList"` @@ -7010,7 +7552,7 @@ func (s *ListDistributionsOutput) SetDistributionList(v *DistributionList) *List } // The request to list invalidations. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2016-11-25/ListInvalidationsRequest +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2017-03-25/ListInvalidationsRequest type ListInvalidationsInput struct { _ struct{} `type:"structure"` @@ -7075,7 +7617,7 @@ func (s *ListInvalidationsInput) SetMaxItems(v int64) *ListInvalidationsInput { } // The returned result of the corresponding request. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2016-11-25/ListInvalidationsResult +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2017-03-25/ListInvalidationsResult type ListInvalidationsOutput struct { _ struct{} `type:"structure" payload:"InvalidationList"` @@ -7100,7 +7642,7 @@ func (s *ListInvalidationsOutput) SetInvalidationList(v *InvalidationList) *List } // The request to list your streaming distributions. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2016-11-25/ListStreamingDistributionsRequest +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2017-03-25/ListStreamingDistributionsRequest type ListStreamingDistributionsInput struct { _ struct{} `type:"structure"` @@ -7134,7 +7676,7 @@ func (s *ListStreamingDistributionsInput) SetMaxItems(v int64) *ListStreamingDis } // The returned result of the corresponding request. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2016-11-25/ListStreamingDistributionsResult +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2017-03-25/ListStreamingDistributionsResult type ListStreamingDistributionsOutput struct { _ struct{} `type:"structure" payload:"StreamingDistributionList"` @@ -7159,7 +7701,7 @@ func (s *ListStreamingDistributionsOutput) SetStreamingDistributionList(v *Strea } // The request to list tags for a CloudFront resource. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2016-11-25/ListTagsForResourceRequest +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2017-03-25/ListTagsForResourceRequest type ListTagsForResourceInput struct { _ struct{} `type:"structure"` @@ -7199,7 +7741,7 @@ func (s *ListTagsForResourceInput) SetResource(v string) *ListTagsForResourceInp } // The returned result of the corresponding request. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2016-11-25/ListTagsForResourceResult +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2017-03-25/ListTagsForResourceResult type ListTagsForResourceOutput struct { _ struct{} `type:"structure" payload:"Tags"` @@ -7226,7 +7768,7 @@ func (s *ListTagsForResourceOutput) SetTags(v *Tags) *ListTagsForResourceOutput } // A complex type that controls whether access logs are written for the distribution. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2016-11-25/LoggingConfig +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2017-03-25/LoggingConfig type LoggingConfig struct { _ struct{} `type:"structure"` @@ -7327,7 +7869,7 @@ func (s *LoggingConfig) SetPrefix(v string) *LoggingConfig { // For the current limit on the number of origins that you can create for a // distribution, see Amazon CloudFront Limits (http://docs.aws.amazon.com/general/latest/gr/aws_service_limits.html#limits_cloudfront) // in the AWS General Reference. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2016-11-25/Origin +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2017-03-25/Origin type Origin struct { _ struct{} `type:"structure"` @@ -7485,7 +8027,7 @@ func (s *Origin) SetS3OriginConfig(v *S3OriginConfig) *Origin { } // CloudFront origin access identity. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2016-11-25/CloudFrontOriginAccessIdentity +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2017-03-25/CloudFrontOriginAccessIdentity type OriginAccessIdentity struct { _ struct{} `type:"structure"` @@ -7535,7 +8077,7 @@ func (s *OriginAccessIdentity) SetS3CanonicalUserId(v string) *OriginAccessIdent // Origin access identity configuration. Send a GET request to the /CloudFront // API version/CloudFront/identity ID/config resource. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2016-11-25/CloudFrontOriginAccessIdentityConfig +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2017-03-25/CloudFrontOriginAccessIdentityConfig type OriginAccessIdentityConfig struct { _ struct{} `type:"structure"` @@ -7607,7 +8149,7 @@ func (s *OriginAccessIdentityConfig) SetComment(v string) *OriginAccessIdentityC // child elements. By default, your entire list of origin access identities // is returned in one single page. If the list is long, you can paginate it // using the MaxItems and Marker parameters. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2016-11-25/CloudFrontOriginAccessIdentityList +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2017-03-25/CloudFrontOriginAccessIdentityList type OriginAccessIdentityList struct { _ struct{} `type:"structure"` @@ -7696,7 +8238,7 @@ func (s *OriginAccessIdentityList) SetQuantity(v int64) *OriginAccessIdentityLis } // Summary of the information about a CloudFront origin access identity. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2016-11-25/CloudFrontOriginAccessIdentitySummary +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2017-03-25/CloudFrontOriginAccessIdentitySummary type OriginAccessIdentitySummary struct { _ struct{} `type:"structure"` @@ -7749,7 +8291,7 @@ func (s *OriginAccessIdentitySummary) SetS3CanonicalUserId(v string) *OriginAcce // A complex type that contains HeaderName and HeaderValue elements, if any, // for this distribution. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2016-11-25/OriginCustomHeader +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2017-03-25/OriginCustomHeader type OriginCustomHeader struct { _ struct{} `type:"structure"` @@ -7807,7 +8349,7 @@ func (s *OriginCustomHeader) SetHeaderValue(v string) *OriginCustomHeader { // A complex type that contains information about the SSL/TLS protocols that // CloudFront can use when establishing an HTTPS connection with your origin. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2016-11-25/OriginSslProtocols +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2017-03-25/OriginSslProtocols type OriginSslProtocols struct { _ struct{} `type:"structure"` @@ -7862,7 +8404,7 @@ func (s *OriginSslProtocols) SetQuantity(v int64) *OriginSslProtocols { } // A complex type that contains information about origins for this distribution. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2016-11-25/Origins +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2017-03-25/Origins type Origins struct { _ struct{} `type:"structure"` @@ -7927,7 +8469,7 @@ func (s *Origins) SetQuantity(v int64) *Origins { // to invalidate. For more information, see Specifying the Objects to Invalidate // (http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/Invalidation.html#invalidation-specifying-objects) // in the Amazon CloudFront Developer Guide. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2016-11-25/Paths +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2017-03-25/Paths type Paths struct { _ struct{} `type:"structure"` @@ -7975,7 +8517,7 @@ func (s *Paths) SetQuantity(v int64) *Paths { return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2016-11-25/QueryStringCacheKeys +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2017-03-25/QueryStringCacheKeys type QueryStringCacheKeys struct { _ struct{} `type:"structure"` @@ -8027,7 +8569,7 @@ func (s *QueryStringCacheKeys) SetQuantity(v int64) *QueryStringCacheKeys { // A complex type that identifies ways in which you want to restrict distribution // of your content. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2016-11-25/Restrictions +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2017-03-25/Restrictions type Restrictions struct { _ struct{} `type:"structure"` @@ -8074,7 +8616,7 @@ func (s *Restrictions) SetGeoRestriction(v *GeoRestriction) *Restrictions { // A complex type that contains information about the Amazon S3 bucket from // which you want CloudFront to get your media files for distribution. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2016-11-25/S3Origin +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2017-03-25/S3Origin type S3Origin struct { _ struct{} `type:"structure"` @@ -8145,7 +8687,7 @@ func (s *S3Origin) SetOriginAccessIdentity(v string) *S3Origin { // A complex type that contains information about the Amazon S3 origin. If the // origin is a custom origin, use the CustomOriginConfig element instead. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2016-11-25/S3OriginConfig +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2017-03-25/S3OriginConfig type S3OriginConfig struct { _ struct{} `type:"structure"` @@ -8208,7 +8750,7 @@ func (s *S3OriginConfig) SetOriginAccessIdentity(v string) *S3OriginConfig { // A complex type that lists the AWS accounts that were included in the TrustedSigners // complex type, as well as their active CloudFront key pair IDs, if any. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2016-11-25/Signer +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2017-03-25/Signer type Signer struct { _ struct{} `type:"structure"` @@ -8248,7 +8790,7 @@ func (s *Signer) SetKeyPairIds(v *KeyPairIds) *Signer { } // A streaming distribution. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2016-11-25/StreamingDistribution +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2017-03-25/StreamingDistribution type StreamingDistribution struct { _ struct{} `type:"structure"` @@ -8350,7 +8892,7 @@ func (s *StreamingDistribution) SetStreamingDistributionConfig(v *StreamingDistr } // The RTMP distribution's configuration information. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2016-11-25/StreamingDistributionConfig +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2017-03-25/StreamingDistributionConfig type StreamingDistributionConfig struct { _ struct{} `type:"structure"` @@ -8513,7 +9055,7 @@ func (s *StreamingDistributionConfig) SetTrustedSigners(v *TrustedSigners) *Stre // A streaming distribution Configuration and a list of tags to be associated // with the streaming distribution. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2016-11-25/StreamingDistributionConfigWithTags +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2017-03-25/StreamingDistributionConfigWithTags type StreamingDistributionConfigWithTags struct { _ struct{} `type:"structure"` @@ -8577,7 +9119,7 @@ func (s *StreamingDistributionConfigWithTags) SetTags(v *Tags) *StreamingDistrib } // A streaming distribution list. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2016-11-25/StreamingDistributionList +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2017-03-25/StreamingDistributionList type StreamingDistributionList struct { _ struct{} `type:"structure"` @@ -8662,7 +9204,7 @@ func (s *StreamingDistributionList) SetQuantity(v int64) *StreamingDistributionL } // A summary of the information for an Amazon CloudFront streaming distribution. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2016-11-25/StreamingDistributionSummary +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2017-03-25/StreamingDistributionSummary type StreamingDistributionSummary struct { _ struct{} `type:"structure"` @@ -8813,7 +9355,7 @@ func (s *StreamingDistributionSummary) SetTrustedSigners(v *TrustedSigners) *Str // A complex type that controls whether access logs are written for this streaming // distribution. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2016-11-25/StreamingLoggingConfig +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2017-03-25/StreamingLoggingConfig type StreamingLoggingConfig struct { _ struct{} `type:"structure"` @@ -8889,7 +9431,7 @@ func (s *StreamingLoggingConfig) SetPrefix(v string) *StreamingLoggingConfig { } // A complex type that contains Tag key and Tag value. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2016-11-25/Tag +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2017-03-25/Tag type Tag struct { _ struct{} `type:"structure"` @@ -8947,7 +9489,7 @@ func (s *Tag) SetValue(v string) *Tag { } // A complex type that contains zero or more Tag elements. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2016-11-25/TagKeys +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2017-03-25/TagKeys type TagKeys struct { _ struct{} `type:"structure"` @@ -8972,7 +9514,7 @@ func (s *TagKeys) SetItems(v []*string) *TagKeys { } // The request to add tags to a CloudFront resource. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2016-11-25/TagResourceRequest +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2017-03-25/TagResourceRequest type TagResourceInput struct { _ struct{} `type:"structure" payload:"Tags"` @@ -9030,7 +9572,7 @@ func (s *TagResourceInput) SetTags(v *Tags) *TagResourceInput { return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2016-11-25/TagResourceOutput +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2017-03-25/TagResourceOutput type TagResourceOutput struct { _ struct{} `type:"structure"` } @@ -9046,7 +9588,7 @@ func (s TagResourceOutput) GoString() string { } // A complex type that contains zero or more Tag elements. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2016-11-25/Tags +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2017-03-25/Tags type Tags struct { _ struct{} `type:"structure"` @@ -9108,7 +9650,7 @@ func (s *Tags) SetItems(v []*Tag) *Tags { // // For more information about updating the distribution configuration, see DistributionConfig // . -// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2016-11-25/TrustedSigners +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2017-03-25/TrustedSigners type TrustedSigners struct { _ struct{} `type:"structure"` @@ -9173,7 +9715,7 @@ func (s *TrustedSigners) SetQuantity(v int64) *TrustedSigners { } // The request to remove tags from a CloudFront resource. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2016-11-25/UntagResourceRequest +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2017-03-25/UntagResourceRequest type UntagResourceInput struct { _ struct{} `type:"structure" payload:"TagKeys"` @@ -9226,7 +9768,7 @@ func (s *UntagResourceInput) SetTagKeys(v *TagKeys) *UntagResourceInput { return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2016-11-25/UntagResourceOutput +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2017-03-25/UntagResourceOutput type UntagResourceOutput struct { _ struct{} `type:"structure"` } @@ -9242,7 +9784,7 @@ func (s UntagResourceOutput) GoString() string { } // The request to update an origin access identity. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2016-11-25/UpdateCloudFrontOriginAccessIdentityRequest +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2017-03-25/UpdateCloudFrontOriginAccessIdentityRequest type UpdateCloudFrontOriginAccessIdentityInput struct { _ struct{} `type:"structure" payload:"CloudFrontOriginAccessIdentityConfig"` @@ -9311,7 +9853,7 @@ func (s *UpdateCloudFrontOriginAccessIdentityInput) SetIfMatch(v string) *Update } // The returned result of the corresponding request. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2016-11-25/UpdateCloudFrontOriginAccessIdentityResult +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2017-03-25/UpdateCloudFrontOriginAccessIdentityResult type UpdateCloudFrontOriginAccessIdentityOutput struct { _ struct{} `type:"structure" payload:"CloudFrontOriginAccessIdentity"` @@ -9345,7 +9887,7 @@ func (s *UpdateCloudFrontOriginAccessIdentityOutput) SetETag(v string) *UpdateCl } // The request to update a distribution. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2016-11-25/UpdateDistributionRequest +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2017-03-25/UpdateDistributionRequest type UpdateDistributionInput struct { _ struct{} `type:"structure" payload:"DistributionConfig"` @@ -9414,7 +9956,7 @@ func (s *UpdateDistributionInput) SetIfMatch(v string) *UpdateDistributionInput } // The returned result of the corresponding request. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2016-11-25/UpdateDistributionResult +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2017-03-25/UpdateDistributionResult type UpdateDistributionOutput struct { _ struct{} `type:"structure" payload:"Distribution"` @@ -9448,7 +9990,7 @@ func (s *UpdateDistributionOutput) SetETag(v string) *UpdateDistributionOutput { } // The request to update a streaming distribution. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2016-11-25/UpdateStreamingDistributionRequest +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2017-03-25/UpdateStreamingDistributionRequest type UpdateStreamingDistributionInput struct { _ struct{} `type:"structure" payload:"StreamingDistributionConfig"` @@ -9517,7 +10059,7 @@ func (s *UpdateStreamingDistributionInput) SetStreamingDistributionConfig(v *Str } // The returned result of the corresponding request. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2016-11-25/UpdateStreamingDistributionResult +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2017-03-25/UpdateStreamingDistributionResult type UpdateStreamingDistributionOutput struct { _ struct{} `type:"structure" payload:"StreamingDistribution"` @@ -9564,7 +10106,7 @@ func (s *UpdateStreamingDistributionOutput) SetStreamingDistribution(v *Streamin // For more information, see Using an HTTPS Connection to Access Your Objects // (http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/SecureConnections.html) // in the Amazon Amazon CloudFront Developer Guide. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2016-11-25/ViewerCertificate +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2017-03-25/ViewerCertificate type ViewerCertificate struct { _ struct{} `type:"structure"` @@ -9679,8 +10221,8 @@ type ViewerCertificate struct { // a method that works for all clients or one that works for most clients: // // * vip: CloudFront uses dedicated IP addresses for your content and can - // respond to HTTPS requests from any viewer. However, you must request permission - // to use this feature, and you incur additional monthly charges. + // respond to HTTPS requests from any viewer. However, you will incur additional + // monthly charges. // // * sni-only: CloudFront can respond to HTTPS requests from viewers that // support Server Name Indication (SNI). All modern browsers support SNI, diff --git a/vendor/github.com/aws/aws-sdk-go/service/cloudfront/doc.go b/vendor/github.com/aws/aws-sdk-go/service/cloudfront/doc.go new file mode 100644 index 000000000..0865a9097 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/service/cloudfront/doc.go @@ -0,0 +1,83 @@ +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. + +// Package cloudfront provides the client and types for making API +// requests to Amazon CloudFront. +// +// This is the Amazon CloudFront API Reference. This guide is for developers +// who need detailed information about the CloudFront API actions, data types, +// and errors. For detailed information about CloudFront features and their +// associated API calls, see the Amazon CloudFront Developer Guide. +// +// See https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2017-03-25 for more information on this service. +// +// See cloudfront package documentation for more information. +// https://docs.aws.amazon.com/sdk-for-go/api/service/cloudfront/ +// +// Using the Client +// +// To use the client for Amazon CloudFront you will first need +// to create a new instance of it. +// +// When creating a client for an AWS service you'll first need to have a Session +// already created. The Session provides configuration that can be shared +// between multiple service clients. Additional configuration can be applied to +// the Session and service's client when they are constructed. The aws package's +// Config type contains several fields such as Region for the AWS Region the +// client should make API requests too. The optional Config value can be provided +// as the variadic argument for Sessions and client creation. +// +// Once the service's client is created you can use it to make API requests the +// AWS service. These clients are safe to use concurrently. +// +// // Create a session to share configuration, and load external configuration. +// sess := session.Must(session.NewSession()) +// +// // Create the service's client with the session. +// svc := cloudfront.New(sess) +// +// See the SDK's documentation for more information on how to use service clients. +// https://docs.aws.amazon.com/sdk-for-go/api/ +// +// See aws package's Config type for more information on configuration options. +// https://docs.aws.amazon.com/sdk-for-go/api/aws/#Config +// +// See the Amazon CloudFront client CloudFront for more +// information on creating the service's client. +// https://docs.aws.amazon.com/sdk-for-go/api/service/cloudfront/#New +// +// Once the client is created you can make an API request to the service. +// Each API method takes a input parameter, and returns the service response +// and an error. +// +// The API method will document which error codes the service can be returned +// by the operation if the service models the API operation's errors. These +// errors will also be available as const strings prefixed with "ErrCode". +// +// result, err := svc.CreateCloudFrontOriginAccessIdentity(params) +// if err != nil { +// // Cast err to awserr.Error to handle specific error codes. +// aerr, ok := err.(awserr.Error) +// if ok && aerr.Code() == { +// // Specific error code handling +// } +// return err +// } +// +// fmt.Println("CreateCloudFrontOriginAccessIdentity result:") +// fmt.Println(result) +// +// Using the Client with Context +// +// The service's client also provides methods to make API requests with a Context +// value. This allows you to control the timeout, and cancellation of pending +// requests. These methods also take request Option as variadic parameter to apply +// additional configuration to the API request. +// +// ctx := context.Background() +// +// result, err := svc.CreateCloudFrontOriginAccessIdentityWithContext(ctx, params) +// +// See the request package documentation for more information on using Context pattern +// with the SDK. +// https://docs.aws.amazon.com/sdk-for-go/api/aws/request/ +package cloudfront diff --git a/vendor/github.com/aws/aws-sdk-go/service/cloudfront/errors.go b/vendor/github.com/aws/aws-sdk-go/service/cloudfront/errors.go index 072359c4c..2a38d5442 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/cloudfront/errors.go +++ b/vendor/github.com/aws/aws-sdk-go/service/cloudfront/errors.go @@ -1,4 +1,4 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. package cloudfront @@ -107,6 +107,14 @@ const ( // The origin access identity is not valid or doesn't exist. ErrCodeInvalidOriginAccessIdentity = "InvalidOriginAccessIdentity" + // ErrCodeInvalidOriginKeepaliveTimeout for service response error code + // "InvalidOriginKeepaliveTimeout". + ErrCodeInvalidOriginKeepaliveTimeout = "InvalidOriginKeepaliveTimeout" + + // ErrCodeInvalidOriginReadTimeout for service response error code + // "InvalidOriginReadTimeout". + ErrCodeInvalidOriginReadTimeout = "InvalidOriginReadTimeout" + // ErrCodeInvalidProtocolSettings for service response error code // "InvalidProtocolSettings". // diff --git a/vendor/github.com/aws/aws-sdk-go/service/cloudfront/service.go b/vendor/github.com/aws/aws-sdk-go/service/cloudfront/service.go index b815814e7..75dcf86e8 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/cloudfront/service.go +++ b/vendor/github.com/aws/aws-sdk-go/service/cloudfront/service.go @@ -1,4 +1,4 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. package cloudfront @@ -11,13 +11,12 @@ import ( "github.com/aws/aws-sdk-go/private/protocol/restxml" ) -// This is the Amazon CloudFront API Reference. This guide is for developers -// who need detailed information about the CloudFront API actions, data types, -// and errors. For detailed information about CloudFront features and their -// associated API calls, see the Amazon CloudFront Developer Guide. -// The service client's operations are safe to be used concurrently. -// It is not safe to mutate any of the client's properties though. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2016-11-25 +// CloudFront provides the API operation methods for making requests to +// Amazon CloudFront. See this package's package overview docs +// for details on the service. +// +// CloudFront methods are safe to use concurrently. It is not safe to +// modify mutate any of the struct's properties though. type CloudFront struct { *client.Client } @@ -59,7 +58,7 @@ func newClient(cfg aws.Config, handlers request.Handlers, endpoint, signingRegio SigningName: signingName, SigningRegion: signingRegion, Endpoint: endpoint, - APIVersion: "2016-11-25", + APIVersion: "2017-03-25", }, handlers, ), diff --git a/vendor/github.com/aws/aws-sdk-go/service/cloudfront/waiters.go b/vendor/github.com/aws/aws-sdk-go/service/cloudfront/waiters.go index c14e9d101..c8d4b14da 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/cloudfront/waiters.go +++ b/vendor/github.com/aws/aws-sdk-go/service/cloudfront/waiters.go @@ -1,9 +1,12 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. package cloudfront import ( - "github.com/aws/aws-sdk-go/private/waiter" + "time" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/request" ) // WaitUntilDistributionDeployed uses the CloudFront API operation @@ -11,26 +14,45 @@ import ( // If the condition is not meet within the max attempt window an error will // be returned. func (c *CloudFront) WaitUntilDistributionDeployed(input *GetDistributionInput) error { - waiterCfg := waiter.Config{ - Operation: "GetDistribution", - Delay: 60, + return c.WaitUntilDistributionDeployedWithContext(aws.BackgroundContext(), input) +} + +// WaitUntilDistributionDeployedWithContext is an extended version of WaitUntilDistributionDeployed. +// 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 *CloudFront) WaitUntilDistributionDeployedWithContext(ctx aws.Context, input *GetDistributionInput, opts ...request.WaiterOption) error { + w := request.Waiter{ + Name: "WaitUntilDistributionDeployed", MaxAttempts: 25, - Acceptors: []waiter.WaitAcceptor{ + Delay: request.ConstantWaiterDelay(60 * time.Second), + Acceptors: []request.WaiterAcceptor{ { - State: "success", - Matcher: "path", - Argument: "Distribution.Status", + State: request.SuccessWaiterState, + Matcher: request.PathWaiterMatch, Argument: "Distribution.Status", Expected: "Deployed", }, }, + Logger: c.Config.Logger, + NewRequest: func(opts []request.Option) (*request.Request, error) { + var inCpy *GetDistributionInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.GetDistributionRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, } + w.ApplyOptions(opts...) - w := waiter.Waiter{ - Client: c, - Input: input, - Config: waiterCfg, - } - return w.Wait() + return w.WaitWithContext(ctx) } // WaitUntilInvalidationCompleted uses the CloudFront API operation @@ -38,26 +60,45 @@ func (c *CloudFront) WaitUntilDistributionDeployed(input *GetDistributionInput) // If the condition is not meet within the max attempt window an error will // be returned. func (c *CloudFront) WaitUntilInvalidationCompleted(input *GetInvalidationInput) error { - waiterCfg := waiter.Config{ - Operation: "GetInvalidation", - Delay: 20, + return c.WaitUntilInvalidationCompletedWithContext(aws.BackgroundContext(), input) +} + +// WaitUntilInvalidationCompletedWithContext is an extended version of WaitUntilInvalidationCompleted. +// 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 *CloudFront) WaitUntilInvalidationCompletedWithContext(ctx aws.Context, input *GetInvalidationInput, opts ...request.WaiterOption) error { + w := request.Waiter{ + Name: "WaitUntilInvalidationCompleted", MaxAttempts: 30, - Acceptors: []waiter.WaitAcceptor{ + Delay: request.ConstantWaiterDelay(20 * time.Second), + Acceptors: []request.WaiterAcceptor{ { - State: "success", - Matcher: "path", - Argument: "Invalidation.Status", + State: request.SuccessWaiterState, + Matcher: request.PathWaiterMatch, Argument: "Invalidation.Status", Expected: "Completed", }, }, + Logger: c.Config.Logger, + NewRequest: func(opts []request.Option) (*request.Request, error) { + var inCpy *GetInvalidationInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.GetInvalidationRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, } + w.ApplyOptions(opts...) - w := waiter.Waiter{ - Client: c, - Input: input, - Config: waiterCfg, - } - return w.Wait() + return w.WaitWithContext(ctx) } // WaitUntilStreamingDistributionDeployed uses the CloudFront API operation @@ -65,24 +106,43 @@ func (c *CloudFront) WaitUntilInvalidationCompleted(input *GetInvalidationInput) // If the condition is not meet within the max attempt window an error will // be returned. func (c *CloudFront) WaitUntilStreamingDistributionDeployed(input *GetStreamingDistributionInput) error { - waiterCfg := waiter.Config{ - Operation: "GetStreamingDistribution", - Delay: 60, + return c.WaitUntilStreamingDistributionDeployedWithContext(aws.BackgroundContext(), input) +} + +// WaitUntilStreamingDistributionDeployedWithContext is an extended version of WaitUntilStreamingDistributionDeployed. +// 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 *CloudFront) WaitUntilStreamingDistributionDeployedWithContext(ctx aws.Context, input *GetStreamingDistributionInput, opts ...request.WaiterOption) error { + w := request.Waiter{ + Name: "WaitUntilStreamingDistributionDeployed", MaxAttempts: 25, - Acceptors: []waiter.WaitAcceptor{ + Delay: request.ConstantWaiterDelay(60 * time.Second), + Acceptors: []request.WaiterAcceptor{ { - State: "success", - Matcher: "path", - Argument: "StreamingDistribution.Status", + State: request.SuccessWaiterState, + Matcher: request.PathWaiterMatch, Argument: "StreamingDistribution.Status", Expected: "Deployed", }, }, + Logger: c.Config.Logger, + NewRequest: func(opts []request.Option) (*request.Request, error) { + var inCpy *GetStreamingDistributionInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.GetStreamingDistributionRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, } + w.ApplyOptions(opts...) - w := waiter.Waiter{ - Client: c, - Input: input, - Config: waiterCfg, - } - return w.Wait() + return w.WaitWithContext(ctx) } diff --git a/vendor/github.com/aws/aws-sdk-go/service/cloudtrail/api.go b/vendor/github.com/aws/aws-sdk-go/service/cloudtrail/api.go index f3ada2c13..cbc83bae0 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/cloudtrail/api.go +++ b/vendor/github.com/aws/aws-sdk-go/service/cloudtrail/api.go @@ -1,12 +1,12 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. -// Package cloudtrail provides a client for AWS CloudTrail. package cloudtrail import ( "fmt" "time" + "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awsutil" "github.com/aws/aws-sdk-go/aws/request" ) @@ -117,8 +117,23 @@ func (c *CloudTrail) AddTagsRequest(input *AddTagsInput) (req *request.Request, // Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudtrail-2013-11-01/AddTags func (c *CloudTrail) AddTags(input *AddTagsInput) (*AddTagsOutput, error) { req, out := c.AddTagsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// AddTagsWithContext is the same as AddTags with the addition of +// the ability to pass a context and additional request options. +// +// See AddTags 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 *CloudTrail) AddTagsWithContext(ctx aws.Context, input *AddTagsInput, opts ...request.Option) (*AddTagsOutput, error) { + req, out := c.AddTagsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateTrail = "CreateTrail" @@ -261,8 +276,23 @@ func (c *CloudTrail) CreateTrailRequest(input *CreateTrailInput) (req *request.R // Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudtrail-2013-11-01/CreateTrail func (c *CloudTrail) CreateTrail(input *CreateTrailInput) (*CreateTrailOutput, error) { req, out := c.CreateTrailRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateTrailWithContext is the same as CreateTrail with the addition of +// the ability to pass a context and additional request options. +// +// See CreateTrail 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 *CloudTrail) CreateTrailWithContext(ctx aws.Context, input *CreateTrailInput, opts ...request.Option) (*CreateTrailOutput, error) { + req, out := c.CreateTrailRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteTrail = "DeleteTrail" @@ -348,8 +378,23 @@ func (c *CloudTrail) DeleteTrailRequest(input *DeleteTrailInput) (req *request.R // Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudtrail-2013-11-01/DeleteTrail func (c *CloudTrail) DeleteTrail(input *DeleteTrailInput) (*DeleteTrailOutput, error) { req, out := c.DeleteTrailRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteTrailWithContext is the same as DeleteTrail with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteTrail 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 *CloudTrail) DeleteTrailWithContext(ctx aws.Context, input *DeleteTrailInput, opts ...request.Option) (*DeleteTrailOutput, error) { + req, out := c.DeleteTrailRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeTrails = "DescribeTrails" @@ -417,8 +462,23 @@ func (c *CloudTrail) DescribeTrailsRequest(input *DescribeTrailsInput) (req *req // Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudtrail-2013-11-01/DescribeTrails func (c *CloudTrail) DescribeTrails(input *DescribeTrailsInput) (*DescribeTrailsOutput, error) { req, out := c.DescribeTrailsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeTrailsWithContext is the same as DescribeTrails with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeTrails 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 *CloudTrail) DescribeTrailsWithContext(ctx aws.Context, input *DescribeTrailsInput, opts ...request.Option) (*DescribeTrailsOutput, error) { + req, out := c.DescribeTrailsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetEventSelectors = "GetEventSelectors" @@ -516,8 +576,23 @@ func (c *CloudTrail) GetEventSelectorsRequest(input *GetEventSelectorsInput) (re // Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudtrail-2013-11-01/GetEventSelectors func (c *CloudTrail) GetEventSelectors(input *GetEventSelectorsInput) (*GetEventSelectorsOutput, error) { req, out := c.GetEventSelectorsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetEventSelectorsWithContext is the same as GetEventSelectors with the addition of +// the ability to pass a context and additional request options. +// +// See GetEventSelectors 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 *CloudTrail) GetEventSelectorsWithContext(ctx aws.Context, input *GetEventSelectorsInput, opts ...request.Option) (*GetEventSelectorsOutput, error) { + req, out := c.GetEventSelectorsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetTrailStatus = "GetTrailStatus" @@ -601,8 +676,23 @@ func (c *CloudTrail) GetTrailStatusRequest(input *GetTrailStatusInput) (req *req // Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudtrail-2013-11-01/GetTrailStatus func (c *CloudTrail) GetTrailStatus(input *GetTrailStatusInput) (*GetTrailStatusOutput, error) { req, out := c.GetTrailStatusRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetTrailStatusWithContext is the same as GetTrailStatus with the addition of +// the ability to pass a context and additional request options. +// +// See GetTrailStatus 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 *CloudTrail) GetTrailStatusWithContext(ctx aws.Context, input *GetTrailStatusInput, opts ...request.Option) (*GetTrailStatusOutput, error) { + req, out := c.GetTrailStatusRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opListPublicKeys = "ListPublicKeys" @@ -683,8 +773,23 @@ func (c *CloudTrail) ListPublicKeysRequest(input *ListPublicKeysInput) (req *req // Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudtrail-2013-11-01/ListPublicKeys func (c *CloudTrail) ListPublicKeys(input *ListPublicKeysInput) (*ListPublicKeysOutput, error) { req, out := c.ListPublicKeysRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListPublicKeysWithContext is the same as ListPublicKeys with the addition of +// the ability to pass a context and additional request options. +// +// See ListPublicKeys 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 *CloudTrail) ListPublicKeysWithContext(ctx aws.Context, input *ListPublicKeysInput, opts ...request.Option) (*ListPublicKeysOutput, error) { + req, out := c.ListPublicKeysRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opListTags = "ListTags" @@ -783,8 +888,23 @@ func (c *CloudTrail) ListTagsRequest(input *ListTagsInput) (req *request.Request // Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudtrail-2013-11-01/ListTags func (c *CloudTrail) ListTags(input *ListTagsInput) (*ListTagsOutput, error) { req, out := c.ListTagsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListTagsWithContext is the same as ListTags with the addition of +// the ability to pass a context and additional request options. +// +// See ListTags 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 *CloudTrail) ListTagsWithContext(ctx aws.Context, input *ListTagsInput, opts ...request.Option) (*ListTagsOutput, error) { + req, out := c.ListTagsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opLookupEvents = "LookupEvents" @@ -890,8 +1010,23 @@ func (c *CloudTrail) LookupEventsRequest(input *LookupEventsInput) (req *request // Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudtrail-2013-11-01/LookupEvents func (c *CloudTrail) LookupEvents(input *LookupEventsInput) (*LookupEventsOutput, error) { req, out := c.LookupEventsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// LookupEventsWithContext is the same as LookupEvents with the addition of +// the ability to pass a context and additional request options. +// +// See LookupEvents 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 *CloudTrail) LookupEventsWithContext(ctx aws.Context, input *LookupEventsInput, opts ...request.Option) (*LookupEventsOutput, error) { + req, out := c.LookupEventsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // LookupEventsPages iterates over the pages of a LookupEvents operation, @@ -911,12 +1046,37 @@ func (c *CloudTrail) LookupEvents(input *LookupEventsInput) (*LookupEventsOutput // return pageNum <= 3 // }) // -func (c *CloudTrail) LookupEventsPages(input *LookupEventsInput, fn func(p *LookupEventsOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.LookupEventsRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*LookupEventsOutput), lastPage) - }) +func (c *CloudTrail) LookupEventsPages(input *LookupEventsInput, fn func(*LookupEventsOutput, bool) bool) error { + return c.LookupEventsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// LookupEventsPagesWithContext same as LookupEventsPages 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 *CloudTrail) LookupEventsPagesWithContext(ctx aws.Context, input *LookupEventsInput, fn func(*LookupEventsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *LookupEventsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.LookupEventsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*LookupEventsOutput), !p.HasNextPage()) + } + return p.Err() } const opPutEventSelectors = "PutEventSelectors" @@ -1045,8 +1205,23 @@ func (c *CloudTrail) PutEventSelectorsRequest(input *PutEventSelectorsInput) (re // Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudtrail-2013-11-01/PutEventSelectors func (c *CloudTrail) PutEventSelectors(input *PutEventSelectorsInput) (*PutEventSelectorsOutput, error) { req, out := c.PutEventSelectorsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// PutEventSelectorsWithContext is the same as PutEventSelectors with the addition of +// the ability to pass a context and additional request options. +// +// See PutEventSelectors 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 *CloudTrail) PutEventSelectorsWithContext(ctx aws.Context, input *PutEventSelectorsInput, opts ...request.Option) (*PutEventSelectorsOutput, error) { + req, out := c.PutEventSelectorsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opRemoveTags = "RemoveTags" @@ -1146,8 +1321,23 @@ func (c *CloudTrail) RemoveTagsRequest(input *RemoveTagsInput) (req *request.Req // Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudtrail-2013-11-01/RemoveTags func (c *CloudTrail) RemoveTags(input *RemoveTagsInput) (*RemoveTagsOutput, error) { req, out := c.RemoveTagsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// RemoveTagsWithContext is the same as RemoveTags with the addition of +// the ability to pass a context and additional request options. +// +// See RemoveTags 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 *CloudTrail) RemoveTagsWithContext(ctx aws.Context, input *RemoveTagsInput, opts ...request.Option) (*RemoveTagsOutput, error) { + req, out := c.RemoveTagsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opStartLogging = "StartLogging" @@ -1235,8 +1425,23 @@ func (c *CloudTrail) StartLoggingRequest(input *StartLoggingInput) (req *request // Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudtrail-2013-11-01/StartLogging func (c *CloudTrail) StartLogging(input *StartLoggingInput) (*StartLoggingOutput, error) { req, out := c.StartLoggingRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// StartLoggingWithContext is the same as StartLogging with the addition of +// the ability to pass a context and additional request options. +// +// See StartLogging 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 *CloudTrail) StartLoggingWithContext(ctx aws.Context, input *StartLoggingInput, opts ...request.Option) (*StartLoggingOutput, error) { + req, out := c.StartLoggingRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opStopLogging = "StopLogging" @@ -1326,8 +1531,23 @@ func (c *CloudTrail) StopLoggingRequest(input *StopLoggingInput) (req *request.R // Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudtrail-2013-11-01/StopLogging func (c *CloudTrail) StopLogging(input *StopLoggingInput) (*StopLoggingOutput, error) { req, out := c.StopLoggingRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// StopLoggingWithContext is the same as StopLogging with the addition of +// the ability to pass a context and additional request options. +// +// See StopLogging 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 *CloudTrail) StopLoggingWithContext(ctx aws.Context, input *StopLoggingInput, opts ...request.Option) (*StopLoggingOutput, error) { + req, out := c.StopLoggingRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opUpdateTrail = "UpdateTrail" @@ -1474,8 +1694,23 @@ func (c *CloudTrail) UpdateTrailRequest(input *UpdateTrailInput) (req *request.R // Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudtrail-2013-11-01/UpdateTrail func (c *CloudTrail) UpdateTrail(input *UpdateTrailInput) (*UpdateTrailOutput, error) { req, out := c.UpdateTrailRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// UpdateTrailWithContext is the same as UpdateTrail with the addition of +// the ability to pass a context and additional request options. +// +// See UpdateTrail 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 *CloudTrail) UpdateTrailWithContext(ctx aws.Context, input *UpdateTrailInput, opts ...request.Option) (*UpdateTrailOutput, error) { + req, out := c.UpdateTrailRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // Specifies the tags to add to a trail. @@ -2232,7 +2467,9 @@ type GetEventSelectorsInput struct { // If you specify a trail ARN, it must be in the format: // // arn:aws:cloudtrail:us-east-1:123456789012:trail/MyTrail - TrailName *string `type:"string"` + // + // TrailName is a required field + TrailName *string `type:"string" required:"true"` } // String returns the string representation @@ -2245,6 +2482,19 @@ func (s GetEventSelectorsInput) GoString() string { return s.String() } +// Validate inspects the fields of the type to determine if they are valid. +func (s *GetEventSelectorsInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "GetEventSelectorsInput"} + if s.TrailName == nil { + invalidParams.Add(request.NewErrParamRequired("TrailName")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + // SetTrailName sets the TrailName field's value. func (s *GetEventSelectorsInput) SetTrailName(v string) *GetEventSelectorsInput { s.TrailName = &v @@ -2941,7 +3191,9 @@ type PutEventSelectorsInput struct { // Specifies the settings for your event selectors. You can configure up to // five event selectors for a trail. - EventSelectors []*EventSelector `type:"list"` + // + // EventSelectors is a required field + EventSelectors []*EventSelector `type:"list" required:"true"` // Specifies the name of the trail or trail ARN. If you specify a trail name, // the string must meet the following requirements: @@ -2961,7 +3213,9 @@ type PutEventSelectorsInput struct { // If you specify a trail ARN, it must be in the format: // // arn:aws:cloudtrail:us-east-1:123456789012:trail/MyTrail - TrailName *string `type:"string"` + // + // TrailName is a required field + TrailName *string `type:"string" required:"true"` } // String returns the string representation @@ -2974,6 +3228,22 @@ func (s PutEventSelectorsInput) GoString() string { return s.String() } +// Validate inspects the fields of the type to determine if they are valid. +func (s *PutEventSelectorsInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "PutEventSelectorsInput"} + if s.EventSelectors == nil { + invalidParams.Add(request.NewErrParamRequired("EventSelectors")) + } + if s.TrailName == nil { + invalidParams.Add(request.NewErrParamRequired("TrailName")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + // SetEventSelectors sets the EventSelectors field's value. func (s *PutEventSelectorsInput) SetEventSelectors(v []*EventSelector) *PutEventSelectorsInput { s.EventSelectors = v diff --git a/vendor/github.com/aws/aws-sdk-go/service/cloudtrail/doc.go b/vendor/github.com/aws/aws-sdk-go/service/cloudtrail/doc.go new file mode 100644 index 000000000..0f25c8b7a --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/service/cloudtrail/doc.go @@ -0,0 +1,100 @@ +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. + +// Package cloudtrail provides the client and types for making API +// requests to AWS CloudTrail. +// +// This is the CloudTrail API Reference. It provides descriptions of actions, +// data types, common parameters, and common errors for CloudTrail. +// +// CloudTrail is a web service that records AWS API calls for your AWS account +// and delivers log files to an Amazon S3 bucket. The recorded information includes +// the identity of the user, the start time of the AWS API call, the source +// IP address, the request parameters, and the response elements returned by +// the service. +// +// As an alternative to the API, you can use one of the AWS SDKs, which 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 AWSCloudTrail. For example, the SDKs take +// care of cryptographically signing requests, 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 page +// (http://aws.amazon.com/tools/). +// +// See the AWS CloudTrail User Guide (http://docs.aws.amazon.com/awscloudtrail/latest/userguide/cloudtrail-user-guide.html) +// for information about the data that is included with each AWS API call listed +// in the log files. +// +// See https://docs.aws.amazon.com/goto/WebAPI/cloudtrail-2013-11-01 for more information on this service. +// +// See cloudtrail package documentation for more information. +// https://docs.aws.amazon.com/sdk-for-go/api/service/cloudtrail/ +// +// Using the Client +// +// To use the client for AWS CloudTrail you will first need +// to create a new instance of it. +// +// When creating a client for an AWS service you'll first need to have a Session +// already created. The Session provides configuration that can be shared +// between multiple service clients. Additional configuration can be applied to +// the Session and service's client when they are constructed. The aws package's +// Config type contains several fields such as Region for the AWS Region the +// client should make API requests too. The optional Config value can be provided +// as the variadic argument for Sessions and client creation. +// +// Once the service's client is created you can use it to make API requests the +// AWS service. These clients are safe to use concurrently. +// +// // Create a session to share configuration, and load external configuration. +// sess := session.Must(session.NewSession()) +// +// // Create the service's client with the session. +// svc := cloudtrail.New(sess) +// +// See the SDK's documentation for more information on how to use service clients. +// https://docs.aws.amazon.com/sdk-for-go/api/ +// +// See aws package's Config type for more information on configuration options. +// https://docs.aws.amazon.com/sdk-for-go/api/aws/#Config +// +// See the AWS CloudTrail client CloudTrail for more +// information on creating the service's client. +// https://docs.aws.amazon.com/sdk-for-go/api/service/cloudtrail/#New +// +// Once the client is created you can make an API request to the service. +// Each API method takes a input parameter, and returns the service response +// and an error. +// +// The API method will document which error codes the service can be returned +// by the operation if the service models the API operation's errors. These +// errors will also be available as const strings prefixed with "ErrCode". +// +// result, err := svc.AddTags(params) +// if err != nil { +// // Cast err to awserr.Error to handle specific error codes. +// aerr, ok := err.(awserr.Error) +// if ok && aerr.Code() == { +// // Specific error code handling +// } +// return err +// } +// +// fmt.Println("AddTags result:") +// fmt.Println(result) +// +// Using the Client with Context +// +// The service's client also provides methods to make API requests with a Context +// value. This allows you to control the timeout, and cancellation of pending +// requests. These methods also take request Option as variadic parameter to apply +// additional configuration to the API request. +// +// ctx := context.Background() +// +// result, err := svc.AddTagsWithContext(ctx, params) +// +// See the request package documentation for more information on using Context pattern +// with the SDK. +// https://docs.aws.amazon.com/sdk-for-go/api/aws/request/ +package cloudtrail diff --git a/vendor/github.com/aws/aws-sdk-go/service/cloudtrail/errors.go b/vendor/github.com/aws/aws-sdk-go/service/cloudtrail/errors.go index 14e12f428..0da999b33 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/cloudtrail/errors.go +++ b/vendor/github.com/aws/aws-sdk-go/service/cloudtrail/errors.go @@ -1,4 +1,4 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. package cloudtrail diff --git a/vendor/github.com/aws/aws-sdk-go/service/cloudtrail/service.go b/vendor/github.com/aws/aws-sdk-go/service/cloudtrail/service.go index f5fcb38c2..49198fc63 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/cloudtrail/service.go +++ b/vendor/github.com/aws/aws-sdk-go/service/cloudtrail/service.go @@ -1,4 +1,4 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. package cloudtrail @@ -11,30 +11,12 @@ import ( "github.com/aws/aws-sdk-go/private/protocol/jsonrpc" ) -// This is the CloudTrail API Reference. It provides descriptions of actions, -// data types, common parameters, and common errors for CloudTrail. +// CloudTrail provides the API operation methods for making requests to +// AWS CloudTrail. See this package's package overview docs +// for details on the service. // -// CloudTrail is a web service that records AWS API calls for your AWS account -// and delivers log files to an Amazon S3 bucket. The recorded information includes -// the identity of the user, the start time of the AWS API call, the source -// IP address, the request parameters, and the response elements returned by -// the service. -// -// As an alternative to the API, you can use one of the AWS SDKs, which 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 AWSCloudTrail. For example, the SDKs take -// care of cryptographically signing requests, 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 page -// (http://aws.amazon.com/tools/). -// -// See the AWS CloudTrail User Guide (http://docs.aws.amazon.com/awscloudtrail/latest/userguide/cloudtrail-user-guide.html) -// for information about the data that is included with each AWS API call listed -// in the log files. -// The service client's operations are safe to be used concurrently. -// It is not safe to mutate any of the client's properties though. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudtrail-2013-11-01 +// CloudTrail methods are safe to use concurrently. It is not safe to +// modify mutate any of the struct's properties though. type CloudTrail struct { *client.Client } diff --git a/vendor/github.com/aws/aws-sdk-go/service/cloudwatch/api.go b/vendor/github.com/aws/aws-sdk-go/service/cloudwatch/api.go index 3abedb2ce..41b8696ef 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/cloudwatch/api.go +++ b/vendor/github.com/aws/aws-sdk-go/service/cloudwatch/api.go @@ -1,12 +1,12 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. -// Package cloudwatch provides a client for Amazon CloudWatch. package cloudwatch import ( "fmt" "time" + "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awsutil" "github.com/aws/aws-sdk-go/aws/request" "github.com/aws/aws-sdk-go/private/protocol" @@ -76,8 +76,23 @@ func (c *CloudWatch) DeleteAlarmsRequest(input *DeleteAlarmsInput) (req *request // Please also see https://docs.aws.amazon.com/goto/WebAPI/monitoring-2010-08-01/DeleteAlarms func (c *CloudWatch) DeleteAlarms(input *DeleteAlarmsInput) (*DeleteAlarmsOutput, error) { req, out := c.DeleteAlarmsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteAlarmsWithContext is the same as DeleteAlarms with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteAlarms 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 *CloudWatch) DeleteAlarmsWithContext(ctx aws.Context, input *DeleteAlarmsInput, opts ...request.Option) (*DeleteAlarmsOutput, error) { + req, out := c.DeleteAlarmsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeAlarmHistory = "DescribeAlarmHistory" @@ -152,8 +167,23 @@ func (c *CloudWatch) DescribeAlarmHistoryRequest(input *DescribeAlarmHistoryInpu // Please also see https://docs.aws.amazon.com/goto/WebAPI/monitoring-2010-08-01/DescribeAlarmHistory func (c *CloudWatch) DescribeAlarmHistory(input *DescribeAlarmHistoryInput) (*DescribeAlarmHistoryOutput, error) { req, out := c.DescribeAlarmHistoryRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeAlarmHistoryWithContext is the same as DescribeAlarmHistory with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeAlarmHistory 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 *CloudWatch) DescribeAlarmHistoryWithContext(ctx aws.Context, input *DescribeAlarmHistoryInput, opts ...request.Option) (*DescribeAlarmHistoryOutput, error) { + req, out := c.DescribeAlarmHistoryRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // DescribeAlarmHistoryPages iterates over the pages of a DescribeAlarmHistory operation, @@ -173,12 +203,37 @@ func (c *CloudWatch) DescribeAlarmHistory(input *DescribeAlarmHistoryInput) (*De // return pageNum <= 3 // }) // -func (c *CloudWatch) DescribeAlarmHistoryPages(input *DescribeAlarmHistoryInput, fn func(p *DescribeAlarmHistoryOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.DescribeAlarmHistoryRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*DescribeAlarmHistoryOutput), lastPage) - }) +func (c *CloudWatch) DescribeAlarmHistoryPages(input *DescribeAlarmHistoryInput, fn func(*DescribeAlarmHistoryOutput, bool) bool) error { + return c.DescribeAlarmHistoryPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// DescribeAlarmHistoryPagesWithContext same as DescribeAlarmHistoryPages 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 *CloudWatch) DescribeAlarmHistoryPagesWithContext(ctx aws.Context, input *DescribeAlarmHistoryInput, fn func(*DescribeAlarmHistoryOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *DescribeAlarmHistoryInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeAlarmHistoryRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*DescribeAlarmHistoryOutput), !p.HasNextPage()) + } + return p.Err() } const opDescribeAlarms = "DescribeAlarms" @@ -250,8 +305,23 @@ func (c *CloudWatch) DescribeAlarmsRequest(input *DescribeAlarmsInput) (req *req // Please also see https://docs.aws.amazon.com/goto/WebAPI/monitoring-2010-08-01/DescribeAlarms func (c *CloudWatch) DescribeAlarms(input *DescribeAlarmsInput) (*DescribeAlarmsOutput, error) { req, out := c.DescribeAlarmsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeAlarmsWithContext is the same as DescribeAlarms with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeAlarms 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 *CloudWatch) DescribeAlarmsWithContext(ctx aws.Context, input *DescribeAlarmsInput, opts ...request.Option) (*DescribeAlarmsOutput, error) { + req, out := c.DescribeAlarmsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // DescribeAlarmsPages iterates over the pages of a DescribeAlarms operation, @@ -271,12 +341,37 @@ func (c *CloudWatch) DescribeAlarms(input *DescribeAlarmsInput) (*DescribeAlarms // return pageNum <= 3 // }) // -func (c *CloudWatch) DescribeAlarmsPages(input *DescribeAlarmsInput, fn func(p *DescribeAlarmsOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.DescribeAlarmsRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*DescribeAlarmsOutput), lastPage) - }) +func (c *CloudWatch) DescribeAlarmsPages(input *DescribeAlarmsInput, fn func(*DescribeAlarmsOutput, bool) bool) error { + return c.DescribeAlarmsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// DescribeAlarmsPagesWithContext same as DescribeAlarmsPages 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 *CloudWatch) DescribeAlarmsPagesWithContext(ctx aws.Context, input *DescribeAlarmsInput, fn func(*DescribeAlarmsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *DescribeAlarmsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeAlarmsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*DescribeAlarmsOutput), !p.HasNextPage()) + } + return p.Err() } const opDescribeAlarmsForMetric = "DescribeAlarmsForMetric" @@ -336,8 +431,23 @@ func (c *CloudWatch) DescribeAlarmsForMetricRequest(input *DescribeAlarmsForMetr // Please also see https://docs.aws.amazon.com/goto/WebAPI/monitoring-2010-08-01/DescribeAlarmsForMetric func (c *CloudWatch) DescribeAlarmsForMetric(input *DescribeAlarmsForMetricInput) (*DescribeAlarmsForMetricOutput, error) { req, out := c.DescribeAlarmsForMetricRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeAlarmsForMetricWithContext is the same as DescribeAlarmsForMetric with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeAlarmsForMetric 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 *CloudWatch) DescribeAlarmsForMetricWithContext(ctx aws.Context, input *DescribeAlarmsForMetricInput, opts ...request.Option) (*DescribeAlarmsForMetricOutput, error) { + req, out := c.DescribeAlarmsForMetricRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDisableAlarmActions = "DisableAlarmActions" @@ -399,8 +509,23 @@ func (c *CloudWatch) DisableAlarmActionsRequest(input *DisableAlarmActionsInput) // Please also see https://docs.aws.amazon.com/goto/WebAPI/monitoring-2010-08-01/DisableAlarmActions func (c *CloudWatch) DisableAlarmActions(input *DisableAlarmActionsInput) (*DisableAlarmActionsOutput, error) { req, out := c.DisableAlarmActionsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DisableAlarmActionsWithContext is the same as DisableAlarmActions with the addition of +// the ability to pass a context and additional request options. +// +// See DisableAlarmActions 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 *CloudWatch) DisableAlarmActionsWithContext(ctx aws.Context, input *DisableAlarmActionsInput, opts ...request.Option) (*DisableAlarmActionsOutput, error) { + req, out := c.DisableAlarmActionsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opEnableAlarmActions = "EnableAlarmActions" @@ -461,8 +586,23 @@ func (c *CloudWatch) EnableAlarmActionsRequest(input *EnableAlarmActionsInput) ( // Please also see https://docs.aws.amazon.com/goto/WebAPI/monitoring-2010-08-01/EnableAlarmActions func (c *CloudWatch) EnableAlarmActions(input *EnableAlarmActionsInput) (*EnableAlarmActionsOutput, error) { req, out := c.EnableAlarmActionsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// EnableAlarmActionsWithContext is the same as EnableAlarmActions with the addition of +// the ability to pass a context and additional request options. +// +// See EnableAlarmActions 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 *CloudWatch) EnableAlarmActionsWithContext(ctx aws.Context, input *EnableAlarmActionsInput, opts ...request.Option) (*EnableAlarmActionsOutput, error) { + req, out := c.EnableAlarmActionsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetMetricStatistics = "GetMetricStatistics" @@ -539,6 +679,14 @@ func (c *CloudWatch) GetMetricStatisticsRequest(input *GetMetricStatisticsInput) // fall within each one-hour period. Therefore, the number of values aggregated // by CloudWatch is larger than the number of data points returned. // +// CloudWatch needs raw data points to calculate percentile statistics. If you +// publish data using a statistic set instead, you cannot retrieve percentile +// statistics for this data unless one of the following conditions is true: +// +// * The SampleCount of the statistic set is 1 +// +// * The Min and the Max of the statistic set are equal +// // For a list of metrics and dimensions supported by AWS services, see the Amazon // CloudWatch Metrics and Dimensions Reference (http://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CW_Support_For_AWS.html) // in the Amazon CloudWatch User Guide. @@ -566,8 +714,23 @@ func (c *CloudWatch) GetMetricStatisticsRequest(input *GetMetricStatisticsInput) // Please also see https://docs.aws.amazon.com/goto/WebAPI/monitoring-2010-08-01/GetMetricStatistics func (c *CloudWatch) GetMetricStatistics(input *GetMetricStatisticsInput) (*GetMetricStatisticsOutput, error) { req, out := c.GetMetricStatisticsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetMetricStatisticsWithContext is the same as GetMetricStatistics with the addition of +// the ability to pass a context and additional request options. +// +// See GetMetricStatistics 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 *CloudWatch) GetMetricStatisticsWithContext(ctx aws.Context, input *GetMetricStatisticsInput, opts ...request.Option) (*GetMetricStatisticsOutput, error) { + req, out := c.GetMetricStatisticsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opListMetrics = "ListMetrics" @@ -648,8 +811,23 @@ func (c *CloudWatch) ListMetricsRequest(input *ListMetricsInput) (req *request.R // Please also see https://docs.aws.amazon.com/goto/WebAPI/monitoring-2010-08-01/ListMetrics func (c *CloudWatch) ListMetrics(input *ListMetricsInput) (*ListMetricsOutput, error) { req, out := c.ListMetricsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListMetricsWithContext is the same as ListMetrics with the addition of +// the ability to pass a context and additional request options. +// +// See ListMetrics 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 *CloudWatch) ListMetricsWithContext(ctx aws.Context, input *ListMetricsInput, opts ...request.Option) (*ListMetricsOutput, error) { + req, out := c.ListMetricsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // ListMetricsPages iterates over the pages of a ListMetrics operation, @@ -669,12 +847,37 @@ func (c *CloudWatch) ListMetrics(input *ListMetricsInput) (*ListMetricsOutput, e // return pageNum <= 3 // }) // -func (c *CloudWatch) ListMetricsPages(input *ListMetricsInput, fn func(p *ListMetricsOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.ListMetricsRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*ListMetricsOutput), lastPage) - }) +func (c *CloudWatch) ListMetricsPages(input *ListMetricsInput, fn func(*ListMetricsOutput, bool) bool) error { + return c.ListMetricsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListMetricsPagesWithContext same as ListMetricsPages 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 *CloudWatch) ListMetricsPagesWithContext(ctx aws.Context, input *ListMetricsInput, fn func(*ListMetricsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListMetricsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListMetricsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*ListMetricsOutput), !p.HasNextPage()) + } + return p.Err() } const opPutMetricAlarm = "PutMetricAlarm" @@ -781,8 +984,23 @@ func (c *CloudWatch) PutMetricAlarmRequest(input *PutMetricAlarmInput) (req *req // Please also see https://docs.aws.amazon.com/goto/WebAPI/monitoring-2010-08-01/PutMetricAlarm func (c *CloudWatch) PutMetricAlarm(input *PutMetricAlarmInput) (*PutMetricAlarmOutput, error) { req, out := c.PutMetricAlarmRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// PutMetricAlarmWithContext is the same as PutMetricAlarm with the addition of +// the ability to pass a context and additional request options. +// +// See PutMetricAlarm 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 *CloudWatch) PutMetricAlarmWithContext(ctx aws.Context, input *PutMetricAlarmInput, opts ...request.Option) (*PutMetricAlarmOutput, error) { + req, out := c.PutMetricAlarmRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opPutMetricData = "PutMetricData" @@ -838,8 +1056,7 @@ func (c *CloudWatch) PutMetricDataRequest(input *PutMetricDataInput) (req *reque // a metric, it can take up to fifteen minutes for the metric to appear in calls // to ListMetrics. // -// Each PutMetricData request is limited to 8 KB in size for HTTP GET requests -// and is limited to 40 KB in size for HTTP POST requests. +// Each PutMetricData request is limited to 40 KB in size for HTTP POST requests. // // Although the Value parameter accepts numbers of type Double, Amazon CloudWatch // rejects values that are either too small or too large. Values must be in @@ -847,10 +1064,23 @@ func (c *CloudWatch) PutMetricDataRequest(input *PutMetricDataInput) (req *reque // (Base 2). In addition, special values (e.g., NaN, +Infinity, -Infinity) are // not supported. // +// You can use up to 10 dimensions per metric to further clarify what data the +// metric collects. For more information on specifying dimensions, see Publishing +// Metrics (http://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/publishingMetrics.html) +// in the Amazon CloudWatch User Guide. +// // Data points with time stamps from 24 hours ago or longer can take at least // 48 hours to become available for GetMetricStatistics from the time they are // submitted. // +// CloudWatch needs raw data points to calculate percentile statistics. If you +// publish data using a statistic set instead, you cannot retrieve percentile +// statistics for this data unless one of the following conditions is true: +// +// * The SampleCount of the statistic set is 1 +// +// * The Min and the Max of the statistic set are equal +// // 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. @@ -874,8 +1104,23 @@ func (c *CloudWatch) PutMetricDataRequest(input *PutMetricDataInput) (req *reque // Please also see https://docs.aws.amazon.com/goto/WebAPI/monitoring-2010-08-01/PutMetricData func (c *CloudWatch) PutMetricData(input *PutMetricDataInput) (*PutMetricDataOutput, error) { req, out := c.PutMetricDataRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// PutMetricDataWithContext is the same as PutMetricData with the addition of +// the ability to pass a context and additional request options. +// +// See PutMetricData 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 *CloudWatch) PutMetricDataWithContext(ctx aws.Context, input *PutMetricDataInput, opts ...request.Option) (*PutMetricDataOutput, error) { + req, out := c.PutMetricDataRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opSetAlarmState = "SetAlarmState" @@ -951,8 +1196,23 @@ func (c *CloudWatch) SetAlarmStateRequest(input *SetAlarmStateInput) (req *reque // Please also see https://docs.aws.amazon.com/goto/WebAPI/monitoring-2010-08-01/SetAlarmState func (c *CloudWatch) SetAlarmState(input *SetAlarmStateInput) (*SetAlarmStateOutput, error) { req, out := c.SetAlarmStateRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// SetAlarmStateWithContext is the same as SetAlarmState with the addition of +// the ability to pass a context and additional request options. +// +// See SetAlarmState 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 *CloudWatch) SetAlarmStateWithContext(ctx aws.Context, input *SetAlarmStateInput, opts ...request.Option) (*SetAlarmStateOutput, error) { + req, out := c.SetAlarmStateRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // Represents the history of a specific alarm. @@ -1773,11 +2033,14 @@ func (s EnableAlarmActionsOutput) GoString() string { type GetMetricStatisticsInput struct { _ struct{} `type:"structure"` - // The dimensions. CloudWatch treats each unique combination of dimensions as - // a separate metric. You can't retrieve statistics using combinations of dimensions - // that were not specially published. You must specify the same dimensions that - // were used when the metrics were created. For an example, see Dimension Combinations - // (http://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/cloudwatch_concepts.html#dimension-combinations) + // The dimensions. If the metric contains multiple dimensions, you must include + // a value for each dimension. CloudWatch treats each unique combination of + // dimensions as a separate metric. You can't retrieve statistics using combinations + // of dimensions that were not specially published. You must specify the same + // dimensions that were used when the metrics were created. For an example, + // see Dimension Combinations (http://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/cloudwatch_concepts.html#dimension-combinations) + // in the Amazon CloudWatch User Guide. For more information on specifying dimensions, + // see Publishing Metrics (http://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/publishingMetrics.html) // in the Amazon CloudWatch User Guide. Dimensions []*Dimension `type:"list"` @@ -2184,6 +2447,8 @@ type MetricAlarm struct { // The dimensions for the metric associated with the alarm. Dimensions []*Dimension `type:"list"` + EvaluateLowSampleCountPercentile *string `min:"1" type:"string"` + // The number of periods over which data is compared to the specified threshold. EvaluationPeriods *int64 `min:"1" type:"integer"` @@ -2228,6 +2493,8 @@ type MetricAlarm struct { // The value to compare with the specified statistic. Threshold *float64 `type:"double"` + TreatMissingData *string `min:"1" type:"string"` + // The unit of the metric associated with the alarm. Unit *string `type:"string" enum:"StandardUnit"` } @@ -2290,6 +2557,12 @@ func (s *MetricAlarm) SetDimensions(v []*Dimension) *MetricAlarm { return s } +// SetEvaluateLowSampleCountPercentile sets the EvaluateLowSampleCountPercentile field's value. +func (s *MetricAlarm) SetEvaluateLowSampleCountPercentile(v string) *MetricAlarm { + s.EvaluateLowSampleCountPercentile = &v + return s +} + // SetEvaluationPeriods sets the EvaluationPeriods field's value. func (s *MetricAlarm) SetEvaluationPeriods(v int64) *MetricAlarm { s.EvaluationPeriods = &v @@ -2368,6 +2641,12 @@ func (s *MetricAlarm) SetThreshold(v float64) *MetricAlarm { return s } +// SetTreatMissingData sets the TreatMissingData field's value. +func (s *MetricAlarm) SetTreatMissingData(v string) *MetricAlarm { + s.TreatMissingData = &v + return s +} + // SetUnit sets the Unit field's value. func (s *MetricAlarm) SetUnit(v string) *MetricAlarm { s.Unit = &v @@ -2521,6 +2800,16 @@ type PutMetricAlarmInput struct { // The dimensions for the metric associated with the alarm. Dimensions []*Dimension `type:"list"` + // Used only for alarms based on percentiles. If you specify ignore, the alarm + // state will not change during periods with too few data points to be statistically + // significant. If you specify evaluate or omit this parameter, the alarm will + // always be evaluated and possibly change state no matter how many data points + // are available. For more information, see Percentile-Based CloudWatch Alarms + // and Low Data Samples (http://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/AlarmThatSendsEmail.html#percentiles-with-low-samples). + // + // Valid Values: evaluate | ignore + EvaluateLowSampleCountPercentile *string `min:"1" type:"string"` + // The number of periods over which data is compared to the specified threshold. // // EvaluationPeriods is a required field @@ -2577,6 +2866,13 @@ type PutMetricAlarmInput struct { // Threshold is a required field Threshold *float64 `type:"double" required:"true"` + // Sets how this alarm is to handle missing data points. If TreatMissingData + // is omitted, the default behavior of missing is used. For more information, + // see Configuring How CloudWatch Alarms Treats Missing Data (http://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/AlarmThatSendsEmail.html#alarms-and-missing-data). + // + // Valid Values: breaching | notBreaching | ignore | missing + TreatMissingData *string `min:"1" type:"string"` + // The unit of measure for the statistic. For example, the units for the Amazon // EC2 NetworkIn metric are Bytes because NetworkIn tracks the number of bytes // that an instance receives on all network interfaces. You can also specify @@ -2612,6 +2908,9 @@ func (s *PutMetricAlarmInput) Validate() error { if s.ComparisonOperator == nil { invalidParams.Add(request.NewErrParamRequired("ComparisonOperator")) } + if s.EvaluateLowSampleCountPercentile != nil && len(*s.EvaluateLowSampleCountPercentile) < 1 { + invalidParams.Add(request.NewErrParamMinLen("EvaluateLowSampleCountPercentile", 1)) + } if s.EvaluationPeriods == nil { invalidParams.Add(request.NewErrParamRequired("EvaluationPeriods")) } @@ -2639,6 +2938,9 @@ func (s *PutMetricAlarmInput) Validate() error { if s.Threshold == nil { invalidParams.Add(request.NewErrParamRequired("Threshold")) } + if s.TreatMissingData != nil && len(*s.TreatMissingData) < 1 { + invalidParams.Add(request.NewErrParamMinLen("TreatMissingData", 1)) + } if s.Dimensions != nil { for i, v := range s.Dimensions { if v == nil { @@ -2692,6 +2994,12 @@ func (s *PutMetricAlarmInput) SetDimensions(v []*Dimension) *PutMetricAlarmInput return s } +// SetEvaluateLowSampleCountPercentile sets the EvaluateLowSampleCountPercentile field's value. +func (s *PutMetricAlarmInput) SetEvaluateLowSampleCountPercentile(v string) *PutMetricAlarmInput { + s.EvaluateLowSampleCountPercentile = &v + return s +} + // SetEvaluationPeriods sets the EvaluationPeriods field's value. func (s *PutMetricAlarmInput) SetEvaluationPeriods(v int64) *PutMetricAlarmInput { s.EvaluationPeriods = &v @@ -2746,6 +3054,12 @@ func (s *PutMetricAlarmInput) SetThreshold(v float64) *PutMetricAlarmInput { return s } +// SetTreatMissingData sets the TreatMissingData field's value. +func (s *PutMetricAlarmInput) SetTreatMissingData(v string) *PutMetricAlarmInput { + s.TreatMissingData = &v + return s +} + // SetUnit sets the Unit field's value. func (s *PutMetricAlarmInput) SetUnit(v string) *PutMetricAlarmInput { s.Unit = &v diff --git a/vendor/github.com/aws/aws-sdk-go/service/cloudwatch/doc.go b/vendor/github.com/aws/aws-sdk-go/service/cloudwatch/doc.go new file mode 100644 index 000000000..f6cbf2ad8 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/service/cloudwatch/doc.go @@ -0,0 +1,94 @@ +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. + +// Package cloudwatch provides the client and types for making API +// requests to Amazon CloudWatch. +// +// Amazon CloudWatch monitors your Amazon Web Services (AWS) resources and the +// applications you run on AWS in real-time. You can use CloudWatch to collect +// and track metrics, which are the variables you want to measure for your resources +// and applications. +// +// CloudWatch alarms send notifications or automatically make changes to the +// resources you are monitoring based on rules that you define. For example, +// you can monitor the CPU usage and disk reads and writes of your Amazon Elastic +// Compute Cloud (Amazon EC2) instances and then use this data to determine +// whether you should launch additional instances to handle increased load. +// You can also use this data to stop under-used instances to save money. +// +// In addition to monitoring the built-in metrics that come with AWS, you can +// monitor your own custom metrics. With CloudWatch, you gain system-wide visibility +// into resource utilization, application performance, and operational health. +// +// See https://docs.aws.amazon.com/goto/WebAPI/monitoring-2010-08-01 for more information on this service. +// +// See cloudwatch package documentation for more information. +// https://docs.aws.amazon.com/sdk-for-go/api/service/cloudwatch/ +// +// Using the Client +// +// To use the client for Amazon CloudWatch you will first need +// to create a new instance of it. +// +// When creating a client for an AWS service you'll first need to have a Session +// already created. The Session provides configuration that can be shared +// between multiple service clients. Additional configuration can be applied to +// the Session and service's client when they are constructed. The aws package's +// Config type contains several fields such as Region for the AWS Region the +// client should make API requests too. The optional Config value can be provided +// as the variadic argument for Sessions and client creation. +// +// Once the service's client is created you can use it to make API requests the +// AWS service. These clients are safe to use concurrently. +// +// // Create a session to share configuration, and load external configuration. +// sess := session.Must(session.NewSession()) +// +// // Create the service's client with the session. +// svc := cloudwatch.New(sess) +// +// See the SDK's documentation for more information on how to use service clients. +// https://docs.aws.amazon.com/sdk-for-go/api/ +// +// See aws package's Config type for more information on configuration options. +// https://docs.aws.amazon.com/sdk-for-go/api/aws/#Config +// +// See the Amazon CloudWatch client CloudWatch for more +// information on creating the service's client. +// https://docs.aws.amazon.com/sdk-for-go/api/service/cloudwatch/#New +// +// Once the client is created you can make an API request to the service. +// Each API method takes a input parameter, and returns the service response +// and an error. +// +// The API method will document which error codes the service can be returned +// by the operation if the service models the API operation's errors. These +// errors will also be available as const strings prefixed with "ErrCode". +// +// result, err := svc.DeleteAlarms(params) +// if err != nil { +// // Cast err to awserr.Error to handle specific error codes. +// aerr, ok := err.(awserr.Error) +// if ok && aerr.Code() == { +// // Specific error code handling +// } +// return err +// } +// +// fmt.Println("DeleteAlarms result:") +// fmt.Println(result) +// +// Using the Client with Context +// +// The service's client also provides methods to make API requests with a Context +// value. This allows you to control the timeout, and cancellation of pending +// requests. These methods also take request Option as variadic parameter to apply +// additional configuration to the API request. +// +// ctx := context.Background() +// +// result, err := svc.DeleteAlarmsWithContext(ctx, params) +// +// See the request package documentation for more information on using Context pattern +// with the SDK. +// https://docs.aws.amazon.com/sdk-for-go/api/aws/request/ +package cloudwatch diff --git a/vendor/github.com/aws/aws-sdk-go/service/cloudwatch/errors.go b/vendor/github.com/aws/aws-sdk-go/service/cloudwatch/errors.go index 60bced5f1..6eb8cb37f 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/cloudwatch/errors.go +++ b/vendor/github.com/aws/aws-sdk-go/service/cloudwatch/errors.go @@ -1,4 +1,4 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. package cloudwatch diff --git a/vendor/github.com/aws/aws-sdk-go/service/cloudwatch/service.go b/vendor/github.com/aws/aws-sdk-go/service/cloudwatch/service.go index 4a992be67..4b0aa76ed 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/cloudwatch/service.go +++ b/vendor/github.com/aws/aws-sdk-go/service/cloudwatch/service.go @@ -1,4 +1,4 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. package cloudwatch @@ -11,24 +11,12 @@ import ( "github.com/aws/aws-sdk-go/private/protocol/query" ) -// Amazon CloudWatch monitors your Amazon Web Services (AWS) resources and the -// applications you run on AWS in real-time. You can use CloudWatch to collect -// and track metrics, which are the variables you want to measure for your resources -// and applications. +// CloudWatch provides the API operation methods for making requests to +// Amazon CloudWatch. See this package's package overview docs +// for details on the service. // -// CloudWatch alarms send notifications or automatically make changes to the -// resources you are monitoring based on rules that you define. For example, -// you can monitor the CPU usage and disk reads and writes of your Amazon Elastic -// Compute Cloud (Amazon EC2) instances and then use this data to determine -// whether you should launch additional instances to handle increased load. -// You can also use this data to stop under-used instances to save money. -// -// In addition to monitoring the built-in metrics that come with AWS, you can -// monitor your own custom metrics. With CloudWatch, you gain system-wide visibility -// into resource utilization, application performance, and operational health. -// The service client's operations are safe to be used concurrently. -// It is not safe to mutate any of the client's properties though. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/monitoring-2010-08-01 +// CloudWatch methods are safe to use concurrently. It is not safe to +// modify mutate any of the struct's properties though. type CloudWatch struct { *client.Client } diff --git a/vendor/github.com/aws/aws-sdk-go/service/cloudwatch/waiters.go b/vendor/github.com/aws/aws-sdk-go/service/cloudwatch/waiters.go index 1184650e2..064abf015 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/cloudwatch/waiters.go +++ b/vendor/github.com/aws/aws-sdk-go/service/cloudwatch/waiters.go @@ -1,9 +1,12 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. package cloudwatch import ( - "github.com/aws/aws-sdk-go/private/waiter" + "time" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/request" ) // WaitUntilAlarmExists uses the CloudWatch API operation @@ -11,24 +14,43 @@ import ( // If the condition is not meet within the max attempt window an error will // be returned. func (c *CloudWatch) WaitUntilAlarmExists(input *DescribeAlarmsInput) error { - waiterCfg := waiter.Config{ - Operation: "DescribeAlarms", - Delay: 5, + return c.WaitUntilAlarmExistsWithContext(aws.BackgroundContext(), input) +} + +// WaitUntilAlarmExistsWithContext is an extended version of WaitUntilAlarmExists. +// 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 *CloudWatch) WaitUntilAlarmExistsWithContext(ctx aws.Context, input *DescribeAlarmsInput, opts ...request.WaiterOption) error { + w := request.Waiter{ + Name: "WaitUntilAlarmExists", MaxAttempts: 40, - Acceptors: []waiter.WaitAcceptor{ + Delay: request.ConstantWaiterDelay(5 * time.Second), + Acceptors: []request.WaiterAcceptor{ { - State: "success", - Matcher: "path", - Argument: "length(MetricAlarms[]) > `0`", + State: request.SuccessWaiterState, + Matcher: request.PathWaiterMatch, Argument: "length(MetricAlarms[]) > `0`", Expected: true, }, }, + Logger: c.Config.Logger, + NewRequest: func(opts []request.Option) (*request.Request, error) { + var inCpy *DescribeAlarmsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeAlarmsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, } + w.ApplyOptions(opts...) - w := waiter.Waiter{ - Client: c, - Input: input, - Config: waiterCfg, - } - return w.Wait() + return w.WaitWithContext(ctx) } diff --git a/vendor/github.com/aws/aws-sdk-go/service/cloudwatchevents/api.go b/vendor/github.com/aws/aws-sdk-go/service/cloudwatchevents/api.go index d626b354f..5d64f7704 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/cloudwatchevents/api.go +++ b/vendor/github.com/aws/aws-sdk-go/service/cloudwatchevents/api.go @@ -1,12 +1,12 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. -// Package cloudwatchevents provides a client for Amazon CloudWatch Events. package cloudwatchevents import ( "fmt" "time" + "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awsutil" "github.com/aws/aws-sdk-go/aws/request" "github.com/aws/aws-sdk-go/private/protocol" @@ -85,8 +85,23 @@ func (c *CloudWatchEvents) DeleteRuleRequest(input *DeleteRuleInput) (req *reque // Please also see https://docs.aws.amazon.com/goto/WebAPI/events-2015-10-07/DeleteRule func (c *CloudWatchEvents) DeleteRule(input *DeleteRuleInput) (*DeleteRuleOutput, error) { req, out := c.DeleteRuleRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteRuleWithContext is the same as DeleteRule with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteRule 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 *CloudWatchEvents) DeleteRuleWithContext(ctx aws.Context, input *DeleteRuleInput, opts ...request.Option) (*DeleteRuleOutput, error) { + req, out := c.DeleteRuleRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeRule = "DescribeRule" @@ -153,8 +168,23 @@ func (c *CloudWatchEvents) DescribeRuleRequest(input *DescribeRuleInput) (req *r // Please also see https://docs.aws.amazon.com/goto/WebAPI/events-2015-10-07/DescribeRule func (c *CloudWatchEvents) DescribeRule(input *DescribeRuleInput) (*DescribeRuleOutput, error) { req, out := c.DescribeRuleRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeRuleWithContext is the same as DescribeRule with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeRule 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 *CloudWatchEvents) DescribeRuleWithContext(ctx aws.Context, input *DescribeRuleInput, opts ...request.Option) (*DescribeRuleOutput, error) { + req, out := c.DescribeRuleRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDisableRule = "DisableRule" @@ -230,8 +260,23 @@ func (c *CloudWatchEvents) DisableRuleRequest(input *DisableRuleInput) (req *req // Please also see https://docs.aws.amazon.com/goto/WebAPI/events-2015-10-07/DisableRule func (c *CloudWatchEvents) DisableRule(input *DisableRuleInput) (*DisableRuleOutput, error) { req, out := c.DisableRuleRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DisableRuleWithContext is the same as DisableRule with the addition of +// the ability to pass a context and additional request options. +// +// See DisableRule 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 *CloudWatchEvents) DisableRuleWithContext(ctx aws.Context, input *DisableRuleInput, opts ...request.Option) (*DisableRuleOutput, error) { + req, out := c.DisableRuleRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opEnableRule = "EnableRule" @@ -307,8 +352,23 @@ func (c *CloudWatchEvents) EnableRuleRequest(input *EnableRuleInput) (req *reque // Please also see https://docs.aws.amazon.com/goto/WebAPI/events-2015-10-07/EnableRule func (c *CloudWatchEvents) EnableRule(input *EnableRuleInput) (*EnableRuleOutput, error) { req, out := c.EnableRuleRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// EnableRuleWithContext is the same as EnableRule with the addition of +// the ability to pass a context and additional request options. +// +// See EnableRule 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 *CloudWatchEvents) EnableRuleWithContext(ctx aws.Context, input *EnableRuleInput, opts ...request.Option) (*EnableRuleOutput, error) { + req, out := c.EnableRuleRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opListRuleNamesByTarget = "ListRuleNamesByTarget" @@ -373,8 +433,23 @@ func (c *CloudWatchEvents) ListRuleNamesByTargetRequest(input *ListRuleNamesByTa // Please also see https://docs.aws.amazon.com/goto/WebAPI/events-2015-10-07/ListRuleNamesByTarget func (c *CloudWatchEvents) ListRuleNamesByTarget(input *ListRuleNamesByTargetInput) (*ListRuleNamesByTargetOutput, error) { req, out := c.ListRuleNamesByTargetRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListRuleNamesByTargetWithContext is the same as ListRuleNamesByTarget with the addition of +// the ability to pass a context and additional request options. +// +// See ListRuleNamesByTarget 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 *CloudWatchEvents) ListRuleNamesByTargetWithContext(ctx aws.Context, input *ListRuleNamesByTargetInput, opts ...request.Option) (*ListRuleNamesByTargetOutput, error) { + req, out := c.ListRuleNamesByTargetRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opListRules = "ListRules" @@ -439,8 +514,23 @@ func (c *CloudWatchEvents) ListRulesRequest(input *ListRulesInput) (req *request // Please also see https://docs.aws.amazon.com/goto/WebAPI/events-2015-10-07/ListRules func (c *CloudWatchEvents) ListRules(input *ListRulesInput) (*ListRulesOutput, error) { req, out := c.ListRulesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListRulesWithContext is the same as ListRules with the addition of +// the ability to pass a context and additional request options. +// +// See ListRules 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 *CloudWatchEvents) ListRulesWithContext(ctx aws.Context, input *ListRulesInput, opts ...request.Option) (*ListRulesOutput, error) { + req, out := c.ListRulesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opListTargetsByRule = "ListTargetsByRule" @@ -507,8 +597,23 @@ func (c *CloudWatchEvents) ListTargetsByRuleRequest(input *ListTargetsByRuleInpu // Please also see https://docs.aws.amazon.com/goto/WebAPI/events-2015-10-07/ListTargetsByRule func (c *CloudWatchEvents) ListTargetsByRule(input *ListTargetsByRuleInput) (*ListTargetsByRuleOutput, error) { req, out := c.ListTargetsByRuleRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListTargetsByRuleWithContext is the same as ListTargetsByRule with the addition of +// the ability to pass a context and additional request options. +// +// See ListTargetsByRule 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 *CloudWatchEvents) ListTargetsByRuleWithContext(ctx aws.Context, input *ListTargetsByRuleInput, opts ...request.Option) (*ListTargetsByRuleOutput, error) { + req, out := c.ListTargetsByRuleRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opPutEvents = "PutEvents" @@ -573,8 +678,23 @@ func (c *CloudWatchEvents) PutEventsRequest(input *PutEventsInput) (req *request // Please also see https://docs.aws.amazon.com/goto/WebAPI/events-2015-10-07/PutEvents func (c *CloudWatchEvents) PutEvents(input *PutEventsInput) (*PutEventsOutput, error) { req, out := c.PutEventsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// PutEventsWithContext is the same as PutEvents with the addition of +// the ability to pass a context and additional request options. +// +// See PutEvents 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 *CloudWatchEvents) PutEventsWithContext(ctx aws.Context, input *PutEventsInput, opts ...request.Option) (*PutEventsOutput, error) { + req, out := c.PutEventsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opPutRule = "PutRule" @@ -663,8 +783,23 @@ func (c *CloudWatchEvents) PutRuleRequest(input *PutRuleInput) (req *request.Req // Please also see https://docs.aws.amazon.com/goto/WebAPI/events-2015-10-07/PutRule func (c *CloudWatchEvents) PutRule(input *PutRuleInput) (*PutRuleOutput, error) { req, out := c.PutRuleRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// PutRuleWithContext is the same as PutRule with the addition of +// the ability to pass a context and additional request options. +// +// See PutRule 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 *CloudWatchEvents) PutRuleWithContext(ctx aws.Context, input *PutRuleInput, opts ...request.Option) (*PutRuleOutput, error) { + req, out := c.PutRuleRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opPutTargets = "PutTargets" @@ -781,8 +916,23 @@ func (c *CloudWatchEvents) PutTargetsRequest(input *PutTargetsInput) (req *reque // Please also see https://docs.aws.amazon.com/goto/WebAPI/events-2015-10-07/PutTargets func (c *CloudWatchEvents) PutTargets(input *PutTargetsInput) (*PutTargetsOutput, error) { req, out := c.PutTargetsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// PutTargetsWithContext is the same as PutTargets with the addition of +// the ability to pass a context and additional request options. +// +// See PutTargets 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 *CloudWatchEvents) PutTargetsWithContext(ctx aws.Context, input *PutTargetsInput, opts ...request.Option) (*PutTargetsOutput, error) { + req, out := c.PutTargetsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opRemoveTargets = "RemoveTargets" @@ -857,8 +1007,23 @@ func (c *CloudWatchEvents) RemoveTargetsRequest(input *RemoveTargetsInput) (req // Please also see https://docs.aws.amazon.com/goto/WebAPI/events-2015-10-07/RemoveTargets func (c *CloudWatchEvents) RemoveTargets(input *RemoveTargetsInput) (*RemoveTargetsOutput, error) { req, out := c.RemoveTargetsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// RemoveTargetsWithContext is the same as RemoveTargets with the addition of +// the ability to pass a context and additional request options. +// +// See RemoveTargets 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 *CloudWatchEvents) RemoveTargetsWithContext(ctx aws.Context, input *RemoveTargetsInput, opts ...request.Option) (*RemoveTargetsOutput, error) { + req, out := c.RemoveTargetsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opTestEventPattern = "TestEventPattern" @@ -930,8 +1095,23 @@ func (c *CloudWatchEvents) TestEventPatternRequest(input *TestEventPatternInput) // Please also see https://docs.aws.amazon.com/goto/WebAPI/events-2015-10-07/TestEventPattern func (c *CloudWatchEvents) TestEventPattern(input *TestEventPatternInput) (*TestEventPatternOutput, error) { req, out := c.TestEventPatternRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// TestEventPatternWithContext is the same as TestEventPattern with the addition of +// the ability to pass a context and additional request options. +// +// See TestEventPattern 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 *CloudWatchEvents) TestEventPatternWithContext(ctx aws.Context, input *TestEventPatternInput, opts ...request.Option) (*TestEventPatternOutput, error) { + req, out := c.TestEventPatternRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // Please also see https://docs.aws.amazon.com/goto/WebAPI/events-2015-10-07/DeleteRuleRequest diff --git a/vendor/github.com/aws/aws-sdk-go/service/cloudwatchevents/doc.go b/vendor/github.com/aws/aws-sdk-go/service/cloudwatchevents/doc.go new file mode 100644 index 000000000..a56cf09dc --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/service/cloudwatchevents/doc.go @@ -0,0 +1,97 @@ +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. + +// Package cloudwatchevents provides the client and types for making API +// requests to Amazon CloudWatch Events. +// +// Amazon CloudWatch Events helps you to respond to state changes in your AWS +// resources. When your resources change state, they automatically send events +// into an event stream. You can create rules that match selected events in +// the stream and route them to targets to take action. You can also use rules +// to take action on a pre-determined schedule. For example, you can configure +// rules to: +// +// * Automatically invoke an AWS Lambda function to update DNS entries when +// an event notifies you that Amazon EC2 instance enters the running state. +// +// * Direct specific API records from CloudTrail to an Amazon Kinesis stream +// for detailed analysis of potential security or availability risks. +// +// * Periodically invoke a built-in target to create a snapshot of an Amazon +// EBS volume. +// +// For more information about the features of Amazon CloudWatch Events, see +// the Amazon CloudWatch Events User Guide (http://docs.aws.amazon.com/AmazonCloudWatch/latest/events). +// +// See https://docs.aws.amazon.com/goto/WebAPI/events-2015-10-07 for more information on this service. +// +// See cloudwatchevents package documentation for more information. +// https://docs.aws.amazon.com/sdk-for-go/api/service/cloudwatchevents/ +// +// Using the Client +// +// To use the client for Amazon CloudWatch Events you will first need +// to create a new instance of it. +// +// When creating a client for an AWS service you'll first need to have a Session +// already created. The Session provides configuration that can be shared +// between multiple service clients. Additional configuration can be applied to +// the Session and service's client when they are constructed. The aws package's +// Config type contains several fields such as Region for the AWS Region the +// client should make API requests too. The optional Config value can be provided +// as the variadic argument for Sessions and client creation. +// +// Once the service's client is created you can use it to make API requests the +// AWS service. These clients are safe to use concurrently. +// +// // Create a session to share configuration, and load external configuration. +// sess := session.Must(session.NewSession()) +// +// // Create the service's client with the session. +// svc := cloudwatchevents.New(sess) +// +// See the SDK's documentation for more information on how to use service clients. +// https://docs.aws.amazon.com/sdk-for-go/api/ +// +// See aws package's Config type for more information on configuration options. +// https://docs.aws.amazon.com/sdk-for-go/api/aws/#Config +// +// See the Amazon CloudWatch Events client CloudWatchEvents for more +// information on creating the service's client. +// https://docs.aws.amazon.com/sdk-for-go/api/service/cloudwatchevents/#New +// +// Once the client is created you can make an API request to the service. +// Each API method takes a input parameter, and returns the service response +// and an error. +// +// The API method will document which error codes the service can be returned +// by the operation if the service models the API operation's errors. These +// errors will also be available as const strings prefixed with "ErrCode". +// +// result, err := svc.DeleteRule(params) +// if err != nil { +// // Cast err to awserr.Error to handle specific error codes. +// aerr, ok := err.(awserr.Error) +// if ok && aerr.Code() == { +// // Specific error code handling +// } +// return err +// } +// +// fmt.Println("DeleteRule result:") +// fmt.Println(result) +// +// Using the Client with Context +// +// The service's client also provides methods to make API requests with a Context +// value. This allows you to control the timeout, and cancellation of pending +// requests. These methods also take request Option as variadic parameter to apply +// additional configuration to the API request. +// +// ctx := context.Background() +// +// result, err := svc.DeleteRuleWithContext(ctx, params) +// +// See the request package documentation for more information on using Context pattern +// with the SDK. +// https://docs.aws.amazon.com/sdk-for-go/api/aws/request/ +package cloudwatchevents diff --git a/vendor/github.com/aws/aws-sdk-go/service/cloudwatchevents/errors.go b/vendor/github.com/aws/aws-sdk-go/service/cloudwatchevents/errors.go index fe9ecb8f8..c7bbe1f58 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/cloudwatchevents/errors.go +++ b/vendor/github.com/aws/aws-sdk-go/service/cloudwatchevents/errors.go @@ -1,4 +1,4 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. package cloudwatchevents diff --git a/vendor/github.com/aws/aws-sdk-go/service/cloudwatchevents/service.go b/vendor/github.com/aws/aws-sdk-go/service/cloudwatchevents/service.go index 569d91ed8..1fb24f16b 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/cloudwatchevents/service.go +++ b/vendor/github.com/aws/aws-sdk-go/service/cloudwatchevents/service.go @@ -1,4 +1,4 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. package cloudwatchevents @@ -11,27 +11,12 @@ import ( "github.com/aws/aws-sdk-go/private/protocol/jsonrpc" ) -// Amazon CloudWatch Events helps you to respond to state changes in your AWS -// resources. When your resources change state, they automatically send events -// into an event stream. You can create rules that match selected events in -// the stream and route them to targets to take action. You can also use rules -// to take action on a pre-determined schedule. For example, you can configure -// rules to: +// CloudWatchEvents provides the API operation methods for making requests to +// Amazon CloudWatch Events. See this package's package overview docs +// for details on the service. // -// * Automatically invoke an AWS Lambda function to update DNS entries when -// an event notifies you that Amazon EC2 instance enters the running state. -// -// * Direct specific API records from CloudTrail to an Amazon Kinesis stream -// for detailed analysis of potential security or availability risks. -// -// * Periodically invoke a built-in target to create a snapshot of an Amazon -// EBS volume. -// -// For more information about the features of Amazon CloudWatch Events, see -// the Amazon CloudWatch Events User Guide (http://docs.aws.amazon.com/AmazonCloudWatch/latest/events). -// The service client's operations are safe to be used concurrently. -// It is not safe to mutate any of the client's properties though. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/events-2015-10-07 +// CloudWatchEvents methods are safe to use concurrently. It is not safe to +// modify mutate any of the struct's properties though. type CloudWatchEvents struct { *client.Client } diff --git a/vendor/github.com/aws/aws-sdk-go/service/cloudwatchlogs/api.go b/vendor/github.com/aws/aws-sdk-go/service/cloudwatchlogs/api.go index 38fee5bc7..aa55e434e 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/cloudwatchlogs/api.go +++ b/vendor/github.com/aws/aws-sdk-go/service/cloudwatchlogs/api.go @@ -1,11 +1,11 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. -// Package cloudwatchlogs provides a client for Amazon CloudWatch Logs. package cloudwatchlogs import ( "fmt" + "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awsutil" "github.com/aws/aws-sdk-go/aws/request" "github.com/aws/aws-sdk-go/private/protocol" @@ -86,8 +86,23 @@ func (c *CloudWatchLogs) CancelExportTaskRequest(input *CancelExportTaskInput) ( // Please also see https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/CancelExportTask func (c *CloudWatchLogs) CancelExportTask(input *CancelExportTaskInput) (*CancelExportTaskOutput, error) { req, out := c.CancelExportTaskRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CancelExportTaskWithContext is the same as CancelExportTask with the addition of +// the ability to pass a context and additional request options. +// +// See CancelExportTask 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 *CloudWatchLogs) CancelExportTaskWithContext(ctx aws.Context, input *CancelExportTaskInput, opts ...request.Option) (*CancelExportTaskOutput, error) { + req, out := c.CancelExportTaskRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateExportTask = "CreateExportTask" @@ -177,8 +192,23 @@ func (c *CloudWatchLogs) CreateExportTaskRequest(input *CreateExportTaskInput) ( // Please also see https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/CreateExportTask func (c *CloudWatchLogs) CreateExportTask(input *CreateExportTaskInput) (*CreateExportTaskOutput, error) { req, out := c.CreateExportTaskRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateExportTaskWithContext is the same as CreateExportTask with the addition of +// the ability to pass a context and additional request options. +// +// See CreateExportTask 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 *CloudWatchLogs) CreateExportTaskWithContext(ctx aws.Context, input *CreateExportTaskInput, opts ...request.Option) (*CreateExportTaskOutput, error) { + req, out := c.CreateExportTaskRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateLogGroup = "CreateLogGroup" @@ -267,8 +297,23 @@ func (c *CloudWatchLogs) CreateLogGroupRequest(input *CreateLogGroupInput) (req // Please also see https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/CreateLogGroup func (c *CloudWatchLogs) CreateLogGroup(input *CreateLogGroupInput) (*CreateLogGroupOutput, error) { req, out := c.CreateLogGroupRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateLogGroupWithContext is the same as CreateLogGroup with the addition of +// the ability to pass a context and additional request options. +// +// See CreateLogGroup 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 *CloudWatchLogs) CreateLogGroupWithContext(ctx aws.Context, input *CreateLogGroupInput, opts ...request.Option) (*CreateLogGroupOutput, error) { + req, out := c.CreateLogGroupRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateLogStream = "CreateLogStream" @@ -354,8 +399,23 @@ func (c *CloudWatchLogs) CreateLogStreamRequest(input *CreateLogStreamInput) (re // Please also see https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/CreateLogStream func (c *CloudWatchLogs) CreateLogStream(input *CreateLogStreamInput) (*CreateLogStreamOutput, error) { req, out := c.CreateLogStreamRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateLogStreamWithContext is the same as CreateLogStream with the addition of +// the ability to pass a context and additional request options. +// +// See CreateLogStream 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 *CloudWatchLogs) CreateLogStreamWithContext(ctx aws.Context, input *CreateLogStreamInput, opts ...request.Option) (*CreateLogStreamOutput, error) { + req, out := c.CreateLogStreamRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteDestination = "DeleteDestination" @@ -432,8 +492,23 @@ func (c *CloudWatchLogs) DeleteDestinationRequest(input *DeleteDestinationInput) // Please also see https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/DeleteDestination func (c *CloudWatchLogs) DeleteDestination(input *DeleteDestinationInput) (*DeleteDestinationOutput, error) { req, out := c.DeleteDestinationRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteDestinationWithContext is the same as DeleteDestination with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteDestination 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 *CloudWatchLogs) DeleteDestinationWithContext(ctx aws.Context, input *DeleteDestinationInput, opts ...request.Option) (*DeleteDestinationOutput, error) { + req, out := c.DeleteDestinationRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteLogGroup = "DeleteLogGroup" @@ -509,8 +584,23 @@ func (c *CloudWatchLogs) DeleteLogGroupRequest(input *DeleteLogGroupInput) (req // Please also see https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/DeleteLogGroup func (c *CloudWatchLogs) DeleteLogGroup(input *DeleteLogGroupInput) (*DeleteLogGroupOutput, error) { req, out := c.DeleteLogGroupRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteLogGroupWithContext is the same as DeleteLogGroup with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteLogGroup 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 *CloudWatchLogs) DeleteLogGroupWithContext(ctx aws.Context, input *DeleteLogGroupInput, opts ...request.Option) (*DeleteLogGroupOutput, error) { + req, out := c.DeleteLogGroupRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteLogStream = "DeleteLogStream" @@ -586,8 +676,23 @@ func (c *CloudWatchLogs) DeleteLogStreamRequest(input *DeleteLogStreamInput) (re // Please also see https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/DeleteLogStream func (c *CloudWatchLogs) DeleteLogStream(input *DeleteLogStreamInput) (*DeleteLogStreamOutput, error) { req, out := c.DeleteLogStreamRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteLogStreamWithContext is the same as DeleteLogStream with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteLogStream 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 *CloudWatchLogs) DeleteLogStreamWithContext(ctx aws.Context, input *DeleteLogStreamInput, opts ...request.Option) (*DeleteLogStreamOutput, error) { + req, out := c.DeleteLogStreamRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteMetricFilter = "DeleteMetricFilter" @@ -662,8 +767,23 @@ func (c *CloudWatchLogs) DeleteMetricFilterRequest(input *DeleteMetricFilterInpu // Please also see https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/DeleteMetricFilter func (c *CloudWatchLogs) DeleteMetricFilter(input *DeleteMetricFilterInput) (*DeleteMetricFilterOutput, error) { req, out := c.DeleteMetricFilterRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteMetricFilterWithContext is the same as DeleteMetricFilter with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteMetricFilter 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 *CloudWatchLogs) DeleteMetricFilterWithContext(ctx aws.Context, input *DeleteMetricFilterInput, opts ...request.Option) (*DeleteMetricFilterOutput, error) { + req, out := c.DeleteMetricFilterRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteRetentionPolicy = "DeleteRetentionPolicy" @@ -741,8 +861,23 @@ func (c *CloudWatchLogs) DeleteRetentionPolicyRequest(input *DeleteRetentionPoli // Please also see https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/DeleteRetentionPolicy func (c *CloudWatchLogs) DeleteRetentionPolicy(input *DeleteRetentionPolicyInput) (*DeleteRetentionPolicyOutput, error) { req, out := c.DeleteRetentionPolicyRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteRetentionPolicyWithContext is the same as DeleteRetentionPolicy with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteRetentionPolicy 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 *CloudWatchLogs) DeleteRetentionPolicyWithContext(ctx aws.Context, input *DeleteRetentionPolicyInput, opts ...request.Option) (*DeleteRetentionPolicyOutput, error) { + req, out := c.DeleteRetentionPolicyRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteSubscriptionFilter = "DeleteSubscriptionFilter" @@ -817,8 +952,23 @@ func (c *CloudWatchLogs) DeleteSubscriptionFilterRequest(input *DeleteSubscripti // Please also see https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/DeleteSubscriptionFilter func (c *CloudWatchLogs) DeleteSubscriptionFilter(input *DeleteSubscriptionFilterInput) (*DeleteSubscriptionFilterOutput, error) { req, out := c.DeleteSubscriptionFilterRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteSubscriptionFilterWithContext is the same as DeleteSubscriptionFilter with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteSubscriptionFilter 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 *CloudWatchLogs) DeleteSubscriptionFilterWithContext(ctx aws.Context, input *DeleteSubscriptionFilterInput, opts ...request.Option) (*DeleteSubscriptionFilterOutput, error) { + req, out := c.DeleteSubscriptionFilterRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeDestinations = "DescribeDestinations" @@ -892,8 +1042,23 @@ func (c *CloudWatchLogs) DescribeDestinationsRequest(input *DescribeDestinations // Please also see https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/DescribeDestinations func (c *CloudWatchLogs) DescribeDestinations(input *DescribeDestinationsInput) (*DescribeDestinationsOutput, error) { req, out := c.DescribeDestinationsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeDestinationsWithContext is the same as DescribeDestinations with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeDestinations 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 *CloudWatchLogs) DescribeDestinationsWithContext(ctx aws.Context, input *DescribeDestinationsInput, opts ...request.Option) (*DescribeDestinationsOutput, error) { + req, out := c.DescribeDestinationsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // DescribeDestinationsPages iterates over the pages of a DescribeDestinations operation, @@ -913,12 +1078,37 @@ func (c *CloudWatchLogs) DescribeDestinations(input *DescribeDestinationsInput) // return pageNum <= 3 // }) // -func (c *CloudWatchLogs) DescribeDestinationsPages(input *DescribeDestinationsInput, fn func(p *DescribeDestinationsOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.DescribeDestinationsRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*DescribeDestinationsOutput), lastPage) - }) +func (c *CloudWatchLogs) DescribeDestinationsPages(input *DescribeDestinationsInput, fn func(*DescribeDestinationsOutput, bool) bool) error { + return c.DescribeDestinationsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// DescribeDestinationsPagesWithContext same as DescribeDestinationsPages 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 *CloudWatchLogs) DescribeDestinationsPagesWithContext(ctx aws.Context, input *DescribeDestinationsInput, fn func(*DescribeDestinationsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *DescribeDestinationsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeDestinationsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*DescribeDestinationsOutput), !p.HasNextPage()) + } + return p.Err() } const opDescribeExportTasks = "DescribeExportTasks" @@ -986,8 +1176,23 @@ func (c *CloudWatchLogs) DescribeExportTasksRequest(input *DescribeExportTasksIn // Please also see https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/DescribeExportTasks func (c *CloudWatchLogs) DescribeExportTasks(input *DescribeExportTasksInput) (*DescribeExportTasksOutput, error) { req, out := c.DescribeExportTasksRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeExportTasksWithContext is the same as DescribeExportTasks with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeExportTasks 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 *CloudWatchLogs) DescribeExportTasksWithContext(ctx aws.Context, input *DescribeExportTasksInput, opts ...request.Option) (*DescribeExportTasksOutput, error) { + req, out := c.DescribeExportTasksRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeLogGroups = "DescribeLogGroups" @@ -1061,8 +1266,23 @@ func (c *CloudWatchLogs) DescribeLogGroupsRequest(input *DescribeLogGroupsInput) // Please also see https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/DescribeLogGroups func (c *CloudWatchLogs) DescribeLogGroups(input *DescribeLogGroupsInput) (*DescribeLogGroupsOutput, error) { req, out := c.DescribeLogGroupsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeLogGroupsWithContext is the same as DescribeLogGroups with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeLogGroups 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 *CloudWatchLogs) DescribeLogGroupsWithContext(ctx aws.Context, input *DescribeLogGroupsInput, opts ...request.Option) (*DescribeLogGroupsOutput, error) { + req, out := c.DescribeLogGroupsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // DescribeLogGroupsPages iterates over the pages of a DescribeLogGroups operation, @@ -1082,12 +1302,37 @@ func (c *CloudWatchLogs) DescribeLogGroups(input *DescribeLogGroupsInput) (*Desc // return pageNum <= 3 // }) // -func (c *CloudWatchLogs) DescribeLogGroupsPages(input *DescribeLogGroupsInput, fn func(p *DescribeLogGroupsOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.DescribeLogGroupsRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*DescribeLogGroupsOutput), lastPage) - }) +func (c *CloudWatchLogs) DescribeLogGroupsPages(input *DescribeLogGroupsInput, fn func(*DescribeLogGroupsOutput, bool) bool) error { + return c.DescribeLogGroupsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// DescribeLogGroupsPagesWithContext same as DescribeLogGroupsPages 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 *CloudWatchLogs) DescribeLogGroupsPagesWithContext(ctx aws.Context, input *DescribeLogGroupsInput, fn func(*DescribeLogGroupsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *DescribeLogGroupsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeLogGroupsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*DescribeLogGroupsOutput), !p.HasNextPage()) + } + return p.Err() } const opDescribeLogStreams = "DescribeLogStreams" @@ -1168,8 +1413,23 @@ func (c *CloudWatchLogs) DescribeLogStreamsRequest(input *DescribeLogStreamsInpu // Please also see https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/DescribeLogStreams func (c *CloudWatchLogs) DescribeLogStreams(input *DescribeLogStreamsInput) (*DescribeLogStreamsOutput, error) { req, out := c.DescribeLogStreamsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeLogStreamsWithContext is the same as DescribeLogStreams with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeLogStreams 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 *CloudWatchLogs) DescribeLogStreamsWithContext(ctx aws.Context, input *DescribeLogStreamsInput, opts ...request.Option) (*DescribeLogStreamsOutput, error) { + req, out := c.DescribeLogStreamsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // DescribeLogStreamsPages iterates over the pages of a DescribeLogStreams operation, @@ -1189,12 +1449,37 @@ func (c *CloudWatchLogs) DescribeLogStreams(input *DescribeLogStreamsInput) (*De // return pageNum <= 3 // }) // -func (c *CloudWatchLogs) DescribeLogStreamsPages(input *DescribeLogStreamsInput, fn func(p *DescribeLogStreamsOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.DescribeLogStreamsRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*DescribeLogStreamsOutput), lastPage) - }) +func (c *CloudWatchLogs) DescribeLogStreamsPages(input *DescribeLogStreamsInput, fn func(*DescribeLogStreamsOutput, bool) bool) error { + return c.DescribeLogStreamsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// DescribeLogStreamsPagesWithContext same as DescribeLogStreamsPages 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 *CloudWatchLogs) DescribeLogStreamsPagesWithContext(ctx aws.Context, input *DescribeLogStreamsInput, fn func(*DescribeLogStreamsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *DescribeLogStreamsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeLogStreamsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*DescribeLogStreamsOutput), !p.HasNextPage()) + } + return p.Err() } const opDescribeMetricFilters = "DescribeMetricFilters" @@ -1272,8 +1557,23 @@ func (c *CloudWatchLogs) DescribeMetricFiltersRequest(input *DescribeMetricFilte // Please also see https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/DescribeMetricFilters func (c *CloudWatchLogs) DescribeMetricFilters(input *DescribeMetricFiltersInput) (*DescribeMetricFiltersOutput, error) { req, out := c.DescribeMetricFiltersRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeMetricFiltersWithContext is the same as DescribeMetricFilters with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeMetricFilters 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 *CloudWatchLogs) DescribeMetricFiltersWithContext(ctx aws.Context, input *DescribeMetricFiltersInput, opts ...request.Option) (*DescribeMetricFiltersOutput, error) { + req, out := c.DescribeMetricFiltersRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // DescribeMetricFiltersPages iterates over the pages of a DescribeMetricFilters operation, @@ -1293,12 +1593,37 @@ func (c *CloudWatchLogs) DescribeMetricFilters(input *DescribeMetricFiltersInput // return pageNum <= 3 // }) // -func (c *CloudWatchLogs) DescribeMetricFiltersPages(input *DescribeMetricFiltersInput, fn func(p *DescribeMetricFiltersOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.DescribeMetricFiltersRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*DescribeMetricFiltersOutput), lastPage) - }) +func (c *CloudWatchLogs) DescribeMetricFiltersPages(input *DescribeMetricFiltersInput, fn func(*DescribeMetricFiltersOutput, bool) bool) error { + return c.DescribeMetricFiltersPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// DescribeMetricFiltersPagesWithContext same as DescribeMetricFiltersPages 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 *CloudWatchLogs) DescribeMetricFiltersPagesWithContext(ctx aws.Context, input *DescribeMetricFiltersInput, fn func(*DescribeMetricFiltersOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *DescribeMetricFiltersInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeMetricFiltersRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*DescribeMetricFiltersOutput), !p.HasNextPage()) + } + return p.Err() } const opDescribeSubscriptionFilters = "DescribeSubscriptionFilters" @@ -1376,8 +1701,23 @@ func (c *CloudWatchLogs) DescribeSubscriptionFiltersRequest(input *DescribeSubsc // Please also see https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/DescribeSubscriptionFilters func (c *CloudWatchLogs) DescribeSubscriptionFilters(input *DescribeSubscriptionFiltersInput) (*DescribeSubscriptionFiltersOutput, error) { req, out := c.DescribeSubscriptionFiltersRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeSubscriptionFiltersWithContext is the same as DescribeSubscriptionFilters with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeSubscriptionFilters 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 *CloudWatchLogs) DescribeSubscriptionFiltersWithContext(ctx aws.Context, input *DescribeSubscriptionFiltersInput, opts ...request.Option) (*DescribeSubscriptionFiltersOutput, error) { + req, out := c.DescribeSubscriptionFiltersRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // DescribeSubscriptionFiltersPages iterates over the pages of a DescribeSubscriptionFilters operation, @@ -1397,12 +1737,37 @@ func (c *CloudWatchLogs) DescribeSubscriptionFilters(input *DescribeSubscription // return pageNum <= 3 // }) // -func (c *CloudWatchLogs) DescribeSubscriptionFiltersPages(input *DescribeSubscriptionFiltersInput, fn func(p *DescribeSubscriptionFiltersOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.DescribeSubscriptionFiltersRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*DescribeSubscriptionFiltersOutput), lastPage) - }) +func (c *CloudWatchLogs) DescribeSubscriptionFiltersPages(input *DescribeSubscriptionFiltersInput, fn func(*DescribeSubscriptionFiltersOutput, bool) bool) error { + return c.DescribeSubscriptionFiltersPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// DescribeSubscriptionFiltersPagesWithContext same as DescribeSubscriptionFiltersPages 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 *CloudWatchLogs) DescribeSubscriptionFiltersPagesWithContext(ctx aws.Context, input *DescribeSubscriptionFiltersInput, fn func(*DescribeSubscriptionFiltersOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *DescribeSubscriptionFiltersInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeSubscriptionFiltersRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*DescribeSubscriptionFiltersOutput), !p.HasNextPage()) + } + return p.Err() } const opFilterLogEvents = "FilterLogEvents" @@ -1486,8 +1851,23 @@ func (c *CloudWatchLogs) FilterLogEventsRequest(input *FilterLogEventsInput) (re // Please also see https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/FilterLogEvents func (c *CloudWatchLogs) FilterLogEvents(input *FilterLogEventsInput) (*FilterLogEventsOutput, error) { req, out := c.FilterLogEventsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// FilterLogEventsWithContext is the same as FilterLogEvents with the addition of +// the ability to pass a context and additional request options. +// +// See FilterLogEvents 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 *CloudWatchLogs) FilterLogEventsWithContext(ctx aws.Context, input *FilterLogEventsInput, opts ...request.Option) (*FilterLogEventsOutput, error) { + req, out := c.FilterLogEventsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // FilterLogEventsPages iterates over the pages of a FilterLogEvents operation, @@ -1507,12 +1887,37 @@ func (c *CloudWatchLogs) FilterLogEvents(input *FilterLogEventsInput) (*FilterLo // return pageNum <= 3 // }) // -func (c *CloudWatchLogs) FilterLogEventsPages(input *FilterLogEventsInput, fn func(p *FilterLogEventsOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.FilterLogEventsRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*FilterLogEventsOutput), lastPage) - }) +func (c *CloudWatchLogs) FilterLogEventsPages(input *FilterLogEventsInput, fn func(*FilterLogEventsOutput, bool) bool) error { + return c.FilterLogEventsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// FilterLogEventsPagesWithContext same as FilterLogEventsPages 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 *CloudWatchLogs) FilterLogEventsPagesWithContext(ctx aws.Context, input *FilterLogEventsInput, fn func(*FilterLogEventsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *FilterLogEventsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.FilterLogEventsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*FilterLogEventsOutput), !p.HasNextPage()) + } + return p.Err() } const opGetLogEvents = "GetLogEvents" @@ -1594,8 +1999,23 @@ func (c *CloudWatchLogs) GetLogEventsRequest(input *GetLogEventsInput) (req *req // Please also see https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/GetLogEvents func (c *CloudWatchLogs) GetLogEvents(input *GetLogEventsInput) (*GetLogEventsOutput, error) { req, out := c.GetLogEventsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetLogEventsWithContext is the same as GetLogEvents with the addition of +// the ability to pass a context and additional request options. +// +// See GetLogEvents 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 *CloudWatchLogs) GetLogEventsWithContext(ctx aws.Context, input *GetLogEventsInput, opts ...request.Option) (*GetLogEventsOutput, error) { + req, out := c.GetLogEventsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // GetLogEventsPages iterates over the pages of a GetLogEvents operation, @@ -1615,12 +2035,37 @@ func (c *CloudWatchLogs) GetLogEvents(input *GetLogEventsInput) (*GetLogEventsOu // return pageNum <= 3 // }) // -func (c *CloudWatchLogs) GetLogEventsPages(input *GetLogEventsInput, fn func(p *GetLogEventsOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.GetLogEventsRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*GetLogEventsOutput), lastPage) - }) +func (c *CloudWatchLogs) GetLogEventsPages(input *GetLogEventsInput, fn func(*GetLogEventsOutput, bool) bool) error { + return c.GetLogEventsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// GetLogEventsPagesWithContext same as GetLogEventsPages 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 *CloudWatchLogs) GetLogEventsPagesWithContext(ctx aws.Context, input *GetLogEventsInput, fn func(*GetLogEventsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *GetLogEventsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.GetLogEventsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*GetLogEventsOutput), !p.HasNextPage()) + } + return p.Err() } const opListTagsLogGroup = "ListTagsLogGroup" @@ -1689,8 +2134,23 @@ func (c *CloudWatchLogs) ListTagsLogGroupRequest(input *ListTagsLogGroupInput) ( // Please also see https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/ListTagsLogGroup func (c *CloudWatchLogs) ListTagsLogGroup(input *ListTagsLogGroupInput) (*ListTagsLogGroupOutput, error) { req, out := c.ListTagsLogGroupRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListTagsLogGroupWithContext is the same as ListTagsLogGroup with the addition of +// the ability to pass a context and additional request options. +// +// See ListTagsLogGroup 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 *CloudWatchLogs) ListTagsLogGroupWithContext(ctx aws.Context, input *ListTagsLogGroupInput, opts ...request.Option) (*ListTagsLogGroupOutput, error) { + req, out := c.ListTagsLogGroupRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opPutDestination = "PutDestination" @@ -1770,8 +2230,23 @@ func (c *CloudWatchLogs) PutDestinationRequest(input *PutDestinationInput) (req // Please also see https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/PutDestination func (c *CloudWatchLogs) PutDestination(input *PutDestinationInput) (*PutDestinationOutput, error) { req, out := c.PutDestinationRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// PutDestinationWithContext is the same as PutDestination with the addition of +// the ability to pass a context and additional request options. +// +// See PutDestination 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 *CloudWatchLogs) PutDestinationWithContext(ctx aws.Context, input *PutDestinationInput, opts ...request.Option) (*PutDestinationOutput, error) { + req, out := c.PutDestinationRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opPutDestinationPolicy = "PutDestinationPolicy" @@ -1846,8 +2321,23 @@ func (c *CloudWatchLogs) PutDestinationPolicyRequest(input *PutDestinationPolicy // Please also see https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/PutDestinationPolicy func (c *CloudWatchLogs) PutDestinationPolicy(input *PutDestinationPolicyInput) (*PutDestinationPolicyOutput, error) { req, out := c.PutDestinationPolicyRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// PutDestinationPolicyWithContext is the same as PutDestinationPolicy with the addition of +// the ability to pass a context and additional request options. +// +// See PutDestinationPolicy 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 *CloudWatchLogs) PutDestinationPolicyWithContext(ctx aws.Context, input *PutDestinationPolicyInput, opts ...request.Option) (*PutDestinationPolicyOutput, error) { + req, out := c.PutDestinationPolicyRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opPutLogEvents = "PutLogEvents" @@ -1948,8 +2438,23 @@ func (c *CloudWatchLogs) PutLogEventsRequest(input *PutLogEventsInput) (req *req // Please also see https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/PutLogEvents func (c *CloudWatchLogs) PutLogEvents(input *PutLogEventsInput) (*PutLogEventsOutput, error) { req, out := c.PutLogEventsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// PutLogEventsWithContext is the same as PutLogEvents with the addition of +// the ability to pass a context and additional request options. +// +// See PutLogEvents 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 *CloudWatchLogs) PutLogEventsWithContext(ctx aws.Context, input *PutLogEventsInput, opts ...request.Option) (*PutLogEventsOutput, error) { + req, out := c.PutLogEventsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opPutMetricFilter = "PutMetricFilter" @@ -2032,8 +2537,23 @@ func (c *CloudWatchLogs) PutMetricFilterRequest(input *PutMetricFilterInput) (re // Please also see https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/PutMetricFilter func (c *CloudWatchLogs) PutMetricFilter(input *PutMetricFilterInput) (*PutMetricFilterOutput, error) { req, out := c.PutMetricFilterRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// PutMetricFilterWithContext is the same as PutMetricFilter with the addition of +// the ability to pass a context and additional request options. +// +// See PutMetricFilter 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 *CloudWatchLogs) PutMetricFilterWithContext(ctx aws.Context, input *PutMetricFilterInput, opts ...request.Option) (*PutMetricFilterOutput, error) { + req, out := c.PutMetricFilterRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opPutRetentionPolicy = "PutRetentionPolicy" @@ -2110,8 +2630,23 @@ func (c *CloudWatchLogs) PutRetentionPolicyRequest(input *PutRetentionPolicyInpu // Please also see https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/PutRetentionPolicy func (c *CloudWatchLogs) PutRetentionPolicy(input *PutRetentionPolicyInput) (*PutRetentionPolicyOutput, error) { req, out := c.PutRetentionPolicyRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// PutRetentionPolicyWithContext is the same as PutRetentionPolicy with the addition of +// the ability to pass a context and additional request options. +// +// See PutRetentionPolicy 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 *CloudWatchLogs) PutRetentionPolicyWithContext(ctx aws.Context, input *PutRetentionPolicyInput, opts ...request.Option) (*PutRetentionPolicyOutput, error) { + req, out := c.PutRetentionPolicyRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opPutSubscriptionFilter = "PutSubscriptionFilter" @@ -2206,8 +2741,23 @@ func (c *CloudWatchLogs) PutSubscriptionFilterRequest(input *PutSubscriptionFilt // Please also see https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/PutSubscriptionFilter func (c *CloudWatchLogs) PutSubscriptionFilter(input *PutSubscriptionFilterInput) (*PutSubscriptionFilterOutput, error) { req, out := c.PutSubscriptionFilterRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// PutSubscriptionFilterWithContext is the same as PutSubscriptionFilter with the addition of +// the ability to pass a context and additional request options. +// +// See PutSubscriptionFilter 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 *CloudWatchLogs) PutSubscriptionFilterWithContext(ctx aws.Context, input *PutSubscriptionFilterInput, opts ...request.Option) (*PutSubscriptionFilterOutput, error) { + req, out := c.PutSubscriptionFilterRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opTagLogGroup = "TagLogGroup" @@ -2283,8 +2833,23 @@ func (c *CloudWatchLogs) TagLogGroupRequest(input *TagLogGroupInput) (req *reque // Please also see https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/TagLogGroup func (c *CloudWatchLogs) TagLogGroup(input *TagLogGroupInput) (*TagLogGroupOutput, error) { req, out := c.TagLogGroupRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// TagLogGroupWithContext is the same as TagLogGroup with the addition of +// the ability to pass a context and additional request options. +// +// See TagLogGroup 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 *CloudWatchLogs) TagLogGroupWithContext(ctx aws.Context, input *TagLogGroupInput, opts ...request.Option) (*TagLogGroupOutput, error) { + req, out := c.TagLogGroupRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opTestMetricFilter = "TestMetricFilter" @@ -2353,8 +2918,23 @@ func (c *CloudWatchLogs) TestMetricFilterRequest(input *TestMetricFilterInput) ( // Please also see https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/TestMetricFilter func (c *CloudWatchLogs) TestMetricFilter(input *TestMetricFilterInput) (*TestMetricFilterOutput, error) { req, out := c.TestMetricFilterRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// TestMetricFilterWithContext is the same as TestMetricFilter with the addition of +// the ability to pass a context and additional request options. +// +// See TestMetricFilter 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 *CloudWatchLogs) TestMetricFilterWithContext(ctx aws.Context, input *TestMetricFilterInput, opts ...request.Option) (*TestMetricFilterOutput, error) { + req, out := c.TestMetricFilterRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opUntagLogGroup = "UntagLogGroup" @@ -2423,8 +3003,23 @@ func (c *CloudWatchLogs) UntagLogGroupRequest(input *UntagLogGroupInput) (req *r // Please also see https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/UntagLogGroup func (c *CloudWatchLogs) UntagLogGroup(input *UntagLogGroupInput) (*UntagLogGroupOutput, error) { req, out := c.UntagLogGroupRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// UntagLogGroupWithContext is the same as UntagLogGroup with the addition of +// the ability to pass a context and additional request options. +// +// See UntagLogGroup 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 *CloudWatchLogs) UntagLogGroupWithContext(ctx aws.Context, input *UntagLogGroupInput, opts ...request.Option) (*UntagLogGroupOutput, error) { + req, out := c.UntagLogGroupRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // Please also see https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/CancelExportTaskRequest diff --git a/vendor/github.com/aws/aws-sdk-go/service/cloudwatchlogs/doc.go b/vendor/github.com/aws/aws-sdk-go/service/cloudwatchlogs/doc.go new file mode 100644 index 000000000..b8c406919 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/service/cloudwatchlogs/doc.go @@ -0,0 +1,109 @@ +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. + +// Package cloudwatchlogs provides the client and types for making API +// requests to Amazon CloudWatch Logs. +// +// You can use Amazon CloudWatch Logs to monitor, store, and access your log +// files from EC2 instances, Amazon CloudTrail, or other sources. You can then +// retrieve the associated log data from CloudWatch Logs using the Amazon CloudWatch +// console, the CloudWatch Logs commands in the AWS CLI, the CloudWatch Logs +// API, or the CloudWatch Logs SDK. +// +// You can use CloudWatch Logs to: +// +// * Monitor Logs from Amazon EC2 Instances in Real-time: You can use CloudWatch +// Logs to monitor applications and systems using log data. For example, +// CloudWatch Logs can track the number of errors that occur in your application +// logs and send you a notification whenever the rate of errors exceeds a +// threshold you specify. CloudWatch Logs uses your log data for monitoring; +// so, no code changes are required. For example, you can monitor application +// logs for specific literal terms (such as "NullReferenceException") or +// count the number of occurrences of a literal term at a particular position +// in log data (such as "404" status codes in an Apache access log). When +// the term you are searching for is found, CloudWatch Logs reports the data +// to a Amazon CloudWatch metric that you specify. +// +// * Monitor Amazon CloudTrail Logged Events: You can create alarms in Amazon +// CloudWatch and receive notifications of particular API activity as captured +// by CloudTrail and use the notification to perform troubleshooting. +// +// * Archive Log Data: You can use CloudWatch Logs to store your log data +// in highly durable storage. You can change the log retention setting so +// that any log events older than this setting are automatically deleted. +// The CloudWatch Logs agent makes it easy to quickly send both rotated and +// non-rotated log data off of a host and into the log service. You can then +// access the raw log data when you need it. +// +// See https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28 for more information on this service. +// +// See cloudwatchlogs package documentation for more information. +// https://docs.aws.amazon.com/sdk-for-go/api/service/cloudwatchlogs/ +// +// Using the Client +// +// To use the client for Amazon CloudWatch Logs you will first need +// to create a new instance of it. +// +// When creating a client for an AWS service you'll first need to have a Session +// already created. The Session provides configuration that can be shared +// between multiple service clients. Additional configuration can be applied to +// the Session and service's client when they are constructed. The aws package's +// Config type contains several fields such as Region for the AWS Region the +// client should make API requests too. The optional Config value can be provided +// as the variadic argument for Sessions and client creation. +// +// Once the service's client is created you can use it to make API requests the +// AWS service. These clients are safe to use concurrently. +// +// // Create a session to share configuration, and load external configuration. +// sess := session.Must(session.NewSession()) +// +// // Create the service's client with the session. +// svc := cloudwatchlogs.New(sess) +// +// See the SDK's documentation for more information on how to use service clients. +// https://docs.aws.amazon.com/sdk-for-go/api/ +// +// See aws package's Config type for more information on configuration options. +// https://docs.aws.amazon.com/sdk-for-go/api/aws/#Config +// +// See the Amazon CloudWatch Logs client CloudWatchLogs for more +// information on creating the service's client. +// https://docs.aws.amazon.com/sdk-for-go/api/service/cloudwatchlogs/#New +// +// Once the client is created you can make an API request to the service. +// Each API method takes a input parameter, and returns the service response +// and an error. +// +// The API method will document which error codes the service can be returned +// by the operation if the service models the API operation's errors. These +// errors will also be available as const strings prefixed with "ErrCode". +// +// result, err := svc.CancelExportTask(params) +// if err != nil { +// // Cast err to awserr.Error to handle specific error codes. +// aerr, ok := err.(awserr.Error) +// if ok && aerr.Code() == { +// // Specific error code handling +// } +// return err +// } +// +// fmt.Println("CancelExportTask result:") +// fmt.Println(result) +// +// Using the Client with Context +// +// The service's client also provides methods to make API requests with a Context +// value. This allows you to control the timeout, and cancellation of pending +// requests. These methods also take request Option as variadic parameter to apply +// additional configuration to the API request. +// +// ctx := context.Background() +// +// result, err := svc.CancelExportTaskWithContext(ctx, params) +// +// See the request package documentation for more information on using Context pattern +// with the SDK. +// https://docs.aws.amazon.com/sdk-for-go/api/aws/request/ +package cloudwatchlogs diff --git a/vendor/github.com/aws/aws-sdk-go/service/cloudwatchlogs/errors.go b/vendor/github.com/aws/aws-sdk-go/service/cloudwatchlogs/errors.go index de1b3fd9d..772141f53 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/cloudwatchlogs/errors.go +++ b/vendor/github.com/aws/aws-sdk-go/service/cloudwatchlogs/errors.go @@ -1,4 +1,4 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. package cloudwatchlogs diff --git a/vendor/github.com/aws/aws-sdk-go/service/cloudwatchlogs/service.go b/vendor/github.com/aws/aws-sdk-go/service/cloudwatchlogs/service.go index e161f962b..8e6094d58 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/cloudwatchlogs/service.go +++ b/vendor/github.com/aws/aws-sdk-go/service/cloudwatchlogs/service.go @@ -1,4 +1,4 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. package cloudwatchlogs @@ -11,39 +11,12 @@ import ( "github.com/aws/aws-sdk-go/private/protocol/jsonrpc" ) -// You can use Amazon CloudWatch Logs to monitor, store, and access your log -// files from EC2 instances, Amazon CloudTrail, or other sources. You can then -// retrieve the associated log data from CloudWatch Logs using the Amazon CloudWatch -// console, the CloudWatch Logs commands in the AWS CLI, the CloudWatch Logs -// API, or the CloudWatch Logs SDK. +// CloudWatchLogs provides the API operation methods for making requests to +// Amazon CloudWatch Logs. See this package's package overview docs +// for details on the service. // -// You can use CloudWatch Logs to: -// -// * Monitor Logs from Amazon EC2 Instances in Real-time: You can use CloudWatch -// Logs to monitor applications and systems using log data. For example, -// CloudWatch Logs can track the number of errors that occur in your application -// logs and send you a notification whenever the rate of errors exceeds a -// threshold you specify. CloudWatch Logs uses your log data for monitoring; -// so, no code changes are required. For example, you can monitor application -// logs for specific literal terms (such as "NullReferenceException") or -// count the number of occurrences of a literal term at a particular position -// in log data (such as "404" status codes in an Apache access log). When -// the term you are searching for is found, CloudWatch Logs reports the data -// to a Amazon CloudWatch metric that you specify. -// -// * Monitor Amazon CloudTrail Logged Events: You can create alarms in Amazon -// CloudWatch and receive notifications of particular API activity as captured -// by CloudTrail and use the notification to perform troubleshooting. -// -// * Archive Log Data: You can use CloudWatch Logs to store your log data -// in highly durable storage. You can change the log retention setting so -// that any log events older than this setting are automatically deleted. -// The CloudWatch Logs agent makes it easy to quickly send both rotated and -// non-rotated log data off of a host and into the log service. You can then -// access the raw log data when you need it. -// The service client's operations are safe to be used concurrently. -// It is not safe to mutate any of the client's properties though. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28 +// CloudWatchLogs methods are safe to use concurrently. It is not safe to +// modify mutate any of the struct's properties though. type CloudWatchLogs struct { *client.Client } diff --git a/vendor/github.com/aws/aws-sdk-go/service/codebuild/api.go b/vendor/github.com/aws/aws-sdk-go/service/codebuild/api.go index ebef335d1..79c191020 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/codebuild/api.go +++ b/vendor/github.com/aws/aws-sdk-go/service/codebuild/api.go @@ -1,12 +1,12 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. -// Package codebuild provides a client for AWS CodeBuild. package codebuild import ( "fmt" "time" + "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awsutil" "github.com/aws/aws-sdk-go/aws/request" ) @@ -72,8 +72,23 @@ func (c *CodeBuild) BatchGetBuildsRequest(input *BatchGetBuildsInput) (req *requ // Please also see https://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/BatchGetBuilds func (c *CodeBuild) BatchGetBuilds(input *BatchGetBuildsInput) (*BatchGetBuildsOutput, error) { req, out := c.BatchGetBuildsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// BatchGetBuildsWithContext is the same as BatchGetBuilds with the addition of +// the ability to pass a context and additional request options. +// +// See BatchGetBuilds 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 *CodeBuild) BatchGetBuildsWithContext(ctx aws.Context, input *BatchGetBuildsInput, opts ...request.Option) (*BatchGetBuildsOutput, error) { + req, out := c.BatchGetBuildsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opBatchGetProjects = "BatchGetProjects" @@ -137,8 +152,23 @@ func (c *CodeBuild) BatchGetProjectsRequest(input *BatchGetProjectsInput) (req * // Please also see https://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/BatchGetProjects func (c *CodeBuild) BatchGetProjects(input *BatchGetProjectsInput) (*BatchGetProjectsOutput, error) { req, out := c.BatchGetProjectsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// BatchGetProjectsWithContext is the same as BatchGetProjects with the addition of +// the ability to pass a context and additional request options. +// +// See BatchGetProjects 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 *CodeBuild) BatchGetProjectsWithContext(ctx aws.Context, input *BatchGetProjectsInput, opts ...request.Option) (*BatchGetProjectsOutput, error) { + req, out := c.BatchGetProjectsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateProject = "CreateProject" @@ -209,8 +239,23 @@ func (c *CodeBuild) CreateProjectRequest(input *CreateProjectInput) (req *reques // Please also see https://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/CreateProject func (c *CodeBuild) CreateProject(input *CreateProjectInput) (*CreateProjectOutput, error) { req, out := c.CreateProjectRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateProjectWithContext is the same as CreateProject with the addition of +// the ability to pass a context and additional request options. +// +// See CreateProject 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 *CodeBuild) CreateProjectWithContext(ctx aws.Context, input *CreateProjectInput, opts ...request.Option) (*CreateProjectOutput, error) { + req, out := c.CreateProjectRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteProject = "DeleteProject" @@ -274,8 +319,23 @@ func (c *CodeBuild) DeleteProjectRequest(input *DeleteProjectInput) (req *reques // Please also see https://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/DeleteProject func (c *CodeBuild) DeleteProject(input *DeleteProjectInput) (*DeleteProjectOutput, error) { req, out := c.DeleteProjectRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteProjectWithContext is the same as DeleteProject with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteProject 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 *CodeBuild) DeleteProjectWithContext(ctx aws.Context, input *DeleteProjectInput, opts ...request.Option) (*DeleteProjectOutput, error) { + req, out := c.DeleteProjectRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opListBuilds = "ListBuilds" @@ -339,8 +399,23 @@ func (c *CodeBuild) ListBuildsRequest(input *ListBuildsInput) (req *request.Requ // Please also see https://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/ListBuilds func (c *CodeBuild) ListBuilds(input *ListBuildsInput) (*ListBuildsOutput, error) { req, out := c.ListBuildsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListBuildsWithContext is the same as ListBuilds with the addition of +// the ability to pass a context and additional request options. +// +// See ListBuilds 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 *CodeBuild) ListBuildsWithContext(ctx aws.Context, input *ListBuildsInput, opts ...request.Option) (*ListBuildsOutput, error) { + req, out := c.ListBuildsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opListBuildsForProject = "ListBuildsForProject" @@ -408,8 +483,23 @@ func (c *CodeBuild) ListBuildsForProjectRequest(input *ListBuildsForProjectInput // Please also see https://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/ListBuildsForProject func (c *CodeBuild) ListBuildsForProject(input *ListBuildsForProjectInput) (*ListBuildsForProjectOutput, error) { req, out := c.ListBuildsForProjectRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListBuildsForProjectWithContext is the same as ListBuildsForProject with the addition of +// the ability to pass a context and additional request options. +// +// See ListBuildsForProject 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 *CodeBuild) ListBuildsForProjectWithContext(ctx aws.Context, input *ListBuildsForProjectInput, opts ...request.Option) (*ListBuildsForProjectOutput, error) { + req, out := c.ListBuildsForProjectRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opListCuratedEnvironmentImages = "ListCuratedEnvironmentImages" @@ -468,8 +558,23 @@ func (c *CodeBuild) ListCuratedEnvironmentImagesRequest(input *ListCuratedEnviro // Please also see https://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/ListCuratedEnvironmentImages func (c *CodeBuild) ListCuratedEnvironmentImages(input *ListCuratedEnvironmentImagesInput) (*ListCuratedEnvironmentImagesOutput, error) { req, out := c.ListCuratedEnvironmentImagesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListCuratedEnvironmentImagesWithContext is the same as ListCuratedEnvironmentImages with the addition of +// the ability to pass a context and additional request options. +// +// See ListCuratedEnvironmentImages 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 *CodeBuild) ListCuratedEnvironmentImagesWithContext(ctx aws.Context, input *ListCuratedEnvironmentImagesInput, opts ...request.Option) (*ListCuratedEnvironmentImagesOutput, error) { + req, out := c.ListCuratedEnvironmentImagesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opListProjects = "ListProjects" @@ -534,8 +639,23 @@ func (c *CodeBuild) ListProjectsRequest(input *ListProjectsInput) (req *request. // Please also see https://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/ListProjects func (c *CodeBuild) ListProjects(input *ListProjectsInput) (*ListProjectsOutput, error) { req, out := c.ListProjectsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListProjectsWithContext is the same as ListProjects with the addition of +// the ability to pass a context and additional request options. +// +// See ListProjects 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 *CodeBuild) ListProjectsWithContext(ctx aws.Context, input *ListProjectsInput, opts ...request.Option) (*ListProjectsOutput, error) { + req, out := c.ListProjectsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opStartBuild = "StartBuild" @@ -605,8 +725,23 @@ func (c *CodeBuild) StartBuildRequest(input *StartBuildInput) (req *request.Requ // Please also see https://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/StartBuild func (c *CodeBuild) StartBuild(input *StartBuildInput) (*StartBuildOutput, error) { req, out := c.StartBuildRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// StartBuildWithContext is the same as StartBuild with the addition of +// the ability to pass a context and additional request options. +// +// See StartBuild 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 *CodeBuild) StartBuildWithContext(ctx aws.Context, input *StartBuildInput, opts ...request.Option) (*StartBuildOutput, error) { + req, out := c.StartBuildRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opStopBuild = "StopBuild" @@ -673,8 +808,23 @@ func (c *CodeBuild) StopBuildRequest(input *StopBuildInput) (req *request.Reques // Please also see https://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/StopBuild func (c *CodeBuild) StopBuild(input *StopBuildInput) (*StopBuildOutput, error) { req, out := c.StopBuildRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// StopBuildWithContext is the same as StopBuild with the addition of +// the ability to pass a context and additional request options. +// +// See StopBuild 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 *CodeBuild) StopBuildWithContext(ctx aws.Context, input *StopBuildInput, opts ...request.Option) (*StopBuildOutput, error) { + req, out := c.StopBuildRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opUpdateProject = "UpdateProject" @@ -741,8 +891,23 @@ func (c *CodeBuild) UpdateProjectRequest(input *UpdateProjectInput) (req *reques // Please also see https://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/UpdateProject func (c *CodeBuild) UpdateProject(input *UpdateProjectInput) (*UpdateProjectOutput, error) { req, out := c.UpdateProjectRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// UpdateProjectWithContext is the same as UpdateProject with the addition of +// the ability to pass a context and additional request options. +// +// See UpdateProject 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 *CodeBuild) UpdateProjectWithContext(ctx aws.Context, input *UpdateProjectInput, opts ...request.Option) (*UpdateProjectOutput, error) { + req, out := c.UpdateProjectRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // Please also see https://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/BatchGetBuildsInput @@ -2505,14 +2670,15 @@ type ProjectSource struct { // bucket, the path to the ZIP file that contains the source code (for example, // bucket-name/path/to/object-name.zip) // - // * For source code in a GitHub repository, instead of specifying a value - // here, you connect your AWS account to your GitHub account. To do this, - // use the AWS CodeBuild console to begin creating a build project, and follow - // the on-screen instructions to complete the connection. (After you have - // connected to your GitHub account, you do not need to finish creating the - // build project, and you may then leave the AWS CodeBuild console.) To instruct - // AWS CodeBuild to then use this connection, in the source object, set the - // auth object's type value to OAUTH. + // * For source code in a GitHub repository, the HTTPS clone URL to the repository + // that contains the source and the build spec. Also, you must connect your + // AWS account to your GitHub account. To do this, use the AWS CodeBuild + // console to begin creating a build project, and follow the on-screen instructions + // to complete the connection. (After you have connected to your GitHub account, + // you do not need to finish creating the build project, and you may then + // leave the AWS CodeBuild console.) To instruct AWS CodeBuild to then use + // this connection, in the source object, set the auth object's type value + // to OAUTH. Location *string `locationName:"location" type:"string"` // The type of repository that contains the source code to be built. Valid values diff --git a/vendor/github.com/aws/aws-sdk-go/service/codebuild/doc.go b/vendor/github.com/aws/aws-sdk-go/service/codebuild/doc.go new file mode 100644 index 000000000..078a56f3d --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/service/codebuild/doc.go @@ -0,0 +1,123 @@ +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. + +// Package codebuild provides the client and types for making API +// requests to AWS CodeBuild. +// +// AWS CodeBuild is a fully managed build service in the cloud. AWS CodeBuild +// compiles your source code, runs unit tests, and produces artifacts that are +// ready to deploy. AWS CodeBuild eliminates the need to provision, manage, +// and scale your own build servers. It provides prepackaged build environments +// for the most popular programming languages and build tools, such as Apach +// Maven, Gradle, and more. You can also fully customize build environments +// in AWS CodeBuild to use your own build tools. AWS CodeBuild scales automatically +// to meet peak build requests, and you pay only for the build time you consume. +// For more information about AWS CodeBuild, see the AWS CodeBuild User Guide. +// +// AWS CodeBuild supports these operations: +// +// * BatchGetProjects: Gets information about one or more build projects. +// A build project defines how AWS CodeBuild will run a build. This includes +// information such as where to get the source code to build, the build environment +// to use, the build commands to run, and where to store the build output. +// A build environment represents a combination of operating system, programming +// language runtime, and tools that AWS CodeBuild will use to run a build. +// Also, you can add tags to build projects to help manage your resources +// and costs. +// +// * CreateProject: Creates a build project. +// +// * DeleteProject: Deletes a build project. +// +// * ListProjects: Gets a list of build project names, with each build project +// name representing a single build project. +// +// * UpdateProject: Changes the settings of an existing build project. +// +// * BatchGetBuilds: Gets information about one or more builds. +// +// * ListBuilds: Gets a list of build IDs, with each build ID representing +// a single build. +// +// * ListBuildsForProject: Gets a list of build IDs for the specified build +// project, with each build ID representing a single build. +// +// * StartBuild: Starts running a build. +// +// * StopBuild: Attempts to stop running a build. +// +// * ListCuratedEnvironmentImages: Gets information about Docker images that +// are managed by AWS CodeBuild. +// +// See https://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06 for more information on this service. +// +// See codebuild package documentation for more information. +// https://docs.aws.amazon.com/sdk-for-go/api/service/codebuild/ +// +// Using the Client +// +// To use the client for AWS CodeBuild you will first need +// to create a new instance of it. +// +// When creating a client for an AWS service you'll first need to have a Session +// already created. The Session provides configuration that can be shared +// between multiple service clients. Additional configuration can be applied to +// the Session and service's client when they are constructed. The aws package's +// Config type contains several fields such as Region for the AWS Region the +// client should make API requests too. The optional Config value can be provided +// as the variadic argument for Sessions and client creation. +// +// Once the service's client is created you can use it to make API requests the +// AWS service. These clients are safe to use concurrently. +// +// // Create a session to share configuration, and load external configuration. +// sess := session.Must(session.NewSession()) +// +// // Create the service's client with the session. +// svc := codebuild.New(sess) +// +// See the SDK's documentation for more information on how to use service clients. +// https://docs.aws.amazon.com/sdk-for-go/api/ +// +// See aws package's Config type for more information on configuration options. +// https://docs.aws.amazon.com/sdk-for-go/api/aws/#Config +// +// See the AWS CodeBuild client CodeBuild for more +// information on creating the service's client. +// https://docs.aws.amazon.com/sdk-for-go/api/service/codebuild/#New +// +// Once the client is created you can make an API request to the service. +// Each API method takes a input parameter, and returns the service response +// and an error. +// +// The API method will document which error codes the service can be returned +// by the operation if the service models the API operation's errors. These +// errors will also be available as const strings prefixed with "ErrCode". +// +// result, err := svc.BatchGetBuilds(params) +// if err != nil { +// // Cast err to awserr.Error to handle specific error codes. +// aerr, ok := err.(awserr.Error) +// if ok && aerr.Code() == { +// // Specific error code handling +// } +// return err +// } +// +// fmt.Println("BatchGetBuilds result:") +// fmt.Println(result) +// +// Using the Client with Context +// +// The service's client also provides methods to make API requests with a Context +// value. This allows you to control the timeout, and cancellation of pending +// requests. These methods also take request Option as variadic parameter to apply +// additional configuration to the API request. +// +// ctx := context.Background() +// +// result, err := svc.BatchGetBuildsWithContext(ctx, params) +// +// See the request package documentation for more information on using Context pattern +// with the SDK. +// https://docs.aws.amazon.com/sdk-for-go/api/aws/request/ +package codebuild diff --git a/vendor/github.com/aws/aws-sdk-go/service/codebuild/errors.go b/vendor/github.com/aws/aws-sdk-go/service/codebuild/errors.go index 88cfe77ad..2b91b700a 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/codebuild/errors.go +++ b/vendor/github.com/aws/aws-sdk-go/service/codebuild/errors.go @@ -1,4 +1,4 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. package codebuild diff --git a/vendor/github.com/aws/aws-sdk-go/service/codebuild/service.go b/vendor/github.com/aws/aws-sdk-go/service/codebuild/service.go index 41d6dd7e7..d45aed633 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/codebuild/service.go +++ b/vendor/github.com/aws/aws-sdk-go/service/codebuild/service.go @@ -1,4 +1,4 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. package codebuild @@ -11,53 +11,12 @@ import ( "github.com/aws/aws-sdk-go/private/protocol/jsonrpc" ) -// AWS CodeBuild is a fully managed build service in the cloud. AWS CodeBuild -// compiles your source code, runs unit tests, and produces artifacts that are -// ready to deploy. AWS CodeBuild eliminates the need to provision, manage, -// and scale your own build servers. It provides prepackaged build environments -// for the most popular programming languages and build tools, such as Apach -// Maven, Gradle, and more. You can also fully customize build environments -// in AWS CodeBuild to use your own build tools. AWS CodeBuild scales automatically -// to meet peak build requests, and you pay only for the build time you consume. -// For more information about AWS CodeBuild, see the AWS CodeBuild User Guide. +// CodeBuild provides the API operation methods for making requests to +// AWS CodeBuild. See this package's package overview docs +// for details on the service. // -// AWS CodeBuild supports these operations: -// -// * BatchGetProjects: Gets information about one or more build projects. -// A build project defines how AWS CodeBuild will run a build. This includes -// information such as where to get the source code to build, the build environment -// to use, the build commands to run, and where to store the build output. -// A build environment represents a combination of operating system, programming -// language runtime, and tools that AWS CodeBuild will use to run a build. -// Also, you can add tags to build projects to help manage your resources -// and costs. -// -// * CreateProject: Creates a build project. -// -// * DeleteProject: Deletes a build project. -// -// * ListProjects: Gets a list of build project names, with each build project -// name representing a single build project. -// -// * UpdateProject: Changes the settings of an existing build project. -// -// * BatchGetBuilds: Gets information about one or more builds. -// -// * ListBuilds: Gets a list of build IDs, with each build ID representing -// a single build. -// -// * ListBuildsForProject: Gets a list of build IDs for the specified build -// project, with each build ID representing a single build. -// -// * StartBuild: Starts running a build. -// -// * StopBuild: Attempts to stop running a build. -// -// * ListCuratedEnvironmentImages: Gets information about Docker images that -// are managed by AWS CodeBuild. -// The service client's operations are safe to be used concurrently. -// It is not safe to mutate any of the client's properties though. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06 +// CodeBuild methods are safe to use concurrently. It is not safe to +// modify mutate any of the struct's properties though. type CodeBuild struct { *client.Client } diff --git a/vendor/github.com/aws/aws-sdk-go/service/codecommit/api.go b/vendor/github.com/aws/aws-sdk-go/service/codecommit/api.go index 47ab5eab2..9e71917aa 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/codecommit/api.go +++ b/vendor/github.com/aws/aws-sdk-go/service/codecommit/api.go @@ -1,12 +1,12 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. -// Package codecommit provides a client for AWS CodeCommit. package codecommit import ( "fmt" "time" + "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awsutil" "github.com/aws/aws-sdk-go/aws/request" "github.com/aws/aws-sdk-go/private/protocol" @@ -106,8 +106,23 @@ func (c *CodeCommit) BatchGetRepositoriesRequest(input *BatchGetRepositoriesInpu // Please also see https://docs.aws.amazon.com/goto/WebAPI/codecommit-2015-04-13/BatchGetRepositories func (c *CodeCommit) BatchGetRepositories(input *BatchGetRepositoriesInput) (*BatchGetRepositoriesOutput, error) { req, out := c.BatchGetRepositoriesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// BatchGetRepositoriesWithContext is the same as BatchGetRepositories with the addition of +// the ability to pass a context and additional request options. +// +// See BatchGetRepositories 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 *CodeCommit) BatchGetRepositoriesWithContext(ctx aws.Context, input *BatchGetRepositoriesInput, opts ...request.Option) (*BatchGetRepositoriesOutput, error) { + req, out := c.BatchGetRepositoriesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateBranch = "CreateBranch" @@ -220,8 +235,23 @@ func (c *CodeCommit) CreateBranchRequest(input *CreateBranchInput) (req *request // Please also see https://docs.aws.amazon.com/goto/WebAPI/codecommit-2015-04-13/CreateBranch func (c *CodeCommit) CreateBranch(input *CreateBranchInput) (*CreateBranchOutput, error) { req, out := c.CreateBranchRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateBranchWithContext is the same as CreateBranch with the addition of +// the ability to pass a context and additional request options. +// +// See CreateBranch 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 *CodeCommit) CreateBranchWithContext(ctx aws.Context, input *CreateBranchInput, opts ...request.Option) (*CreateBranchOutput, error) { + req, out := c.CreateBranchRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateRepository = "CreateRepository" @@ -316,8 +346,23 @@ func (c *CodeCommit) CreateRepositoryRequest(input *CreateRepositoryInput) (req // Please also see https://docs.aws.amazon.com/goto/WebAPI/codecommit-2015-04-13/CreateRepository func (c *CodeCommit) CreateRepository(input *CreateRepositoryInput) (*CreateRepositoryOutput, error) { req, out := c.CreateRepositoryRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateRepositoryWithContext is the same as CreateRepository with the addition of +// the ability to pass a context and additional request options. +// +// See CreateRepository 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 *CodeCommit) CreateRepositoryWithContext(ctx aws.Context, input *CreateRepositoryInput, opts ...request.Option) (*CreateRepositoryOutput, error) { + req, out := c.CreateRepositoryRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteRepository = "DeleteRepository" @@ -408,8 +453,23 @@ func (c *CodeCommit) DeleteRepositoryRequest(input *DeleteRepositoryInput) (req // Please also see https://docs.aws.amazon.com/goto/WebAPI/codecommit-2015-04-13/DeleteRepository func (c *CodeCommit) DeleteRepository(input *DeleteRepositoryInput) (*DeleteRepositoryOutput, error) { req, out := c.DeleteRepositoryRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteRepositoryWithContext is the same as DeleteRepository with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteRepository 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 *CodeCommit) DeleteRepositoryWithContext(ctx aws.Context, input *DeleteRepositoryInput, opts ...request.Option) (*DeleteRepositoryOutput, error) { + req, out := c.DeleteRepositoryRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetBlob = "GetBlob" @@ -512,8 +572,23 @@ func (c *CodeCommit) GetBlobRequest(input *GetBlobInput) (req *request.Request, // Please also see https://docs.aws.amazon.com/goto/WebAPI/codecommit-2015-04-13/GetBlob func (c *CodeCommit) GetBlob(input *GetBlobInput) (*GetBlobOutput, error) { req, out := c.GetBlobRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetBlobWithContext is the same as GetBlob with the addition of +// the ability to pass a context and additional request options. +// +// See GetBlob 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 *CodeCommit) GetBlobWithContext(ctx aws.Context, input *GetBlobInput, opts ...request.Option) (*GetBlobOutput, error) { + req, out := c.GetBlobRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetBranch = "GetBranch" @@ -612,8 +687,23 @@ func (c *CodeCommit) GetBranchRequest(input *GetBranchInput) (req *request.Reque // Please also see https://docs.aws.amazon.com/goto/WebAPI/codecommit-2015-04-13/GetBranch func (c *CodeCommit) GetBranch(input *GetBranchInput) (*GetBranchOutput, error) { req, out := c.GetBranchRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetBranchWithContext is the same as GetBranch with the addition of +// the ability to pass a context and additional request options. +// +// See GetBranch 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 *CodeCommit) GetBranchWithContext(ctx aws.Context, input *GetBranchInput, opts ...request.Option) (*GetBranchOutput, error) { + req, out := c.GetBranchRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetCommit = "GetCommit" @@ -712,8 +802,23 @@ func (c *CodeCommit) GetCommitRequest(input *GetCommitInput) (req *request.Reque // Please also see https://docs.aws.amazon.com/goto/WebAPI/codecommit-2015-04-13/GetCommit func (c *CodeCommit) GetCommit(input *GetCommitInput) (*GetCommitOutput, error) { req, out := c.GetCommitRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetCommitWithContext is the same as GetCommit with the addition of +// the ability to pass a context and additional request options. +// +// See GetCommit 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 *CodeCommit) GetCommitWithContext(ctx aws.Context, input *GetCommitInput, opts ...request.Option) (*GetCommitOutput, error) { + req, out := c.GetCommitRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetDifferences = "GetDifferences" @@ -835,8 +940,23 @@ func (c *CodeCommit) GetDifferencesRequest(input *GetDifferencesInput) (req *req // Please also see https://docs.aws.amazon.com/goto/WebAPI/codecommit-2015-04-13/GetDifferences func (c *CodeCommit) GetDifferences(input *GetDifferencesInput) (*GetDifferencesOutput, error) { req, out := c.GetDifferencesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetDifferencesWithContext is the same as GetDifferences with the addition of +// the ability to pass a context and additional request options. +// +// See GetDifferences 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 *CodeCommit) GetDifferencesWithContext(ctx aws.Context, input *GetDifferencesInput, opts ...request.Option) (*GetDifferencesOutput, error) { + req, out := c.GetDifferencesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // GetDifferencesPages iterates over the pages of a GetDifferences operation, @@ -856,12 +976,37 @@ func (c *CodeCommit) GetDifferences(input *GetDifferencesInput) (*GetDifferences // return pageNum <= 3 // }) // -func (c *CodeCommit) GetDifferencesPages(input *GetDifferencesInput, fn func(p *GetDifferencesOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.GetDifferencesRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*GetDifferencesOutput), lastPage) - }) +func (c *CodeCommit) GetDifferencesPages(input *GetDifferencesInput, fn func(*GetDifferencesOutput, bool) bool) error { + return c.GetDifferencesPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// GetDifferencesPagesWithContext same as GetDifferencesPages 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 *CodeCommit) GetDifferencesPagesWithContext(ctx aws.Context, input *GetDifferencesInput, fn func(*GetDifferencesOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *GetDifferencesInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.GetDifferencesRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*GetDifferencesOutput), !p.HasNextPage()) + } + return p.Err() } const opGetRepository = "GetRepository" @@ -956,8 +1101,23 @@ func (c *CodeCommit) GetRepositoryRequest(input *GetRepositoryInput) (req *reque // Please also see https://docs.aws.amazon.com/goto/WebAPI/codecommit-2015-04-13/GetRepository func (c *CodeCommit) GetRepository(input *GetRepositoryInput) (*GetRepositoryOutput, error) { req, out := c.GetRepositoryRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetRepositoryWithContext is the same as GetRepository with the addition of +// the ability to pass a context and additional request options. +// +// See GetRepository 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 *CodeCommit) GetRepositoryWithContext(ctx aws.Context, input *GetRepositoryInput, opts ...request.Option) (*GetRepositoryOutput, error) { + req, out := c.GetRepositoryRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetRepositoryTriggers = "GetRepositoryTriggers" @@ -1046,8 +1206,23 @@ func (c *CodeCommit) GetRepositoryTriggersRequest(input *GetRepositoryTriggersIn // Please also see https://docs.aws.amazon.com/goto/WebAPI/codecommit-2015-04-13/GetRepositoryTriggers func (c *CodeCommit) GetRepositoryTriggers(input *GetRepositoryTriggersInput) (*GetRepositoryTriggersOutput, error) { req, out := c.GetRepositoryTriggersRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetRepositoryTriggersWithContext is the same as GetRepositoryTriggers with the addition of +// the ability to pass a context and additional request options. +// +// See GetRepositoryTriggers 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 *CodeCommit) GetRepositoryTriggersWithContext(ctx aws.Context, input *GetRepositoryTriggersInput, opts ...request.Option) (*GetRepositoryTriggersOutput, error) { + req, out := c.GetRepositoryTriggersRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opListBranches = "ListBranches" @@ -1145,8 +1320,23 @@ func (c *CodeCommit) ListBranchesRequest(input *ListBranchesInput) (req *request // Please also see https://docs.aws.amazon.com/goto/WebAPI/codecommit-2015-04-13/ListBranches func (c *CodeCommit) ListBranches(input *ListBranchesInput) (*ListBranchesOutput, error) { req, out := c.ListBranchesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListBranchesWithContext is the same as ListBranches with the addition of +// the ability to pass a context and additional request options. +// +// See ListBranches 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 *CodeCommit) ListBranchesWithContext(ctx aws.Context, input *ListBranchesInput, opts ...request.Option) (*ListBranchesOutput, error) { + req, out := c.ListBranchesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // ListBranchesPages iterates over the pages of a ListBranches operation, @@ -1166,12 +1356,37 @@ func (c *CodeCommit) ListBranches(input *ListBranchesInput) (*ListBranchesOutput // return pageNum <= 3 // }) // -func (c *CodeCommit) ListBranchesPages(input *ListBranchesInput, fn func(p *ListBranchesOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.ListBranchesRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*ListBranchesOutput), lastPage) - }) +func (c *CodeCommit) ListBranchesPages(input *ListBranchesInput, fn func(*ListBranchesOutput, bool) bool) error { + return c.ListBranchesPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListBranchesPagesWithContext same as ListBranchesPages 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 *CodeCommit) ListBranchesPagesWithContext(ctx aws.Context, input *ListBranchesInput, fn func(*ListBranchesOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListBranchesInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListBranchesRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*ListBranchesOutput), !p.HasNextPage()) + } + return p.Err() } const opListRepositories = "ListRepositories" @@ -1247,8 +1462,23 @@ func (c *CodeCommit) ListRepositoriesRequest(input *ListRepositoriesInput) (req // Please also see https://docs.aws.amazon.com/goto/WebAPI/codecommit-2015-04-13/ListRepositories func (c *CodeCommit) ListRepositories(input *ListRepositoriesInput) (*ListRepositoriesOutput, error) { req, out := c.ListRepositoriesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListRepositoriesWithContext is the same as ListRepositories with the addition of +// the ability to pass a context and additional request options. +// +// See ListRepositories 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 *CodeCommit) ListRepositoriesWithContext(ctx aws.Context, input *ListRepositoriesInput, opts ...request.Option) (*ListRepositoriesOutput, error) { + req, out := c.ListRepositoriesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // ListRepositoriesPages iterates over the pages of a ListRepositories operation, @@ -1268,12 +1498,37 @@ func (c *CodeCommit) ListRepositories(input *ListRepositoriesInput) (*ListReposi // return pageNum <= 3 // }) // -func (c *CodeCommit) ListRepositoriesPages(input *ListRepositoriesInput, fn func(p *ListRepositoriesOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.ListRepositoriesRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*ListRepositoriesOutput), lastPage) - }) +func (c *CodeCommit) ListRepositoriesPages(input *ListRepositoriesInput, fn func(*ListRepositoriesOutput, bool) bool) error { + return c.ListRepositoriesPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListRepositoriesPagesWithContext same as ListRepositoriesPages 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 *CodeCommit) ListRepositoriesPagesWithContext(ctx aws.Context, input *ListRepositoriesInput, fn func(*ListRepositoriesOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListRepositoriesInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListRepositoriesRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*ListRepositoriesOutput), !p.HasNextPage()) + } + return p.Err() } const opPutRepositoryTriggers = "PutRepositoryTriggers" @@ -1408,8 +1663,23 @@ func (c *CodeCommit) PutRepositoryTriggersRequest(input *PutRepositoryTriggersIn // Please also see https://docs.aws.amazon.com/goto/WebAPI/codecommit-2015-04-13/PutRepositoryTriggers func (c *CodeCommit) PutRepositoryTriggers(input *PutRepositoryTriggersInput) (*PutRepositoryTriggersOutput, error) { req, out := c.PutRepositoryTriggersRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// PutRepositoryTriggersWithContext is the same as PutRepositoryTriggers with the addition of +// the ability to pass a context and additional request options. +// +// See PutRepositoryTriggers 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 *CodeCommit) PutRepositoryTriggersWithContext(ctx aws.Context, input *PutRepositoryTriggersInput, opts ...request.Option) (*PutRepositoryTriggersOutput, error) { + req, out := c.PutRepositoryTriggersRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opTestRepositoryTriggers = "TestRepositoryTriggers" @@ -1546,8 +1816,23 @@ func (c *CodeCommit) TestRepositoryTriggersRequest(input *TestRepositoryTriggers // Please also see https://docs.aws.amazon.com/goto/WebAPI/codecommit-2015-04-13/TestRepositoryTriggers func (c *CodeCommit) TestRepositoryTriggers(input *TestRepositoryTriggersInput) (*TestRepositoryTriggersOutput, error) { req, out := c.TestRepositoryTriggersRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// TestRepositoryTriggersWithContext is the same as TestRepositoryTriggers with the addition of +// the ability to pass a context and additional request options. +// +// See TestRepositoryTriggers 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 *CodeCommit) TestRepositoryTriggersWithContext(ctx aws.Context, input *TestRepositoryTriggersInput, opts ...request.Option) (*TestRepositoryTriggersOutput, error) { + req, out := c.TestRepositoryTriggersRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opUpdateDefaultBranch = "UpdateDefaultBranch" @@ -1651,8 +1936,23 @@ func (c *CodeCommit) UpdateDefaultBranchRequest(input *UpdateDefaultBranchInput) // Please also see https://docs.aws.amazon.com/goto/WebAPI/codecommit-2015-04-13/UpdateDefaultBranch func (c *CodeCommit) UpdateDefaultBranch(input *UpdateDefaultBranchInput) (*UpdateDefaultBranchOutput, error) { req, out := c.UpdateDefaultBranchRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// UpdateDefaultBranchWithContext is the same as UpdateDefaultBranch with the addition of +// the ability to pass a context and additional request options. +// +// See UpdateDefaultBranch 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 *CodeCommit) UpdateDefaultBranchWithContext(ctx aws.Context, input *UpdateDefaultBranchInput, opts ...request.Option) (*UpdateDefaultBranchOutput, error) { + req, out := c.UpdateDefaultBranchRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opUpdateRepositoryDescription = "UpdateRepositoryDescription" @@ -1752,8 +2052,23 @@ func (c *CodeCommit) UpdateRepositoryDescriptionRequest(input *UpdateRepositoryD // Please also see https://docs.aws.amazon.com/goto/WebAPI/codecommit-2015-04-13/UpdateRepositoryDescription func (c *CodeCommit) UpdateRepositoryDescription(input *UpdateRepositoryDescriptionInput) (*UpdateRepositoryDescriptionOutput, error) { req, out := c.UpdateRepositoryDescriptionRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// UpdateRepositoryDescriptionWithContext is the same as UpdateRepositoryDescription with the addition of +// the ability to pass a context and additional request options. +// +// See UpdateRepositoryDescription 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 *CodeCommit) UpdateRepositoryDescriptionWithContext(ctx aws.Context, input *UpdateRepositoryDescriptionInput, opts ...request.Option) (*UpdateRepositoryDescriptionOutput, error) { + req, out := c.UpdateRepositoryDescriptionRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opUpdateRepositoryName = "UpdateRepositoryName" @@ -1837,8 +2152,23 @@ func (c *CodeCommit) UpdateRepositoryNameRequest(input *UpdateRepositoryNameInpu // Please also see https://docs.aws.amazon.com/goto/WebAPI/codecommit-2015-04-13/UpdateRepositoryName func (c *CodeCommit) UpdateRepositoryName(input *UpdateRepositoryNameInput) (*UpdateRepositoryNameOutput, error) { req, out := c.UpdateRepositoryNameRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// UpdateRepositoryNameWithContext is the same as UpdateRepositoryName with the addition of +// the ability to pass a context and additional request options. +// +// See UpdateRepositoryName 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 *CodeCommit) UpdateRepositoryNameWithContext(ctx aws.Context, input *UpdateRepositoryNameInput, opts ...request.Option) (*UpdateRepositoryNameOutput, error) { + req, out := c.UpdateRepositoryNameRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // Represents the input of a batch get repositories operation. diff --git a/vendor/github.com/aws/aws-sdk-go/service/codecommit/doc.go b/vendor/github.com/aws/aws-sdk-go/service/codecommit/doc.go new file mode 100644 index 000000000..fafa08c1d --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/service/codecommit/doc.go @@ -0,0 +1,141 @@ +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. + +// Package codecommit provides the client and types for making API +// requests to AWS CodeCommit. +// +// This is the AWS CodeCommit API Reference. This reference provides descriptions +// of the operations and data types for AWS CodeCommit API along with usage +// examples. +// +// You can use the AWS CodeCommit API to work with the following objects: +// +// Repositories, by calling the following: +// +// * BatchGetRepositories, which returns information about one or more repositories +// associated with your AWS account +// +// * CreateRepository, which creates an AWS CodeCommit repository +// +// * DeleteRepository, which deletes an AWS CodeCommit repository +// +// * GetRepository, which returns information about a specified repository +// +// * ListRepositories, which lists all AWS CodeCommit repositories associated +// with your AWS account +// +// * UpdateRepositoryDescription, which sets or updates the description of +// the repository +// +// * UpdateRepositoryName, which changes the name of the repository. If you +// change the name of a repository, no other users of that repository will +// be able to access it until you send them the new HTTPS or SSH URL to use. +// +// Branches, by calling the following: +// +// * CreateBranch, which creates a new branch in a specified repository +// +// * GetBranch, which returns information about a specified branch +// +// * ListBranches, which lists all branches for a specified repository +// +// * UpdateDefaultBranch, which changes the default branch for a repository +// +// Information about committed code in a repository, by calling the following: +// +// * GetBlob, which returns the base-64 encoded content of an individual +// Git blob object within a repository +// +// * GetCommit, which returns information about a commit, including commit +// messages and author and committer information +// +// * GetDifferences, which returns information about the differences in a +// valid commit specifier (such as a branch, tag, HEAD, commit ID or other +// fully qualified reference) +// +// Triggers, by calling the following: +// +// * GetRepositoryTriggers, which returns information about triggers configured +// for a repository +// +// * PutRepositoryTriggers, which replaces all triggers for a repository +// and can be used to create or delete triggers +// +// * TestRepositoryTriggers, which tests the functionality of a repository +// trigger by sending data to the trigger target +// +// For information about how to use AWS CodeCommit, see the AWS CodeCommit User +// Guide (http://docs.aws.amazon.com/codecommit/latest/userguide/welcome.html). +// +// See https://docs.aws.amazon.com/goto/WebAPI/codecommit-2015-04-13 for more information on this service. +// +// See codecommit package documentation for more information. +// https://docs.aws.amazon.com/sdk-for-go/api/service/codecommit/ +// +// Using the Client +// +// To use the client for AWS CodeCommit you will first need +// to create a new instance of it. +// +// When creating a client for an AWS service you'll first need to have a Session +// already created. The Session provides configuration that can be shared +// between multiple service clients. Additional configuration can be applied to +// the Session and service's client when they are constructed. The aws package's +// Config type contains several fields such as Region for the AWS Region the +// client should make API requests too. The optional Config value can be provided +// as the variadic argument for Sessions and client creation. +// +// Once the service's client is created you can use it to make API requests the +// AWS service. These clients are safe to use concurrently. +// +// // Create a session to share configuration, and load external configuration. +// sess := session.Must(session.NewSession()) +// +// // Create the service's client with the session. +// svc := codecommit.New(sess) +// +// See the SDK's documentation for more information on how to use service clients. +// https://docs.aws.amazon.com/sdk-for-go/api/ +// +// See aws package's Config type for more information on configuration options. +// https://docs.aws.amazon.com/sdk-for-go/api/aws/#Config +// +// See the AWS CodeCommit client CodeCommit for more +// information on creating the service's client. +// https://docs.aws.amazon.com/sdk-for-go/api/service/codecommit/#New +// +// Once the client is created you can make an API request to the service. +// Each API method takes a input parameter, and returns the service response +// and an error. +// +// The API method will document which error codes the service can be returned +// by the operation if the service models the API operation's errors. These +// errors will also be available as const strings prefixed with "ErrCode". +// +// result, err := svc.BatchGetRepositories(params) +// if err != nil { +// // Cast err to awserr.Error to handle specific error codes. +// aerr, ok := err.(awserr.Error) +// if ok && aerr.Code() == { +// // Specific error code handling +// } +// return err +// } +// +// fmt.Println("BatchGetRepositories result:") +// fmt.Println(result) +// +// Using the Client with Context +// +// The service's client also provides methods to make API requests with a Context +// value. This allows you to control the timeout, and cancellation of pending +// requests. These methods also take request Option as variadic parameter to apply +// additional configuration to the API request. +// +// ctx := context.Background() +// +// result, err := svc.BatchGetRepositoriesWithContext(ctx, params) +// +// See the request package documentation for more information on using Context pattern +// with the SDK. +// https://docs.aws.amazon.com/sdk-for-go/api/aws/request/ +package codecommit diff --git a/vendor/github.com/aws/aws-sdk-go/service/codecommit/errors.go b/vendor/github.com/aws/aws-sdk-go/service/codecommit/errors.go index 718d09dec..6200809f4 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/codecommit/errors.go +++ b/vendor/github.com/aws/aws-sdk-go/service/codecommit/errors.go @@ -1,4 +1,4 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. package codecommit diff --git a/vendor/github.com/aws/aws-sdk-go/service/codecommit/service.go b/vendor/github.com/aws/aws-sdk-go/service/codecommit/service.go index dd0b66613..cb25eaba7 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/codecommit/service.go +++ b/vendor/github.com/aws/aws-sdk-go/service/codecommit/service.go @@ -1,4 +1,4 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. package codecommit @@ -11,71 +11,12 @@ import ( "github.com/aws/aws-sdk-go/private/protocol/jsonrpc" ) -// This is the AWS CodeCommit API Reference. This reference provides descriptions -// of the operations and data types for AWS CodeCommit API along with usage -// examples. +// CodeCommit provides the API operation methods for making requests to +// AWS CodeCommit. See this package's package overview docs +// for details on the service. // -// You can use the AWS CodeCommit API to work with the following objects: -// -// Repositories, by calling the following: -// -// * BatchGetRepositories, which returns information about one or more repositories -// associated with your AWS account -// -// * CreateRepository, which creates an AWS CodeCommit repository -// -// * DeleteRepository, which deletes an AWS CodeCommit repository -// -// * GetRepository, which returns information about a specified repository -// -// * ListRepositories, which lists all AWS CodeCommit repositories associated -// with your AWS account -// -// * UpdateRepositoryDescription, which sets or updates the description of -// the repository -// -// * UpdateRepositoryName, which changes the name of the repository. If you -// change the name of a repository, no other users of that repository will -// be able to access it until you send them the new HTTPS or SSH URL to use. -// -// Branches, by calling the following: -// -// * CreateBranch, which creates a new branch in a specified repository -// -// * GetBranch, which returns information about a specified branch -// -// * ListBranches, which lists all branches for a specified repository -// -// * UpdateDefaultBranch, which changes the default branch for a repository -// -// Information about committed code in a repository, by calling the following: -// -// * GetBlob, which returns the base-64 encoded content of an individual -// Git blob object within a repository -// -// * GetCommit, which returns information about a commit, including commit -// messages and author and committer information -// -// * GetDifferences, which returns information about the differences in a -// valid commit specifier (such as a branch, tag, HEAD, commit ID or other -// fully qualified reference) -// -// Triggers, by calling the following: -// -// * GetRepositoryTriggers, which returns information about triggers configured -// for a repository -// -// * PutRepositoryTriggers, which replaces all triggers for a repository -// and can be used to create or delete triggers -// -// * TestRepositoryTriggers, which tests the functionality of a repository -// trigger by sending data to the trigger target -// -// For information about how to use AWS CodeCommit, see the AWS CodeCommit User -// Guide (http://docs.aws.amazon.com/codecommit/latest/userguide/welcome.html). -// The service client's operations are safe to be used concurrently. -// It is not safe to mutate any of the client's properties though. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/codecommit-2015-04-13 +// CodeCommit methods are safe to use concurrently. It is not safe to +// modify mutate any of the struct's properties though. type CodeCommit struct { *client.Client } diff --git a/vendor/github.com/aws/aws-sdk-go/service/codedeploy/api.go b/vendor/github.com/aws/aws-sdk-go/service/codedeploy/api.go index 1004323da..61da57561 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/codedeploy/api.go +++ b/vendor/github.com/aws/aws-sdk-go/service/codedeploy/api.go @@ -1,11 +1,11 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. -// Package codedeploy provides a client for AWS CodeDeploy. package codedeploy import ( "time" + "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awsutil" "github.com/aws/aws-sdk-go/aws/request" "github.com/aws/aws-sdk-go/private/protocol" @@ -91,8 +91,23 @@ func (c *CodeDeploy) AddTagsToOnPremisesInstancesRequest(input *AddTagsToOnPremi // Please also see https://docs.aws.amazon.com/goto/WebAPI/codedeploy-2014-10-06/AddTagsToOnPremisesInstances func (c *CodeDeploy) AddTagsToOnPremisesInstances(input *AddTagsToOnPremisesInstancesInput) (*AddTagsToOnPremisesInstancesOutput, error) { req, out := c.AddTagsToOnPremisesInstancesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// AddTagsToOnPremisesInstancesWithContext is the same as AddTagsToOnPremisesInstances with the addition of +// the ability to pass a context and additional request options. +// +// See AddTagsToOnPremisesInstances 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 *CodeDeploy) AddTagsToOnPremisesInstancesWithContext(ctx aws.Context, input *AddTagsToOnPremisesInstancesInput, opts ...request.Option) (*AddTagsToOnPremisesInstancesOutput, error) { + req, out := c.AddTagsToOnPremisesInstancesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opBatchGetApplicationRevisions = "BatchGetApplicationRevisions" @@ -171,8 +186,23 @@ func (c *CodeDeploy) BatchGetApplicationRevisionsRequest(input *BatchGetApplicat // Please also see https://docs.aws.amazon.com/goto/WebAPI/codedeploy-2014-10-06/BatchGetApplicationRevisions func (c *CodeDeploy) BatchGetApplicationRevisions(input *BatchGetApplicationRevisionsInput) (*BatchGetApplicationRevisionsOutput, error) { req, out := c.BatchGetApplicationRevisionsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// BatchGetApplicationRevisionsWithContext is the same as BatchGetApplicationRevisions with the addition of +// the ability to pass a context and additional request options. +// +// See BatchGetApplicationRevisions 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 *CodeDeploy) BatchGetApplicationRevisionsWithContext(ctx aws.Context, input *BatchGetApplicationRevisionsInput, opts ...request.Option) (*BatchGetApplicationRevisionsOutput, error) { + req, out := c.BatchGetApplicationRevisionsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opBatchGetApplications = "BatchGetApplications" @@ -245,8 +275,23 @@ func (c *CodeDeploy) BatchGetApplicationsRequest(input *BatchGetApplicationsInpu // Please also see https://docs.aws.amazon.com/goto/WebAPI/codedeploy-2014-10-06/BatchGetApplications func (c *CodeDeploy) BatchGetApplications(input *BatchGetApplicationsInput) (*BatchGetApplicationsOutput, error) { req, out := c.BatchGetApplicationsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// BatchGetApplicationsWithContext is the same as BatchGetApplications with the addition of +// the ability to pass a context and additional request options. +// +// See BatchGetApplications 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 *CodeDeploy) BatchGetApplicationsWithContext(ctx aws.Context, input *BatchGetApplicationsInput, opts ...request.Option) (*BatchGetApplicationsOutput, error) { + req, out := c.BatchGetApplicationsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opBatchGetDeploymentGroups = "BatchGetDeploymentGroups" @@ -325,8 +370,23 @@ func (c *CodeDeploy) BatchGetDeploymentGroupsRequest(input *BatchGetDeploymentGr // Please also see https://docs.aws.amazon.com/goto/WebAPI/codedeploy-2014-10-06/BatchGetDeploymentGroups func (c *CodeDeploy) BatchGetDeploymentGroups(input *BatchGetDeploymentGroupsInput) (*BatchGetDeploymentGroupsOutput, error) { req, out := c.BatchGetDeploymentGroupsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// BatchGetDeploymentGroupsWithContext is the same as BatchGetDeploymentGroups with the addition of +// the ability to pass a context and additional request options. +// +// See BatchGetDeploymentGroups 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 *CodeDeploy) BatchGetDeploymentGroupsWithContext(ctx aws.Context, input *BatchGetDeploymentGroupsInput, opts ...request.Option) (*BatchGetDeploymentGroupsOutput, error) { + req, out := c.BatchGetDeploymentGroupsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opBatchGetDeploymentInstances = "BatchGetDeploymentInstances" @@ -406,8 +466,23 @@ func (c *CodeDeploy) BatchGetDeploymentInstancesRequest(input *BatchGetDeploymen // Please also see https://docs.aws.amazon.com/goto/WebAPI/codedeploy-2014-10-06/BatchGetDeploymentInstances func (c *CodeDeploy) BatchGetDeploymentInstances(input *BatchGetDeploymentInstancesInput) (*BatchGetDeploymentInstancesOutput, error) { req, out := c.BatchGetDeploymentInstancesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// BatchGetDeploymentInstancesWithContext is the same as BatchGetDeploymentInstances with the addition of +// the ability to pass a context and additional request options. +// +// See BatchGetDeploymentInstances 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 *CodeDeploy) BatchGetDeploymentInstancesWithContext(ctx aws.Context, input *BatchGetDeploymentInstancesInput, opts ...request.Option) (*BatchGetDeploymentInstancesOutput, error) { + req, out := c.BatchGetDeploymentInstancesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opBatchGetDeployments = "BatchGetDeployments" @@ -477,8 +552,23 @@ func (c *CodeDeploy) BatchGetDeploymentsRequest(input *BatchGetDeploymentsInput) // Please also see https://docs.aws.amazon.com/goto/WebAPI/codedeploy-2014-10-06/BatchGetDeployments func (c *CodeDeploy) BatchGetDeployments(input *BatchGetDeploymentsInput) (*BatchGetDeploymentsOutput, error) { req, out := c.BatchGetDeploymentsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// BatchGetDeploymentsWithContext is the same as BatchGetDeployments with the addition of +// the ability to pass a context and additional request options. +// +// See BatchGetDeployments 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 *CodeDeploy) BatchGetDeploymentsWithContext(ctx aws.Context, input *BatchGetDeploymentsInput, opts ...request.Option) (*BatchGetDeploymentsOutput, error) { + req, out := c.BatchGetDeploymentsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opBatchGetOnPremisesInstances = "BatchGetOnPremisesInstances" @@ -548,8 +638,23 @@ func (c *CodeDeploy) BatchGetOnPremisesInstancesRequest(input *BatchGetOnPremise // Please also see https://docs.aws.amazon.com/goto/WebAPI/codedeploy-2014-10-06/BatchGetOnPremisesInstances func (c *CodeDeploy) BatchGetOnPremisesInstances(input *BatchGetOnPremisesInstancesInput) (*BatchGetOnPremisesInstancesOutput, error) { req, out := c.BatchGetOnPremisesInstancesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// BatchGetOnPremisesInstancesWithContext is the same as BatchGetOnPremisesInstances with the addition of +// the ability to pass a context and additional request options. +// +// See BatchGetOnPremisesInstances 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 *CodeDeploy) BatchGetOnPremisesInstancesWithContext(ctx aws.Context, input *BatchGetOnPremisesInstancesInput, opts ...request.Option) (*BatchGetOnPremisesInstancesOutput, error) { + req, out := c.BatchGetOnPremisesInstancesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opContinueDeployment = "ContinueDeployment" @@ -634,8 +739,23 @@ func (c *CodeDeploy) ContinueDeploymentRequest(input *ContinueDeploymentInput) ( // Please also see https://docs.aws.amazon.com/goto/WebAPI/codedeploy-2014-10-06/ContinueDeployment func (c *CodeDeploy) ContinueDeployment(input *ContinueDeploymentInput) (*ContinueDeploymentOutput, error) { req, out := c.ContinueDeploymentRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ContinueDeploymentWithContext is the same as ContinueDeployment with the addition of +// the ability to pass a context and additional request options. +// +// See ContinueDeployment 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 *CodeDeploy) ContinueDeploymentWithContext(ctx aws.Context, input *ContinueDeploymentInput, opts ...request.Option) (*ContinueDeploymentOutput, error) { + req, out := c.ContinueDeploymentRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateApplication = "CreateApplication" @@ -709,8 +829,23 @@ func (c *CodeDeploy) CreateApplicationRequest(input *CreateApplicationInput) (re // Please also see https://docs.aws.amazon.com/goto/WebAPI/codedeploy-2014-10-06/CreateApplication func (c *CodeDeploy) CreateApplication(input *CreateApplicationInput) (*CreateApplicationOutput, error) { req, out := c.CreateApplicationRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateApplicationWithContext is the same as CreateApplication with the addition of +// the ability to pass a context and additional request options. +// +// See CreateApplication 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 *CodeDeploy) CreateApplicationWithContext(ctx aws.Context, input *CreateApplicationInput, opts ...request.Option) (*CreateApplicationOutput, error) { + req, out := c.CreateApplicationRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateDeployment = "CreateDeployment" @@ -832,8 +967,23 @@ func (c *CodeDeploy) CreateDeploymentRequest(input *CreateDeploymentInput) (req // Please also see https://docs.aws.amazon.com/goto/WebAPI/codedeploy-2014-10-06/CreateDeployment func (c *CodeDeploy) CreateDeployment(input *CreateDeploymentInput) (*CreateDeploymentOutput, error) { req, out := c.CreateDeploymentRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateDeploymentWithContext is the same as CreateDeployment with the addition of +// the ability to pass a context and additional request options. +// +// See CreateDeployment 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 *CodeDeploy) CreateDeploymentWithContext(ctx aws.Context, input *CreateDeploymentInput, opts ...request.Option) (*CreateDeploymentOutput, error) { + req, out := c.CreateDeploymentRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateDeploymentConfig = "CreateDeploymentConfig" @@ -910,8 +1060,23 @@ func (c *CodeDeploy) CreateDeploymentConfigRequest(input *CreateDeploymentConfig // Please also see https://docs.aws.amazon.com/goto/WebAPI/codedeploy-2014-10-06/CreateDeploymentConfig func (c *CodeDeploy) CreateDeploymentConfig(input *CreateDeploymentConfigInput) (*CreateDeploymentConfigOutput, error) { req, out := c.CreateDeploymentConfigRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateDeploymentConfigWithContext is the same as CreateDeploymentConfig with the addition of +// the ability to pass a context and additional request options. +// +// See CreateDeploymentConfig 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 *CodeDeploy) CreateDeploymentConfigWithContext(ctx aws.Context, input *CreateDeploymentConfigInput, opts ...request.Option) (*CreateDeploymentConfigOutput, error) { + req, out := c.CreateDeploymentConfigRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateDeploymentGroup = "CreateDeploymentGroup" @@ -1061,8 +1226,23 @@ func (c *CodeDeploy) CreateDeploymentGroupRequest(input *CreateDeploymentGroupIn // Please also see https://docs.aws.amazon.com/goto/WebAPI/codedeploy-2014-10-06/CreateDeploymentGroup func (c *CodeDeploy) CreateDeploymentGroup(input *CreateDeploymentGroupInput) (*CreateDeploymentGroupOutput, error) { req, out := c.CreateDeploymentGroupRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateDeploymentGroupWithContext is the same as CreateDeploymentGroup with the addition of +// the ability to pass a context and additional request options. +// +// See CreateDeploymentGroup 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 *CodeDeploy) CreateDeploymentGroupWithContext(ctx aws.Context, input *CreateDeploymentGroupInput, opts ...request.Option) (*CreateDeploymentGroupOutput, error) { + req, out := c.CreateDeploymentGroupRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteApplication = "DeleteApplication" @@ -1131,8 +1311,23 @@ func (c *CodeDeploy) DeleteApplicationRequest(input *DeleteApplicationInput) (re // Please also see https://docs.aws.amazon.com/goto/WebAPI/codedeploy-2014-10-06/DeleteApplication func (c *CodeDeploy) DeleteApplication(input *DeleteApplicationInput) (*DeleteApplicationOutput, error) { req, out := c.DeleteApplicationRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteApplicationWithContext is the same as DeleteApplication with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteApplication 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 *CodeDeploy) DeleteApplicationWithContext(ctx aws.Context, input *DeleteApplicationInput, opts ...request.Option) (*DeleteApplicationOutput, error) { + req, out := c.DeleteApplicationRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteDeploymentConfig = "DeleteDeploymentConfig" @@ -1210,8 +1405,23 @@ func (c *CodeDeploy) DeleteDeploymentConfigRequest(input *DeleteDeploymentConfig // Please also see https://docs.aws.amazon.com/goto/WebAPI/codedeploy-2014-10-06/DeleteDeploymentConfig func (c *CodeDeploy) DeleteDeploymentConfig(input *DeleteDeploymentConfigInput) (*DeleteDeploymentConfigOutput, error) { req, out := c.DeleteDeploymentConfigRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteDeploymentConfigWithContext is the same as DeleteDeploymentConfig with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteDeploymentConfig 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 *CodeDeploy) DeleteDeploymentConfigWithContext(ctx aws.Context, input *DeleteDeploymentConfigInput, opts ...request.Option) (*DeleteDeploymentConfigOutput, error) { + req, out := c.DeleteDeploymentConfigRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteDeploymentGroup = "DeleteDeploymentGroup" @@ -1289,8 +1499,23 @@ func (c *CodeDeploy) DeleteDeploymentGroupRequest(input *DeleteDeploymentGroupIn // Please also see https://docs.aws.amazon.com/goto/WebAPI/codedeploy-2014-10-06/DeleteDeploymentGroup func (c *CodeDeploy) DeleteDeploymentGroup(input *DeleteDeploymentGroupInput) (*DeleteDeploymentGroupOutput, error) { req, out := c.DeleteDeploymentGroupRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteDeploymentGroupWithContext is the same as DeleteDeploymentGroup with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteDeploymentGroup 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 *CodeDeploy) DeleteDeploymentGroupWithContext(ctx aws.Context, input *DeleteDeploymentGroupInput, opts ...request.Option) (*DeleteDeploymentGroupOutput, error) { + req, out := c.DeleteDeploymentGroupRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeregisterOnPremisesInstance = "DeregisterOnPremisesInstance" @@ -1359,8 +1584,23 @@ func (c *CodeDeploy) DeregisterOnPremisesInstanceRequest(input *DeregisterOnPrem // Please also see https://docs.aws.amazon.com/goto/WebAPI/codedeploy-2014-10-06/DeregisterOnPremisesInstance func (c *CodeDeploy) DeregisterOnPremisesInstance(input *DeregisterOnPremisesInstanceInput) (*DeregisterOnPremisesInstanceOutput, error) { req, out := c.DeregisterOnPremisesInstanceRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeregisterOnPremisesInstanceWithContext is the same as DeregisterOnPremisesInstance with the addition of +// the ability to pass a context and additional request options. +// +// See DeregisterOnPremisesInstance 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 *CodeDeploy) DeregisterOnPremisesInstanceWithContext(ctx aws.Context, input *DeregisterOnPremisesInstanceInput, opts ...request.Option) (*DeregisterOnPremisesInstanceOutput, error) { + req, out := c.DeregisterOnPremisesInstanceRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetApplication = "GetApplication" @@ -1430,8 +1670,23 @@ func (c *CodeDeploy) GetApplicationRequest(input *GetApplicationInput) (req *req // Please also see https://docs.aws.amazon.com/goto/WebAPI/codedeploy-2014-10-06/GetApplication func (c *CodeDeploy) GetApplication(input *GetApplicationInput) (*GetApplicationOutput, error) { req, out := c.GetApplicationRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetApplicationWithContext is the same as GetApplication with the addition of +// the ability to pass a context and additional request options. +// +// See GetApplication 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 *CodeDeploy) GetApplicationWithContext(ctx aws.Context, input *GetApplicationInput, opts ...request.Option) (*GetApplicationOutput, error) { + req, out := c.GetApplicationRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetApplicationRevision = "GetApplicationRevision" @@ -1510,8 +1765,23 @@ func (c *CodeDeploy) GetApplicationRevisionRequest(input *GetApplicationRevision // Please also see https://docs.aws.amazon.com/goto/WebAPI/codedeploy-2014-10-06/GetApplicationRevision func (c *CodeDeploy) GetApplicationRevision(input *GetApplicationRevisionInput) (*GetApplicationRevisionOutput, error) { req, out := c.GetApplicationRevisionRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetApplicationRevisionWithContext is the same as GetApplicationRevision with the addition of +// the ability to pass a context and additional request options. +// +// See GetApplicationRevision 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 *CodeDeploy) GetApplicationRevisionWithContext(ctx aws.Context, input *GetApplicationRevisionInput, opts ...request.Option) (*GetApplicationRevisionOutput, error) { + req, out := c.GetApplicationRevisionRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetDeployment = "GetDeployment" @@ -1581,8 +1851,23 @@ func (c *CodeDeploy) GetDeploymentRequest(input *GetDeploymentInput) (req *reque // Please also see https://docs.aws.amazon.com/goto/WebAPI/codedeploy-2014-10-06/GetDeployment func (c *CodeDeploy) GetDeployment(input *GetDeploymentInput) (*GetDeploymentOutput, error) { req, out := c.GetDeploymentRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetDeploymentWithContext is the same as GetDeployment with the addition of +// the ability to pass a context and additional request options. +// +// See GetDeployment 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 *CodeDeploy) GetDeploymentWithContext(ctx aws.Context, input *GetDeploymentInput, opts ...request.Option) (*GetDeploymentOutput, error) { + req, out := c.GetDeploymentRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetDeploymentConfig = "GetDeploymentConfig" @@ -1653,8 +1938,23 @@ func (c *CodeDeploy) GetDeploymentConfigRequest(input *GetDeploymentConfigInput) // Please also see https://docs.aws.amazon.com/goto/WebAPI/codedeploy-2014-10-06/GetDeploymentConfig func (c *CodeDeploy) GetDeploymentConfig(input *GetDeploymentConfigInput) (*GetDeploymentConfigOutput, error) { req, out := c.GetDeploymentConfigRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetDeploymentConfigWithContext is the same as GetDeploymentConfig with the addition of +// the ability to pass a context and additional request options. +// +// See GetDeploymentConfig 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 *CodeDeploy) GetDeploymentConfigWithContext(ctx aws.Context, input *GetDeploymentConfigInput, opts ...request.Option) (*GetDeploymentConfigOutput, error) { + req, out := c.GetDeploymentConfigRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetDeploymentGroup = "GetDeploymentGroup" @@ -1734,8 +2034,23 @@ func (c *CodeDeploy) GetDeploymentGroupRequest(input *GetDeploymentGroupInput) ( // Please also see https://docs.aws.amazon.com/goto/WebAPI/codedeploy-2014-10-06/GetDeploymentGroup func (c *CodeDeploy) GetDeploymentGroup(input *GetDeploymentGroupInput) (*GetDeploymentGroupOutput, error) { req, out := c.GetDeploymentGroupRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetDeploymentGroupWithContext is the same as GetDeploymentGroup with the addition of +// the ability to pass a context and additional request options. +// +// See GetDeploymentGroup 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 *CodeDeploy) GetDeploymentGroupWithContext(ctx aws.Context, input *GetDeploymentGroupInput, opts ...request.Option) (*GetDeploymentGroupOutput, error) { + req, out := c.GetDeploymentGroupRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetDeploymentInstance = "GetDeploymentInstance" @@ -1814,8 +2129,23 @@ func (c *CodeDeploy) GetDeploymentInstanceRequest(input *GetDeploymentInstanceIn // Please also see https://docs.aws.amazon.com/goto/WebAPI/codedeploy-2014-10-06/GetDeploymentInstance func (c *CodeDeploy) GetDeploymentInstance(input *GetDeploymentInstanceInput) (*GetDeploymentInstanceOutput, error) { req, out := c.GetDeploymentInstanceRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetDeploymentInstanceWithContext is the same as GetDeploymentInstance with the addition of +// the ability to pass a context and additional request options. +// +// See GetDeploymentInstance 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 *CodeDeploy) GetDeploymentInstanceWithContext(ctx aws.Context, input *GetDeploymentInstanceInput, opts ...request.Option) (*GetDeploymentInstanceOutput, error) { + req, out := c.GetDeploymentInstanceRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetOnPremisesInstance = "GetOnPremisesInstance" @@ -1885,8 +2215,23 @@ func (c *CodeDeploy) GetOnPremisesInstanceRequest(input *GetOnPremisesInstanceIn // Please also see https://docs.aws.amazon.com/goto/WebAPI/codedeploy-2014-10-06/GetOnPremisesInstance func (c *CodeDeploy) GetOnPremisesInstance(input *GetOnPremisesInstanceInput) (*GetOnPremisesInstanceOutput, error) { req, out := c.GetOnPremisesInstanceRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetOnPremisesInstanceWithContext is the same as GetOnPremisesInstance with the addition of +// the ability to pass a context and additional request options. +// +// See GetOnPremisesInstance 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 *CodeDeploy) GetOnPremisesInstanceWithContext(ctx aws.Context, input *GetOnPremisesInstanceInput, opts ...request.Option) (*GetOnPremisesInstanceOutput, error) { + req, out := c.GetOnPremisesInstanceRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opListApplicationRevisions = "ListApplicationRevisions" @@ -1984,8 +2329,23 @@ func (c *CodeDeploy) ListApplicationRevisionsRequest(input *ListApplicationRevis // Please also see https://docs.aws.amazon.com/goto/WebAPI/codedeploy-2014-10-06/ListApplicationRevisions func (c *CodeDeploy) ListApplicationRevisions(input *ListApplicationRevisionsInput) (*ListApplicationRevisionsOutput, error) { req, out := c.ListApplicationRevisionsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListApplicationRevisionsWithContext is the same as ListApplicationRevisions with the addition of +// the ability to pass a context and additional request options. +// +// See ListApplicationRevisions 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 *CodeDeploy) ListApplicationRevisionsWithContext(ctx aws.Context, input *ListApplicationRevisionsInput, opts ...request.Option) (*ListApplicationRevisionsOutput, error) { + req, out := c.ListApplicationRevisionsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // ListApplicationRevisionsPages iterates over the pages of a ListApplicationRevisions operation, @@ -2005,12 +2365,37 @@ func (c *CodeDeploy) ListApplicationRevisions(input *ListApplicationRevisionsInp // return pageNum <= 3 // }) // -func (c *CodeDeploy) ListApplicationRevisionsPages(input *ListApplicationRevisionsInput, fn func(p *ListApplicationRevisionsOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.ListApplicationRevisionsRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*ListApplicationRevisionsOutput), lastPage) - }) +func (c *CodeDeploy) ListApplicationRevisionsPages(input *ListApplicationRevisionsInput, fn func(*ListApplicationRevisionsOutput, bool) bool) error { + return c.ListApplicationRevisionsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListApplicationRevisionsPagesWithContext same as ListApplicationRevisionsPages 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 *CodeDeploy) ListApplicationRevisionsPagesWithContext(ctx aws.Context, input *ListApplicationRevisionsInput, fn func(*ListApplicationRevisionsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListApplicationRevisionsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListApplicationRevisionsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*ListApplicationRevisionsOutput), !p.HasNextPage()) + } + return p.Err() } const opListApplications = "ListApplications" @@ -2080,8 +2465,23 @@ func (c *CodeDeploy) ListApplicationsRequest(input *ListApplicationsInput) (req // Please also see https://docs.aws.amazon.com/goto/WebAPI/codedeploy-2014-10-06/ListApplications func (c *CodeDeploy) ListApplications(input *ListApplicationsInput) (*ListApplicationsOutput, error) { req, out := c.ListApplicationsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListApplicationsWithContext is the same as ListApplications with the addition of +// the ability to pass a context and additional request options. +// +// See ListApplications 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 *CodeDeploy) ListApplicationsWithContext(ctx aws.Context, input *ListApplicationsInput, opts ...request.Option) (*ListApplicationsOutput, error) { + req, out := c.ListApplicationsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // ListApplicationsPages iterates over the pages of a ListApplications operation, @@ -2101,12 +2501,37 @@ func (c *CodeDeploy) ListApplications(input *ListApplicationsInput) (*ListApplic // return pageNum <= 3 // }) // -func (c *CodeDeploy) ListApplicationsPages(input *ListApplicationsInput, fn func(p *ListApplicationsOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.ListApplicationsRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*ListApplicationsOutput), lastPage) - }) +func (c *CodeDeploy) ListApplicationsPages(input *ListApplicationsInput, fn func(*ListApplicationsOutput, bool) bool) error { + return c.ListApplicationsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListApplicationsPagesWithContext same as ListApplicationsPages 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 *CodeDeploy) ListApplicationsPagesWithContext(ctx aws.Context, input *ListApplicationsInput, fn func(*ListApplicationsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListApplicationsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListApplicationsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*ListApplicationsOutput), !p.HasNextPage()) + } + return p.Err() } const opListDeploymentConfigs = "ListDeploymentConfigs" @@ -2176,8 +2601,23 @@ func (c *CodeDeploy) ListDeploymentConfigsRequest(input *ListDeploymentConfigsIn // Please also see https://docs.aws.amazon.com/goto/WebAPI/codedeploy-2014-10-06/ListDeploymentConfigs func (c *CodeDeploy) ListDeploymentConfigs(input *ListDeploymentConfigsInput) (*ListDeploymentConfigsOutput, error) { req, out := c.ListDeploymentConfigsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListDeploymentConfigsWithContext is the same as ListDeploymentConfigs with the addition of +// the ability to pass a context and additional request options. +// +// See ListDeploymentConfigs 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 *CodeDeploy) ListDeploymentConfigsWithContext(ctx aws.Context, input *ListDeploymentConfigsInput, opts ...request.Option) (*ListDeploymentConfigsOutput, error) { + req, out := c.ListDeploymentConfigsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // ListDeploymentConfigsPages iterates over the pages of a ListDeploymentConfigs operation, @@ -2197,12 +2637,37 @@ func (c *CodeDeploy) ListDeploymentConfigs(input *ListDeploymentConfigsInput) (* // return pageNum <= 3 // }) // -func (c *CodeDeploy) ListDeploymentConfigsPages(input *ListDeploymentConfigsInput, fn func(p *ListDeploymentConfigsOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.ListDeploymentConfigsRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*ListDeploymentConfigsOutput), lastPage) - }) +func (c *CodeDeploy) ListDeploymentConfigsPages(input *ListDeploymentConfigsInput, fn func(*ListDeploymentConfigsOutput, bool) bool) error { + return c.ListDeploymentConfigsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListDeploymentConfigsPagesWithContext same as ListDeploymentConfigsPages 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 *CodeDeploy) ListDeploymentConfigsPagesWithContext(ctx aws.Context, input *ListDeploymentConfigsInput, fn func(*ListDeploymentConfigsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListDeploymentConfigsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListDeploymentConfigsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*ListDeploymentConfigsOutput), !p.HasNextPage()) + } + return p.Err() } const opListDeploymentGroups = "ListDeploymentGroups" @@ -2282,8 +2747,23 @@ func (c *CodeDeploy) ListDeploymentGroupsRequest(input *ListDeploymentGroupsInpu // Please also see https://docs.aws.amazon.com/goto/WebAPI/codedeploy-2014-10-06/ListDeploymentGroups func (c *CodeDeploy) ListDeploymentGroups(input *ListDeploymentGroupsInput) (*ListDeploymentGroupsOutput, error) { req, out := c.ListDeploymentGroupsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListDeploymentGroupsWithContext is the same as ListDeploymentGroups with the addition of +// the ability to pass a context and additional request options. +// +// See ListDeploymentGroups 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 *CodeDeploy) ListDeploymentGroupsWithContext(ctx aws.Context, input *ListDeploymentGroupsInput, opts ...request.Option) (*ListDeploymentGroupsOutput, error) { + req, out := c.ListDeploymentGroupsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // ListDeploymentGroupsPages iterates over the pages of a ListDeploymentGroups operation, @@ -2303,12 +2783,37 @@ func (c *CodeDeploy) ListDeploymentGroups(input *ListDeploymentGroupsInput) (*Li // return pageNum <= 3 // }) // -func (c *CodeDeploy) ListDeploymentGroupsPages(input *ListDeploymentGroupsInput, fn func(p *ListDeploymentGroupsOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.ListDeploymentGroupsRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*ListDeploymentGroupsOutput), lastPage) - }) +func (c *CodeDeploy) ListDeploymentGroupsPages(input *ListDeploymentGroupsInput, fn func(*ListDeploymentGroupsOutput, bool) bool) error { + return c.ListDeploymentGroupsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListDeploymentGroupsPagesWithContext same as ListDeploymentGroupsPages 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 *CodeDeploy) ListDeploymentGroupsPagesWithContext(ctx aws.Context, input *ListDeploymentGroupsInput, fn func(*ListDeploymentGroupsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListDeploymentGroupsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListDeploymentGroupsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*ListDeploymentGroupsOutput), !p.HasNextPage()) + } + return p.Err() } const opListDeploymentInstances = "ListDeploymentInstances" @@ -2399,8 +2904,23 @@ func (c *CodeDeploy) ListDeploymentInstancesRequest(input *ListDeploymentInstanc // Please also see https://docs.aws.amazon.com/goto/WebAPI/codedeploy-2014-10-06/ListDeploymentInstances func (c *CodeDeploy) ListDeploymentInstances(input *ListDeploymentInstancesInput) (*ListDeploymentInstancesOutput, error) { req, out := c.ListDeploymentInstancesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListDeploymentInstancesWithContext is the same as ListDeploymentInstances with the addition of +// the ability to pass a context and additional request options. +// +// See ListDeploymentInstances 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 *CodeDeploy) ListDeploymentInstancesWithContext(ctx aws.Context, input *ListDeploymentInstancesInput, opts ...request.Option) (*ListDeploymentInstancesOutput, error) { + req, out := c.ListDeploymentInstancesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // ListDeploymentInstancesPages iterates over the pages of a ListDeploymentInstances operation, @@ -2420,12 +2940,37 @@ func (c *CodeDeploy) ListDeploymentInstances(input *ListDeploymentInstancesInput // return pageNum <= 3 // }) // -func (c *CodeDeploy) ListDeploymentInstancesPages(input *ListDeploymentInstancesInput, fn func(p *ListDeploymentInstancesOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.ListDeploymentInstancesRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*ListDeploymentInstancesOutput), lastPage) - }) +func (c *CodeDeploy) ListDeploymentInstancesPages(input *ListDeploymentInstancesInput, fn func(*ListDeploymentInstancesOutput, bool) bool) error { + return c.ListDeploymentInstancesPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListDeploymentInstancesPagesWithContext same as ListDeploymentInstancesPages 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 *CodeDeploy) ListDeploymentInstancesPagesWithContext(ctx aws.Context, input *ListDeploymentInstancesInput, fn func(*ListDeploymentInstancesOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListDeploymentInstancesInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListDeploymentInstancesRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*ListDeploymentInstancesOutput), !p.HasNextPage()) + } + return p.Err() } const opListDeployments = "ListDeployments" @@ -2521,8 +3066,23 @@ func (c *CodeDeploy) ListDeploymentsRequest(input *ListDeploymentsInput) (req *r // Please also see https://docs.aws.amazon.com/goto/WebAPI/codedeploy-2014-10-06/ListDeployments func (c *CodeDeploy) ListDeployments(input *ListDeploymentsInput) (*ListDeploymentsOutput, error) { req, out := c.ListDeploymentsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListDeploymentsWithContext is the same as ListDeployments with the addition of +// the ability to pass a context and additional request options. +// +// See ListDeployments 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 *CodeDeploy) ListDeploymentsWithContext(ctx aws.Context, input *ListDeploymentsInput, opts ...request.Option) (*ListDeploymentsOutput, error) { + req, out := c.ListDeploymentsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // ListDeploymentsPages iterates over the pages of a ListDeployments operation, @@ -2542,12 +3102,37 @@ func (c *CodeDeploy) ListDeployments(input *ListDeploymentsInput) (*ListDeployme // return pageNum <= 3 // }) // -func (c *CodeDeploy) ListDeploymentsPages(input *ListDeploymentsInput, fn func(p *ListDeploymentsOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.ListDeploymentsRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*ListDeploymentsOutput), lastPage) - }) +func (c *CodeDeploy) ListDeploymentsPages(input *ListDeploymentsInput, fn func(*ListDeploymentsOutput, bool) bool) error { + return c.ListDeploymentsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListDeploymentsPagesWithContext same as ListDeploymentsPages 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 *CodeDeploy) ListDeploymentsPagesWithContext(ctx aws.Context, input *ListDeploymentsInput, fn func(*ListDeploymentsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListDeploymentsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListDeploymentsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*ListDeploymentsOutput), !p.HasNextPage()) + } + return p.Err() } const opListOnPremisesInstances = "ListOnPremisesInstances" @@ -2621,8 +3206,23 @@ func (c *CodeDeploy) ListOnPremisesInstancesRequest(input *ListOnPremisesInstanc // Please also see https://docs.aws.amazon.com/goto/WebAPI/codedeploy-2014-10-06/ListOnPremisesInstances func (c *CodeDeploy) ListOnPremisesInstances(input *ListOnPremisesInstancesInput) (*ListOnPremisesInstancesOutput, error) { req, out := c.ListOnPremisesInstancesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListOnPremisesInstancesWithContext is the same as ListOnPremisesInstances with the addition of +// the ability to pass a context and additional request options. +// +// See ListOnPremisesInstances 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 *CodeDeploy) ListOnPremisesInstancesWithContext(ctx aws.Context, input *ListOnPremisesInstancesInput, opts ...request.Option) (*ListOnPremisesInstancesOutput, error) { + req, out := c.ListOnPremisesInstancesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opRegisterApplicationRevision = "RegisterApplicationRevision" @@ -2703,8 +3303,23 @@ func (c *CodeDeploy) RegisterApplicationRevisionRequest(input *RegisterApplicati // Please also see https://docs.aws.amazon.com/goto/WebAPI/codedeploy-2014-10-06/RegisterApplicationRevision func (c *CodeDeploy) RegisterApplicationRevision(input *RegisterApplicationRevisionInput) (*RegisterApplicationRevisionOutput, error) { req, out := c.RegisterApplicationRevisionRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// RegisterApplicationRevisionWithContext is the same as RegisterApplicationRevision with the addition of +// the ability to pass a context and additional request options. +// +// See RegisterApplicationRevision 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 *CodeDeploy) RegisterApplicationRevisionWithContext(ctx aws.Context, input *RegisterApplicationRevisionInput, opts ...request.Option) (*RegisterApplicationRevisionOutput, error) { + req, out := c.RegisterApplicationRevisionRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opRegisterOnPremisesInstance = "RegisterOnPremisesInstance" @@ -2803,8 +3418,23 @@ func (c *CodeDeploy) RegisterOnPremisesInstanceRequest(input *RegisterOnPremises // Please also see https://docs.aws.amazon.com/goto/WebAPI/codedeploy-2014-10-06/RegisterOnPremisesInstance func (c *CodeDeploy) RegisterOnPremisesInstance(input *RegisterOnPremisesInstanceInput) (*RegisterOnPremisesInstanceOutput, error) { req, out := c.RegisterOnPremisesInstanceRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// RegisterOnPremisesInstanceWithContext is the same as RegisterOnPremisesInstance with the addition of +// the ability to pass a context and additional request options. +// +// See RegisterOnPremisesInstance 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 *CodeDeploy) RegisterOnPremisesInstanceWithContext(ctx aws.Context, input *RegisterOnPremisesInstanceInput, opts ...request.Option) (*RegisterOnPremisesInstanceOutput, error) { + req, out := c.RegisterOnPremisesInstanceRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opRemoveTagsFromOnPremisesInstances = "RemoveTagsFromOnPremisesInstances" @@ -2886,8 +3516,23 @@ func (c *CodeDeploy) RemoveTagsFromOnPremisesInstancesRequest(input *RemoveTagsF // Please also see https://docs.aws.amazon.com/goto/WebAPI/codedeploy-2014-10-06/RemoveTagsFromOnPremisesInstances func (c *CodeDeploy) RemoveTagsFromOnPremisesInstances(input *RemoveTagsFromOnPremisesInstancesInput) (*RemoveTagsFromOnPremisesInstancesOutput, error) { req, out := c.RemoveTagsFromOnPremisesInstancesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// RemoveTagsFromOnPremisesInstancesWithContext is the same as RemoveTagsFromOnPremisesInstances with the addition of +// the ability to pass a context and additional request options. +// +// See RemoveTagsFromOnPremisesInstances 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 *CodeDeploy) RemoveTagsFromOnPremisesInstancesWithContext(ctx aws.Context, input *RemoveTagsFromOnPremisesInstancesInput, opts ...request.Option) (*RemoveTagsFromOnPremisesInstancesOutput, error) { + req, out := c.RemoveTagsFromOnPremisesInstancesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opSkipWaitTimeForInstanceTermination = "SkipWaitTimeForInstanceTermination" @@ -2969,8 +3614,23 @@ func (c *CodeDeploy) SkipWaitTimeForInstanceTerminationRequest(input *SkipWaitTi // Please also see https://docs.aws.amazon.com/goto/WebAPI/codedeploy-2014-10-06/SkipWaitTimeForInstanceTermination func (c *CodeDeploy) SkipWaitTimeForInstanceTermination(input *SkipWaitTimeForInstanceTerminationInput) (*SkipWaitTimeForInstanceTerminationOutput, error) { req, out := c.SkipWaitTimeForInstanceTerminationRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// SkipWaitTimeForInstanceTerminationWithContext is the same as SkipWaitTimeForInstanceTermination with the addition of +// the ability to pass a context and additional request options. +// +// See SkipWaitTimeForInstanceTermination 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 *CodeDeploy) SkipWaitTimeForInstanceTerminationWithContext(ctx aws.Context, input *SkipWaitTimeForInstanceTerminationInput, opts ...request.Option) (*SkipWaitTimeForInstanceTerminationOutput, error) { + req, out := c.SkipWaitTimeForInstanceTerminationRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opStopDeployment = "StopDeployment" @@ -3043,8 +3703,23 @@ func (c *CodeDeploy) StopDeploymentRequest(input *StopDeploymentInput) (req *req // Please also see https://docs.aws.amazon.com/goto/WebAPI/codedeploy-2014-10-06/StopDeployment func (c *CodeDeploy) StopDeployment(input *StopDeploymentInput) (*StopDeploymentOutput, error) { req, out := c.StopDeploymentRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// StopDeploymentWithContext is the same as StopDeployment with the addition of +// the ability to pass a context and additional request options. +// +// See StopDeployment 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 *CodeDeploy) StopDeploymentWithContext(ctx aws.Context, input *StopDeploymentInput, opts ...request.Option) (*StopDeploymentOutput, error) { + req, out := c.StopDeploymentRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opUpdateApplication = "UpdateApplication" @@ -3120,8 +3795,23 @@ func (c *CodeDeploy) UpdateApplicationRequest(input *UpdateApplicationInput) (re // Please also see https://docs.aws.amazon.com/goto/WebAPI/codedeploy-2014-10-06/UpdateApplication func (c *CodeDeploy) UpdateApplication(input *UpdateApplicationInput) (*UpdateApplicationOutput, error) { req, out := c.UpdateApplicationRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// UpdateApplicationWithContext is the same as UpdateApplication with the addition of +// the ability to pass a context and additional request options. +// +// See UpdateApplication 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 *CodeDeploy) UpdateApplicationWithContext(ctx aws.Context, input *UpdateApplicationInput, opts ...request.Option) (*UpdateApplicationOutput, error) { + req, out := c.UpdateApplicationRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opUpdateDeploymentGroup = "UpdateDeploymentGroup" @@ -3269,8 +3959,23 @@ func (c *CodeDeploy) UpdateDeploymentGroupRequest(input *UpdateDeploymentGroupIn // Please also see https://docs.aws.amazon.com/goto/WebAPI/codedeploy-2014-10-06/UpdateDeploymentGroup func (c *CodeDeploy) UpdateDeploymentGroup(input *UpdateDeploymentGroupInput) (*UpdateDeploymentGroupOutput, error) { req, out := c.UpdateDeploymentGroupRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// UpdateDeploymentGroupWithContext is the same as UpdateDeploymentGroup with the addition of +// the ability to pass a context and additional request options. +// +// See UpdateDeploymentGroup 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 *CodeDeploy) UpdateDeploymentGroupWithContext(ctx aws.Context, input *UpdateDeploymentGroupInput, opts ...request.Option) (*UpdateDeploymentGroupOutput, error) { + req, out := c.UpdateDeploymentGroupRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // Represents the input of, and adds tags to, an on-premises instance operation. diff --git a/vendor/github.com/aws/aws-sdk-go/service/codedeploy/doc.go b/vendor/github.com/aws/aws-sdk-go/service/codedeploy/doc.go new file mode 100644 index 000000000..7e46df547 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/service/codedeploy/doc.go @@ -0,0 +1,132 @@ +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. + +// Package codedeploy provides the client and types for making API +// requests to AWS CodeDeploy. +// +// Overview +// +// This reference guide provides descriptions of the AWS CodeDeploy APIs. For +// more information about AWS CodeDeploy, see the AWS CodeDeploy User Guide +// (http://docs.aws.amazon.com/codedeploy/latest/userguide). +// +// Using the APIs +// +// You can use the AWS CodeDeploy APIs to work with the following: +// +// * Applications are unique identifiers used by AWS CodeDeploy to ensure +// the correct combinations of revisions, deployment configurations, and +// deployment groups are being referenced during deployments. +// +// You can use the AWS CodeDeploy APIs to create, delete, get, list, and update +// applications. +// +// * Deployment configurations are sets of deployment rules and success and +// failure conditions used by AWS CodeDeploy during deployments. +// +// You can use the AWS CodeDeploy APIs to create, delete, get, and list deployment +// configurations. +// +// * Deployment groups are groups of instances to which application revisions +// can be deployed. +// +// You can use the AWS CodeDeploy APIs to create, delete, get, list, and update +// deployment groups. +// +// * Instances represent Amazon EC2 instances to which application revisions +// are deployed. Instances are identified by their Amazon EC2 tags or Auto +// Scaling group names. Instances belong to deployment groups. +// +// You can use the AWS CodeDeploy APIs to get and list instance. +// +// * Deployments represent the process of deploying revisions to instances. +// +// You can use the AWS CodeDeploy APIs to create, get, list, and stop deployments. +// +// * Application revisions are archive files stored in Amazon S3 buckets +// or GitHub repositories. These revisions contain source content (such as +// source code, web pages, executable files, and deployment scripts) along +// with an application specification (AppSpec) file. (The AppSpec file is +// unique to AWS CodeDeploy; it defines the deployment actions you want AWS +// CodeDeploy to execute.) For application revisions stored in Amazon S3 +// buckets, an application revision is uniquely identified by its Amazon +// S3 object key and its ETag, version, or both. For application revisions +// stored in GitHub repositories, an application revision is uniquely identified +// by its repository name and commit ID. Application revisions are deployed +// through deployment groups. +// +// You can use the AWS CodeDeploy APIs to get, list, and register application +// revisions. +// +// See https://docs.aws.amazon.com/goto/WebAPI/codedeploy-2014-10-06 for more information on this service. +// +// See codedeploy package documentation for more information. +// https://docs.aws.amazon.com/sdk-for-go/api/service/codedeploy/ +// +// Using the Client +// +// To use the client for AWS CodeDeploy you will first need +// to create a new instance of it. +// +// When creating a client for an AWS service you'll first need to have a Session +// already created. The Session provides configuration that can be shared +// between multiple service clients. Additional configuration can be applied to +// the Session and service's client when they are constructed. The aws package's +// Config type contains several fields such as Region for the AWS Region the +// client should make API requests too. The optional Config value can be provided +// as the variadic argument for Sessions and client creation. +// +// Once the service's client is created you can use it to make API requests the +// AWS service. These clients are safe to use concurrently. +// +// // Create a session to share configuration, and load external configuration. +// sess := session.Must(session.NewSession()) +// +// // Create the service's client with the session. +// svc := codedeploy.New(sess) +// +// See the SDK's documentation for more information on how to use service clients. +// https://docs.aws.amazon.com/sdk-for-go/api/ +// +// See aws package's Config type for more information on configuration options. +// https://docs.aws.amazon.com/sdk-for-go/api/aws/#Config +// +// See the AWS CodeDeploy client CodeDeploy for more +// information on creating the service's client. +// https://docs.aws.amazon.com/sdk-for-go/api/service/codedeploy/#New +// +// Once the client is created you can make an API request to the service. +// Each API method takes a input parameter, and returns the service response +// and an error. +// +// The API method will document which error codes the service can be returned +// by the operation if the service models the API operation's errors. These +// errors will also be available as const strings prefixed with "ErrCode". +// +// result, err := svc.AddTagsToOnPremisesInstances(params) +// if err != nil { +// // Cast err to awserr.Error to handle specific error codes. +// aerr, ok := err.(awserr.Error) +// if ok && aerr.Code() == { +// // Specific error code handling +// } +// return err +// } +// +// fmt.Println("AddTagsToOnPremisesInstances result:") +// fmt.Println(result) +// +// Using the Client with Context +// +// The service's client also provides methods to make API requests with a Context +// value. This allows you to control the timeout, and cancellation of pending +// requests. These methods also take request Option as variadic parameter to apply +// additional configuration to the API request. +// +// ctx := context.Background() +// +// result, err := svc.AddTagsToOnPremisesInstancesWithContext(ctx, params) +// +// See the request package documentation for more information on using Context pattern +// with the SDK. +// https://docs.aws.amazon.com/sdk-for-go/api/aws/request/ +package codedeploy diff --git a/vendor/github.com/aws/aws-sdk-go/service/codedeploy/errors.go b/vendor/github.com/aws/aws-sdk-go/service/codedeploy/errors.go index 6eebf7315..1f8c6a96d 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/codedeploy/errors.go +++ b/vendor/github.com/aws/aws-sdk-go/service/codedeploy/errors.go @@ -1,4 +1,4 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. package codedeploy diff --git a/vendor/github.com/aws/aws-sdk-go/service/codedeploy/service.go b/vendor/github.com/aws/aws-sdk-go/service/codedeploy/service.go index 5b20f2a45..e6524d04d 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/codedeploy/service.go +++ b/vendor/github.com/aws/aws-sdk-go/service/codedeploy/service.go @@ -1,4 +1,4 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. package codedeploy @@ -11,62 +11,12 @@ import ( "github.com/aws/aws-sdk-go/private/protocol/jsonrpc" ) -// Overview +// CodeDeploy provides the API operation methods for making requests to +// AWS CodeDeploy. See this package's package overview docs +// for details on the service. // -// This reference guide provides descriptions of the AWS CodeDeploy APIs. For -// more information about AWS CodeDeploy, see the AWS CodeDeploy User Guide -// (http://docs.aws.amazon.com/codedeploy/latest/userguide). -// -// Using the APIs -// -// You can use the AWS CodeDeploy APIs to work with the following: -// -// * Applications are unique identifiers used by AWS CodeDeploy to ensure -// the correct combinations of revisions, deployment configurations, and -// deployment groups are being referenced during deployments. -// -// You can use the AWS CodeDeploy APIs to create, delete, get, list, and update -// applications. -// -// * Deployment configurations are sets of deployment rules and success and -// failure conditions used by AWS CodeDeploy during deployments. -// -// You can use the AWS CodeDeploy APIs to create, delete, get, and list deployment -// configurations. -// -// * Deployment groups are groups of instances to which application revisions -// can be deployed. -// -// You can use the AWS CodeDeploy APIs to create, delete, get, list, and update -// deployment groups. -// -// * Instances represent Amazon EC2 instances to which application revisions -// are deployed. Instances are identified by their Amazon EC2 tags or Auto -// Scaling group names. Instances belong to deployment groups. -// -// You can use the AWS CodeDeploy APIs to get and list instance. -// -// * Deployments represent the process of deploying revisions to instances. -// -// You can use the AWS CodeDeploy APIs to create, get, list, and stop deployments. -// -// * Application revisions are archive files stored in Amazon S3 buckets -// or GitHub repositories. These revisions contain source content (such as -// source code, web pages, executable files, and deployment scripts) along -// with an application specification (AppSpec) file. (The AppSpec file is -// unique to AWS CodeDeploy; it defines the deployment actions you want AWS -// CodeDeploy to execute.) For application revisions stored in Amazon S3 -// buckets, an application revision is uniquely identified by its Amazon -// S3 object key and its ETag, version, or both. For application revisions -// stored in GitHub repositories, an application revision is uniquely identified -// by its repository name and commit ID. Application revisions are deployed -// through deployment groups. -// -// You can use the AWS CodeDeploy APIs to get, list, and register application -// revisions. -// The service client's operations are safe to be used concurrently. -// It is not safe to mutate any of the client's properties though. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/codedeploy-2014-10-06 +// CodeDeploy methods are safe to use concurrently. It is not safe to +// modify mutate any of the struct's properties though. type CodeDeploy struct { *client.Client } diff --git a/vendor/github.com/aws/aws-sdk-go/service/codedeploy/waiters.go b/vendor/github.com/aws/aws-sdk-go/service/codedeploy/waiters.go index 3d605b11b..8b885e852 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/codedeploy/waiters.go +++ b/vendor/github.com/aws/aws-sdk-go/service/codedeploy/waiters.go @@ -1,9 +1,12 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. package codedeploy import ( - "github.com/aws/aws-sdk-go/private/waiter" + "time" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/request" ) // WaitUntilDeploymentSuccessful uses the CodeDeploy API operation @@ -11,36 +14,53 @@ import ( // If the condition is not meet within the max attempt window an error will // be returned. func (c *CodeDeploy) WaitUntilDeploymentSuccessful(input *GetDeploymentInput) error { - waiterCfg := waiter.Config{ - Operation: "GetDeployment", - Delay: 15, + return c.WaitUntilDeploymentSuccessfulWithContext(aws.BackgroundContext(), input) +} + +// WaitUntilDeploymentSuccessfulWithContext is an extended version of WaitUntilDeploymentSuccessful. +// 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 *CodeDeploy) WaitUntilDeploymentSuccessfulWithContext(ctx aws.Context, input *GetDeploymentInput, opts ...request.WaiterOption) error { + w := request.Waiter{ + Name: "WaitUntilDeploymentSuccessful", MaxAttempts: 120, - Acceptors: []waiter.WaitAcceptor{ + Delay: request.ConstantWaiterDelay(15 * time.Second), + Acceptors: []request.WaiterAcceptor{ { - State: "success", - Matcher: "path", - Argument: "deploymentInfo.status", + State: request.SuccessWaiterState, + Matcher: request.PathWaiterMatch, Argument: "deploymentInfo.status", Expected: "Succeeded", }, { - State: "failure", - Matcher: "path", - Argument: "deploymentInfo.status", + State: request.FailureWaiterState, + Matcher: request.PathWaiterMatch, Argument: "deploymentInfo.status", Expected: "Failed", }, { - State: "failure", - Matcher: "path", - Argument: "deploymentInfo.status", + State: request.FailureWaiterState, + Matcher: request.PathWaiterMatch, Argument: "deploymentInfo.status", Expected: "Stopped", }, }, + Logger: c.Config.Logger, + NewRequest: func(opts []request.Option) (*request.Request, error) { + var inCpy *GetDeploymentInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.GetDeploymentRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, } + w.ApplyOptions(opts...) - w := waiter.Waiter{ - Client: c, - Input: input, - Config: waiterCfg, - } - return w.Wait() + return w.WaitWithContext(ctx) } diff --git a/vendor/github.com/aws/aws-sdk-go/service/codepipeline/api.go b/vendor/github.com/aws/aws-sdk-go/service/codepipeline/api.go index 0320007aa..0a7360de6 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/codepipeline/api.go +++ b/vendor/github.com/aws/aws-sdk-go/service/codepipeline/api.go @@ -1,12 +1,12 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. -// Package codepipeline provides a client for AWS CodePipeline. package codepipeline import ( "fmt" "time" + "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awsutil" "github.com/aws/aws-sdk-go/aws/request" "github.com/aws/aws-sdk-go/private/protocol" @@ -81,8 +81,23 @@ func (c *CodePipeline) AcknowledgeJobRequest(input *AcknowledgeJobInput) (req *r // Please also see https://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/AcknowledgeJob func (c *CodePipeline) AcknowledgeJob(input *AcknowledgeJobInput) (*AcknowledgeJobOutput, error) { req, out := c.AcknowledgeJobRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// AcknowledgeJobWithContext is the same as AcknowledgeJob with the addition of +// the ability to pass a context and additional request options. +// +// See AcknowledgeJob 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 *CodePipeline) AcknowledgeJobWithContext(ctx aws.Context, input *AcknowledgeJobInput, opts ...request.Option) (*AcknowledgeJobOutput, error) { + req, out := c.AcknowledgeJobRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opAcknowledgeThirdPartyJob = "AcknowledgeThirdPartyJob" @@ -156,8 +171,23 @@ func (c *CodePipeline) AcknowledgeThirdPartyJobRequest(input *AcknowledgeThirdPa // Please also see https://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/AcknowledgeThirdPartyJob func (c *CodePipeline) AcknowledgeThirdPartyJob(input *AcknowledgeThirdPartyJobInput) (*AcknowledgeThirdPartyJobOutput, error) { req, out := c.AcknowledgeThirdPartyJobRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// AcknowledgeThirdPartyJobWithContext is the same as AcknowledgeThirdPartyJob with the addition of +// the ability to pass a context and additional request options. +// +// See AcknowledgeThirdPartyJob 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 *CodePipeline) AcknowledgeThirdPartyJobWithContext(ctx aws.Context, input *AcknowledgeThirdPartyJobInput, opts ...request.Option) (*AcknowledgeThirdPartyJobOutput, error) { + req, out := c.AcknowledgeThirdPartyJobRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateCustomActionType = "CreateCustomActionType" @@ -226,8 +256,23 @@ func (c *CodePipeline) CreateCustomActionTypeRequest(input *CreateCustomActionTy // Please also see https://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/CreateCustomActionType func (c *CodePipeline) CreateCustomActionType(input *CreateCustomActionTypeInput) (*CreateCustomActionTypeOutput, error) { req, out := c.CreateCustomActionTypeRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateCustomActionTypeWithContext is the same as CreateCustomActionType with the addition of +// the ability to pass a context and additional request options. +// +// See CreateCustomActionType 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 *CodePipeline) CreateCustomActionTypeWithContext(ctx aws.Context, input *CreateCustomActionTypeInput, opts ...request.Option) (*CreateCustomActionTypeOutput, error) { + req, out := c.CreateCustomActionTypeRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreatePipeline = "CreatePipeline" @@ -310,8 +355,23 @@ func (c *CodePipeline) CreatePipelineRequest(input *CreatePipelineInput) (req *r // Please also see https://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/CreatePipeline func (c *CodePipeline) CreatePipeline(input *CreatePipelineInput) (*CreatePipelineOutput, error) { req, out := c.CreatePipelineRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreatePipelineWithContext is the same as CreatePipeline with the addition of +// the ability to pass a context and additional request options. +// +// See CreatePipeline 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 *CodePipeline) CreatePipelineWithContext(ctx aws.Context, input *CreatePipelineInput, opts ...request.Option) (*CreatePipelineOutput, error) { + req, out := c.CreatePipelineRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteCustomActionType = "DeleteCustomActionType" @@ -381,8 +441,23 @@ func (c *CodePipeline) DeleteCustomActionTypeRequest(input *DeleteCustomActionTy // Please also see https://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/DeleteCustomActionType func (c *CodePipeline) DeleteCustomActionType(input *DeleteCustomActionTypeInput) (*DeleteCustomActionTypeOutput, error) { req, out := c.DeleteCustomActionTypeRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteCustomActionTypeWithContext is the same as DeleteCustomActionType with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteCustomActionType 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 *CodePipeline) DeleteCustomActionTypeWithContext(ctx aws.Context, input *DeleteCustomActionTypeInput, opts ...request.Option) (*DeleteCustomActionTypeOutput, error) { + req, out := c.DeleteCustomActionTypeRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeletePipeline = "DeletePipeline" @@ -448,8 +523,23 @@ func (c *CodePipeline) DeletePipelineRequest(input *DeletePipelineInput) (req *r // Please also see https://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/DeletePipeline func (c *CodePipeline) DeletePipeline(input *DeletePipelineInput) (*DeletePipelineOutput, error) { req, out := c.DeletePipelineRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeletePipelineWithContext is the same as DeletePipeline with the addition of +// the ability to pass a context and additional request options. +// +// See DeletePipeline 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 *CodePipeline) DeletePipelineWithContext(ctx aws.Context, input *DeletePipelineInput, opts ...request.Option) (*DeletePipelineOutput, error) { + req, out := c.DeletePipelineRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDisableStageTransition = "DisableStageTransition" @@ -522,8 +612,23 @@ func (c *CodePipeline) DisableStageTransitionRequest(input *DisableStageTransiti // Please also see https://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/DisableStageTransition func (c *CodePipeline) DisableStageTransition(input *DisableStageTransitionInput) (*DisableStageTransitionOutput, error) { req, out := c.DisableStageTransitionRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DisableStageTransitionWithContext is the same as DisableStageTransition with the addition of +// the ability to pass a context and additional request options. +// +// See DisableStageTransition 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 *CodePipeline) DisableStageTransitionWithContext(ctx aws.Context, input *DisableStageTransitionInput, opts ...request.Option) (*DisableStageTransitionOutput, error) { + req, out := c.DisableStageTransitionRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opEnableStageTransition = "EnableStageTransition" @@ -595,8 +700,23 @@ func (c *CodePipeline) EnableStageTransitionRequest(input *EnableStageTransition // Please also see https://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/EnableStageTransition func (c *CodePipeline) EnableStageTransition(input *EnableStageTransitionInput) (*EnableStageTransitionOutput, error) { req, out := c.EnableStageTransitionRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// EnableStageTransitionWithContext is the same as EnableStageTransition with the addition of +// the ability to pass a context and additional request options. +// +// See EnableStageTransition 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 *CodePipeline) EnableStageTransitionWithContext(ctx aws.Context, input *EnableStageTransitionInput, opts ...request.Option) (*EnableStageTransitionOutput, error) { + req, out := c.EnableStageTransitionRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetJobDetails = "GetJobDetails" @@ -668,8 +788,23 @@ func (c *CodePipeline) GetJobDetailsRequest(input *GetJobDetailsInput) (req *req // Please also see https://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/GetJobDetails func (c *CodePipeline) GetJobDetails(input *GetJobDetailsInput) (*GetJobDetailsOutput, error) { req, out := c.GetJobDetailsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetJobDetailsWithContext is the same as GetJobDetails with the addition of +// the ability to pass a context and additional request options. +// +// See GetJobDetails 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 *CodePipeline) GetJobDetailsWithContext(ctx aws.Context, input *GetJobDetailsInput, opts ...request.Option) (*GetJobDetailsOutput, error) { + req, out := c.GetJobDetailsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetPipeline = "GetPipeline" @@ -742,8 +877,23 @@ func (c *CodePipeline) GetPipelineRequest(input *GetPipelineInput) (req *request // Please also see https://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/GetPipeline func (c *CodePipeline) GetPipeline(input *GetPipelineInput) (*GetPipelineOutput, error) { req, out := c.GetPipelineRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetPipelineWithContext is the same as GetPipeline with the addition of +// the ability to pass a context and additional request options. +// +// See GetPipeline 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 *CodePipeline) GetPipelineWithContext(ctx aws.Context, input *GetPipelineInput, opts ...request.Option) (*GetPipelineOutput, error) { + req, out := c.GetPipelineRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetPipelineExecution = "GetPipelineExecution" @@ -816,8 +966,23 @@ func (c *CodePipeline) GetPipelineExecutionRequest(input *GetPipelineExecutionIn // Please also see https://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/GetPipelineExecution func (c *CodePipeline) GetPipelineExecution(input *GetPipelineExecutionInput) (*GetPipelineExecutionOutput, error) { req, out := c.GetPipelineExecutionRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetPipelineExecutionWithContext is the same as GetPipelineExecution with the addition of +// the ability to pass a context and additional request options. +// +// See GetPipelineExecution 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 *CodePipeline) GetPipelineExecutionWithContext(ctx aws.Context, input *GetPipelineExecutionInput, opts ...request.Option) (*GetPipelineExecutionOutput, error) { + req, out := c.GetPipelineExecutionRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetPipelineState = "GetPipelineState" @@ -885,8 +1050,23 @@ func (c *CodePipeline) GetPipelineStateRequest(input *GetPipelineStateInput) (re // Please also see https://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/GetPipelineState func (c *CodePipeline) GetPipelineState(input *GetPipelineStateInput) (*GetPipelineStateOutput, error) { req, out := c.GetPipelineStateRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetPipelineStateWithContext is the same as GetPipelineState with the addition of +// the ability to pass a context and additional request options. +// +// See GetPipelineState 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 *CodePipeline) GetPipelineStateWithContext(ctx aws.Context, input *GetPipelineStateInput, opts ...request.Option) (*GetPipelineStateOutput, error) { + req, out := c.GetPipelineStateRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetThirdPartyJobDetails = "GetThirdPartyJobDetails" @@ -965,8 +1145,23 @@ func (c *CodePipeline) GetThirdPartyJobDetailsRequest(input *GetThirdPartyJobDet // Please also see https://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/GetThirdPartyJobDetails func (c *CodePipeline) GetThirdPartyJobDetails(input *GetThirdPartyJobDetailsInput) (*GetThirdPartyJobDetailsOutput, error) { req, out := c.GetThirdPartyJobDetailsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetThirdPartyJobDetailsWithContext is the same as GetThirdPartyJobDetails with the addition of +// the ability to pass a context and additional request options. +// +// See GetThirdPartyJobDetails 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 *CodePipeline) GetThirdPartyJobDetailsWithContext(ctx aws.Context, input *GetThirdPartyJobDetailsInput, opts ...request.Option) (*GetThirdPartyJobDetailsOutput, error) { + req, out := c.GetThirdPartyJobDetailsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opListActionTypes = "ListActionTypes" @@ -1035,8 +1230,23 @@ func (c *CodePipeline) ListActionTypesRequest(input *ListActionTypesInput) (req // Please also see https://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/ListActionTypes func (c *CodePipeline) ListActionTypes(input *ListActionTypesInput) (*ListActionTypesOutput, error) { req, out := c.ListActionTypesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListActionTypesWithContext is the same as ListActionTypes with the addition of +// the ability to pass a context and additional request options. +// +// See ListActionTypes 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 *CodePipeline) ListActionTypesWithContext(ctx aws.Context, input *ListActionTypesInput, opts ...request.Option) (*ListActionTypesOutput, error) { + req, out := c.ListActionTypesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opListPipelines = "ListPipelines" @@ -1101,8 +1311,23 @@ func (c *CodePipeline) ListPipelinesRequest(input *ListPipelinesInput) (req *req // Please also see https://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/ListPipelines func (c *CodePipeline) ListPipelines(input *ListPipelinesInput) (*ListPipelinesOutput, error) { req, out := c.ListPipelinesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListPipelinesWithContext is the same as ListPipelines with the addition of +// the ability to pass a context and additional request options. +// +// See ListPipelines 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 *CodePipeline) ListPipelinesWithContext(ctx aws.Context, input *ListPipelinesInput, opts ...request.Option) (*ListPipelinesOutput, error) { + req, out := c.ListPipelinesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opPollForJobs = "PollForJobs" @@ -1174,8 +1399,23 @@ func (c *CodePipeline) PollForJobsRequest(input *PollForJobsInput) (req *request // Please also see https://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/PollForJobs func (c *CodePipeline) PollForJobs(input *PollForJobsInput) (*PollForJobsOutput, error) { req, out := c.PollForJobsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// PollForJobsWithContext is the same as PollForJobs with the addition of +// the ability to pass a context and additional request options. +// +// See PollForJobs 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 *CodePipeline) PollForJobsWithContext(ctx aws.Context, input *PollForJobsInput, opts ...request.Option) (*PollForJobsOutput, error) { + req, out := c.PollForJobsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opPollForThirdPartyJobs = "PollForThirdPartyJobs" @@ -1247,8 +1487,23 @@ func (c *CodePipeline) PollForThirdPartyJobsRequest(input *PollForThirdPartyJobs // Please also see https://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/PollForThirdPartyJobs func (c *CodePipeline) PollForThirdPartyJobs(input *PollForThirdPartyJobsInput) (*PollForThirdPartyJobsOutput, error) { req, out := c.PollForThirdPartyJobsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// PollForThirdPartyJobsWithContext is the same as PollForThirdPartyJobs with the addition of +// the ability to pass a context and additional request options. +// +// See PollForThirdPartyJobs 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 *CodePipeline) PollForThirdPartyJobsWithContext(ctx aws.Context, input *PollForThirdPartyJobsInput, opts ...request.Option) (*PollForThirdPartyJobsOutput, error) { + req, out := c.PollForThirdPartyJobsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opPutActionRevision = "PutActionRevision" @@ -1321,8 +1576,23 @@ func (c *CodePipeline) PutActionRevisionRequest(input *PutActionRevisionInput) ( // Please also see https://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/PutActionRevision func (c *CodePipeline) PutActionRevision(input *PutActionRevisionInput) (*PutActionRevisionOutput, error) { req, out := c.PutActionRevisionRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// PutActionRevisionWithContext is the same as PutActionRevision with the addition of +// the ability to pass a context and additional request options. +// +// See PutActionRevision 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 *CodePipeline) PutActionRevisionWithContext(ctx aws.Context, input *PutActionRevisionInput, opts ...request.Option) (*PutActionRevisionOutput, error) { + req, out := c.PutActionRevisionRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opPutApprovalResult = "PutApprovalResult" @@ -1402,8 +1672,23 @@ func (c *CodePipeline) PutApprovalResultRequest(input *PutApprovalResultInput) ( // Please also see https://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/PutApprovalResult func (c *CodePipeline) PutApprovalResult(input *PutApprovalResultInput) (*PutApprovalResultOutput, error) { req, out := c.PutApprovalResultRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// PutApprovalResultWithContext is the same as PutApprovalResult with the addition of +// the ability to pass a context and additional request options. +// +// See PutApprovalResult 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 *CodePipeline) PutApprovalResultWithContext(ctx aws.Context, input *PutApprovalResultInput, opts ...request.Option) (*PutApprovalResultOutput, error) { + req, out := c.PutApprovalResultRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opPutJobFailureResult = "PutJobFailureResult" @@ -1476,8 +1761,23 @@ func (c *CodePipeline) PutJobFailureResultRequest(input *PutJobFailureResultInpu // Please also see https://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/PutJobFailureResult func (c *CodePipeline) PutJobFailureResult(input *PutJobFailureResultInput) (*PutJobFailureResultOutput, error) { req, out := c.PutJobFailureResultRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// PutJobFailureResultWithContext is the same as PutJobFailureResult with the addition of +// the ability to pass a context and additional request options. +// +// See PutJobFailureResult 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 *CodePipeline) PutJobFailureResultWithContext(ctx aws.Context, input *PutJobFailureResultInput, opts ...request.Option) (*PutJobFailureResultOutput, error) { + req, out := c.PutJobFailureResultRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opPutJobSuccessResult = "PutJobSuccessResult" @@ -1550,8 +1850,23 @@ func (c *CodePipeline) PutJobSuccessResultRequest(input *PutJobSuccessResultInpu // Please also see https://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/PutJobSuccessResult func (c *CodePipeline) PutJobSuccessResult(input *PutJobSuccessResultInput) (*PutJobSuccessResultOutput, error) { req, out := c.PutJobSuccessResultRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// PutJobSuccessResultWithContext is the same as PutJobSuccessResult with the addition of +// the ability to pass a context and additional request options. +// +// See PutJobSuccessResult 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 *CodePipeline) PutJobSuccessResultWithContext(ctx aws.Context, input *PutJobSuccessResultInput, opts ...request.Option) (*PutJobSuccessResultOutput, error) { + req, out := c.PutJobSuccessResultRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opPutThirdPartyJobFailureResult = "PutThirdPartyJobFailureResult" @@ -1627,8 +1942,23 @@ func (c *CodePipeline) PutThirdPartyJobFailureResultRequest(input *PutThirdParty // Please also see https://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/PutThirdPartyJobFailureResult func (c *CodePipeline) PutThirdPartyJobFailureResult(input *PutThirdPartyJobFailureResultInput) (*PutThirdPartyJobFailureResultOutput, error) { req, out := c.PutThirdPartyJobFailureResultRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// PutThirdPartyJobFailureResultWithContext is the same as PutThirdPartyJobFailureResult with the addition of +// the ability to pass a context and additional request options. +// +// See PutThirdPartyJobFailureResult 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 *CodePipeline) PutThirdPartyJobFailureResultWithContext(ctx aws.Context, input *PutThirdPartyJobFailureResultInput, opts ...request.Option) (*PutThirdPartyJobFailureResultOutput, error) { + req, out := c.PutThirdPartyJobFailureResultRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opPutThirdPartyJobSuccessResult = "PutThirdPartyJobSuccessResult" @@ -1704,8 +2034,23 @@ func (c *CodePipeline) PutThirdPartyJobSuccessResultRequest(input *PutThirdParty // Please also see https://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/PutThirdPartyJobSuccessResult func (c *CodePipeline) PutThirdPartyJobSuccessResult(input *PutThirdPartyJobSuccessResultInput) (*PutThirdPartyJobSuccessResultOutput, error) { req, out := c.PutThirdPartyJobSuccessResultRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// PutThirdPartyJobSuccessResultWithContext is the same as PutThirdPartyJobSuccessResult with the addition of +// the ability to pass a context and additional request options. +// +// See PutThirdPartyJobSuccessResult 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 *CodePipeline) PutThirdPartyJobSuccessResultWithContext(ctx aws.Context, input *PutThirdPartyJobSuccessResultInput, opts ...request.Option) (*PutThirdPartyJobSuccessResultOutput, error) { + req, out := c.PutThirdPartyJobSuccessResultRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opRetryStageExecution = "RetryStageExecution" @@ -1785,8 +2130,23 @@ func (c *CodePipeline) RetryStageExecutionRequest(input *RetryStageExecutionInpu // Please also see https://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/RetryStageExecution func (c *CodePipeline) RetryStageExecution(input *RetryStageExecutionInput) (*RetryStageExecutionOutput, error) { req, out := c.RetryStageExecutionRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// RetryStageExecutionWithContext is the same as RetryStageExecution with the addition of +// the ability to pass a context and additional request options. +// +// See RetryStageExecution 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 *CodePipeline) RetryStageExecutionWithContext(ctx aws.Context, input *RetryStageExecutionInput, opts ...request.Option) (*RetryStageExecutionOutput, error) { + req, out := c.RetryStageExecutionRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opStartPipelineExecution = "StartPipelineExecution" @@ -1854,8 +2214,23 @@ func (c *CodePipeline) StartPipelineExecutionRequest(input *StartPipelineExecuti // Please also see https://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/StartPipelineExecution func (c *CodePipeline) StartPipelineExecution(input *StartPipelineExecutionInput) (*StartPipelineExecutionOutput, error) { req, out := c.StartPipelineExecutionRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// StartPipelineExecutionWithContext is the same as StartPipelineExecution with the addition of +// the ability to pass a context and additional request options. +// +// See StartPipelineExecution 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 *CodePipeline) StartPipelineExecutionWithContext(ctx aws.Context, input *StartPipelineExecutionInput, opts ...request.Option) (*StartPipelineExecutionOutput, error) { + req, out := c.StartPipelineExecutionRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opUpdatePipeline = "UpdatePipeline" @@ -1934,8 +2309,23 @@ func (c *CodePipeline) UpdatePipelineRequest(input *UpdatePipelineInput) (req *r // Please also see https://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/UpdatePipeline func (c *CodePipeline) UpdatePipeline(input *UpdatePipelineInput) (*UpdatePipelineOutput, error) { req, out := c.UpdatePipelineRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// UpdatePipelineWithContext is the same as UpdatePipeline with the addition of +// the ability to pass a context and additional request options. +// +// See UpdatePipeline 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 *CodePipeline) UpdatePipelineWithContext(ctx aws.Context, input *UpdatePipelineInput, opts ...request.Option) (*UpdatePipelineOutput, error) { + req, out := c.UpdatePipelineRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // Represents an AWS session credentials object. These credentials are temporary diff --git a/vendor/github.com/aws/aws-sdk-go/service/codepipeline/doc.go b/vendor/github.com/aws/aws-sdk-go/service/codepipeline/doc.go new file mode 100644 index 000000000..0746cc4cd --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/service/codepipeline/doc.go @@ -0,0 +1,188 @@ +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. + +// Package codepipeline provides the client and types for making API +// requests to AWS CodePipeline. +// +// Overview +// +// This is the AWS CodePipeline API Reference. This guide provides descriptions +// of the actions and data types for AWS CodePipeline. Some functionality for +// your pipeline is only configurable through the API. For additional information, +// see the AWS CodePipeline User Guide (http://docs.aws.amazon.com/codepipeline/latest/userguide/welcome.html). +// +// You can use the AWS CodePipeline API to work with pipelines, stages, actions, +// gates, and transitions, as described below. +// +// Pipelines are models of automated release processes. Each pipeline is uniquely +// named, and consists of actions, gates, and stages. +// +// You can work with pipelines by calling: +// +// * CreatePipeline, which creates a uniquely-named pipeline. +// +// * DeletePipeline, which deletes the specified pipeline. +// +// * GetPipeline, which returns information about a pipeline structure. +// +// * GetPipelineExecution, which returns information about a specific execution +// of a pipeline. +// +// * GetPipelineState, which returns information about the current state +// of the stages and actions of a pipeline. +// +// * ListPipelines, which gets a summary of all of the pipelines associated +// with your account. +// +// * StartPipelineExecution, which runs the the most recent revision of an +// artifact through the pipeline. +// +// * UpdatePipeline, which updates a pipeline with edits or changes to the +// structure of the pipeline. +// +// Pipelines include stages, which are logical groupings of gates and actions. +// Each stage contains one or more actions that must complete before the next +// stage begins. A stage will result in success or failure. If a stage fails, +// then the pipeline stops at that stage and will remain stopped until either +// a new version of an artifact appears in the source location, or a user takes +// action to re-run the most recent artifact through the pipeline. You can call +// GetPipelineState, which displays the status of a pipeline, including the +// status of stages in the pipeline, or GetPipeline, which returns the entire +// structure of the pipeline, including the stages of that pipeline. For more +// information about the structure of stages and actions, also refer to the +// AWS CodePipeline Pipeline Structure Reference (http://docs.aws.amazon.com/codepipeline/latest/userguide/pipeline-structure.html). +// +// Pipeline stages include actions, which are categorized into categories such +// as source or build actions performed within a stage of a pipeline. For example, +// you can use a source action to import artifacts into a pipeline from a source +// such as Amazon S3. Like stages, you do not work with actions directly in +// most cases, but you do define and interact with actions when working with +// pipeline operations such as CreatePipeline and GetPipelineState. +// +// Pipelines also include transitions, which allow the transition of artifacts +// from one stage to the next in a pipeline after the actions in one stage complete. +// +// You can work with transitions by calling: +// +// * DisableStageTransition, which prevents artifacts from transitioning +// to the next stage in a pipeline. +// +// * EnableStageTransition, which enables transition of artifacts between +// stages in a pipeline. +// +// Using the API to integrate with AWS CodePipeline +// +// For third-party integrators or developers who want to create their own integrations +// with AWS CodePipeline, the expected sequence varies from the standard API +// user. In order to integrate with AWS CodePipeline, developers will need to +// work with the following items: +// +// Jobs, which are instances of an action. For example, a job for a source action +// might import a revision of an artifact from a source. +// +// You can work with jobs by calling: +// +// * AcknowledgeJob, which confirms whether a job worker has received the +// specified job, +// +// * GetJobDetails, which returns the details of a job, +// +// * PollForJobs, which determines whether there are any jobs to act upon, +// +// +// * PutJobFailureResult, which provides details of a job failure, and +// +// * PutJobSuccessResult, which provides details of a job success. +// +// Third party jobs, which are instances of an action created by a partner action +// and integrated into AWS CodePipeline. Partner actions are created by members +// of the AWS Partner Network. +// +// You can work with third party jobs by calling: +// +// * AcknowledgeThirdPartyJob, which confirms whether a job worker has received +// the specified job, +// +// * GetThirdPartyJobDetails, which requests the details of a job for a partner +// action, +// +// * PollForThirdPartyJobs, which determines whether there are any jobs to +// act upon, +// +// * PutThirdPartyJobFailureResult, which provides details of a job failure, +// and +// +// * PutThirdPartyJobSuccessResult, which provides details of a job success. +// +// See https://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09 for more information on this service. +// +// See codepipeline package documentation for more information. +// https://docs.aws.amazon.com/sdk-for-go/api/service/codepipeline/ +// +// Using the Client +// +// To use the client for AWS CodePipeline you will first need +// to create a new instance of it. +// +// When creating a client for an AWS service you'll first need to have a Session +// already created. The Session provides configuration that can be shared +// between multiple service clients. Additional configuration can be applied to +// the Session and service's client when they are constructed. The aws package's +// Config type contains several fields such as Region for the AWS Region the +// client should make API requests too. The optional Config value can be provided +// as the variadic argument for Sessions and client creation. +// +// Once the service's client is created you can use it to make API requests the +// AWS service. These clients are safe to use concurrently. +// +// // Create a session to share configuration, and load external configuration. +// sess := session.Must(session.NewSession()) +// +// // Create the service's client with the session. +// svc := codepipeline.New(sess) +// +// See the SDK's documentation for more information on how to use service clients. +// https://docs.aws.amazon.com/sdk-for-go/api/ +// +// See aws package's Config type for more information on configuration options. +// https://docs.aws.amazon.com/sdk-for-go/api/aws/#Config +// +// See the AWS CodePipeline client CodePipeline for more +// information on creating the service's client. +// https://docs.aws.amazon.com/sdk-for-go/api/service/codepipeline/#New +// +// Once the client is created you can make an API request to the service. +// Each API method takes a input parameter, and returns the service response +// and an error. +// +// The API method will document which error codes the service can be returned +// by the operation if the service models the API operation's errors. These +// errors will also be available as const strings prefixed with "ErrCode". +// +// result, err := svc.AcknowledgeJob(params) +// if err != nil { +// // Cast err to awserr.Error to handle specific error codes. +// aerr, ok := err.(awserr.Error) +// if ok && aerr.Code() == { +// // Specific error code handling +// } +// return err +// } +// +// fmt.Println("AcknowledgeJob result:") +// fmt.Println(result) +// +// Using the Client with Context +// +// The service's client also provides methods to make API requests with a Context +// value. This allows you to control the timeout, and cancellation of pending +// requests. These methods also take request Option as variadic parameter to apply +// additional configuration to the API request. +// +// ctx := context.Background() +// +// result, err := svc.AcknowledgeJobWithContext(ctx, params) +// +// See the request package documentation for more information on using Context pattern +// with the SDK. +// https://docs.aws.amazon.com/sdk-for-go/api/aws/request/ +package codepipeline diff --git a/vendor/github.com/aws/aws-sdk-go/service/codepipeline/errors.go b/vendor/github.com/aws/aws-sdk-go/service/codepipeline/errors.go index 7e664c0e7..ca160b26a 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/codepipeline/errors.go +++ b/vendor/github.com/aws/aws-sdk-go/service/codepipeline/errors.go @@ -1,4 +1,4 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. package codepipeline diff --git a/vendor/github.com/aws/aws-sdk-go/service/codepipeline/service.go b/vendor/github.com/aws/aws-sdk-go/service/codepipeline/service.go index 960d8f52a..8b7737abb 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/codepipeline/service.go +++ b/vendor/github.com/aws/aws-sdk-go/service/codepipeline/service.go @@ -1,4 +1,4 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. package codepipeline @@ -11,118 +11,12 @@ import ( "github.com/aws/aws-sdk-go/private/protocol/jsonrpc" ) -// Overview +// CodePipeline provides the API operation methods for making requests to +// AWS CodePipeline. See this package's package overview docs +// for details on the service. // -// This is the AWS CodePipeline API Reference. This guide provides descriptions -// of the actions and data types for AWS CodePipeline. Some functionality for -// your pipeline is only configurable through the API. For additional information, -// see the AWS CodePipeline User Guide (http://docs.aws.amazon.com/codepipeline/latest/userguide/welcome.html). -// -// You can use the AWS CodePipeline API to work with pipelines, stages, actions, -// gates, and transitions, as described below. -// -// Pipelines are models of automated release processes. Each pipeline is uniquely -// named, and consists of actions, gates, and stages. -// -// You can work with pipelines by calling: -// -// * CreatePipeline, which creates a uniquely-named pipeline. -// -// * DeletePipeline, which deletes the specified pipeline. -// -// * GetPipeline, which returns information about a pipeline structure. -// -// * GetPipelineExecution, which returns information about a specific execution -// of a pipeline. -// -// * GetPipelineState, which returns information about the current state -// of the stages and actions of a pipeline. -// -// * ListPipelines, which gets a summary of all of the pipelines associated -// with your account. -// -// * StartPipelineExecution, which runs the the most recent revision of an -// artifact through the pipeline. -// -// * UpdatePipeline, which updates a pipeline with edits or changes to the -// structure of the pipeline. -// -// Pipelines include stages, which are logical groupings of gates and actions. -// Each stage contains one or more actions that must complete before the next -// stage begins. A stage will result in success or failure. If a stage fails, -// then the pipeline stops at that stage and will remain stopped until either -// a new version of an artifact appears in the source location, or a user takes -// action to re-run the most recent artifact through the pipeline. You can call -// GetPipelineState, which displays the status of a pipeline, including the -// status of stages in the pipeline, or GetPipeline, which returns the entire -// structure of the pipeline, including the stages of that pipeline. For more -// information about the structure of stages and actions, also refer to the -// AWS CodePipeline Pipeline Structure Reference (http://docs.aws.amazon.com/codepipeline/latest/userguide/pipeline-structure.html). -// -// Pipeline stages include actions, which are categorized into categories such -// as source or build actions performed within a stage of a pipeline. For example, -// you can use a source action to import artifacts into a pipeline from a source -// such as Amazon S3. Like stages, you do not work with actions directly in -// most cases, but you do define and interact with actions when working with -// pipeline operations such as CreatePipeline and GetPipelineState. -// -// Pipelines also include transitions, which allow the transition of artifacts -// from one stage to the next in a pipeline after the actions in one stage complete. -// -// You can work with transitions by calling: -// -// * DisableStageTransition, which prevents artifacts from transitioning -// to the next stage in a pipeline. -// -// * EnableStageTransition, which enables transition of artifacts between -// stages in a pipeline. -// -// Using the API to integrate with AWS CodePipeline -// -// For third-party integrators or developers who want to create their own integrations -// with AWS CodePipeline, the expected sequence varies from the standard API -// user. In order to integrate with AWS CodePipeline, developers will need to -// work with the following items: -// -// Jobs, which are instances of an action. For example, a job for a source action -// might import a revision of an artifact from a source. -// -// You can work with jobs by calling: -// -// * AcknowledgeJob, which confirms whether a job worker has received the -// specified job, -// -// * GetJobDetails, which returns the details of a job, -// -// * PollForJobs, which determines whether there are any jobs to act upon, -// -// -// * PutJobFailureResult, which provides details of a job failure, and -// -// * PutJobSuccessResult, which provides details of a job success. -// -// Third party jobs, which are instances of an action created by a partner action -// and integrated into AWS CodePipeline. Partner actions are created by members -// of the AWS Partner Network. -// -// You can work with third party jobs by calling: -// -// * AcknowledgeThirdPartyJob, which confirms whether a job worker has received -// the specified job, -// -// * GetThirdPartyJobDetails, which requests the details of a job for a partner -// action, -// -// * PollForThirdPartyJobs, which determines whether there are any jobs to -// act upon, -// -// * PutThirdPartyJobFailureResult, which provides details of a job failure, -// and -// -// * PutThirdPartyJobSuccessResult, which provides details of a job success. -// The service client's operations are safe to be used concurrently. -// It is not safe to mutate any of the client's properties though. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09 +// CodePipeline methods are safe to use concurrently. It is not safe to +// modify mutate any of the struct's properties though. type CodePipeline struct { *client.Client } diff --git a/vendor/github.com/aws/aws-sdk-go/service/cognitoidentity/api.go b/vendor/github.com/aws/aws-sdk-go/service/cognitoidentity/api.go new file mode 100644 index 000000000..6e01c3c23 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/service/cognitoidentity/api.go @@ -0,0 +1,4112 @@ +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. + +package cognitoidentity + +import ( + "fmt" + "time" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/awsutil" + "github.com/aws/aws-sdk-go/aws/request" + "github.com/aws/aws-sdk-go/private/protocol" + "github.com/aws/aws-sdk-go/private/protocol/jsonrpc" +) + +const opCreateIdentityPool = "CreateIdentityPool" + +// CreateIdentityPoolRequest generates a "aws/request.Request" representing the +// client's request for the CreateIdentityPool operation. The "output" return +// value can be used to capture response data after the request's "Send" method +// is called. +// +// See CreateIdentityPool for usage and error information. +// +// Creating a request object using this method should be used when you want to inject +// custom logic into the request's lifecycle using a custom handler, or if you want to +// access properties on the request object before or after sending the request. If +// you just want the service response, call the CreateIdentityPool method directly +// instead. +// +// Note: You must call the "Send" method on the returned request object in order +// to execute the request. +// +// // Example sending a request using the CreateIdentityPoolRequest method. +// req, resp := client.CreateIdentityPoolRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cognito-identity-2014-06-30/CreateIdentityPool +func (c *CognitoIdentity) CreateIdentityPoolRequest(input *CreateIdentityPoolInput) (req *request.Request, output *IdentityPool) { + op := &request.Operation{ + Name: opCreateIdentityPool, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &CreateIdentityPoolInput{} + } + + output = &IdentityPool{} + req = c.newRequest(op, input, output) + return +} + +// CreateIdentityPool API operation for Amazon Cognito Identity. +// +// Creates a new identity pool. The identity pool is a store of user identity +// information that is specific to your AWS account. The limit on identity pools +// is 60 per account. The keys for SupportedLoginProviders are as follows: +// +// * Facebook: graph.facebook.com +// +// * Google: accounts.google.com +// +// * Amazon: www.amazon.com +// +// * Twitter: api.twitter.com +// +// * Digits: www.digits.com +// +// You must use AWS Developer credentials to call this API. +// +// 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 Cognito Identity's +// API operation CreateIdentityPool for usage and error information. +// +// Returned Error Codes: +// * ErrCodeInvalidParameterException "InvalidParameterException" +// Thrown for missing or bad input parameter(s). +// +// * ErrCodeNotAuthorizedException "NotAuthorizedException" +// Thrown when a user is not authorized to access the requested resource. +// +// * ErrCodeResourceConflictException "ResourceConflictException" +// Thrown when a user tries to use a login which is already linked to another +// account. +// +// * ErrCodeTooManyRequestsException "TooManyRequestsException" +// Thrown when a request is throttled. +// +// * ErrCodeInternalErrorException "InternalErrorException" +// Thrown when the service encounters an error during processing the request. +// +// * ErrCodeLimitExceededException "LimitExceededException" +// Thrown when the total number of user pools has exceeded a preset limit. +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cognito-identity-2014-06-30/CreateIdentityPool +func (c *CognitoIdentity) CreateIdentityPool(input *CreateIdentityPoolInput) (*IdentityPool, error) { + req, out := c.CreateIdentityPoolRequest(input) + return out, req.Send() +} + +// CreateIdentityPoolWithContext is the same as CreateIdentityPool with the addition of +// the ability to pass a context and additional request options. +// +// See CreateIdentityPool 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 *CognitoIdentity) CreateIdentityPoolWithContext(ctx aws.Context, input *CreateIdentityPoolInput, opts ...request.Option) (*IdentityPool, error) { + req, out := c.CreateIdentityPoolRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opDeleteIdentities = "DeleteIdentities" + +// DeleteIdentitiesRequest generates a "aws/request.Request" representing the +// client's request for the DeleteIdentities operation. The "output" return +// value can be used to capture response data after the request's "Send" method +// is called. +// +// See DeleteIdentities for usage and error information. +// +// Creating a request object using this method should be used when you want to inject +// custom logic into the request's lifecycle using a custom handler, or if you want to +// access properties on the request object before or after sending the request. If +// you just want the service response, call the DeleteIdentities method directly +// instead. +// +// Note: You must call the "Send" method on the returned request object in order +// to execute the request. +// +// // Example sending a request using the DeleteIdentitiesRequest method. +// req, resp := client.DeleteIdentitiesRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cognito-identity-2014-06-30/DeleteIdentities +func (c *CognitoIdentity) DeleteIdentitiesRequest(input *DeleteIdentitiesInput) (req *request.Request, output *DeleteIdentitiesOutput) { + op := &request.Operation{ + Name: opDeleteIdentities, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &DeleteIdentitiesInput{} + } + + output = &DeleteIdentitiesOutput{} + req = c.newRequest(op, input, output) + return +} + +// DeleteIdentities API operation for Amazon Cognito Identity. +// +// Deletes identities from an identity pool. You can specify a list of 1-60 +// identities that you want to delete. +// +// You must use AWS Developer credentials to call this API. +// +// 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 Cognito Identity's +// API operation DeleteIdentities for usage and error information. +// +// Returned Error Codes: +// * ErrCodeInvalidParameterException "InvalidParameterException" +// Thrown for missing or bad input parameter(s). +// +// * ErrCodeTooManyRequestsException "TooManyRequestsException" +// Thrown when a request is throttled. +// +// * ErrCodeInternalErrorException "InternalErrorException" +// Thrown when the service encounters an error during processing the request. +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cognito-identity-2014-06-30/DeleteIdentities +func (c *CognitoIdentity) DeleteIdentities(input *DeleteIdentitiesInput) (*DeleteIdentitiesOutput, error) { + req, out := c.DeleteIdentitiesRequest(input) + return out, req.Send() +} + +// DeleteIdentitiesWithContext is the same as DeleteIdentities with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteIdentities 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 *CognitoIdentity) DeleteIdentitiesWithContext(ctx aws.Context, input *DeleteIdentitiesInput, opts ...request.Option) (*DeleteIdentitiesOutput, error) { + req, out := c.DeleteIdentitiesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opDeleteIdentityPool = "DeleteIdentityPool" + +// DeleteIdentityPoolRequest generates a "aws/request.Request" representing the +// client's request for the DeleteIdentityPool operation. The "output" return +// value can be used to capture response data after the request's "Send" method +// is called. +// +// See DeleteIdentityPool for usage and error information. +// +// Creating a request object using this method should be used when you want to inject +// custom logic into the request's lifecycle using a custom handler, or if you want to +// access properties on the request object before or after sending the request. If +// you just want the service response, call the DeleteIdentityPool method directly +// instead. +// +// Note: You must call the "Send" method on the returned request object in order +// to execute the request. +// +// // Example sending a request using the DeleteIdentityPoolRequest method. +// req, resp := client.DeleteIdentityPoolRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cognito-identity-2014-06-30/DeleteIdentityPool +func (c *CognitoIdentity) DeleteIdentityPoolRequest(input *DeleteIdentityPoolInput) (req *request.Request, output *DeleteIdentityPoolOutput) { + op := &request.Operation{ + Name: opDeleteIdentityPool, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &DeleteIdentityPoolInput{} + } + + output = &DeleteIdentityPoolOutput{} + req = c.newRequest(op, input, output) + req.Handlers.Unmarshal.Remove(jsonrpc.UnmarshalHandler) + req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) + return +} + +// DeleteIdentityPool API operation for Amazon Cognito Identity. +// +// Deletes a user pool. Once a pool is deleted, users will not be able to authenticate +// with the pool. +// +// You must use AWS Developer credentials to call this API. +// +// 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 Cognito Identity's +// API operation DeleteIdentityPool for usage and error information. +// +// Returned Error Codes: +// * ErrCodeInvalidParameterException "InvalidParameterException" +// Thrown for missing or bad input parameter(s). +// +// * ErrCodeResourceNotFoundException "ResourceNotFoundException" +// Thrown when the requested resource (for example, a dataset or record) does +// not exist. +// +// * ErrCodeNotAuthorizedException "NotAuthorizedException" +// Thrown when a user is not authorized to access the requested resource. +// +// * ErrCodeTooManyRequestsException "TooManyRequestsException" +// Thrown when a request is throttled. +// +// * ErrCodeInternalErrorException "InternalErrorException" +// Thrown when the service encounters an error during processing the request. +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cognito-identity-2014-06-30/DeleteIdentityPool +func (c *CognitoIdentity) DeleteIdentityPool(input *DeleteIdentityPoolInput) (*DeleteIdentityPoolOutput, error) { + req, out := c.DeleteIdentityPoolRequest(input) + return out, req.Send() +} + +// DeleteIdentityPoolWithContext is the same as DeleteIdentityPool with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteIdentityPool 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 *CognitoIdentity) DeleteIdentityPoolWithContext(ctx aws.Context, input *DeleteIdentityPoolInput, opts ...request.Option) (*DeleteIdentityPoolOutput, error) { + req, out := c.DeleteIdentityPoolRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opDescribeIdentity = "DescribeIdentity" + +// DescribeIdentityRequest generates a "aws/request.Request" representing the +// client's request for the DescribeIdentity operation. The "output" return +// value can be used to capture response data after the request's "Send" method +// is called. +// +// See DescribeIdentity for usage and error information. +// +// Creating a request object using this method should be used when you want to inject +// custom logic into the request's lifecycle using a custom handler, or if you want to +// access properties on the request object before or after sending the request. If +// you just want the service response, call the DescribeIdentity method directly +// instead. +// +// Note: You must call the "Send" method on the returned request object in order +// to execute the request. +// +// // Example sending a request using the DescribeIdentityRequest method. +// req, resp := client.DescribeIdentityRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cognito-identity-2014-06-30/DescribeIdentity +func (c *CognitoIdentity) DescribeIdentityRequest(input *DescribeIdentityInput) (req *request.Request, output *IdentityDescription) { + op := &request.Operation{ + Name: opDescribeIdentity, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &DescribeIdentityInput{} + } + + output = &IdentityDescription{} + req = c.newRequest(op, input, output) + return +} + +// DescribeIdentity API operation for Amazon Cognito Identity. +// +// Returns metadata related to the given identity, including when the identity +// was created and any associated linked logins. +// +// You must use AWS Developer credentials to call this API. +// +// 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 Cognito Identity's +// API operation DescribeIdentity for usage and error information. +// +// Returned Error Codes: +// * ErrCodeInvalidParameterException "InvalidParameterException" +// Thrown for missing or bad input parameter(s). +// +// * ErrCodeResourceNotFoundException "ResourceNotFoundException" +// Thrown when the requested resource (for example, a dataset or record) does +// not exist. +// +// * ErrCodeNotAuthorizedException "NotAuthorizedException" +// Thrown when a user is not authorized to access the requested resource. +// +// * ErrCodeTooManyRequestsException "TooManyRequestsException" +// Thrown when a request is throttled. +// +// * ErrCodeInternalErrorException "InternalErrorException" +// Thrown when the service encounters an error during processing the request. +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cognito-identity-2014-06-30/DescribeIdentity +func (c *CognitoIdentity) DescribeIdentity(input *DescribeIdentityInput) (*IdentityDescription, error) { + req, out := c.DescribeIdentityRequest(input) + return out, req.Send() +} + +// DescribeIdentityWithContext is the same as DescribeIdentity with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeIdentity 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 *CognitoIdentity) DescribeIdentityWithContext(ctx aws.Context, input *DescribeIdentityInput, opts ...request.Option) (*IdentityDescription, error) { + req, out := c.DescribeIdentityRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opDescribeIdentityPool = "DescribeIdentityPool" + +// DescribeIdentityPoolRequest generates a "aws/request.Request" representing the +// client's request for the DescribeIdentityPool operation. The "output" return +// value can be used to capture response data after the request's "Send" method +// is called. +// +// See DescribeIdentityPool for usage and error information. +// +// Creating a request object using this method should be used when you want to inject +// custom logic into the request's lifecycle using a custom handler, or if you want to +// access properties on the request object before or after sending the request. If +// you just want the service response, call the DescribeIdentityPool method directly +// instead. +// +// Note: You must call the "Send" method on the returned request object in order +// to execute the request. +// +// // Example sending a request using the DescribeIdentityPoolRequest method. +// req, resp := client.DescribeIdentityPoolRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cognito-identity-2014-06-30/DescribeIdentityPool +func (c *CognitoIdentity) DescribeIdentityPoolRequest(input *DescribeIdentityPoolInput) (req *request.Request, output *IdentityPool) { + op := &request.Operation{ + Name: opDescribeIdentityPool, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &DescribeIdentityPoolInput{} + } + + output = &IdentityPool{} + req = c.newRequest(op, input, output) + return +} + +// DescribeIdentityPool API operation for Amazon Cognito Identity. +// +// Gets details about a particular identity pool, including the pool name, ID +// description, creation date, and current number of users. +// +// You must use AWS Developer credentials to call this API. +// +// 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 Cognito Identity's +// API operation DescribeIdentityPool for usage and error information. +// +// Returned Error Codes: +// * ErrCodeInvalidParameterException "InvalidParameterException" +// Thrown for missing or bad input parameter(s). +// +// * ErrCodeResourceNotFoundException "ResourceNotFoundException" +// Thrown when the requested resource (for example, a dataset or record) does +// not exist. +// +// * ErrCodeNotAuthorizedException "NotAuthorizedException" +// Thrown when a user is not authorized to access the requested resource. +// +// * ErrCodeTooManyRequestsException "TooManyRequestsException" +// Thrown when a request is throttled. +// +// * ErrCodeInternalErrorException "InternalErrorException" +// Thrown when the service encounters an error during processing the request. +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cognito-identity-2014-06-30/DescribeIdentityPool +func (c *CognitoIdentity) DescribeIdentityPool(input *DescribeIdentityPoolInput) (*IdentityPool, error) { + req, out := c.DescribeIdentityPoolRequest(input) + return out, req.Send() +} + +// DescribeIdentityPoolWithContext is the same as DescribeIdentityPool with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeIdentityPool 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 *CognitoIdentity) DescribeIdentityPoolWithContext(ctx aws.Context, input *DescribeIdentityPoolInput, opts ...request.Option) (*IdentityPool, error) { + req, out := c.DescribeIdentityPoolRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opGetCredentialsForIdentity = "GetCredentialsForIdentity" + +// GetCredentialsForIdentityRequest generates a "aws/request.Request" representing the +// client's request for the GetCredentialsForIdentity operation. The "output" return +// value can be used to capture response data after the request's "Send" method +// is called. +// +// See GetCredentialsForIdentity for usage and error information. +// +// Creating a request object using this method should be used when you want to inject +// custom logic into the request's lifecycle using a custom handler, or if you want to +// access properties on the request object before or after sending the request. If +// you just want the service response, call the GetCredentialsForIdentity method directly +// instead. +// +// Note: You must call the "Send" method on the returned request object in order +// to execute the request. +// +// // Example sending a request using the GetCredentialsForIdentityRequest method. +// req, resp := client.GetCredentialsForIdentityRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cognito-identity-2014-06-30/GetCredentialsForIdentity +func (c *CognitoIdentity) GetCredentialsForIdentityRequest(input *GetCredentialsForIdentityInput) (req *request.Request, output *GetCredentialsForIdentityOutput) { + op := &request.Operation{ + Name: opGetCredentialsForIdentity, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &GetCredentialsForIdentityInput{} + } + + output = &GetCredentialsForIdentityOutput{} + req = c.newRequest(op, input, output) + return +} + +// GetCredentialsForIdentity API operation for Amazon Cognito Identity. +// +// Returns credentials for the provided identity ID. Any provided logins will +// be validated against supported login providers. If the token is for cognito-identity.amazonaws.com, +// it will be passed through to AWS Security Token Service with the appropriate +// role for the token. +// +// This is a public API. You do not need any credentials to call this API. +// +// 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 Cognito Identity's +// API operation GetCredentialsForIdentity for usage and error information. +// +// Returned Error Codes: +// * ErrCodeInvalidParameterException "InvalidParameterException" +// Thrown for missing or bad input parameter(s). +// +// * ErrCodeResourceNotFoundException "ResourceNotFoundException" +// Thrown when the requested resource (for example, a dataset or record) does +// not exist. +// +// * ErrCodeNotAuthorizedException "NotAuthorizedException" +// Thrown when a user is not authorized to access the requested resource. +// +// * ErrCodeResourceConflictException "ResourceConflictException" +// Thrown when a user tries to use a login which is already linked to another +// account. +// +// * ErrCodeTooManyRequestsException "TooManyRequestsException" +// Thrown when a request is throttled. +// +// * ErrCodeInvalidIdentityPoolConfigurationException "InvalidIdentityPoolConfigurationException" +// Thrown if the identity pool has no role associated for the given auth type +// (auth/unauth) or if the AssumeRole fails. +// +// * ErrCodeInternalErrorException "InternalErrorException" +// Thrown when the service encounters an error during processing the request. +// +// * ErrCodeExternalServiceException "ExternalServiceException" +// An exception thrown when a dependent service such as Facebook or Twitter +// is not responding +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cognito-identity-2014-06-30/GetCredentialsForIdentity +func (c *CognitoIdentity) GetCredentialsForIdentity(input *GetCredentialsForIdentityInput) (*GetCredentialsForIdentityOutput, error) { + req, out := c.GetCredentialsForIdentityRequest(input) + return out, req.Send() +} + +// GetCredentialsForIdentityWithContext is the same as GetCredentialsForIdentity with the addition of +// the ability to pass a context and additional request options. +// +// See GetCredentialsForIdentity 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 *CognitoIdentity) GetCredentialsForIdentityWithContext(ctx aws.Context, input *GetCredentialsForIdentityInput, opts ...request.Option) (*GetCredentialsForIdentityOutput, error) { + req, out := c.GetCredentialsForIdentityRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opGetId = "GetId" + +// GetIdRequest generates a "aws/request.Request" representing the +// client's request for the GetId operation. The "output" return +// value can be used to capture response data after the request's "Send" method +// is called. +// +// See GetId for usage and error information. +// +// Creating a request object using this method should be used when you want to inject +// custom logic into the request's lifecycle using a custom handler, or if you want to +// access properties on the request object before or after sending the request. If +// you just want the service response, call the GetId method directly +// instead. +// +// Note: You must call the "Send" method on the returned request object in order +// to execute the request. +// +// // Example sending a request using the GetIdRequest method. +// req, resp := client.GetIdRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cognito-identity-2014-06-30/GetId +func (c *CognitoIdentity) GetIdRequest(input *GetIdInput) (req *request.Request, output *GetIdOutput) { + op := &request.Operation{ + Name: opGetId, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &GetIdInput{} + } + + output = &GetIdOutput{} + req = c.newRequest(op, input, output) + return +} + +// GetId API operation for Amazon Cognito Identity. +// +// Generates (or retrieves) a Cognito ID. Supplying multiple logins will create +// an implicit linked account. +// +// This is a public API. You do not need any credentials to call this API. +// +// 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 Cognito Identity's +// API operation GetId for usage and error information. +// +// Returned Error Codes: +// * ErrCodeInvalidParameterException "InvalidParameterException" +// Thrown for missing or bad input parameter(s). +// +// * ErrCodeResourceNotFoundException "ResourceNotFoundException" +// Thrown when the requested resource (for example, a dataset or record) does +// not exist. +// +// * ErrCodeNotAuthorizedException "NotAuthorizedException" +// Thrown when a user is not authorized to access the requested resource. +// +// * ErrCodeResourceConflictException "ResourceConflictException" +// Thrown when a user tries to use a login which is already linked to another +// account. +// +// * ErrCodeTooManyRequestsException "TooManyRequestsException" +// Thrown when a request is throttled. +// +// * ErrCodeInternalErrorException "InternalErrorException" +// Thrown when the service encounters an error during processing the request. +// +// * ErrCodeLimitExceededException "LimitExceededException" +// Thrown when the total number of user pools has exceeded a preset limit. +// +// * ErrCodeExternalServiceException "ExternalServiceException" +// An exception thrown when a dependent service such as Facebook or Twitter +// is not responding +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cognito-identity-2014-06-30/GetId +func (c *CognitoIdentity) GetId(input *GetIdInput) (*GetIdOutput, error) { + req, out := c.GetIdRequest(input) + return out, req.Send() +} + +// GetIdWithContext is the same as GetId with the addition of +// the ability to pass a context and additional request options. +// +// See GetId 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 *CognitoIdentity) GetIdWithContext(ctx aws.Context, input *GetIdInput, opts ...request.Option) (*GetIdOutput, error) { + req, out := c.GetIdRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opGetIdentityPoolRoles = "GetIdentityPoolRoles" + +// GetIdentityPoolRolesRequest generates a "aws/request.Request" representing the +// client's request for the GetIdentityPoolRoles operation. The "output" return +// value can be used to capture response data after the request's "Send" method +// is called. +// +// See GetIdentityPoolRoles for usage and error information. +// +// Creating a request object using this method should be used when you want to inject +// custom logic into the request's lifecycle using a custom handler, or if you want to +// access properties on the request object before or after sending the request. If +// you just want the service response, call the GetIdentityPoolRoles method directly +// instead. +// +// Note: You must call the "Send" method on the returned request object in order +// to execute the request. +// +// // Example sending a request using the GetIdentityPoolRolesRequest method. +// req, resp := client.GetIdentityPoolRolesRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cognito-identity-2014-06-30/GetIdentityPoolRoles +func (c *CognitoIdentity) GetIdentityPoolRolesRequest(input *GetIdentityPoolRolesInput) (req *request.Request, output *GetIdentityPoolRolesOutput) { + op := &request.Operation{ + Name: opGetIdentityPoolRoles, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &GetIdentityPoolRolesInput{} + } + + output = &GetIdentityPoolRolesOutput{} + req = c.newRequest(op, input, output) + return +} + +// GetIdentityPoolRoles API operation for Amazon Cognito Identity. +// +// Gets the roles for an identity pool. +// +// You must use AWS Developer credentials to call this API. +// +// 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 Cognito Identity's +// API operation GetIdentityPoolRoles for usage and error information. +// +// Returned Error Codes: +// * ErrCodeInvalidParameterException "InvalidParameterException" +// Thrown for missing or bad input parameter(s). +// +// * ErrCodeResourceNotFoundException "ResourceNotFoundException" +// Thrown when the requested resource (for example, a dataset or record) does +// not exist. +// +// * ErrCodeNotAuthorizedException "NotAuthorizedException" +// Thrown when a user is not authorized to access the requested resource. +// +// * ErrCodeResourceConflictException "ResourceConflictException" +// Thrown when a user tries to use a login which is already linked to another +// account. +// +// * ErrCodeTooManyRequestsException "TooManyRequestsException" +// Thrown when a request is throttled. +// +// * ErrCodeInternalErrorException "InternalErrorException" +// Thrown when the service encounters an error during processing the request. +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cognito-identity-2014-06-30/GetIdentityPoolRoles +func (c *CognitoIdentity) GetIdentityPoolRoles(input *GetIdentityPoolRolesInput) (*GetIdentityPoolRolesOutput, error) { + req, out := c.GetIdentityPoolRolesRequest(input) + return out, req.Send() +} + +// GetIdentityPoolRolesWithContext is the same as GetIdentityPoolRoles with the addition of +// the ability to pass a context and additional request options. +// +// See GetIdentityPoolRoles 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 *CognitoIdentity) GetIdentityPoolRolesWithContext(ctx aws.Context, input *GetIdentityPoolRolesInput, opts ...request.Option) (*GetIdentityPoolRolesOutput, error) { + req, out := c.GetIdentityPoolRolesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opGetOpenIdToken = "GetOpenIdToken" + +// GetOpenIdTokenRequest generates a "aws/request.Request" representing the +// client's request for the GetOpenIdToken operation. The "output" return +// value can be used to capture response data after the request's "Send" method +// is called. +// +// See GetOpenIdToken for usage and error information. +// +// Creating a request object using this method should be used when you want to inject +// custom logic into the request's lifecycle using a custom handler, or if you want to +// access properties on the request object before or after sending the request. If +// you just want the service response, call the GetOpenIdToken method directly +// instead. +// +// Note: You must call the "Send" method on the returned request object in order +// to execute the request. +// +// // Example sending a request using the GetOpenIdTokenRequest method. +// req, resp := client.GetOpenIdTokenRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cognito-identity-2014-06-30/GetOpenIdToken +func (c *CognitoIdentity) GetOpenIdTokenRequest(input *GetOpenIdTokenInput) (req *request.Request, output *GetOpenIdTokenOutput) { + op := &request.Operation{ + Name: opGetOpenIdToken, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &GetOpenIdTokenInput{} + } + + output = &GetOpenIdTokenOutput{} + req = c.newRequest(op, input, output) + return +} + +// GetOpenIdToken API operation for Amazon Cognito Identity. +// +// Gets an OpenID token, using a known Cognito ID. This known Cognito ID is +// returned by GetId. You can optionally add additional logins for the identity. +// Supplying multiple logins creates an implicit link. +// +// The OpenId token is valid for 15 minutes. +// +// This is a public API. You do not need any credentials to call this API. +// +// 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 Cognito Identity's +// API operation GetOpenIdToken for usage and error information. +// +// Returned Error Codes: +// * ErrCodeInvalidParameterException "InvalidParameterException" +// Thrown for missing or bad input parameter(s). +// +// * ErrCodeResourceNotFoundException "ResourceNotFoundException" +// Thrown when the requested resource (for example, a dataset or record) does +// not exist. +// +// * ErrCodeNotAuthorizedException "NotAuthorizedException" +// Thrown when a user is not authorized to access the requested resource. +// +// * ErrCodeResourceConflictException "ResourceConflictException" +// Thrown when a user tries to use a login which is already linked to another +// account. +// +// * ErrCodeTooManyRequestsException "TooManyRequestsException" +// Thrown when a request is throttled. +// +// * ErrCodeInternalErrorException "InternalErrorException" +// Thrown when the service encounters an error during processing the request. +// +// * ErrCodeExternalServiceException "ExternalServiceException" +// An exception thrown when a dependent service such as Facebook or Twitter +// is not responding +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cognito-identity-2014-06-30/GetOpenIdToken +func (c *CognitoIdentity) GetOpenIdToken(input *GetOpenIdTokenInput) (*GetOpenIdTokenOutput, error) { + req, out := c.GetOpenIdTokenRequest(input) + return out, req.Send() +} + +// GetOpenIdTokenWithContext is the same as GetOpenIdToken with the addition of +// the ability to pass a context and additional request options. +// +// See GetOpenIdToken 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 *CognitoIdentity) GetOpenIdTokenWithContext(ctx aws.Context, input *GetOpenIdTokenInput, opts ...request.Option) (*GetOpenIdTokenOutput, error) { + req, out := c.GetOpenIdTokenRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opGetOpenIdTokenForDeveloperIdentity = "GetOpenIdTokenForDeveloperIdentity" + +// GetOpenIdTokenForDeveloperIdentityRequest generates a "aws/request.Request" representing the +// client's request for the GetOpenIdTokenForDeveloperIdentity operation. The "output" return +// value can be used to capture response data after the request's "Send" method +// is called. +// +// See GetOpenIdTokenForDeveloperIdentity for usage and error information. +// +// Creating a request object using this method should be used when you want to inject +// custom logic into the request's lifecycle using a custom handler, or if you want to +// access properties on the request object before or after sending the request. If +// you just want the service response, call the GetOpenIdTokenForDeveloperIdentity method directly +// instead. +// +// Note: You must call the "Send" method on the returned request object in order +// to execute the request. +// +// // Example sending a request using the GetOpenIdTokenForDeveloperIdentityRequest method. +// req, resp := client.GetOpenIdTokenForDeveloperIdentityRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cognito-identity-2014-06-30/GetOpenIdTokenForDeveloperIdentity +func (c *CognitoIdentity) GetOpenIdTokenForDeveloperIdentityRequest(input *GetOpenIdTokenForDeveloperIdentityInput) (req *request.Request, output *GetOpenIdTokenForDeveloperIdentityOutput) { + op := &request.Operation{ + Name: opGetOpenIdTokenForDeveloperIdentity, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &GetOpenIdTokenForDeveloperIdentityInput{} + } + + output = &GetOpenIdTokenForDeveloperIdentityOutput{} + req = c.newRequest(op, input, output) + return +} + +// GetOpenIdTokenForDeveloperIdentity API operation for Amazon Cognito Identity. +// +// Registers (or retrieves) a Cognito IdentityId and an OpenID Connect token +// for a user authenticated by your backend authentication process. Supplying +// multiple logins will create an implicit linked account. You can only specify +// one developer provider as part of the Logins map, which is linked to the +// identity pool. The developer provider is the "domain" by which Cognito will +// refer to your users. +// +// You can use GetOpenIdTokenForDeveloperIdentity to create a new identity and +// to link new logins (that is, user credentials issued by a public provider +// or developer provider) to an existing identity. When you want to create a +// new identity, the IdentityId should be null. When you want to associate a +// new login with an existing authenticated/unauthenticated identity, you can +// do so by providing the existing IdentityId. This API will create the identity +// in the specified IdentityPoolId. +// +// You must use AWS Developer credentials to call this API. +// +// 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 Cognito Identity's +// API operation GetOpenIdTokenForDeveloperIdentity for usage and error information. +// +// Returned Error Codes: +// * ErrCodeInvalidParameterException "InvalidParameterException" +// Thrown for missing or bad input parameter(s). +// +// * ErrCodeResourceNotFoundException "ResourceNotFoundException" +// Thrown when the requested resource (for example, a dataset or record) does +// not exist. +// +// * ErrCodeNotAuthorizedException "NotAuthorizedException" +// Thrown when a user is not authorized to access the requested resource. +// +// * ErrCodeResourceConflictException "ResourceConflictException" +// Thrown when a user tries to use a login which is already linked to another +// account. +// +// * ErrCodeTooManyRequestsException "TooManyRequestsException" +// Thrown when a request is throttled. +// +// * ErrCodeInternalErrorException "InternalErrorException" +// Thrown when the service encounters an error during processing the request. +// +// * ErrCodeDeveloperUserAlreadyRegisteredException "DeveloperUserAlreadyRegisteredException" +// The provided developer user identifier is already registered with Cognito +// under a different identity ID. +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cognito-identity-2014-06-30/GetOpenIdTokenForDeveloperIdentity +func (c *CognitoIdentity) GetOpenIdTokenForDeveloperIdentity(input *GetOpenIdTokenForDeveloperIdentityInput) (*GetOpenIdTokenForDeveloperIdentityOutput, error) { + req, out := c.GetOpenIdTokenForDeveloperIdentityRequest(input) + return out, req.Send() +} + +// GetOpenIdTokenForDeveloperIdentityWithContext is the same as GetOpenIdTokenForDeveloperIdentity with the addition of +// the ability to pass a context and additional request options. +// +// See GetOpenIdTokenForDeveloperIdentity 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 *CognitoIdentity) GetOpenIdTokenForDeveloperIdentityWithContext(ctx aws.Context, input *GetOpenIdTokenForDeveloperIdentityInput, opts ...request.Option) (*GetOpenIdTokenForDeveloperIdentityOutput, error) { + req, out := c.GetOpenIdTokenForDeveloperIdentityRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opListIdentities = "ListIdentities" + +// ListIdentitiesRequest generates a "aws/request.Request" representing the +// client's request for the ListIdentities operation. The "output" return +// value can be used to capture response data after the request's "Send" method +// is called. +// +// See ListIdentities for usage and error information. +// +// Creating a request object using this method should be used when you want to inject +// custom logic into the request's lifecycle using a custom handler, or if you want to +// access properties on the request object before or after sending the request. If +// you just want the service response, call the ListIdentities method directly +// instead. +// +// Note: You must call the "Send" method on the returned request object in order +// to execute the request. +// +// // Example sending a request using the ListIdentitiesRequest method. +// req, resp := client.ListIdentitiesRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cognito-identity-2014-06-30/ListIdentities +func (c *CognitoIdentity) ListIdentitiesRequest(input *ListIdentitiesInput) (req *request.Request, output *ListIdentitiesOutput) { + op := &request.Operation{ + Name: opListIdentities, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &ListIdentitiesInput{} + } + + output = &ListIdentitiesOutput{} + req = c.newRequest(op, input, output) + return +} + +// ListIdentities API operation for Amazon Cognito Identity. +// +// Lists the identities in a pool. +// +// You must use AWS Developer credentials to call this API. +// +// 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 Cognito Identity's +// API operation ListIdentities for usage and error information. +// +// Returned Error Codes: +// * ErrCodeInvalidParameterException "InvalidParameterException" +// Thrown for missing or bad input parameter(s). +// +// * ErrCodeResourceNotFoundException "ResourceNotFoundException" +// Thrown when the requested resource (for example, a dataset or record) does +// not exist. +// +// * ErrCodeNotAuthorizedException "NotAuthorizedException" +// Thrown when a user is not authorized to access the requested resource. +// +// * ErrCodeTooManyRequestsException "TooManyRequestsException" +// Thrown when a request is throttled. +// +// * ErrCodeInternalErrorException "InternalErrorException" +// Thrown when the service encounters an error during processing the request. +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cognito-identity-2014-06-30/ListIdentities +func (c *CognitoIdentity) ListIdentities(input *ListIdentitiesInput) (*ListIdentitiesOutput, error) { + req, out := c.ListIdentitiesRequest(input) + return out, req.Send() +} + +// ListIdentitiesWithContext is the same as ListIdentities with the addition of +// the ability to pass a context and additional request options. +// +// See ListIdentities 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 *CognitoIdentity) ListIdentitiesWithContext(ctx aws.Context, input *ListIdentitiesInput, opts ...request.Option) (*ListIdentitiesOutput, error) { + req, out := c.ListIdentitiesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opListIdentityPools = "ListIdentityPools" + +// ListIdentityPoolsRequest generates a "aws/request.Request" representing the +// client's request for the ListIdentityPools operation. The "output" return +// value can be used to capture response data after the request's "Send" method +// is called. +// +// See ListIdentityPools for usage and error information. +// +// Creating a request object using this method should be used when you want to inject +// custom logic into the request's lifecycle using a custom handler, or if you want to +// access properties on the request object before or after sending the request. If +// you just want the service response, call the ListIdentityPools method directly +// instead. +// +// Note: You must call the "Send" method on the returned request object in order +// to execute the request. +// +// // Example sending a request using the ListIdentityPoolsRequest method. +// req, resp := client.ListIdentityPoolsRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cognito-identity-2014-06-30/ListIdentityPools +func (c *CognitoIdentity) ListIdentityPoolsRequest(input *ListIdentityPoolsInput) (req *request.Request, output *ListIdentityPoolsOutput) { + op := &request.Operation{ + Name: opListIdentityPools, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &ListIdentityPoolsInput{} + } + + output = &ListIdentityPoolsOutput{} + req = c.newRequest(op, input, output) + return +} + +// ListIdentityPools API operation for Amazon Cognito Identity. +// +// Lists all of the Cognito identity pools registered for your account. +// +// You must use AWS Developer credentials to call this API. +// +// 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 Cognito Identity's +// API operation ListIdentityPools for usage and error information. +// +// Returned Error Codes: +// * ErrCodeInvalidParameterException "InvalidParameterException" +// Thrown for missing or bad input parameter(s). +// +// * ErrCodeNotAuthorizedException "NotAuthorizedException" +// Thrown when a user is not authorized to access the requested resource. +// +// * ErrCodeTooManyRequestsException "TooManyRequestsException" +// Thrown when a request is throttled. +// +// * ErrCodeInternalErrorException "InternalErrorException" +// Thrown when the service encounters an error during processing the request. +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cognito-identity-2014-06-30/ListIdentityPools +func (c *CognitoIdentity) ListIdentityPools(input *ListIdentityPoolsInput) (*ListIdentityPoolsOutput, error) { + req, out := c.ListIdentityPoolsRequest(input) + return out, req.Send() +} + +// ListIdentityPoolsWithContext is the same as ListIdentityPools with the addition of +// the ability to pass a context and additional request options. +// +// See ListIdentityPools 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 *CognitoIdentity) ListIdentityPoolsWithContext(ctx aws.Context, input *ListIdentityPoolsInput, opts ...request.Option) (*ListIdentityPoolsOutput, error) { + req, out := c.ListIdentityPoolsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opLookupDeveloperIdentity = "LookupDeveloperIdentity" + +// LookupDeveloperIdentityRequest generates a "aws/request.Request" representing the +// client's request for the LookupDeveloperIdentity operation. The "output" return +// value can be used to capture response data after the request's "Send" method +// is called. +// +// See LookupDeveloperIdentity for usage and error information. +// +// Creating a request object using this method should be used when you want to inject +// custom logic into the request's lifecycle using a custom handler, or if you want to +// access properties on the request object before or after sending the request. If +// you just want the service response, call the LookupDeveloperIdentity method directly +// instead. +// +// Note: You must call the "Send" method on the returned request object in order +// to execute the request. +// +// // Example sending a request using the LookupDeveloperIdentityRequest method. +// req, resp := client.LookupDeveloperIdentityRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cognito-identity-2014-06-30/LookupDeveloperIdentity +func (c *CognitoIdentity) LookupDeveloperIdentityRequest(input *LookupDeveloperIdentityInput) (req *request.Request, output *LookupDeveloperIdentityOutput) { + op := &request.Operation{ + Name: opLookupDeveloperIdentity, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &LookupDeveloperIdentityInput{} + } + + output = &LookupDeveloperIdentityOutput{} + req = c.newRequest(op, input, output) + return +} + +// LookupDeveloperIdentity API operation for Amazon Cognito Identity. +// +// Retrieves the IdentityID associated with a DeveloperUserIdentifier or the +// list of DeveloperUserIdentifiers associated with an IdentityId for an existing +// identity. Either IdentityID or DeveloperUserIdentifier must not be null. +// If you supply only one of these values, the other value will be searched +// in the database and returned as a part of the response. If you supply both, +// DeveloperUserIdentifier will be matched against IdentityID. If the values +// are verified against the database, the response returns both values and is +// the same as the request. Otherwise a ResourceConflictException is thrown. +// +// You must use AWS Developer credentials to call this API. +// +// 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 Cognito Identity's +// API operation LookupDeveloperIdentity for usage and error information. +// +// Returned Error Codes: +// * ErrCodeInvalidParameterException "InvalidParameterException" +// Thrown for missing or bad input parameter(s). +// +// * ErrCodeResourceNotFoundException "ResourceNotFoundException" +// Thrown when the requested resource (for example, a dataset or record) does +// not exist. +// +// * ErrCodeNotAuthorizedException "NotAuthorizedException" +// Thrown when a user is not authorized to access the requested resource. +// +// * ErrCodeResourceConflictException "ResourceConflictException" +// Thrown when a user tries to use a login which is already linked to another +// account. +// +// * ErrCodeTooManyRequestsException "TooManyRequestsException" +// Thrown when a request is throttled. +// +// * ErrCodeInternalErrorException "InternalErrorException" +// Thrown when the service encounters an error during processing the request. +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cognito-identity-2014-06-30/LookupDeveloperIdentity +func (c *CognitoIdentity) LookupDeveloperIdentity(input *LookupDeveloperIdentityInput) (*LookupDeveloperIdentityOutput, error) { + req, out := c.LookupDeveloperIdentityRequest(input) + return out, req.Send() +} + +// LookupDeveloperIdentityWithContext is the same as LookupDeveloperIdentity with the addition of +// the ability to pass a context and additional request options. +// +// See LookupDeveloperIdentity 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 *CognitoIdentity) LookupDeveloperIdentityWithContext(ctx aws.Context, input *LookupDeveloperIdentityInput, opts ...request.Option) (*LookupDeveloperIdentityOutput, error) { + req, out := c.LookupDeveloperIdentityRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opMergeDeveloperIdentities = "MergeDeveloperIdentities" + +// MergeDeveloperIdentitiesRequest generates a "aws/request.Request" representing the +// client's request for the MergeDeveloperIdentities operation. The "output" return +// value can be used to capture response data after the request's "Send" method +// is called. +// +// See MergeDeveloperIdentities for usage and error information. +// +// Creating a request object using this method should be used when you want to inject +// custom logic into the request's lifecycle using a custom handler, or if you want to +// access properties on the request object before or after sending the request. If +// you just want the service response, call the MergeDeveloperIdentities method directly +// instead. +// +// Note: You must call the "Send" method on the returned request object in order +// to execute the request. +// +// // Example sending a request using the MergeDeveloperIdentitiesRequest method. +// req, resp := client.MergeDeveloperIdentitiesRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cognito-identity-2014-06-30/MergeDeveloperIdentities +func (c *CognitoIdentity) MergeDeveloperIdentitiesRequest(input *MergeDeveloperIdentitiesInput) (req *request.Request, output *MergeDeveloperIdentitiesOutput) { + op := &request.Operation{ + Name: opMergeDeveloperIdentities, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &MergeDeveloperIdentitiesInput{} + } + + output = &MergeDeveloperIdentitiesOutput{} + req = c.newRequest(op, input, output) + return +} + +// MergeDeveloperIdentities API operation for Amazon Cognito Identity. +// +// Merges two users having different IdentityIds, existing in the same identity +// pool, and identified by the same developer provider. You can use this action +// to request that discrete users be merged and identified as a single user +// in the Cognito environment. Cognito associates the given source user (SourceUserIdentifier) +// with the IdentityId of the DestinationUserIdentifier. Only developer-authenticated +// users can be merged. If the users to be merged are associated with the same +// public provider, but as two different users, an exception will be thrown. +// +// You must use AWS Developer credentials to call this API. +// +// 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 Cognito Identity's +// API operation MergeDeveloperIdentities for usage and error information. +// +// Returned Error Codes: +// * ErrCodeInvalidParameterException "InvalidParameterException" +// Thrown for missing or bad input parameter(s). +// +// * ErrCodeResourceNotFoundException "ResourceNotFoundException" +// Thrown when the requested resource (for example, a dataset or record) does +// not exist. +// +// * ErrCodeNotAuthorizedException "NotAuthorizedException" +// Thrown when a user is not authorized to access the requested resource. +// +// * ErrCodeResourceConflictException "ResourceConflictException" +// Thrown when a user tries to use a login which is already linked to another +// account. +// +// * ErrCodeTooManyRequestsException "TooManyRequestsException" +// Thrown when a request is throttled. +// +// * ErrCodeInternalErrorException "InternalErrorException" +// Thrown when the service encounters an error during processing the request. +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cognito-identity-2014-06-30/MergeDeveloperIdentities +func (c *CognitoIdentity) MergeDeveloperIdentities(input *MergeDeveloperIdentitiesInput) (*MergeDeveloperIdentitiesOutput, error) { + req, out := c.MergeDeveloperIdentitiesRequest(input) + return out, req.Send() +} + +// MergeDeveloperIdentitiesWithContext is the same as MergeDeveloperIdentities with the addition of +// the ability to pass a context and additional request options. +// +// See MergeDeveloperIdentities 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 *CognitoIdentity) MergeDeveloperIdentitiesWithContext(ctx aws.Context, input *MergeDeveloperIdentitiesInput, opts ...request.Option) (*MergeDeveloperIdentitiesOutput, error) { + req, out := c.MergeDeveloperIdentitiesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opSetIdentityPoolRoles = "SetIdentityPoolRoles" + +// SetIdentityPoolRolesRequest generates a "aws/request.Request" representing the +// client's request for the SetIdentityPoolRoles operation. The "output" return +// value can be used to capture response data after the request's "Send" method +// is called. +// +// See SetIdentityPoolRoles for usage and error information. +// +// Creating a request object using this method should be used when you want to inject +// custom logic into the request's lifecycle using a custom handler, or if you want to +// access properties on the request object before or after sending the request. If +// you just want the service response, call the SetIdentityPoolRoles method directly +// instead. +// +// Note: You must call the "Send" method on the returned request object in order +// to execute the request. +// +// // Example sending a request using the SetIdentityPoolRolesRequest method. +// req, resp := client.SetIdentityPoolRolesRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cognito-identity-2014-06-30/SetIdentityPoolRoles +func (c *CognitoIdentity) SetIdentityPoolRolesRequest(input *SetIdentityPoolRolesInput) (req *request.Request, output *SetIdentityPoolRolesOutput) { + op := &request.Operation{ + Name: opSetIdentityPoolRoles, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &SetIdentityPoolRolesInput{} + } + + output = &SetIdentityPoolRolesOutput{} + req = c.newRequest(op, input, output) + req.Handlers.Unmarshal.Remove(jsonrpc.UnmarshalHandler) + req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) + return +} + +// SetIdentityPoolRoles API operation for Amazon Cognito Identity. +// +// Sets the roles for an identity pool. These roles are used when making calls +// to GetCredentialsForIdentity action. +// +// You must use AWS Developer credentials to call this API. +// +// 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 Cognito Identity's +// API operation SetIdentityPoolRoles for usage and error information. +// +// Returned Error Codes: +// * ErrCodeInvalidParameterException "InvalidParameterException" +// Thrown for missing or bad input parameter(s). +// +// * ErrCodeResourceNotFoundException "ResourceNotFoundException" +// Thrown when the requested resource (for example, a dataset or record) does +// not exist. +// +// * ErrCodeNotAuthorizedException "NotAuthorizedException" +// Thrown when a user is not authorized to access the requested resource. +// +// * ErrCodeResourceConflictException "ResourceConflictException" +// Thrown when a user tries to use a login which is already linked to another +// account. +// +// * ErrCodeTooManyRequestsException "TooManyRequestsException" +// Thrown when a request is throttled. +// +// * ErrCodeInternalErrorException "InternalErrorException" +// Thrown when the service encounters an error during processing the request. +// +// * ErrCodeConcurrentModificationException "ConcurrentModificationException" +// Thrown if there are parallel requests to modify a resource. +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cognito-identity-2014-06-30/SetIdentityPoolRoles +func (c *CognitoIdentity) SetIdentityPoolRoles(input *SetIdentityPoolRolesInput) (*SetIdentityPoolRolesOutput, error) { + req, out := c.SetIdentityPoolRolesRequest(input) + return out, req.Send() +} + +// SetIdentityPoolRolesWithContext is the same as SetIdentityPoolRoles with the addition of +// the ability to pass a context and additional request options. +// +// See SetIdentityPoolRoles 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 *CognitoIdentity) SetIdentityPoolRolesWithContext(ctx aws.Context, input *SetIdentityPoolRolesInput, opts ...request.Option) (*SetIdentityPoolRolesOutput, error) { + req, out := c.SetIdentityPoolRolesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opUnlinkDeveloperIdentity = "UnlinkDeveloperIdentity" + +// UnlinkDeveloperIdentityRequest generates a "aws/request.Request" representing the +// client's request for the UnlinkDeveloperIdentity operation. The "output" return +// value can be used to capture response data after the request's "Send" method +// is called. +// +// See UnlinkDeveloperIdentity for usage and error information. +// +// Creating a request object using this method should be used when you want to inject +// custom logic into the request's lifecycle using a custom handler, or if you want to +// access properties on the request object before or after sending the request. If +// you just want the service response, call the UnlinkDeveloperIdentity method directly +// instead. +// +// Note: You must call the "Send" method on the returned request object in order +// to execute the request. +// +// // Example sending a request using the UnlinkDeveloperIdentityRequest method. +// req, resp := client.UnlinkDeveloperIdentityRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cognito-identity-2014-06-30/UnlinkDeveloperIdentity +func (c *CognitoIdentity) UnlinkDeveloperIdentityRequest(input *UnlinkDeveloperIdentityInput) (req *request.Request, output *UnlinkDeveloperIdentityOutput) { + op := &request.Operation{ + Name: opUnlinkDeveloperIdentity, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &UnlinkDeveloperIdentityInput{} + } + + output = &UnlinkDeveloperIdentityOutput{} + req = c.newRequest(op, input, output) + req.Handlers.Unmarshal.Remove(jsonrpc.UnmarshalHandler) + req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) + return +} + +// UnlinkDeveloperIdentity API operation for Amazon Cognito Identity. +// +// Unlinks a DeveloperUserIdentifier from an existing identity. Unlinked developer +// users will be considered new identities next time they are seen. If, for +// a given Cognito identity, you remove all federated identities as well as +// the developer user identifier, the Cognito identity becomes inaccessible. +// +// You must use AWS Developer credentials to call this API. +// +// 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 Cognito Identity's +// API operation UnlinkDeveloperIdentity for usage and error information. +// +// Returned Error Codes: +// * ErrCodeInvalidParameterException "InvalidParameterException" +// Thrown for missing or bad input parameter(s). +// +// * ErrCodeResourceNotFoundException "ResourceNotFoundException" +// Thrown when the requested resource (for example, a dataset or record) does +// not exist. +// +// * ErrCodeNotAuthorizedException "NotAuthorizedException" +// Thrown when a user is not authorized to access the requested resource. +// +// * ErrCodeResourceConflictException "ResourceConflictException" +// Thrown when a user tries to use a login which is already linked to another +// account. +// +// * ErrCodeTooManyRequestsException "TooManyRequestsException" +// Thrown when a request is throttled. +// +// * ErrCodeInternalErrorException "InternalErrorException" +// Thrown when the service encounters an error during processing the request. +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cognito-identity-2014-06-30/UnlinkDeveloperIdentity +func (c *CognitoIdentity) UnlinkDeveloperIdentity(input *UnlinkDeveloperIdentityInput) (*UnlinkDeveloperIdentityOutput, error) { + req, out := c.UnlinkDeveloperIdentityRequest(input) + return out, req.Send() +} + +// UnlinkDeveloperIdentityWithContext is the same as UnlinkDeveloperIdentity with the addition of +// the ability to pass a context and additional request options. +// +// See UnlinkDeveloperIdentity 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 *CognitoIdentity) UnlinkDeveloperIdentityWithContext(ctx aws.Context, input *UnlinkDeveloperIdentityInput, opts ...request.Option) (*UnlinkDeveloperIdentityOutput, error) { + req, out := c.UnlinkDeveloperIdentityRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opUnlinkIdentity = "UnlinkIdentity" + +// UnlinkIdentityRequest generates a "aws/request.Request" representing the +// client's request for the UnlinkIdentity operation. The "output" return +// value can be used to capture response data after the request's "Send" method +// is called. +// +// See UnlinkIdentity for usage and error information. +// +// Creating a request object using this method should be used when you want to inject +// custom logic into the request's lifecycle using a custom handler, or if you want to +// access properties on the request object before or after sending the request. If +// you just want the service response, call the UnlinkIdentity method directly +// instead. +// +// Note: You must call the "Send" method on the returned request object in order +// to execute the request. +// +// // Example sending a request using the UnlinkIdentityRequest method. +// req, resp := client.UnlinkIdentityRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cognito-identity-2014-06-30/UnlinkIdentity +func (c *CognitoIdentity) UnlinkIdentityRequest(input *UnlinkIdentityInput) (req *request.Request, output *UnlinkIdentityOutput) { + op := &request.Operation{ + Name: opUnlinkIdentity, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &UnlinkIdentityInput{} + } + + output = &UnlinkIdentityOutput{} + req = c.newRequest(op, input, output) + req.Handlers.Unmarshal.Remove(jsonrpc.UnmarshalHandler) + req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) + return +} + +// UnlinkIdentity API operation for Amazon Cognito Identity. +// +// Unlinks a federated identity from an existing account. Unlinked logins will +// be considered new identities next time they are seen. Removing the last linked +// login will make this identity inaccessible. +// +// This is a public API. You do not need any credentials to call this API. +// +// 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 Cognito Identity's +// API operation UnlinkIdentity for usage and error information. +// +// Returned Error Codes: +// * ErrCodeInvalidParameterException "InvalidParameterException" +// Thrown for missing or bad input parameter(s). +// +// * ErrCodeResourceNotFoundException "ResourceNotFoundException" +// Thrown when the requested resource (for example, a dataset or record) does +// not exist. +// +// * ErrCodeNotAuthorizedException "NotAuthorizedException" +// Thrown when a user is not authorized to access the requested resource. +// +// * ErrCodeResourceConflictException "ResourceConflictException" +// Thrown when a user tries to use a login which is already linked to another +// account. +// +// * ErrCodeTooManyRequestsException "TooManyRequestsException" +// Thrown when a request is throttled. +// +// * ErrCodeInternalErrorException "InternalErrorException" +// Thrown when the service encounters an error during processing the request. +// +// * ErrCodeExternalServiceException "ExternalServiceException" +// An exception thrown when a dependent service such as Facebook or Twitter +// is not responding +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cognito-identity-2014-06-30/UnlinkIdentity +func (c *CognitoIdentity) UnlinkIdentity(input *UnlinkIdentityInput) (*UnlinkIdentityOutput, error) { + req, out := c.UnlinkIdentityRequest(input) + return out, req.Send() +} + +// UnlinkIdentityWithContext is the same as UnlinkIdentity with the addition of +// the ability to pass a context and additional request options. +// +// See UnlinkIdentity 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 *CognitoIdentity) UnlinkIdentityWithContext(ctx aws.Context, input *UnlinkIdentityInput, opts ...request.Option) (*UnlinkIdentityOutput, error) { + req, out := c.UnlinkIdentityRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opUpdateIdentityPool = "UpdateIdentityPool" + +// UpdateIdentityPoolRequest generates a "aws/request.Request" representing the +// client's request for the UpdateIdentityPool operation. The "output" return +// value can be used to capture response data after the request's "Send" method +// is called. +// +// See UpdateIdentityPool for usage and error information. +// +// Creating a request object using this method should be used when you want to inject +// custom logic into the request's lifecycle using a custom handler, or if you want to +// access properties on the request object before or after sending the request. If +// you just want the service response, call the UpdateIdentityPool method directly +// instead. +// +// Note: You must call the "Send" method on the returned request object in order +// to execute the request. +// +// // Example sending a request using the UpdateIdentityPoolRequest method. +// req, resp := client.UpdateIdentityPoolRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cognito-identity-2014-06-30/UpdateIdentityPool +func (c *CognitoIdentity) UpdateIdentityPoolRequest(input *IdentityPool) (req *request.Request, output *IdentityPool) { + op := &request.Operation{ + Name: opUpdateIdentityPool, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &IdentityPool{} + } + + output = &IdentityPool{} + req = c.newRequest(op, input, output) + return +} + +// UpdateIdentityPool API operation for Amazon Cognito Identity. +// +// Updates a user pool. +// +// You must use AWS Developer credentials to call this API. +// +// 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 Cognito Identity's +// API operation UpdateIdentityPool for usage and error information. +// +// Returned Error Codes: +// * ErrCodeInvalidParameterException "InvalidParameterException" +// Thrown for missing or bad input parameter(s). +// +// * ErrCodeResourceNotFoundException "ResourceNotFoundException" +// Thrown when the requested resource (for example, a dataset or record) does +// not exist. +// +// * ErrCodeNotAuthorizedException "NotAuthorizedException" +// Thrown when a user is not authorized to access the requested resource. +// +// * ErrCodeResourceConflictException "ResourceConflictException" +// Thrown when a user tries to use a login which is already linked to another +// account. +// +// * ErrCodeTooManyRequestsException "TooManyRequestsException" +// Thrown when a request is throttled. +// +// * ErrCodeInternalErrorException "InternalErrorException" +// Thrown when the service encounters an error during processing the request. +// +// * ErrCodeConcurrentModificationException "ConcurrentModificationException" +// Thrown if there are parallel requests to modify a resource. +// +// * ErrCodeLimitExceededException "LimitExceededException" +// Thrown when the total number of user pools has exceeded a preset limit. +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cognito-identity-2014-06-30/UpdateIdentityPool +func (c *CognitoIdentity) UpdateIdentityPool(input *IdentityPool) (*IdentityPool, error) { + req, out := c.UpdateIdentityPoolRequest(input) + return out, req.Send() +} + +// UpdateIdentityPoolWithContext is the same as UpdateIdentityPool with the addition of +// the ability to pass a context and additional request options. +// +// See UpdateIdentityPool 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 *CognitoIdentity) UpdateIdentityPoolWithContext(ctx aws.Context, input *IdentityPool, opts ...request.Option) (*IdentityPool, error) { + req, out := c.UpdateIdentityPoolRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +// Input to the CreateIdentityPool action. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cognito-identity-2014-06-30/CreateIdentityPoolInput +type CreateIdentityPoolInput struct { + _ struct{} `type:"structure"` + + // TRUE if the identity pool supports unauthenticated logins. + // + // AllowUnauthenticatedIdentities is a required field + AllowUnauthenticatedIdentities *bool `type:"boolean" required:"true"` + + // An array of Amazon Cognito Identity user pools and their client IDs. + CognitoIdentityProviders []*Provider `type:"list"` + + // The "domain" by which Cognito will refer to your users. This name acts as + // a placeholder that allows your backend and the Cognito service to communicate + // about the developer provider. For the DeveloperProviderName, you can use + // letters as well as period (.), underscore (_), and dash (-). + // + // Once you have set a developer provider name, you cannot change it. Please + // take care in setting this parameter. + DeveloperProviderName *string `min:"1" type:"string"` + + // A string that you provide. + // + // IdentityPoolName is a required field + IdentityPoolName *string `min:"1" type:"string" required:"true"` + + // A list of OpendID Connect provider ARNs. + OpenIdConnectProviderARNs []*string `type:"list"` + + // An array of Amazon Resource Names (ARNs) of the SAML provider for your identity + // pool. + SamlProviderARNs []*string `type:"list"` + + // Optional key:value pairs mapping provider names to provider app IDs. + SupportedLoginProviders map[string]*string `type:"map"` +} + +// String returns the string representation +func (s CreateIdentityPoolInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s CreateIdentityPoolInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *CreateIdentityPoolInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "CreateIdentityPoolInput"} + if s.AllowUnauthenticatedIdentities == nil { + invalidParams.Add(request.NewErrParamRequired("AllowUnauthenticatedIdentities")) + } + if s.DeveloperProviderName != nil && len(*s.DeveloperProviderName) < 1 { + invalidParams.Add(request.NewErrParamMinLen("DeveloperProviderName", 1)) + } + if s.IdentityPoolName == nil { + invalidParams.Add(request.NewErrParamRequired("IdentityPoolName")) + } + if s.IdentityPoolName != nil && len(*s.IdentityPoolName) < 1 { + invalidParams.Add(request.NewErrParamMinLen("IdentityPoolName", 1)) + } + if s.CognitoIdentityProviders != nil { + for i, v := range s.CognitoIdentityProviders { + if v == nil { + continue + } + if err := v.Validate(); err != nil { + invalidParams.AddNested(fmt.Sprintf("%s[%v]", "CognitoIdentityProviders", i), err.(request.ErrInvalidParams)) + } + } + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetAllowUnauthenticatedIdentities sets the AllowUnauthenticatedIdentities field's value. +func (s *CreateIdentityPoolInput) SetAllowUnauthenticatedIdentities(v bool) *CreateIdentityPoolInput { + s.AllowUnauthenticatedIdentities = &v + return s +} + +// SetCognitoIdentityProviders sets the CognitoIdentityProviders field's value. +func (s *CreateIdentityPoolInput) SetCognitoIdentityProviders(v []*Provider) *CreateIdentityPoolInput { + s.CognitoIdentityProviders = v + return s +} + +// SetDeveloperProviderName sets the DeveloperProviderName field's value. +func (s *CreateIdentityPoolInput) SetDeveloperProviderName(v string) *CreateIdentityPoolInput { + s.DeveloperProviderName = &v + return s +} + +// SetIdentityPoolName sets the IdentityPoolName field's value. +func (s *CreateIdentityPoolInput) SetIdentityPoolName(v string) *CreateIdentityPoolInput { + s.IdentityPoolName = &v + return s +} + +// SetOpenIdConnectProviderARNs sets the OpenIdConnectProviderARNs field's value. +func (s *CreateIdentityPoolInput) SetOpenIdConnectProviderARNs(v []*string) *CreateIdentityPoolInput { + s.OpenIdConnectProviderARNs = v + return s +} + +// SetSamlProviderARNs sets the SamlProviderARNs field's value. +func (s *CreateIdentityPoolInput) SetSamlProviderARNs(v []*string) *CreateIdentityPoolInput { + s.SamlProviderARNs = v + return s +} + +// SetSupportedLoginProviders sets the SupportedLoginProviders field's value. +func (s *CreateIdentityPoolInput) SetSupportedLoginProviders(v map[string]*string) *CreateIdentityPoolInput { + s.SupportedLoginProviders = v + return s +} + +// Credentials for the provided identity ID. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cognito-identity-2014-06-30/Credentials +type Credentials struct { + _ struct{} `type:"structure"` + + // The Access Key portion of the credentials. + AccessKeyId *string `type:"string"` + + // The date at which these credentials will expire. + Expiration *time.Time `type:"timestamp" timestampFormat:"unix"` + + // The Secret Access Key portion of the credentials + SecretKey *string `type:"string"` + + // The Session Token portion of the credentials + SessionToken *string `type:"string"` +} + +// String returns the string representation +func (s Credentials) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s Credentials) GoString() string { + return s.String() +} + +// SetAccessKeyId sets the AccessKeyId field's value. +func (s *Credentials) SetAccessKeyId(v string) *Credentials { + s.AccessKeyId = &v + return s +} + +// SetExpiration sets the Expiration field's value. +func (s *Credentials) SetExpiration(v time.Time) *Credentials { + s.Expiration = &v + return s +} + +// SetSecretKey sets the SecretKey field's value. +func (s *Credentials) SetSecretKey(v string) *Credentials { + s.SecretKey = &v + return s +} + +// SetSessionToken sets the SessionToken field's value. +func (s *Credentials) SetSessionToken(v string) *Credentials { + s.SessionToken = &v + return s +} + +// Input to the DeleteIdentities action. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cognito-identity-2014-06-30/DeleteIdentitiesInput +type DeleteIdentitiesInput struct { + _ struct{} `type:"structure"` + + // A list of 1-60 identities that you want to delete. + // + // IdentityIdsToDelete is a required field + IdentityIdsToDelete []*string `min:"1" type:"list" required:"true"` +} + +// String returns the string representation +func (s DeleteIdentitiesInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DeleteIdentitiesInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *DeleteIdentitiesInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DeleteIdentitiesInput"} + if s.IdentityIdsToDelete == nil { + invalidParams.Add(request.NewErrParamRequired("IdentityIdsToDelete")) + } + if s.IdentityIdsToDelete != nil && len(s.IdentityIdsToDelete) < 1 { + invalidParams.Add(request.NewErrParamMinLen("IdentityIdsToDelete", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetIdentityIdsToDelete sets the IdentityIdsToDelete field's value. +func (s *DeleteIdentitiesInput) SetIdentityIdsToDelete(v []*string) *DeleteIdentitiesInput { + s.IdentityIdsToDelete = v + return s +} + +// Returned in response to a successful DeleteIdentities operation. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cognito-identity-2014-06-30/DeleteIdentitiesResponse +type DeleteIdentitiesOutput struct { + _ struct{} `type:"structure"` + + // An array of UnprocessedIdentityId objects, each of which contains an ErrorCode + // and IdentityId. + UnprocessedIdentityIds []*UnprocessedIdentityId `type:"list"` +} + +// String returns the string representation +func (s DeleteIdentitiesOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DeleteIdentitiesOutput) GoString() string { + return s.String() +} + +// SetUnprocessedIdentityIds sets the UnprocessedIdentityIds field's value. +func (s *DeleteIdentitiesOutput) SetUnprocessedIdentityIds(v []*UnprocessedIdentityId) *DeleteIdentitiesOutput { + s.UnprocessedIdentityIds = v + return s +} + +// Input to the DeleteIdentityPool action. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cognito-identity-2014-06-30/DeleteIdentityPoolInput +type DeleteIdentityPoolInput struct { + _ struct{} `type:"structure"` + + // An identity pool ID in the format REGION:GUID. + // + // IdentityPoolId is a required field + IdentityPoolId *string `min:"1" type:"string" required:"true"` +} + +// String returns the string representation +func (s DeleteIdentityPoolInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DeleteIdentityPoolInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *DeleteIdentityPoolInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DeleteIdentityPoolInput"} + if s.IdentityPoolId == nil { + invalidParams.Add(request.NewErrParamRequired("IdentityPoolId")) + } + if s.IdentityPoolId != nil && len(*s.IdentityPoolId) < 1 { + invalidParams.Add(request.NewErrParamMinLen("IdentityPoolId", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetIdentityPoolId sets the IdentityPoolId field's value. +func (s *DeleteIdentityPoolInput) SetIdentityPoolId(v string) *DeleteIdentityPoolInput { + s.IdentityPoolId = &v + return s +} + +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cognito-identity-2014-06-30/DeleteIdentityPoolOutput +type DeleteIdentityPoolOutput struct { + _ struct{} `type:"structure"` +} + +// String returns the string representation +func (s DeleteIdentityPoolOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DeleteIdentityPoolOutput) GoString() string { + return s.String() +} + +// Input to the DescribeIdentity action. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cognito-identity-2014-06-30/DescribeIdentityInput +type DescribeIdentityInput struct { + _ struct{} `type:"structure"` + + // A unique identifier in the format REGION:GUID. + // + // IdentityId is a required field + IdentityId *string `min:"1" type:"string" required:"true"` +} + +// String returns the string representation +func (s DescribeIdentityInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DescribeIdentityInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *DescribeIdentityInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DescribeIdentityInput"} + if s.IdentityId == nil { + invalidParams.Add(request.NewErrParamRequired("IdentityId")) + } + if s.IdentityId != nil && len(*s.IdentityId) < 1 { + invalidParams.Add(request.NewErrParamMinLen("IdentityId", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetIdentityId sets the IdentityId field's value. +func (s *DescribeIdentityInput) SetIdentityId(v string) *DescribeIdentityInput { + s.IdentityId = &v + return s +} + +// Input to the DescribeIdentityPool action. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cognito-identity-2014-06-30/DescribeIdentityPoolInput +type DescribeIdentityPoolInput struct { + _ struct{} `type:"structure"` + + // An identity pool ID in the format REGION:GUID. + // + // IdentityPoolId is a required field + IdentityPoolId *string `min:"1" type:"string" required:"true"` +} + +// String returns the string representation +func (s DescribeIdentityPoolInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DescribeIdentityPoolInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *DescribeIdentityPoolInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DescribeIdentityPoolInput"} + if s.IdentityPoolId == nil { + invalidParams.Add(request.NewErrParamRequired("IdentityPoolId")) + } + if s.IdentityPoolId != nil && len(*s.IdentityPoolId) < 1 { + invalidParams.Add(request.NewErrParamMinLen("IdentityPoolId", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetIdentityPoolId sets the IdentityPoolId field's value. +func (s *DescribeIdentityPoolInput) SetIdentityPoolId(v string) *DescribeIdentityPoolInput { + s.IdentityPoolId = &v + return s +} + +// Input to the GetCredentialsForIdentity action. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cognito-identity-2014-06-30/GetCredentialsForIdentityInput +type GetCredentialsForIdentityInput struct { + _ struct{} `type:"structure"` + + // The Amazon Resource Name (ARN) of the role to be assumed when multiple roles + // were received in the token from the identity provider. For example, a SAML-based + // identity provider. This parameter is optional for identity providers that + // do not support role customization. + CustomRoleArn *string `min:"20" type:"string"` + + // A unique identifier in the format REGION:GUID. + // + // IdentityId is a required field + IdentityId *string `min:"1" type:"string" required:"true"` + + // A set of optional name-value pairs that map provider names to provider tokens. + Logins map[string]*string `type:"map"` +} + +// String returns the string representation +func (s GetCredentialsForIdentityInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s GetCredentialsForIdentityInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *GetCredentialsForIdentityInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "GetCredentialsForIdentityInput"} + if s.CustomRoleArn != nil && len(*s.CustomRoleArn) < 20 { + invalidParams.Add(request.NewErrParamMinLen("CustomRoleArn", 20)) + } + if s.IdentityId == nil { + invalidParams.Add(request.NewErrParamRequired("IdentityId")) + } + if s.IdentityId != nil && len(*s.IdentityId) < 1 { + invalidParams.Add(request.NewErrParamMinLen("IdentityId", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetCustomRoleArn sets the CustomRoleArn field's value. +func (s *GetCredentialsForIdentityInput) SetCustomRoleArn(v string) *GetCredentialsForIdentityInput { + s.CustomRoleArn = &v + return s +} + +// SetIdentityId sets the IdentityId field's value. +func (s *GetCredentialsForIdentityInput) SetIdentityId(v string) *GetCredentialsForIdentityInput { + s.IdentityId = &v + return s +} + +// SetLogins sets the Logins field's value. +func (s *GetCredentialsForIdentityInput) SetLogins(v map[string]*string) *GetCredentialsForIdentityInput { + s.Logins = v + return s +} + +// Returned in response to a successful GetCredentialsForIdentity operation. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cognito-identity-2014-06-30/GetCredentialsForIdentityResponse +type GetCredentialsForIdentityOutput struct { + _ struct{} `type:"structure"` + + // Credentials for the provided identity ID. + Credentials *Credentials `type:"structure"` + + // A unique identifier in the format REGION:GUID. + IdentityId *string `min:"1" type:"string"` +} + +// String returns the string representation +func (s GetCredentialsForIdentityOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s GetCredentialsForIdentityOutput) GoString() string { + return s.String() +} + +// SetCredentials sets the Credentials field's value. +func (s *GetCredentialsForIdentityOutput) SetCredentials(v *Credentials) *GetCredentialsForIdentityOutput { + s.Credentials = v + return s +} + +// SetIdentityId sets the IdentityId field's value. +func (s *GetCredentialsForIdentityOutput) SetIdentityId(v string) *GetCredentialsForIdentityOutput { + s.IdentityId = &v + return s +} + +// Input to the GetId action. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cognito-identity-2014-06-30/GetIdInput +type GetIdInput struct { + _ struct{} `type:"structure"` + + // A standard AWS account ID (9+ digits). + AccountId *string `min:"1" type:"string"` + + // An identity pool ID in the format REGION:GUID. + // + // IdentityPoolId is a required field + IdentityPoolId *string `min:"1" type:"string" required:"true"` + + // A set of optional name-value pairs that map provider names to provider tokens. + // The available provider names for Logins are as follows: + // + // * Facebook: graph.facebook.com + // + // * Amazon Cognito Identity Provider: cognito-idp.us-east-1.amazonaws.com/us-east-1_123456789 + // + // * Google: accounts.google.com + // + // * Amazon: www.amazon.com + // + // * Twitter: api.twitter.com + // + // * Digits: www.digits.com + Logins map[string]*string `type:"map"` +} + +// String returns the string representation +func (s GetIdInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s GetIdInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *GetIdInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "GetIdInput"} + if s.AccountId != nil && len(*s.AccountId) < 1 { + invalidParams.Add(request.NewErrParamMinLen("AccountId", 1)) + } + if s.IdentityPoolId == nil { + invalidParams.Add(request.NewErrParamRequired("IdentityPoolId")) + } + if s.IdentityPoolId != nil && len(*s.IdentityPoolId) < 1 { + invalidParams.Add(request.NewErrParamMinLen("IdentityPoolId", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetAccountId sets the AccountId field's value. +func (s *GetIdInput) SetAccountId(v string) *GetIdInput { + s.AccountId = &v + return s +} + +// SetIdentityPoolId sets the IdentityPoolId field's value. +func (s *GetIdInput) SetIdentityPoolId(v string) *GetIdInput { + s.IdentityPoolId = &v + return s +} + +// SetLogins sets the Logins field's value. +func (s *GetIdInput) SetLogins(v map[string]*string) *GetIdInput { + s.Logins = v + return s +} + +// Returned in response to a GetId request. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cognito-identity-2014-06-30/GetIdResponse +type GetIdOutput struct { + _ struct{} `type:"structure"` + + // A unique identifier in the format REGION:GUID. + IdentityId *string `min:"1" type:"string"` +} + +// String returns the string representation +func (s GetIdOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s GetIdOutput) GoString() string { + return s.String() +} + +// SetIdentityId sets the IdentityId field's value. +func (s *GetIdOutput) SetIdentityId(v string) *GetIdOutput { + s.IdentityId = &v + return s +} + +// Input to the GetIdentityPoolRoles action. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cognito-identity-2014-06-30/GetIdentityPoolRolesInput +type GetIdentityPoolRolesInput struct { + _ struct{} `type:"structure"` + + // An identity pool ID in the format REGION:GUID. + // + // IdentityPoolId is a required field + IdentityPoolId *string `min:"1" type:"string" required:"true"` +} + +// String returns the string representation +func (s GetIdentityPoolRolesInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s GetIdentityPoolRolesInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *GetIdentityPoolRolesInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "GetIdentityPoolRolesInput"} + if s.IdentityPoolId == nil { + invalidParams.Add(request.NewErrParamRequired("IdentityPoolId")) + } + if s.IdentityPoolId != nil && len(*s.IdentityPoolId) < 1 { + invalidParams.Add(request.NewErrParamMinLen("IdentityPoolId", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetIdentityPoolId sets the IdentityPoolId field's value. +func (s *GetIdentityPoolRolesInput) SetIdentityPoolId(v string) *GetIdentityPoolRolesInput { + s.IdentityPoolId = &v + return s +} + +// Returned in response to a successful GetIdentityPoolRoles operation. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cognito-identity-2014-06-30/GetIdentityPoolRolesResponse +type GetIdentityPoolRolesOutput struct { + _ struct{} `type:"structure"` + + // An identity pool ID in the format REGION:GUID. + IdentityPoolId *string `min:"1" type:"string"` + + // How users for a specific identity provider are to mapped to roles. This is + // a String-to-RoleMapping object map. The string identifies the identity provider, + // for example, "graph.facebook.com" or "cognito-idp-east-1.amazonaws.com/us-east-1_abcdefghi:app_client_id". + RoleMappings map[string]*RoleMapping `type:"map"` + + // The map of roles associated with this pool. Currently only authenticated + // and unauthenticated roles are supported. + Roles map[string]*string `type:"map"` +} + +// String returns the string representation +func (s GetIdentityPoolRolesOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s GetIdentityPoolRolesOutput) GoString() string { + return s.String() +} + +// SetIdentityPoolId sets the IdentityPoolId field's value. +func (s *GetIdentityPoolRolesOutput) SetIdentityPoolId(v string) *GetIdentityPoolRolesOutput { + s.IdentityPoolId = &v + return s +} + +// SetRoleMappings sets the RoleMappings field's value. +func (s *GetIdentityPoolRolesOutput) SetRoleMappings(v map[string]*RoleMapping) *GetIdentityPoolRolesOutput { + s.RoleMappings = v + return s +} + +// SetRoles sets the Roles field's value. +func (s *GetIdentityPoolRolesOutput) SetRoles(v map[string]*string) *GetIdentityPoolRolesOutput { + s.Roles = v + return s +} + +// Input to the GetOpenIdTokenForDeveloperIdentity action. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cognito-identity-2014-06-30/GetOpenIdTokenForDeveloperIdentityInput +type GetOpenIdTokenForDeveloperIdentityInput struct { + _ struct{} `type:"structure"` + + // A unique identifier in the format REGION:GUID. + IdentityId *string `min:"1" type:"string"` + + // An identity pool ID in the format REGION:GUID. + // + // IdentityPoolId is a required field + IdentityPoolId *string `min:"1" type:"string" required:"true"` + + // A set of optional name-value pairs that map provider names to provider tokens. + // Each name-value pair represents a user from a public provider or developer + // provider. If the user is from a developer provider, the name-value pair will + // follow the syntax "developer_provider_name": "developer_user_identifier". + // The developer provider is the "domain" by which Cognito will refer to your + // users; you provided this domain while creating/updating the identity pool. + // The developer user identifier is an identifier from your backend that uniquely + // identifies a user. When you create an identity pool, you can specify the + // supported logins. + // + // Logins is a required field + Logins map[string]*string `type:"map" required:"true"` + + // The expiration time of the token, in seconds. You can specify a custom expiration + // time for the token so that you can cache it. If you don't provide an expiration + // time, the token is valid for 15 minutes. You can exchange the token with + // Amazon STS for temporary AWS credentials, which are valid for a maximum of + // one hour. The maximum token duration you can set is 24 hours. You should + // take care in setting the expiration time for a token, as there are significant + // security implications: an attacker could use a leaked token to access your + // AWS resources for the token's duration. + TokenDuration *int64 `min:"1" type:"long"` +} + +// String returns the string representation +func (s GetOpenIdTokenForDeveloperIdentityInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s GetOpenIdTokenForDeveloperIdentityInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *GetOpenIdTokenForDeveloperIdentityInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "GetOpenIdTokenForDeveloperIdentityInput"} + if s.IdentityId != nil && len(*s.IdentityId) < 1 { + invalidParams.Add(request.NewErrParamMinLen("IdentityId", 1)) + } + if s.IdentityPoolId == nil { + invalidParams.Add(request.NewErrParamRequired("IdentityPoolId")) + } + if s.IdentityPoolId != nil && len(*s.IdentityPoolId) < 1 { + invalidParams.Add(request.NewErrParamMinLen("IdentityPoolId", 1)) + } + if s.Logins == nil { + invalidParams.Add(request.NewErrParamRequired("Logins")) + } + if s.TokenDuration != nil && *s.TokenDuration < 1 { + invalidParams.Add(request.NewErrParamMinValue("TokenDuration", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetIdentityId sets the IdentityId field's value. +func (s *GetOpenIdTokenForDeveloperIdentityInput) SetIdentityId(v string) *GetOpenIdTokenForDeveloperIdentityInput { + s.IdentityId = &v + return s +} + +// SetIdentityPoolId sets the IdentityPoolId field's value. +func (s *GetOpenIdTokenForDeveloperIdentityInput) SetIdentityPoolId(v string) *GetOpenIdTokenForDeveloperIdentityInput { + s.IdentityPoolId = &v + return s +} + +// SetLogins sets the Logins field's value. +func (s *GetOpenIdTokenForDeveloperIdentityInput) SetLogins(v map[string]*string) *GetOpenIdTokenForDeveloperIdentityInput { + s.Logins = v + return s +} + +// SetTokenDuration sets the TokenDuration field's value. +func (s *GetOpenIdTokenForDeveloperIdentityInput) SetTokenDuration(v int64) *GetOpenIdTokenForDeveloperIdentityInput { + s.TokenDuration = &v + return s +} + +// Returned in response to a successful GetOpenIdTokenForDeveloperIdentity request. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cognito-identity-2014-06-30/GetOpenIdTokenForDeveloperIdentityResponse +type GetOpenIdTokenForDeveloperIdentityOutput struct { + _ struct{} `type:"structure"` + + // A unique identifier in the format REGION:GUID. + IdentityId *string `min:"1" type:"string"` + + // An OpenID token. + Token *string `type:"string"` +} + +// String returns the string representation +func (s GetOpenIdTokenForDeveloperIdentityOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s GetOpenIdTokenForDeveloperIdentityOutput) GoString() string { + return s.String() +} + +// SetIdentityId sets the IdentityId field's value. +func (s *GetOpenIdTokenForDeveloperIdentityOutput) SetIdentityId(v string) *GetOpenIdTokenForDeveloperIdentityOutput { + s.IdentityId = &v + return s +} + +// SetToken sets the Token field's value. +func (s *GetOpenIdTokenForDeveloperIdentityOutput) SetToken(v string) *GetOpenIdTokenForDeveloperIdentityOutput { + s.Token = &v + return s +} + +// Input to the GetOpenIdToken action. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cognito-identity-2014-06-30/GetOpenIdTokenInput +type GetOpenIdTokenInput struct { + _ struct{} `type:"structure"` + + // A unique identifier in the format REGION:GUID. + // + // IdentityId is a required field + IdentityId *string `min:"1" type:"string" required:"true"` + + // A set of optional name-value pairs that map provider names to provider tokens. + // When using graph.facebook.com and www.amazon.com, supply the access_token + // returned from the provider's authflow. For accounts.google.com, an Amazon + // Cognito Identity Provider, or any other OpenId Connect provider, always include + // the id_token. + Logins map[string]*string `type:"map"` +} + +// String returns the string representation +func (s GetOpenIdTokenInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s GetOpenIdTokenInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *GetOpenIdTokenInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "GetOpenIdTokenInput"} + if s.IdentityId == nil { + invalidParams.Add(request.NewErrParamRequired("IdentityId")) + } + if s.IdentityId != nil && len(*s.IdentityId) < 1 { + invalidParams.Add(request.NewErrParamMinLen("IdentityId", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetIdentityId sets the IdentityId field's value. +func (s *GetOpenIdTokenInput) SetIdentityId(v string) *GetOpenIdTokenInput { + s.IdentityId = &v + return s +} + +// SetLogins sets the Logins field's value. +func (s *GetOpenIdTokenInput) SetLogins(v map[string]*string) *GetOpenIdTokenInput { + s.Logins = v + return s +} + +// Returned in response to a successful GetOpenIdToken request. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cognito-identity-2014-06-30/GetOpenIdTokenResponse +type GetOpenIdTokenOutput struct { + _ struct{} `type:"structure"` + + // A unique identifier in the format REGION:GUID. Note that the IdentityId returned + // may not match the one passed on input. + IdentityId *string `min:"1" type:"string"` + + // An OpenID token, valid for 15 minutes. + Token *string `type:"string"` +} + +// String returns the string representation +func (s GetOpenIdTokenOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s GetOpenIdTokenOutput) GoString() string { + return s.String() +} + +// SetIdentityId sets the IdentityId field's value. +func (s *GetOpenIdTokenOutput) SetIdentityId(v string) *GetOpenIdTokenOutput { + s.IdentityId = &v + return s +} + +// SetToken sets the Token field's value. +func (s *GetOpenIdTokenOutput) SetToken(v string) *GetOpenIdTokenOutput { + s.Token = &v + return s +} + +// A description of the identity. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cognito-identity-2014-06-30/IdentityDescription +type IdentityDescription struct { + _ struct{} `type:"structure"` + + // Date on which the identity was created. + CreationDate *time.Time `type:"timestamp" timestampFormat:"unix"` + + // A unique identifier in the format REGION:GUID. + IdentityId *string `min:"1" type:"string"` + + // Date on which the identity was last modified. + LastModifiedDate *time.Time `type:"timestamp" timestampFormat:"unix"` + + // A set of optional name-value pairs that map provider names to provider tokens. + Logins []*string `type:"list"` +} + +// String returns the string representation +func (s IdentityDescription) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s IdentityDescription) GoString() string { + return s.String() +} + +// SetCreationDate sets the CreationDate field's value. +func (s *IdentityDescription) SetCreationDate(v time.Time) *IdentityDescription { + s.CreationDate = &v + return s +} + +// SetIdentityId sets the IdentityId field's value. +func (s *IdentityDescription) SetIdentityId(v string) *IdentityDescription { + s.IdentityId = &v + return s +} + +// SetLastModifiedDate sets the LastModifiedDate field's value. +func (s *IdentityDescription) SetLastModifiedDate(v time.Time) *IdentityDescription { + s.LastModifiedDate = &v + return s +} + +// SetLogins sets the Logins field's value. +func (s *IdentityDescription) SetLogins(v []*string) *IdentityDescription { + s.Logins = v + return s +} + +// An object representing an Amazon Cognito identity pool. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cognito-identity-2014-06-30/IdentityPool +type IdentityPool struct { + _ struct{} `type:"structure"` + + // TRUE if the identity pool supports unauthenticated logins. + // + // AllowUnauthenticatedIdentities is a required field + AllowUnauthenticatedIdentities *bool `type:"boolean" required:"true"` + + // A list representing an Amazon Cognito Identity User Pool and its client ID. + CognitoIdentityProviders []*Provider `type:"list"` + + // The "domain" by which Cognito will refer to your users. + DeveloperProviderName *string `min:"1" type:"string"` + + // An identity pool ID in the format REGION:GUID. + // + // IdentityPoolId is a required field + IdentityPoolId *string `min:"1" type:"string" required:"true"` + + // A string that you provide. + // + // IdentityPoolName is a required field + IdentityPoolName *string `min:"1" type:"string" required:"true"` + + // A list of OpendID Connect provider ARNs. + OpenIdConnectProviderARNs []*string `type:"list"` + + // An array of Amazon Resource Names (ARNs) of the SAML provider for your identity + // pool. + SamlProviderARNs []*string `type:"list"` + + // Optional key:value pairs mapping provider names to provider app IDs. + SupportedLoginProviders map[string]*string `type:"map"` +} + +// String returns the string representation +func (s IdentityPool) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s IdentityPool) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *IdentityPool) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "IdentityPool"} + if s.AllowUnauthenticatedIdentities == nil { + invalidParams.Add(request.NewErrParamRequired("AllowUnauthenticatedIdentities")) + } + if s.DeveloperProviderName != nil && len(*s.DeveloperProviderName) < 1 { + invalidParams.Add(request.NewErrParamMinLen("DeveloperProviderName", 1)) + } + if s.IdentityPoolId == nil { + invalidParams.Add(request.NewErrParamRequired("IdentityPoolId")) + } + if s.IdentityPoolId != nil && len(*s.IdentityPoolId) < 1 { + invalidParams.Add(request.NewErrParamMinLen("IdentityPoolId", 1)) + } + if s.IdentityPoolName == nil { + invalidParams.Add(request.NewErrParamRequired("IdentityPoolName")) + } + if s.IdentityPoolName != nil && len(*s.IdentityPoolName) < 1 { + invalidParams.Add(request.NewErrParamMinLen("IdentityPoolName", 1)) + } + if s.CognitoIdentityProviders != nil { + for i, v := range s.CognitoIdentityProviders { + if v == nil { + continue + } + if err := v.Validate(); err != nil { + invalidParams.AddNested(fmt.Sprintf("%s[%v]", "CognitoIdentityProviders", i), err.(request.ErrInvalidParams)) + } + } + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetAllowUnauthenticatedIdentities sets the AllowUnauthenticatedIdentities field's value. +func (s *IdentityPool) SetAllowUnauthenticatedIdentities(v bool) *IdentityPool { + s.AllowUnauthenticatedIdentities = &v + return s +} + +// SetCognitoIdentityProviders sets the CognitoIdentityProviders field's value. +func (s *IdentityPool) SetCognitoIdentityProviders(v []*Provider) *IdentityPool { + s.CognitoIdentityProviders = v + return s +} + +// SetDeveloperProviderName sets the DeveloperProviderName field's value. +func (s *IdentityPool) SetDeveloperProviderName(v string) *IdentityPool { + s.DeveloperProviderName = &v + return s +} + +// SetIdentityPoolId sets the IdentityPoolId field's value. +func (s *IdentityPool) SetIdentityPoolId(v string) *IdentityPool { + s.IdentityPoolId = &v + return s +} + +// SetIdentityPoolName sets the IdentityPoolName field's value. +func (s *IdentityPool) SetIdentityPoolName(v string) *IdentityPool { + s.IdentityPoolName = &v + return s +} + +// SetOpenIdConnectProviderARNs sets the OpenIdConnectProviderARNs field's value. +func (s *IdentityPool) SetOpenIdConnectProviderARNs(v []*string) *IdentityPool { + s.OpenIdConnectProviderARNs = v + return s +} + +// SetSamlProviderARNs sets the SamlProviderARNs field's value. +func (s *IdentityPool) SetSamlProviderARNs(v []*string) *IdentityPool { + s.SamlProviderARNs = v + return s +} + +// SetSupportedLoginProviders sets the SupportedLoginProviders field's value. +func (s *IdentityPool) SetSupportedLoginProviders(v map[string]*string) *IdentityPool { + s.SupportedLoginProviders = v + return s +} + +// A description of the identity pool. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cognito-identity-2014-06-30/IdentityPoolShortDescription +type IdentityPoolShortDescription struct { + _ struct{} `type:"structure"` + + // An identity pool ID in the format REGION:GUID. + IdentityPoolId *string `min:"1" type:"string"` + + // A string that you provide. + IdentityPoolName *string `min:"1" type:"string"` +} + +// String returns the string representation +func (s IdentityPoolShortDescription) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s IdentityPoolShortDescription) GoString() string { + return s.String() +} + +// SetIdentityPoolId sets the IdentityPoolId field's value. +func (s *IdentityPoolShortDescription) SetIdentityPoolId(v string) *IdentityPoolShortDescription { + s.IdentityPoolId = &v + return s +} + +// SetIdentityPoolName sets the IdentityPoolName field's value. +func (s *IdentityPoolShortDescription) SetIdentityPoolName(v string) *IdentityPoolShortDescription { + s.IdentityPoolName = &v + return s +} + +// Input to the ListIdentities action. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cognito-identity-2014-06-30/ListIdentitiesInput +type ListIdentitiesInput struct { + _ struct{} `type:"structure"` + + // An optional boolean parameter that allows you to hide disabled identities. + // If omitted, the ListIdentities API will include disabled identities in the + // response. + HideDisabled *bool `type:"boolean"` + + // An identity pool ID in the format REGION:GUID. + // + // IdentityPoolId is a required field + IdentityPoolId *string `min:"1" type:"string" required:"true"` + + // The maximum number of identities to return. + // + // MaxResults is a required field + MaxResults *int64 `min:"1" type:"integer" required:"true"` + + // A pagination token. + NextToken *string `min:"1" type:"string"` +} + +// String returns the string representation +func (s ListIdentitiesInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ListIdentitiesInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *ListIdentitiesInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "ListIdentitiesInput"} + if s.IdentityPoolId == nil { + invalidParams.Add(request.NewErrParamRequired("IdentityPoolId")) + } + if s.IdentityPoolId != nil && len(*s.IdentityPoolId) < 1 { + invalidParams.Add(request.NewErrParamMinLen("IdentityPoolId", 1)) + } + if s.MaxResults == nil { + invalidParams.Add(request.NewErrParamRequired("MaxResults")) + } + if s.MaxResults != nil && *s.MaxResults < 1 { + invalidParams.Add(request.NewErrParamMinValue("MaxResults", 1)) + } + if s.NextToken != nil && len(*s.NextToken) < 1 { + invalidParams.Add(request.NewErrParamMinLen("NextToken", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetHideDisabled sets the HideDisabled field's value. +func (s *ListIdentitiesInput) SetHideDisabled(v bool) *ListIdentitiesInput { + s.HideDisabled = &v + return s +} + +// SetIdentityPoolId sets the IdentityPoolId field's value. +func (s *ListIdentitiesInput) SetIdentityPoolId(v string) *ListIdentitiesInput { + s.IdentityPoolId = &v + return s +} + +// SetMaxResults sets the MaxResults field's value. +func (s *ListIdentitiesInput) SetMaxResults(v int64) *ListIdentitiesInput { + s.MaxResults = &v + return s +} + +// SetNextToken sets the NextToken field's value. +func (s *ListIdentitiesInput) SetNextToken(v string) *ListIdentitiesInput { + s.NextToken = &v + return s +} + +// The response to a ListIdentities request. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cognito-identity-2014-06-30/ListIdentitiesResponse +type ListIdentitiesOutput struct { + _ struct{} `type:"structure"` + + // An object containing a set of identities and associated mappings. + Identities []*IdentityDescription `type:"list"` + + // An identity pool ID in the format REGION:GUID. + IdentityPoolId *string `min:"1" type:"string"` + + // A pagination token. + NextToken *string `min:"1" type:"string"` +} + +// String returns the string representation +func (s ListIdentitiesOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ListIdentitiesOutput) GoString() string { + return s.String() +} + +// SetIdentities sets the Identities field's value. +func (s *ListIdentitiesOutput) SetIdentities(v []*IdentityDescription) *ListIdentitiesOutput { + s.Identities = v + return s +} + +// SetIdentityPoolId sets the IdentityPoolId field's value. +func (s *ListIdentitiesOutput) SetIdentityPoolId(v string) *ListIdentitiesOutput { + s.IdentityPoolId = &v + return s +} + +// SetNextToken sets the NextToken field's value. +func (s *ListIdentitiesOutput) SetNextToken(v string) *ListIdentitiesOutput { + s.NextToken = &v + return s +} + +// Input to the ListIdentityPools action. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cognito-identity-2014-06-30/ListIdentityPoolsInput +type ListIdentityPoolsInput struct { + _ struct{} `type:"structure"` + + // The maximum number of identities to return. + // + // MaxResults is a required field + MaxResults *int64 `min:"1" type:"integer" required:"true"` + + // A pagination token. + NextToken *string `min:"1" type:"string"` +} + +// String returns the string representation +func (s ListIdentityPoolsInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ListIdentityPoolsInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *ListIdentityPoolsInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "ListIdentityPoolsInput"} + if s.MaxResults == nil { + invalidParams.Add(request.NewErrParamRequired("MaxResults")) + } + if s.MaxResults != nil && *s.MaxResults < 1 { + invalidParams.Add(request.NewErrParamMinValue("MaxResults", 1)) + } + if s.NextToken != nil && len(*s.NextToken) < 1 { + invalidParams.Add(request.NewErrParamMinLen("NextToken", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetMaxResults sets the MaxResults field's value. +func (s *ListIdentityPoolsInput) SetMaxResults(v int64) *ListIdentityPoolsInput { + s.MaxResults = &v + return s +} + +// SetNextToken sets the NextToken field's value. +func (s *ListIdentityPoolsInput) SetNextToken(v string) *ListIdentityPoolsInput { + s.NextToken = &v + return s +} + +// The result of a successful ListIdentityPools action. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cognito-identity-2014-06-30/ListIdentityPoolsResponse +type ListIdentityPoolsOutput struct { + _ struct{} `type:"structure"` + + // The identity pools returned by the ListIdentityPools action. + IdentityPools []*IdentityPoolShortDescription `type:"list"` + + // A pagination token. + NextToken *string `min:"1" type:"string"` +} + +// String returns the string representation +func (s ListIdentityPoolsOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ListIdentityPoolsOutput) GoString() string { + return s.String() +} + +// SetIdentityPools sets the IdentityPools field's value. +func (s *ListIdentityPoolsOutput) SetIdentityPools(v []*IdentityPoolShortDescription) *ListIdentityPoolsOutput { + s.IdentityPools = v + return s +} + +// SetNextToken sets the NextToken field's value. +func (s *ListIdentityPoolsOutput) SetNextToken(v string) *ListIdentityPoolsOutput { + s.NextToken = &v + return s +} + +// Input to the LookupDeveloperIdentityInput action. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cognito-identity-2014-06-30/LookupDeveloperIdentityInput +type LookupDeveloperIdentityInput struct { + _ struct{} `type:"structure"` + + // A unique ID used by your backend authentication process to identify a user. + // Typically, a developer identity provider would issue many developer user + // identifiers, in keeping with the number of users. + DeveloperUserIdentifier *string `min:"1" type:"string"` + + // A unique identifier in the format REGION:GUID. + IdentityId *string `min:"1" type:"string"` + + // An identity pool ID in the format REGION:GUID. + // + // IdentityPoolId is a required field + IdentityPoolId *string `min:"1" type:"string" required:"true"` + + // The maximum number of identities to return. + MaxResults *int64 `min:"1" type:"integer"` + + // A pagination token. The first call you make will have NextToken set to null. + // After that the service will return NextToken values as needed. For example, + // let's say you make a request with MaxResults set to 10, and there are 20 + // matches in the database. The service will return a pagination token as a + // part of the response. This token can be used to call the API again and get + // results starting from the 11th match. + NextToken *string `min:"1" type:"string"` +} + +// String returns the string representation +func (s LookupDeveloperIdentityInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s LookupDeveloperIdentityInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *LookupDeveloperIdentityInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "LookupDeveloperIdentityInput"} + if s.DeveloperUserIdentifier != nil && len(*s.DeveloperUserIdentifier) < 1 { + invalidParams.Add(request.NewErrParamMinLen("DeveloperUserIdentifier", 1)) + } + if s.IdentityId != nil && len(*s.IdentityId) < 1 { + invalidParams.Add(request.NewErrParamMinLen("IdentityId", 1)) + } + if s.IdentityPoolId == nil { + invalidParams.Add(request.NewErrParamRequired("IdentityPoolId")) + } + if s.IdentityPoolId != nil && len(*s.IdentityPoolId) < 1 { + invalidParams.Add(request.NewErrParamMinLen("IdentityPoolId", 1)) + } + if s.MaxResults != nil && *s.MaxResults < 1 { + invalidParams.Add(request.NewErrParamMinValue("MaxResults", 1)) + } + if s.NextToken != nil && len(*s.NextToken) < 1 { + invalidParams.Add(request.NewErrParamMinLen("NextToken", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetDeveloperUserIdentifier sets the DeveloperUserIdentifier field's value. +func (s *LookupDeveloperIdentityInput) SetDeveloperUserIdentifier(v string) *LookupDeveloperIdentityInput { + s.DeveloperUserIdentifier = &v + return s +} + +// SetIdentityId sets the IdentityId field's value. +func (s *LookupDeveloperIdentityInput) SetIdentityId(v string) *LookupDeveloperIdentityInput { + s.IdentityId = &v + return s +} + +// SetIdentityPoolId sets the IdentityPoolId field's value. +func (s *LookupDeveloperIdentityInput) SetIdentityPoolId(v string) *LookupDeveloperIdentityInput { + s.IdentityPoolId = &v + return s +} + +// SetMaxResults sets the MaxResults field's value. +func (s *LookupDeveloperIdentityInput) SetMaxResults(v int64) *LookupDeveloperIdentityInput { + s.MaxResults = &v + return s +} + +// SetNextToken sets the NextToken field's value. +func (s *LookupDeveloperIdentityInput) SetNextToken(v string) *LookupDeveloperIdentityInput { + s.NextToken = &v + return s +} + +// Returned in response to a successful LookupDeveloperIdentity action. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cognito-identity-2014-06-30/LookupDeveloperIdentityResponse +type LookupDeveloperIdentityOutput struct { + _ struct{} `type:"structure"` + + // This is the list of developer user identifiers associated with an identity + // ID. Cognito supports the association of multiple developer user identifiers + // with an identity ID. + DeveloperUserIdentifierList []*string `type:"list"` + + // A unique identifier in the format REGION:GUID. + IdentityId *string `min:"1" type:"string"` + + // A pagination token. The first call you make will have NextToken set to null. + // After that the service will return NextToken values as needed. For example, + // let's say you make a request with MaxResults set to 10, and there are 20 + // matches in the database. The service will return a pagination token as a + // part of the response. This token can be used to call the API again and get + // results starting from the 11th match. + NextToken *string `min:"1" type:"string"` +} + +// String returns the string representation +func (s LookupDeveloperIdentityOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s LookupDeveloperIdentityOutput) GoString() string { + return s.String() +} + +// SetDeveloperUserIdentifierList sets the DeveloperUserIdentifierList field's value. +func (s *LookupDeveloperIdentityOutput) SetDeveloperUserIdentifierList(v []*string) *LookupDeveloperIdentityOutput { + s.DeveloperUserIdentifierList = v + return s +} + +// SetIdentityId sets the IdentityId field's value. +func (s *LookupDeveloperIdentityOutput) SetIdentityId(v string) *LookupDeveloperIdentityOutput { + s.IdentityId = &v + return s +} + +// SetNextToken sets the NextToken field's value. +func (s *LookupDeveloperIdentityOutput) SetNextToken(v string) *LookupDeveloperIdentityOutput { + s.NextToken = &v + return s +} + +// A rule that maps a claim name, a claim value, and a match type to a role +// ARN. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cognito-identity-2014-06-30/MappingRule +type MappingRule struct { + _ struct{} `type:"structure"` + + // The claim name that must be present in the token, for example, "isAdmin" + // or "paid". + // + // Claim is a required field + Claim *string `min:"1" type:"string" required:"true"` + + // The match condition that specifies how closely the claim value in the IdP + // token must match Value. + // + // MatchType is a required field + MatchType *string `type:"string" required:"true" enum:"MappingRuleMatchType"` + + // The role ARN. + // + // RoleARN is a required field + RoleARN *string `min:"20" type:"string" required:"true"` + + // A brief string that the claim must match, for example, "paid" or "yes". + // + // Value is a required field + Value *string `min:"1" type:"string" required:"true"` +} + +// String returns the string representation +func (s MappingRule) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s MappingRule) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *MappingRule) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "MappingRule"} + if s.Claim == nil { + invalidParams.Add(request.NewErrParamRequired("Claim")) + } + if s.Claim != nil && len(*s.Claim) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Claim", 1)) + } + if s.MatchType == nil { + invalidParams.Add(request.NewErrParamRequired("MatchType")) + } + if s.RoleARN == nil { + invalidParams.Add(request.NewErrParamRequired("RoleARN")) + } + if s.RoleARN != nil && len(*s.RoleARN) < 20 { + invalidParams.Add(request.NewErrParamMinLen("RoleARN", 20)) + } + if s.Value == nil { + invalidParams.Add(request.NewErrParamRequired("Value")) + } + if s.Value != nil && len(*s.Value) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Value", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetClaim sets the Claim field's value. +func (s *MappingRule) SetClaim(v string) *MappingRule { + s.Claim = &v + return s +} + +// SetMatchType sets the MatchType field's value. +func (s *MappingRule) SetMatchType(v string) *MappingRule { + s.MatchType = &v + return s +} + +// SetRoleARN sets the RoleARN field's value. +func (s *MappingRule) SetRoleARN(v string) *MappingRule { + s.RoleARN = &v + return s +} + +// SetValue sets the Value field's value. +func (s *MappingRule) SetValue(v string) *MappingRule { + s.Value = &v + return s +} + +// Input to the MergeDeveloperIdentities action. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cognito-identity-2014-06-30/MergeDeveloperIdentitiesInput +type MergeDeveloperIdentitiesInput struct { + _ struct{} `type:"structure"` + + // User identifier for the destination user. The value should be a DeveloperUserIdentifier. + // + // DestinationUserIdentifier is a required field + DestinationUserIdentifier *string `min:"1" type:"string" required:"true"` + + // The "domain" by which Cognito will refer to your users. This is a (pseudo) + // domain name that you provide while creating an identity pool. This name acts + // as a placeholder that allows your backend and the Cognito service to communicate + // about the developer provider. For the DeveloperProviderName, you can use + // letters as well as period (.), underscore (_), and dash (-). + // + // DeveloperProviderName is a required field + DeveloperProviderName *string `min:"1" type:"string" required:"true"` + + // An identity pool ID in the format REGION:GUID. + // + // IdentityPoolId is a required field + IdentityPoolId *string `min:"1" type:"string" required:"true"` + + // User identifier for the source user. The value should be a DeveloperUserIdentifier. + // + // SourceUserIdentifier is a required field + SourceUserIdentifier *string `min:"1" type:"string" required:"true"` +} + +// String returns the string representation +func (s MergeDeveloperIdentitiesInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s MergeDeveloperIdentitiesInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *MergeDeveloperIdentitiesInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "MergeDeveloperIdentitiesInput"} + if s.DestinationUserIdentifier == nil { + invalidParams.Add(request.NewErrParamRequired("DestinationUserIdentifier")) + } + if s.DestinationUserIdentifier != nil && len(*s.DestinationUserIdentifier) < 1 { + invalidParams.Add(request.NewErrParamMinLen("DestinationUserIdentifier", 1)) + } + if s.DeveloperProviderName == nil { + invalidParams.Add(request.NewErrParamRequired("DeveloperProviderName")) + } + if s.DeveloperProviderName != nil && len(*s.DeveloperProviderName) < 1 { + invalidParams.Add(request.NewErrParamMinLen("DeveloperProviderName", 1)) + } + if s.IdentityPoolId == nil { + invalidParams.Add(request.NewErrParamRequired("IdentityPoolId")) + } + if s.IdentityPoolId != nil && len(*s.IdentityPoolId) < 1 { + invalidParams.Add(request.NewErrParamMinLen("IdentityPoolId", 1)) + } + if s.SourceUserIdentifier == nil { + invalidParams.Add(request.NewErrParamRequired("SourceUserIdentifier")) + } + if s.SourceUserIdentifier != nil && len(*s.SourceUserIdentifier) < 1 { + invalidParams.Add(request.NewErrParamMinLen("SourceUserIdentifier", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetDestinationUserIdentifier sets the DestinationUserIdentifier field's value. +func (s *MergeDeveloperIdentitiesInput) SetDestinationUserIdentifier(v string) *MergeDeveloperIdentitiesInput { + s.DestinationUserIdentifier = &v + return s +} + +// SetDeveloperProviderName sets the DeveloperProviderName field's value. +func (s *MergeDeveloperIdentitiesInput) SetDeveloperProviderName(v string) *MergeDeveloperIdentitiesInput { + s.DeveloperProviderName = &v + return s +} + +// SetIdentityPoolId sets the IdentityPoolId field's value. +func (s *MergeDeveloperIdentitiesInput) SetIdentityPoolId(v string) *MergeDeveloperIdentitiesInput { + s.IdentityPoolId = &v + return s +} + +// SetSourceUserIdentifier sets the SourceUserIdentifier field's value. +func (s *MergeDeveloperIdentitiesInput) SetSourceUserIdentifier(v string) *MergeDeveloperIdentitiesInput { + s.SourceUserIdentifier = &v + return s +} + +// Returned in response to a successful MergeDeveloperIdentities action. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cognito-identity-2014-06-30/MergeDeveloperIdentitiesResponse +type MergeDeveloperIdentitiesOutput struct { + _ struct{} `type:"structure"` + + // A unique identifier in the format REGION:GUID. + IdentityId *string `min:"1" type:"string"` +} + +// String returns the string representation +func (s MergeDeveloperIdentitiesOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s MergeDeveloperIdentitiesOutput) GoString() string { + return s.String() +} + +// SetIdentityId sets the IdentityId field's value. +func (s *MergeDeveloperIdentitiesOutput) SetIdentityId(v string) *MergeDeveloperIdentitiesOutput { + s.IdentityId = &v + return s +} + +// A provider representing an Amazon Cognito Identity User Pool and its client +// ID. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cognito-identity-2014-06-30/CognitoIdentityProvider +type Provider struct { + _ struct{} `type:"structure"` + + // The client ID for the Amazon Cognito Identity User Pool. + ClientId *string `min:"1" type:"string"` + + // The provider name for an Amazon Cognito Identity User Pool. For example, + // cognito-idp.us-east-1.amazonaws.com/us-east-1_123456789. + ProviderName *string `min:"1" type:"string"` + + // TRUE if server-side token validation is enabled for the identity provider’s + // token. + ServerSideTokenCheck *bool `type:"boolean"` +} + +// String returns the string representation +func (s Provider) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s Provider) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *Provider) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "Provider"} + if s.ClientId != nil && len(*s.ClientId) < 1 { + invalidParams.Add(request.NewErrParamMinLen("ClientId", 1)) + } + if s.ProviderName != nil && len(*s.ProviderName) < 1 { + invalidParams.Add(request.NewErrParamMinLen("ProviderName", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetClientId sets the ClientId field's value. +func (s *Provider) SetClientId(v string) *Provider { + s.ClientId = &v + return s +} + +// SetProviderName sets the ProviderName field's value. +func (s *Provider) SetProviderName(v string) *Provider { + s.ProviderName = &v + return s +} + +// SetServerSideTokenCheck sets the ServerSideTokenCheck field's value. +func (s *Provider) SetServerSideTokenCheck(v bool) *Provider { + s.ServerSideTokenCheck = &v + return s +} + +// A role mapping. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cognito-identity-2014-06-30/RoleMapping +type RoleMapping struct { + _ struct{} `type:"structure"` + + // If you specify Token or Rules as the Type, AmbiguousRoleResolution is required. + // + // Specifies the action to be taken if either no rules match the claim value + // for the Rules type, or there is no cognito:preferred_role claim and there + // are multiple cognito:roles matches for the Token type. + AmbiguousRoleResolution *string `type:"string" enum:"AmbiguousRoleResolutionType"` + + // The rules to be used for mapping users to roles. + // + // If you specify Rules as the role mapping type, RulesConfiguration is required. + RulesConfiguration *RulesConfigurationType `type:"structure"` + + // The role mapping type. Token will use cognito:roles and cognito:preferred_role + // claims from the Cognito identity provider token to map groups to roles. Rules + // will attempt to match claims from the token to map to a role. + // + // Type is a required field + Type *string `type:"string" required:"true" enum:"RoleMappingType"` +} + +// String returns the string representation +func (s RoleMapping) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s RoleMapping) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *RoleMapping) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "RoleMapping"} + if s.Type == nil { + invalidParams.Add(request.NewErrParamRequired("Type")) + } + if s.RulesConfiguration != nil { + if err := s.RulesConfiguration.Validate(); err != nil { + invalidParams.AddNested("RulesConfiguration", err.(request.ErrInvalidParams)) + } + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetAmbiguousRoleResolution sets the AmbiguousRoleResolution field's value. +func (s *RoleMapping) SetAmbiguousRoleResolution(v string) *RoleMapping { + s.AmbiguousRoleResolution = &v + return s +} + +// SetRulesConfiguration sets the RulesConfiguration field's value. +func (s *RoleMapping) SetRulesConfiguration(v *RulesConfigurationType) *RoleMapping { + s.RulesConfiguration = v + return s +} + +// SetType sets the Type field's value. +func (s *RoleMapping) SetType(v string) *RoleMapping { + s.Type = &v + return s +} + +// A container for rules. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cognito-identity-2014-06-30/RulesConfigurationType +type RulesConfigurationType struct { + _ struct{} `type:"structure"` + + // An array of rules. You can specify up to 25 rules per identity provider. + // + // Rules are evaluated in order. The first one to match specifies the role. + // + // Rules is a required field + Rules []*MappingRule `min:"1" type:"list" required:"true"` +} + +// String returns the string representation +func (s RulesConfigurationType) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s RulesConfigurationType) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *RulesConfigurationType) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "RulesConfigurationType"} + if s.Rules == nil { + invalidParams.Add(request.NewErrParamRequired("Rules")) + } + if s.Rules != nil && len(s.Rules) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Rules", 1)) + } + if s.Rules != nil { + for i, v := range s.Rules { + if v == nil { + continue + } + if err := v.Validate(); err != nil { + invalidParams.AddNested(fmt.Sprintf("%s[%v]", "Rules", i), err.(request.ErrInvalidParams)) + } + } + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetRules sets the Rules field's value. +func (s *RulesConfigurationType) SetRules(v []*MappingRule) *RulesConfigurationType { + s.Rules = v + return s +} + +// Input to the SetIdentityPoolRoles action. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cognito-identity-2014-06-30/SetIdentityPoolRolesInput +type SetIdentityPoolRolesInput struct { + _ struct{} `type:"structure"` + + // An identity pool ID in the format REGION:GUID. + // + // IdentityPoolId is a required field + IdentityPoolId *string `min:"1" type:"string" required:"true"` + + // How users for a specific identity provider are to mapped to roles. This is + // a string to RoleMapping object map. The string identifies the identity provider, + // for example, "graph.facebook.com" or "cognito-idp-east-1.amazonaws.com/us-east-1_abcdefghi:app_client_id". + // + // Up to 25 rules can be specified per identity provider. + RoleMappings map[string]*RoleMapping `type:"map"` + + // The map of roles associated with this pool. For a given role, the key will + // be either "authenticated" or "unauthenticated" and the value will be the + // Role ARN. + // + // Roles is a required field + Roles map[string]*string `type:"map" required:"true"` +} + +// String returns the string representation +func (s SetIdentityPoolRolesInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s SetIdentityPoolRolesInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *SetIdentityPoolRolesInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "SetIdentityPoolRolesInput"} + if s.IdentityPoolId == nil { + invalidParams.Add(request.NewErrParamRequired("IdentityPoolId")) + } + if s.IdentityPoolId != nil && len(*s.IdentityPoolId) < 1 { + invalidParams.Add(request.NewErrParamMinLen("IdentityPoolId", 1)) + } + if s.Roles == nil { + invalidParams.Add(request.NewErrParamRequired("Roles")) + } + if s.RoleMappings != nil { + for i, v := range s.RoleMappings { + if v == nil { + continue + } + if err := v.Validate(); err != nil { + invalidParams.AddNested(fmt.Sprintf("%s[%v]", "RoleMappings", i), err.(request.ErrInvalidParams)) + } + } + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetIdentityPoolId sets the IdentityPoolId field's value. +func (s *SetIdentityPoolRolesInput) SetIdentityPoolId(v string) *SetIdentityPoolRolesInput { + s.IdentityPoolId = &v + return s +} + +// SetRoleMappings sets the RoleMappings field's value. +func (s *SetIdentityPoolRolesInput) SetRoleMappings(v map[string]*RoleMapping) *SetIdentityPoolRolesInput { + s.RoleMappings = v + return s +} + +// SetRoles sets the Roles field's value. +func (s *SetIdentityPoolRolesInput) SetRoles(v map[string]*string) *SetIdentityPoolRolesInput { + s.Roles = v + return s +} + +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cognito-identity-2014-06-30/SetIdentityPoolRolesOutput +type SetIdentityPoolRolesOutput struct { + _ struct{} `type:"structure"` +} + +// String returns the string representation +func (s SetIdentityPoolRolesOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s SetIdentityPoolRolesOutput) GoString() string { + return s.String() +} + +// Input to the UnlinkDeveloperIdentity action. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cognito-identity-2014-06-30/UnlinkDeveloperIdentityInput +type UnlinkDeveloperIdentityInput struct { + _ struct{} `type:"structure"` + + // The "domain" by which Cognito will refer to your users. + // + // DeveloperProviderName is a required field + DeveloperProviderName *string `min:"1" type:"string" required:"true"` + + // A unique ID used by your backend authentication process to identify a user. + // + // DeveloperUserIdentifier is a required field + DeveloperUserIdentifier *string `min:"1" type:"string" required:"true"` + + // A unique identifier in the format REGION:GUID. + // + // IdentityId is a required field + IdentityId *string `min:"1" type:"string" required:"true"` + + // An identity pool ID in the format REGION:GUID. + // + // IdentityPoolId is a required field + IdentityPoolId *string `min:"1" type:"string" required:"true"` +} + +// String returns the string representation +func (s UnlinkDeveloperIdentityInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s UnlinkDeveloperIdentityInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *UnlinkDeveloperIdentityInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "UnlinkDeveloperIdentityInput"} + if s.DeveloperProviderName == nil { + invalidParams.Add(request.NewErrParamRequired("DeveloperProviderName")) + } + if s.DeveloperProviderName != nil && len(*s.DeveloperProviderName) < 1 { + invalidParams.Add(request.NewErrParamMinLen("DeveloperProviderName", 1)) + } + if s.DeveloperUserIdentifier == nil { + invalidParams.Add(request.NewErrParamRequired("DeveloperUserIdentifier")) + } + if s.DeveloperUserIdentifier != nil && len(*s.DeveloperUserIdentifier) < 1 { + invalidParams.Add(request.NewErrParamMinLen("DeveloperUserIdentifier", 1)) + } + if s.IdentityId == nil { + invalidParams.Add(request.NewErrParamRequired("IdentityId")) + } + if s.IdentityId != nil && len(*s.IdentityId) < 1 { + invalidParams.Add(request.NewErrParamMinLen("IdentityId", 1)) + } + if s.IdentityPoolId == nil { + invalidParams.Add(request.NewErrParamRequired("IdentityPoolId")) + } + if s.IdentityPoolId != nil && len(*s.IdentityPoolId) < 1 { + invalidParams.Add(request.NewErrParamMinLen("IdentityPoolId", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetDeveloperProviderName sets the DeveloperProviderName field's value. +func (s *UnlinkDeveloperIdentityInput) SetDeveloperProviderName(v string) *UnlinkDeveloperIdentityInput { + s.DeveloperProviderName = &v + return s +} + +// SetDeveloperUserIdentifier sets the DeveloperUserIdentifier field's value. +func (s *UnlinkDeveloperIdentityInput) SetDeveloperUserIdentifier(v string) *UnlinkDeveloperIdentityInput { + s.DeveloperUserIdentifier = &v + return s +} + +// SetIdentityId sets the IdentityId field's value. +func (s *UnlinkDeveloperIdentityInput) SetIdentityId(v string) *UnlinkDeveloperIdentityInput { + s.IdentityId = &v + return s +} + +// SetIdentityPoolId sets the IdentityPoolId field's value. +func (s *UnlinkDeveloperIdentityInput) SetIdentityPoolId(v string) *UnlinkDeveloperIdentityInput { + s.IdentityPoolId = &v + return s +} + +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cognito-identity-2014-06-30/UnlinkDeveloperIdentityOutput +type UnlinkDeveloperIdentityOutput struct { + _ struct{} `type:"structure"` +} + +// String returns the string representation +func (s UnlinkDeveloperIdentityOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s UnlinkDeveloperIdentityOutput) GoString() string { + return s.String() +} + +// Input to the UnlinkIdentity action. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cognito-identity-2014-06-30/UnlinkIdentityInput +type UnlinkIdentityInput struct { + _ struct{} `type:"structure"` + + // A unique identifier in the format REGION:GUID. + // + // IdentityId is a required field + IdentityId *string `min:"1" type:"string" required:"true"` + + // A set of optional name-value pairs that map provider names to provider tokens. + // + // Logins is a required field + Logins map[string]*string `type:"map" required:"true"` + + // Provider names to unlink from this identity. + // + // LoginsToRemove is a required field + LoginsToRemove []*string `type:"list" required:"true"` +} + +// String returns the string representation +func (s UnlinkIdentityInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s UnlinkIdentityInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *UnlinkIdentityInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "UnlinkIdentityInput"} + if s.IdentityId == nil { + invalidParams.Add(request.NewErrParamRequired("IdentityId")) + } + if s.IdentityId != nil && len(*s.IdentityId) < 1 { + invalidParams.Add(request.NewErrParamMinLen("IdentityId", 1)) + } + if s.Logins == nil { + invalidParams.Add(request.NewErrParamRequired("Logins")) + } + if s.LoginsToRemove == nil { + invalidParams.Add(request.NewErrParamRequired("LoginsToRemove")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetIdentityId sets the IdentityId field's value. +func (s *UnlinkIdentityInput) SetIdentityId(v string) *UnlinkIdentityInput { + s.IdentityId = &v + return s +} + +// SetLogins sets the Logins field's value. +func (s *UnlinkIdentityInput) SetLogins(v map[string]*string) *UnlinkIdentityInput { + s.Logins = v + return s +} + +// SetLoginsToRemove sets the LoginsToRemove field's value. +func (s *UnlinkIdentityInput) SetLoginsToRemove(v []*string) *UnlinkIdentityInput { + s.LoginsToRemove = v + return s +} + +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cognito-identity-2014-06-30/UnlinkIdentityOutput +type UnlinkIdentityOutput struct { + _ struct{} `type:"structure"` +} + +// String returns the string representation +func (s UnlinkIdentityOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s UnlinkIdentityOutput) GoString() string { + return s.String() +} + +// An array of UnprocessedIdentityId objects, each of which contains an ErrorCode +// and IdentityId. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/cognito-identity-2014-06-30/UnprocessedIdentityId +type UnprocessedIdentityId struct { + _ struct{} `type:"structure"` + + // The error code indicating the type of error that occurred. + ErrorCode *string `type:"string" enum:"ErrorCode"` + + // A unique identifier in the format REGION:GUID. + IdentityId *string `min:"1" type:"string"` +} + +// String returns the string representation +func (s UnprocessedIdentityId) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s UnprocessedIdentityId) GoString() string { + return s.String() +} + +// SetErrorCode sets the ErrorCode field's value. +func (s *UnprocessedIdentityId) SetErrorCode(v string) *UnprocessedIdentityId { + s.ErrorCode = &v + return s +} + +// SetIdentityId sets the IdentityId field's value. +func (s *UnprocessedIdentityId) SetIdentityId(v string) *UnprocessedIdentityId { + s.IdentityId = &v + return s +} + +const ( + // AmbiguousRoleResolutionTypeAuthenticatedRole is a AmbiguousRoleResolutionType enum value + AmbiguousRoleResolutionTypeAuthenticatedRole = "AuthenticatedRole" + + // AmbiguousRoleResolutionTypeDeny is a AmbiguousRoleResolutionType enum value + AmbiguousRoleResolutionTypeDeny = "Deny" +) + +const ( + // ErrorCodeAccessDenied is a ErrorCode enum value + ErrorCodeAccessDenied = "AccessDenied" + + // ErrorCodeInternalServerError is a ErrorCode enum value + ErrorCodeInternalServerError = "InternalServerError" +) + +const ( + // MappingRuleMatchTypeEquals is a MappingRuleMatchType enum value + MappingRuleMatchTypeEquals = "Equals" + + // MappingRuleMatchTypeContains is a MappingRuleMatchType enum value + MappingRuleMatchTypeContains = "Contains" + + // MappingRuleMatchTypeStartsWith is a MappingRuleMatchType enum value + MappingRuleMatchTypeStartsWith = "StartsWith" + + // MappingRuleMatchTypeNotEqual is a MappingRuleMatchType enum value + MappingRuleMatchTypeNotEqual = "NotEqual" +) + +const ( + // RoleMappingTypeToken is a RoleMappingType enum value + RoleMappingTypeToken = "Token" + + // RoleMappingTypeRules is a RoleMappingType enum value + RoleMappingTypeRules = "Rules" +) diff --git a/vendor/github.com/aws/aws-sdk-go/service/cognitoidentity/customizations.go b/vendor/github.com/aws/aws-sdk-go/service/cognitoidentity/customizations.go new file mode 100644 index 000000000..4bf243c35 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/service/cognitoidentity/customizations.go @@ -0,0 +1,12 @@ +package cognitoidentity + +import "github.com/aws/aws-sdk-go/aws/request" + +func init() { + initRequest = func(r *request.Request) { + switch r.Operation.Name { + case opGetOpenIdToken, opGetId, opGetCredentialsForIdentity: + r.Handlers.Sign.Clear() // these operations are unsigned + } + } +} diff --git a/vendor/github.com/aws/aws-sdk-go/service/cognitoidentity/doc.go b/vendor/github.com/aws/aws-sdk-go/service/cognitoidentity/doc.go new file mode 100644 index 000000000..138b4503a --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/service/cognitoidentity/doc.go @@ -0,0 +1,111 @@ +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. + +// Package cognitoidentity provides the client and types for making API +// requests to Amazon Cognito Identity. +// +// Amazon Cognito is a web service that delivers scoped temporary credentials +// to mobile devices and other untrusted environments. Amazon Cognito uniquely +// identifies a device and supplies the user with a consistent identity over +// the lifetime of an application. +// +// Using Amazon Cognito, you can enable authentication with one or more third-party +// identity providers (Facebook, Google, or Login with Amazon), and you can +// also choose to support unauthenticated access from your app. Cognito delivers +// a unique identifier for each user and acts as an OpenID token provider trusted +// by AWS Security Token Service (STS) to access temporary, limited-privilege +// AWS credentials. +// +// To provide end-user credentials, first make an unsigned call to GetId. If +// the end user is authenticated with one of the supported identity providers, +// set the Logins map with the identity provider token. GetId returns a unique +// identifier for the user. +// +// Next, make an unsigned call to GetCredentialsForIdentity. This call expects +// the same Logins map as the GetId call, as well as the IdentityID originally +// returned by GetId. Assuming your identity pool has been configured via the +// SetIdentityPoolRoles operation, GetCredentialsForIdentity will return AWS +// credentials for your use. If your pool has not been configured with SetIdentityPoolRoles, +// or if you want to follow legacy flow, make an unsigned call to GetOpenIdToken, +// which returns the OpenID token necessary to call STS and retrieve AWS credentials. +// This call expects the same Logins map as the GetId call, as well as the IdentityID +// originally returned by GetId. The token returned by GetOpenIdToken can be +// passed to the STS operation AssumeRoleWithWebIdentity (http://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRoleWithWebIdentity.html) +// to retrieve AWS credentials. +// +// If you want to use Amazon Cognito in an Android, iOS, or Unity application, +// you will probably want to make API calls via the AWS Mobile SDK. To learn +// more, see the AWS Mobile SDK Developer Guide (http://docs.aws.amazon.com/mobile/index.html). +// +// See https://docs.aws.amazon.com/goto/WebAPI/cognito-identity-2014-06-30 for more information on this service. +// +// See cognitoidentity package documentation for more information. +// https://docs.aws.amazon.com/sdk-for-go/api/service/cognitoidentity/ +// +// Using the Client +// +// To use the client for Amazon Cognito Identity you will first need +// to create a new instance of it. +// +// When creating a client for an AWS service you'll first need to have a Session +// already created. The Session provides configuration that can be shared +// between multiple service clients. Additional configuration can be applied to +// the Session and service's client when they are constructed. The aws package's +// Config type contains several fields such as Region for the AWS Region the +// client should make API requests too. The optional Config value can be provided +// as the variadic argument for Sessions and client creation. +// +// Once the service's client is created you can use it to make API requests the +// AWS service. These clients are safe to use concurrently. +// +// // Create a session to share configuration, and load external configuration. +// sess := session.Must(session.NewSession()) +// +// // Create the service's client with the session. +// svc := cognitoidentity.New(sess) +// +// See the SDK's documentation for more information on how to use service clients. +// https://docs.aws.amazon.com/sdk-for-go/api/ +// +// See aws package's Config type for more information on configuration options. +// https://docs.aws.amazon.com/sdk-for-go/api/aws/#Config +// +// See the Amazon Cognito Identity client CognitoIdentity for more +// information on creating the service's client. +// https://docs.aws.amazon.com/sdk-for-go/api/service/cognitoidentity/#New +// +// Once the client is created you can make an API request to the service. +// Each API method takes a input parameter, and returns the service response +// and an error. +// +// The API method will document which error codes the service can be returned +// by the operation if the service models the API operation's errors. These +// errors will also be available as const strings prefixed with "ErrCode". +// +// result, err := svc.CreateIdentityPool(params) +// if err != nil { +// // Cast err to awserr.Error to handle specific error codes. +// aerr, ok := err.(awserr.Error) +// if ok && aerr.Code() == { +// // Specific error code handling +// } +// return err +// } +// +// fmt.Println("CreateIdentityPool result:") +// fmt.Println(result) +// +// Using the Client with Context +// +// The service's client also provides methods to make API requests with a Context +// value. This allows you to control the timeout, and cancellation of pending +// requests. These methods also take request Option as variadic parameter to apply +// additional configuration to the API request. +// +// ctx := context.Background() +// +// result, err := svc.CreateIdentityPoolWithContext(ctx, params) +// +// See the request package documentation for more information on using Context pattern +// with the SDK. +// https://docs.aws.amazon.com/sdk-for-go/api/aws/request/ +package cognitoidentity diff --git a/vendor/github.com/aws/aws-sdk-go/service/cognitoidentity/errors.go b/vendor/github.com/aws/aws-sdk-go/service/cognitoidentity/errors.go new file mode 100644 index 000000000..9094d135b --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/service/cognitoidentity/errors.go @@ -0,0 +1,77 @@ +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. + +package cognitoidentity + +const ( + + // ErrCodeConcurrentModificationException for service response error code + // "ConcurrentModificationException". + // + // Thrown if there are parallel requests to modify a resource. + ErrCodeConcurrentModificationException = "ConcurrentModificationException" + + // ErrCodeDeveloperUserAlreadyRegisteredException for service response error code + // "DeveloperUserAlreadyRegisteredException". + // + // The provided developer user identifier is already registered with Cognito + // under a different identity ID. + ErrCodeDeveloperUserAlreadyRegisteredException = "DeveloperUserAlreadyRegisteredException" + + // ErrCodeExternalServiceException for service response error code + // "ExternalServiceException". + // + // An exception thrown when a dependent service such as Facebook or Twitter + // is not responding + ErrCodeExternalServiceException = "ExternalServiceException" + + // ErrCodeInternalErrorException for service response error code + // "InternalErrorException". + // + // Thrown when the service encounters an error during processing the request. + ErrCodeInternalErrorException = "InternalErrorException" + + // ErrCodeInvalidIdentityPoolConfigurationException for service response error code + // "InvalidIdentityPoolConfigurationException". + // + // Thrown if the identity pool has no role associated for the given auth type + // (auth/unauth) or if the AssumeRole fails. + ErrCodeInvalidIdentityPoolConfigurationException = "InvalidIdentityPoolConfigurationException" + + // ErrCodeInvalidParameterException for service response error code + // "InvalidParameterException". + // + // Thrown for missing or bad input parameter(s). + ErrCodeInvalidParameterException = "InvalidParameterException" + + // ErrCodeLimitExceededException for service response error code + // "LimitExceededException". + // + // Thrown when the total number of user pools has exceeded a preset limit. + ErrCodeLimitExceededException = "LimitExceededException" + + // ErrCodeNotAuthorizedException for service response error code + // "NotAuthorizedException". + // + // Thrown when a user is not authorized to access the requested resource. + ErrCodeNotAuthorizedException = "NotAuthorizedException" + + // ErrCodeResourceConflictException for service response error code + // "ResourceConflictException". + // + // Thrown when a user tries to use a login which is already linked to another + // account. + ErrCodeResourceConflictException = "ResourceConflictException" + + // ErrCodeResourceNotFoundException for service response error code + // "ResourceNotFoundException". + // + // Thrown when the requested resource (for example, a dataset or record) does + // not exist. + ErrCodeResourceNotFoundException = "ResourceNotFoundException" + + // ErrCodeTooManyRequestsException for service response error code + // "TooManyRequestsException". + // + // Thrown when a request is throttled. + ErrCodeTooManyRequestsException = "TooManyRequestsException" +) diff --git a/vendor/github.com/aws/aws-sdk-go/service/cognitoidentity/service.go b/vendor/github.com/aws/aws-sdk-go/service/cognitoidentity/service.go new file mode 100644 index 000000000..ee82b18ce --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/service/cognitoidentity/service.go @@ -0,0 +1,95 @@ +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. + +package cognitoidentity + +import ( + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/client" + "github.com/aws/aws-sdk-go/aws/client/metadata" + "github.com/aws/aws-sdk-go/aws/request" + "github.com/aws/aws-sdk-go/aws/signer/v4" + "github.com/aws/aws-sdk-go/private/protocol/jsonrpc" +) + +// CognitoIdentity provides the API operation methods for making requests to +// Amazon Cognito Identity. See this package's package overview docs +// for details on the service. +// +// CognitoIdentity methods are safe to use concurrently. It is not safe to +// modify mutate any of the struct's properties though. +type CognitoIdentity struct { + *client.Client +} + +// Used for custom client initialization logic +var initClient func(*client.Client) + +// Used for custom request initialization logic +var initRequest func(*request.Request) + +// Service information constants +const ( + ServiceName = "cognito-identity" // Service endpoint prefix API calls made to. + EndpointsID = ServiceName // Service ID for Regions and Endpoints metadata. +) + +// New creates a new instance of the CognitoIdentity client with a session. +// If additional configuration is needed for the client instance use the optional +// aws.Config parameter to add your extra config. +// +// Example: +// // Create a CognitoIdentity client from just a session. +// svc := cognitoidentity.New(mySession) +// +// // Create a CognitoIdentity client with additional configuration +// svc := cognitoidentity.New(mySession, aws.NewConfig().WithRegion("us-west-2")) +func New(p client.ConfigProvider, cfgs ...*aws.Config) *CognitoIdentity { + c := p.ClientConfig(EndpointsID, cfgs...) + return newClient(*c.Config, c.Handlers, c.Endpoint, c.SigningRegion, c.SigningName) +} + +// newClient creates, initializes and returns a new service client instance. +func newClient(cfg aws.Config, handlers request.Handlers, endpoint, signingRegion, signingName string) *CognitoIdentity { + svc := &CognitoIdentity{ + Client: client.New( + cfg, + metadata.ClientInfo{ + ServiceName: ServiceName, + SigningName: signingName, + SigningRegion: signingRegion, + Endpoint: endpoint, + APIVersion: "2014-06-30", + JSONVersion: "1.1", + TargetPrefix: "AWSCognitoIdentityService", + }, + handlers, + ), + } + + // Handlers + svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler) + svc.Handlers.Build.PushBackNamed(jsonrpc.BuildHandler) + svc.Handlers.Unmarshal.PushBackNamed(jsonrpc.UnmarshalHandler) + svc.Handlers.UnmarshalMeta.PushBackNamed(jsonrpc.UnmarshalMetaHandler) + svc.Handlers.UnmarshalError.PushBackNamed(jsonrpc.UnmarshalErrorHandler) + + // Run custom client initialization if present + if initClient != nil { + initClient(svc.Client) + } + + return svc +} + +// newRequest creates a new request for a CognitoIdentity operation and runs any +// custom request initialization. +func (c *CognitoIdentity) newRequest(op *request.Operation, params, data interface{}) *request.Request { + req := c.NewRequest(op, params, data) + + // Run custom request initialization if present + if initRequest != nil { + initRequest(req) + } + + return req +} diff --git a/vendor/github.com/aws/aws-sdk-go/service/configservice/api.go b/vendor/github.com/aws/aws-sdk-go/service/configservice/api.go index c5b4467ce..76a18e5e5 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/configservice/api.go +++ b/vendor/github.com/aws/aws-sdk-go/service/configservice/api.go @@ -1,12 +1,12 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. -// Package configservice provides a client for AWS Config. package configservice import ( "fmt" "time" + "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awsutil" "github.com/aws/aws-sdk-go/aws/request" "github.com/aws/aws-sdk-go/private/protocol" @@ -87,8 +87,23 @@ func (c *ConfigService) DeleteConfigRuleRequest(input *DeleteConfigRuleInput) (r // Please also see https://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/DeleteConfigRule func (c *ConfigService) DeleteConfigRule(input *DeleteConfigRuleInput) (*DeleteConfigRuleOutput, error) { req, out := c.DeleteConfigRuleRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteConfigRuleWithContext is the same as DeleteConfigRule with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteConfigRule 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 *ConfigService) DeleteConfigRuleWithContext(ctx aws.Context, input *DeleteConfigRuleInput, opts ...request.Option) (*DeleteConfigRuleOutput, error) { + req, out := c.DeleteConfigRuleRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteConfigurationRecorder = "DeleteConfigurationRecorder" @@ -163,8 +178,23 @@ func (c *ConfigService) DeleteConfigurationRecorderRequest(input *DeleteConfigur // Please also see https://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/DeleteConfigurationRecorder func (c *ConfigService) DeleteConfigurationRecorder(input *DeleteConfigurationRecorderInput) (*DeleteConfigurationRecorderOutput, error) { req, out := c.DeleteConfigurationRecorderRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteConfigurationRecorderWithContext is the same as DeleteConfigurationRecorder with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteConfigurationRecorder 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 *ConfigService) DeleteConfigurationRecorderWithContext(ctx aws.Context, input *DeleteConfigurationRecorderInput, opts ...request.Option) (*DeleteConfigurationRecorderOutput, error) { + req, out := c.DeleteConfigurationRecorderRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteDeliveryChannel = "DeleteDeliveryChannel" @@ -237,8 +267,23 @@ func (c *ConfigService) DeleteDeliveryChannelRequest(input *DeleteDeliveryChanne // Please also see https://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/DeleteDeliveryChannel func (c *ConfigService) DeleteDeliveryChannel(input *DeleteDeliveryChannelInput) (*DeleteDeliveryChannelOutput, error) { req, out := c.DeleteDeliveryChannelRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteDeliveryChannelWithContext is the same as DeleteDeliveryChannel with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteDeliveryChannel 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 *ConfigService) DeleteDeliveryChannelWithContext(ctx aws.Context, input *DeleteDeliveryChannelInput, opts ...request.Option) (*DeleteDeliveryChannelOutput, error) { + req, out := c.DeleteDeliveryChannelRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteEvaluationResults = "DeleteEvaluationResults" @@ -310,8 +355,23 @@ func (c *ConfigService) DeleteEvaluationResultsRequest(input *DeleteEvaluationRe // Please also see https://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/DeleteEvaluationResults func (c *ConfigService) DeleteEvaluationResults(input *DeleteEvaluationResultsInput) (*DeleteEvaluationResultsOutput, error) { req, out := c.DeleteEvaluationResultsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteEvaluationResultsWithContext is the same as DeleteEvaluationResults with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteEvaluationResults 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 *ConfigService) DeleteEvaluationResultsWithContext(ctx aws.Context, input *DeleteEvaluationResultsInput, opts ...request.Option) (*DeleteEvaluationResultsOutput, error) { + req, out := c.DeleteEvaluationResultsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeliverConfigSnapshot = "DeliverConfigSnapshot" @@ -391,8 +451,23 @@ func (c *ConfigService) DeliverConfigSnapshotRequest(input *DeliverConfigSnapsho // Please also see https://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/DeliverConfigSnapshot func (c *ConfigService) DeliverConfigSnapshot(input *DeliverConfigSnapshotInput) (*DeliverConfigSnapshotOutput, error) { req, out := c.DeliverConfigSnapshotRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeliverConfigSnapshotWithContext is the same as DeliverConfigSnapshot with the addition of +// the ability to pass a context and additional request options. +// +// See DeliverConfigSnapshot 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 *ConfigService) DeliverConfigSnapshotWithContext(ctx aws.Context, input *DeliverConfigSnapshotInput, opts ...request.Option) (*DeliverConfigSnapshotOutput, error) { + req, out := c.DeliverConfigSnapshotRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeComplianceByConfigRule = "DescribeComplianceByConfigRule" @@ -487,8 +562,23 @@ func (c *ConfigService) DescribeComplianceByConfigRuleRequest(input *DescribeCom // Please also see https://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/DescribeComplianceByConfigRule func (c *ConfigService) DescribeComplianceByConfigRule(input *DescribeComplianceByConfigRuleInput) (*DescribeComplianceByConfigRuleOutput, error) { req, out := c.DescribeComplianceByConfigRuleRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeComplianceByConfigRuleWithContext is the same as DescribeComplianceByConfigRule with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeComplianceByConfigRule 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 *ConfigService) DescribeComplianceByConfigRuleWithContext(ctx aws.Context, input *DescribeComplianceByConfigRuleInput, opts ...request.Option) (*DescribeComplianceByConfigRuleOutput, error) { + req, out := c.DescribeComplianceByConfigRuleRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeComplianceByResource = "DescribeComplianceByResource" @@ -581,8 +671,23 @@ func (c *ConfigService) DescribeComplianceByResourceRequest(input *DescribeCompl // Please also see https://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/DescribeComplianceByResource func (c *ConfigService) DescribeComplianceByResource(input *DescribeComplianceByResourceInput) (*DescribeComplianceByResourceOutput, error) { req, out := c.DescribeComplianceByResourceRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeComplianceByResourceWithContext is the same as DescribeComplianceByResource with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeComplianceByResource 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 *ConfigService) DescribeComplianceByResourceWithContext(ctx aws.Context, input *DescribeComplianceByResourceInput, opts ...request.Option) (*DescribeComplianceByResourceOutput, error) { + req, out := c.DescribeComplianceByResourceRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeConfigRuleEvaluationStatus = "DescribeConfigRuleEvaluationStatus" @@ -658,8 +763,23 @@ func (c *ConfigService) DescribeConfigRuleEvaluationStatusRequest(input *Describ // Please also see https://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/DescribeConfigRuleEvaluationStatus func (c *ConfigService) DescribeConfigRuleEvaluationStatus(input *DescribeConfigRuleEvaluationStatusInput) (*DescribeConfigRuleEvaluationStatusOutput, error) { req, out := c.DescribeConfigRuleEvaluationStatusRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeConfigRuleEvaluationStatusWithContext is the same as DescribeConfigRuleEvaluationStatus with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeConfigRuleEvaluationStatus 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 *ConfigService) DescribeConfigRuleEvaluationStatusWithContext(ctx aws.Context, input *DescribeConfigRuleEvaluationStatusInput, opts ...request.Option) (*DescribeConfigRuleEvaluationStatusOutput, error) { + req, out := c.DescribeConfigRuleEvaluationStatusRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeConfigRules = "DescribeConfigRules" @@ -728,8 +848,23 @@ func (c *ConfigService) DescribeConfigRulesRequest(input *DescribeConfigRulesInp // Please also see https://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/DescribeConfigRules func (c *ConfigService) DescribeConfigRules(input *DescribeConfigRulesInput) (*DescribeConfigRulesOutput, error) { req, out := c.DescribeConfigRulesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeConfigRulesWithContext is the same as DescribeConfigRules with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeConfigRules 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 *ConfigService) DescribeConfigRulesWithContext(ctx aws.Context, input *DescribeConfigRulesInput, opts ...request.Option) (*DescribeConfigRulesOutput, error) { + req, out := c.DescribeConfigRulesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeConfigurationRecorderStatus = "DescribeConfigurationRecorderStatus" @@ -798,8 +933,23 @@ func (c *ConfigService) DescribeConfigurationRecorderStatusRequest(input *Descri // Please also see https://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/DescribeConfigurationRecorderStatus func (c *ConfigService) DescribeConfigurationRecorderStatus(input *DescribeConfigurationRecorderStatusInput) (*DescribeConfigurationRecorderStatusOutput, error) { req, out := c.DescribeConfigurationRecorderStatusRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeConfigurationRecorderStatusWithContext is the same as DescribeConfigurationRecorderStatus with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeConfigurationRecorderStatus 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 *ConfigService) DescribeConfigurationRecorderStatusWithContext(ctx aws.Context, input *DescribeConfigurationRecorderStatusInput, opts ...request.Option) (*DescribeConfigurationRecorderStatusOutput, error) { + req, out := c.DescribeConfigurationRecorderStatusRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeConfigurationRecorders = "DescribeConfigurationRecorders" @@ -868,8 +1018,23 @@ func (c *ConfigService) DescribeConfigurationRecordersRequest(input *DescribeCon // Please also see https://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/DescribeConfigurationRecorders func (c *ConfigService) DescribeConfigurationRecorders(input *DescribeConfigurationRecordersInput) (*DescribeConfigurationRecordersOutput, error) { req, out := c.DescribeConfigurationRecordersRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeConfigurationRecordersWithContext is the same as DescribeConfigurationRecorders with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeConfigurationRecorders 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 *ConfigService) DescribeConfigurationRecordersWithContext(ctx aws.Context, input *DescribeConfigurationRecordersInput, opts ...request.Option) (*DescribeConfigurationRecordersOutput, error) { + req, out := c.DescribeConfigurationRecordersRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeDeliveryChannelStatus = "DescribeDeliveryChannelStatus" @@ -937,8 +1102,23 @@ func (c *ConfigService) DescribeDeliveryChannelStatusRequest(input *DescribeDeli // Please also see https://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/DescribeDeliveryChannelStatus func (c *ConfigService) DescribeDeliveryChannelStatus(input *DescribeDeliveryChannelStatusInput) (*DescribeDeliveryChannelStatusOutput, error) { req, out := c.DescribeDeliveryChannelStatusRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeDeliveryChannelStatusWithContext is the same as DescribeDeliveryChannelStatus with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeDeliveryChannelStatus 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 *ConfigService) DescribeDeliveryChannelStatusWithContext(ctx aws.Context, input *DescribeDeliveryChannelStatusInput, opts ...request.Option) (*DescribeDeliveryChannelStatusOutput, error) { + req, out := c.DescribeDeliveryChannelStatusRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeDeliveryChannels = "DescribeDeliveryChannels" @@ -1006,8 +1186,23 @@ func (c *ConfigService) DescribeDeliveryChannelsRequest(input *DescribeDeliveryC // Please also see https://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/DescribeDeliveryChannels func (c *ConfigService) DescribeDeliveryChannels(input *DescribeDeliveryChannelsInput) (*DescribeDeliveryChannelsOutput, error) { req, out := c.DescribeDeliveryChannelsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeDeliveryChannelsWithContext is the same as DescribeDeliveryChannels with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeDeliveryChannels 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 *ConfigService) DescribeDeliveryChannelsWithContext(ctx aws.Context, input *DescribeDeliveryChannelsInput, opts ...request.Option) (*DescribeDeliveryChannelsOutput, error) { + req, out := c.DescribeDeliveryChannelsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetComplianceDetailsByConfigRule = "GetComplianceDetailsByConfigRule" @@ -1082,8 +1277,23 @@ func (c *ConfigService) GetComplianceDetailsByConfigRuleRequest(input *GetCompli // Please also see https://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/GetComplianceDetailsByConfigRule func (c *ConfigService) GetComplianceDetailsByConfigRule(input *GetComplianceDetailsByConfigRuleInput) (*GetComplianceDetailsByConfigRuleOutput, error) { req, out := c.GetComplianceDetailsByConfigRuleRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetComplianceDetailsByConfigRuleWithContext is the same as GetComplianceDetailsByConfigRule with the addition of +// the ability to pass a context and additional request options. +// +// See GetComplianceDetailsByConfigRule 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 *ConfigService) GetComplianceDetailsByConfigRuleWithContext(ctx aws.Context, input *GetComplianceDetailsByConfigRuleInput, opts ...request.Option) (*GetComplianceDetailsByConfigRuleOutput, error) { + req, out := c.GetComplianceDetailsByConfigRuleRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetComplianceDetailsByResource = "GetComplianceDetailsByResource" @@ -1150,8 +1360,23 @@ func (c *ConfigService) GetComplianceDetailsByResourceRequest(input *GetComplian // Please also see https://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/GetComplianceDetailsByResource func (c *ConfigService) GetComplianceDetailsByResource(input *GetComplianceDetailsByResourceInput) (*GetComplianceDetailsByResourceOutput, error) { req, out := c.GetComplianceDetailsByResourceRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetComplianceDetailsByResourceWithContext is the same as GetComplianceDetailsByResource with the addition of +// the ability to pass a context and additional request options. +// +// See GetComplianceDetailsByResource 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 *ConfigService) GetComplianceDetailsByResourceWithContext(ctx aws.Context, input *GetComplianceDetailsByResourceInput, opts ...request.Option) (*GetComplianceDetailsByResourceOutput, error) { + req, out := c.GetComplianceDetailsByResourceRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetComplianceSummaryByConfigRule = "GetComplianceSummaryByConfigRule" @@ -1211,8 +1436,23 @@ func (c *ConfigService) GetComplianceSummaryByConfigRuleRequest(input *GetCompli // Please also see https://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/GetComplianceSummaryByConfigRule func (c *ConfigService) GetComplianceSummaryByConfigRule(input *GetComplianceSummaryByConfigRuleInput) (*GetComplianceSummaryByConfigRuleOutput, error) { req, out := c.GetComplianceSummaryByConfigRuleRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetComplianceSummaryByConfigRuleWithContext is the same as GetComplianceSummaryByConfigRule with the addition of +// the ability to pass a context and additional request options. +// +// See GetComplianceSummaryByConfigRule 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 *ConfigService) GetComplianceSummaryByConfigRuleWithContext(ctx aws.Context, input *GetComplianceSummaryByConfigRuleInput, opts ...request.Option) (*GetComplianceSummaryByConfigRuleOutput, error) { + req, out := c.GetComplianceSummaryByConfigRuleRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetComplianceSummaryByResourceType = "GetComplianceSummaryByResourceType" @@ -1279,8 +1519,23 @@ func (c *ConfigService) GetComplianceSummaryByResourceTypeRequest(input *GetComp // Please also see https://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/GetComplianceSummaryByResourceType func (c *ConfigService) GetComplianceSummaryByResourceType(input *GetComplianceSummaryByResourceTypeInput) (*GetComplianceSummaryByResourceTypeOutput, error) { req, out := c.GetComplianceSummaryByResourceTypeRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetComplianceSummaryByResourceTypeWithContext is the same as GetComplianceSummaryByResourceType with the addition of +// the ability to pass a context and additional request options. +// +// See GetComplianceSummaryByResourceType 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 *ConfigService) GetComplianceSummaryByResourceTypeWithContext(ctx aws.Context, input *GetComplianceSummaryByResourceTypeInput, opts ...request.Option) (*GetComplianceSummaryByResourceTypeOutput, error) { + req, out := c.GetComplianceSummaryByResourceTypeRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetResourceConfigHistory = "GetResourceConfigHistory" @@ -1380,8 +1635,23 @@ func (c *ConfigService) GetResourceConfigHistoryRequest(input *GetResourceConfig // Please also see https://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/GetResourceConfigHistory func (c *ConfigService) GetResourceConfigHistory(input *GetResourceConfigHistoryInput) (*GetResourceConfigHistoryOutput, error) { req, out := c.GetResourceConfigHistoryRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetResourceConfigHistoryWithContext is the same as GetResourceConfigHistory with the addition of +// the ability to pass a context and additional request options. +// +// See GetResourceConfigHistory 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 *ConfigService) GetResourceConfigHistoryWithContext(ctx aws.Context, input *GetResourceConfigHistoryInput, opts ...request.Option) (*GetResourceConfigHistoryOutput, error) { + req, out := c.GetResourceConfigHistoryRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // GetResourceConfigHistoryPages iterates over the pages of a GetResourceConfigHistory operation, @@ -1401,12 +1671,37 @@ func (c *ConfigService) GetResourceConfigHistory(input *GetResourceConfigHistory // return pageNum <= 3 // }) // -func (c *ConfigService) GetResourceConfigHistoryPages(input *GetResourceConfigHistoryInput, fn func(p *GetResourceConfigHistoryOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.GetResourceConfigHistoryRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*GetResourceConfigHistoryOutput), lastPage) - }) +func (c *ConfigService) GetResourceConfigHistoryPages(input *GetResourceConfigHistoryInput, fn func(*GetResourceConfigHistoryOutput, bool) bool) error { + return c.GetResourceConfigHistoryPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// GetResourceConfigHistoryPagesWithContext same as GetResourceConfigHistoryPages 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 *ConfigService) GetResourceConfigHistoryPagesWithContext(ctx aws.Context, input *GetResourceConfigHistoryInput, fn func(*GetResourceConfigHistoryOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *GetResourceConfigHistoryInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.GetResourceConfigHistoryRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*GetResourceConfigHistoryOutput), !p.HasNextPage()) + } + return p.Err() } const opListDiscoveredResources = "ListDiscoveredResources" @@ -1494,8 +1789,23 @@ func (c *ConfigService) ListDiscoveredResourcesRequest(input *ListDiscoveredReso // Please also see https://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/ListDiscoveredResources func (c *ConfigService) ListDiscoveredResources(input *ListDiscoveredResourcesInput) (*ListDiscoveredResourcesOutput, error) { req, out := c.ListDiscoveredResourcesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListDiscoveredResourcesWithContext is the same as ListDiscoveredResources with the addition of +// the ability to pass a context and additional request options. +// +// See ListDiscoveredResources 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 *ConfigService) ListDiscoveredResourcesWithContext(ctx aws.Context, input *ListDiscoveredResourcesInput, opts ...request.Option) (*ListDiscoveredResourcesOutput, error) { + req, out := c.ListDiscoveredResourcesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opPutConfigRule = "PutConfigRule" @@ -1559,9 +1869,9 @@ func (c *ConfigService) PutConfigRuleRequest(input *PutConfigRuleInput) (req *re // the ARN for the SourceIdentifier key. This key is part of the Source object, // which is part of the ConfigRule object. // -// If you are adding a new AWS managed Config rule, specify the rule's identifier +// If you are adding an AWS managed Config rule, specify the rule's identifier // for the SourceIdentifier key. To reference AWS managed Config rule identifiers, -// see Using AWS Managed Config Rules (http://docs.aws.amazon.com/config/latest/developerguide/evaluate-config_use-managed-rules.html). +// see About AWS Managed Config Rules (http://docs.aws.amazon.com/config/latest/developerguide/evaluate-config_use-managed-rules.html). // // For any new rule that you add, specify the ConfigRuleName in the ConfigRule // object. Do not specify the ConfigRuleArn or the ConfigRuleId. These values @@ -1618,8 +1928,23 @@ func (c *ConfigService) PutConfigRuleRequest(input *PutConfigRuleInput) (req *re // Please also see https://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/PutConfigRule func (c *ConfigService) PutConfigRule(input *PutConfigRuleInput) (*PutConfigRuleOutput, error) { req, out := c.PutConfigRuleRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// PutConfigRuleWithContext is the same as PutConfigRule with the addition of +// the ability to pass a context and additional request options. +// +// See PutConfigRule 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 *ConfigService) PutConfigRuleWithContext(ctx aws.Context, input *PutConfigRuleInput, opts ...request.Option) (*PutConfigRuleOutput, error) { + req, out := c.PutConfigRuleRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opPutConfigurationRecorder = "PutConfigurationRecorder" @@ -1705,8 +2030,23 @@ func (c *ConfigService) PutConfigurationRecorderRequest(input *PutConfigurationR // Please also see https://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/PutConfigurationRecorder func (c *ConfigService) PutConfigurationRecorder(input *PutConfigurationRecorderInput) (*PutConfigurationRecorderOutput, error) { req, out := c.PutConfigurationRecorderRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// PutConfigurationRecorderWithContext is the same as PutConfigurationRecorder with the addition of +// the ability to pass a context and additional request options. +// +// See PutConfigurationRecorder 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 *ConfigService) PutConfigurationRecorderWithContext(ctx aws.Context, input *PutConfigurationRecorderInput, opts ...request.Option) (*PutConfigurationRecorderOutput, error) { + req, out := c.PutConfigurationRecorderRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opPutDeliveryChannel = "PutDeliveryChannel" @@ -1804,8 +2144,23 @@ func (c *ConfigService) PutDeliveryChannelRequest(input *PutDeliveryChannelInput // Please also see https://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/PutDeliveryChannel func (c *ConfigService) PutDeliveryChannel(input *PutDeliveryChannelInput) (*PutDeliveryChannelOutput, error) { req, out := c.PutDeliveryChannelRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// PutDeliveryChannelWithContext is the same as PutDeliveryChannel with the addition of +// the ability to pass a context and additional request options. +// +// See PutDeliveryChannel 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 *ConfigService) PutDeliveryChannelWithContext(ctx aws.Context, input *PutDeliveryChannelInput, opts ...request.Option) (*PutDeliveryChannelOutput, error) { + req, out := c.PutDeliveryChannelRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opPutEvaluations = "PutEvaluations" @@ -1879,8 +2234,23 @@ func (c *ConfigService) PutEvaluationsRequest(input *PutEvaluationsInput) (req * // Please also see https://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/PutEvaluations func (c *ConfigService) PutEvaluations(input *PutEvaluationsInput) (*PutEvaluationsOutput, error) { req, out := c.PutEvaluationsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// PutEvaluationsWithContext is the same as PutEvaluations with the addition of +// the ability to pass a context and additional request options. +// +// See PutEvaluations 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 *ConfigService) PutEvaluationsWithContext(ctx aws.Context, input *PutEvaluationsInput, opts ...request.Option) (*PutEvaluationsOutput, error) { + req, out := c.PutEvaluationsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opStartConfigRulesEvaluation = "StartConfigRulesEvaluation" @@ -1986,8 +2356,23 @@ func (c *ConfigService) StartConfigRulesEvaluationRequest(input *StartConfigRule // Please also see https://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/StartConfigRulesEvaluation func (c *ConfigService) StartConfigRulesEvaluation(input *StartConfigRulesEvaluationInput) (*StartConfigRulesEvaluationOutput, error) { req, out := c.StartConfigRulesEvaluationRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// StartConfigRulesEvaluationWithContext is the same as StartConfigRulesEvaluation with the addition of +// the ability to pass a context and additional request options. +// +// See StartConfigRulesEvaluation 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 *ConfigService) StartConfigRulesEvaluationWithContext(ctx aws.Context, input *StartConfigRulesEvaluationInput, opts ...request.Option) (*StartConfigRulesEvaluationOutput, error) { + req, out := c.StartConfigRulesEvaluationRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opStartConfigurationRecorder = "StartConfigurationRecorder" @@ -2060,8 +2445,23 @@ func (c *ConfigService) StartConfigurationRecorderRequest(input *StartConfigurat // Please also see https://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/StartConfigurationRecorder func (c *ConfigService) StartConfigurationRecorder(input *StartConfigurationRecorderInput) (*StartConfigurationRecorderOutput, error) { req, out := c.StartConfigurationRecorderRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// StartConfigurationRecorderWithContext is the same as StartConfigurationRecorder with the addition of +// the ability to pass a context and additional request options. +// +// See StartConfigurationRecorder 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 *ConfigService) StartConfigurationRecorderWithContext(ctx aws.Context, input *StartConfigurationRecorderInput, opts ...request.Option) (*StartConfigurationRecorderOutput, error) { + req, out := c.StartConfigurationRecorderRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opStopConfigurationRecorder = "StopConfigurationRecorder" @@ -2128,8 +2528,23 @@ func (c *ConfigService) StopConfigurationRecorderRequest(input *StopConfiguratio // Please also see https://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/StopConfigurationRecorder func (c *ConfigService) StopConfigurationRecorder(input *StopConfigurationRecorderInput) (*StopConfigurationRecorderOutput, error) { req, out := c.StopConfigurationRecorderRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// StopConfigurationRecorderWithContext is the same as StopConfigurationRecorder with the addition of +// the ability to pass a context and additional request options. +// +// See StopConfigurationRecorder 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 *ConfigService) StopConfigurationRecorderWithContext(ctx aws.Context, input *StopConfigurationRecorderInput, opts ...request.Option) (*StopConfigurationRecorderOutput, error) { + req, out := c.StopConfigurationRecorderRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // Indicates whether an AWS resource or AWS Config rule is compliant and provides @@ -2511,9 +2926,11 @@ type ConfigRule struct { // * You are using an AWS managed rule that is triggered at a periodic frequency. // // * Your custom rule is triggered when AWS Config delivers the configuration - // snapshot. + // snapshot. For more information, see ConfigSnapshotDeliveryProperties. // - // For more information, see ConfigSnapshotDeliveryProperties. + // By default, rules with a periodic trigger are evaluated every 24 hours. To + // change the frequency, specify a valid value for the MaximumExecutionFrequency + // parameter. MaximumExecutionFrequency *string `type:"string" enum:"MaximumExecutionFrequency"` // Defines which resources can trigger an evaluation for the rule. The scope @@ -3522,45 +3939,8 @@ func (s *DeliverConfigSnapshotOutput) SetConfigSnapshotId(v string) *DeliverConf type DeliveryChannel struct { _ struct{} `type:"structure"` - // Provides options for how often AWS Config delivers configuration snapshots - // to the Amazon S3 bucket in your delivery channel. - // - // If you want to create a rule that triggers evaluations for your resources - // when AWS Config delivers the configuration snapshot, see the following: - // - // The frequency for a rule that triggers evaluations for your resources when - // AWS Config delivers the configuration snapshot is set by one of two values, - // depending on which is less frequent: - // - // * The value for the deliveryFrequency parameter within the delivery channel - // configuration, which sets how often AWS Config delivers configuration - // snapshots. This value also sets how often AWS Config invokes evaluations - // for Config rules. - // - // * The value for the MaximumExecutionFrequency parameter, which sets the - // maximum frequency with which AWS Config invokes evaluations for the rule. - // For more information, see ConfigRule. - // - // If the deliveryFrequency value is less frequent than the MaximumExecutionFrequency - // value for a rule, AWS Config invokes the rule only as often as the deliveryFrequency - // value. - // - // For example, you want your rule to run evaluations when AWS Config delivers - // the configuration snapshot. - // - // You specify the MaximumExecutionFrequency value for Six_Hours. - // - // You then specify the delivery channel deliveryFrequency value for TwentyFour_Hours. - // - // Because the value for deliveryFrequency is less frequent than MaximumExecutionFrequency, - // AWS Config invokes evaluations for the rule every 24 hours. - // - // You should set the MaximumExecutionFrequency value to be at least as frequent - // as the deliveryFrequency value. You can view the deliveryFrequency value - // by using the DescribeDeliveryChannnels action. - // - // To update the deliveryFrequency with which AWS Config delivers your configuration - // snapshots, use the PutDeliveryChannel action. + // The options for how often AWS Config delivers configuration snapshots to + // the Amazon S3 bucket. ConfigSnapshotDeliveryProperties *ConfigSnapshotDeliveryProperties `locationName:"configSnapshotDeliveryProperties" type:"structure"` // The name of the delivery channel. By default, AWS Config assigns the name @@ -5124,20 +5504,7 @@ func (s *ListDiscoveredResourcesOutput) SetResourceIdentifiers(v []*ResourceIden type PutConfigRuleInput struct { _ struct{} `type:"structure"` - // An AWS Config rule represents an AWS Lambda function that you create for - // a custom rule or a predefined function for an AWS managed rule. The function - // evaluates configuration items to assess whether your AWS resources comply - // with your desired configurations. This function can run when AWS Config detects - // a configuration change to an AWS resource and at a periodic frequency that - // you choose (for example, every 24 hours). - // - // You can use the AWS CLI and AWS SDKs if you want to create a rule that triggers - // evaluations for your resources when AWS Config delivers the configuration - // snapshot. For more information, see ConfigSnapshotDeliveryProperties. - // - // For more information about developing and using AWS Config rules, see Evaluating - // AWS Resource Configurations with AWS Config (http://docs.aws.amazon.com/config/latest/developerguide/evaluate-config.html) - // in the AWS Config Developer Guide. + // The rule that you want to add to your account. // // ConfigRule is a required field ConfigRule *ConfigRule `type:"structure" required:"true"` @@ -5790,9 +6157,13 @@ type SourceDetail struct { // to evaluate your AWS resources. EventSource *string `type:"string" enum:"EventSource"` - // The frequency that you want AWS Config to run evaluations for a rule that - // is triggered periodically. If you specify a value for MaximumExecutionFrequency, + // The frequency that you want AWS Config to run evaluations for a custom rule + // with a periodic trigger. If you specify a value for MaximumExecutionFrequency, // then MessageType must use the ScheduledNotification value. + // + // By default, rules with a periodic trigger are evaluated every 24 hours. To + // change the frequency, specify a valid value for the MaximumExecutionFrequency + // parameter. MaximumExecutionFrequency *string `type:"string" enum:"MaximumExecutionFrequency"` // The type of notification that triggers AWS Config to run an evaluation for diff --git a/vendor/github.com/aws/aws-sdk-go/service/configservice/doc.go b/vendor/github.com/aws/aws-sdk-go/service/configservice/doc.go new file mode 100644 index 000000000..3b010512b --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/service/configservice/doc.go @@ -0,0 +1,103 @@ +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. + +// Package configservice provides the client and types for making API +// requests to AWS Config. +// +// AWS Config provides a way to keep track of the configurations of all the +// AWS resources associated with your AWS account. You can use AWS Config to +// get the current and historical configurations of each AWS resource and also +// to get information about the relationship between the resources. An AWS resource +// can be an Amazon Compute Cloud (Amazon EC2) instance, an Elastic Block Store +// (EBS) volume, an Elastic network Interface (ENI), or a security group. For +// a complete list of resources currently supported by AWS Config, see Supported +// AWS Resources (http://docs.aws.amazon.com/config/latest/developerguide/resource-config-reference.html#supported-resources). +// +// You can access and manage AWS Config through the AWS Management Console, +// the AWS Command Line Interface (AWS CLI), the AWS Config API, or the AWS +// SDKs for AWS Config +// +// This reference guide contains documentation for the AWS Config API and the +// AWS CLI commands that you can use to manage AWS Config. +// +// The AWS Config API uses the Signature Version 4 protocol for signing requests. +// For more information about how to sign a request with this protocol, see +// Signature Version 4 Signing Process (http://docs.aws.amazon.com/general/latest/gr/signature-version-4.html). +// +// For detailed information about AWS Config features and their associated actions +// or commands, as well as how to work with AWS Management Console, see What +// Is AWS Config? (http://docs.aws.amazon.com/config/latest/developerguide/WhatIsConfig.html) +// in the AWS Config Developer Guide. +// +// See https://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12 for more information on this service. +// +// See configservice package documentation for more information. +// https://docs.aws.amazon.com/sdk-for-go/api/service/configservice/ +// +// Using the Client +// +// To use the client for AWS Config you will first need +// to create a new instance of it. +// +// When creating a client for an AWS service you'll first need to have a Session +// already created. The Session provides configuration that can be shared +// between multiple service clients. Additional configuration can be applied to +// the Session and service's client when they are constructed. The aws package's +// Config type contains several fields such as Region for the AWS Region the +// client should make API requests too. The optional Config value can be provided +// as the variadic argument for Sessions and client creation. +// +// Once the service's client is created you can use it to make API requests the +// AWS service. These clients are safe to use concurrently. +// +// // Create a session to share configuration, and load external configuration. +// sess := session.Must(session.NewSession()) +// +// // Create the service's client with the session. +// svc := configservice.New(sess) +// +// See the SDK's documentation for more information on how to use service clients. +// https://docs.aws.amazon.com/sdk-for-go/api/ +// +// See aws package's Config type for more information on configuration options. +// https://docs.aws.amazon.com/sdk-for-go/api/aws/#Config +// +// See the AWS Config client ConfigService for more +// information on creating the service's client. +// https://docs.aws.amazon.com/sdk-for-go/api/service/configservice/#New +// +// Once the client is created you can make an API request to the service. +// Each API method takes a input parameter, and returns the service response +// and an error. +// +// The API method will document which error codes the service can be returned +// by the operation if the service models the API operation's errors. These +// errors will also be available as const strings prefixed with "ErrCode". +// +// result, err := svc.DeleteConfigRule(params) +// if err != nil { +// // Cast err to awserr.Error to handle specific error codes. +// aerr, ok := err.(awserr.Error) +// if ok && aerr.Code() == { +// // Specific error code handling +// } +// return err +// } +// +// fmt.Println("DeleteConfigRule result:") +// fmt.Println(result) +// +// Using the Client with Context +// +// The service's client also provides methods to make API requests with a Context +// value. This allows you to control the timeout, and cancellation of pending +// requests. These methods also take request Option as variadic parameter to apply +// additional configuration to the API request. +// +// ctx := context.Background() +// +// result, err := svc.DeleteConfigRuleWithContext(ctx, params) +// +// See the request package documentation for more information on using Context pattern +// with the SDK. +// https://docs.aws.amazon.com/sdk-for-go/api/aws/request/ +package configservice diff --git a/vendor/github.com/aws/aws-sdk-go/service/configservice/errors.go b/vendor/github.com/aws/aws-sdk-go/service/configservice/errors.go index abe7294e3..cc1554087 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/configservice/errors.go +++ b/vendor/github.com/aws/aws-sdk-go/service/configservice/errors.go @@ -1,4 +1,4 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. package configservice diff --git a/vendor/github.com/aws/aws-sdk-go/service/configservice/service.go b/vendor/github.com/aws/aws-sdk-go/service/configservice/service.go index b27bfb5a5..3593126ad 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/configservice/service.go +++ b/vendor/github.com/aws/aws-sdk-go/service/configservice/service.go @@ -1,4 +1,4 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. package configservice @@ -11,33 +11,12 @@ import ( "github.com/aws/aws-sdk-go/private/protocol/jsonrpc" ) -// AWS Config provides a way to keep track of the configurations of all the -// AWS resources associated with your AWS account. You can use AWS Config to -// get the current and historical configurations of each AWS resource and also -// to get information about the relationship between the resources. An AWS resource -// can be an Amazon Compute Cloud (Amazon EC2) instance, an Elastic Block Store -// (EBS) volume, an Elastic network Interface (ENI), or a security group. For -// a complete list of resources currently supported by AWS Config, see Supported -// AWS Resources (http://docs.aws.amazon.com/config/latest/developerguide/resource-config-reference.html#supported-resources). +// ConfigService provides the API operation methods for making requests to +// AWS Config. See this package's package overview docs +// for details on the service. // -// You can access and manage AWS Config through the AWS Management Console, -// the AWS Command Line Interface (AWS CLI), the AWS Config API, or the AWS -// SDKs for AWS Config -// -// This reference guide contains documentation for the AWS Config API and the -// AWS CLI commands that you can use to manage AWS Config. -// -// The AWS Config API uses the Signature Version 4 protocol for signing requests. -// For more information about how to sign a request with this protocol, see -// Signature Version 4 Signing Process (http://docs.aws.amazon.com/general/latest/gr/signature-version-4.html). -// -// For detailed information about AWS Config features and their associated actions -// or commands, as well as how to work with AWS Management Console, see What -// Is AWS Config? (http://docs.aws.amazon.com/config/latest/developerguide/WhatIsConfig.html) -// in the AWS Config Developer Guide. -// The service client's operations are safe to be used concurrently. -// It is not safe to mutate any of the client's properties though. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12 +// ConfigService methods are safe to use concurrently. It is not safe to +// modify mutate any of the struct's properties though. type ConfigService struct { *client.Client } diff --git a/vendor/github.com/aws/aws-sdk-go/service/databasemigrationservice/api.go b/vendor/github.com/aws/aws-sdk-go/service/databasemigrationservice/api.go index 06ceb9495..a79d2915b 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/databasemigrationservice/api.go +++ b/vendor/github.com/aws/aws-sdk-go/service/databasemigrationservice/api.go @@ -1,12 +1,12 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. -// Package databasemigrationservice provides a client for AWS Database Migration Service. package databasemigrationservice import ( "fmt" "time" + "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awsutil" "github.com/aws/aws-sdk-go/aws/request" ) @@ -75,8 +75,23 @@ func (c *DatabaseMigrationService) AddTagsToResourceRequest(input *AddTagsToReso // Please also see https://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/AddTagsToResource func (c *DatabaseMigrationService) AddTagsToResource(input *AddTagsToResourceInput) (*AddTagsToResourceOutput, error) { req, out := c.AddTagsToResourceRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// AddTagsToResourceWithContext is the same as AddTagsToResource with the addition of +// the ability to pass a context and additional request options. +// +// See AddTagsToResource 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 *DatabaseMigrationService) AddTagsToResourceWithContext(ctx aws.Context, input *AddTagsToResourceInput, opts ...request.Option) (*AddTagsToResourceOutput, error) { + req, out := c.AddTagsToResourceRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateEndpoint = "CreateEndpoint" @@ -156,8 +171,23 @@ func (c *DatabaseMigrationService) CreateEndpointRequest(input *CreateEndpointIn // Please also see https://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/CreateEndpoint func (c *DatabaseMigrationService) CreateEndpoint(input *CreateEndpointInput) (*CreateEndpointOutput, error) { req, out := c.CreateEndpointRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateEndpointWithContext is the same as CreateEndpoint with the addition of +// the ability to pass a context and additional request options. +// +// See CreateEndpoint 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 *DatabaseMigrationService) CreateEndpointWithContext(ctx aws.Context, input *CreateEndpointInput, opts ...request.Option) (*CreateEndpointOutput, error) { + req, out := c.CreateEndpointRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateReplicationInstance = "CreateReplicationInstance" @@ -250,8 +280,23 @@ func (c *DatabaseMigrationService) CreateReplicationInstanceRequest(input *Creat // Please also see https://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/CreateReplicationInstance func (c *DatabaseMigrationService) CreateReplicationInstance(input *CreateReplicationInstanceInput) (*CreateReplicationInstanceOutput, error) { req, out := c.CreateReplicationInstanceRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateReplicationInstanceWithContext is the same as CreateReplicationInstance with the addition of +// the ability to pass a context and additional request options. +// +// See CreateReplicationInstance 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 *DatabaseMigrationService) CreateReplicationInstanceWithContext(ctx aws.Context, input *CreateReplicationInstanceInput, opts ...request.Option) (*CreateReplicationInstanceOutput, error) { + req, out := c.CreateReplicationInstanceRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateReplicationSubnetGroup = "CreateReplicationSubnetGroup" @@ -331,8 +376,23 @@ func (c *DatabaseMigrationService) CreateReplicationSubnetGroupRequest(input *Cr // Please also see https://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/CreateReplicationSubnetGroup func (c *DatabaseMigrationService) CreateReplicationSubnetGroup(input *CreateReplicationSubnetGroupInput) (*CreateReplicationSubnetGroupOutput, error) { req, out := c.CreateReplicationSubnetGroupRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateReplicationSubnetGroupWithContext is the same as CreateReplicationSubnetGroup with the addition of +// the ability to pass a context and additional request options. +// +// See CreateReplicationSubnetGroup 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 *DatabaseMigrationService) CreateReplicationSubnetGroupWithContext(ctx aws.Context, input *CreateReplicationSubnetGroupInput, opts ...request.Option) (*CreateReplicationSubnetGroupOutput, error) { + req, out := c.CreateReplicationSubnetGroupRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateReplicationTask = "CreateReplicationTask" @@ -409,8 +469,23 @@ func (c *DatabaseMigrationService) CreateReplicationTaskRequest(input *CreateRep // Please also see https://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/CreateReplicationTask func (c *DatabaseMigrationService) CreateReplicationTask(input *CreateReplicationTaskInput) (*CreateReplicationTaskOutput, error) { req, out := c.CreateReplicationTaskRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateReplicationTaskWithContext is the same as CreateReplicationTask with the addition of +// the ability to pass a context and additional request options. +// +// See CreateReplicationTask 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 *DatabaseMigrationService) CreateReplicationTaskWithContext(ctx aws.Context, input *CreateReplicationTaskInput, opts ...request.Option) (*CreateReplicationTaskOutput, error) { + req, out := c.CreateReplicationTaskRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteCertificate = "DeleteCertificate" @@ -478,8 +553,23 @@ func (c *DatabaseMigrationService) DeleteCertificateRequest(input *DeleteCertifi // Please also see https://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/DeleteCertificate func (c *DatabaseMigrationService) DeleteCertificate(input *DeleteCertificateInput) (*DeleteCertificateOutput, error) { req, out := c.DeleteCertificateRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteCertificateWithContext is the same as DeleteCertificate with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteCertificate 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 *DatabaseMigrationService) DeleteCertificateWithContext(ctx aws.Context, input *DeleteCertificateInput, opts ...request.Option) (*DeleteCertificateOutput, error) { + req, out := c.DeleteCertificateRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteEndpoint = "DeleteEndpoint" @@ -550,8 +640,23 @@ func (c *DatabaseMigrationService) DeleteEndpointRequest(input *DeleteEndpointIn // Please also see https://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/DeleteEndpoint func (c *DatabaseMigrationService) DeleteEndpoint(input *DeleteEndpointInput) (*DeleteEndpointOutput, error) { req, out := c.DeleteEndpointRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteEndpointWithContext is the same as DeleteEndpoint with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteEndpoint 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 *DatabaseMigrationService) DeleteEndpointWithContext(ctx aws.Context, input *DeleteEndpointInput, opts ...request.Option) (*DeleteEndpointOutput, error) { + req, out := c.DeleteEndpointRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteReplicationInstance = "DeleteReplicationInstance" @@ -622,8 +727,23 @@ func (c *DatabaseMigrationService) DeleteReplicationInstanceRequest(input *Delet // Please also see https://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/DeleteReplicationInstance func (c *DatabaseMigrationService) DeleteReplicationInstance(input *DeleteReplicationInstanceInput) (*DeleteReplicationInstanceOutput, error) { req, out := c.DeleteReplicationInstanceRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteReplicationInstanceWithContext is the same as DeleteReplicationInstance with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteReplicationInstance 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 *DatabaseMigrationService) DeleteReplicationInstanceWithContext(ctx aws.Context, input *DeleteReplicationInstanceInput, opts ...request.Option) (*DeleteReplicationInstanceOutput, error) { + req, out := c.DeleteReplicationInstanceRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteReplicationSubnetGroup = "DeleteReplicationSubnetGroup" @@ -691,8 +811,23 @@ func (c *DatabaseMigrationService) DeleteReplicationSubnetGroupRequest(input *De // Please also see https://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/DeleteReplicationSubnetGroup func (c *DatabaseMigrationService) DeleteReplicationSubnetGroup(input *DeleteReplicationSubnetGroupInput) (*DeleteReplicationSubnetGroupOutput, error) { req, out := c.DeleteReplicationSubnetGroupRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteReplicationSubnetGroupWithContext is the same as DeleteReplicationSubnetGroup with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteReplicationSubnetGroup 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 *DatabaseMigrationService) DeleteReplicationSubnetGroupWithContext(ctx aws.Context, input *DeleteReplicationSubnetGroupInput, opts ...request.Option) (*DeleteReplicationSubnetGroupOutput, error) { + req, out := c.DeleteReplicationSubnetGroupRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteReplicationTask = "DeleteReplicationTask" @@ -760,8 +895,23 @@ func (c *DatabaseMigrationService) DeleteReplicationTaskRequest(input *DeleteRep // Please also see https://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/DeleteReplicationTask func (c *DatabaseMigrationService) DeleteReplicationTask(input *DeleteReplicationTaskInput) (*DeleteReplicationTaskOutput, error) { req, out := c.DeleteReplicationTaskRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteReplicationTaskWithContext is the same as DeleteReplicationTask with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteReplicationTask 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 *DatabaseMigrationService) DeleteReplicationTaskWithContext(ctx aws.Context, input *DeleteReplicationTaskInput, opts ...request.Option) (*DeleteReplicationTaskOutput, error) { + req, out := c.DeleteReplicationTaskRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeAccountAttributes = "DescribeAccountAttributes" @@ -825,8 +975,23 @@ func (c *DatabaseMigrationService) DescribeAccountAttributesRequest(input *Descr // Please also see https://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/DescribeAccountAttributes func (c *DatabaseMigrationService) DescribeAccountAttributes(input *DescribeAccountAttributesInput) (*DescribeAccountAttributesOutput, error) { req, out := c.DescribeAccountAttributesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeAccountAttributesWithContext is the same as DescribeAccountAttributes with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeAccountAttributes 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 *DatabaseMigrationService) DescribeAccountAttributesWithContext(ctx aws.Context, input *DescribeAccountAttributesInput, opts ...request.Option) (*DescribeAccountAttributesOutput, error) { + req, out := c.DescribeAccountAttributesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeCertificates = "DescribeCertificates" @@ -890,8 +1055,23 @@ func (c *DatabaseMigrationService) DescribeCertificatesRequest(input *DescribeCe // Please also see https://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/DescribeCertificates func (c *DatabaseMigrationService) DescribeCertificates(input *DescribeCertificatesInput) (*DescribeCertificatesOutput, error) { req, out := c.DescribeCertificatesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeCertificatesWithContext is the same as DescribeCertificates with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeCertificates 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 *DatabaseMigrationService) DescribeCertificatesWithContext(ctx aws.Context, input *DescribeCertificatesInput, opts ...request.Option) (*DescribeCertificatesOutput, error) { + req, out := c.DescribeCertificatesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeConnections = "DescribeConnections" @@ -956,8 +1136,23 @@ func (c *DatabaseMigrationService) DescribeConnectionsRequest(input *DescribeCon // Please also see https://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/DescribeConnections func (c *DatabaseMigrationService) DescribeConnections(input *DescribeConnectionsInput) (*DescribeConnectionsOutput, error) { req, out := c.DescribeConnectionsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeConnectionsWithContext is the same as DescribeConnections with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeConnections 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 *DatabaseMigrationService) DescribeConnectionsWithContext(ctx aws.Context, input *DescribeConnectionsInput, opts ...request.Option) (*DescribeConnectionsOutput, error) { + req, out := c.DescribeConnectionsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeEndpointTypes = "DescribeEndpointTypes" @@ -1016,8 +1211,23 @@ func (c *DatabaseMigrationService) DescribeEndpointTypesRequest(input *DescribeE // Please also see https://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/DescribeEndpointTypes func (c *DatabaseMigrationService) DescribeEndpointTypes(input *DescribeEndpointTypesInput) (*DescribeEndpointTypesOutput, error) { req, out := c.DescribeEndpointTypesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeEndpointTypesWithContext is the same as DescribeEndpointTypes with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeEndpointTypes 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 *DatabaseMigrationService) DescribeEndpointTypesWithContext(ctx aws.Context, input *DescribeEndpointTypesInput, opts ...request.Option) (*DescribeEndpointTypesOutput, error) { + req, out := c.DescribeEndpointTypesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeEndpoints = "DescribeEndpoints" @@ -1081,8 +1291,23 @@ func (c *DatabaseMigrationService) DescribeEndpointsRequest(input *DescribeEndpo // Please also see https://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/DescribeEndpoints func (c *DatabaseMigrationService) DescribeEndpoints(input *DescribeEndpointsInput) (*DescribeEndpointsOutput, error) { req, out := c.DescribeEndpointsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeEndpointsWithContext is the same as DescribeEndpoints with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeEndpoints 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 *DatabaseMigrationService) DescribeEndpointsWithContext(ctx aws.Context, input *DescribeEndpointsInput, opts ...request.Option) (*DescribeEndpointsOutput, error) { + req, out := c.DescribeEndpointsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeOrderableReplicationInstances = "DescribeOrderableReplicationInstances" @@ -1142,8 +1367,23 @@ func (c *DatabaseMigrationService) DescribeOrderableReplicationInstancesRequest( // Please also see https://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/DescribeOrderableReplicationInstances func (c *DatabaseMigrationService) DescribeOrderableReplicationInstances(input *DescribeOrderableReplicationInstancesInput) (*DescribeOrderableReplicationInstancesOutput, error) { req, out := c.DescribeOrderableReplicationInstancesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeOrderableReplicationInstancesWithContext is the same as DescribeOrderableReplicationInstances with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeOrderableReplicationInstances 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 *DatabaseMigrationService) DescribeOrderableReplicationInstancesWithContext(ctx aws.Context, input *DescribeOrderableReplicationInstancesInput, opts ...request.Option) (*DescribeOrderableReplicationInstancesOutput, error) { + req, out := c.DescribeOrderableReplicationInstancesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeRefreshSchemasStatus = "DescribeRefreshSchemasStatus" @@ -1211,8 +1451,23 @@ func (c *DatabaseMigrationService) DescribeRefreshSchemasStatusRequest(input *De // Please also see https://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/DescribeRefreshSchemasStatus func (c *DatabaseMigrationService) DescribeRefreshSchemasStatus(input *DescribeRefreshSchemasStatusInput) (*DescribeRefreshSchemasStatusOutput, error) { req, out := c.DescribeRefreshSchemasStatusRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeRefreshSchemasStatusWithContext is the same as DescribeRefreshSchemasStatus with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeRefreshSchemasStatus 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 *DatabaseMigrationService) DescribeRefreshSchemasStatusWithContext(ctx aws.Context, input *DescribeRefreshSchemasStatusInput, opts ...request.Option) (*DescribeRefreshSchemasStatusOutput, error) { + req, out := c.DescribeRefreshSchemasStatusRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeReplicationInstances = "DescribeReplicationInstances" @@ -1277,8 +1532,23 @@ func (c *DatabaseMigrationService) DescribeReplicationInstancesRequest(input *De // Please also see https://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/DescribeReplicationInstances func (c *DatabaseMigrationService) DescribeReplicationInstances(input *DescribeReplicationInstancesInput) (*DescribeReplicationInstancesOutput, error) { req, out := c.DescribeReplicationInstancesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeReplicationInstancesWithContext is the same as DescribeReplicationInstances with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeReplicationInstances 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 *DatabaseMigrationService) DescribeReplicationInstancesWithContext(ctx aws.Context, input *DescribeReplicationInstancesInput, opts ...request.Option) (*DescribeReplicationInstancesOutput, error) { + req, out := c.DescribeReplicationInstancesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeReplicationSubnetGroups = "DescribeReplicationSubnetGroups" @@ -1342,8 +1612,23 @@ func (c *DatabaseMigrationService) DescribeReplicationSubnetGroupsRequest(input // Please also see https://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/DescribeReplicationSubnetGroups func (c *DatabaseMigrationService) DescribeReplicationSubnetGroups(input *DescribeReplicationSubnetGroupsInput) (*DescribeReplicationSubnetGroupsOutput, error) { req, out := c.DescribeReplicationSubnetGroupsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeReplicationSubnetGroupsWithContext is the same as DescribeReplicationSubnetGroups with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeReplicationSubnetGroups 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 *DatabaseMigrationService) DescribeReplicationSubnetGroupsWithContext(ctx aws.Context, input *DescribeReplicationSubnetGroupsInput, opts ...request.Option) (*DescribeReplicationSubnetGroupsOutput, error) { + req, out := c.DescribeReplicationSubnetGroupsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeReplicationTasks = "DescribeReplicationTasks" @@ -1408,8 +1693,23 @@ func (c *DatabaseMigrationService) DescribeReplicationTasksRequest(input *Descri // Please also see https://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/DescribeReplicationTasks func (c *DatabaseMigrationService) DescribeReplicationTasks(input *DescribeReplicationTasksInput) (*DescribeReplicationTasksOutput, error) { req, out := c.DescribeReplicationTasksRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeReplicationTasksWithContext is the same as DescribeReplicationTasks with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeReplicationTasks 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 *DatabaseMigrationService) DescribeReplicationTasksWithContext(ctx aws.Context, input *DescribeReplicationTasksInput, opts ...request.Option) (*DescribeReplicationTasksOutput, error) { + req, out := c.DescribeReplicationTasksRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeSchemas = "DescribeSchemas" @@ -1477,8 +1777,23 @@ func (c *DatabaseMigrationService) DescribeSchemasRequest(input *DescribeSchemas // Please also see https://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/DescribeSchemas func (c *DatabaseMigrationService) DescribeSchemas(input *DescribeSchemasInput) (*DescribeSchemasOutput, error) { req, out := c.DescribeSchemasRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeSchemasWithContext is the same as DescribeSchemas with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeSchemas 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 *DatabaseMigrationService) DescribeSchemasWithContext(ctx aws.Context, input *DescribeSchemasInput, opts ...request.Option) (*DescribeSchemasOutput, error) { + req, out := c.DescribeSchemasRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeTableStatistics = "DescribeTableStatistics" @@ -1547,8 +1862,23 @@ func (c *DatabaseMigrationService) DescribeTableStatisticsRequest(input *Describ // Please also see https://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/DescribeTableStatistics func (c *DatabaseMigrationService) DescribeTableStatistics(input *DescribeTableStatisticsInput) (*DescribeTableStatisticsOutput, error) { req, out := c.DescribeTableStatisticsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeTableStatisticsWithContext is the same as DescribeTableStatistics with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeTableStatistics 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 *DatabaseMigrationService) DescribeTableStatisticsWithContext(ctx aws.Context, input *DescribeTableStatisticsInput, opts ...request.Option) (*DescribeTableStatisticsOutput, error) { + req, out := c.DescribeTableStatisticsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opImportCertificate = "ImportCertificate" @@ -1615,8 +1945,23 @@ func (c *DatabaseMigrationService) ImportCertificateRequest(input *ImportCertifi // Please also see https://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/ImportCertificate func (c *DatabaseMigrationService) ImportCertificate(input *ImportCertificateInput) (*ImportCertificateOutput, error) { req, out := c.ImportCertificateRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ImportCertificateWithContext is the same as ImportCertificate with the addition of +// the ability to pass a context and additional request options. +// +// See ImportCertificate 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 *DatabaseMigrationService) ImportCertificateWithContext(ctx aws.Context, input *ImportCertificateInput, opts ...request.Option) (*ImportCertificateOutput, error) { + req, out := c.ImportCertificateRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opListTagsForResource = "ListTagsForResource" @@ -1680,8 +2025,23 @@ func (c *DatabaseMigrationService) ListTagsForResourceRequest(input *ListTagsFor // Please also see https://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/ListTagsForResource func (c *DatabaseMigrationService) ListTagsForResource(input *ListTagsForResourceInput) (*ListTagsForResourceOutput, error) { req, out := c.ListTagsForResourceRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListTagsForResourceWithContext is the same as ListTagsForResource with the addition of +// the ability to pass a context and additional request options. +// +// See ListTagsForResource 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 *DatabaseMigrationService) ListTagsForResourceWithContext(ctx aws.Context, input *ListTagsForResourceInput, opts ...request.Option) (*ListTagsForResourceOutput, error) { + req, out := c.ListTagsForResourceRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opModifyEndpoint = "ModifyEndpoint" @@ -1755,8 +2115,23 @@ func (c *DatabaseMigrationService) ModifyEndpointRequest(input *ModifyEndpointIn // Please also see https://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/ModifyEndpoint func (c *DatabaseMigrationService) ModifyEndpoint(input *ModifyEndpointInput) (*ModifyEndpointOutput, error) { req, out := c.ModifyEndpointRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ModifyEndpointWithContext is the same as ModifyEndpoint with the addition of +// the ability to pass a context and additional request options. +// +// See ModifyEndpoint 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 *DatabaseMigrationService) ModifyEndpointWithContext(ctx aws.Context, input *ModifyEndpointInput, opts ...request.Option) (*ModifyEndpointOutput, error) { + req, out := c.ModifyEndpointRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opModifyReplicationInstance = "ModifyReplicationInstance" @@ -1840,8 +2215,23 @@ func (c *DatabaseMigrationService) ModifyReplicationInstanceRequest(input *Modif // Please also see https://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/ModifyReplicationInstance func (c *DatabaseMigrationService) ModifyReplicationInstance(input *ModifyReplicationInstanceInput) (*ModifyReplicationInstanceOutput, error) { req, out := c.ModifyReplicationInstanceRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ModifyReplicationInstanceWithContext is the same as ModifyReplicationInstance with the addition of +// the ability to pass a context and additional request options. +// +// See ModifyReplicationInstance 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 *DatabaseMigrationService) ModifyReplicationInstanceWithContext(ctx aws.Context, input *ModifyReplicationInstanceInput, opts ...request.Option) (*ModifyReplicationInstanceOutput, error) { + req, out := c.ModifyReplicationInstanceRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opModifyReplicationSubnetGroup = "ModifyReplicationSubnetGroup" @@ -1921,8 +2311,23 @@ func (c *DatabaseMigrationService) ModifyReplicationSubnetGroupRequest(input *Mo // Please also see https://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/ModifyReplicationSubnetGroup func (c *DatabaseMigrationService) ModifyReplicationSubnetGroup(input *ModifyReplicationSubnetGroupInput) (*ModifyReplicationSubnetGroupOutput, error) { req, out := c.ModifyReplicationSubnetGroupRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ModifyReplicationSubnetGroupWithContext is the same as ModifyReplicationSubnetGroup with the addition of +// the ability to pass a context and additional request options. +// +// See ModifyReplicationSubnetGroup 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 *DatabaseMigrationService) ModifyReplicationSubnetGroupWithContext(ctx aws.Context, input *ModifyReplicationSubnetGroupInput, opts ...request.Option) (*ModifyReplicationSubnetGroupOutput, error) { + req, out := c.ModifyReplicationSubnetGroupRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opModifyReplicationTask = "ModifyReplicationTask" @@ -1999,8 +2404,23 @@ func (c *DatabaseMigrationService) ModifyReplicationTaskRequest(input *ModifyRep // Please also see https://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/ModifyReplicationTask func (c *DatabaseMigrationService) ModifyReplicationTask(input *ModifyReplicationTaskInput) (*ModifyReplicationTaskOutput, error) { req, out := c.ModifyReplicationTaskRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ModifyReplicationTaskWithContext is the same as ModifyReplicationTask with the addition of +// the ability to pass a context and additional request options. +// +// See ModifyReplicationTask 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 *DatabaseMigrationService) ModifyReplicationTaskWithContext(ctx aws.Context, input *ModifyReplicationTaskInput, opts ...request.Option) (*ModifyReplicationTaskOutput, error) { + req, out := c.ModifyReplicationTaskRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opRefreshSchemas = "RefreshSchemas" @@ -2076,8 +2496,23 @@ func (c *DatabaseMigrationService) RefreshSchemasRequest(input *RefreshSchemasIn // Please also see https://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/RefreshSchemas func (c *DatabaseMigrationService) RefreshSchemas(input *RefreshSchemasInput) (*RefreshSchemasOutput, error) { req, out := c.RefreshSchemasRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// RefreshSchemasWithContext is the same as RefreshSchemas with the addition of +// the ability to pass a context and additional request options. +// +// See RefreshSchemas 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 *DatabaseMigrationService) RefreshSchemasWithContext(ctx aws.Context, input *RefreshSchemasInput, opts ...request.Option) (*RefreshSchemasOutput, error) { + req, out := c.RefreshSchemasRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opRemoveTagsFromResource = "RemoveTagsFromResource" @@ -2141,8 +2576,23 @@ func (c *DatabaseMigrationService) RemoveTagsFromResourceRequest(input *RemoveTa // Please also see https://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/RemoveTagsFromResource func (c *DatabaseMigrationService) RemoveTagsFromResource(input *RemoveTagsFromResourceInput) (*RemoveTagsFromResourceOutput, error) { req, out := c.RemoveTagsFromResourceRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// RemoveTagsFromResourceWithContext is the same as RemoveTagsFromResource with the addition of +// the ability to pass a context and additional request options. +// +// See RemoveTagsFromResource 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 *DatabaseMigrationService) RemoveTagsFromResourceWithContext(ctx aws.Context, input *RemoveTagsFromResourceInput, opts ...request.Option) (*RemoveTagsFromResourceOutput, error) { + req, out := c.RemoveTagsFromResourceRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opStartReplicationTask = "StartReplicationTask" @@ -2210,8 +2660,23 @@ func (c *DatabaseMigrationService) StartReplicationTaskRequest(input *StartRepli // Please also see https://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/StartReplicationTask func (c *DatabaseMigrationService) StartReplicationTask(input *StartReplicationTaskInput) (*StartReplicationTaskOutput, error) { req, out := c.StartReplicationTaskRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// StartReplicationTaskWithContext is the same as StartReplicationTask with the addition of +// the ability to pass a context and additional request options. +// +// See StartReplicationTask 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 *DatabaseMigrationService) StartReplicationTaskWithContext(ctx aws.Context, input *StartReplicationTaskInput, opts ...request.Option) (*StartReplicationTaskOutput, error) { + req, out := c.StartReplicationTaskRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opStopReplicationTask = "StopReplicationTask" @@ -2279,8 +2744,23 @@ func (c *DatabaseMigrationService) StopReplicationTaskRequest(input *StopReplica // Please also see https://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/StopReplicationTask func (c *DatabaseMigrationService) StopReplicationTask(input *StopReplicationTaskInput) (*StopReplicationTaskOutput, error) { req, out := c.StopReplicationTaskRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// StopReplicationTaskWithContext is the same as StopReplicationTask with the addition of +// the ability to pass a context and additional request options. +// +// See StopReplicationTask 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 *DatabaseMigrationService) StopReplicationTaskWithContext(ctx aws.Context, input *StopReplicationTaskInput, opts ...request.Option) (*StopReplicationTaskOutput, error) { + req, out := c.StopReplicationTaskRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opTestConnection = "TestConnection" @@ -2354,8 +2834,23 @@ func (c *DatabaseMigrationService) TestConnectionRequest(input *TestConnectionIn // Please also see https://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/TestConnection func (c *DatabaseMigrationService) TestConnection(input *TestConnectionInput) (*TestConnectionOutput, error) { req, out := c.TestConnectionRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// TestConnectionWithContext is the same as TestConnection with the addition of +// the ability to pass a context and additional request options. +// +// See TestConnection 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 *DatabaseMigrationService) TestConnectionWithContext(ctx aws.Context, input *TestConnectionInput, opts ...request.Option) (*TestConnectionOutput, error) { + req, out := c.TestConnectionRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // Describes a quota for an AWS account, for example, the number of replication diff --git a/vendor/github.com/aws/aws-sdk-go/service/databasemigrationservice/doc.go b/vendor/github.com/aws/aws-sdk-go/service/databasemigrationservice/doc.go new file mode 100644 index 000000000..c0dafec86 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/service/databasemigrationservice/doc.go @@ -0,0 +1,86 @@ +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. + +// Package databasemigrationservice provides the client and types for making API +// requests to AWS Database Migration Service. +// +// AWS Database Migration Service (AWS DMS) can migrate your data to and from +// the most widely used commercial and open-source databases such as Oracle, +// PostgreSQL, Microsoft SQL Server, Amazon Redshift, MariaDB, Amazon Aurora, +// MySQL, and SAP Adaptive Server Enterprise (ASE). The service supports homogeneous +// migrations such as Oracle to Oracle, as well as heterogeneous migrations +// between different database platforms, such as Oracle to MySQL or SQL Server +// to PostgreSQL. +// +// See https://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01 for more information on this service. +// +// See databasemigrationservice package documentation for more information. +// https://docs.aws.amazon.com/sdk-for-go/api/service/databasemigrationservice/ +// +// Using the Client +// +// To use the client for AWS Database Migration Service you will first need +// to create a new instance of it. +// +// When creating a client for an AWS service you'll first need to have a Session +// already created. The Session provides configuration that can be shared +// between multiple service clients. Additional configuration can be applied to +// the Session and service's client when they are constructed. The aws package's +// Config type contains several fields such as Region for the AWS Region the +// client should make API requests too. The optional Config value can be provided +// as the variadic argument for Sessions and client creation. +// +// Once the service's client is created you can use it to make API requests the +// AWS service. These clients are safe to use concurrently. +// +// // Create a session to share configuration, and load external configuration. +// sess := session.Must(session.NewSession()) +// +// // Create the service's client with the session. +// svc := databasemigrationservice.New(sess) +// +// See the SDK's documentation for more information on how to use service clients. +// https://docs.aws.amazon.com/sdk-for-go/api/ +// +// See aws package's Config type for more information on configuration options. +// https://docs.aws.amazon.com/sdk-for-go/api/aws/#Config +// +// See the AWS Database Migration Service client DatabaseMigrationService for more +// information on creating the service's client. +// https://docs.aws.amazon.com/sdk-for-go/api/service/databasemigrationservice/#New +// +// Once the client is created you can make an API request to the service. +// Each API method takes a input parameter, and returns the service response +// and an error. +// +// The API method will document which error codes the service can be returned +// by the operation if the service models the API operation's errors. These +// errors will also be available as const strings prefixed with "ErrCode". +// +// result, err := svc.AddTagsToResource(params) +// if err != nil { +// // Cast err to awserr.Error to handle specific error codes. +// aerr, ok := err.(awserr.Error) +// if ok && aerr.Code() == { +// // Specific error code handling +// } +// return err +// } +// +// fmt.Println("AddTagsToResource result:") +// fmt.Println(result) +// +// Using the Client with Context +// +// The service's client also provides methods to make API requests with a Context +// value. This allows you to control the timeout, and cancellation of pending +// requests. These methods also take request Option as variadic parameter to apply +// additional configuration to the API request. +// +// ctx := context.Background() +// +// result, err := svc.AddTagsToResourceWithContext(ctx, params) +// +// See the request package documentation for more information on using Context pattern +// with the SDK. +// https://docs.aws.amazon.com/sdk-for-go/api/aws/request/ +package databasemigrationservice diff --git a/vendor/github.com/aws/aws-sdk-go/service/databasemigrationservice/errors.go b/vendor/github.com/aws/aws-sdk-go/service/databasemigrationservice/errors.go index 11d19d7a7..01d12048a 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/databasemigrationservice/errors.go +++ b/vendor/github.com/aws/aws-sdk-go/service/databasemigrationservice/errors.go @@ -1,4 +1,4 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. package databasemigrationservice diff --git a/vendor/github.com/aws/aws-sdk-go/service/databasemigrationservice/service.go b/vendor/github.com/aws/aws-sdk-go/service/databasemigrationservice/service.go index cbb36fd34..bf5b47613 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/databasemigrationservice/service.go +++ b/vendor/github.com/aws/aws-sdk-go/service/databasemigrationservice/service.go @@ -1,4 +1,4 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. package databasemigrationservice @@ -11,16 +11,12 @@ import ( "github.com/aws/aws-sdk-go/private/protocol/jsonrpc" ) -// AWS Database Migration Service (AWS DMS) can migrate your data to and from -// the most widely used commercial and open-source databases such as Oracle, -// PostgreSQL, Microsoft SQL Server, Amazon Redshift, MariaDB, Amazon Aurora, -// MySQL, and SAP Adaptive Server Enterprise (ASE). The service supports homogeneous -// migrations such as Oracle to Oracle, as well as heterogeneous migrations -// between different database platforms, such as Oracle to MySQL or SQL Server -// to PostgreSQL. -// The service client's operations are safe to be used concurrently. -// It is not safe to mutate any of the client's properties though. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01 +// DatabaseMigrationService provides the API operation methods for making requests to +// AWS Database Migration Service. See this package's package overview docs +// for details on the service. +// +// DatabaseMigrationService methods are safe to use concurrently. It is not safe to +// modify mutate any of the struct's properties though. type DatabaseMigrationService struct { *client.Client } diff --git a/vendor/github.com/aws/aws-sdk-go/service/devicefarm/api.go b/vendor/github.com/aws/aws-sdk-go/service/devicefarm/api.go new file mode 100644 index 000000000..7f4e61d94 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/service/devicefarm/api.go @@ -0,0 +1,13027 @@ +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. + +package devicefarm + +import ( + "time" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/awsutil" + "github.com/aws/aws-sdk-go/aws/request" +) + +const opCreateDevicePool = "CreateDevicePool" + +// CreateDevicePoolRequest generates a "aws/request.Request" representing the +// client's request for the CreateDevicePool operation. The "output" return +// value can be used to capture response data after the request's "Send" method +// is called. +// +// See CreateDevicePool for usage and error information. +// +// Creating a request object using this method should be used when you want to inject +// custom logic into the request's lifecycle using a custom handler, or if you want to +// access properties on the request object before or after sending the request. If +// you just want the service response, call the CreateDevicePool method directly +// instead. +// +// Note: You must call the "Send" method on the returned request object in order +// to execute the request. +// +// // Example sending a request using the CreateDevicePoolRequest method. +// req, resp := client.CreateDevicePoolRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/CreateDevicePool +func (c *DeviceFarm) CreateDevicePoolRequest(input *CreateDevicePoolInput) (req *request.Request, output *CreateDevicePoolOutput) { + op := &request.Operation{ + Name: opCreateDevicePool, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &CreateDevicePoolInput{} + } + + output = &CreateDevicePoolOutput{} + req = c.newRequest(op, input, output) + return +} + +// CreateDevicePool API operation for AWS Device Farm. +// +// Creates a device pool. +// +// 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 Device Farm's +// API operation CreateDevicePool for usage and error information. +// +// Returned Error Codes: +// * ErrCodeArgumentException "ArgumentException" +// An invalid argument was specified. +// +// * ErrCodeNotFoundException "NotFoundException" +// The specified entity was not found. +// +// * ErrCodeLimitExceededException "LimitExceededException" +// A limit was exceeded. +// +// * ErrCodeServiceAccountException "ServiceAccountException" +// There was a problem with the service account. +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/CreateDevicePool +func (c *DeviceFarm) CreateDevicePool(input *CreateDevicePoolInput) (*CreateDevicePoolOutput, error) { + req, out := c.CreateDevicePoolRequest(input) + return out, req.Send() +} + +// CreateDevicePoolWithContext is the same as CreateDevicePool with the addition of +// the ability to pass a context and additional request options. +// +// See CreateDevicePool 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 *DeviceFarm) CreateDevicePoolWithContext(ctx aws.Context, input *CreateDevicePoolInput, opts ...request.Option) (*CreateDevicePoolOutput, error) { + req, out := c.CreateDevicePoolRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opCreateNetworkProfile = "CreateNetworkProfile" + +// CreateNetworkProfileRequest generates a "aws/request.Request" representing the +// client's request for the CreateNetworkProfile operation. The "output" return +// value can be used to capture response data after the request's "Send" method +// is called. +// +// See CreateNetworkProfile for usage and error information. +// +// Creating a request object using this method should be used when you want to inject +// custom logic into the request's lifecycle using a custom handler, or if you want to +// access properties on the request object before or after sending the request. If +// you just want the service response, call the CreateNetworkProfile method directly +// instead. +// +// Note: You must call the "Send" method on the returned request object in order +// to execute the request. +// +// // Example sending a request using the CreateNetworkProfileRequest method. +// req, resp := client.CreateNetworkProfileRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/CreateNetworkProfile +func (c *DeviceFarm) CreateNetworkProfileRequest(input *CreateNetworkProfileInput) (req *request.Request, output *CreateNetworkProfileOutput) { + op := &request.Operation{ + Name: opCreateNetworkProfile, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &CreateNetworkProfileInput{} + } + + output = &CreateNetworkProfileOutput{} + req = c.newRequest(op, input, output) + return +} + +// CreateNetworkProfile API operation for AWS Device Farm. +// +// Creates a network profile. +// +// 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 Device Farm's +// API operation CreateNetworkProfile for usage and error information. +// +// Returned Error Codes: +// * ErrCodeArgumentException "ArgumentException" +// An invalid argument was specified. +// +// * ErrCodeNotFoundException "NotFoundException" +// The specified entity was not found. +// +// * ErrCodeLimitExceededException "LimitExceededException" +// A limit was exceeded. +// +// * ErrCodeServiceAccountException "ServiceAccountException" +// There was a problem with the service account. +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/CreateNetworkProfile +func (c *DeviceFarm) CreateNetworkProfile(input *CreateNetworkProfileInput) (*CreateNetworkProfileOutput, error) { + req, out := c.CreateNetworkProfileRequest(input) + return out, req.Send() +} + +// CreateNetworkProfileWithContext is the same as CreateNetworkProfile with the addition of +// the ability to pass a context and additional request options. +// +// See CreateNetworkProfile 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 *DeviceFarm) CreateNetworkProfileWithContext(ctx aws.Context, input *CreateNetworkProfileInput, opts ...request.Option) (*CreateNetworkProfileOutput, error) { + req, out := c.CreateNetworkProfileRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opCreateProject = "CreateProject" + +// CreateProjectRequest generates a "aws/request.Request" representing the +// client's request for the CreateProject operation. The "output" return +// value can be used to capture response data after the request's "Send" method +// is called. +// +// See CreateProject for usage and error information. +// +// Creating a request object using this method should be used when you want to inject +// custom logic into the request's lifecycle using a custom handler, or if you want to +// access properties on the request object before or after sending the request. If +// you just want the service response, call the CreateProject method directly +// instead. +// +// Note: You must call the "Send" method on the returned request object in order +// to execute the request. +// +// // Example sending a request using the CreateProjectRequest method. +// req, resp := client.CreateProjectRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/CreateProject +func (c *DeviceFarm) CreateProjectRequest(input *CreateProjectInput) (req *request.Request, output *CreateProjectOutput) { + op := &request.Operation{ + Name: opCreateProject, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &CreateProjectInput{} + } + + output = &CreateProjectOutput{} + req = c.newRequest(op, input, output) + return +} + +// CreateProject API operation for AWS Device Farm. +// +// Creates a new project. +// +// 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 Device Farm's +// API operation CreateProject for usage and error information. +// +// Returned Error Codes: +// * ErrCodeArgumentException "ArgumentException" +// An invalid argument was specified. +// +// * ErrCodeNotFoundException "NotFoundException" +// The specified entity was not found. +// +// * ErrCodeLimitExceededException "LimitExceededException" +// A limit was exceeded. +// +// * ErrCodeServiceAccountException "ServiceAccountException" +// There was a problem with the service account. +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/CreateProject +func (c *DeviceFarm) CreateProject(input *CreateProjectInput) (*CreateProjectOutput, error) { + req, out := c.CreateProjectRequest(input) + return out, req.Send() +} + +// CreateProjectWithContext is the same as CreateProject with the addition of +// the ability to pass a context and additional request options. +// +// See CreateProject 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 *DeviceFarm) CreateProjectWithContext(ctx aws.Context, input *CreateProjectInput, opts ...request.Option) (*CreateProjectOutput, error) { + req, out := c.CreateProjectRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opCreateRemoteAccessSession = "CreateRemoteAccessSession" + +// CreateRemoteAccessSessionRequest generates a "aws/request.Request" representing the +// client's request for the CreateRemoteAccessSession operation. The "output" return +// value can be used to capture response data after the request's "Send" method +// is called. +// +// See CreateRemoteAccessSession for usage and error information. +// +// Creating a request object using this method should be used when you want to inject +// custom logic into the request's lifecycle using a custom handler, or if you want to +// access properties on the request object before or after sending the request. If +// you just want the service response, call the CreateRemoteAccessSession method directly +// instead. +// +// Note: You must call the "Send" method on the returned request object in order +// to execute the request. +// +// // Example sending a request using the CreateRemoteAccessSessionRequest method. +// req, resp := client.CreateRemoteAccessSessionRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/CreateRemoteAccessSession +func (c *DeviceFarm) CreateRemoteAccessSessionRequest(input *CreateRemoteAccessSessionInput) (req *request.Request, output *CreateRemoteAccessSessionOutput) { + op := &request.Operation{ + Name: opCreateRemoteAccessSession, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &CreateRemoteAccessSessionInput{} + } + + output = &CreateRemoteAccessSessionOutput{} + req = c.newRequest(op, input, output) + return +} + +// CreateRemoteAccessSession API operation for AWS Device Farm. +// +// Specifies and starts a remote access session. +// +// 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 Device Farm's +// API operation CreateRemoteAccessSession for usage and error information. +// +// Returned Error Codes: +// * ErrCodeArgumentException "ArgumentException" +// An invalid argument was specified. +// +// * ErrCodeNotFoundException "NotFoundException" +// The specified entity was not found. +// +// * ErrCodeLimitExceededException "LimitExceededException" +// A limit was exceeded. +// +// * ErrCodeServiceAccountException "ServiceAccountException" +// There was a problem with the service account. +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/CreateRemoteAccessSession +func (c *DeviceFarm) CreateRemoteAccessSession(input *CreateRemoteAccessSessionInput) (*CreateRemoteAccessSessionOutput, error) { + req, out := c.CreateRemoteAccessSessionRequest(input) + return out, req.Send() +} + +// CreateRemoteAccessSessionWithContext is the same as CreateRemoteAccessSession with the addition of +// the ability to pass a context and additional request options. +// +// See CreateRemoteAccessSession 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 *DeviceFarm) CreateRemoteAccessSessionWithContext(ctx aws.Context, input *CreateRemoteAccessSessionInput, opts ...request.Option) (*CreateRemoteAccessSessionOutput, error) { + req, out := c.CreateRemoteAccessSessionRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opCreateUpload = "CreateUpload" + +// CreateUploadRequest generates a "aws/request.Request" representing the +// client's request for the CreateUpload operation. The "output" return +// value can be used to capture response data after the request's "Send" method +// is called. +// +// See CreateUpload for usage and error information. +// +// Creating a request object using this method should be used when you want to inject +// custom logic into the request's lifecycle using a custom handler, or if you want to +// access properties on the request object before or after sending the request. If +// you just want the service response, call the CreateUpload method directly +// instead. +// +// Note: You must call the "Send" method on the returned request object in order +// to execute the request. +// +// // Example sending a request using the CreateUploadRequest method. +// req, resp := client.CreateUploadRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/CreateUpload +func (c *DeviceFarm) CreateUploadRequest(input *CreateUploadInput) (req *request.Request, output *CreateUploadOutput) { + op := &request.Operation{ + Name: opCreateUpload, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &CreateUploadInput{} + } + + output = &CreateUploadOutput{} + req = c.newRequest(op, input, output) + return +} + +// CreateUpload API operation for AWS Device Farm. +// +// Uploads an app or test scripts. +// +// 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 Device Farm's +// API operation CreateUpload for usage and error information. +// +// Returned Error Codes: +// * ErrCodeArgumentException "ArgumentException" +// An invalid argument was specified. +// +// * ErrCodeNotFoundException "NotFoundException" +// The specified entity was not found. +// +// * ErrCodeLimitExceededException "LimitExceededException" +// A limit was exceeded. +// +// * ErrCodeServiceAccountException "ServiceAccountException" +// There was a problem with the service account. +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/CreateUpload +func (c *DeviceFarm) CreateUpload(input *CreateUploadInput) (*CreateUploadOutput, error) { + req, out := c.CreateUploadRequest(input) + return out, req.Send() +} + +// CreateUploadWithContext is the same as CreateUpload with the addition of +// the ability to pass a context and additional request options. +// +// See CreateUpload 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 *DeviceFarm) CreateUploadWithContext(ctx aws.Context, input *CreateUploadInput, opts ...request.Option) (*CreateUploadOutput, error) { + req, out := c.CreateUploadRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opDeleteDevicePool = "DeleteDevicePool" + +// DeleteDevicePoolRequest generates a "aws/request.Request" representing the +// client's request for the DeleteDevicePool operation. The "output" return +// value can be used to capture response data after the request's "Send" method +// is called. +// +// See DeleteDevicePool for usage and error information. +// +// Creating a request object using this method should be used when you want to inject +// custom logic into the request's lifecycle using a custom handler, or if you want to +// access properties on the request object before or after sending the request. If +// you just want the service response, call the DeleteDevicePool method directly +// instead. +// +// Note: You must call the "Send" method on the returned request object in order +// to execute the request. +// +// // Example sending a request using the DeleteDevicePoolRequest method. +// req, resp := client.DeleteDevicePoolRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/DeleteDevicePool +func (c *DeviceFarm) DeleteDevicePoolRequest(input *DeleteDevicePoolInput) (req *request.Request, output *DeleteDevicePoolOutput) { + op := &request.Operation{ + Name: opDeleteDevicePool, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &DeleteDevicePoolInput{} + } + + output = &DeleteDevicePoolOutput{} + req = c.newRequest(op, input, output) + return +} + +// DeleteDevicePool API operation for AWS Device Farm. +// +// Deletes a device pool given the pool ARN. Does not allow deletion of curated +// pools owned by the system. +// +// 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 Device Farm's +// API operation DeleteDevicePool for usage and error information. +// +// Returned Error Codes: +// * ErrCodeArgumentException "ArgumentException" +// An invalid argument was specified. +// +// * ErrCodeNotFoundException "NotFoundException" +// The specified entity was not found. +// +// * ErrCodeLimitExceededException "LimitExceededException" +// A limit was exceeded. +// +// * ErrCodeServiceAccountException "ServiceAccountException" +// There was a problem with the service account. +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/DeleteDevicePool +func (c *DeviceFarm) DeleteDevicePool(input *DeleteDevicePoolInput) (*DeleteDevicePoolOutput, error) { + req, out := c.DeleteDevicePoolRequest(input) + return out, req.Send() +} + +// DeleteDevicePoolWithContext is the same as DeleteDevicePool with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteDevicePool 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 *DeviceFarm) DeleteDevicePoolWithContext(ctx aws.Context, input *DeleteDevicePoolInput, opts ...request.Option) (*DeleteDevicePoolOutput, error) { + req, out := c.DeleteDevicePoolRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opDeleteNetworkProfile = "DeleteNetworkProfile" + +// DeleteNetworkProfileRequest generates a "aws/request.Request" representing the +// client's request for the DeleteNetworkProfile operation. The "output" return +// value can be used to capture response data after the request's "Send" method +// is called. +// +// See DeleteNetworkProfile for usage and error information. +// +// Creating a request object using this method should be used when you want to inject +// custom logic into the request's lifecycle using a custom handler, or if you want to +// access properties on the request object before or after sending the request. If +// you just want the service response, call the DeleteNetworkProfile method directly +// instead. +// +// Note: You must call the "Send" method on the returned request object in order +// to execute the request. +// +// // Example sending a request using the DeleteNetworkProfileRequest method. +// req, resp := client.DeleteNetworkProfileRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/DeleteNetworkProfile +func (c *DeviceFarm) DeleteNetworkProfileRequest(input *DeleteNetworkProfileInput) (req *request.Request, output *DeleteNetworkProfileOutput) { + op := &request.Operation{ + Name: opDeleteNetworkProfile, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &DeleteNetworkProfileInput{} + } + + output = &DeleteNetworkProfileOutput{} + req = c.newRequest(op, input, output) + return +} + +// DeleteNetworkProfile API operation for AWS Device Farm. +// +// Deletes a network profile. +// +// 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 Device Farm's +// API operation DeleteNetworkProfile for usage and error information. +// +// Returned Error Codes: +// * ErrCodeArgumentException "ArgumentException" +// An invalid argument was specified. +// +// * ErrCodeNotFoundException "NotFoundException" +// The specified entity was not found. +// +// * ErrCodeLimitExceededException "LimitExceededException" +// A limit was exceeded. +// +// * ErrCodeServiceAccountException "ServiceAccountException" +// There was a problem with the service account. +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/DeleteNetworkProfile +func (c *DeviceFarm) DeleteNetworkProfile(input *DeleteNetworkProfileInput) (*DeleteNetworkProfileOutput, error) { + req, out := c.DeleteNetworkProfileRequest(input) + return out, req.Send() +} + +// DeleteNetworkProfileWithContext is the same as DeleteNetworkProfile with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteNetworkProfile 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 *DeviceFarm) DeleteNetworkProfileWithContext(ctx aws.Context, input *DeleteNetworkProfileInput, opts ...request.Option) (*DeleteNetworkProfileOutput, error) { + req, out := c.DeleteNetworkProfileRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opDeleteProject = "DeleteProject" + +// DeleteProjectRequest generates a "aws/request.Request" representing the +// client's request for the DeleteProject operation. The "output" return +// value can be used to capture response data after the request's "Send" method +// is called. +// +// See DeleteProject for usage and error information. +// +// Creating a request object using this method should be used when you want to inject +// custom logic into the request's lifecycle using a custom handler, or if you want to +// access properties on the request object before or after sending the request. If +// you just want the service response, call the DeleteProject method directly +// instead. +// +// Note: You must call the "Send" method on the returned request object in order +// to execute the request. +// +// // Example sending a request using the DeleteProjectRequest method. +// req, resp := client.DeleteProjectRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/DeleteProject +func (c *DeviceFarm) DeleteProjectRequest(input *DeleteProjectInput) (req *request.Request, output *DeleteProjectOutput) { + op := &request.Operation{ + Name: opDeleteProject, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &DeleteProjectInput{} + } + + output = &DeleteProjectOutput{} + req = c.newRequest(op, input, output) + return +} + +// DeleteProject API operation for AWS Device Farm. +// +// Deletes an AWS Device Farm project, given the project ARN. +// +// Note Deleting this resource does not stop an in-progress run. +// +// 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 Device Farm's +// API operation DeleteProject for usage and error information. +// +// Returned Error Codes: +// * ErrCodeArgumentException "ArgumentException" +// An invalid argument was specified. +// +// * ErrCodeNotFoundException "NotFoundException" +// The specified entity was not found. +// +// * ErrCodeLimitExceededException "LimitExceededException" +// A limit was exceeded. +// +// * ErrCodeServiceAccountException "ServiceAccountException" +// There was a problem with the service account. +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/DeleteProject +func (c *DeviceFarm) DeleteProject(input *DeleteProjectInput) (*DeleteProjectOutput, error) { + req, out := c.DeleteProjectRequest(input) + return out, req.Send() +} + +// DeleteProjectWithContext is the same as DeleteProject with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteProject 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 *DeviceFarm) DeleteProjectWithContext(ctx aws.Context, input *DeleteProjectInput, opts ...request.Option) (*DeleteProjectOutput, error) { + req, out := c.DeleteProjectRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opDeleteRemoteAccessSession = "DeleteRemoteAccessSession" + +// DeleteRemoteAccessSessionRequest generates a "aws/request.Request" representing the +// client's request for the DeleteRemoteAccessSession operation. The "output" return +// value can be used to capture response data after the request's "Send" method +// is called. +// +// See DeleteRemoteAccessSession for usage and error information. +// +// Creating a request object using this method should be used when you want to inject +// custom logic into the request's lifecycle using a custom handler, or if you want to +// access properties on the request object before or after sending the request. If +// you just want the service response, call the DeleteRemoteAccessSession method directly +// instead. +// +// Note: You must call the "Send" method on the returned request object in order +// to execute the request. +// +// // Example sending a request using the DeleteRemoteAccessSessionRequest method. +// req, resp := client.DeleteRemoteAccessSessionRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/DeleteRemoteAccessSession +func (c *DeviceFarm) DeleteRemoteAccessSessionRequest(input *DeleteRemoteAccessSessionInput) (req *request.Request, output *DeleteRemoteAccessSessionOutput) { + op := &request.Operation{ + Name: opDeleteRemoteAccessSession, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &DeleteRemoteAccessSessionInput{} + } + + output = &DeleteRemoteAccessSessionOutput{} + req = c.newRequest(op, input, output) + return +} + +// DeleteRemoteAccessSession API operation for AWS Device Farm. +// +// Deletes a completed remote access session and its results. +// +// 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 Device Farm's +// API operation DeleteRemoteAccessSession for usage and error information. +// +// Returned Error Codes: +// * ErrCodeArgumentException "ArgumentException" +// An invalid argument was specified. +// +// * ErrCodeNotFoundException "NotFoundException" +// The specified entity was not found. +// +// * ErrCodeLimitExceededException "LimitExceededException" +// A limit was exceeded. +// +// * ErrCodeServiceAccountException "ServiceAccountException" +// There was a problem with the service account. +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/DeleteRemoteAccessSession +func (c *DeviceFarm) DeleteRemoteAccessSession(input *DeleteRemoteAccessSessionInput) (*DeleteRemoteAccessSessionOutput, error) { + req, out := c.DeleteRemoteAccessSessionRequest(input) + return out, req.Send() +} + +// DeleteRemoteAccessSessionWithContext is the same as DeleteRemoteAccessSession with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteRemoteAccessSession 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 *DeviceFarm) DeleteRemoteAccessSessionWithContext(ctx aws.Context, input *DeleteRemoteAccessSessionInput, opts ...request.Option) (*DeleteRemoteAccessSessionOutput, error) { + req, out := c.DeleteRemoteAccessSessionRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opDeleteRun = "DeleteRun" + +// DeleteRunRequest generates a "aws/request.Request" representing the +// client's request for the DeleteRun operation. The "output" return +// value can be used to capture response data after the request's "Send" method +// is called. +// +// See DeleteRun for usage and error information. +// +// Creating a request object using this method should be used when you want to inject +// custom logic into the request's lifecycle using a custom handler, or if you want to +// access properties on the request object before or after sending the request. If +// you just want the service response, call the DeleteRun method directly +// instead. +// +// Note: You must call the "Send" method on the returned request object in order +// to execute the request. +// +// // Example sending a request using the DeleteRunRequest method. +// req, resp := client.DeleteRunRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/DeleteRun +func (c *DeviceFarm) DeleteRunRequest(input *DeleteRunInput) (req *request.Request, output *DeleteRunOutput) { + op := &request.Operation{ + Name: opDeleteRun, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &DeleteRunInput{} + } + + output = &DeleteRunOutput{} + req = c.newRequest(op, input, output) + return +} + +// DeleteRun API operation for AWS Device Farm. +// +// Deletes the run, given the run ARN. +// +// Note Deleting this resource does not stop an in-progress run. +// +// 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 Device Farm's +// API operation DeleteRun for usage and error information. +// +// Returned Error Codes: +// * ErrCodeArgumentException "ArgumentException" +// An invalid argument was specified. +// +// * ErrCodeNotFoundException "NotFoundException" +// The specified entity was not found. +// +// * ErrCodeLimitExceededException "LimitExceededException" +// A limit was exceeded. +// +// * ErrCodeServiceAccountException "ServiceAccountException" +// There was a problem with the service account. +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/DeleteRun +func (c *DeviceFarm) DeleteRun(input *DeleteRunInput) (*DeleteRunOutput, error) { + req, out := c.DeleteRunRequest(input) + return out, req.Send() +} + +// DeleteRunWithContext is the same as DeleteRun with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteRun 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 *DeviceFarm) DeleteRunWithContext(ctx aws.Context, input *DeleteRunInput, opts ...request.Option) (*DeleteRunOutput, error) { + req, out := c.DeleteRunRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opDeleteUpload = "DeleteUpload" + +// DeleteUploadRequest generates a "aws/request.Request" representing the +// client's request for the DeleteUpload operation. The "output" return +// value can be used to capture response data after the request's "Send" method +// is called. +// +// See DeleteUpload for usage and error information. +// +// Creating a request object using this method should be used when you want to inject +// custom logic into the request's lifecycle using a custom handler, or if you want to +// access properties on the request object before or after sending the request. If +// you just want the service response, call the DeleteUpload method directly +// instead. +// +// Note: You must call the "Send" method on the returned request object in order +// to execute the request. +// +// // Example sending a request using the DeleteUploadRequest method. +// req, resp := client.DeleteUploadRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/DeleteUpload +func (c *DeviceFarm) DeleteUploadRequest(input *DeleteUploadInput) (req *request.Request, output *DeleteUploadOutput) { + op := &request.Operation{ + Name: opDeleteUpload, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &DeleteUploadInput{} + } + + output = &DeleteUploadOutput{} + req = c.newRequest(op, input, output) + return +} + +// DeleteUpload API operation for AWS Device Farm. +// +// Deletes an upload given the upload ARN. +// +// 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 Device Farm's +// API operation DeleteUpload for usage and error information. +// +// Returned Error Codes: +// * ErrCodeArgumentException "ArgumentException" +// An invalid argument was specified. +// +// * ErrCodeNotFoundException "NotFoundException" +// The specified entity was not found. +// +// * ErrCodeLimitExceededException "LimitExceededException" +// A limit was exceeded. +// +// * ErrCodeServiceAccountException "ServiceAccountException" +// There was a problem with the service account. +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/DeleteUpload +func (c *DeviceFarm) DeleteUpload(input *DeleteUploadInput) (*DeleteUploadOutput, error) { + req, out := c.DeleteUploadRequest(input) + return out, req.Send() +} + +// DeleteUploadWithContext is the same as DeleteUpload with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteUpload 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 *DeviceFarm) DeleteUploadWithContext(ctx aws.Context, input *DeleteUploadInput, opts ...request.Option) (*DeleteUploadOutput, error) { + req, out := c.DeleteUploadRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opGetAccountSettings = "GetAccountSettings" + +// GetAccountSettingsRequest generates a "aws/request.Request" representing the +// client's request for the GetAccountSettings operation. The "output" return +// value can be used to capture response data after the request's "Send" method +// is called. +// +// See GetAccountSettings for usage and error information. +// +// Creating a request object using this method should be used when you want to inject +// custom logic into the request's lifecycle using a custom handler, or if you want to +// access properties on the request object before or after sending the request. If +// you just want the service response, call the GetAccountSettings method directly +// instead. +// +// Note: You must call the "Send" method on the returned request object in order +// to execute the request. +// +// // Example sending a request using the GetAccountSettingsRequest method. +// req, resp := client.GetAccountSettingsRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/GetAccountSettings +func (c *DeviceFarm) GetAccountSettingsRequest(input *GetAccountSettingsInput) (req *request.Request, output *GetAccountSettingsOutput) { + op := &request.Operation{ + Name: opGetAccountSettings, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &GetAccountSettingsInput{} + } + + output = &GetAccountSettingsOutput{} + req = c.newRequest(op, input, output) + return +} + +// GetAccountSettings API operation for AWS Device Farm. +// +// Returns the number of unmetered iOS and/or unmetered Android devices that +// have been purchased by the 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 +// the error. +// +// See the AWS API reference guide for AWS Device Farm's +// API operation GetAccountSettings for usage and error information. +// +// Returned Error Codes: +// * ErrCodeArgumentException "ArgumentException" +// An invalid argument was specified. +// +// * ErrCodeNotFoundException "NotFoundException" +// The specified entity was not found. +// +// * ErrCodeLimitExceededException "LimitExceededException" +// A limit was exceeded. +// +// * ErrCodeServiceAccountException "ServiceAccountException" +// There was a problem with the service account. +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/GetAccountSettings +func (c *DeviceFarm) GetAccountSettings(input *GetAccountSettingsInput) (*GetAccountSettingsOutput, error) { + req, out := c.GetAccountSettingsRequest(input) + return out, req.Send() +} + +// GetAccountSettingsWithContext is the same as GetAccountSettings with the addition of +// the ability to pass a context and additional request options. +// +// See GetAccountSettings 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 *DeviceFarm) GetAccountSettingsWithContext(ctx aws.Context, input *GetAccountSettingsInput, opts ...request.Option) (*GetAccountSettingsOutput, error) { + req, out := c.GetAccountSettingsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opGetDevice = "GetDevice" + +// GetDeviceRequest generates a "aws/request.Request" representing the +// client's request for the GetDevice operation. The "output" return +// value can be used to capture response data after the request's "Send" method +// is called. +// +// See GetDevice for usage and error information. +// +// Creating a request object using this method should be used when you want to inject +// custom logic into the request's lifecycle using a custom handler, or if you want to +// access properties on the request object before or after sending the request. If +// you just want the service response, call the GetDevice method directly +// instead. +// +// Note: You must call the "Send" method on the returned request object in order +// to execute the request. +// +// // Example sending a request using the GetDeviceRequest method. +// req, resp := client.GetDeviceRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/GetDevice +func (c *DeviceFarm) GetDeviceRequest(input *GetDeviceInput) (req *request.Request, output *GetDeviceOutput) { + op := &request.Operation{ + Name: opGetDevice, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &GetDeviceInput{} + } + + output = &GetDeviceOutput{} + req = c.newRequest(op, input, output) + return +} + +// GetDevice API operation for AWS Device Farm. +// +// Gets information about a unique device type. +// +// 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 Device Farm's +// API operation GetDevice for usage and error information. +// +// Returned Error Codes: +// * ErrCodeArgumentException "ArgumentException" +// An invalid argument was specified. +// +// * ErrCodeNotFoundException "NotFoundException" +// The specified entity was not found. +// +// * ErrCodeLimitExceededException "LimitExceededException" +// A limit was exceeded. +// +// * ErrCodeServiceAccountException "ServiceAccountException" +// There was a problem with the service account. +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/GetDevice +func (c *DeviceFarm) GetDevice(input *GetDeviceInput) (*GetDeviceOutput, error) { + req, out := c.GetDeviceRequest(input) + return out, req.Send() +} + +// GetDeviceWithContext is the same as GetDevice with the addition of +// the ability to pass a context and additional request options. +// +// See GetDevice 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 *DeviceFarm) GetDeviceWithContext(ctx aws.Context, input *GetDeviceInput, opts ...request.Option) (*GetDeviceOutput, error) { + req, out := c.GetDeviceRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opGetDevicePool = "GetDevicePool" + +// GetDevicePoolRequest generates a "aws/request.Request" representing the +// client's request for the GetDevicePool operation. The "output" return +// value can be used to capture response data after the request's "Send" method +// is called. +// +// See GetDevicePool for usage and error information. +// +// Creating a request object using this method should be used when you want to inject +// custom logic into the request's lifecycle using a custom handler, or if you want to +// access properties on the request object before or after sending the request. If +// you just want the service response, call the GetDevicePool method directly +// instead. +// +// Note: You must call the "Send" method on the returned request object in order +// to execute the request. +// +// // Example sending a request using the GetDevicePoolRequest method. +// req, resp := client.GetDevicePoolRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/GetDevicePool +func (c *DeviceFarm) GetDevicePoolRequest(input *GetDevicePoolInput) (req *request.Request, output *GetDevicePoolOutput) { + op := &request.Operation{ + Name: opGetDevicePool, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &GetDevicePoolInput{} + } + + output = &GetDevicePoolOutput{} + req = c.newRequest(op, input, output) + return +} + +// GetDevicePool API operation for AWS Device Farm. +// +// Gets information about a device pool. +// +// 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 Device Farm's +// API operation GetDevicePool for usage and error information. +// +// Returned Error Codes: +// * ErrCodeArgumentException "ArgumentException" +// An invalid argument was specified. +// +// * ErrCodeNotFoundException "NotFoundException" +// The specified entity was not found. +// +// * ErrCodeLimitExceededException "LimitExceededException" +// A limit was exceeded. +// +// * ErrCodeServiceAccountException "ServiceAccountException" +// There was a problem with the service account. +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/GetDevicePool +func (c *DeviceFarm) GetDevicePool(input *GetDevicePoolInput) (*GetDevicePoolOutput, error) { + req, out := c.GetDevicePoolRequest(input) + return out, req.Send() +} + +// GetDevicePoolWithContext is the same as GetDevicePool with the addition of +// the ability to pass a context and additional request options. +// +// See GetDevicePool 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 *DeviceFarm) GetDevicePoolWithContext(ctx aws.Context, input *GetDevicePoolInput, opts ...request.Option) (*GetDevicePoolOutput, error) { + req, out := c.GetDevicePoolRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opGetDevicePoolCompatibility = "GetDevicePoolCompatibility" + +// GetDevicePoolCompatibilityRequest generates a "aws/request.Request" representing the +// client's request for the GetDevicePoolCompatibility operation. The "output" return +// value can be used to capture response data after the request's "Send" method +// is called. +// +// See GetDevicePoolCompatibility for usage and error information. +// +// Creating a request object using this method should be used when you want to inject +// custom logic into the request's lifecycle using a custom handler, or if you want to +// access properties on the request object before or after sending the request. If +// you just want the service response, call the GetDevicePoolCompatibility method directly +// instead. +// +// Note: You must call the "Send" method on the returned request object in order +// to execute the request. +// +// // Example sending a request using the GetDevicePoolCompatibilityRequest method. +// req, resp := client.GetDevicePoolCompatibilityRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/GetDevicePoolCompatibility +func (c *DeviceFarm) GetDevicePoolCompatibilityRequest(input *GetDevicePoolCompatibilityInput) (req *request.Request, output *GetDevicePoolCompatibilityOutput) { + op := &request.Operation{ + Name: opGetDevicePoolCompatibility, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &GetDevicePoolCompatibilityInput{} + } + + output = &GetDevicePoolCompatibilityOutput{} + req = c.newRequest(op, input, output) + return +} + +// GetDevicePoolCompatibility API operation for AWS Device Farm. +// +// Gets information about compatibility with a device pool. +// +// 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 Device Farm's +// API operation GetDevicePoolCompatibility for usage and error information. +// +// Returned Error Codes: +// * ErrCodeArgumentException "ArgumentException" +// An invalid argument was specified. +// +// * ErrCodeNotFoundException "NotFoundException" +// The specified entity was not found. +// +// * ErrCodeLimitExceededException "LimitExceededException" +// A limit was exceeded. +// +// * ErrCodeServiceAccountException "ServiceAccountException" +// There was a problem with the service account. +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/GetDevicePoolCompatibility +func (c *DeviceFarm) GetDevicePoolCompatibility(input *GetDevicePoolCompatibilityInput) (*GetDevicePoolCompatibilityOutput, error) { + req, out := c.GetDevicePoolCompatibilityRequest(input) + return out, req.Send() +} + +// GetDevicePoolCompatibilityWithContext is the same as GetDevicePoolCompatibility with the addition of +// the ability to pass a context and additional request options. +// +// See GetDevicePoolCompatibility 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 *DeviceFarm) GetDevicePoolCompatibilityWithContext(ctx aws.Context, input *GetDevicePoolCompatibilityInput, opts ...request.Option) (*GetDevicePoolCompatibilityOutput, error) { + req, out := c.GetDevicePoolCompatibilityRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opGetJob = "GetJob" + +// GetJobRequest generates a "aws/request.Request" representing the +// client's request for the GetJob operation. The "output" return +// value can be used to capture response data after the request's "Send" method +// is called. +// +// See GetJob for usage and error information. +// +// Creating a request object using this method should be used when you want to inject +// custom logic into the request's lifecycle using a custom handler, or if you want to +// access properties on the request object before or after sending the request. If +// you just want the service response, call the GetJob method directly +// instead. +// +// Note: You must call the "Send" method on the returned request object in order +// to execute the request. +// +// // Example sending a request using the GetJobRequest method. +// req, resp := client.GetJobRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/GetJob +func (c *DeviceFarm) GetJobRequest(input *GetJobInput) (req *request.Request, output *GetJobOutput) { + op := &request.Operation{ + Name: opGetJob, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &GetJobInput{} + } + + output = &GetJobOutput{} + req = c.newRequest(op, input, output) + return +} + +// GetJob API operation for AWS Device Farm. +// +// Gets information about a job. +// +// 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 Device Farm's +// API operation GetJob for usage and error information. +// +// Returned Error Codes: +// * ErrCodeArgumentException "ArgumentException" +// An invalid argument was specified. +// +// * ErrCodeNotFoundException "NotFoundException" +// The specified entity was not found. +// +// * ErrCodeLimitExceededException "LimitExceededException" +// A limit was exceeded. +// +// * ErrCodeServiceAccountException "ServiceAccountException" +// There was a problem with the service account. +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/GetJob +func (c *DeviceFarm) GetJob(input *GetJobInput) (*GetJobOutput, error) { + req, out := c.GetJobRequest(input) + return out, req.Send() +} + +// GetJobWithContext is the same as GetJob with the addition of +// the ability to pass a context and additional request options. +// +// See GetJob 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 *DeviceFarm) GetJobWithContext(ctx aws.Context, input *GetJobInput, opts ...request.Option) (*GetJobOutput, error) { + req, out := c.GetJobRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opGetNetworkProfile = "GetNetworkProfile" + +// GetNetworkProfileRequest generates a "aws/request.Request" representing the +// client's request for the GetNetworkProfile operation. The "output" return +// value can be used to capture response data after the request's "Send" method +// is called. +// +// See GetNetworkProfile for usage and error information. +// +// Creating a request object using this method should be used when you want to inject +// custom logic into the request's lifecycle using a custom handler, or if you want to +// access properties on the request object before or after sending the request. If +// you just want the service response, call the GetNetworkProfile method directly +// instead. +// +// Note: You must call the "Send" method on the returned request object in order +// to execute the request. +// +// // Example sending a request using the GetNetworkProfileRequest method. +// req, resp := client.GetNetworkProfileRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/GetNetworkProfile +func (c *DeviceFarm) GetNetworkProfileRequest(input *GetNetworkProfileInput) (req *request.Request, output *GetNetworkProfileOutput) { + op := &request.Operation{ + Name: opGetNetworkProfile, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &GetNetworkProfileInput{} + } + + output = &GetNetworkProfileOutput{} + req = c.newRequest(op, input, output) + return +} + +// GetNetworkProfile API operation for AWS Device Farm. +// +// Returns information about a network profile. +// +// 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 Device Farm's +// API operation GetNetworkProfile for usage and error information. +// +// Returned Error Codes: +// * ErrCodeArgumentException "ArgumentException" +// An invalid argument was specified. +// +// * ErrCodeNotFoundException "NotFoundException" +// The specified entity was not found. +// +// * ErrCodeLimitExceededException "LimitExceededException" +// A limit was exceeded. +// +// * ErrCodeServiceAccountException "ServiceAccountException" +// There was a problem with the service account. +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/GetNetworkProfile +func (c *DeviceFarm) GetNetworkProfile(input *GetNetworkProfileInput) (*GetNetworkProfileOutput, error) { + req, out := c.GetNetworkProfileRequest(input) + return out, req.Send() +} + +// GetNetworkProfileWithContext is the same as GetNetworkProfile with the addition of +// the ability to pass a context and additional request options. +// +// See GetNetworkProfile 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 *DeviceFarm) GetNetworkProfileWithContext(ctx aws.Context, input *GetNetworkProfileInput, opts ...request.Option) (*GetNetworkProfileOutput, error) { + req, out := c.GetNetworkProfileRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opGetOfferingStatus = "GetOfferingStatus" + +// GetOfferingStatusRequest generates a "aws/request.Request" representing the +// client's request for the GetOfferingStatus operation. The "output" return +// value can be used to capture response data after the request's "Send" method +// is called. +// +// See GetOfferingStatus for usage and error information. +// +// Creating a request object using this method should be used when you want to inject +// custom logic into the request's lifecycle using a custom handler, or if you want to +// access properties on the request object before or after sending the request. If +// you just want the service response, call the GetOfferingStatus method directly +// instead. +// +// Note: You must call the "Send" method on the returned request object in order +// to execute the request. +// +// // Example sending a request using the GetOfferingStatusRequest method. +// req, resp := client.GetOfferingStatusRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/GetOfferingStatus +func (c *DeviceFarm) GetOfferingStatusRequest(input *GetOfferingStatusInput) (req *request.Request, output *GetOfferingStatusOutput) { + op := &request.Operation{ + Name: opGetOfferingStatus, + HTTPMethod: "POST", + HTTPPath: "/", + Paginator: &request.Paginator{ + InputTokens: []string{"nextToken"}, + OutputTokens: []string{"nextToken"}, + LimitToken: "", + TruncationToken: "", + }, + } + + if input == nil { + input = &GetOfferingStatusInput{} + } + + output = &GetOfferingStatusOutput{} + req = c.newRequest(op, input, output) + return +} + +// GetOfferingStatus API operation for AWS Device Farm. +// +// Gets the current status and future status of all offerings purchased by an +// AWS account. The response indicates how many offerings are currently available +// and the offerings that will be available in the next period. The API returns +// a NotEligible error if the user is not permitted to invoke the operation. +// Please contact aws-devicefarm-support@amazon.com (mailto:aws-devicefarm-support@amazon.com) +// if you believe that you should be able to invoke this 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 +// the error. +// +// See the AWS API reference guide for AWS Device Farm's +// API operation GetOfferingStatus for usage and error information. +// +// Returned Error Codes: +// * ErrCodeArgumentException "ArgumentException" +// An invalid argument was specified. +// +// * ErrCodeNotFoundException "NotFoundException" +// The specified entity was not found. +// +// * ErrCodeNotEligibleException "NotEligibleException" +// Exception gets thrown when a user is not eligible to perform the specified +// transaction. +// +// * ErrCodeLimitExceededException "LimitExceededException" +// A limit was exceeded. +// +// * ErrCodeServiceAccountException "ServiceAccountException" +// There was a problem with the service account. +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/GetOfferingStatus +func (c *DeviceFarm) GetOfferingStatus(input *GetOfferingStatusInput) (*GetOfferingStatusOutput, error) { + req, out := c.GetOfferingStatusRequest(input) + return out, req.Send() +} + +// GetOfferingStatusWithContext is the same as GetOfferingStatus with the addition of +// the ability to pass a context and additional request options. +// +// See GetOfferingStatus 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 *DeviceFarm) GetOfferingStatusWithContext(ctx aws.Context, input *GetOfferingStatusInput, opts ...request.Option) (*GetOfferingStatusOutput, error) { + req, out := c.GetOfferingStatusRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +// GetOfferingStatusPages iterates over the pages of a GetOfferingStatus operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See GetOfferingStatus 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 GetOfferingStatus operation. +// pageNum := 0 +// err := client.GetOfferingStatusPages(params, +// func(page *GetOfferingStatusOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *DeviceFarm) GetOfferingStatusPages(input *GetOfferingStatusInput, fn func(*GetOfferingStatusOutput, bool) bool) error { + return c.GetOfferingStatusPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// GetOfferingStatusPagesWithContext same as GetOfferingStatusPages 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 *DeviceFarm) GetOfferingStatusPagesWithContext(ctx aws.Context, input *GetOfferingStatusInput, fn func(*GetOfferingStatusOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *GetOfferingStatusInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.GetOfferingStatusRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*GetOfferingStatusOutput), !p.HasNextPage()) + } + return p.Err() +} + +const opGetProject = "GetProject" + +// GetProjectRequest generates a "aws/request.Request" representing the +// client's request for the GetProject operation. The "output" return +// value can be used to capture response data after the request's "Send" method +// is called. +// +// See GetProject for usage and error information. +// +// Creating a request object using this method should be used when you want to inject +// custom logic into the request's lifecycle using a custom handler, or if you want to +// access properties on the request object before or after sending the request. If +// you just want the service response, call the GetProject method directly +// instead. +// +// Note: You must call the "Send" method on the returned request object in order +// to execute the request. +// +// // Example sending a request using the GetProjectRequest method. +// req, resp := client.GetProjectRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/GetProject +func (c *DeviceFarm) GetProjectRequest(input *GetProjectInput) (req *request.Request, output *GetProjectOutput) { + op := &request.Operation{ + Name: opGetProject, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &GetProjectInput{} + } + + output = &GetProjectOutput{} + req = c.newRequest(op, input, output) + return +} + +// GetProject API operation for AWS Device Farm. +// +// Gets information about a project. +// +// 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 Device Farm's +// API operation GetProject for usage and error information. +// +// Returned Error Codes: +// * ErrCodeArgumentException "ArgumentException" +// An invalid argument was specified. +// +// * ErrCodeNotFoundException "NotFoundException" +// The specified entity was not found. +// +// * ErrCodeLimitExceededException "LimitExceededException" +// A limit was exceeded. +// +// * ErrCodeServiceAccountException "ServiceAccountException" +// There was a problem with the service account. +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/GetProject +func (c *DeviceFarm) GetProject(input *GetProjectInput) (*GetProjectOutput, error) { + req, out := c.GetProjectRequest(input) + return out, req.Send() +} + +// GetProjectWithContext is the same as GetProject with the addition of +// the ability to pass a context and additional request options. +// +// See GetProject 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 *DeviceFarm) GetProjectWithContext(ctx aws.Context, input *GetProjectInput, opts ...request.Option) (*GetProjectOutput, error) { + req, out := c.GetProjectRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opGetRemoteAccessSession = "GetRemoteAccessSession" + +// GetRemoteAccessSessionRequest generates a "aws/request.Request" representing the +// client's request for the GetRemoteAccessSession operation. The "output" return +// value can be used to capture response data after the request's "Send" method +// is called. +// +// See GetRemoteAccessSession for usage and error information. +// +// Creating a request object using this method should be used when you want to inject +// custom logic into the request's lifecycle using a custom handler, or if you want to +// access properties on the request object before or after sending the request. If +// you just want the service response, call the GetRemoteAccessSession method directly +// instead. +// +// Note: You must call the "Send" method on the returned request object in order +// to execute the request. +// +// // Example sending a request using the GetRemoteAccessSessionRequest method. +// req, resp := client.GetRemoteAccessSessionRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/GetRemoteAccessSession +func (c *DeviceFarm) GetRemoteAccessSessionRequest(input *GetRemoteAccessSessionInput) (req *request.Request, output *GetRemoteAccessSessionOutput) { + op := &request.Operation{ + Name: opGetRemoteAccessSession, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &GetRemoteAccessSessionInput{} + } + + output = &GetRemoteAccessSessionOutput{} + req = c.newRequest(op, input, output) + return +} + +// GetRemoteAccessSession API operation for AWS Device Farm. +// +// Returns a link to a currently running remote access session. +// +// 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 Device Farm's +// API operation GetRemoteAccessSession for usage and error information. +// +// Returned Error Codes: +// * ErrCodeArgumentException "ArgumentException" +// An invalid argument was specified. +// +// * ErrCodeNotFoundException "NotFoundException" +// The specified entity was not found. +// +// * ErrCodeLimitExceededException "LimitExceededException" +// A limit was exceeded. +// +// * ErrCodeServiceAccountException "ServiceAccountException" +// There was a problem with the service account. +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/GetRemoteAccessSession +func (c *DeviceFarm) GetRemoteAccessSession(input *GetRemoteAccessSessionInput) (*GetRemoteAccessSessionOutput, error) { + req, out := c.GetRemoteAccessSessionRequest(input) + return out, req.Send() +} + +// GetRemoteAccessSessionWithContext is the same as GetRemoteAccessSession with the addition of +// the ability to pass a context and additional request options. +// +// See GetRemoteAccessSession 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 *DeviceFarm) GetRemoteAccessSessionWithContext(ctx aws.Context, input *GetRemoteAccessSessionInput, opts ...request.Option) (*GetRemoteAccessSessionOutput, error) { + req, out := c.GetRemoteAccessSessionRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opGetRun = "GetRun" + +// GetRunRequest generates a "aws/request.Request" representing the +// client's request for the GetRun operation. The "output" return +// value can be used to capture response data after the request's "Send" method +// is called. +// +// See GetRun for usage and error information. +// +// Creating a request object using this method should be used when you want to inject +// custom logic into the request's lifecycle using a custom handler, or if you want to +// access properties on the request object before or after sending the request. If +// you just want the service response, call the GetRun method directly +// instead. +// +// Note: You must call the "Send" method on the returned request object in order +// to execute the request. +// +// // Example sending a request using the GetRunRequest method. +// req, resp := client.GetRunRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/GetRun +func (c *DeviceFarm) GetRunRequest(input *GetRunInput) (req *request.Request, output *GetRunOutput) { + op := &request.Operation{ + Name: opGetRun, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &GetRunInput{} + } + + output = &GetRunOutput{} + req = c.newRequest(op, input, output) + return +} + +// GetRun API operation for AWS Device Farm. +// +// Gets information about a run. +// +// 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 Device Farm's +// API operation GetRun for usage and error information. +// +// Returned Error Codes: +// * ErrCodeArgumentException "ArgumentException" +// An invalid argument was specified. +// +// * ErrCodeNotFoundException "NotFoundException" +// The specified entity was not found. +// +// * ErrCodeLimitExceededException "LimitExceededException" +// A limit was exceeded. +// +// * ErrCodeServiceAccountException "ServiceAccountException" +// There was a problem with the service account. +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/GetRun +func (c *DeviceFarm) GetRun(input *GetRunInput) (*GetRunOutput, error) { + req, out := c.GetRunRequest(input) + return out, req.Send() +} + +// GetRunWithContext is the same as GetRun with the addition of +// the ability to pass a context and additional request options. +// +// See GetRun 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 *DeviceFarm) GetRunWithContext(ctx aws.Context, input *GetRunInput, opts ...request.Option) (*GetRunOutput, error) { + req, out := c.GetRunRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opGetSuite = "GetSuite" + +// GetSuiteRequest generates a "aws/request.Request" representing the +// client's request for the GetSuite operation. The "output" return +// value can be used to capture response data after the request's "Send" method +// is called. +// +// See GetSuite for usage and error information. +// +// Creating a request object using this method should be used when you want to inject +// custom logic into the request's lifecycle using a custom handler, or if you want to +// access properties on the request object before or after sending the request. If +// you just want the service response, call the GetSuite method directly +// instead. +// +// Note: You must call the "Send" method on the returned request object in order +// to execute the request. +// +// // Example sending a request using the GetSuiteRequest method. +// req, resp := client.GetSuiteRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/GetSuite +func (c *DeviceFarm) GetSuiteRequest(input *GetSuiteInput) (req *request.Request, output *GetSuiteOutput) { + op := &request.Operation{ + Name: opGetSuite, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &GetSuiteInput{} + } + + output = &GetSuiteOutput{} + req = c.newRequest(op, input, output) + return +} + +// GetSuite API operation for AWS Device Farm. +// +// Gets information about a suite. +// +// 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 Device Farm's +// API operation GetSuite for usage and error information. +// +// Returned Error Codes: +// * ErrCodeArgumentException "ArgumentException" +// An invalid argument was specified. +// +// * ErrCodeNotFoundException "NotFoundException" +// The specified entity was not found. +// +// * ErrCodeLimitExceededException "LimitExceededException" +// A limit was exceeded. +// +// * ErrCodeServiceAccountException "ServiceAccountException" +// There was a problem with the service account. +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/GetSuite +func (c *DeviceFarm) GetSuite(input *GetSuiteInput) (*GetSuiteOutput, error) { + req, out := c.GetSuiteRequest(input) + return out, req.Send() +} + +// GetSuiteWithContext is the same as GetSuite with the addition of +// the ability to pass a context and additional request options. +// +// See GetSuite 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 *DeviceFarm) GetSuiteWithContext(ctx aws.Context, input *GetSuiteInput, opts ...request.Option) (*GetSuiteOutput, error) { + req, out := c.GetSuiteRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opGetTest = "GetTest" + +// GetTestRequest generates a "aws/request.Request" representing the +// client's request for the GetTest operation. The "output" return +// value can be used to capture response data after the request's "Send" method +// is called. +// +// See GetTest for usage and error information. +// +// Creating a request object using this method should be used when you want to inject +// custom logic into the request's lifecycle using a custom handler, or if you want to +// access properties on the request object before or after sending the request. If +// you just want the service response, call the GetTest method directly +// instead. +// +// Note: You must call the "Send" method on the returned request object in order +// to execute the request. +// +// // Example sending a request using the GetTestRequest method. +// req, resp := client.GetTestRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/GetTest +func (c *DeviceFarm) GetTestRequest(input *GetTestInput) (req *request.Request, output *GetTestOutput) { + op := &request.Operation{ + Name: opGetTest, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &GetTestInput{} + } + + output = &GetTestOutput{} + req = c.newRequest(op, input, output) + return +} + +// GetTest API operation for AWS Device Farm. +// +// Gets information about a test. +// +// 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 Device Farm's +// API operation GetTest for usage and error information. +// +// Returned Error Codes: +// * ErrCodeArgumentException "ArgumentException" +// An invalid argument was specified. +// +// * ErrCodeNotFoundException "NotFoundException" +// The specified entity was not found. +// +// * ErrCodeLimitExceededException "LimitExceededException" +// A limit was exceeded. +// +// * ErrCodeServiceAccountException "ServiceAccountException" +// There was a problem with the service account. +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/GetTest +func (c *DeviceFarm) GetTest(input *GetTestInput) (*GetTestOutput, error) { + req, out := c.GetTestRequest(input) + return out, req.Send() +} + +// GetTestWithContext is the same as GetTest with the addition of +// the ability to pass a context and additional request options. +// +// See GetTest 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 *DeviceFarm) GetTestWithContext(ctx aws.Context, input *GetTestInput, opts ...request.Option) (*GetTestOutput, error) { + req, out := c.GetTestRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opGetUpload = "GetUpload" + +// GetUploadRequest generates a "aws/request.Request" representing the +// client's request for the GetUpload operation. The "output" return +// value can be used to capture response data after the request's "Send" method +// is called. +// +// See GetUpload for usage and error information. +// +// Creating a request object using this method should be used when you want to inject +// custom logic into the request's lifecycle using a custom handler, or if you want to +// access properties on the request object before or after sending the request. If +// you just want the service response, call the GetUpload method directly +// instead. +// +// Note: You must call the "Send" method on the returned request object in order +// to execute the request. +// +// // Example sending a request using the GetUploadRequest method. +// req, resp := client.GetUploadRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/GetUpload +func (c *DeviceFarm) GetUploadRequest(input *GetUploadInput) (req *request.Request, output *GetUploadOutput) { + op := &request.Operation{ + Name: opGetUpload, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &GetUploadInput{} + } + + output = &GetUploadOutput{} + req = c.newRequest(op, input, output) + return +} + +// GetUpload API operation for AWS Device Farm. +// +// Gets information about an upload. +// +// 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 Device Farm's +// API operation GetUpload for usage and error information. +// +// Returned Error Codes: +// * ErrCodeArgumentException "ArgumentException" +// An invalid argument was specified. +// +// * ErrCodeNotFoundException "NotFoundException" +// The specified entity was not found. +// +// * ErrCodeLimitExceededException "LimitExceededException" +// A limit was exceeded. +// +// * ErrCodeServiceAccountException "ServiceAccountException" +// There was a problem with the service account. +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/GetUpload +func (c *DeviceFarm) GetUpload(input *GetUploadInput) (*GetUploadOutput, error) { + req, out := c.GetUploadRequest(input) + return out, req.Send() +} + +// GetUploadWithContext is the same as GetUpload with the addition of +// the ability to pass a context and additional request options. +// +// See GetUpload 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 *DeviceFarm) GetUploadWithContext(ctx aws.Context, input *GetUploadInput, opts ...request.Option) (*GetUploadOutput, error) { + req, out := c.GetUploadRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opInstallToRemoteAccessSession = "InstallToRemoteAccessSession" + +// InstallToRemoteAccessSessionRequest generates a "aws/request.Request" representing the +// client's request for the InstallToRemoteAccessSession operation. The "output" return +// value can be used to capture response data after the request's "Send" method +// is called. +// +// See InstallToRemoteAccessSession for usage and error information. +// +// Creating a request object using this method should be used when you want to inject +// custom logic into the request's lifecycle using a custom handler, or if you want to +// access properties on the request object before or after sending the request. If +// you just want the service response, call the InstallToRemoteAccessSession method directly +// instead. +// +// Note: You must call the "Send" method on the returned request object in order +// to execute the request. +// +// // Example sending a request using the InstallToRemoteAccessSessionRequest method. +// req, resp := client.InstallToRemoteAccessSessionRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/InstallToRemoteAccessSession +func (c *DeviceFarm) InstallToRemoteAccessSessionRequest(input *InstallToRemoteAccessSessionInput) (req *request.Request, output *InstallToRemoteAccessSessionOutput) { + op := &request.Operation{ + Name: opInstallToRemoteAccessSession, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &InstallToRemoteAccessSessionInput{} + } + + output = &InstallToRemoteAccessSessionOutput{} + req = c.newRequest(op, input, output) + return +} + +// InstallToRemoteAccessSession API operation for AWS Device Farm. +// +// Installs an application to the device in a remote access session. For Android +// applications, the file must be in .apk format. For iOS applications, the +// file must be in .ipa format. +// +// 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 Device Farm's +// API operation InstallToRemoteAccessSession for usage and error information. +// +// Returned Error Codes: +// * ErrCodeArgumentException "ArgumentException" +// An invalid argument was specified. +// +// * ErrCodeNotFoundException "NotFoundException" +// The specified entity was not found. +// +// * ErrCodeLimitExceededException "LimitExceededException" +// A limit was exceeded. +// +// * ErrCodeServiceAccountException "ServiceAccountException" +// There was a problem with the service account. +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/InstallToRemoteAccessSession +func (c *DeviceFarm) InstallToRemoteAccessSession(input *InstallToRemoteAccessSessionInput) (*InstallToRemoteAccessSessionOutput, error) { + req, out := c.InstallToRemoteAccessSessionRequest(input) + return out, req.Send() +} + +// InstallToRemoteAccessSessionWithContext is the same as InstallToRemoteAccessSession with the addition of +// the ability to pass a context and additional request options. +// +// See InstallToRemoteAccessSession 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 *DeviceFarm) InstallToRemoteAccessSessionWithContext(ctx aws.Context, input *InstallToRemoteAccessSessionInput, opts ...request.Option) (*InstallToRemoteAccessSessionOutput, error) { + req, out := c.InstallToRemoteAccessSessionRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opListArtifacts = "ListArtifacts" + +// ListArtifactsRequest generates a "aws/request.Request" representing the +// client's request for the ListArtifacts operation. The "output" return +// value can be used to capture response data after the request's "Send" method +// is called. +// +// See ListArtifacts for usage and error information. +// +// Creating a request object using this method should be used when you want to inject +// custom logic into the request's lifecycle using a custom handler, or if you want to +// access properties on the request object before or after sending the request. If +// you just want the service response, call the ListArtifacts method directly +// instead. +// +// Note: You must call the "Send" method on the returned request object in order +// to execute the request. +// +// // Example sending a request using the ListArtifactsRequest method. +// req, resp := client.ListArtifactsRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/ListArtifacts +func (c *DeviceFarm) ListArtifactsRequest(input *ListArtifactsInput) (req *request.Request, output *ListArtifactsOutput) { + op := &request.Operation{ + Name: opListArtifacts, + HTTPMethod: "POST", + HTTPPath: "/", + Paginator: &request.Paginator{ + InputTokens: []string{"nextToken"}, + OutputTokens: []string{"nextToken"}, + LimitToken: "", + TruncationToken: "", + }, + } + + if input == nil { + input = &ListArtifactsInput{} + } + + output = &ListArtifactsOutput{} + req = c.newRequest(op, input, output) + return +} + +// ListArtifacts API operation for AWS Device Farm. +// +// Gets information about artifacts. +// +// 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 Device Farm's +// API operation ListArtifacts for usage and error information. +// +// Returned Error Codes: +// * ErrCodeArgumentException "ArgumentException" +// An invalid argument was specified. +// +// * ErrCodeNotFoundException "NotFoundException" +// The specified entity was not found. +// +// * ErrCodeLimitExceededException "LimitExceededException" +// A limit was exceeded. +// +// * ErrCodeServiceAccountException "ServiceAccountException" +// There was a problem with the service account. +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/ListArtifacts +func (c *DeviceFarm) ListArtifacts(input *ListArtifactsInput) (*ListArtifactsOutput, error) { + req, out := c.ListArtifactsRequest(input) + return out, req.Send() +} + +// ListArtifactsWithContext is the same as ListArtifacts with the addition of +// the ability to pass a context and additional request options. +// +// See ListArtifacts 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 *DeviceFarm) ListArtifactsWithContext(ctx aws.Context, input *ListArtifactsInput, opts ...request.Option) (*ListArtifactsOutput, error) { + req, out := c.ListArtifactsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +// ListArtifactsPages iterates over the pages of a ListArtifacts operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See ListArtifacts 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 ListArtifacts operation. +// pageNum := 0 +// err := client.ListArtifactsPages(params, +// func(page *ListArtifactsOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *DeviceFarm) ListArtifactsPages(input *ListArtifactsInput, fn func(*ListArtifactsOutput, bool) bool) error { + return c.ListArtifactsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListArtifactsPagesWithContext same as ListArtifactsPages 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 *DeviceFarm) ListArtifactsPagesWithContext(ctx aws.Context, input *ListArtifactsInput, fn func(*ListArtifactsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListArtifactsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListArtifactsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*ListArtifactsOutput), !p.HasNextPage()) + } + return p.Err() +} + +const opListDevicePools = "ListDevicePools" + +// ListDevicePoolsRequest generates a "aws/request.Request" representing the +// client's request for the ListDevicePools operation. The "output" return +// value can be used to capture response data after the request's "Send" method +// is called. +// +// See ListDevicePools for usage and error information. +// +// Creating a request object using this method should be used when you want to inject +// custom logic into the request's lifecycle using a custom handler, or if you want to +// access properties on the request object before or after sending the request. If +// you just want the service response, call the ListDevicePools method directly +// instead. +// +// Note: You must call the "Send" method on the returned request object in order +// to execute the request. +// +// // Example sending a request using the ListDevicePoolsRequest method. +// req, resp := client.ListDevicePoolsRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/ListDevicePools +func (c *DeviceFarm) ListDevicePoolsRequest(input *ListDevicePoolsInput) (req *request.Request, output *ListDevicePoolsOutput) { + op := &request.Operation{ + Name: opListDevicePools, + HTTPMethod: "POST", + HTTPPath: "/", + Paginator: &request.Paginator{ + InputTokens: []string{"nextToken"}, + OutputTokens: []string{"nextToken"}, + LimitToken: "", + TruncationToken: "", + }, + } + + if input == nil { + input = &ListDevicePoolsInput{} + } + + output = &ListDevicePoolsOutput{} + req = c.newRequest(op, input, output) + return +} + +// ListDevicePools API operation for AWS Device Farm. +// +// Gets information about device pools. +// +// 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 Device Farm's +// API operation ListDevicePools for usage and error information. +// +// Returned Error Codes: +// * ErrCodeArgumentException "ArgumentException" +// An invalid argument was specified. +// +// * ErrCodeNotFoundException "NotFoundException" +// The specified entity was not found. +// +// * ErrCodeLimitExceededException "LimitExceededException" +// A limit was exceeded. +// +// * ErrCodeServiceAccountException "ServiceAccountException" +// There was a problem with the service account. +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/ListDevicePools +func (c *DeviceFarm) ListDevicePools(input *ListDevicePoolsInput) (*ListDevicePoolsOutput, error) { + req, out := c.ListDevicePoolsRequest(input) + return out, req.Send() +} + +// ListDevicePoolsWithContext is the same as ListDevicePools with the addition of +// the ability to pass a context and additional request options. +// +// See ListDevicePools 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 *DeviceFarm) ListDevicePoolsWithContext(ctx aws.Context, input *ListDevicePoolsInput, opts ...request.Option) (*ListDevicePoolsOutput, error) { + req, out := c.ListDevicePoolsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +// ListDevicePoolsPages iterates over the pages of a ListDevicePools operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See ListDevicePools 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 ListDevicePools operation. +// pageNum := 0 +// err := client.ListDevicePoolsPages(params, +// func(page *ListDevicePoolsOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *DeviceFarm) ListDevicePoolsPages(input *ListDevicePoolsInput, fn func(*ListDevicePoolsOutput, bool) bool) error { + return c.ListDevicePoolsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListDevicePoolsPagesWithContext same as ListDevicePoolsPages 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 *DeviceFarm) ListDevicePoolsPagesWithContext(ctx aws.Context, input *ListDevicePoolsInput, fn func(*ListDevicePoolsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListDevicePoolsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListDevicePoolsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*ListDevicePoolsOutput), !p.HasNextPage()) + } + return p.Err() +} + +const opListDevices = "ListDevices" + +// ListDevicesRequest generates a "aws/request.Request" representing the +// client's request for the ListDevices operation. The "output" return +// value can be used to capture response data after the request's "Send" method +// is called. +// +// See ListDevices for usage and error information. +// +// Creating a request object using this method should be used when you want to inject +// custom logic into the request's lifecycle using a custom handler, or if you want to +// access properties on the request object before or after sending the request. If +// you just want the service response, call the ListDevices method directly +// instead. +// +// Note: You must call the "Send" method on the returned request object in order +// to execute the request. +// +// // Example sending a request using the ListDevicesRequest method. +// req, resp := client.ListDevicesRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/ListDevices +func (c *DeviceFarm) ListDevicesRequest(input *ListDevicesInput) (req *request.Request, output *ListDevicesOutput) { + op := &request.Operation{ + Name: opListDevices, + HTTPMethod: "POST", + HTTPPath: "/", + Paginator: &request.Paginator{ + InputTokens: []string{"nextToken"}, + OutputTokens: []string{"nextToken"}, + LimitToken: "", + TruncationToken: "", + }, + } + + if input == nil { + input = &ListDevicesInput{} + } + + output = &ListDevicesOutput{} + req = c.newRequest(op, input, output) + return +} + +// ListDevices API operation for AWS Device Farm. +// +// Gets information about unique device types. +// +// 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 Device Farm's +// API operation ListDevices for usage and error information. +// +// Returned Error Codes: +// * ErrCodeArgumentException "ArgumentException" +// An invalid argument was specified. +// +// * ErrCodeNotFoundException "NotFoundException" +// The specified entity was not found. +// +// * ErrCodeLimitExceededException "LimitExceededException" +// A limit was exceeded. +// +// * ErrCodeServiceAccountException "ServiceAccountException" +// There was a problem with the service account. +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/ListDevices +func (c *DeviceFarm) ListDevices(input *ListDevicesInput) (*ListDevicesOutput, error) { + req, out := c.ListDevicesRequest(input) + return out, req.Send() +} + +// ListDevicesWithContext is the same as ListDevices with the addition of +// the ability to pass a context and additional request options. +// +// See ListDevices 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 *DeviceFarm) ListDevicesWithContext(ctx aws.Context, input *ListDevicesInput, opts ...request.Option) (*ListDevicesOutput, error) { + req, out := c.ListDevicesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +// ListDevicesPages iterates over the pages of a ListDevices operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See ListDevices 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 ListDevices operation. +// pageNum := 0 +// err := client.ListDevicesPages(params, +// func(page *ListDevicesOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *DeviceFarm) ListDevicesPages(input *ListDevicesInput, fn func(*ListDevicesOutput, bool) bool) error { + return c.ListDevicesPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListDevicesPagesWithContext same as ListDevicesPages 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 *DeviceFarm) ListDevicesPagesWithContext(ctx aws.Context, input *ListDevicesInput, fn func(*ListDevicesOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListDevicesInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListDevicesRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*ListDevicesOutput), !p.HasNextPage()) + } + return p.Err() +} + +const opListJobs = "ListJobs" + +// ListJobsRequest generates a "aws/request.Request" representing the +// client's request for the ListJobs operation. The "output" return +// value can be used to capture response data after the request's "Send" method +// is called. +// +// See ListJobs for usage and error information. +// +// Creating a request object using this method should be used when you want to inject +// custom logic into the request's lifecycle using a custom handler, or if you want to +// access properties on the request object before or after sending the request. If +// you just want the service response, call the ListJobs method directly +// instead. +// +// Note: You must call the "Send" method on the returned request object in order +// to execute the request. +// +// // Example sending a request using the ListJobsRequest method. +// req, resp := client.ListJobsRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/ListJobs +func (c *DeviceFarm) ListJobsRequest(input *ListJobsInput) (req *request.Request, output *ListJobsOutput) { + op := &request.Operation{ + Name: opListJobs, + HTTPMethod: "POST", + HTTPPath: "/", + Paginator: &request.Paginator{ + InputTokens: []string{"nextToken"}, + OutputTokens: []string{"nextToken"}, + LimitToken: "", + TruncationToken: "", + }, + } + + if input == nil { + input = &ListJobsInput{} + } + + output = &ListJobsOutput{} + req = c.newRequest(op, input, output) + return +} + +// ListJobs API operation for AWS Device Farm. +// +// Gets information about jobs. +// +// 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 Device Farm's +// API operation ListJobs for usage and error information. +// +// Returned Error Codes: +// * ErrCodeArgumentException "ArgumentException" +// An invalid argument was specified. +// +// * ErrCodeNotFoundException "NotFoundException" +// The specified entity was not found. +// +// * ErrCodeLimitExceededException "LimitExceededException" +// A limit was exceeded. +// +// * ErrCodeServiceAccountException "ServiceAccountException" +// There was a problem with the service account. +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/ListJobs +func (c *DeviceFarm) ListJobs(input *ListJobsInput) (*ListJobsOutput, error) { + req, out := c.ListJobsRequest(input) + return out, req.Send() +} + +// ListJobsWithContext is the same as ListJobs with the addition of +// the ability to pass a context and additional request options. +// +// See ListJobs 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 *DeviceFarm) ListJobsWithContext(ctx aws.Context, input *ListJobsInput, opts ...request.Option) (*ListJobsOutput, error) { + req, out := c.ListJobsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +// ListJobsPages iterates over the pages of a ListJobs operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See ListJobs 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 ListJobs operation. +// pageNum := 0 +// err := client.ListJobsPages(params, +// func(page *ListJobsOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *DeviceFarm) ListJobsPages(input *ListJobsInput, fn func(*ListJobsOutput, bool) bool) error { + return c.ListJobsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListJobsPagesWithContext same as ListJobsPages 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 *DeviceFarm) ListJobsPagesWithContext(ctx aws.Context, input *ListJobsInput, fn func(*ListJobsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListJobsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListJobsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*ListJobsOutput), !p.HasNextPage()) + } + return p.Err() +} + +const opListNetworkProfiles = "ListNetworkProfiles" + +// ListNetworkProfilesRequest generates a "aws/request.Request" representing the +// client's request for the ListNetworkProfiles operation. The "output" return +// value can be used to capture response data after the request's "Send" method +// is called. +// +// See ListNetworkProfiles for usage and error information. +// +// Creating a request object using this method should be used when you want to inject +// custom logic into the request's lifecycle using a custom handler, or if you want to +// access properties on the request object before or after sending the request. If +// you just want the service response, call the ListNetworkProfiles method directly +// instead. +// +// Note: You must call the "Send" method on the returned request object in order +// to execute the request. +// +// // Example sending a request using the ListNetworkProfilesRequest method. +// req, resp := client.ListNetworkProfilesRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/ListNetworkProfiles +func (c *DeviceFarm) ListNetworkProfilesRequest(input *ListNetworkProfilesInput) (req *request.Request, output *ListNetworkProfilesOutput) { + op := &request.Operation{ + Name: opListNetworkProfiles, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &ListNetworkProfilesInput{} + } + + output = &ListNetworkProfilesOutput{} + req = c.newRequest(op, input, output) + return +} + +// ListNetworkProfiles API operation for AWS Device Farm. +// +// Returns the list of available network profiles. +// +// 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 Device Farm's +// API operation ListNetworkProfiles for usage and error information. +// +// Returned Error Codes: +// * ErrCodeArgumentException "ArgumentException" +// An invalid argument was specified. +// +// * ErrCodeNotFoundException "NotFoundException" +// The specified entity was not found. +// +// * ErrCodeLimitExceededException "LimitExceededException" +// A limit was exceeded. +// +// * ErrCodeServiceAccountException "ServiceAccountException" +// There was a problem with the service account. +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/ListNetworkProfiles +func (c *DeviceFarm) ListNetworkProfiles(input *ListNetworkProfilesInput) (*ListNetworkProfilesOutput, error) { + req, out := c.ListNetworkProfilesRequest(input) + return out, req.Send() +} + +// ListNetworkProfilesWithContext is the same as ListNetworkProfiles with the addition of +// the ability to pass a context and additional request options. +// +// See ListNetworkProfiles 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 *DeviceFarm) ListNetworkProfilesWithContext(ctx aws.Context, input *ListNetworkProfilesInput, opts ...request.Option) (*ListNetworkProfilesOutput, error) { + req, out := c.ListNetworkProfilesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opListOfferingPromotions = "ListOfferingPromotions" + +// ListOfferingPromotionsRequest generates a "aws/request.Request" representing the +// client's request for the ListOfferingPromotions operation. The "output" return +// value can be used to capture response data after the request's "Send" method +// is called. +// +// See ListOfferingPromotions for usage and error information. +// +// Creating a request object using this method should be used when you want to inject +// custom logic into the request's lifecycle using a custom handler, or if you want to +// access properties on the request object before or after sending the request. If +// you just want the service response, call the ListOfferingPromotions method directly +// instead. +// +// Note: You must call the "Send" method on the returned request object in order +// to execute the request. +// +// // Example sending a request using the ListOfferingPromotionsRequest method. +// req, resp := client.ListOfferingPromotionsRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/ListOfferingPromotions +func (c *DeviceFarm) ListOfferingPromotionsRequest(input *ListOfferingPromotionsInput) (req *request.Request, output *ListOfferingPromotionsOutput) { + op := &request.Operation{ + Name: opListOfferingPromotions, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &ListOfferingPromotionsInput{} + } + + output = &ListOfferingPromotionsOutput{} + req = c.newRequest(op, input, output) + return +} + +// ListOfferingPromotions API operation for AWS Device Farm. +// +// Returns a list of offering promotions. Each offering promotion record contains +// the ID and description of the promotion. The API returns a NotEligible error +// if the caller is not permitted to invoke the operation. Contact aws-devicefarm-support@amazon.com +// (mailto:aws-devicefarm-support@amazon.com) if you believe that you should +// be able to invoke this 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 +// the error. +// +// See the AWS API reference guide for AWS Device Farm's +// API operation ListOfferingPromotions for usage and error information. +// +// Returned Error Codes: +// * ErrCodeArgumentException "ArgumentException" +// An invalid argument was specified. +// +// * ErrCodeNotFoundException "NotFoundException" +// The specified entity was not found. +// +// * ErrCodeNotEligibleException "NotEligibleException" +// Exception gets thrown when a user is not eligible to perform the specified +// transaction. +// +// * ErrCodeLimitExceededException "LimitExceededException" +// A limit was exceeded. +// +// * ErrCodeServiceAccountException "ServiceAccountException" +// There was a problem with the service account. +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/ListOfferingPromotions +func (c *DeviceFarm) ListOfferingPromotions(input *ListOfferingPromotionsInput) (*ListOfferingPromotionsOutput, error) { + req, out := c.ListOfferingPromotionsRequest(input) + return out, req.Send() +} + +// ListOfferingPromotionsWithContext is the same as ListOfferingPromotions with the addition of +// the ability to pass a context and additional request options. +// +// See ListOfferingPromotions 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 *DeviceFarm) ListOfferingPromotionsWithContext(ctx aws.Context, input *ListOfferingPromotionsInput, opts ...request.Option) (*ListOfferingPromotionsOutput, error) { + req, out := c.ListOfferingPromotionsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opListOfferingTransactions = "ListOfferingTransactions" + +// ListOfferingTransactionsRequest generates a "aws/request.Request" representing the +// client's request for the ListOfferingTransactions operation. The "output" return +// value can be used to capture response data after the request's "Send" method +// is called. +// +// See ListOfferingTransactions for usage and error information. +// +// Creating a request object using this method should be used when you want to inject +// custom logic into the request's lifecycle using a custom handler, or if you want to +// access properties on the request object before or after sending the request. If +// you just want the service response, call the ListOfferingTransactions method directly +// instead. +// +// Note: You must call the "Send" method on the returned request object in order +// to execute the request. +// +// // Example sending a request using the ListOfferingTransactionsRequest method. +// req, resp := client.ListOfferingTransactionsRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/ListOfferingTransactions +func (c *DeviceFarm) ListOfferingTransactionsRequest(input *ListOfferingTransactionsInput) (req *request.Request, output *ListOfferingTransactionsOutput) { + op := &request.Operation{ + Name: opListOfferingTransactions, + HTTPMethod: "POST", + HTTPPath: "/", + Paginator: &request.Paginator{ + InputTokens: []string{"nextToken"}, + OutputTokens: []string{"nextToken"}, + LimitToken: "", + TruncationToken: "", + }, + } + + if input == nil { + input = &ListOfferingTransactionsInput{} + } + + output = &ListOfferingTransactionsOutput{} + req = c.newRequest(op, input, output) + return +} + +// ListOfferingTransactions API operation for AWS Device Farm. +// +// Returns a list of all historical purchases, renewals, and system renewal +// transactions for an AWS account. The list is paginated and ordered by a descending +// timestamp (most recent transactions are first). The API returns a NotEligible +// error if the user is not permitted to invoke the operation. Please contact +// aws-devicefarm-support@amazon.com (mailto:aws-devicefarm-support@amazon.com) +// if you believe that you should be able to invoke this 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 +// the error. +// +// See the AWS API reference guide for AWS Device Farm's +// API operation ListOfferingTransactions for usage and error information. +// +// Returned Error Codes: +// * ErrCodeArgumentException "ArgumentException" +// An invalid argument was specified. +// +// * ErrCodeNotFoundException "NotFoundException" +// The specified entity was not found. +// +// * ErrCodeNotEligibleException "NotEligibleException" +// Exception gets thrown when a user is not eligible to perform the specified +// transaction. +// +// * ErrCodeLimitExceededException "LimitExceededException" +// A limit was exceeded. +// +// * ErrCodeServiceAccountException "ServiceAccountException" +// There was a problem with the service account. +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/ListOfferingTransactions +func (c *DeviceFarm) ListOfferingTransactions(input *ListOfferingTransactionsInput) (*ListOfferingTransactionsOutput, error) { + req, out := c.ListOfferingTransactionsRequest(input) + return out, req.Send() +} + +// ListOfferingTransactionsWithContext is the same as ListOfferingTransactions with the addition of +// the ability to pass a context and additional request options. +// +// See ListOfferingTransactions 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 *DeviceFarm) ListOfferingTransactionsWithContext(ctx aws.Context, input *ListOfferingTransactionsInput, opts ...request.Option) (*ListOfferingTransactionsOutput, error) { + req, out := c.ListOfferingTransactionsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +// ListOfferingTransactionsPages iterates over the pages of a ListOfferingTransactions operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See ListOfferingTransactions 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 ListOfferingTransactions operation. +// pageNum := 0 +// err := client.ListOfferingTransactionsPages(params, +// func(page *ListOfferingTransactionsOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *DeviceFarm) ListOfferingTransactionsPages(input *ListOfferingTransactionsInput, fn func(*ListOfferingTransactionsOutput, bool) bool) error { + return c.ListOfferingTransactionsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListOfferingTransactionsPagesWithContext same as ListOfferingTransactionsPages 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 *DeviceFarm) ListOfferingTransactionsPagesWithContext(ctx aws.Context, input *ListOfferingTransactionsInput, fn func(*ListOfferingTransactionsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListOfferingTransactionsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListOfferingTransactionsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*ListOfferingTransactionsOutput), !p.HasNextPage()) + } + return p.Err() +} + +const opListOfferings = "ListOfferings" + +// ListOfferingsRequest generates a "aws/request.Request" representing the +// client's request for the ListOfferings operation. The "output" return +// value can be used to capture response data after the request's "Send" method +// is called. +// +// See ListOfferings for usage and error information. +// +// Creating a request object using this method should be used when you want to inject +// custom logic into the request's lifecycle using a custom handler, or if you want to +// access properties on the request object before or after sending the request. If +// you just want the service response, call the ListOfferings method directly +// instead. +// +// Note: You must call the "Send" method on the returned request object in order +// to execute the request. +// +// // Example sending a request using the ListOfferingsRequest method. +// req, resp := client.ListOfferingsRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/ListOfferings +func (c *DeviceFarm) ListOfferingsRequest(input *ListOfferingsInput) (req *request.Request, output *ListOfferingsOutput) { + op := &request.Operation{ + Name: opListOfferings, + HTTPMethod: "POST", + HTTPPath: "/", + Paginator: &request.Paginator{ + InputTokens: []string{"nextToken"}, + OutputTokens: []string{"nextToken"}, + LimitToken: "", + TruncationToken: "", + }, + } + + if input == nil { + input = &ListOfferingsInput{} + } + + output = &ListOfferingsOutput{} + req = c.newRequest(op, input, output) + return +} + +// ListOfferings API operation for AWS Device Farm. +// +// Returns a list of products or offerings that the user can manage through +// the API. Each offering record indicates the recurring price per unit and +// the frequency for that offering. The API returns a NotEligible error if the +// user is not permitted to invoke the operation. Please contact aws-devicefarm-support@amazon.com +// (mailto:aws-devicefarm-support@amazon.com) if you believe that you should +// be able to invoke this 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 +// the error. +// +// See the AWS API reference guide for AWS Device Farm's +// API operation ListOfferings for usage and error information. +// +// Returned Error Codes: +// * ErrCodeArgumentException "ArgumentException" +// An invalid argument was specified. +// +// * ErrCodeNotFoundException "NotFoundException" +// The specified entity was not found. +// +// * ErrCodeNotEligibleException "NotEligibleException" +// Exception gets thrown when a user is not eligible to perform the specified +// transaction. +// +// * ErrCodeLimitExceededException "LimitExceededException" +// A limit was exceeded. +// +// * ErrCodeServiceAccountException "ServiceAccountException" +// There was a problem with the service account. +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/ListOfferings +func (c *DeviceFarm) ListOfferings(input *ListOfferingsInput) (*ListOfferingsOutput, error) { + req, out := c.ListOfferingsRequest(input) + return out, req.Send() +} + +// ListOfferingsWithContext is the same as ListOfferings with the addition of +// the ability to pass a context and additional request options. +// +// See ListOfferings 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 *DeviceFarm) ListOfferingsWithContext(ctx aws.Context, input *ListOfferingsInput, opts ...request.Option) (*ListOfferingsOutput, error) { + req, out := c.ListOfferingsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +// ListOfferingsPages iterates over the pages of a ListOfferings operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See ListOfferings 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 ListOfferings operation. +// pageNum := 0 +// err := client.ListOfferingsPages(params, +// func(page *ListOfferingsOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *DeviceFarm) ListOfferingsPages(input *ListOfferingsInput, fn func(*ListOfferingsOutput, bool) bool) error { + return c.ListOfferingsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListOfferingsPagesWithContext same as ListOfferingsPages 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 *DeviceFarm) ListOfferingsPagesWithContext(ctx aws.Context, input *ListOfferingsInput, fn func(*ListOfferingsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListOfferingsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListOfferingsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*ListOfferingsOutput), !p.HasNextPage()) + } + return p.Err() +} + +const opListProjects = "ListProjects" + +// ListProjectsRequest generates a "aws/request.Request" representing the +// client's request for the ListProjects operation. The "output" return +// value can be used to capture response data after the request's "Send" method +// is called. +// +// See ListProjects for usage and error information. +// +// Creating a request object using this method should be used when you want to inject +// custom logic into the request's lifecycle using a custom handler, or if you want to +// access properties on the request object before or after sending the request. If +// you just want the service response, call the ListProjects method directly +// instead. +// +// Note: You must call the "Send" method on the returned request object in order +// to execute the request. +// +// // Example sending a request using the ListProjectsRequest method. +// req, resp := client.ListProjectsRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/ListProjects +func (c *DeviceFarm) ListProjectsRequest(input *ListProjectsInput) (req *request.Request, output *ListProjectsOutput) { + op := &request.Operation{ + Name: opListProjects, + HTTPMethod: "POST", + HTTPPath: "/", + Paginator: &request.Paginator{ + InputTokens: []string{"nextToken"}, + OutputTokens: []string{"nextToken"}, + LimitToken: "", + TruncationToken: "", + }, + } + + if input == nil { + input = &ListProjectsInput{} + } + + output = &ListProjectsOutput{} + req = c.newRequest(op, input, output) + return +} + +// ListProjects API operation for AWS Device Farm. +// +// Gets information about projects. +// +// 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 Device Farm's +// API operation ListProjects for usage and error information. +// +// Returned Error Codes: +// * ErrCodeArgumentException "ArgumentException" +// An invalid argument was specified. +// +// * ErrCodeNotFoundException "NotFoundException" +// The specified entity was not found. +// +// * ErrCodeLimitExceededException "LimitExceededException" +// A limit was exceeded. +// +// * ErrCodeServiceAccountException "ServiceAccountException" +// There was a problem with the service account. +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/ListProjects +func (c *DeviceFarm) ListProjects(input *ListProjectsInput) (*ListProjectsOutput, error) { + req, out := c.ListProjectsRequest(input) + return out, req.Send() +} + +// ListProjectsWithContext is the same as ListProjects with the addition of +// the ability to pass a context and additional request options. +// +// See ListProjects 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 *DeviceFarm) ListProjectsWithContext(ctx aws.Context, input *ListProjectsInput, opts ...request.Option) (*ListProjectsOutput, error) { + req, out := c.ListProjectsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +// ListProjectsPages iterates over the pages of a ListProjects operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See ListProjects 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 ListProjects operation. +// pageNum := 0 +// err := client.ListProjectsPages(params, +// func(page *ListProjectsOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *DeviceFarm) ListProjectsPages(input *ListProjectsInput, fn func(*ListProjectsOutput, bool) bool) error { + return c.ListProjectsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListProjectsPagesWithContext same as ListProjectsPages 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 *DeviceFarm) ListProjectsPagesWithContext(ctx aws.Context, input *ListProjectsInput, fn func(*ListProjectsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListProjectsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListProjectsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*ListProjectsOutput), !p.HasNextPage()) + } + return p.Err() +} + +const opListRemoteAccessSessions = "ListRemoteAccessSessions" + +// ListRemoteAccessSessionsRequest generates a "aws/request.Request" representing the +// client's request for the ListRemoteAccessSessions operation. The "output" return +// value can be used to capture response data after the request's "Send" method +// is called. +// +// See ListRemoteAccessSessions for usage and error information. +// +// Creating a request object using this method should be used when you want to inject +// custom logic into the request's lifecycle using a custom handler, or if you want to +// access properties on the request object before or after sending the request. If +// you just want the service response, call the ListRemoteAccessSessions method directly +// instead. +// +// Note: You must call the "Send" method on the returned request object in order +// to execute the request. +// +// // Example sending a request using the ListRemoteAccessSessionsRequest method. +// req, resp := client.ListRemoteAccessSessionsRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/ListRemoteAccessSessions +func (c *DeviceFarm) ListRemoteAccessSessionsRequest(input *ListRemoteAccessSessionsInput) (req *request.Request, output *ListRemoteAccessSessionsOutput) { + op := &request.Operation{ + Name: opListRemoteAccessSessions, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &ListRemoteAccessSessionsInput{} + } + + output = &ListRemoteAccessSessionsOutput{} + req = c.newRequest(op, input, output) + return +} + +// ListRemoteAccessSessions API operation for AWS Device Farm. +// +// Returns a list of all currently running remote access sessions. +// +// 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 Device Farm's +// API operation ListRemoteAccessSessions for usage and error information. +// +// Returned Error Codes: +// * ErrCodeArgumentException "ArgumentException" +// An invalid argument was specified. +// +// * ErrCodeNotFoundException "NotFoundException" +// The specified entity was not found. +// +// * ErrCodeLimitExceededException "LimitExceededException" +// A limit was exceeded. +// +// * ErrCodeServiceAccountException "ServiceAccountException" +// There was a problem with the service account. +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/ListRemoteAccessSessions +func (c *DeviceFarm) ListRemoteAccessSessions(input *ListRemoteAccessSessionsInput) (*ListRemoteAccessSessionsOutput, error) { + req, out := c.ListRemoteAccessSessionsRequest(input) + return out, req.Send() +} + +// ListRemoteAccessSessionsWithContext is the same as ListRemoteAccessSessions with the addition of +// the ability to pass a context and additional request options. +// +// See ListRemoteAccessSessions 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 *DeviceFarm) ListRemoteAccessSessionsWithContext(ctx aws.Context, input *ListRemoteAccessSessionsInput, opts ...request.Option) (*ListRemoteAccessSessionsOutput, error) { + req, out := c.ListRemoteAccessSessionsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opListRuns = "ListRuns" + +// ListRunsRequest generates a "aws/request.Request" representing the +// client's request for the ListRuns operation. The "output" return +// value can be used to capture response data after the request's "Send" method +// is called. +// +// See ListRuns for usage and error information. +// +// Creating a request object using this method should be used when you want to inject +// custom logic into the request's lifecycle using a custom handler, or if you want to +// access properties on the request object before or after sending the request. If +// you just want the service response, call the ListRuns method directly +// instead. +// +// Note: You must call the "Send" method on the returned request object in order +// to execute the request. +// +// // Example sending a request using the ListRunsRequest method. +// req, resp := client.ListRunsRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/ListRuns +func (c *DeviceFarm) ListRunsRequest(input *ListRunsInput) (req *request.Request, output *ListRunsOutput) { + op := &request.Operation{ + Name: opListRuns, + HTTPMethod: "POST", + HTTPPath: "/", + Paginator: &request.Paginator{ + InputTokens: []string{"nextToken"}, + OutputTokens: []string{"nextToken"}, + LimitToken: "", + TruncationToken: "", + }, + } + + if input == nil { + input = &ListRunsInput{} + } + + output = &ListRunsOutput{} + req = c.newRequest(op, input, output) + return +} + +// ListRuns API operation for AWS Device Farm. +// +// Gets information about runs, given an AWS Device Farm project ARN. +// +// 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 Device Farm's +// API operation ListRuns for usage and error information. +// +// Returned Error Codes: +// * ErrCodeArgumentException "ArgumentException" +// An invalid argument was specified. +// +// * ErrCodeNotFoundException "NotFoundException" +// The specified entity was not found. +// +// * ErrCodeLimitExceededException "LimitExceededException" +// A limit was exceeded. +// +// * ErrCodeServiceAccountException "ServiceAccountException" +// There was a problem with the service account. +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/ListRuns +func (c *DeviceFarm) ListRuns(input *ListRunsInput) (*ListRunsOutput, error) { + req, out := c.ListRunsRequest(input) + return out, req.Send() +} + +// ListRunsWithContext is the same as ListRuns with the addition of +// the ability to pass a context and additional request options. +// +// See ListRuns 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 *DeviceFarm) ListRunsWithContext(ctx aws.Context, input *ListRunsInput, opts ...request.Option) (*ListRunsOutput, error) { + req, out := c.ListRunsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +// ListRunsPages iterates over the pages of a ListRuns operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See ListRuns 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 ListRuns operation. +// pageNum := 0 +// err := client.ListRunsPages(params, +// func(page *ListRunsOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *DeviceFarm) ListRunsPages(input *ListRunsInput, fn func(*ListRunsOutput, bool) bool) error { + return c.ListRunsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListRunsPagesWithContext same as ListRunsPages 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 *DeviceFarm) ListRunsPagesWithContext(ctx aws.Context, input *ListRunsInput, fn func(*ListRunsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListRunsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListRunsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*ListRunsOutput), !p.HasNextPage()) + } + return p.Err() +} + +const opListSamples = "ListSamples" + +// ListSamplesRequest generates a "aws/request.Request" representing the +// client's request for the ListSamples operation. The "output" return +// value can be used to capture response data after the request's "Send" method +// is called. +// +// See ListSamples for usage and error information. +// +// Creating a request object using this method should be used when you want to inject +// custom logic into the request's lifecycle using a custom handler, or if you want to +// access properties on the request object before or after sending the request. If +// you just want the service response, call the ListSamples method directly +// instead. +// +// Note: You must call the "Send" method on the returned request object in order +// to execute the request. +// +// // Example sending a request using the ListSamplesRequest method. +// req, resp := client.ListSamplesRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/ListSamples +func (c *DeviceFarm) ListSamplesRequest(input *ListSamplesInput) (req *request.Request, output *ListSamplesOutput) { + op := &request.Operation{ + Name: opListSamples, + HTTPMethod: "POST", + HTTPPath: "/", + Paginator: &request.Paginator{ + InputTokens: []string{"nextToken"}, + OutputTokens: []string{"nextToken"}, + LimitToken: "", + TruncationToken: "", + }, + } + + if input == nil { + input = &ListSamplesInput{} + } + + output = &ListSamplesOutput{} + req = c.newRequest(op, input, output) + return +} + +// ListSamples API operation for AWS Device Farm. +// +// Gets information about samples, given an AWS Device Farm project ARN +// +// 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 Device Farm's +// API operation ListSamples for usage and error information. +// +// Returned Error Codes: +// * ErrCodeArgumentException "ArgumentException" +// An invalid argument was specified. +// +// * ErrCodeNotFoundException "NotFoundException" +// The specified entity was not found. +// +// * ErrCodeLimitExceededException "LimitExceededException" +// A limit was exceeded. +// +// * ErrCodeServiceAccountException "ServiceAccountException" +// There was a problem with the service account. +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/ListSamples +func (c *DeviceFarm) ListSamples(input *ListSamplesInput) (*ListSamplesOutput, error) { + req, out := c.ListSamplesRequest(input) + return out, req.Send() +} + +// ListSamplesWithContext is the same as ListSamples with the addition of +// the ability to pass a context and additional request options. +// +// See ListSamples 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 *DeviceFarm) ListSamplesWithContext(ctx aws.Context, input *ListSamplesInput, opts ...request.Option) (*ListSamplesOutput, error) { + req, out := c.ListSamplesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +// ListSamplesPages iterates over the pages of a ListSamples operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See ListSamples 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 ListSamples operation. +// pageNum := 0 +// err := client.ListSamplesPages(params, +// func(page *ListSamplesOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *DeviceFarm) ListSamplesPages(input *ListSamplesInput, fn func(*ListSamplesOutput, bool) bool) error { + return c.ListSamplesPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListSamplesPagesWithContext same as ListSamplesPages 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 *DeviceFarm) ListSamplesPagesWithContext(ctx aws.Context, input *ListSamplesInput, fn func(*ListSamplesOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListSamplesInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListSamplesRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*ListSamplesOutput), !p.HasNextPage()) + } + return p.Err() +} + +const opListSuites = "ListSuites" + +// ListSuitesRequest generates a "aws/request.Request" representing the +// client's request for the ListSuites operation. The "output" return +// value can be used to capture response data after the request's "Send" method +// is called. +// +// See ListSuites for usage and error information. +// +// Creating a request object using this method should be used when you want to inject +// custom logic into the request's lifecycle using a custom handler, or if you want to +// access properties on the request object before or after sending the request. If +// you just want the service response, call the ListSuites method directly +// instead. +// +// Note: You must call the "Send" method on the returned request object in order +// to execute the request. +// +// // Example sending a request using the ListSuitesRequest method. +// req, resp := client.ListSuitesRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/ListSuites +func (c *DeviceFarm) ListSuitesRequest(input *ListSuitesInput) (req *request.Request, output *ListSuitesOutput) { + op := &request.Operation{ + Name: opListSuites, + HTTPMethod: "POST", + HTTPPath: "/", + Paginator: &request.Paginator{ + InputTokens: []string{"nextToken"}, + OutputTokens: []string{"nextToken"}, + LimitToken: "", + TruncationToken: "", + }, + } + + if input == nil { + input = &ListSuitesInput{} + } + + output = &ListSuitesOutput{} + req = c.newRequest(op, input, output) + return +} + +// ListSuites API operation for AWS Device Farm. +// +// Gets information about suites. +// +// 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 Device Farm's +// API operation ListSuites for usage and error information. +// +// Returned Error Codes: +// * ErrCodeArgumentException "ArgumentException" +// An invalid argument was specified. +// +// * ErrCodeNotFoundException "NotFoundException" +// The specified entity was not found. +// +// * ErrCodeLimitExceededException "LimitExceededException" +// A limit was exceeded. +// +// * ErrCodeServiceAccountException "ServiceAccountException" +// There was a problem with the service account. +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/ListSuites +func (c *DeviceFarm) ListSuites(input *ListSuitesInput) (*ListSuitesOutput, error) { + req, out := c.ListSuitesRequest(input) + return out, req.Send() +} + +// ListSuitesWithContext is the same as ListSuites with the addition of +// the ability to pass a context and additional request options. +// +// See ListSuites 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 *DeviceFarm) ListSuitesWithContext(ctx aws.Context, input *ListSuitesInput, opts ...request.Option) (*ListSuitesOutput, error) { + req, out := c.ListSuitesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +// ListSuitesPages iterates over the pages of a ListSuites operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See ListSuites 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 ListSuites operation. +// pageNum := 0 +// err := client.ListSuitesPages(params, +// func(page *ListSuitesOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *DeviceFarm) ListSuitesPages(input *ListSuitesInput, fn func(*ListSuitesOutput, bool) bool) error { + return c.ListSuitesPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListSuitesPagesWithContext same as ListSuitesPages 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 *DeviceFarm) ListSuitesPagesWithContext(ctx aws.Context, input *ListSuitesInput, fn func(*ListSuitesOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListSuitesInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListSuitesRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*ListSuitesOutput), !p.HasNextPage()) + } + return p.Err() +} + +const opListTests = "ListTests" + +// ListTestsRequest generates a "aws/request.Request" representing the +// client's request for the ListTests operation. The "output" return +// value can be used to capture response data after the request's "Send" method +// is called. +// +// See ListTests for usage and error information. +// +// Creating a request object using this method should be used when you want to inject +// custom logic into the request's lifecycle using a custom handler, or if you want to +// access properties on the request object before or after sending the request. If +// you just want the service response, call the ListTests method directly +// instead. +// +// Note: You must call the "Send" method on the returned request object in order +// to execute the request. +// +// // Example sending a request using the ListTestsRequest method. +// req, resp := client.ListTestsRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/ListTests +func (c *DeviceFarm) ListTestsRequest(input *ListTestsInput) (req *request.Request, output *ListTestsOutput) { + op := &request.Operation{ + Name: opListTests, + HTTPMethod: "POST", + HTTPPath: "/", + Paginator: &request.Paginator{ + InputTokens: []string{"nextToken"}, + OutputTokens: []string{"nextToken"}, + LimitToken: "", + TruncationToken: "", + }, + } + + if input == nil { + input = &ListTestsInput{} + } + + output = &ListTestsOutput{} + req = c.newRequest(op, input, output) + return +} + +// ListTests API operation for AWS Device Farm. +// +// Gets information about tests. +// +// 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 Device Farm's +// API operation ListTests for usage and error information. +// +// Returned Error Codes: +// * ErrCodeArgumentException "ArgumentException" +// An invalid argument was specified. +// +// * ErrCodeNotFoundException "NotFoundException" +// The specified entity was not found. +// +// * ErrCodeLimitExceededException "LimitExceededException" +// A limit was exceeded. +// +// * ErrCodeServiceAccountException "ServiceAccountException" +// There was a problem with the service account. +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/ListTests +func (c *DeviceFarm) ListTests(input *ListTestsInput) (*ListTestsOutput, error) { + req, out := c.ListTestsRequest(input) + return out, req.Send() +} + +// ListTestsWithContext is the same as ListTests with the addition of +// the ability to pass a context and additional request options. +// +// See ListTests 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 *DeviceFarm) ListTestsWithContext(ctx aws.Context, input *ListTestsInput, opts ...request.Option) (*ListTestsOutput, error) { + req, out := c.ListTestsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +// ListTestsPages iterates over the pages of a ListTests operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See ListTests 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 ListTests operation. +// pageNum := 0 +// err := client.ListTestsPages(params, +// func(page *ListTestsOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *DeviceFarm) ListTestsPages(input *ListTestsInput, fn func(*ListTestsOutput, bool) bool) error { + return c.ListTestsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListTestsPagesWithContext same as ListTestsPages 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 *DeviceFarm) ListTestsPagesWithContext(ctx aws.Context, input *ListTestsInput, fn func(*ListTestsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListTestsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListTestsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*ListTestsOutput), !p.HasNextPage()) + } + return p.Err() +} + +const opListUniqueProblems = "ListUniqueProblems" + +// ListUniqueProblemsRequest generates a "aws/request.Request" representing the +// client's request for the ListUniqueProblems operation. The "output" return +// value can be used to capture response data after the request's "Send" method +// is called. +// +// See ListUniqueProblems for usage and error information. +// +// Creating a request object using this method should be used when you want to inject +// custom logic into the request's lifecycle using a custom handler, or if you want to +// access properties on the request object before or after sending the request. If +// you just want the service response, call the ListUniqueProblems method directly +// instead. +// +// Note: You must call the "Send" method on the returned request object in order +// to execute the request. +// +// // Example sending a request using the ListUniqueProblemsRequest method. +// req, resp := client.ListUniqueProblemsRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/ListUniqueProblems +func (c *DeviceFarm) ListUniqueProblemsRequest(input *ListUniqueProblemsInput) (req *request.Request, output *ListUniqueProblemsOutput) { + op := &request.Operation{ + Name: opListUniqueProblems, + HTTPMethod: "POST", + HTTPPath: "/", + Paginator: &request.Paginator{ + InputTokens: []string{"nextToken"}, + OutputTokens: []string{"nextToken"}, + LimitToken: "", + TruncationToken: "", + }, + } + + if input == nil { + input = &ListUniqueProblemsInput{} + } + + output = &ListUniqueProblemsOutput{} + req = c.newRequest(op, input, output) + return +} + +// ListUniqueProblems API operation for AWS Device Farm. +// +// Gets information about unique problems. +// +// 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 Device Farm's +// API operation ListUniqueProblems for usage and error information. +// +// Returned Error Codes: +// * ErrCodeArgumentException "ArgumentException" +// An invalid argument was specified. +// +// * ErrCodeNotFoundException "NotFoundException" +// The specified entity was not found. +// +// * ErrCodeLimitExceededException "LimitExceededException" +// A limit was exceeded. +// +// * ErrCodeServiceAccountException "ServiceAccountException" +// There was a problem with the service account. +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/ListUniqueProblems +func (c *DeviceFarm) ListUniqueProblems(input *ListUniqueProblemsInput) (*ListUniqueProblemsOutput, error) { + req, out := c.ListUniqueProblemsRequest(input) + return out, req.Send() +} + +// ListUniqueProblemsWithContext is the same as ListUniqueProblems with the addition of +// the ability to pass a context and additional request options. +// +// See ListUniqueProblems 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 *DeviceFarm) ListUniqueProblemsWithContext(ctx aws.Context, input *ListUniqueProblemsInput, opts ...request.Option) (*ListUniqueProblemsOutput, error) { + req, out := c.ListUniqueProblemsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +// ListUniqueProblemsPages iterates over the pages of a ListUniqueProblems operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See ListUniqueProblems 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 ListUniqueProblems operation. +// pageNum := 0 +// err := client.ListUniqueProblemsPages(params, +// func(page *ListUniqueProblemsOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *DeviceFarm) ListUniqueProblemsPages(input *ListUniqueProblemsInput, fn func(*ListUniqueProblemsOutput, bool) bool) error { + return c.ListUniqueProblemsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListUniqueProblemsPagesWithContext same as ListUniqueProblemsPages 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 *DeviceFarm) ListUniqueProblemsPagesWithContext(ctx aws.Context, input *ListUniqueProblemsInput, fn func(*ListUniqueProblemsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListUniqueProblemsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListUniqueProblemsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*ListUniqueProblemsOutput), !p.HasNextPage()) + } + return p.Err() +} + +const opListUploads = "ListUploads" + +// ListUploadsRequest generates a "aws/request.Request" representing the +// client's request for the ListUploads operation. The "output" return +// value can be used to capture response data after the request's "Send" method +// is called. +// +// See ListUploads for usage and error information. +// +// Creating a request object using this method should be used when you want to inject +// custom logic into the request's lifecycle using a custom handler, or if you want to +// access properties on the request object before or after sending the request. If +// you just want the service response, call the ListUploads method directly +// instead. +// +// Note: You must call the "Send" method on the returned request object in order +// to execute the request. +// +// // Example sending a request using the ListUploadsRequest method. +// req, resp := client.ListUploadsRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/ListUploads +func (c *DeviceFarm) ListUploadsRequest(input *ListUploadsInput) (req *request.Request, output *ListUploadsOutput) { + op := &request.Operation{ + Name: opListUploads, + HTTPMethod: "POST", + HTTPPath: "/", + Paginator: &request.Paginator{ + InputTokens: []string{"nextToken"}, + OutputTokens: []string{"nextToken"}, + LimitToken: "", + TruncationToken: "", + }, + } + + if input == nil { + input = &ListUploadsInput{} + } + + output = &ListUploadsOutput{} + req = c.newRequest(op, input, output) + return +} + +// ListUploads API operation for AWS Device Farm. +// +// Gets information about uploads, given an AWS Device Farm project ARN. +// +// 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 Device Farm's +// API operation ListUploads for usage and error information. +// +// Returned Error Codes: +// * ErrCodeArgumentException "ArgumentException" +// An invalid argument was specified. +// +// * ErrCodeNotFoundException "NotFoundException" +// The specified entity was not found. +// +// * ErrCodeLimitExceededException "LimitExceededException" +// A limit was exceeded. +// +// * ErrCodeServiceAccountException "ServiceAccountException" +// There was a problem with the service account. +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/ListUploads +func (c *DeviceFarm) ListUploads(input *ListUploadsInput) (*ListUploadsOutput, error) { + req, out := c.ListUploadsRequest(input) + return out, req.Send() +} + +// ListUploadsWithContext is the same as ListUploads with the addition of +// the ability to pass a context and additional request options. +// +// See ListUploads 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 *DeviceFarm) ListUploadsWithContext(ctx aws.Context, input *ListUploadsInput, opts ...request.Option) (*ListUploadsOutput, error) { + req, out := c.ListUploadsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +// ListUploadsPages iterates over the pages of a ListUploads operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See ListUploads 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 ListUploads operation. +// pageNum := 0 +// err := client.ListUploadsPages(params, +// func(page *ListUploadsOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *DeviceFarm) ListUploadsPages(input *ListUploadsInput, fn func(*ListUploadsOutput, bool) bool) error { + return c.ListUploadsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListUploadsPagesWithContext same as ListUploadsPages 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 *DeviceFarm) ListUploadsPagesWithContext(ctx aws.Context, input *ListUploadsInput, fn func(*ListUploadsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListUploadsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListUploadsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*ListUploadsOutput), !p.HasNextPage()) + } + return p.Err() +} + +const opPurchaseOffering = "PurchaseOffering" + +// PurchaseOfferingRequest generates a "aws/request.Request" representing the +// client's request for the PurchaseOffering operation. The "output" return +// value can be used to capture response data after the request's "Send" method +// is called. +// +// See PurchaseOffering for usage and error information. +// +// Creating a request object using this method should be used when you want to inject +// custom logic into the request's lifecycle using a custom handler, or if you want to +// access properties on the request object before or after sending the request. If +// you just want the service response, call the PurchaseOffering method directly +// instead. +// +// Note: You must call the "Send" method on the returned request object in order +// to execute the request. +// +// // Example sending a request using the PurchaseOfferingRequest method. +// req, resp := client.PurchaseOfferingRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/PurchaseOffering +func (c *DeviceFarm) PurchaseOfferingRequest(input *PurchaseOfferingInput) (req *request.Request, output *PurchaseOfferingOutput) { + op := &request.Operation{ + Name: opPurchaseOffering, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &PurchaseOfferingInput{} + } + + output = &PurchaseOfferingOutput{} + req = c.newRequest(op, input, output) + return +} + +// PurchaseOffering API operation for AWS Device Farm. +// +// Immediately purchases offerings for an AWS account. Offerings renew with +// the latest total purchased quantity for an offering, unless the renewal was +// overridden. The API returns a NotEligible error if the user is not permitted +// to invoke the operation. Please contact aws-devicefarm-support@amazon.com +// (mailto:aws-devicefarm-support@amazon.com) if you believe that you should +// be able to invoke this 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 +// the error. +// +// See the AWS API reference guide for AWS Device Farm's +// API operation PurchaseOffering for usage and error information. +// +// Returned Error Codes: +// * ErrCodeArgumentException "ArgumentException" +// An invalid argument was specified. +// +// * ErrCodeNotFoundException "NotFoundException" +// The specified entity was not found. +// +// * ErrCodeNotEligibleException "NotEligibleException" +// Exception gets thrown when a user is not eligible to perform the specified +// transaction. +// +// * ErrCodeLimitExceededException "LimitExceededException" +// A limit was exceeded. +// +// * ErrCodeServiceAccountException "ServiceAccountException" +// There was a problem with the service account. +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/PurchaseOffering +func (c *DeviceFarm) PurchaseOffering(input *PurchaseOfferingInput) (*PurchaseOfferingOutput, error) { + req, out := c.PurchaseOfferingRequest(input) + return out, req.Send() +} + +// PurchaseOfferingWithContext is the same as PurchaseOffering with the addition of +// the ability to pass a context and additional request options. +// +// See PurchaseOffering 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 *DeviceFarm) PurchaseOfferingWithContext(ctx aws.Context, input *PurchaseOfferingInput, opts ...request.Option) (*PurchaseOfferingOutput, error) { + req, out := c.PurchaseOfferingRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opRenewOffering = "RenewOffering" + +// RenewOfferingRequest generates a "aws/request.Request" representing the +// client's request for the RenewOffering operation. The "output" return +// value can be used to capture response data after the request's "Send" method +// is called. +// +// See RenewOffering for usage and error information. +// +// Creating a request object using this method should be used when you want to inject +// custom logic into the request's lifecycle using a custom handler, or if you want to +// access properties on the request object before or after sending the request. If +// you just want the service response, call the RenewOffering method directly +// instead. +// +// Note: You must call the "Send" method on the returned request object in order +// to execute the request. +// +// // Example sending a request using the RenewOfferingRequest method. +// req, resp := client.RenewOfferingRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/RenewOffering +func (c *DeviceFarm) RenewOfferingRequest(input *RenewOfferingInput) (req *request.Request, output *RenewOfferingOutput) { + op := &request.Operation{ + Name: opRenewOffering, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &RenewOfferingInput{} + } + + output = &RenewOfferingOutput{} + req = c.newRequest(op, input, output) + return +} + +// RenewOffering API operation for AWS Device Farm. +// +// Explicitly sets the quantity of devices to renew for an offering, starting +// from the effectiveDate of the next period. The API returns a NotEligible +// error if the user is not permitted to invoke the operation. Please contact +// aws-devicefarm-support@amazon.com (mailto:aws-devicefarm-support@amazon.com) +// if you believe that you should be able to invoke this 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 +// the error. +// +// See the AWS API reference guide for AWS Device Farm's +// API operation RenewOffering for usage and error information. +// +// Returned Error Codes: +// * ErrCodeArgumentException "ArgumentException" +// An invalid argument was specified. +// +// * ErrCodeNotFoundException "NotFoundException" +// The specified entity was not found. +// +// * ErrCodeNotEligibleException "NotEligibleException" +// Exception gets thrown when a user is not eligible to perform the specified +// transaction. +// +// * ErrCodeLimitExceededException "LimitExceededException" +// A limit was exceeded. +// +// * ErrCodeServiceAccountException "ServiceAccountException" +// There was a problem with the service account. +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/RenewOffering +func (c *DeviceFarm) RenewOffering(input *RenewOfferingInput) (*RenewOfferingOutput, error) { + req, out := c.RenewOfferingRequest(input) + return out, req.Send() +} + +// RenewOfferingWithContext is the same as RenewOffering with the addition of +// the ability to pass a context and additional request options. +// +// See RenewOffering 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 *DeviceFarm) RenewOfferingWithContext(ctx aws.Context, input *RenewOfferingInput, opts ...request.Option) (*RenewOfferingOutput, error) { + req, out := c.RenewOfferingRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opScheduleRun = "ScheduleRun" + +// ScheduleRunRequest generates a "aws/request.Request" representing the +// client's request for the ScheduleRun operation. The "output" return +// value can be used to capture response data after the request's "Send" method +// is called. +// +// See ScheduleRun for usage and error information. +// +// Creating a request object using this method should be used when you want to inject +// custom logic into the request's lifecycle using a custom handler, or if you want to +// access properties on the request object before or after sending the request. If +// you just want the service response, call the ScheduleRun method directly +// instead. +// +// Note: You must call the "Send" method on the returned request object in order +// to execute the request. +// +// // Example sending a request using the ScheduleRunRequest method. +// req, resp := client.ScheduleRunRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/ScheduleRun +func (c *DeviceFarm) ScheduleRunRequest(input *ScheduleRunInput) (req *request.Request, output *ScheduleRunOutput) { + op := &request.Operation{ + Name: opScheduleRun, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &ScheduleRunInput{} + } + + output = &ScheduleRunOutput{} + req = c.newRequest(op, input, output) + return +} + +// ScheduleRun API operation for AWS Device Farm. +// +// Schedules a run. +// +// 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 Device Farm's +// API operation ScheduleRun for usage and error information. +// +// Returned Error Codes: +// * ErrCodeArgumentException "ArgumentException" +// An invalid argument was specified. +// +// * ErrCodeNotFoundException "NotFoundException" +// The specified entity was not found. +// +// * ErrCodeLimitExceededException "LimitExceededException" +// A limit was exceeded. +// +// * ErrCodeIdempotencyException "IdempotencyException" +// An entity with the same name already exists. +// +// * ErrCodeServiceAccountException "ServiceAccountException" +// There was a problem with the service account. +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/ScheduleRun +func (c *DeviceFarm) ScheduleRun(input *ScheduleRunInput) (*ScheduleRunOutput, error) { + req, out := c.ScheduleRunRequest(input) + return out, req.Send() +} + +// ScheduleRunWithContext is the same as ScheduleRun with the addition of +// the ability to pass a context and additional request options. +// +// See ScheduleRun 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 *DeviceFarm) ScheduleRunWithContext(ctx aws.Context, input *ScheduleRunInput, opts ...request.Option) (*ScheduleRunOutput, error) { + req, out := c.ScheduleRunRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opStopRemoteAccessSession = "StopRemoteAccessSession" + +// StopRemoteAccessSessionRequest generates a "aws/request.Request" representing the +// client's request for the StopRemoteAccessSession operation. The "output" return +// value can be used to capture response data after the request's "Send" method +// is called. +// +// See StopRemoteAccessSession for usage and error information. +// +// Creating a request object using this method should be used when you want to inject +// custom logic into the request's lifecycle using a custom handler, or if you want to +// access properties on the request object before or after sending the request. If +// you just want the service response, call the StopRemoteAccessSession method directly +// instead. +// +// Note: You must call the "Send" method on the returned request object in order +// to execute the request. +// +// // Example sending a request using the StopRemoteAccessSessionRequest method. +// req, resp := client.StopRemoteAccessSessionRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/StopRemoteAccessSession +func (c *DeviceFarm) StopRemoteAccessSessionRequest(input *StopRemoteAccessSessionInput) (req *request.Request, output *StopRemoteAccessSessionOutput) { + op := &request.Operation{ + Name: opStopRemoteAccessSession, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &StopRemoteAccessSessionInput{} + } + + output = &StopRemoteAccessSessionOutput{} + req = c.newRequest(op, input, output) + return +} + +// StopRemoteAccessSession API operation for AWS Device Farm. +// +// Ends a specified remote access session. +// +// 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 Device Farm's +// API operation StopRemoteAccessSession for usage and error information. +// +// Returned Error Codes: +// * ErrCodeArgumentException "ArgumentException" +// An invalid argument was specified. +// +// * ErrCodeNotFoundException "NotFoundException" +// The specified entity was not found. +// +// * ErrCodeLimitExceededException "LimitExceededException" +// A limit was exceeded. +// +// * ErrCodeServiceAccountException "ServiceAccountException" +// There was a problem with the service account. +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/StopRemoteAccessSession +func (c *DeviceFarm) StopRemoteAccessSession(input *StopRemoteAccessSessionInput) (*StopRemoteAccessSessionOutput, error) { + req, out := c.StopRemoteAccessSessionRequest(input) + return out, req.Send() +} + +// StopRemoteAccessSessionWithContext is the same as StopRemoteAccessSession with the addition of +// the ability to pass a context and additional request options. +// +// See StopRemoteAccessSession 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 *DeviceFarm) StopRemoteAccessSessionWithContext(ctx aws.Context, input *StopRemoteAccessSessionInput, opts ...request.Option) (*StopRemoteAccessSessionOutput, error) { + req, out := c.StopRemoteAccessSessionRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opStopRun = "StopRun" + +// StopRunRequest generates a "aws/request.Request" representing the +// client's request for the StopRun operation. The "output" return +// value can be used to capture response data after the request's "Send" method +// is called. +// +// See StopRun for usage and error information. +// +// Creating a request object using this method should be used when you want to inject +// custom logic into the request's lifecycle using a custom handler, or if you want to +// access properties on the request object before or after sending the request. If +// you just want the service response, call the StopRun method directly +// instead. +// +// Note: You must call the "Send" method on the returned request object in order +// to execute the request. +// +// // Example sending a request using the StopRunRequest method. +// req, resp := client.StopRunRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/StopRun +func (c *DeviceFarm) StopRunRequest(input *StopRunInput) (req *request.Request, output *StopRunOutput) { + op := &request.Operation{ + Name: opStopRun, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &StopRunInput{} + } + + output = &StopRunOutput{} + req = c.newRequest(op, input, output) + return +} + +// StopRun API operation for AWS Device Farm. +// +// Initiates a stop request for the current test run. AWS Device Farm will immediately +// stop the run on devices where tests have not started executing, and you will +// not be billed for these devices. On devices where tests have started executing, +// Setup Suite and Teardown Suite tests will run to completion before stopping +// execution on those devices. You will be billed for Setup, Teardown, and any +// tests that were in progress or already completed. +// +// 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 Device Farm's +// API operation StopRun for usage and error information. +// +// Returned Error Codes: +// * ErrCodeArgumentException "ArgumentException" +// An invalid argument was specified. +// +// * ErrCodeNotFoundException "NotFoundException" +// The specified entity was not found. +// +// * ErrCodeLimitExceededException "LimitExceededException" +// A limit was exceeded. +// +// * ErrCodeServiceAccountException "ServiceAccountException" +// There was a problem with the service account. +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/StopRun +func (c *DeviceFarm) StopRun(input *StopRunInput) (*StopRunOutput, error) { + req, out := c.StopRunRequest(input) + return out, req.Send() +} + +// StopRunWithContext is the same as StopRun with the addition of +// the ability to pass a context and additional request options. +// +// See StopRun 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 *DeviceFarm) StopRunWithContext(ctx aws.Context, input *StopRunInput, opts ...request.Option) (*StopRunOutput, error) { + req, out := c.StopRunRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opUpdateDevicePool = "UpdateDevicePool" + +// UpdateDevicePoolRequest generates a "aws/request.Request" representing the +// client's request for the UpdateDevicePool operation. The "output" return +// value can be used to capture response data after the request's "Send" method +// is called. +// +// See UpdateDevicePool for usage and error information. +// +// Creating a request object using this method should be used when you want to inject +// custom logic into the request's lifecycle using a custom handler, or if you want to +// access properties on the request object before or after sending the request. If +// you just want the service response, call the UpdateDevicePool method directly +// instead. +// +// Note: You must call the "Send" method on the returned request object in order +// to execute the request. +// +// // Example sending a request using the UpdateDevicePoolRequest method. +// req, resp := client.UpdateDevicePoolRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/UpdateDevicePool +func (c *DeviceFarm) UpdateDevicePoolRequest(input *UpdateDevicePoolInput) (req *request.Request, output *UpdateDevicePoolOutput) { + op := &request.Operation{ + Name: opUpdateDevicePool, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &UpdateDevicePoolInput{} + } + + output = &UpdateDevicePoolOutput{} + req = c.newRequest(op, input, output) + return +} + +// UpdateDevicePool API operation for AWS Device Farm. +// +// Modifies the name, description, and rules in a device pool given the attributes +// and the pool ARN. Rule updates are all-or-nothing, meaning they can only +// be updated as a whole (or not at all). +// +// 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 Device Farm's +// API operation UpdateDevicePool for usage and error information. +// +// Returned Error Codes: +// * ErrCodeArgumentException "ArgumentException" +// An invalid argument was specified. +// +// * ErrCodeNotFoundException "NotFoundException" +// The specified entity was not found. +// +// * ErrCodeLimitExceededException "LimitExceededException" +// A limit was exceeded. +// +// * ErrCodeServiceAccountException "ServiceAccountException" +// There was a problem with the service account. +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/UpdateDevicePool +func (c *DeviceFarm) UpdateDevicePool(input *UpdateDevicePoolInput) (*UpdateDevicePoolOutput, error) { + req, out := c.UpdateDevicePoolRequest(input) + return out, req.Send() +} + +// UpdateDevicePoolWithContext is the same as UpdateDevicePool with the addition of +// the ability to pass a context and additional request options. +// +// See UpdateDevicePool 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 *DeviceFarm) UpdateDevicePoolWithContext(ctx aws.Context, input *UpdateDevicePoolInput, opts ...request.Option) (*UpdateDevicePoolOutput, error) { + req, out := c.UpdateDevicePoolRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opUpdateNetworkProfile = "UpdateNetworkProfile" + +// UpdateNetworkProfileRequest generates a "aws/request.Request" representing the +// client's request for the UpdateNetworkProfile operation. The "output" return +// value can be used to capture response data after the request's "Send" method +// is called. +// +// See UpdateNetworkProfile for usage and error information. +// +// Creating a request object using this method should be used when you want to inject +// custom logic into the request's lifecycle using a custom handler, or if you want to +// access properties on the request object before or after sending the request. If +// you just want the service response, call the UpdateNetworkProfile method directly +// instead. +// +// Note: You must call the "Send" method on the returned request object in order +// to execute the request. +// +// // Example sending a request using the UpdateNetworkProfileRequest method. +// req, resp := client.UpdateNetworkProfileRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/UpdateNetworkProfile +func (c *DeviceFarm) UpdateNetworkProfileRequest(input *UpdateNetworkProfileInput) (req *request.Request, output *UpdateNetworkProfileOutput) { + op := &request.Operation{ + Name: opUpdateNetworkProfile, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &UpdateNetworkProfileInput{} + } + + output = &UpdateNetworkProfileOutput{} + req = c.newRequest(op, input, output) + return +} + +// UpdateNetworkProfile API operation for AWS Device Farm. +// +// Updates the network profile with specific settings. +// +// 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 Device Farm's +// API operation UpdateNetworkProfile for usage and error information. +// +// Returned Error Codes: +// * ErrCodeArgumentException "ArgumentException" +// An invalid argument was specified. +// +// * ErrCodeNotFoundException "NotFoundException" +// The specified entity was not found. +// +// * ErrCodeLimitExceededException "LimitExceededException" +// A limit was exceeded. +// +// * ErrCodeServiceAccountException "ServiceAccountException" +// There was a problem with the service account. +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/UpdateNetworkProfile +func (c *DeviceFarm) UpdateNetworkProfile(input *UpdateNetworkProfileInput) (*UpdateNetworkProfileOutput, error) { + req, out := c.UpdateNetworkProfileRequest(input) + return out, req.Send() +} + +// UpdateNetworkProfileWithContext is the same as UpdateNetworkProfile with the addition of +// the ability to pass a context and additional request options. +// +// See UpdateNetworkProfile 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 *DeviceFarm) UpdateNetworkProfileWithContext(ctx aws.Context, input *UpdateNetworkProfileInput, opts ...request.Option) (*UpdateNetworkProfileOutput, error) { + req, out := c.UpdateNetworkProfileRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opUpdateProject = "UpdateProject" + +// UpdateProjectRequest generates a "aws/request.Request" representing the +// client's request for the UpdateProject operation. The "output" return +// value can be used to capture response data after the request's "Send" method +// is called. +// +// See UpdateProject for usage and error information. +// +// Creating a request object using this method should be used when you want to inject +// custom logic into the request's lifecycle using a custom handler, or if you want to +// access properties on the request object before or after sending the request. If +// you just want the service response, call the UpdateProject method directly +// instead. +// +// Note: You must call the "Send" method on the returned request object in order +// to execute the request. +// +// // Example sending a request using the UpdateProjectRequest method. +// req, resp := client.UpdateProjectRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/UpdateProject +func (c *DeviceFarm) UpdateProjectRequest(input *UpdateProjectInput) (req *request.Request, output *UpdateProjectOutput) { + op := &request.Operation{ + Name: opUpdateProject, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &UpdateProjectInput{} + } + + output = &UpdateProjectOutput{} + req = c.newRequest(op, input, output) + return +} + +// UpdateProject API operation for AWS Device Farm. +// +// Modifies the specified project name, given the project ARN and a new name. +// +// 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 Device Farm's +// API operation UpdateProject for usage and error information. +// +// Returned Error Codes: +// * ErrCodeArgumentException "ArgumentException" +// An invalid argument was specified. +// +// * ErrCodeNotFoundException "NotFoundException" +// The specified entity was not found. +// +// * ErrCodeLimitExceededException "LimitExceededException" +// A limit was exceeded. +// +// * ErrCodeServiceAccountException "ServiceAccountException" +// There was a problem with the service account. +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/UpdateProject +func (c *DeviceFarm) UpdateProject(input *UpdateProjectInput) (*UpdateProjectOutput, error) { + req, out := c.UpdateProjectRequest(input) + return out, req.Send() +} + +// UpdateProjectWithContext is the same as UpdateProject with the addition of +// the ability to pass a context and additional request options. +// +// See UpdateProject 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 *DeviceFarm) UpdateProjectWithContext(ctx aws.Context, input *UpdateProjectInput, opts ...request.Option) (*UpdateProjectOutput, error) { + req, out := c.UpdateProjectRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +// A container for account-level settings within AWS Device Farm. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/AccountSettings +type AccountSettings struct { + _ struct{} `type:"structure"` + + // The AWS account number specified in the AccountSettings container. + AwsAccountNumber *string `locationName:"awsAccountNumber" min:"2" type:"string"` + + // The default number of minutes (at the account level) a test run will execute + // before it times out. Default value is 60 minutes. + DefaultJobTimeoutMinutes *int64 `locationName:"defaultJobTimeoutMinutes" type:"integer"` + + // The maximum number of minutes a test run will execute before it times out. + MaxJobTimeoutMinutes *int64 `locationName:"maxJobTimeoutMinutes" type:"integer"` + + // The maximum number of device slots that the AWS account can purchase. Each + // maximum is expressed as an offering-id:number pair, where the offering-id + // represents one of the IDs returned by the ListOfferings command. + MaxSlots map[string]*int64 `locationName:"maxSlots" type:"map"` + + // Information about an AWS account's usage of free trial device minutes. + TrialMinutes *TrialMinutes `locationName:"trialMinutes" type:"structure"` + + // Returns the unmetered devices you have purchased or want to purchase. + UnmeteredDevices map[string]*int64 `locationName:"unmeteredDevices" type:"map"` + + // Returns the unmetered remote access devices you have purchased or want to + // purchase. + UnmeteredRemoteAccessDevices map[string]*int64 `locationName:"unmeteredRemoteAccessDevices" type:"map"` +} + +// String returns the string representation +func (s AccountSettings) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s AccountSettings) GoString() string { + return s.String() +} + +// SetAwsAccountNumber sets the AwsAccountNumber field's value. +func (s *AccountSettings) SetAwsAccountNumber(v string) *AccountSettings { + s.AwsAccountNumber = &v + return s +} + +// SetDefaultJobTimeoutMinutes sets the DefaultJobTimeoutMinutes field's value. +func (s *AccountSettings) SetDefaultJobTimeoutMinutes(v int64) *AccountSettings { + s.DefaultJobTimeoutMinutes = &v + return s +} + +// SetMaxJobTimeoutMinutes sets the MaxJobTimeoutMinutes field's value. +func (s *AccountSettings) SetMaxJobTimeoutMinutes(v int64) *AccountSettings { + s.MaxJobTimeoutMinutes = &v + return s +} + +// SetMaxSlots sets the MaxSlots field's value. +func (s *AccountSettings) SetMaxSlots(v map[string]*int64) *AccountSettings { + s.MaxSlots = v + return s +} + +// SetTrialMinutes sets the TrialMinutes field's value. +func (s *AccountSettings) SetTrialMinutes(v *TrialMinutes) *AccountSettings { + s.TrialMinutes = v + return s +} + +// SetUnmeteredDevices sets the UnmeteredDevices field's value. +func (s *AccountSettings) SetUnmeteredDevices(v map[string]*int64) *AccountSettings { + s.UnmeteredDevices = v + return s +} + +// SetUnmeteredRemoteAccessDevices sets the UnmeteredRemoteAccessDevices field's value. +func (s *AccountSettings) SetUnmeteredRemoteAccessDevices(v map[string]*int64) *AccountSettings { + s.UnmeteredRemoteAccessDevices = v + return s +} + +// Represents the output of a test. Examples of artifacts include logs and screenshots. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/Artifact +type Artifact struct { + _ struct{} `type:"structure"` + + // The artifact's ARN. + Arn *string `locationName:"arn" min:"32" type:"string"` + + // The artifact's file extension. + Extension *string `locationName:"extension" type:"string"` + + // The artifact's name. + Name *string `locationName:"name" type:"string"` + + // The artifact's type. + // + // Allowed values include the following: + // + // * UNKNOWN: An unknown type. + // + // * SCREENSHOT: The screenshot type. + // + // * DEVICE_LOG: The device log type. + // + // * MESSAGE_LOG: The message log type. + // + // * RESULT_LOG: The result log type. + // + // * SERVICE_LOG: The service log type. + // + // * WEBKIT_LOG: The web kit log type. + // + // * INSTRUMENTATION_OUTPUT: The instrumentation type. + // + // * EXERCISER_MONKEY_OUTPUT: For Android, the artifact (log) generated by + // an Android fuzz test. + // + // * CALABASH_JSON_OUTPUT: The Calabash JSON output type. + // + // * CALABASH_PRETTY_OUTPUT: The Calabash pretty output type. + // + // * CALABASH_STANDARD_OUTPUT: The Calabash standard output type. + // + // * CALABASH_JAVA_XML_OUTPUT: The Calabash Java XML output type. + // + // * AUTOMATION_OUTPUT: The automation output type. + // + // * APPIUM_SERVER_OUTPUT: The Appium server output type. + // + // * APPIUM_JAVA_OUTPUT: The Appium Java output type. + // + // * APPIUM_JAVA_XML_OUTPUT: The Appium Java XML output type. + // + // * APPIUM_PYTHON_OUTPUT: The Appium Python output type. + // + // * APPIUM_PYTHON_XML_OUTPUT: The Appium Python XML output type. + // + // * EXPLORER_EVENT_LOG: The Explorer event log output type. + // + // * EXPLORER_SUMMARY_LOG: The Explorer summary log output type. + // + // * APPLICATION_CRASH_REPORT: The application crash report output type. + // + // * XCTEST_LOG: The XCode test output type. + Type *string `locationName:"type" type:"string" enum:"ArtifactType"` + + // The pre-signed Amazon S3 URL that can be used with a corresponding GET request + // to download the artifact's file. + Url *string `locationName:"url" type:"string"` +} + +// String returns the string representation +func (s Artifact) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s Artifact) GoString() string { + return s.String() +} + +// SetArn sets the Arn field's value. +func (s *Artifact) SetArn(v string) *Artifact { + s.Arn = &v + return s +} + +// SetExtension sets the Extension field's value. +func (s *Artifact) SetExtension(v string) *Artifact { + s.Extension = &v + return s +} + +// SetName sets the Name field's value. +func (s *Artifact) SetName(v string) *Artifact { + s.Name = &v + return s +} + +// SetType sets the Type field's value. +func (s *Artifact) SetType(v string) *Artifact { + s.Type = &v + return s +} + +// SetUrl sets the Url field's value. +func (s *Artifact) SetUrl(v string) *Artifact { + s.Url = &v + return s +} + +// Represents the amount of CPU that an app is using on a physical device. +// +// Note that this does not represent system-wide CPU usage. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/CPU +type CPU struct { + _ struct{} `type:"structure"` + + // The CPU's architecture, for example x86 or ARM. + Architecture *string `locationName:"architecture" type:"string"` + + // The clock speed of the device's CPU, expressed in hertz (Hz). For example, + // a 1.2 GHz CPU is expressed as 1200000000. + Clock *float64 `locationName:"clock" type:"double"` + + // The CPU's frequency. + Frequency *string `locationName:"frequency" type:"string"` +} + +// String returns the string representation +func (s CPU) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s CPU) GoString() string { + return s.String() +} + +// SetArchitecture sets the Architecture field's value. +func (s *CPU) SetArchitecture(v string) *CPU { + s.Architecture = &v + return s +} + +// SetClock sets the Clock field's value. +func (s *CPU) SetClock(v float64) *CPU { + s.Clock = &v + return s +} + +// SetFrequency sets the Frequency field's value. +func (s *CPU) SetFrequency(v string) *CPU { + s.Frequency = &v + return s +} + +// Represents entity counters. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/Counters +type Counters struct { + _ struct{} `type:"structure"` + + // The number of errored entities. + Errored *int64 `locationName:"errored" type:"integer"` + + // The number of failed entities. + Failed *int64 `locationName:"failed" type:"integer"` + + // The number of passed entities. + Passed *int64 `locationName:"passed" type:"integer"` + + // The number of skipped entities. + Skipped *int64 `locationName:"skipped" type:"integer"` + + // The number of stopped entities. + Stopped *int64 `locationName:"stopped" type:"integer"` + + // The total number of entities. + Total *int64 `locationName:"total" type:"integer"` + + // The number of warned entities. + Warned *int64 `locationName:"warned" type:"integer"` +} + +// String returns the string representation +func (s Counters) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s Counters) GoString() string { + return s.String() +} + +// SetErrored sets the Errored field's value. +func (s *Counters) SetErrored(v int64) *Counters { + s.Errored = &v + return s +} + +// SetFailed sets the Failed field's value. +func (s *Counters) SetFailed(v int64) *Counters { + s.Failed = &v + return s +} + +// SetPassed sets the Passed field's value. +func (s *Counters) SetPassed(v int64) *Counters { + s.Passed = &v + return s +} + +// SetSkipped sets the Skipped field's value. +func (s *Counters) SetSkipped(v int64) *Counters { + s.Skipped = &v + return s +} + +// SetStopped sets the Stopped field's value. +func (s *Counters) SetStopped(v int64) *Counters { + s.Stopped = &v + return s +} + +// SetTotal sets the Total field's value. +func (s *Counters) SetTotal(v int64) *Counters { + s.Total = &v + return s +} + +// SetWarned sets the Warned field's value. +func (s *Counters) SetWarned(v int64) *Counters { + s.Warned = &v + return s +} + +// Represents a request to the create device pool operation. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/CreateDevicePoolRequest +type CreateDevicePoolInput struct { + _ struct{} `type:"structure"` + + // The device pool's description. + Description *string `locationName:"description" type:"string"` + + // The device pool's name. + // + // Name is a required field + Name *string `locationName:"name" type:"string" required:"true"` + + // The ARN of the project for the device pool. + // + // ProjectArn is a required field + ProjectArn *string `locationName:"projectArn" min:"32" type:"string" required:"true"` + + // The device pool's rules. + // + // Rules is a required field + Rules []*Rule `locationName:"rules" type:"list" required:"true"` +} + +// String returns the string representation +func (s CreateDevicePoolInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s CreateDevicePoolInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *CreateDevicePoolInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "CreateDevicePoolInput"} + if s.Name == nil { + invalidParams.Add(request.NewErrParamRequired("Name")) + } + if s.ProjectArn == nil { + invalidParams.Add(request.NewErrParamRequired("ProjectArn")) + } + if s.ProjectArn != nil && len(*s.ProjectArn) < 32 { + invalidParams.Add(request.NewErrParamMinLen("ProjectArn", 32)) + } + if s.Rules == nil { + invalidParams.Add(request.NewErrParamRequired("Rules")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetDescription sets the Description field's value. +func (s *CreateDevicePoolInput) SetDescription(v string) *CreateDevicePoolInput { + s.Description = &v + return s +} + +// SetName sets the Name field's value. +func (s *CreateDevicePoolInput) SetName(v string) *CreateDevicePoolInput { + s.Name = &v + return s +} + +// SetProjectArn sets the ProjectArn field's value. +func (s *CreateDevicePoolInput) SetProjectArn(v string) *CreateDevicePoolInput { + s.ProjectArn = &v + return s +} + +// SetRules sets the Rules field's value. +func (s *CreateDevicePoolInput) SetRules(v []*Rule) *CreateDevicePoolInput { + s.Rules = v + return s +} + +// Represents the result of a create device pool request. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/CreateDevicePoolResult +type CreateDevicePoolOutput struct { + _ struct{} `type:"structure"` + + // The newly created device pool. + DevicePool *DevicePool `locationName:"devicePool" type:"structure"` +} + +// String returns the string representation +func (s CreateDevicePoolOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s CreateDevicePoolOutput) GoString() string { + return s.String() +} + +// SetDevicePool sets the DevicePool field's value. +func (s *CreateDevicePoolOutput) SetDevicePool(v *DevicePool) *CreateDevicePoolOutput { + s.DevicePool = v + return s +} + +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/CreateNetworkProfileRequest +type CreateNetworkProfileInput struct { + _ struct{} `type:"structure"` + + // The description of the network profile. + Description *string `locationName:"description" type:"string"` + + // The data throughput rate in bits per second, as an integer from 0 to 104857600. + DownlinkBandwidthBits *int64 `locationName:"downlinkBandwidthBits" type:"long"` + + // Delay time for all packets to destination in milliseconds as an integer from + // 0 to 2000. + DownlinkDelayMs *int64 `locationName:"downlinkDelayMs" type:"long"` + + // Time variation in the delay of received packets in milliseconds as an integer + // from 0 to 2000. + DownlinkJitterMs *int64 `locationName:"downlinkJitterMs" type:"long"` + + // Proportion of received packets that fail to arrive from 0 to 100 percent. + DownlinkLossPercent *int64 `locationName:"downlinkLossPercent" type:"integer"` + + // The name you wish to specify for the new network profile. + // + // Name is a required field + Name *string `locationName:"name" type:"string" required:"true"` + + // The Amazon Resource Name (ARN) of the project for which you want to create + // a network profile. + // + // ProjectArn is a required field + ProjectArn *string `locationName:"projectArn" min:"32" type:"string" required:"true"` + + // The type of network profile you wish to create. Valid values are listed below. + Type *string `locationName:"type" type:"string" enum:"NetworkProfileType"` + + // The data throughput rate in bits per second, as an integer from 0 to 104857600. + UplinkBandwidthBits *int64 `locationName:"uplinkBandwidthBits" type:"long"` + + // Delay time for all packets to destination in milliseconds as an integer from + // 0 to 2000. + UplinkDelayMs *int64 `locationName:"uplinkDelayMs" type:"long"` + + // Time variation in the delay of received packets in milliseconds as an integer + // from 0 to 2000. + UplinkJitterMs *int64 `locationName:"uplinkJitterMs" type:"long"` + + // Proportion of transmitted packets that fail to arrive from 0 to 100 percent. + UplinkLossPercent *int64 `locationName:"uplinkLossPercent" type:"integer"` +} + +// String returns the string representation +func (s CreateNetworkProfileInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s CreateNetworkProfileInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *CreateNetworkProfileInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "CreateNetworkProfileInput"} + if s.Name == nil { + invalidParams.Add(request.NewErrParamRequired("Name")) + } + if s.ProjectArn == nil { + invalidParams.Add(request.NewErrParamRequired("ProjectArn")) + } + if s.ProjectArn != nil && len(*s.ProjectArn) < 32 { + invalidParams.Add(request.NewErrParamMinLen("ProjectArn", 32)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetDescription sets the Description field's value. +func (s *CreateNetworkProfileInput) SetDescription(v string) *CreateNetworkProfileInput { + s.Description = &v + return s +} + +// SetDownlinkBandwidthBits sets the DownlinkBandwidthBits field's value. +func (s *CreateNetworkProfileInput) SetDownlinkBandwidthBits(v int64) *CreateNetworkProfileInput { + s.DownlinkBandwidthBits = &v + return s +} + +// SetDownlinkDelayMs sets the DownlinkDelayMs field's value. +func (s *CreateNetworkProfileInput) SetDownlinkDelayMs(v int64) *CreateNetworkProfileInput { + s.DownlinkDelayMs = &v + return s +} + +// SetDownlinkJitterMs sets the DownlinkJitterMs field's value. +func (s *CreateNetworkProfileInput) SetDownlinkJitterMs(v int64) *CreateNetworkProfileInput { + s.DownlinkJitterMs = &v + return s +} + +// SetDownlinkLossPercent sets the DownlinkLossPercent field's value. +func (s *CreateNetworkProfileInput) SetDownlinkLossPercent(v int64) *CreateNetworkProfileInput { + s.DownlinkLossPercent = &v + return s +} + +// SetName sets the Name field's value. +func (s *CreateNetworkProfileInput) SetName(v string) *CreateNetworkProfileInput { + s.Name = &v + return s +} + +// SetProjectArn sets the ProjectArn field's value. +func (s *CreateNetworkProfileInput) SetProjectArn(v string) *CreateNetworkProfileInput { + s.ProjectArn = &v + return s +} + +// SetType sets the Type field's value. +func (s *CreateNetworkProfileInput) SetType(v string) *CreateNetworkProfileInput { + s.Type = &v + return s +} + +// SetUplinkBandwidthBits sets the UplinkBandwidthBits field's value. +func (s *CreateNetworkProfileInput) SetUplinkBandwidthBits(v int64) *CreateNetworkProfileInput { + s.UplinkBandwidthBits = &v + return s +} + +// SetUplinkDelayMs sets the UplinkDelayMs field's value. +func (s *CreateNetworkProfileInput) SetUplinkDelayMs(v int64) *CreateNetworkProfileInput { + s.UplinkDelayMs = &v + return s +} + +// SetUplinkJitterMs sets the UplinkJitterMs field's value. +func (s *CreateNetworkProfileInput) SetUplinkJitterMs(v int64) *CreateNetworkProfileInput { + s.UplinkJitterMs = &v + return s +} + +// SetUplinkLossPercent sets the UplinkLossPercent field's value. +func (s *CreateNetworkProfileInput) SetUplinkLossPercent(v int64) *CreateNetworkProfileInput { + s.UplinkLossPercent = &v + return s +} + +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/CreateNetworkProfileResult +type CreateNetworkProfileOutput struct { + _ struct{} `type:"structure"` + + // The network profile that is returned by the create network profile request. + NetworkProfile *NetworkProfile `locationName:"networkProfile" type:"structure"` +} + +// String returns the string representation +func (s CreateNetworkProfileOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s CreateNetworkProfileOutput) GoString() string { + return s.String() +} + +// SetNetworkProfile sets the NetworkProfile field's value. +func (s *CreateNetworkProfileOutput) SetNetworkProfile(v *NetworkProfile) *CreateNetworkProfileOutput { + s.NetworkProfile = v + return s +} + +// Represents a request to the create project operation. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/CreateProjectRequest +type CreateProjectInput struct { + _ struct{} `type:"structure"` + + // Sets the execution timeout value (in minutes) for a project. All test runs + // in this project will use the specified execution timeout value unless overridden + // when scheduling a run. + DefaultJobTimeoutMinutes *int64 `locationName:"defaultJobTimeoutMinutes" type:"integer"` + + // The project's name. + // + // Name is a required field + Name *string `locationName:"name" type:"string" required:"true"` +} + +// String returns the string representation +func (s CreateProjectInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s CreateProjectInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *CreateProjectInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "CreateProjectInput"} + if s.Name == nil { + invalidParams.Add(request.NewErrParamRequired("Name")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetDefaultJobTimeoutMinutes sets the DefaultJobTimeoutMinutes field's value. +func (s *CreateProjectInput) SetDefaultJobTimeoutMinutes(v int64) *CreateProjectInput { + s.DefaultJobTimeoutMinutes = &v + return s +} + +// SetName sets the Name field's value. +func (s *CreateProjectInput) SetName(v string) *CreateProjectInput { + s.Name = &v + return s +} + +// Represents the result of a create project request. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/CreateProjectResult +type CreateProjectOutput struct { + _ struct{} `type:"structure"` + + // The newly created project. + Project *Project `locationName:"project" type:"structure"` +} + +// String returns the string representation +func (s CreateProjectOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s CreateProjectOutput) GoString() string { + return s.String() +} + +// SetProject sets the Project field's value. +func (s *CreateProjectOutput) SetProject(v *Project) *CreateProjectOutput { + s.Project = v + return s +} + +// Creates the configuration settings for a remote access session, including +// the device model and type. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/CreateRemoteAccessSessionConfiguration +type CreateRemoteAccessSessionConfiguration struct { + _ struct{} `type:"structure"` + + // Returns the billing method for purposes of configuring a remote access session. + BillingMethod *string `locationName:"billingMethod" type:"string" enum:"BillingMethod"` +} + +// String returns the string representation +func (s CreateRemoteAccessSessionConfiguration) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s CreateRemoteAccessSessionConfiguration) GoString() string { + return s.String() +} + +// SetBillingMethod sets the BillingMethod field's value. +func (s *CreateRemoteAccessSessionConfiguration) SetBillingMethod(v string) *CreateRemoteAccessSessionConfiguration { + s.BillingMethod = &v + return s +} + +// Creates and submits a request to start a remote access session. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/CreateRemoteAccessSessionRequest +type CreateRemoteAccessSessionInput struct { + _ struct{} `type:"structure"` + + // The configuration information for the remote access session request. + Configuration *CreateRemoteAccessSessionConfiguration `locationName:"configuration" type:"structure"` + + // The Amazon Resource Name (ARN) of the device for which you want to create + // a remote access session. + // + // DeviceArn is a required field + DeviceArn *string `locationName:"deviceArn" min:"32" type:"string" required:"true"` + + // The name of the remote access session that you wish to create. + Name *string `locationName:"name" type:"string"` + + // The Amazon Resource Name (ARN) of the project for which you want to create + // a remote access session. + // + // ProjectArn is a required field + ProjectArn *string `locationName:"projectArn" min:"32" type:"string" required:"true"` +} + +// String returns the string representation +func (s CreateRemoteAccessSessionInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s CreateRemoteAccessSessionInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *CreateRemoteAccessSessionInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "CreateRemoteAccessSessionInput"} + if s.DeviceArn == nil { + invalidParams.Add(request.NewErrParamRequired("DeviceArn")) + } + if s.DeviceArn != nil && len(*s.DeviceArn) < 32 { + invalidParams.Add(request.NewErrParamMinLen("DeviceArn", 32)) + } + if s.ProjectArn == nil { + invalidParams.Add(request.NewErrParamRequired("ProjectArn")) + } + if s.ProjectArn != nil && len(*s.ProjectArn) < 32 { + invalidParams.Add(request.NewErrParamMinLen("ProjectArn", 32)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetConfiguration sets the Configuration field's value. +func (s *CreateRemoteAccessSessionInput) SetConfiguration(v *CreateRemoteAccessSessionConfiguration) *CreateRemoteAccessSessionInput { + s.Configuration = v + return s +} + +// SetDeviceArn sets the DeviceArn field's value. +func (s *CreateRemoteAccessSessionInput) SetDeviceArn(v string) *CreateRemoteAccessSessionInput { + s.DeviceArn = &v + return s +} + +// SetName sets the Name field's value. +func (s *CreateRemoteAccessSessionInput) SetName(v string) *CreateRemoteAccessSessionInput { + s.Name = &v + return s +} + +// SetProjectArn sets the ProjectArn field's value. +func (s *CreateRemoteAccessSessionInput) SetProjectArn(v string) *CreateRemoteAccessSessionInput { + s.ProjectArn = &v + return s +} + +// Represents the server response from a request to create a remote access session. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/CreateRemoteAccessSessionResult +type CreateRemoteAccessSessionOutput struct { + _ struct{} `type:"structure"` + + // A container that describes the remote access session when the request to + // create a remote access session is sent. + RemoteAccessSession *RemoteAccessSession `locationName:"remoteAccessSession" type:"structure"` +} + +// String returns the string representation +func (s CreateRemoteAccessSessionOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s CreateRemoteAccessSessionOutput) GoString() string { + return s.String() +} + +// SetRemoteAccessSession sets the RemoteAccessSession field's value. +func (s *CreateRemoteAccessSessionOutput) SetRemoteAccessSession(v *RemoteAccessSession) *CreateRemoteAccessSessionOutput { + s.RemoteAccessSession = v + return s +} + +// Represents a request to the create upload operation. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/CreateUploadRequest +type CreateUploadInput struct { + _ struct{} `type:"structure"` + + // The upload's content type (for example, "application/octet-stream"). + ContentType *string `locationName:"contentType" type:"string"` + + // The upload's file name. The name should not contain the '/' character. If + // uploading an iOS app, the file name needs to end with the .ipa extension. + // If uploading an Android app, the file name needs to end with the .apk extension. + // For all others, the file name must end with the .zip file extension. + // + // Name is a required field + Name *string `locationName:"name" type:"string" required:"true"` + + // The ARN of the project for the upload. + // + // ProjectArn is a required field + ProjectArn *string `locationName:"projectArn" min:"32" type:"string" required:"true"` + + // The upload's upload type. + // + // Must be one of the following values: + // + // * ANDROID_APP: An Android upload. + // + // * IOS_APP: An iOS upload. + // + // * WEB_APP: A web appliction upload. + // + // * EXTERNAL_DATA: An external data upload. + // + // * APPIUM_JAVA_JUNIT_TEST_PACKAGE: An Appium Java JUnit test package upload. + // + // * APPIUM_JAVA_TESTNG_TEST_PACKAGE: An Appium Java TestNG test package + // upload. + // + // * APPIUM_PYTHON_TEST_PACKAGE: An Appium Python test package upload. + // + // * APPIUM_WEB_JAVA_JUNIT_TEST_PACKAGE: An Appium Java JUnit test package + // upload. + // + // * APPIUM_WEB_JAVA_TESTNG_TEST_PACKAGE: An Appium Java TestNG test package + // upload. + // + // * APPIUM_WEB_PYTHON_TEST_PACKAGE: An Appium Python test package upload. + // + // * CALABASH_TEST_PACKAGE: A Calabash test package upload. + // + // * INSTRUMENTATION_TEST_PACKAGE: An instrumentation upload. + // + // * UIAUTOMATION_TEST_PACKAGE: A uiautomation test package upload. + // + // * UIAUTOMATOR_TEST_PACKAGE: A uiautomator test package upload. + // + // * XCTEST_TEST_PACKAGE: An XCode test package upload. + // + // * XCTEST_UI_TEST_PACKAGE: An XCode UI test package upload. + // + // Note If you call CreateUpload with WEB_APP specified, AWS Device Farm throws + // an ArgumentException error. + // + // Type is a required field + Type *string `locationName:"type" type:"string" required:"true" enum:"UploadType"` +} + +// String returns the string representation +func (s CreateUploadInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s CreateUploadInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *CreateUploadInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "CreateUploadInput"} + if s.Name == nil { + invalidParams.Add(request.NewErrParamRequired("Name")) + } + if s.ProjectArn == nil { + invalidParams.Add(request.NewErrParamRequired("ProjectArn")) + } + if s.ProjectArn != nil && len(*s.ProjectArn) < 32 { + invalidParams.Add(request.NewErrParamMinLen("ProjectArn", 32)) + } + if s.Type == nil { + invalidParams.Add(request.NewErrParamRequired("Type")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetContentType sets the ContentType field's value. +func (s *CreateUploadInput) SetContentType(v string) *CreateUploadInput { + s.ContentType = &v + return s +} + +// SetName sets the Name field's value. +func (s *CreateUploadInput) SetName(v string) *CreateUploadInput { + s.Name = &v + return s +} + +// SetProjectArn sets the ProjectArn field's value. +func (s *CreateUploadInput) SetProjectArn(v string) *CreateUploadInput { + s.ProjectArn = &v + return s +} + +// SetType sets the Type field's value. +func (s *CreateUploadInput) SetType(v string) *CreateUploadInput { + s.Type = &v + return s +} + +// Represents the result of a create upload request. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/CreateUploadResult +type CreateUploadOutput struct { + _ struct{} `type:"structure"` + + // The newly created upload. + Upload *Upload `locationName:"upload" type:"structure"` +} + +// String returns the string representation +func (s CreateUploadOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s CreateUploadOutput) GoString() string { + return s.String() +} + +// SetUpload sets the Upload field's value. +func (s *CreateUploadOutput) SetUpload(v *Upload) *CreateUploadOutput { + s.Upload = v + return s +} + +// Represents a request to the delete device pool operation. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/DeleteDevicePoolRequest +type DeleteDevicePoolInput struct { + _ struct{} `type:"structure"` + + // Represents the Amazon Resource Name (ARN) of the Device Farm device pool + // you wish to delete. + // + // Arn is a required field + Arn *string `locationName:"arn" min:"32" type:"string" required:"true"` +} + +// String returns the string representation +func (s DeleteDevicePoolInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DeleteDevicePoolInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *DeleteDevicePoolInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DeleteDevicePoolInput"} + if s.Arn == nil { + invalidParams.Add(request.NewErrParamRequired("Arn")) + } + if s.Arn != nil && len(*s.Arn) < 32 { + invalidParams.Add(request.NewErrParamMinLen("Arn", 32)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetArn sets the Arn field's value. +func (s *DeleteDevicePoolInput) SetArn(v string) *DeleteDevicePoolInput { + s.Arn = &v + return s +} + +// Represents the result of a delete device pool request. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/DeleteDevicePoolResult +type DeleteDevicePoolOutput struct { + _ struct{} `type:"structure"` +} + +// String returns the string representation +func (s DeleteDevicePoolOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DeleteDevicePoolOutput) GoString() string { + return s.String() +} + +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/DeleteNetworkProfileRequest +type DeleteNetworkProfileInput struct { + _ struct{} `type:"structure"` + + // The Amazon Resource Name (ARN) of the network profile you want to delete. + // + // Arn is a required field + Arn *string `locationName:"arn" min:"32" type:"string" required:"true"` +} + +// String returns the string representation +func (s DeleteNetworkProfileInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DeleteNetworkProfileInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *DeleteNetworkProfileInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DeleteNetworkProfileInput"} + if s.Arn == nil { + invalidParams.Add(request.NewErrParamRequired("Arn")) + } + if s.Arn != nil && len(*s.Arn) < 32 { + invalidParams.Add(request.NewErrParamMinLen("Arn", 32)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetArn sets the Arn field's value. +func (s *DeleteNetworkProfileInput) SetArn(v string) *DeleteNetworkProfileInput { + s.Arn = &v + return s +} + +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/DeleteNetworkProfileResult +type DeleteNetworkProfileOutput struct { + _ struct{} `type:"structure"` +} + +// String returns the string representation +func (s DeleteNetworkProfileOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DeleteNetworkProfileOutput) GoString() string { + return s.String() +} + +// Represents a request to the delete project operation. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/DeleteProjectRequest +type DeleteProjectInput struct { + _ struct{} `type:"structure"` + + // Represents the Amazon Resource Name (ARN) of the Device Farm project you + // wish to delete. + // + // Arn is a required field + Arn *string `locationName:"arn" min:"32" type:"string" required:"true"` +} + +// String returns the string representation +func (s DeleteProjectInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DeleteProjectInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *DeleteProjectInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DeleteProjectInput"} + if s.Arn == nil { + invalidParams.Add(request.NewErrParamRequired("Arn")) + } + if s.Arn != nil && len(*s.Arn) < 32 { + invalidParams.Add(request.NewErrParamMinLen("Arn", 32)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetArn sets the Arn field's value. +func (s *DeleteProjectInput) SetArn(v string) *DeleteProjectInput { + s.Arn = &v + return s +} + +// Represents the result of a delete project request. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/DeleteProjectResult +type DeleteProjectOutput struct { + _ struct{} `type:"structure"` +} + +// String returns the string representation +func (s DeleteProjectOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DeleteProjectOutput) GoString() string { + return s.String() +} + +// Represents the request to delete the specified remote access session. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/DeleteRemoteAccessSessionRequest +type DeleteRemoteAccessSessionInput struct { + _ struct{} `type:"structure"` + + // The Amazon Resource Name (ARN) of the sesssion for which you want to delete + // remote access. + // + // Arn is a required field + Arn *string `locationName:"arn" min:"32" type:"string" required:"true"` +} + +// String returns the string representation +func (s DeleteRemoteAccessSessionInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DeleteRemoteAccessSessionInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *DeleteRemoteAccessSessionInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DeleteRemoteAccessSessionInput"} + if s.Arn == nil { + invalidParams.Add(request.NewErrParamRequired("Arn")) + } + if s.Arn != nil && len(*s.Arn) < 32 { + invalidParams.Add(request.NewErrParamMinLen("Arn", 32)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetArn sets the Arn field's value. +func (s *DeleteRemoteAccessSessionInput) SetArn(v string) *DeleteRemoteAccessSessionInput { + s.Arn = &v + return s +} + +// The response from the server when a request is made to delete the remote +// access session. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/DeleteRemoteAccessSessionResult +type DeleteRemoteAccessSessionOutput struct { + _ struct{} `type:"structure"` +} + +// String returns the string representation +func (s DeleteRemoteAccessSessionOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DeleteRemoteAccessSessionOutput) GoString() string { + return s.String() +} + +// Represents a request to the delete run operation. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/DeleteRunRequest +type DeleteRunInput struct { + _ struct{} `type:"structure"` + + // The Amazon Resource Name (ARN) for the run you wish to delete. + // + // Arn is a required field + Arn *string `locationName:"arn" min:"32" type:"string" required:"true"` +} + +// String returns the string representation +func (s DeleteRunInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DeleteRunInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *DeleteRunInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DeleteRunInput"} + if s.Arn == nil { + invalidParams.Add(request.NewErrParamRequired("Arn")) + } + if s.Arn != nil && len(*s.Arn) < 32 { + invalidParams.Add(request.NewErrParamMinLen("Arn", 32)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetArn sets the Arn field's value. +func (s *DeleteRunInput) SetArn(v string) *DeleteRunInput { + s.Arn = &v + return s +} + +// Represents the result of a delete run request. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/DeleteRunResult +type DeleteRunOutput struct { + _ struct{} `type:"structure"` +} + +// String returns the string representation +func (s DeleteRunOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DeleteRunOutput) GoString() string { + return s.String() +} + +// Represents a request to the delete upload operation. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/DeleteUploadRequest +type DeleteUploadInput struct { + _ struct{} `type:"structure"` + + // Represents the Amazon Resource Name (ARN) of the Device Farm upload you wish + // to delete. + // + // Arn is a required field + Arn *string `locationName:"arn" min:"32" type:"string" required:"true"` +} + +// String returns the string representation +func (s DeleteUploadInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DeleteUploadInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *DeleteUploadInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DeleteUploadInput"} + if s.Arn == nil { + invalidParams.Add(request.NewErrParamRequired("Arn")) + } + if s.Arn != nil && len(*s.Arn) < 32 { + invalidParams.Add(request.NewErrParamMinLen("Arn", 32)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetArn sets the Arn field's value. +func (s *DeleteUploadInput) SetArn(v string) *DeleteUploadInput { + s.Arn = &v + return s +} + +// Represents the result of a delete upload request. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/DeleteUploadResult +type DeleteUploadOutput struct { + _ struct{} `type:"structure"` +} + +// String returns the string representation +func (s DeleteUploadOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DeleteUploadOutput) GoString() string { + return s.String() +} + +// Represents a device type that an app is tested against. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/Device +type Device struct { + _ struct{} `type:"structure"` + + // The device's ARN. + Arn *string `locationName:"arn" min:"32" type:"string"` + + // The device's carrier. + Carrier *string `locationName:"carrier" type:"string"` + + // Information about the device's CPU. + Cpu *CPU `locationName:"cpu" type:"structure"` + + // The name of the fleet to which this device belongs. + FleetName *string `locationName:"fleetName" type:"string"` + + // The type of fleet to which this device belongs. Possible values for fleet + // type are PRIVATE and PUBLIC. + FleetType *string `locationName:"fleetType" type:"string"` + + // The device's form factor. + // + // Allowed values include: + // + // * PHONE: The phone form factor. + // + // * TABLET: The tablet form factor. + FormFactor *string `locationName:"formFactor" type:"string" enum:"DeviceFormFactor"` + + // The device's heap size, expressed in bytes. + HeapSize *int64 `locationName:"heapSize" type:"long"` + + // The device's image name. + Image *string `locationName:"image" type:"string"` + + // The device's manufacturer name. + Manufacturer *string `locationName:"manufacturer" type:"string"` + + // The device's total memory size, expressed in bytes. + Memory *int64 `locationName:"memory" type:"long"` + + // The device's model name. + Model *string `locationName:"model" type:"string"` + + // The device's display name. + Name *string `locationName:"name" type:"string"` + + // The device's operating system type. + Os *string `locationName:"os" type:"string"` + + // The device's platform. + // + // Allowed values include: + // + // * ANDROID: The Android platform. + // + // * IOS: The iOS platform. + Platform *string `locationName:"platform" type:"string" enum:"DevicePlatform"` + + // The device's radio. + Radio *string `locationName:"radio" type:"string"` + + // Specifies whether remote access has been enabled for the specified device. + RemoteAccessEnabled *bool `locationName:"remoteAccessEnabled" type:"boolean"` + + // The resolution of the device. + Resolution *Resolution `locationName:"resolution" type:"structure"` +} + +// String returns the string representation +func (s Device) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s Device) GoString() string { + return s.String() +} + +// SetArn sets the Arn field's value. +func (s *Device) SetArn(v string) *Device { + s.Arn = &v + return s +} + +// SetCarrier sets the Carrier field's value. +func (s *Device) SetCarrier(v string) *Device { + s.Carrier = &v + return s +} + +// SetCpu sets the Cpu field's value. +func (s *Device) SetCpu(v *CPU) *Device { + s.Cpu = v + return s +} + +// SetFleetName sets the FleetName field's value. +func (s *Device) SetFleetName(v string) *Device { + s.FleetName = &v + return s +} + +// SetFleetType sets the FleetType field's value. +func (s *Device) SetFleetType(v string) *Device { + s.FleetType = &v + return s +} + +// SetFormFactor sets the FormFactor field's value. +func (s *Device) SetFormFactor(v string) *Device { + s.FormFactor = &v + return s +} + +// SetHeapSize sets the HeapSize field's value. +func (s *Device) SetHeapSize(v int64) *Device { + s.HeapSize = &v + return s +} + +// SetImage sets the Image field's value. +func (s *Device) SetImage(v string) *Device { + s.Image = &v + return s +} + +// SetManufacturer sets the Manufacturer field's value. +func (s *Device) SetManufacturer(v string) *Device { + s.Manufacturer = &v + return s +} + +// SetMemory sets the Memory field's value. +func (s *Device) SetMemory(v int64) *Device { + s.Memory = &v + return s +} + +// SetModel sets the Model field's value. +func (s *Device) SetModel(v string) *Device { + s.Model = &v + return s +} + +// SetName sets the Name field's value. +func (s *Device) SetName(v string) *Device { + s.Name = &v + return s +} + +// SetOs sets the Os field's value. +func (s *Device) SetOs(v string) *Device { + s.Os = &v + return s +} + +// SetPlatform sets the Platform field's value. +func (s *Device) SetPlatform(v string) *Device { + s.Platform = &v + return s +} + +// SetRadio sets the Radio field's value. +func (s *Device) SetRadio(v string) *Device { + s.Radio = &v + return s +} + +// SetRemoteAccessEnabled sets the RemoteAccessEnabled field's value. +func (s *Device) SetRemoteAccessEnabled(v bool) *Device { + s.RemoteAccessEnabled = &v + return s +} + +// SetResolution sets the Resolution field's value. +func (s *Device) SetResolution(v *Resolution) *Device { + s.Resolution = v + return s +} + +// Represents the total (metered or unmetered) minutes used by the resource +// to run tests. Contains the sum of minutes consumed by all children. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/DeviceMinutes +type DeviceMinutes struct { + _ struct{} `type:"structure"` + + // When specified, represents only the sum of metered minutes used by the resource + // to run tests. + Metered *float64 `locationName:"metered" type:"double"` + + // When specified, represents the total minutes used by the resource to run + // tests. + Total *float64 `locationName:"total" type:"double"` + + // When specified, represents only the sum of unmetered minutes used by the + // resource to run tests. + Unmetered *float64 `locationName:"unmetered" type:"double"` +} + +// String returns the string representation +func (s DeviceMinutes) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DeviceMinutes) GoString() string { + return s.String() +} + +// SetMetered sets the Metered field's value. +func (s *DeviceMinutes) SetMetered(v float64) *DeviceMinutes { + s.Metered = &v + return s +} + +// SetTotal sets the Total field's value. +func (s *DeviceMinutes) SetTotal(v float64) *DeviceMinutes { + s.Total = &v + return s +} + +// SetUnmetered sets the Unmetered field's value. +func (s *DeviceMinutes) SetUnmetered(v float64) *DeviceMinutes { + s.Unmetered = &v + return s +} + +// Represents a collection of device types. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/DevicePool +type DevicePool struct { + _ struct{} `type:"structure"` + + // The device pool's ARN. + Arn *string `locationName:"arn" min:"32" type:"string"` + + // The device pool's description. + Description *string `locationName:"description" type:"string"` + + // The device pool's name. + Name *string `locationName:"name" type:"string"` + + // Information about the device pool's rules. + Rules []*Rule `locationName:"rules" type:"list"` + + // The device pool's type. + // + // Allowed values include: + // + // * CURATED: A device pool that is created and managed by AWS Device Farm. + // + // * PRIVATE: A device pool that is created and managed by the device pool + // developer. + Type *string `locationName:"type" type:"string" enum:"DevicePoolType"` +} + +// String returns the string representation +func (s DevicePool) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DevicePool) GoString() string { + return s.String() +} + +// SetArn sets the Arn field's value. +func (s *DevicePool) SetArn(v string) *DevicePool { + s.Arn = &v + return s +} + +// SetDescription sets the Description field's value. +func (s *DevicePool) SetDescription(v string) *DevicePool { + s.Description = &v + return s +} + +// SetName sets the Name field's value. +func (s *DevicePool) SetName(v string) *DevicePool { + s.Name = &v + return s +} + +// SetRules sets the Rules field's value. +func (s *DevicePool) SetRules(v []*Rule) *DevicePool { + s.Rules = v + return s +} + +// SetType sets the Type field's value. +func (s *DevicePool) SetType(v string) *DevicePool { + s.Type = &v + return s +} + +// Represents a device pool compatibility result. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/DevicePoolCompatibilityResult +type DevicePoolCompatibilityResult struct { + _ struct{} `type:"structure"` + + // Whether the result was compatible with the device pool. + Compatible *bool `locationName:"compatible" type:"boolean"` + + // The device (phone or tablet) that you wish to return information about. + Device *Device `locationName:"device" type:"structure"` + + // Information about the compatibility. + IncompatibilityMessages []*IncompatibilityMessage `locationName:"incompatibilityMessages" type:"list"` +} + +// String returns the string representation +func (s DevicePoolCompatibilityResult) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DevicePoolCompatibilityResult) GoString() string { + return s.String() +} + +// SetCompatible sets the Compatible field's value. +func (s *DevicePoolCompatibilityResult) SetCompatible(v bool) *DevicePoolCompatibilityResult { + s.Compatible = &v + return s +} + +// SetDevice sets the Device field's value. +func (s *DevicePoolCompatibilityResult) SetDevice(v *Device) *DevicePoolCompatibilityResult { + s.Device = v + return s +} + +// SetIncompatibilityMessages sets the IncompatibilityMessages field's value. +func (s *DevicePoolCompatibilityResult) SetIncompatibilityMessages(v []*IncompatibilityMessage) *DevicePoolCompatibilityResult { + s.IncompatibilityMessages = v + return s +} + +// Represents configuration information about a test run, such as the execution +// timeout (in minutes). +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/ExecutionConfiguration +type ExecutionConfiguration struct { + _ struct{} `type:"structure"` + + // True if account cleanup is enabled at the beginning of the test; otherwise, + // false. + AccountsCleanup *bool `locationName:"accountsCleanup" type:"boolean"` + + // True if app package cleanup is enabled at the beginning of the test; otherwise, + // false. + AppPackagesCleanup *bool `locationName:"appPackagesCleanup" type:"boolean"` + + // The number of minutes a test run will execute before it times out. + JobTimeoutMinutes *int64 `locationName:"jobTimeoutMinutes" type:"integer"` +} + +// String returns the string representation +func (s ExecutionConfiguration) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ExecutionConfiguration) GoString() string { + return s.String() +} + +// SetAccountsCleanup sets the AccountsCleanup field's value. +func (s *ExecutionConfiguration) SetAccountsCleanup(v bool) *ExecutionConfiguration { + s.AccountsCleanup = &v + return s +} + +// SetAppPackagesCleanup sets the AppPackagesCleanup field's value. +func (s *ExecutionConfiguration) SetAppPackagesCleanup(v bool) *ExecutionConfiguration { + s.AppPackagesCleanup = &v + return s +} + +// SetJobTimeoutMinutes sets the JobTimeoutMinutes field's value. +func (s *ExecutionConfiguration) SetJobTimeoutMinutes(v int64) *ExecutionConfiguration { + s.JobTimeoutMinutes = &v + return s +} + +// Represents the request sent to retrieve the account settings. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/GetAccountSettingsRequest +type GetAccountSettingsInput struct { + _ struct{} `type:"structure"` +} + +// String returns the string representation +func (s GetAccountSettingsInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s GetAccountSettingsInput) GoString() string { + return s.String() +} + +// Represents the account settings return values from the GetAccountSettings +// request. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/GetAccountSettingsResult +type GetAccountSettingsOutput struct { + _ struct{} `type:"structure"` + + // The account settings. + AccountSettings *AccountSettings `locationName:"accountSettings" type:"structure"` +} + +// String returns the string representation +func (s GetAccountSettingsOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s GetAccountSettingsOutput) GoString() string { + return s.String() +} + +// SetAccountSettings sets the AccountSettings field's value. +func (s *GetAccountSettingsOutput) SetAccountSettings(v *AccountSettings) *GetAccountSettingsOutput { + s.AccountSettings = v + return s +} + +// Represents a request to the get device request. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/GetDeviceRequest +type GetDeviceInput struct { + _ struct{} `type:"structure"` + + // The device type's ARN. + // + // Arn is a required field + Arn *string `locationName:"arn" min:"32" type:"string" required:"true"` +} + +// String returns the string representation +func (s GetDeviceInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s GetDeviceInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *GetDeviceInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "GetDeviceInput"} + if s.Arn == nil { + invalidParams.Add(request.NewErrParamRequired("Arn")) + } + if s.Arn != nil && len(*s.Arn) < 32 { + invalidParams.Add(request.NewErrParamMinLen("Arn", 32)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetArn sets the Arn field's value. +func (s *GetDeviceInput) SetArn(v string) *GetDeviceInput { + s.Arn = &v + return s +} + +// Represents the result of a get device request. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/GetDeviceResult +type GetDeviceOutput struct { + _ struct{} `type:"structure"` + + // An object containing information about the requested device. + Device *Device `locationName:"device" type:"structure"` +} + +// String returns the string representation +func (s GetDeviceOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s GetDeviceOutput) GoString() string { + return s.String() +} + +// SetDevice sets the Device field's value. +func (s *GetDeviceOutput) SetDevice(v *Device) *GetDeviceOutput { + s.Device = v + return s +} + +// Represents a request to the get device pool compatibility operation. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/GetDevicePoolCompatibilityRequest +type GetDevicePoolCompatibilityInput struct { + _ struct{} `type:"structure"` + + // The ARN of the app that is associated with the specified device pool. + AppArn *string `locationName:"appArn" min:"32" type:"string"` + + // The device pool's ARN. + // + // DevicePoolArn is a required field + DevicePoolArn *string `locationName:"devicePoolArn" min:"32" type:"string" required:"true"` + + // Information about the uploaded test to be run against the device pool. + Test *ScheduleRunTest `locationName:"test" type:"structure"` + + // The test type for the specified device pool. + // + // Allowed values include the following: + // + // * BUILTIN_FUZZ: The built-in fuzz type. + // + // * BUILTIN_EXPLORER: For Android, an app explorer that will traverse an + // Android app, interacting with it and capturing screenshots at the same + // time. + // + // * APPIUM_JAVA_JUNIT: The Appium Java JUnit type. + // + // * APPIUM_JAVA_TESTNG: The Appium Java TestNG type. + // + // * APPIUM_PYTHON: The Appium Python type. + // + // * APPIUM_WEB_JAVA_JUNIT: The Appium Java JUnit type for Web apps. + // + // * APPIUM_WEB_JAVA_TESTNG: The Appium Java TestNG type for Web apps. + // + // * APPIUM_WEB_PYTHON: The Appium Python type for Web apps. + // + // * CALABASH: The Calabash type. + // + // * INSTRUMENTATION: The Instrumentation type. + // + // * UIAUTOMATION: The uiautomation type. + // + // * UIAUTOMATOR: The uiautomator type. + // + // * XCTEST: The XCode test type. + // + // * XCTEST_UI: The XCode UI test type. + TestType *string `locationName:"testType" type:"string" enum:"TestType"` +} + +// String returns the string representation +func (s GetDevicePoolCompatibilityInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s GetDevicePoolCompatibilityInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *GetDevicePoolCompatibilityInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "GetDevicePoolCompatibilityInput"} + if s.AppArn != nil && len(*s.AppArn) < 32 { + invalidParams.Add(request.NewErrParamMinLen("AppArn", 32)) + } + if s.DevicePoolArn == nil { + invalidParams.Add(request.NewErrParamRequired("DevicePoolArn")) + } + if s.DevicePoolArn != nil && len(*s.DevicePoolArn) < 32 { + invalidParams.Add(request.NewErrParamMinLen("DevicePoolArn", 32)) + } + if s.Test != nil { + if err := s.Test.Validate(); err != nil { + invalidParams.AddNested("Test", err.(request.ErrInvalidParams)) + } + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetAppArn sets the AppArn field's value. +func (s *GetDevicePoolCompatibilityInput) SetAppArn(v string) *GetDevicePoolCompatibilityInput { + s.AppArn = &v + return s +} + +// SetDevicePoolArn sets the DevicePoolArn field's value. +func (s *GetDevicePoolCompatibilityInput) SetDevicePoolArn(v string) *GetDevicePoolCompatibilityInput { + s.DevicePoolArn = &v + return s +} + +// SetTest sets the Test field's value. +func (s *GetDevicePoolCompatibilityInput) SetTest(v *ScheduleRunTest) *GetDevicePoolCompatibilityInput { + s.Test = v + return s +} + +// SetTestType sets the TestType field's value. +func (s *GetDevicePoolCompatibilityInput) SetTestType(v string) *GetDevicePoolCompatibilityInput { + s.TestType = &v + return s +} + +// Represents the result of describe device pool compatibility request. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/GetDevicePoolCompatibilityResult +type GetDevicePoolCompatibilityOutput struct { + _ struct{} `type:"structure"` + + // Information about compatible devices. + CompatibleDevices []*DevicePoolCompatibilityResult `locationName:"compatibleDevices" type:"list"` + + // Information about incompatible devices. + IncompatibleDevices []*DevicePoolCompatibilityResult `locationName:"incompatibleDevices" type:"list"` +} + +// String returns the string representation +func (s GetDevicePoolCompatibilityOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s GetDevicePoolCompatibilityOutput) GoString() string { + return s.String() +} + +// SetCompatibleDevices sets the CompatibleDevices field's value. +func (s *GetDevicePoolCompatibilityOutput) SetCompatibleDevices(v []*DevicePoolCompatibilityResult) *GetDevicePoolCompatibilityOutput { + s.CompatibleDevices = v + return s +} + +// SetIncompatibleDevices sets the IncompatibleDevices field's value. +func (s *GetDevicePoolCompatibilityOutput) SetIncompatibleDevices(v []*DevicePoolCompatibilityResult) *GetDevicePoolCompatibilityOutput { + s.IncompatibleDevices = v + return s +} + +// Represents a request to the get device pool operation. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/GetDevicePoolRequest +type GetDevicePoolInput struct { + _ struct{} `type:"structure"` + + // The device pool's ARN. + // + // Arn is a required field + Arn *string `locationName:"arn" min:"32" type:"string" required:"true"` +} + +// String returns the string representation +func (s GetDevicePoolInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s GetDevicePoolInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *GetDevicePoolInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "GetDevicePoolInput"} + if s.Arn == nil { + invalidParams.Add(request.NewErrParamRequired("Arn")) + } + if s.Arn != nil && len(*s.Arn) < 32 { + invalidParams.Add(request.NewErrParamMinLen("Arn", 32)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetArn sets the Arn field's value. +func (s *GetDevicePoolInput) SetArn(v string) *GetDevicePoolInput { + s.Arn = &v + return s +} + +// Represents the result of a get device pool request. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/GetDevicePoolResult +type GetDevicePoolOutput struct { + _ struct{} `type:"structure"` + + // An object containing information about the requested device pool. + DevicePool *DevicePool `locationName:"devicePool" type:"structure"` +} + +// String returns the string representation +func (s GetDevicePoolOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s GetDevicePoolOutput) GoString() string { + return s.String() +} + +// SetDevicePool sets the DevicePool field's value. +func (s *GetDevicePoolOutput) SetDevicePool(v *DevicePool) *GetDevicePoolOutput { + s.DevicePool = v + return s +} + +// Represents a request to the get job operation. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/GetJobRequest +type GetJobInput struct { + _ struct{} `type:"structure"` + + // The job's ARN. + // + // Arn is a required field + Arn *string `locationName:"arn" min:"32" type:"string" required:"true"` +} + +// String returns the string representation +func (s GetJobInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s GetJobInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *GetJobInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "GetJobInput"} + if s.Arn == nil { + invalidParams.Add(request.NewErrParamRequired("Arn")) + } + if s.Arn != nil && len(*s.Arn) < 32 { + invalidParams.Add(request.NewErrParamMinLen("Arn", 32)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetArn sets the Arn field's value. +func (s *GetJobInput) SetArn(v string) *GetJobInput { + s.Arn = &v + return s +} + +// Represents the result of a get job request. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/GetJobResult +type GetJobOutput struct { + _ struct{} `type:"structure"` + + // An object containing information about the requested job. + Job *Job `locationName:"job" type:"structure"` +} + +// String returns the string representation +func (s GetJobOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s GetJobOutput) GoString() string { + return s.String() +} + +// SetJob sets the Job field's value. +func (s *GetJobOutput) SetJob(v *Job) *GetJobOutput { + s.Job = v + return s +} + +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/GetNetworkProfileRequest +type GetNetworkProfileInput struct { + _ struct{} `type:"structure"` + + // The Amazon Resource Name (ARN) of the network profile you want to return + // information about. + // + // Arn is a required field + Arn *string `locationName:"arn" min:"32" type:"string" required:"true"` +} + +// String returns the string representation +func (s GetNetworkProfileInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s GetNetworkProfileInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *GetNetworkProfileInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "GetNetworkProfileInput"} + if s.Arn == nil { + invalidParams.Add(request.NewErrParamRequired("Arn")) + } + if s.Arn != nil && len(*s.Arn) < 32 { + invalidParams.Add(request.NewErrParamMinLen("Arn", 32)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetArn sets the Arn field's value. +func (s *GetNetworkProfileInput) SetArn(v string) *GetNetworkProfileInput { + s.Arn = &v + return s +} + +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/GetNetworkProfileResult +type GetNetworkProfileOutput struct { + _ struct{} `type:"structure"` + + // The network profile. + NetworkProfile *NetworkProfile `locationName:"networkProfile" type:"structure"` +} + +// String returns the string representation +func (s GetNetworkProfileOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s GetNetworkProfileOutput) GoString() string { + return s.String() +} + +// SetNetworkProfile sets the NetworkProfile field's value. +func (s *GetNetworkProfileOutput) SetNetworkProfile(v *NetworkProfile) *GetNetworkProfileOutput { + s.NetworkProfile = v + return s +} + +// Represents the request to retrieve the offering status for the specified +// customer or account. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/GetOfferingStatusRequest +type GetOfferingStatusInput struct { + _ struct{} `type:"structure"` + + // An identifier that was returned from the previous call to this operation, + // which can be used to return the next set of items in the list. + NextToken *string `locationName:"nextToken" min:"4" type:"string"` +} + +// String returns the string representation +func (s GetOfferingStatusInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s GetOfferingStatusInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *GetOfferingStatusInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "GetOfferingStatusInput"} + if s.NextToken != nil && len(*s.NextToken) < 4 { + invalidParams.Add(request.NewErrParamMinLen("NextToken", 4)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetNextToken sets the NextToken field's value. +func (s *GetOfferingStatusInput) SetNextToken(v string) *GetOfferingStatusInput { + s.NextToken = &v + return s +} + +// Returns the status result for a device offering. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/GetOfferingStatusResult +type GetOfferingStatusOutput struct { + _ struct{} `type:"structure"` + + // When specified, gets the offering status for the current period. + Current map[string]*OfferingStatus `locationName:"current" type:"map"` + + // When specified, gets the offering status for the next period. + NextPeriod map[string]*OfferingStatus `locationName:"nextPeriod" type:"map"` + + // An identifier that was returned from the previous call to this operation, + // which can be used to return the next set of items in the list. + NextToken *string `locationName:"nextToken" min:"4" type:"string"` +} + +// String returns the string representation +func (s GetOfferingStatusOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s GetOfferingStatusOutput) GoString() string { + return s.String() +} + +// SetCurrent sets the Current field's value. +func (s *GetOfferingStatusOutput) SetCurrent(v map[string]*OfferingStatus) *GetOfferingStatusOutput { + s.Current = v + return s +} + +// SetNextPeriod sets the NextPeriod field's value. +func (s *GetOfferingStatusOutput) SetNextPeriod(v map[string]*OfferingStatus) *GetOfferingStatusOutput { + s.NextPeriod = v + return s +} + +// SetNextToken sets the NextToken field's value. +func (s *GetOfferingStatusOutput) SetNextToken(v string) *GetOfferingStatusOutput { + s.NextToken = &v + return s +} + +// Represents a request to the get project operation. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/GetProjectRequest +type GetProjectInput struct { + _ struct{} `type:"structure"` + + // The project's ARN. + // + // Arn is a required field + Arn *string `locationName:"arn" min:"32" type:"string" required:"true"` +} + +// String returns the string representation +func (s GetProjectInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s GetProjectInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *GetProjectInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "GetProjectInput"} + if s.Arn == nil { + invalidParams.Add(request.NewErrParamRequired("Arn")) + } + if s.Arn != nil && len(*s.Arn) < 32 { + invalidParams.Add(request.NewErrParamMinLen("Arn", 32)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetArn sets the Arn field's value. +func (s *GetProjectInput) SetArn(v string) *GetProjectInput { + s.Arn = &v + return s +} + +// Represents the result of a get project request. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/GetProjectResult +type GetProjectOutput struct { + _ struct{} `type:"structure"` + + // The project you wish to get information about. + Project *Project `locationName:"project" type:"structure"` +} + +// String returns the string representation +func (s GetProjectOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s GetProjectOutput) GoString() string { + return s.String() +} + +// SetProject sets the Project field's value. +func (s *GetProjectOutput) SetProject(v *Project) *GetProjectOutput { + s.Project = v + return s +} + +// Represents the request to get information about the specified remote access +// session. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/GetRemoteAccessSessionRequest +type GetRemoteAccessSessionInput struct { + _ struct{} `type:"structure"` + + // The Amazon Resource Name (ARN) of the remote access session about which you + // want to get session information. + // + // Arn is a required field + Arn *string `locationName:"arn" min:"32" type:"string" required:"true"` +} + +// String returns the string representation +func (s GetRemoteAccessSessionInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s GetRemoteAccessSessionInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *GetRemoteAccessSessionInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "GetRemoteAccessSessionInput"} + if s.Arn == nil { + invalidParams.Add(request.NewErrParamRequired("Arn")) + } + if s.Arn != nil && len(*s.Arn) < 32 { + invalidParams.Add(request.NewErrParamMinLen("Arn", 32)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetArn sets the Arn field's value. +func (s *GetRemoteAccessSessionInput) SetArn(v string) *GetRemoteAccessSessionInput { + s.Arn = &v + return s +} + +// Represents the response from the server that lists detailed information about +// the remote access session. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/GetRemoteAccessSessionResult +type GetRemoteAccessSessionOutput struct { + _ struct{} `type:"structure"` + + // A container that lists detailed information about the remote access session. + RemoteAccessSession *RemoteAccessSession `locationName:"remoteAccessSession" type:"structure"` +} + +// String returns the string representation +func (s GetRemoteAccessSessionOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s GetRemoteAccessSessionOutput) GoString() string { + return s.String() +} + +// SetRemoteAccessSession sets the RemoteAccessSession field's value. +func (s *GetRemoteAccessSessionOutput) SetRemoteAccessSession(v *RemoteAccessSession) *GetRemoteAccessSessionOutput { + s.RemoteAccessSession = v + return s +} + +// Represents a request to the get run operation. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/GetRunRequest +type GetRunInput struct { + _ struct{} `type:"structure"` + + // The run's ARN. + // + // Arn is a required field + Arn *string `locationName:"arn" min:"32" type:"string" required:"true"` +} + +// String returns the string representation +func (s GetRunInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s GetRunInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *GetRunInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "GetRunInput"} + if s.Arn == nil { + invalidParams.Add(request.NewErrParamRequired("Arn")) + } + if s.Arn != nil && len(*s.Arn) < 32 { + invalidParams.Add(request.NewErrParamMinLen("Arn", 32)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetArn sets the Arn field's value. +func (s *GetRunInput) SetArn(v string) *GetRunInput { + s.Arn = &v + return s +} + +// Represents the result of a get run request. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/GetRunResult +type GetRunOutput struct { + _ struct{} `type:"structure"` + + // The run you wish to get results from. + Run *Run `locationName:"run" type:"structure"` +} + +// String returns the string representation +func (s GetRunOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s GetRunOutput) GoString() string { + return s.String() +} + +// SetRun sets the Run field's value. +func (s *GetRunOutput) SetRun(v *Run) *GetRunOutput { + s.Run = v + return s +} + +// Represents a request to the get suite operation. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/GetSuiteRequest +type GetSuiteInput struct { + _ struct{} `type:"structure"` + + // The suite's ARN. + // + // Arn is a required field + Arn *string `locationName:"arn" min:"32" type:"string" required:"true"` +} + +// String returns the string representation +func (s GetSuiteInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s GetSuiteInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *GetSuiteInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "GetSuiteInput"} + if s.Arn == nil { + invalidParams.Add(request.NewErrParamRequired("Arn")) + } + if s.Arn != nil && len(*s.Arn) < 32 { + invalidParams.Add(request.NewErrParamMinLen("Arn", 32)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetArn sets the Arn field's value. +func (s *GetSuiteInput) SetArn(v string) *GetSuiteInput { + s.Arn = &v + return s +} + +// Represents the result of a get suite request. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/GetSuiteResult +type GetSuiteOutput struct { + _ struct{} `type:"structure"` + + // A collection of one or more tests. + Suite *Suite `locationName:"suite" type:"structure"` +} + +// String returns the string representation +func (s GetSuiteOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s GetSuiteOutput) GoString() string { + return s.String() +} + +// SetSuite sets the Suite field's value. +func (s *GetSuiteOutput) SetSuite(v *Suite) *GetSuiteOutput { + s.Suite = v + return s +} + +// Represents a request to the get test operation. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/GetTestRequest +type GetTestInput struct { + _ struct{} `type:"structure"` + + // The test's ARN. + // + // Arn is a required field + Arn *string `locationName:"arn" min:"32" type:"string" required:"true"` +} + +// String returns the string representation +func (s GetTestInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s GetTestInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *GetTestInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "GetTestInput"} + if s.Arn == nil { + invalidParams.Add(request.NewErrParamRequired("Arn")) + } + if s.Arn != nil && len(*s.Arn) < 32 { + invalidParams.Add(request.NewErrParamMinLen("Arn", 32)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetArn sets the Arn field's value. +func (s *GetTestInput) SetArn(v string) *GetTestInput { + s.Arn = &v + return s +} + +// Represents the result of a get test request. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/GetTestResult +type GetTestOutput struct { + _ struct{} `type:"structure"` + + // A test condition that is evaluated. + Test *Test `locationName:"test" type:"structure"` +} + +// String returns the string representation +func (s GetTestOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s GetTestOutput) GoString() string { + return s.String() +} + +// SetTest sets the Test field's value. +func (s *GetTestOutput) SetTest(v *Test) *GetTestOutput { + s.Test = v + return s +} + +// Represents a request to the get upload operation. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/GetUploadRequest +type GetUploadInput struct { + _ struct{} `type:"structure"` + + // The upload's ARN. + // + // Arn is a required field + Arn *string `locationName:"arn" min:"32" type:"string" required:"true"` +} + +// String returns the string representation +func (s GetUploadInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s GetUploadInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *GetUploadInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "GetUploadInput"} + if s.Arn == nil { + invalidParams.Add(request.NewErrParamRequired("Arn")) + } + if s.Arn != nil && len(*s.Arn) < 32 { + invalidParams.Add(request.NewErrParamMinLen("Arn", 32)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetArn sets the Arn field's value. +func (s *GetUploadInput) SetArn(v string) *GetUploadInput { + s.Arn = &v + return s +} + +// Represents the result of a get upload request. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/GetUploadResult +type GetUploadOutput struct { + _ struct{} `type:"structure"` + + // An app or a set of one or more tests to upload or that have been uploaded. + Upload *Upload `locationName:"upload" type:"structure"` +} + +// String returns the string representation +func (s GetUploadOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s GetUploadOutput) GoString() string { + return s.String() +} + +// SetUpload sets the Upload field's value. +func (s *GetUploadOutput) SetUpload(v *Upload) *GetUploadOutput { + s.Upload = v + return s +} + +// Represents information about incompatibility. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/IncompatibilityMessage +type IncompatibilityMessage struct { + _ struct{} `type:"structure"` + + // A message about the incompatibility. + Message *string `locationName:"message" type:"string"` + + // The type of incompatibility. + // + // Allowed values include: + // + // * ARN: The ARN. + // + // * FORM_FACTOR: The form factor (for example, phone or tablet). + // + // * MANUFACTURER: The manufacturer. + // + // * PLATFORM: The platform (for example, Android or iOS). + // + // * REMOTE_ACCESS_ENABLED: Whether the device is enabled for remote access. + // + // * APPIUM_VERSION: The Appium version for the test. + Type *string `locationName:"type" type:"string" enum:"DeviceAttribute"` +} + +// String returns the string representation +func (s IncompatibilityMessage) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s IncompatibilityMessage) GoString() string { + return s.String() +} + +// SetMessage sets the Message field's value. +func (s *IncompatibilityMessage) SetMessage(v string) *IncompatibilityMessage { + s.Message = &v + return s +} + +// SetType sets the Type field's value. +func (s *IncompatibilityMessage) SetType(v string) *IncompatibilityMessage { + s.Type = &v + return s +} + +// Represents the request to install an Android application (in .apk format) +// or an iOS application (in .ipa format) as part of a remote access session. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/InstallToRemoteAccessSessionRequest +type InstallToRemoteAccessSessionInput struct { + _ struct{} `type:"structure"` + + // The Amazon Resource Name (ARN) of the app about which you are requesting + // information. + // + // AppArn is a required field + AppArn *string `locationName:"appArn" min:"32" type:"string" required:"true"` + + // The Amazon Resource Name (ARN) of the remote access session about which you + // are requesting information. + // + // RemoteAccessSessionArn is a required field + RemoteAccessSessionArn *string `locationName:"remoteAccessSessionArn" min:"32" type:"string" required:"true"` +} + +// String returns the string representation +func (s InstallToRemoteAccessSessionInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s InstallToRemoteAccessSessionInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *InstallToRemoteAccessSessionInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "InstallToRemoteAccessSessionInput"} + if s.AppArn == nil { + invalidParams.Add(request.NewErrParamRequired("AppArn")) + } + if s.AppArn != nil && len(*s.AppArn) < 32 { + invalidParams.Add(request.NewErrParamMinLen("AppArn", 32)) + } + if s.RemoteAccessSessionArn == nil { + invalidParams.Add(request.NewErrParamRequired("RemoteAccessSessionArn")) + } + if s.RemoteAccessSessionArn != nil && len(*s.RemoteAccessSessionArn) < 32 { + invalidParams.Add(request.NewErrParamMinLen("RemoteAccessSessionArn", 32)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetAppArn sets the AppArn field's value. +func (s *InstallToRemoteAccessSessionInput) SetAppArn(v string) *InstallToRemoteAccessSessionInput { + s.AppArn = &v + return s +} + +// SetRemoteAccessSessionArn sets the RemoteAccessSessionArn field's value. +func (s *InstallToRemoteAccessSessionInput) SetRemoteAccessSessionArn(v string) *InstallToRemoteAccessSessionInput { + s.RemoteAccessSessionArn = &v + return s +} + +// Represents the response from the server after AWS Device Farm makes a request +// to install to a remote access session. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/InstallToRemoteAccessSessionResult +type InstallToRemoteAccessSessionOutput struct { + _ struct{} `type:"structure"` + + // An app to upload or that has been uploaded. + AppUpload *Upload `locationName:"appUpload" type:"structure"` +} + +// String returns the string representation +func (s InstallToRemoteAccessSessionOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s InstallToRemoteAccessSessionOutput) GoString() string { + return s.String() +} + +// SetAppUpload sets the AppUpload field's value. +func (s *InstallToRemoteAccessSessionOutput) SetAppUpload(v *Upload) *InstallToRemoteAccessSessionOutput { + s.AppUpload = v + return s +} + +// Represents a device. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/Job +type Job struct { + _ struct{} `type:"structure"` + + // The job's ARN. + Arn *string `locationName:"arn" min:"32" type:"string"` + + // The job's result counters. + Counters *Counters `locationName:"counters" type:"structure"` + + // When the job was created. + Created *time.Time `locationName:"created" type:"timestamp" timestampFormat:"unix"` + + // The device (phone or tablet). + Device *Device `locationName:"device" type:"structure"` + + // Represents the total (metered or unmetered) minutes used by the job. + DeviceMinutes *DeviceMinutes `locationName:"deviceMinutes" type:"structure"` + + // A message about the job's result. + Message *string `locationName:"message" type:"string"` + + // The job's name. + Name *string `locationName:"name" type:"string"` + + // The job's result. + // + // Allowed values include: + // + // * PENDING: A pending condition. + // + // * PASSED: A passing condition. + // + // * WARNED: A warning condition. + // + // * FAILED: A failed condition. + // + // * SKIPPED: A skipped condition. + // + // * ERRORED: An error condition. + // + // * STOPPED: A stopped condition. + Result *string `locationName:"result" type:"string" enum:"ExecutionResult"` + + // The job's start time. + Started *time.Time `locationName:"started" type:"timestamp" timestampFormat:"unix"` + + // The job's status. + // + // Allowed values include: + // + // * PENDING: A pending status. + // + // * PENDING_CONCURRENCY: A pending concurrency status. + // + // * PENDING_DEVICE: A pending device status. + // + // * PROCESSING: A processing status. + // + // * SCHEDULING: A scheduling status. + // + // * PREPARING: A preparing status. + // + // * RUNNING: A running status. + // + // * COMPLETED: A completed status. + // + // * STOPPING: A stopping status. + Status *string `locationName:"status" type:"string" enum:"ExecutionStatus"` + + // The job's stop time. + Stopped *time.Time `locationName:"stopped" type:"timestamp" timestampFormat:"unix"` + + // The job's type. + // + // Allowed values include the following: + // + // * BUILTIN_FUZZ: The built-in fuzz type. + // + // * BUILTIN_EXPLORER: For Android, an app explorer that will traverse an + // Android app, interacting with it and capturing screenshots at the same + // time. + // + // * APPIUM_JAVA_JUNIT: The Appium Java JUnit type. + // + // * APPIUM_JAVA_TESTNG: The Appium Java TestNG type. + // + // * APPIUM_PYTHON: The Appium Python type. + // + // * APPIUM_WEB_JAVA_JUNIT: The Appium Java JUnit type for Web apps. + // + // * APPIUM_WEB_JAVA_TESTNG: The Appium Java TestNG type for Web apps. + // + // * APPIUM_WEB_PYTHON: The Appium Python type for Web apps. + // + // * CALABASH: The Calabash type. + // + // * INSTRUMENTATION: The Instrumentation type. + // + // * UIAUTOMATION: The uiautomation type. + // + // * UIAUTOMATOR: The uiautomator type. + // + // * XCTEST: The XCode test type. + // + // * XCTEST_UI: The XCode UI test type. + Type *string `locationName:"type" type:"string" enum:"TestType"` +} + +// String returns the string representation +func (s Job) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s Job) GoString() string { + return s.String() +} + +// SetArn sets the Arn field's value. +func (s *Job) SetArn(v string) *Job { + s.Arn = &v + return s +} + +// SetCounters sets the Counters field's value. +func (s *Job) SetCounters(v *Counters) *Job { + s.Counters = v + return s +} + +// SetCreated sets the Created field's value. +func (s *Job) SetCreated(v time.Time) *Job { + s.Created = &v + return s +} + +// SetDevice sets the Device field's value. +func (s *Job) SetDevice(v *Device) *Job { + s.Device = v + return s +} + +// SetDeviceMinutes sets the DeviceMinutes field's value. +func (s *Job) SetDeviceMinutes(v *DeviceMinutes) *Job { + s.DeviceMinutes = v + return s +} + +// SetMessage sets the Message field's value. +func (s *Job) SetMessage(v string) *Job { + s.Message = &v + return s +} + +// SetName sets the Name field's value. +func (s *Job) SetName(v string) *Job { + s.Name = &v + return s +} + +// SetResult sets the Result field's value. +func (s *Job) SetResult(v string) *Job { + s.Result = &v + return s +} + +// SetStarted sets the Started field's value. +func (s *Job) SetStarted(v time.Time) *Job { + s.Started = &v + return s +} + +// SetStatus sets the Status field's value. +func (s *Job) SetStatus(v string) *Job { + s.Status = &v + return s +} + +// SetStopped sets the Stopped field's value. +func (s *Job) SetStopped(v time.Time) *Job { + s.Stopped = &v + return s +} + +// SetType sets the Type field's value. +func (s *Job) SetType(v string) *Job { + s.Type = &v + return s +} + +// Represents a request to the list artifacts operation. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/ListArtifactsRequest +type ListArtifactsInput struct { + _ struct{} `type:"structure"` + + // The Run, Job, Suite, or Test ARN. + // + // Arn is a required field + Arn *string `locationName:"arn" min:"32" type:"string" required:"true"` + + // An identifier that was returned from the previous call to this operation, + // which can be used to return the next set of items in the list. + NextToken *string `locationName:"nextToken" min:"4" type:"string"` + + // The artifacts' type. + // + // Allowed values include: + // + // * FILE: The artifacts are files. + // + // * LOG: The artifacts are logs. + // + // * SCREENSHOT: The artifacts are screenshots. + // + // Type is a required field + Type *string `locationName:"type" type:"string" required:"true" enum:"ArtifactCategory"` +} + +// String returns the string representation +func (s ListArtifactsInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ListArtifactsInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *ListArtifactsInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "ListArtifactsInput"} + if s.Arn == nil { + invalidParams.Add(request.NewErrParamRequired("Arn")) + } + if s.Arn != nil && len(*s.Arn) < 32 { + invalidParams.Add(request.NewErrParamMinLen("Arn", 32)) + } + if s.NextToken != nil && len(*s.NextToken) < 4 { + invalidParams.Add(request.NewErrParamMinLen("NextToken", 4)) + } + if s.Type == nil { + invalidParams.Add(request.NewErrParamRequired("Type")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetArn sets the Arn field's value. +func (s *ListArtifactsInput) SetArn(v string) *ListArtifactsInput { + s.Arn = &v + return s +} + +// SetNextToken sets the NextToken field's value. +func (s *ListArtifactsInput) SetNextToken(v string) *ListArtifactsInput { + s.NextToken = &v + return s +} + +// SetType sets the Type field's value. +func (s *ListArtifactsInput) SetType(v string) *ListArtifactsInput { + s.Type = &v + return s +} + +// Represents the result of a list artifacts operation. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/ListArtifactsResult +type ListArtifactsOutput struct { + _ struct{} `type:"structure"` + + // Information about the artifacts. + Artifacts []*Artifact `locationName:"artifacts" type:"list"` + + // If the number of items that are returned is significantly large, this is + // an identifier that is also returned, which can be used in a subsequent call + // to this operation to return the next set of items in the list. + NextToken *string `locationName:"nextToken" min:"4" type:"string"` +} + +// String returns the string representation +func (s ListArtifactsOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ListArtifactsOutput) GoString() string { + return s.String() +} + +// SetArtifacts sets the Artifacts field's value. +func (s *ListArtifactsOutput) SetArtifacts(v []*Artifact) *ListArtifactsOutput { + s.Artifacts = v + return s +} + +// SetNextToken sets the NextToken field's value. +func (s *ListArtifactsOutput) SetNextToken(v string) *ListArtifactsOutput { + s.NextToken = &v + return s +} + +// Represents the result of a list device pools request. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/ListDevicePoolsRequest +type ListDevicePoolsInput struct { + _ struct{} `type:"structure"` + + // The project ARN. + // + // Arn is a required field + Arn *string `locationName:"arn" min:"32" type:"string" required:"true"` + + // An identifier that was returned from the previous call to this operation, + // which can be used to return the next set of items in the list. + NextToken *string `locationName:"nextToken" min:"4" type:"string"` + + // The device pools' type. + // + // Allowed values include: + // + // * CURATED: A device pool that is created and managed by AWS Device Farm. + // + // * PRIVATE: A device pool that is created and managed by the device pool + // developer. + Type *string `locationName:"type" type:"string" enum:"DevicePoolType"` +} + +// String returns the string representation +func (s ListDevicePoolsInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ListDevicePoolsInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *ListDevicePoolsInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "ListDevicePoolsInput"} + if s.Arn == nil { + invalidParams.Add(request.NewErrParamRequired("Arn")) + } + if s.Arn != nil && len(*s.Arn) < 32 { + invalidParams.Add(request.NewErrParamMinLen("Arn", 32)) + } + if s.NextToken != nil && len(*s.NextToken) < 4 { + invalidParams.Add(request.NewErrParamMinLen("NextToken", 4)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetArn sets the Arn field's value. +func (s *ListDevicePoolsInput) SetArn(v string) *ListDevicePoolsInput { + s.Arn = &v + return s +} + +// SetNextToken sets the NextToken field's value. +func (s *ListDevicePoolsInput) SetNextToken(v string) *ListDevicePoolsInput { + s.NextToken = &v + return s +} + +// SetType sets the Type field's value. +func (s *ListDevicePoolsInput) SetType(v string) *ListDevicePoolsInput { + s.Type = &v + return s +} + +// Represents the result of a list device pools request. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/ListDevicePoolsResult +type ListDevicePoolsOutput struct { + _ struct{} `type:"structure"` + + // Information about the device pools. + DevicePools []*DevicePool `locationName:"devicePools" type:"list"` + + // If the number of items that are returned is significantly large, this is + // an identifier that is also returned, which can be used in a subsequent call + // to this operation to return the next set of items in the list. + NextToken *string `locationName:"nextToken" min:"4" type:"string"` +} + +// String returns the string representation +func (s ListDevicePoolsOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ListDevicePoolsOutput) GoString() string { + return s.String() +} + +// SetDevicePools sets the DevicePools field's value. +func (s *ListDevicePoolsOutput) SetDevicePools(v []*DevicePool) *ListDevicePoolsOutput { + s.DevicePools = v + return s +} + +// SetNextToken sets the NextToken field's value. +func (s *ListDevicePoolsOutput) SetNextToken(v string) *ListDevicePoolsOutput { + s.NextToken = &v + return s +} + +// Represents the result of a list devices request. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/ListDevicesRequest +type ListDevicesInput struct { + _ struct{} `type:"structure"` + + // The Amazon Resource Name (ARN) of the project. + Arn *string `locationName:"arn" min:"32" type:"string"` + + // An identifier that was returned from the previous call to this operation, + // which can be used to return the next set of items in the list. + NextToken *string `locationName:"nextToken" min:"4" type:"string"` +} + +// String returns the string representation +func (s ListDevicesInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ListDevicesInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *ListDevicesInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "ListDevicesInput"} + if s.Arn != nil && len(*s.Arn) < 32 { + invalidParams.Add(request.NewErrParamMinLen("Arn", 32)) + } + if s.NextToken != nil && len(*s.NextToken) < 4 { + invalidParams.Add(request.NewErrParamMinLen("NextToken", 4)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetArn sets the Arn field's value. +func (s *ListDevicesInput) SetArn(v string) *ListDevicesInput { + s.Arn = &v + return s +} + +// SetNextToken sets the NextToken field's value. +func (s *ListDevicesInput) SetNextToken(v string) *ListDevicesInput { + s.NextToken = &v + return s +} + +// Represents the result of a list devices operation. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/ListDevicesResult +type ListDevicesOutput struct { + _ struct{} `type:"structure"` + + // Information about the devices. + Devices []*Device `locationName:"devices" type:"list"` + + // If the number of items that are returned is significantly large, this is + // an identifier that is also returned, which can be used in a subsequent call + // to this operation to return the next set of items in the list. + NextToken *string `locationName:"nextToken" min:"4" type:"string"` +} + +// String returns the string representation +func (s ListDevicesOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ListDevicesOutput) GoString() string { + return s.String() +} + +// SetDevices sets the Devices field's value. +func (s *ListDevicesOutput) SetDevices(v []*Device) *ListDevicesOutput { + s.Devices = v + return s +} + +// SetNextToken sets the NextToken field's value. +func (s *ListDevicesOutput) SetNextToken(v string) *ListDevicesOutput { + s.NextToken = &v + return s +} + +// Represents a request to the list jobs operation. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/ListJobsRequest +type ListJobsInput struct { + _ struct{} `type:"structure"` + + // The jobs' ARNs. + // + // Arn is a required field + Arn *string `locationName:"arn" min:"32" type:"string" required:"true"` + + // An identifier that was returned from the previous call to this operation, + // which can be used to return the next set of items in the list. + NextToken *string `locationName:"nextToken" min:"4" type:"string"` +} + +// String returns the string representation +func (s ListJobsInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ListJobsInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *ListJobsInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "ListJobsInput"} + if s.Arn == nil { + invalidParams.Add(request.NewErrParamRequired("Arn")) + } + if s.Arn != nil && len(*s.Arn) < 32 { + invalidParams.Add(request.NewErrParamMinLen("Arn", 32)) + } + if s.NextToken != nil && len(*s.NextToken) < 4 { + invalidParams.Add(request.NewErrParamMinLen("NextToken", 4)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetArn sets the Arn field's value. +func (s *ListJobsInput) SetArn(v string) *ListJobsInput { + s.Arn = &v + return s +} + +// SetNextToken sets the NextToken field's value. +func (s *ListJobsInput) SetNextToken(v string) *ListJobsInput { + s.NextToken = &v + return s +} + +// Represents the result of a list jobs request. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/ListJobsResult +type ListJobsOutput struct { + _ struct{} `type:"structure"` + + // Information about the jobs. + Jobs []*Job `locationName:"jobs" type:"list"` + + // If the number of items that are returned is significantly large, this is + // an identifier that is also returned, which can be used in a subsequent call + // to this operation to return the next set of items in the list. + NextToken *string `locationName:"nextToken" min:"4" type:"string"` +} + +// String returns the string representation +func (s ListJobsOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ListJobsOutput) GoString() string { + return s.String() +} + +// SetJobs sets the Jobs field's value. +func (s *ListJobsOutput) SetJobs(v []*Job) *ListJobsOutput { + s.Jobs = v + return s +} + +// SetNextToken sets the NextToken field's value. +func (s *ListJobsOutput) SetNextToken(v string) *ListJobsOutput { + s.NextToken = &v + return s +} + +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/ListNetworkProfilesRequest +type ListNetworkProfilesInput struct { + _ struct{} `type:"structure"` + + // The Amazon Resource Name (ARN) of the project for which you want to list + // network profiles. + // + // Arn is a required field + Arn *string `locationName:"arn" min:"32" type:"string" required:"true"` + + // An identifier that was returned from the previous call to this operation, + // which can be used to return the next set of items in the list. + NextToken *string `locationName:"nextToken" min:"4" type:"string"` + + // The type of network profile you wish to return information about. Valid values + // are listed below. + Type *string `locationName:"type" type:"string" enum:"NetworkProfileType"` +} + +// String returns the string representation +func (s ListNetworkProfilesInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ListNetworkProfilesInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *ListNetworkProfilesInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "ListNetworkProfilesInput"} + if s.Arn == nil { + invalidParams.Add(request.NewErrParamRequired("Arn")) + } + if s.Arn != nil && len(*s.Arn) < 32 { + invalidParams.Add(request.NewErrParamMinLen("Arn", 32)) + } + if s.NextToken != nil && len(*s.NextToken) < 4 { + invalidParams.Add(request.NewErrParamMinLen("NextToken", 4)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetArn sets the Arn field's value. +func (s *ListNetworkProfilesInput) SetArn(v string) *ListNetworkProfilesInput { + s.Arn = &v + return s +} + +// SetNextToken sets the NextToken field's value. +func (s *ListNetworkProfilesInput) SetNextToken(v string) *ListNetworkProfilesInput { + s.NextToken = &v + return s +} + +// SetType sets the Type field's value. +func (s *ListNetworkProfilesInput) SetType(v string) *ListNetworkProfilesInput { + s.Type = &v + return s +} + +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/ListNetworkProfilesResult +type ListNetworkProfilesOutput struct { + _ struct{} `type:"structure"` + + // A list of the available network profiles. + NetworkProfiles []*NetworkProfile `locationName:"networkProfiles" type:"list"` + + // An identifier that was returned from the previous call to this operation, + // which can be used to return the next set of items in the list. + NextToken *string `locationName:"nextToken" min:"4" type:"string"` +} + +// String returns the string representation +func (s ListNetworkProfilesOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ListNetworkProfilesOutput) GoString() string { + return s.String() +} + +// SetNetworkProfiles sets the NetworkProfiles field's value. +func (s *ListNetworkProfilesOutput) SetNetworkProfiles(v []*NetworkProfile) *ListNetworkProfilesOutput { + s.NetworkProfiles = v + return s +} + +// SetNextToken sets the NextToken field's value. +func (s *ListNetworkProfilesOutput) SetNextToken(v string) *ListNetworkProfilesOutput { + s.NextToken = &v + return s +} + +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/ListOfferingPromotionsRequest +type ListOfferingPromotionsInput struct { + _ struct{} `type:"structure"` + + // An identifier that was returned from the previous call to this operation, + // which can be used to return the next set of items in the list. + NextToken *string `locationName:"nextToken" min:"4" type:"string"` +} + +// String returns the string representation +func (s ListOfferingPromotionsInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ListOfferingPromotionsInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *ListOfferingPromotionsInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "ListOfferingPromotionsInput"} + if s.NextToken != nil && len(*s.NextToken) < 4 { + invalidParams.Add(request.NewErrParamMinLen("NextToken", 4)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetNextToken sets the NextToken field's value. +func (s *ListOfferingPromotionsInput) SetNextToken(v string) *ListOfferingPromotionsInput { + s.NextToken = &v + return s +} + +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/ListOfferingPromotionsResult +type ListOfferingPromotionsOutput struct { + _ struct{} `type:"structure"` + + // An identifier to be used in the next call to this operation, to return the + // next set of items in the list. + NextToken *string `locationName:"nextToken" min:"4" type:"string"` + + // Information about the offering promotions. + OfferingPromotions []*OfferingPromotion `locationName:"offeringPromotions" type:"list"` +} + +// String returns the string representation +func (s ListOfferingPromotionsOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ListOfferingPromotionsOutput) GoString() string { + return s.String() +} + +// SetNextToken sets the NextToken field's value. +func (s *ListOfferingPromotionsOutput) SetNextToken(v string) *ListOfferingPromotionsOutput { + s.NextToken = &v + return s +} + +// SetOfferingPromotions sets the OfferingPromotions field's value. +func (s *ListOfferingPromotionsOutput) SetOfferingPromotions(v []*OfferingPromotion) *ListOfferingPromotionsOutput { + s.OfferingPromotions = v + return s +} + +// Represents the request to list the offering transaction history. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/ListOfferingTransactionsRequest +type ListOfferingTransactionsInput struct { + _ struct{} `type:"structure"` + + // An identifier that was returned from the previous call to this operation, + // which can be used to return the next set of items in the list. + NextToken *string `locationName:"nextToken" min:"4" type:"string"` +} + +// String returns the string representation +func (s ListOfferingTransactionsInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ListOfferingTransactionsInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *ListOfferingTransactionsInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "ListOfferingTransactionsInput"} + if s.NextToken != nil && len(*s.NextToken) < 4 { + invalidParams.Add(request.NewErrParamMinLen("NextToken", 4)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetNextToken sets the NextToken field's value. +func (s *ListOfferingTransactionsInput) SetNextToken(v string) *ListOfferingTransactionsInput { + s.NextToken = &v + return s +} + +// Returns the transaction log of the specified offerings. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/ListOfferingTransactionsResult +type ListOfferingTransactionsOutput struct { + _ struct{} `type:"structure"` + + // An identifier that was returned from the previous call to this operation, + // which can be used to return the next set of items in the list. + NextToken *string `locationName:"nextToken" min:"4" type:"string"` + + // The audit log of subscriptions you have purchased and modified through AWS + // Device Farm. + OfferingTransactions []*OfferingTransaction `locationName:"offeringTransactions" type:"list"` +} + +// String returns the string representation +func (s ListOfferingTransactionsOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ListOfferingTransactionsOutput) GoString() string { + return s.String() +} + +// SetNextToken sets the NextToken field's value. +func (s *ListOfferingTransactionsOutput) SetNextToken(v string) *ListOfferingTransactionsOutput { + s.NextToken = &v + return s +} + +// SetOfferingTransactions sets the OfferingTransactions field's value. +func (s *ListOfferingTransactionsOutput) SetOfferingTransactions(v []*OfferingTransaction) *ListOfferingTransactionsOutput { + s.OfferingTransactions = v + return s +} + +// Represents the request to list all offerings. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/ListOfferingsRequest +type ListOfferingsInput struct { + _ struct{} `type:"structure"` + + // An identifier that was returned from the previous call to this operation, + // which can be used to return the next set of items in the list. + NextToken *string `locationName:"nextToken" min:"4" type:"string"` +} + +// String returns the string representation +func (s ListOfferingsInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ListOfferingsInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *ListOfferingsInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "ListOfferingsInput"} + if s.NextToken != nil && len(*s.NextToken) < 4 { + invalidParams.Add(request.NewErrParamMinLen("NextToken", 4)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetNextToken sets the NextToken field's value. +func (s *ListOfferingsInput) SetNextToken(v string) *ListOfferingsInput { + s.NextToken = &v + return s +} + +// Represents the return values of the list of offerings. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/ListOfferingsResult +type ListOfferingsOutput struct { + _ struct{} `type:"structure"` + + // An identifier that was returned from the previous call to this operation, + // which can be used to return the next set of items in the list. + NextToken *string `locationName:"nextToken" min:"4" type:"string"` + + // A value representing the list offering results. + Offerings []*Offering `locationName:"offerings" type:"list"` +} + +// String returns the string representation +func (s ListOfferingsOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ListOfferingsOutput) GoString() string { + return s.String() +} + +// SetNextToken sets the NextToken field's value. +func (s *ListOfferingsOutput) SetNextToken(v string) *ListOfferingsOutput { + s.NextToken = &v + return s +} + +// SetOfferings sets the Offerings field's value. +func (s *ListOfferingsOutput) SetOfferings(v []*Offering) *ListOfferingsOutput { + s.Offerings = v + return s +} + +// Represents a request to the list projects operation. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/ListProjectsRequest +type ListProjectsInput struct { + _ struct{} `type:"structure"` + + // Optional. If no Amazon Resource Name (ARN) is specified, then AWS Device + // Farm returns a list of all projects for the AWS account. You can also specify + // a project ARN. + Arn *string `locationName:"arn" min:"32" type:"string"` + + // An identifier that was returned from the previous call to this operation, + // which can be used to return the next set of items in the list. + NextToken *string `locationName:"nextToken" min:"4" type:"string"` +} + +// String returns the string representation +func (s ListProjectsInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ListProjectsInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *ListProjectsInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "ListProjectsInput"} + if s.Arn != nil && len(*s.Arn) < 32 { + invalidParams.Add(request.NewErrParamMinLen("Arn", 32)) + } + if s.NextToken != nil && len(*s.NextToken) < 4 { + invalidParams.Add(request.NewErrParamMinLen("NextToken", 4)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetArn sets the Arn field's value. +func (s *ListProjectsInput) SetArn(v string) *ListProjectsInput { + s.Arn = &v + return s +} + +// SetNextToken sets the NextToken field's value. +func (s *ListProjectsInput) SetNextToken(v string) *ListProjectsInput { + s.NextToken = &v + return s +} + +// Represents the result of a list projects request. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/ListProjectsResult +type ListProjectsOutput struct { + _ struct{} `type:"structure"` + + // If the number of items that are returned is significantly large, this is + // an identifier that is also returned, which can be used in a subsequent call + // to this operation to return the next set of items in the list. + NextToken *string `locationName:"nextToken" min:"4" type:"string"` + + // Information about the projects. + Projects []*Project `locationName:"projects" type:"list"` +} + +// String returns the string representation +func (s ListProjectsOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ListProjectsOutput) GoString() string { + return s.String() +} + +// SetNextToken sets the NextToken field's value. +func (s *ListProjectsOutput) SetNextToken(v string) *ListProjectsOutput { + s.NextToken = &v + return s +} + +// SetProjects sets the Projects field's value. +func (s *ListProjectsOutput) SetProjects(v []*Project) *ListProjectsOutput { + s.Projects = v + return s +} + +// Represents the request to return information about the remote access session. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/ListRemoteAccessSessionsRequest +type ListRemoteAccessSessionsInput struct { + _ struct{} `type:"structure"` + + // The Amazon Resource Name (ARN) of the remote access session about which you + // are requesting information. + // + // Arn is a required field + Arn *string `locationName:"arn" min:"32" type:"string" required:"true"` + + // An identifier that was returned from the previous call to this operation, + // which can be used to return the next set of items in the list. + NextToken *string `locationName:"nextToken" min:"4" type:"string"` +} + +// String returns the string representation +func (s ListRemoteAccessSessionsInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ListRemoteAccessSessionsInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *ListRemoteAccessSessionsInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "ListRemoteAccessSessionsInput"} + if s.Arn == nil { + invalidParams.Add(request.NewErrParamRequired("Arn")) + } + if s.Arn != nil && len(*s.Arn) < 32 { + invalidParams.Add(request.NewErrParamMinLen("Arn", 32)) + } + if s.NextToken != nil && len(*s.NextToken) < 4 { + invalidParams.Add(request.NewErrParamMinLen("NextToken", 4)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetArn sets the Arn field's value. +func (s *ListRemoteAccessSessionsInput) SetArn(v string) *ListRemoteAccessSessionsInput { + s.Arn = &v + return s +} + +// SetNextToken sets the NextToken field's value. +func (s *ListRemoteAccessSessionsInput) SetNextToken(v string) *ListRemoteAccessSessionsInput { + s.NextToken = &v + return s +} + +// Represents the response from the server after AWS Device Farm makes a request +// to return information about the remote access session. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/ListRemoteAccessSessionsResult +type ListRemoteAccessSessionsOutput struct { + _ struct{} `type:"structure"` + + // An identifier that was returned from the previous call to this operation, + // which can be used to return the next set of items in the list. + NextToken *string `locationName:"nextToken" min:"4" type:"string"` + + // A container representing the metadata from the service about each remote + // access session you are requesting. + RemoteAccessSessions []*RemoteAccessSession `locationName:"remoteAccessSessions" type:"list"` +} + +// String returns the string representation +func (s ListRemoteAccessSessionsOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ListRemoteAccessSessionsOutput) GoString() string { + return s.String() +} + +// SetNextToken sets the NextToken field's value. +func (s *ListRemoteAccessSessionsOutput) SetNextToken(v string) *ListRemoteAccessSessionsOutput { + s.NextToken = &v + return s +} + +// SetRemoteAccessSessions sets the RemoteAccessSessions field's value. +func (s *ListRemoteAccessSessionsOutput) SetRemoteAccessSessions(v []*RemoteAccessSession) *ListRemoteAccessSessionsOutput { + s.RemoteAccessSessions = v + return s +} + +// Represents a request to the list runs operation. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/ListRunsRequest +type ListRunsInput struct { + _ struct{} `type:"structure"` + + // The Amazon Resource Name (ARN) of the project for which you want to list + // runs. + // + // Arn is a required field + Arn *string `locationName:"arn" min:"32" type:"string" required:"true"` + + // An identifier that was returned from the previous call to this operation, + // which can be used to return the next set of items in the list. + NextToken *string `locationName:"nextToken" min:"4" type:"string"` +} + +// String returns the string representation +func (s ListRunsInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ListRunsInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *ListRunsInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "ListRunsInput"} + if s.Arn == nil { + invalidParams.Add(request.NewErrParamRequired("Arn")) + } + if s.Arn != nil && len(*s.Arn) < 32 { + invalidParams.Add(request.NewErrParamMinLen("Arn", 32)) + } + if s.NextToken != nil && len(*s.NextToken) < 4 { + invalidParams.Add(request.NewErrParamMinLen("NextToken", 4)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetArn sets the Arn field's value. +func (s *ListRunsInput) SetArn(v string) *ListRunsInput { + s.Arn = &v + return s +} + +// SetNextToken sets the NextToken field's value. +func (s *ListRunsInput) SetNextToken(v string) *ListRunsInput { + s.NextToken = &v + return s +} + +// Represents the result of a list runs request. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/ListRunsResult +type ListRunsOutput struct { + _ struct{} `type:"structure"` + + // If the number of items that are returned is significantly large, this is + // an identifier that is also returned, which can be used in a subsequent call + // to this operation to return the next set of items in the list. + NextToken *string `locationName:"nextToken" min:"4" type:"string"` + + // Information about the runs. + Runs []*Run `locationName:"runs" type:"list"` +} + +// String returns the string representation +func (s ListRunsOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ListRunsOutput) GoString() string { + return s.String() +} + +// SetNextToken sets the NextToken field's value. +func (s *ListRunsOutput) SetNextToken(v string) *ListRunsOutput { + s.NextToken = &v + return s +} + +// SetRuns sets the Runs field's value. +func (s *ListRunsOutput) SetRuns(v []*Run) *ListRunsOutput { + s.Runs = v + return s +} + +// Represents a request to the list samples operation. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/ListSamplesRequest +type ListSamplesInput struct { + _ struct{} `type:"structure"` + + // The Amazon Resource Name (ARN) of the project for which you want to list + // samples. + // + // Arn is a required field + Arn *string `locationName:"arn" min:"32" type:"string" required:"true"` + + // An identifier that was returned from the previous call to this operation, + // which can be used to return the next set of items in the list. + NextToken *string `locationName:"nextToken" min:"4" type:"string"` +} + +// String returns the string representation +func (s ListSamplesInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ListSamplesInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *ListSamplesInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "ListSamplesInput"} + if s.Arn == nil { + invalidParams.Add(request.NewErrParamRequired("Arn")) + } + if s.Arn != nil && len(*s.Arn) < 32 { + invalidParams.Add(request.NewErrParamMinLen("Arn", 32)) + } + if s.NextToken != nil && len(*s.NextToken) < 4 { + invalidParams.Add(request.NewErrParamMinLen("NextToken", 4)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetArn sets the Arn field's value. +func (s *ListSamplesInput) SetArn(v string) *ListSamplesInput { + s.Arn = &v + return s +} + +// SetNextToken sets the NextToken field's value. +func (s *ListSamplesInput) SetNextToken(v string) *ListSamplesInput { + s.NextToken = &v + return s +} + +// Represents the result of a list samples request. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/ListSamplesResult +type ListSamplesOutput struct { + _ struct{} `type:"structure"` + + // If the number of items that are returned is significantly large, this is + // an identifier that is also returned, which can be used in a subsequent call + // to this operation to return the next set of items in the list. + NextToken *string `locationName:"nextToken" min:"4" type:"string"` + + // Information about the samples. + Samples []*Sample `locationName:"samples" type:"list"` +} + +// String returns the string representation +func (s ListSamplesOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ListSamplesOutput) GoString() string { + return s.String() +} + +// SetNextToken sets the NextToken field's value. +func (s *ListSamplesOutput) SetNextToken(v string) *ListSamplesOutput { + s.NextToken = &v + return s +} + +// SetSamples sets the Samples field's value. +func (s *ListSamplesOutput) SetSamples(v []*Sample) *ListSamplesOutput { + s.Samples = v + return s +} + +// Represents a request to the list suites operation. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/ListSuitesRequest +type ListSuitesInput struct { + _ struct{} `type:"structure"` + + // The suites' ARNs. + // + // Arn is a required field + Arn *string `locationName:"arn" min:"32" type:"string" required:"true"` + + // An identifier that was returned from the previous call to this operation, + // which can be used to return the next set of items in the list. + NextToken *string `locationName:"nextToken" min:"4" type:"string"` +} + +// String returns the string representation +func (s ListSuitesInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ListSuitesInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *ListSuitesInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "ListSuitesInput"} + if s.Arn == nil { + invalidParams.Add(request.NewErrParamRequired("Arn")) + } + if s.Arn != nil && len(*s.Arn) < 32 { + invalidParams.Add(request.NewErrParamMinLen("Arn", 32)) + } + if s.NextToken != nil && len(*s.NextToken) < 4 { + invalidParams.Add(request.NewErrParamMinLen("NextToken", 4)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetArn sets the Arn field's value. +func (s *ListSuitesInput) SetArn(v string) *ListSuitesInput { + s.Arn = &v + return s +} + +// SetNextToken sets the NextToken field's value. +func (s *ListSuitesInput) SetNextToken(v string) *ListSuitesInput { + s.NextToken = &v + return s +} + +// Represents the result of a list suites request. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/ListSuitesResult +type ListSuitesOutput struct { + _ struct{} `type:"structure"` + + // If the number of items that are returned is significantly large, this is + // an identifier that is also returned, which can be used in a subsequent call + // to this operation to return the next set of items in the list. + NextToken *string `locationName:"nextToken" min:"4" type:"string"` + + // Information about the suites. + Suites []*Suite `locationName:"suites" type:"list"` +} + +// String returns the string representation +func (s ListSuitesOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ListSuitesOutput) GoString() string { + return s.String() +} + +// SetNextToken sets the NextToken field's value. +func (s *ListSuitesOutput) SetNextToken(v string) *ListSuitesOutput { + s.NextToken = &v + return s +} + +// SetSuites sets the Suites field's value. +func (s *ListSuitesOutput) SetSuites(v []*Suite) *ListSuitesOutput { + s.Suites = v + return s +} + +// Represents a request to the list tests operation. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/ListTestsRequest +type ListTestsInput struct { + _ struct{} `type:"structure"` + + // The tests' ARNs. + // + // Arn is a required field + Arn *string `locationName:"arn" min:"32" type:"string" required:"true"` + + // An identifier that was returned from the previous call to this operation, + // which can be used to return the next set of items in the list. + NextToken *string `locationName:"nextToken" min:"4" type:"string"` +} + +// String returns the string representation +func (s ListTestsInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ListTestsInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *ListTestsInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "ListTestsInput"} + if s.Arn == nil { + invalidParams.Add(request.NewErrParamRequired("Arn")) + } + if s.Arn != nil && len(*s.Arn) < 32 { + invalidParams.Add(request.NewErrParamMinLen("Arn", 32)) + } + if s.NextToken != nil && len(*s.NextToken) < 4 { + invalidParams.Add(request.NewErrParamMinLen("NextToken", 4)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetArn sets the Arn field's value. +func (s *ListTestsInput) SetArn(v string) *ListTestsInput { + s.Arn = &v + return s +} + +// SetNextToken sets the NextToken field's value. +func (s *ListTestsInput) SetNextToken(v string) *ListTestsInput { + s.NextToken = &v + return s +} + +// Represents the result of a list tests request. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/ListTestsResult +type ListTestsOutput struct { + _ struct{} `type:"structure"` + + // If the number of items that are returned is significantly large, this is + // an identifier that is also returned, which can be used in a subsequent call + // to this operation to return the next set of items in the list. + NextToken *string `locationName:"nextToken" min:"4" type:"string"` + + // Information about the tests. + Tests []*Test `locationName:"tests" type:"list"` +} + +// String returns the string representation +func (s ListTestsOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ListTestsOutput) GoString() string { + return s.String() +} + +// SetNextToken sets the NextToken field's value. +func (s *ListTestsOutput) SetNextToken(v string) *ListTestsOutput { + s.NextToken = &v + return s +} + +// SetTests sets the Tests field's value. +func (s *ListTestsOutput) SetTests(v []*Test) *ListTestsOutput { + s.Tests = v + return s +} + +// Represents a request to the list unique problems operation. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/ListUniqueProblemsRequest +type ListUniqueProblemsInput struct { + _ struct{} `type:"structure"` + + // The unique problems' ARNs. + // + // Arn is a required field + Arn *string `locationName:"arn" min:"32" type:"string" required:"true"` + + // An identifier that was returned from the previous call to this operation, + // which can be used to return the next set of items in the list. + NextToken *string `locationName:"nextToken" min:"4" type:"string"` +} + +// String returns the string representation +func (s ListUniqueProblemsInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ListUniqueProblemsInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *ListUniqueProblemsInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "ListUniqueProblemsInput"} + if s.Arn == nil { + invalidParams.Add(request.NewErrParamRequired("Arn")) + } + if s.Arn != nil && len(*s.Arn) < 32 { + invalidParams.Add(request.NewErrParamMinLen("Arn", 32)) + } + if s.NextToken != nil && len(*s.NextToken) < 4 { + invalidParams.Add(request.NewErrParamMinLen("NextToken", 4)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetArn sets the Arn field's value. +func (s *ListUniqueProblemsInput) SetArn(v string) *ListUniqueProblemsInput { + s.Arn = &v + return s +} + +// SetNextToken sets the NextToken field's value. +func (s *ListUniqueProblemsInput) SetNextToken(v string) *ListUniqueProblemsInput { + s.NextToken = &v + return s +} + +// Represents the result of a list unique problems request. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/ListUniqueProblemsResult +type ListUniqueProblemsOutput struct { + _ struct{} `type:"structure"` + + // If the number of items that are returned is significantly large, this is + // an identifier that is also returned, which can be used in a subsequent call + // to this operation to return the next set of items in the list. + NextToken *string `locationName:"nextToken" min:"4" type:"string"` + + // Information about the unique problems. + // + // Allowed values include: + // + // * PENDING: A pending condition. + // + // * PASSED: A passing condition. + // + // * WARNED: A warning condition. + // + // * FAILED: A failed condition. + // + // * SKIPPED: A skipped condition. + // + // * ERRORED: An error condition. + // + // * STOPPED: A stopped condition. + UniqueProblems map[string][]*UniqueProblem `locationName:"uniqueProblems" type:"map"` +} + +// String returns the string representation +func (s ListUniqueProblemsOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ListUniqueProblemsOutput) GoString() string { + return s.String() +} + +// SetNextToken sets the NextToken field's value. +func (s *ListUniqueProblemsOutput) SetNextToken(v string) *ListUniqueProblemsOutput { + s.NextToken = &v + return s +} + +// SetUniqueProblems sets the UniqueProblems field's value. +func (s *ListUniqueProblemsOutput) SetUniqueProblems(v map[string][]*UniqueProblem) *ListUniqueProblemsOutput { + s.UniqueProblems = v + return s +} + +// Represents a request to the list uploads operation. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/ListUploadsRequest +type ListUploadsInput struct { + _ struct{} `type:"structure"` + + // The Amazon Resource Name (ARN) of the project for which you want to list + // uploads. + // + // Arn is a required field + Arn *string `locationName:"arn" min:"32" type:"string" required:"true"` + + // An identifier that was returned from the previous call to this operation, + // which can be used to return the next set of items in the list. + NextToken *string `locationName:"nextToken" min:"4" type:"string"` +} + +// String returns the string representation +func (s ListUploadsInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ListUploadsInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *ListUploadsInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "ListUploadsInput"} + if s.Arn == nil { + invalidParams.Add(request.NewErrParamRequired("Arn")) + } + if s.Arn != nil && len(*s.Arn) < 32 { + invalidParams.Add(request.NewErrParamMinLen("Arn", 32)) + } + if s.NextToken != nil && len(*s.NextToken) < 4 { + invalidParams.Add(request.NewErrParamMinLen("NextToken", 4)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetArn sets the Arn field's value. +func (s *ListUploadsInput) SetArn(v string) *ListUploadsInput { + s.Arn = &v + return s +} + +// SetNextToken sets the NextToken field's value. +func (s *ListUploadsInput) SetNextToken(v string) *ListUploadsInput { + s.NextToken = &v + return s +} + +// Represents the result of a list uploads request. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/ListUploadsResult +type ListUploadsOutput struct { + _ struct{} `type:"structure"` + + // If the number of items that are returned is significantly large, this is + // an identifier that is also returned, which can be used in a subsequent call + // to this operation to return the next set of items in the list. + NextToken *string `locationName:"nextToken" min:"4" type:"string"` + + // Information about the uploads. + Uploads []*Upload `locationName:"uploads" type:"list"` +} + +// String returns the string representation +func (s ListUploadsOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ListUploadsOutput) GoString() string { + return s.String() +} + +// SetNextToken sets the NextToken field's value. +func (s *ListUploadsOutput) SetNextToken(v string) *ListUploadsOutput { + s.NextToken = &v + return s +} + +// SetUploads sets the Uploads field's value. +func (s *ListUploadsOutput) SetUploads(v []*Upload) *ListUploadsOutput { + s.Uploads = v + return s +} + +// Represents a latitude and longitude pair, expressed in geographic coordinate +// system degrees (for example 47.6204, -122.3491). +// +// Elevation is currently not supported. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/Location +type Location struct { + _ struct{} `type:"structure"` + + // The latitude. + // + // Latitude is a required field + Latitude *float64 `locationName:"latitude" type:"double" required:"true"` + + // The longitude. + // + // Longitude is a required field + Longitude *float64 `locationName:"longitude" type:"double" required:"true"` +} + +// String returns the string representation +func (s Location) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s Location) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *Location) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "Location"} + if s.Latitude == nil { + invalidParams.Add(request.NewErrParamRequired("Latitude")) + } + if s.Longitude == nil { + invalidParams.Add(request.NewErrParamRequired("Longitude")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetLatitude sets the Latitude field's value. +func (s *Location) SetLatitude(v float64) *Location { + s.Latitude = &v + return s +} + +// SetLongitude sets the Longitude field's value. +func (s *Location) SetLongitude(v float64) *Location { + s.Longitude = &v + return s +} + +// A number representing the monetary amount for an offering or transaction. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/MonetaryAmount +type MonetaryAmount struct { + _ struct{} `type:"structure"` + + // The numerical amount of an offering or transaction. + Amount *float64 `locationName:"amount" type:"double"` + + // The currency code of a monetary amount. For example, USD means "U.S. dollars." + CurrencyCode *string `locationName:"currencyCode" type:"string" enum:"CurrencyCode"` +} + +// String returns the string representation +func (s MonetaryAmount) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s MonetaryAmount) GoString() string { + return s.String() +} + +// SetAmount sets the Amount field's value. +func (s *MonetaryAmount) SetAmount(v float64) *MonetaryAmount { + s.Amount = &v + return s +} + +// SetCurrencyCode sets the CurrencyCode field's value. +func (s *MonetaryAmount) SetCurrencyCode(v string) *MonetaryAmount { + s.CurrencyCode = &v + return s +} + +// An array of settings that describes characteristics of a network profile. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/NetworkProfile +type NetworkProfile struct { + _ struct{} `type:"structure"` + + // The Amazon Resource Name (ARN) of the network profile. + Arn *string `locationName:"arn" min:"32" type:"string"` + + // The description of the network profile. + Description *string `locationName:"description" type:"string"` + + // The data throughput rate in bits per second, as an integer from 0 to 104857600. + DownlinkBandwidthBits *int64 `locationName:"downlinkBandwidthBits" type:"long"` + + // Delay time for all packets to destination in milliseconds as an integer from + // 0 to 2000. + DownlinkDelayMs *int64 `locationName:"downlinkDelayMs" type:"long"` + + // Time variation in the delay of received packets in milliseconds as an integer + // from 0 to 2000. + DownlinkJitterMs *int64 `locationName:"downlinkJitterMs" type:"long"` + + // Proportion of received packets that fail to arrive from 0 to 100 percent. + DownlinkLossPercent *int64 `locationName:"downlinkLossPercent" type:"integer"` + + // The name of the network profile. + Name *string `locationName:"name" type:"string"` + + // The type of network profile. Valid values are listed below. + Type *string `locationName:"type" type:"string" enum:"NetworkProfileType"` + + // The data throughput rate in bits per second, as an integer from 0 to 104857600. + UplinkBandwidthBits *int64 `locationName:"uplinkBandwidthBits" type:"long"` + + // Delay time for all packets to destination in milliseconds as an integer from + // 0 to 2000. + UplinkDelayMs *int64 `locationName:"uplinkDelayMs" type:"long"` + + // Time variation in the delay of received packets in milliseconds as an integer + // from 0 to 2000. + UplinkJitterMs *int64 `locationName:"uplinkJitterMs" type:"long"` + + // Proportion of transmitted packets that fail to arrive from 0 to 100 percent. + UplinkLossPercent *int64 `locationName:"uplinkLossPercent" type:"integer"` +} + +// String returns the string representation +func (s NetworkProfile) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s NetworkProfile) GoString() string { + return s.String() +} + +// SetArn sets the Arn field's value. +func (s *NetworkProfile) SetArn(v string) *NetworkProfile { + s.Arn = &v + return s +} + +// SetDescription sets the Description field's value. +func (s *NetworkProfile) SetDescription(v string) *NetworkProfile { + s.Description = &v + return s +} + +// SetDownlinkBandwidthBits sets the DownlinkBandwidthBits field's value. +func (s *NetworkProfile) SetDownlinkBandwidthBits(v int64) *NetworkProfile { + s.DownlinkBandwidthBits = &v + return s +} + +// SetDownlinkDelayMs sets the DownlinkDelayMs field's value. +func (s *NetworkProfile) SetDownlinkDelayMs(v int64) *NetworkProfile { + s.DownlinkDelayMs = &v + return s +} + +// SetDownlinkJitterMs sets the DownlinkJitterMs field's value. +func (s *NetworkProfile) SetDownlinkJitterMs(v int64) *NetworkProfile { + s.DownlinkJitterMs = &v + return s +} + +// SetDownlinkLossPercent sets the DownlinkLossPercent field's value. +func (s *NetworkProfile) SetDownlinkLossPercent(v int64) *NetworkProfile { + s.DownlinkLossPercent = &v + return s +} + +// SetName sets the Name field's value. +func (s *NetworkProfile) SetName(v string) *NetworkProfile { + s.Name = &v + return s +} + +// SetType sets the Type field's value. +func (s *NetworkProfile) SetType(v string) *NetworkProfile { + s.Type = &v + return s +} + +// SetUplinkBandwidthBits sets the UplinkBandwidthBits field's value. +func (s *NetworkProfile) SetUplinkBandwidthBits(v int64) *NetworkProfile { + s.UplinkBandwidthBits = &v + return s +} + +// SetUplinkDelayMs sets the UplinkDelayMs field's value. +func (s *NetworkProfile) SetUplinkDelayMs(v int64) *NetworkProfile { + s.UplinkDelayMs = &v + return s +} + +// SetUplinkJitterMs sets the UplinkJitterMs field's value. +func (s *NetworkProfile) SetUplinkJitterMs(v int64) *NetworkProfile { + s.UplinkJitterMs = &v + return s +} + +// SetUplinkLossPercent sets the UplinkLossPercent field's value. +func (s *NetworkProfile) SetUplinkLossPercent(v int64) *NetworkProfile { + s.UplinkLossPercent = &v + return s +} + +// Represents the metadata of a device offering. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/Offering +type Offering struct { + _ struct{} `type:"structure"` + + // A string describing the offering. + Description *string `locationName:"description" type:"string"` + + // The ID that corresponds to a device offering. + Id *string `locationName:"id" min:"32" type:"string"` + + // The platform of the device (e.g., ANDROID or IOS). + Platform *string `locationName:"platform" type:"string" enum:"DevicePlatform"` + + // Specifies whether there are recurring charges for the offering. + RecurringCharges []*RecurringCharge `locationName:"recurringCharges" type:"list"` + + // The type of offering (e.g., "RECURRING") for a device. + Type *string `locationName:"type" type:"string" enum:"OfferingType"` +} + +// String returns the string representation +func (s Offering) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s Offering) GoString() string { + return s.String() +} + +// SetDescription sets the Description field's value. +func (s *Offering) SetDescription(v string) *Offering { + s.Description = &v + return s +} + +// SetId sets the Id field's value. +func (s *Offering) SetId(v string) *Offering { + s.Id = &v + return s +} + +// SetPlatform sets the Platform field's value. +func (s *Offering) SetPlatform(v string) *Offering { + s.Platform = &v + return s +} + +// SetRecurringCharges sets the RecurringCharges field's value. +func (s *Offering) SetRecurringCharges(v []*RecurringCharge) *Offering { + s.RecurringCharges = v + return s +} + +// SetType sets the Type field's value. +func (s *Offering) SetType(v string) *Offering { + s.Type = &v + return s +} + +// Represents information about an offering promotion. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/OfferingPromotion +type OfferingPromotion struct { + _ struct{} `type:"structure"` + + // A string describing the offering promotion. + Description *string `locationName:"description" type:"string"` + + // The ID of the offering promotion. + Id *string `locationName:"id" min:"4" type:"string"` +} + +// String returns the string representation +func (s OfferingPromotion) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s OfferingPromotion) GoString() string { + return s.String() +} + +// SetDescription sets the Description field's value. +func (s *OfferingPromotion) SetDescription(v string) *OfferingPromotion { + s.Description = &v + return s +} + +// SetId sets the Id field's value. +func (s *OfferingPromotion) SetId(v string) *OfferingPromotion { + s.Id = &v + return s +} + +// The status of the offering. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/OfferingStatus +type OfferingStatus struct { + _ struct{} `type:"structure"` + + // The date on which the offering is effective. + EffectiveOn *time.Time `locationName:"effectiveOn" type:"timestamp" timestampFormat:"unix"` + + // Represents the metadata of an offering status. + Offering *Offering `locationName:"offering" type:"structure"` + + // The number of available devices in the offering. + Quantity *int64 `locationName:"quantity" type:"integer"` + + // The type specified for the offering status. + Type *string `locationName:"type" type:"string" enum:"OfferingTransactionType"` +} + +// String returns the string representation +func (s OfferingStatus) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s OfferingStatus) GoString() string { + return s.String() +} + +// SetEffectiveOn sets the EffectiveOn field's value. +func (s *OfferingStatus) SetEffectiveOn(v time.Time) *OfferingStatus { + s.EffectiveOn = &v + return s +} + +// SetOffering sets the Offering field's value. +func (s *OfferingStatus) SetOffering(v *Offering) *OfferingStatus { + s.Offering = v + return s +} + +// SetQuantity sets the Quantity field's value. +func (s *OfferingStatus) SetQuantity(v int64) *OfferingStatus { + s.Quantity = &v + return s +} + +// SetType sets the Type field's value. +func (s *OfferingStatus) SetType(v string) *OfferingStatus { + s.Type = &v + return s +} + +// Represents the metadata of an offering transaction. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/OfferingTransaction +type OfferingTransaction struct { + _ struct{} `type:"structure"` + + // The cost of an offering transaction. + Cost *MonetaryAmount `locationName:"cost" type:"structure"` + + // The date on which an offering transaction was created. + CreatedOn *time.Time `locationName:"createdOn" type:"timestamp" timestampFormat:"unix"` + + // The ID that corresponds to a device offering promotion. + OfferingPromotionId *string `locationName:"offeringPromotionId" min:"4" type:"string"` + + // The status of an offering transaction. + OfferingStatus *OfferingStatus `locationName:"offeringStatus" type:"structure"` + + // The transaction ID of the offering transaction. + TransactionId *string `locationName:"transactionId" min:"32" type:"string"` +} + +// String returns the string representation +func (s OfferingTransaction) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s OfferingTransaction) GoString() string { + return s.String() +} + +// SetCost sets the Cost field's value. +func (s *OfferingTransaction) SetCost(v *MonetaryAmount) *OfferingTransaction { + s.Cost = v + return s +} + +// SetCreatedOn sets the CreatedOn field's value. +func (s *OfferingTransaction) SetCreatedOn(v time.Time) *OfferingTransaction { + s.CreatedOn = &v + return s +} + +// SetOfferingPromotionId sets the OfferingPromotionId field's value. +func (s *OfferingTransaction) SetOfferingPromotionId(v string) *OfferingTransaction { + s.OfferingPromotionId = &v + return s +} + +// SetOfferingStatus sets the OfferingStatus field's value. +func (s *OfferingTransaction) SetOfferingStatus(v *OfferingStatus) *OfferingTransaction { + s.OfferingStatus = v + return s +} + +// SetTransactionId sets the TransactionId field's value. +func (s *OfferingTransaction) SetTransactionId(v string) *OfferingTransaction { + s.TransactionId = &v + return s +} + +// Represents a specific warning or failure. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/Problem +type Problem struct { + _ struct{} `type:"structure"` + + // Information about the associated device. + Device *Device `locationName:"device" type:"structure"` + + // Information about the associated job. + Job *ProblemDetail `locationName:"job" type:"structure"` + + // A message about the problem's result. + Message *string `locationName:"message" type:"string"` + + // The problem's result. + // + // Allowed values include: + // + // * PENDING: A pending condition. + // + // * PASSED: A passing condition. + // + // * WARNED: A warning condition. + // + // * FAILED: A failed condition. + // + // * SKIPPED: A skipped condition. + // + // * ERRORED: An error condition. + // + // * STOPPED: A stopped condition. + Result *string `locationName:"result" type:"string" enum:"ExecutionResult"` + + // Information about the associated run. + Run *ProblemDetail `locationName:"run" type:"structure"` + + // Information about the associated suite. + Suite *ProblemDetail `locationName:"suite" type:"structure"` + + // Information about the associated test. + Test *ProblemDetail `locationName:"test" type:"structure"` +} + +// String returns the string representation +func (s Problem) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s Problem) GoString() string { + return s.String() +} + +// SetDevice sets the Device field's value. +func (s *Problem) SetDevice(v *Device) *Problem { + s.Device = v + return s +} + +// SetJob sets the Job field's value. +func (s *Problem) SetJob(v *ProblemDetail) *Problem { + s.Job = v + return s +} + +// SetMessage sets the Message field's value. +func (s *Problem) SetMessage(v string) *Problem { + s.Message = &v + return s +} + +// SetResult sets the Result field's value. +func (s *Problem) SetResult(v string) *Problem { + s.Result = &v + return s +} + +// SetRun sets the Run field's value. +func (s *Problem) SetRun(v *ProblemDetail) *Problem { + s.Run = v + return s +} + +// SetSuite sets the Suite field's value. +func (s *Problem) SetSuite(v *ProblemDetail) *Problem { + s.Suite = v + return s +} + +// SetTest sets the Test field's value. +func (s *Problem) SetTest(v *ProblemDetail) *Problem { + s.Test = v + return s +} + +// Information about a problem detail. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/ProblemDetail +type ProblemDetail struct { + _ struct{} `type:"structure"` + + // The problem detail's ARN. + Arn *string `locationName:"arn" min:"32" type:"string"` + + // The problem detail's name. + Name *string `locationName:"name" type:"string"` +} + +// String returns the string representation +func (s ProblemDetail) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ProblemDetail) GoString() string { + return s.String() +} + +// SetArn sets the Arn field's value. +func (s *ProblemDetail) SetArn(v string) *ProblemDetail { + s.Arn = &v + return s +} + +// SetName sets the Name field's value. +func (s *ProblemDetail) SetName(v string) *ProblemDetail { + s.Name = &v + return s +} + +// Represents an operating-system neutral workspace for running and managing +// tests. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/Project +type Project struct { + _ struct{} `type:"structure"` + + // The project's ARN. + Arn *string `locationName:"arn" min:"32" type:"string"` + + // When the project was created. + Created *time.Time `locationName:"created" type:"timestamp" timestampFormat:"unix"` + + // The default number of minutes (at the project level) a test run will execute + // before it times out. Default value is 60 minutes. + DefaultJobTimeoutMinutes *int64 `locationName:"defaultJobTimeoutMinutes" type:"integer"` + + // The project's name. + Name *string `locationName:"name" type:"string"` +} + +// String returns the string representation +func (s Project) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s Project) GoString() string { + return s.String() +} + +// SetArn sets the Arn field's value. +func (s *Project) SetArn(v string) *Project { + s.Arn = &v + return s +} + +// SetCreated sets the Created field's value. +func (s *Project) SetCreated(v time.Time) *Project { + s.Created = &v + return s +} + +// SetDefaultJobTimeoutMinutes sets the DefaultJobTimeoutMinutes field's value. +func (s *Project) SetDefaultJobTimeoutMinutes(v int64) *Project { + s.DefaultJobTimeoutMinutes = &v + return s +} + +// SetName sets the Name field's value. +func (s *Project) SetName(v string) *Project { + s.Name = &v + return s +} + +// Represents a request for a purchase offering. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/PurchaseOfferingRequest +type PurchaseOfferingInput struct { + _ struct{} `type:"structure"` + + // The ID of the offering. + OfferingId *string `locationName:"offeringId" min:"32" type:"string"` + + // The ID of the offering promotion to be applied to the purchase. + OfferingPromotionId *string `locationName:"offeringPromotionId" min:"4" type:"string"` + + // The number of device slots you wish to purchase in an offering request. + Quantity *int64 `locationName:"quantity" type:"integer"` +} + +// String returns the string representation +func (s PurchaseOfferingInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s PurchaseOfferingInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *PurchaseOfferingInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "PurchaseOfferingInput"} + if s.OfferingId != nil && len(*s.OfferingId) < 32 { + invalidParams.Add(request.NewErrParamMinLen("OfferingId", 32)) + } + if s.OfferingPromotionId != nil && len(*s.OfferingPromotionId) < 4 { + invalidParams.Add(request.NewErrParamMinLen("OfferingPromotionId", 4)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetOfferingId sets the OfferingId field's value. +func (s *PurchaseOfferingInput) SetOfferingId(v string) *PurchaseOfferingInput { + s.OfferingId = &v + return s +} + +// SetOfferingPromotionId sets the OfferingPromotionId field's value. +func (s *PurchaseOfferingInput) SetOfferingPromotionId(v string) *PurchaseOfferingInput { + s.OfferingPromotionId = &v + return s +} + +// SetQuantity sets the Quantity field's value. +func (s *PurchaseOfferingInput) SetQuantity(v int64) *PurchaseOfferingInput { + s.Quantity = &v + return s +} + +// The result of the purchase offering (e.g., success or failure). +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/PurchaseOfferingResult +type PurchaseOfferingOutput struct { + _ struct{} `type:"structure"` + + // Represents the offering transaction for the purchase result. + OfferingTransaction *OfferingTransaction `locationName:"offeringTransaction" type:"structure"` +} + +// String returns the string representation +func (s PurchaseOfferingOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s PurchaseOfferingOutput) GoString() string { + return s.String() +} + +// SetOfferingTransaction sets the OfferingTransaction field's value. +func (s *PurchaseOfferingOutput) SetOfferingTransaction(v *OfferingTransaction) *PurchaseOfferingOutput { + s.OfferingTransaction = v + return s +} + +// Represents the set of radios and their states on a device. Examples of radios +// include Wi-Fi, GPS, Bluetooth, and NFC. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/Radios +type Radios struct { + _ struct{} `type:"structure"` + + // True if Bluetooth is enabled at the beginning of the test; otherwise, false. + Bluetooth *bool `locationName:"bluetooth" type:"boolean"` + + // True if GPS is enabled at the beginning of the test; otherwise, false. + Gps *bool `locationName:"gps" type:"boolean"` + + // True if NFC is enabled at the beginning of the test; otherwise, false. + Nfc *bool `locationName:"nfc" type:"boolean"` + + // True if Wi-Fi is enabled at the beginning of the test; otherwise, false. + Wifi *bool `locationName:"wifi" type:"boolean"` +} + +// String returns the string representation +func (s Radios) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s Radios) GoString() string { + return s.String() +} + +// SetBluetooth sets the Bluetooth field's value. +func (s *Radios) SetBluetooth(v bool) *Radios { + s.Bluetooth = &v + return s +} + +// SetGps sets the Gps field's value. +func (s *Radios) SetGps(v bool) *Radios { + s.Gps = &v + return s +} + +// SetNfc sets the Nfc field's value. +func (s *Radios) SetNfc(v bool) *Radios { + s.Nfc = &v + return s +} + +// SetWifi sets the Wifi field's value. +func (s *Radios) SetWifi(v bool) *Radios { + s.Wifi = &v + return s +} + +// Specifies whether charges for devices will be recurring. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/RecurringCharge +type RecurringCharge struct { + _ struct{} `type:"structure"` + + // The cost of the recurring charge. + Cost *MonetaryAmount `locationName:"cost" type:"structure"` + + // The frequency in which charges will recur. + Frequency *string `locationName:"frequency" type:"string" enum:"RecurringChargeFrequency"` +} + +// String returns the string representation +func (s RecurringCharge) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s RecurringCharge) GoString() string { + return s.String() +} + +// SetCost sets the Cost field's value. +func (s *RecurringCharge) SetCost(v *MonetaryAmount) *RecurringCharge { + s.Cost = v + return s +} + +// SetFrequency sets the Frequency field's value. +func (s *RecurringCharge) SetFrequency(v string) *RecurringCharge { + s.Frequency = &v + return s +} + +// Represents information about the remote access session. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/RemoteAccessSession +type RemoteAccessSession struct { + _ struct{} `type:"structure"` + + // The Amazon Resource Name (ARN) of the remote access session. + Arn *string `locationName:"arn" min:"32" type:"string"` + + // The billing method of the remote access session. Possible values include + // METERED or UNMETERED. For more information about metered devices, see AWS + // Device Farm terminology (http://docs.aws.amazon.com/devicefarm/latest/developerguide/welcome.html#welcome-terminology)." + BillingMethod *string `locationName:"billingMethod" type:"string" enum:"BillingMethod"` + + // The date and time the remote access session was created. + Created *time.Time `locationName:"created" type:"timestamp" timestampFormat:"unix"` + + // The device (phone or tablet) used in the remote access session. + Device *Device `locationName:"device" type:"structure"` + + // The number of minutes a device is used in a remote access sesssion (including + // setup and teardown minutes). + DeviceMinutes *DeviceMinutes `locationName:"deviceMinutes" type:"structure"` + + // The endpoint for the remote access sesssion. + Endpoint *string `locationName:"endpoint" type:"string"` + + // A message about the remote access session. + Message *string `locationName:"message" type:"string"` + + // The name of the remote access session. + Name *string `locationName:"name" type:"string"` + + // The result of the remote access session. Can be any of the following: + // + // * PENDING: A pending condition. + // + // * PASSED: A passing condition. + // + // * WARNED: A warning condition. + // + // * FAILED: A failed condition. + // + // * SKIPPED: A skipped condition. + // + // * ERRORED: An error condition. + // + // * STOPPED: A stopped condition. + Result *string `locationName:"result" type:"string" enum:"ExecutionResult"` + + // The date and time the remote access session was started. + Started *time.Time `locationName:"started" type:"timestamp" timestampFormat:"unix"` + + // The status of the remote access session. Can be any of the following: + // + // * PENDING: A pending status. + // + // * PENDING_CONCURRENCY: A pending concurrency status. + // + // * PENDING_DEVICE: A pending device status. + // + // * PROCESSING: A processing status. + // + // * SCHEDULING: A scheduling status. + // + // * PREPARING: A preparing status. + // + // * RUNNING: A running status. + // + // * COMPLETED: A completed status. + // + // * STOPPING: A stopping status. + Status *string `locationName:"status" type:"string" enum:"ExecutionStatus"` + + // The date and time the remote access session was stopped. + Stopped *time.Time `locationName:"stopped" type:"timestamp" timestampFormat:"unix"` +} + +// String returns the string representation +func (s RemoteAccessSession) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s RemoteAccessSession) GoString() string { + return s.String() +} + +// SetArn sets the Arn field's value. +func (s *RemoteAccessSession) SetArn(v string) *RemoteAccessSession { + s.Arn = &v + return s +} + +// SetBillingMethod sets the BillingMethod field's value. +func (s *RemoteAccessSession) SetBillingMethod(v string) *RemoteAccessSession { + s.BillingMethod = &v + return s +} + +// SetCreated sets the Created field's value. +func (s *RemoteAccessSession) SetCreated(v time.Time) *RemoteAccessSession { + s.Created = &v + return s +} + +// SetDevice sets the Device field's value. +func (s *RemoteAccessSession) SetDevice(v *Device) *RemoteAccessSession { + s.Device = v + return s +} + +// SetDeviceMinutes sets the DeviceMinutes field's value. +func (s *RemoteAccessSession) SetDeviceMinutes(v *DeviceMinutes) *RemoteAccessSession { + s.DeviceMinutes = v + return s +} + +// SetEndpoint sets the Endpoint field's value. +func (s *RemoteAccessSession) SetEndpoint(v string) *RemoteAccessSession { + s.Endpoint = &v + return s +} + +// SetMessage sets the Message field's value. +func (s *RemoteAccessSession) SetMessage(v string) *RemoteAccessSession { + s.Message = &v + return s +} + +// SetName sets the Name field's value. +func (s *RemoteAccessSession) SetName(v string) *RemoteAccessSession { + s.Name = &v + return s +} + +// SetResult sets the Result field's value. +func (s *RemoteAccessSession) SetResult(v string) *RemoteAccessSession { + s.Result = &v + return s +} + +// SetStarted sets the Started field's value. +func (s *RemoteAccessSession) SetStarted(v time.Time) *RemoteAccessSession { + s.Started = &v + return s +} + +// SetStatus sets the Status field's value. +func (s *RemoteAccessSession) SetStatus(v string) *RemoteAccessSession { + s.Status = &v + return s +} + +// SetStopped sets the Stopped field's value. +func (s *RemoteAccessSession) SetStopped(v time.Time) *RemoteAccessSession { + s.Stopped = &v + return s +} + +// A request representing an offering renewal. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/RenewOfferingRequest +type RenewOfferingInput struct { + _ struct{} `type:"structure"` + + // The ID of a request to renew an offering. + OfferingId *string `locationName:"offeringId" min:"32" type:"string"` + + // The quantity requested in an offering renewal. + Quantity *int64 `locationName:"quantity" type:"integer"` +} + +// String returns the string representation +func (s RenewOfferingInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s RenewOfferingInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *RenewOfferingInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "RenewOfferingInput"} + if s.OfferingId != nil && len(*s.OfferingId) < 32 { + invalidParams.Add(request.NewErrParamMinLen("OfferingId", 32)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetOfferingId sets the OfferingId field's value. +func (s *RenewOfferingInput) SetOfferingId(v string) *RenewOfferingInput { + s.OfferingId = &v + return s +} + +// SetQuantity sets the Quantity field's value. +func (s *RenewOfferingInput) SetQuantity(v int64) *RenewOfferingInput { + s.Quantity = &v + return s +} + +// The result of a renewal offering. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/RenewOfferingResult +type RenewOfferingOutput struct { + _ struct{} `type:"structure"` + + // Represents the status of the offering transaction for the renewal. + OfferingTransaction *OfferingTransaction `locationName:"offeringTransaction" type:"structure"` +} + +// String returns the string representation +func (s RenewOfferingOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s RenewOfferingOutput) GoString() string { + return s.String() +} + +// SetOfferingTransaction sets the OfferingTransaction field's value. +func (s *RenewOfferingOutput) SetOfferingTransaction(v *OfferingTransaction) *RenewOfferingOutput { + s.OfferingTransaction = v + return s +} + +// Represents the screen resolution of a device in height and width, expressed +// in pixels. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/Resolution +type Resolution struct { + _ struct{} `type:"structure"` + + // The screen resolution's height, expressed in pixels. + Height *int64 `locationName:"height" type:"integer"` + + // The screen resolution's width, expressed in pixels. + Width *int64 `locationName:"width" type:"integer"` +} + +// String returns the string representation +func (s Resolution) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s Resolution) GoString() string { + return s.String() +} + +// SetHeight sets the Height field's value. +func (s *Resolution) SetHeight(v int64) *Resolution { + s.Height = &v + return s +} + +// SetWidth sets the Width field's value. +func (s *Resolution) SetWidth(v int64) *Resolution { + s.Width = &v + return s +} + +// Represents a condition for a device pool. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/Rule +type Rule struct { + _ struct{} `type:"structure"` + + // The rule's stringified attribute. For example, specify the value as "\"abc\"". + // + // Allowed values include: + // + // * ARN: The ARN. + // + // * FORM_FACTOR: The form factor (for example, phone or tablet). + // + // * MANUFACTURER: The manufacturer. + // + // * PLATFORM: The platform (for example, Android or iOS). + // + // * REMOTE_ACCESS_ENABLED: Whether the device is enabled for remote access. + // + // * APPIUM_VERSION: The Appium version for the test. + Attribute *string `locationName:"attribute" type:"string" enum:"DeviceAttribute"` + + // The rule's operator. + // + // * EQUALS: The equals operator. + // + // * GREATER_THAN: The greater-than operator. + // + // * IN: The in operator. + // + // * LESS_THAN: The less-than operator. + // + // * NOT_IN: The not-in operator. + // + // * CONTAINS: The contains operator. + Operator *string `locationName:"operator" type:"string" enum:"RuleOperator"` + + // The rule's value. + Value *string `locationName:"value" type:"string"` +} + +// String returns the string representation +func (s Rule) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s Rule) GoString() string { + return s.String() +} + +// SetAttribute sets the Attribute field's value. +func (s *Rule) SetAttribute(v string) *Rule { + s.Attribute = &v + return s +} + +// SetOperator sets the Operator field's value. +func (s *Rule) SetOperator(v string) *Rule { + s.Operator = &v + return s +} + +// SetValue sets the Value field's value. +func (s *Rule) SetValue(v string) *Rule { + s.Value = &v + return s +} + +// Represents an app on a set of devices with a specific test and configuration. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/Run +type Run struct { + _ struct{} `type:"structure"` + + // The run's ARN. + Arn *string `locationName:"arn" min:"32" type:"string"` + + // Specifies the billing method for a test run: metered or unmetered. If the + // parameter is not specified, the default value is metered. + BillingMethod *string `locationName:"billingMethod" type:"string" enum:"BillingMethod"` + + // The total number of completed jobs. + CompletedJobs *int64 `locationName:"completedJobs" type:"integer"` + + // The run's result counters. + Counters *Counters `locationName:"counters" type:"structure"` + + // When the run was created. + Created *time.Time `locationName:"created" type:"timestamp" timestampFormat:"unix"` + + // Represents the total (metered or unmetered) minutes used by the test run. + DeviceMinutes *DeviceMinutes `locationName:"deviceMinutes" type:"structure"` + + // A message about the run's result. + Message *string `locationName:"message" type:"string"` + + // The run's name. + Name *string `locationName:"name" type:"string"` + + // The network profile being used for a test run. + NetworkProfile *NetworkProfile `locationName:"networkProfile" type:"structure"` + + // The run's platform. + // + // Allowed values include: + // + // * ANDROID: The Android platform. + // + // * IOS: The iOS platform. + Platform *string `locationName:"platform" type:"string" enum:"DevicePlatform"` + + // The run's result. + // + // Allowed values include: + // + // * PENDING: A pending condition. + // + // * PASSED: A passing condition. + // + // * WARNED: A warning condition. + // + // * FAILED: A failed condition. + // + // * SKIPPED: A skipped condition. + // + // * ERRORED: An error condition. + // + // * STOPPED: A stopped condition. + Result *string `locationName:"result" type:"string" enum:"ExecutionResult"` + + // The run's start time. + Started *time.Time `locationName:"started" type:"timestamp" timestampFormat:"unix"` + + // The run's status. + // + // Allowed values include: + // + // * PENDING: A pending status. + // + // * PENDING_CONCURRENCY: A pending concurrency status. + // + // * PENDING_DEVICE: A pending device status. + // + // * PROCESSING: A processing status. + // + // * SCHEDULING: A scheduling status. + // + // * PREPARING: A preparing status. + // + // * RUNNING: A running status. + // + // * COMPLETED: A completed status. + // + // * STOPPING: A stopping status. + Status *string `locationName:"status" type:"string" enum:"ExecutionStatus"` + + // The run's stop time. + Stopped *time.Time `locationName:"stopped" type:"timestamp" timestampFormat:"unix"` + + // The total number of jobs for the run. + TotalJobs *int64 `locationName:"totalJobs" type:"integer"` + + // The run's type. + // + // Must be one of the following values: + // + // * BUILTIN_FUZZ: The built-in fuzz type. + // + // * BUILTIN_EXPLORER: For Android, an app explorer that will traverse an + // Android app, interacting with it and capturing screenshots at the same + // time. + // + // * APPIUM_JAVA_JUNIT: The Appium Java JUnit type. + // + // * APPIUM_JAVA_TESTNG: The Appium Java TestNG type. + // + // * APPIUM_PYTHON: The Appium Python type. + // + // * APPIUM_WEB_JAVA_JUNIT: The Appium Java JUnit type for Web apps. + // + // * APPIUM_WEB_JAVA_TESTNG: The Appium Java TestNG type for Web apps. + // + // * APPIUM_WEB_PYTHON: The Appium Python type for Web apps. + // + // * CALABASH: The Calabash type. + // + // * INSTRUMENTATION: The Instrumentation type. + // + // * UIAUTOMATION: The uiautomation type. + // + // * UIAUTOMATOR: The uiautomator type. + // + // * XCTEST: The XCode test type. + // + // * XCTEST_UI: The XCode UI test type. + Type *string `locationName:"type" type:"string" enum:"TestType"` +} + +// String returns the string representation +func (s Run) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s Run) GoString() string { + return s.String() +} + +// SetArn sets the Arn field's value. +func (s *Run) SetArn(v string) *Run { + s.Arn = &v + return s +} + +// SetBillingMethod sets the BillingMethod field's value. +func (s *Run) SetBillingMethod(v string) *Run { + s.BillingMethod = &v + return s +} + +// SetCompletedJobs sets the CompletedJobs field's value. +func (s *Run) SetCompletedJobs(v int64) *Run { + s.CompletedJobs = &v + return s +} + +// SetCounters sets the Counters field's value. +func (s *Run) SetCounters(v *Counters) *Run { + s.Counters = v + return s +} + +// SetCreated sets the Created field's value. +func (s *Run) SetCreated(v time.Time) *Run { + s.Created = &v + return s +} + +// SetDeviceMinutes sets the DeviceMinutes field's value. +func (s *Run) SetDeviceMinutes(v *DeviceMinutes) *Run { + s.DeviceMinutes = v + return s +} + +// SetMessage sets the Message field's value. +func (s *Run) SetMessage(v string) *Run { + s.Message = &v + return s +} + +// SetName sets the Name field's value. +func (s *Run) SetName(v string) *Run { + s.Name = &v + return s +} + +// SetNetworkProfile sets the NetworkProfile field's value. +func (s *Run) SetNetworkProfile(v *NetworkProfile) *Run { + s.NetworkProfile = v + return s +} + +// SetPlatform sets the Platform field's value. +func (s *Run) SetPlatform(v string) *Run { + s.Platform = &v + return s +} + +// SetResult sets the Result field's value. +func (s *Run) SetResult(v string) *Run { + s.Result = &v + return s +} + +// SetStarted sets the Started field's value. +func (s *Run) SetStarted(v time.Time) *Run { + s.Started = &v + return s +} + +// SetStatus sets the Status field's value. +func (s *Run) SetStatus(v string) *Run { + s.Status = &v + return s +} + +// SetStopped sets the Stopped field's value. +func (s *Run) SetStopped(v time.Time) *Run { + s.Stopped = &v + return s +} + +// SetTotalJobs sets the TotalJobs field's value. +func (s *Run) SetTotalJobs(v int64) *Run { + s.TotalJobs = &v + return s +} + +// SetType sets the Type field's value. +func (s *Run) SetType(v string) *Run { + s.Type = &v + return s +} + +// Represents a sample of performance data. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/Sample +type Sample struct { + _ struct{} `type:"structure"` + + // The sample's ARN. + Arn *string `locationName:"arn" min:"32" type:"string"` + + // The sample's type. + // + // Must be one of the following values: + // + // * CPU: A CPU sample type. This is expressed as the app processing CPU + // time (including child processes) as reported by process, as a percentage. + // + // * MEMORY: A memory usage sample type. This is expressed as the total proportional + // set size of an app process, in kilobytes. + // + // * NATIVE_AVG_DRAWTIME + // + // * NATIVE_FPS + // + // * NATIVE_FRAMES + // + // * NATIVE_MAX_DRAWTIME + // + // * NATIVE_MIN_DRAWTIME + // + // * OPENGL_AVG_DRAWTIME + // + // * OPENGL_FPS + // + // * OPENGL_FRAMES + // + // * OPENGL_MAX_DRAWTIME + // + // * OPENGL_MIN_DRAWTIME + // + // * RX + // + // * RX_RATE: The total number of bytes per second (TCP and UDP) that are + // sent, by app process. + // + // * THREADS: A threads sample type. This is expressed as the total number + // of threads per app process. + // + // * TX + // + // * TX_RATE: The total number of bytes per second (TCP and UDP) that are + // received, by app process. + Type *string `locationName:"type" type:"string" enum:"SampleType"` + + // The pre-signed Amazon S3 URL that can be used with a corresponding GET request + // to download the sample's file. + Url *string `locationName:"url" type:"string"` +} + +// String returns the string representation +func (s Sample) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s Sample) GoString() string { + return s.String() +} + +// SetArn sets the Arn field's value. +func (s *Sample) SetArn(v string) *Sample { + s.Arn = &v + return s +} + +// SetType sets the Type field's value. +func (s *Sample) SetType(v string) *Sample { + s.Type = &v + return s +} + +// SetUrl sets the Url field's value. +func (s *Sample) SetUrl(v string) *Sample { + s.Url = &v + return s +} + +// Represents the settings for a run. Includes things like location, radio states, +// auxiliary apps, and network profiles. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/ScheduleRunConfiguration +type ScheduleRunConfiguration struct { + _ struct{} `type:"structure"` + + // A list of auxiliary apps for the run. + AuxiliaryApps []*string `locationName:"auxiliaryApps" type:"list"` + + // Specifies the billing method for a test run: metered or unmetered. If the + // parameter is not specified, the default value is metered. + BillingMethod *string `locationName:"billingMethod" type:"string" enum:"BillingMethod"` + + // The ARN of the extra data for the run. The extra data is a .zip file that + // AWS Device Farm will extract to external data for Android or the app's sandbox + // for iOS. + ExtraDataPackageArn *string `locationName:"extraDataPackageArn" min:"32" type:"string"` + + // Information about the locale that is used for the run. + Locale *string `locationName:"locale" type:"string"` + + // Information about the location that is used for the run. + Location *Location `locationName:"location" type:"structure"` + + // Reserved for internal use. + NetworkProfileArn *string `locationName:"networkProfileArn" min:"32" type:"string"` + + // Information about the radio states for the run. + Radios *Radios `locationName:"radios" type:"structure"` +} + +// String returns the string representation +func (s ScheduleRunConfiguration) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ScheduleRunConfiguration) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *ScheduleRunConfiguration) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "ScheduleRunConfiguration"} + if s.ExtraDataPackageArn != nil && len(*s.ExtraDataPackageArn) < 32 { + invalidParams.Add(request.NewErrParamMinLen("ExtraDataPackageArn", 32)) + } + if s.NetworkProfileArn != nil && len(*s.NetworkProfileArn) < 32 { + invalidParams.Add(request.NewErrParamMinLen("NetworkProfileArn", 32)) + } + if s.Location != nil { + if err := s.Location.Validate(); err != nil { + invalidParams.AddNested("Location", err.(request.ErrInvalidParams)) + } + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetAuxiliaryApps sets the AuxiliaryApps field's value. +func (s *ScheduleRunConfiguration) SetAuxiliaryApps(v []*string) *ScheduleRunConfiguration { + s.AuxiliaryApps = v + return s +} + +// SetBillingMethod sets the BillingMethod field's value. +func (s *ScheduleRunConfiguration) SetBillingMethod(v string) *ScheduleRunConfiguration { + s.BillingMethod = &v + return s +} + +// SetExtraDataPackageArn sets the ExtraDataPackageArn field's value. +func (s *ScheduleRunConfiguration) SetExtraDataPackageArn(v string) *ScheduleRunConfiguration { + s.ExtraDataPackageArn = &v + return s +} + +// SetLocale sets the Locale field's value. +func (s *ScheduleRunConfiguration) SetLocale(v string) *ScheduleRunConfiguration { + s.Locale = &v + return s +} + +// SetLocation sets the Location field's value. +func (s *ScheduleRunConfiguration) SetLocation(v *Location) *ScheduleRunConfiguration { + s.Location = v + return s +} + +// SetNetworkProfileArn sets the NetworkProfileArn field's value. +func (s *ScheduleRunConfiguration) SetNetworkProfileArn(v string) *ScheduleRunConfiguration { + s.NetworkProfileArn = &v + return s +} + +// SetRadios sets the Radios field's value. +func (s *ScheduleRunConfiguration) SetRadios(v *Radios) *ScheduleRunConfiguration { + s.Radios = v + return s +} + +// Represents a request to the schedule run operation. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/ScheduleRunRequest +type ScheduleRunInput struct { + _ struct{} `type:"structure"` + + // The ARN of the app to schedule a run. + AppArn *string `locationName:"appArn" min:"32" type:"string"` + + // Information about the settings for the run to be scheduled. + Configuration *ScheduleRunConfiguration `locationName:"configuration" type:"structure"` + + // The ARN of the device pool for the run to be scheduled. + // + // DevicePoolArn is a required field + DevicePoolArn *string `locationName:"devicePoolArn" min:"32" type:"string" required:"true"` + + // Specifies configuration information about a test run, such as the execution + // timeout (in minutes). + ExecutionConfiguration *ExecutionConfiguration `locationName:"executionConfiguration" type:"structure"` + + // The name for the run to be scheduled. + Name *string `locationName:"name" type:"string"` + + // The ARN of the project for the run to be scheduled. + // + // ProjectArn is a required field + ProjectArn *string `locationName:"projectArn" min:"32" type:"string" required:"true"` + + // Information about the test for the run to be scheduled. + // + // Test is a required field + Test *ScheduleRunTest `locationName:"test" type:"structure" required:"true"` +} + +// String returns the string representation +func (s ScheduleRunInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ScheduleRunInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *ScheduleRunInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "ScheduleRunInput"} + if s.AppArn != nil && len(*s.AppArn) < 32 { + invalidParams.Add(request.NewErrParamMinLen("AppArn", 32)) + } + if s.DevicePoolArn == nil { + invalidParams.Add(request.NewErrParamRequired("DevicePoolArn")) + } + if s.DevicePoolArn != nil && len(*s.DevicePoolArn) < 32 { + invalidParams.Add(request.NewErrParamMinLen("DevicePoolArn", 32)) + } + if s.ProjectArn == nil { + invalidParams.Add(request.NewErrParamRequired("ProjectArn")) + } + if s.ProjectArn != nil && len(*s.ProjectArn) < 32 { + invalidParams.Add(request.NewErrParamMinLen("ProjectArn", 32)) + } + if s.Test == nil { + invalidParams.Add(request.NewErrParamRequired("Test")) + } + if s.Configuration != nil { + if err := s.Configuration.Validate(); err != nil { + invalidParams.AddNested("Configuration", err.(request.ErrInvalidParams)) + } + } + if s.Test != nil { + if err := s.Test.Validate(); err != nil { + invalidParams.AddNested("Test", err.(request.ErrInvalidParams)) + } + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetAppArn sets the AppArn field's value. +func (s *ScheduleRunInput) SetAppArn(v string) *ScheduleRunInput { + s.AppArn = &v + return s +} + +// SetConfiguration sets the Configuration field's value. +func (s *ScheduleRunInput) SetConfiguration(v *ScheduleRunConfiguration) *ScheduleRunInput { + s.Configuration = v + return s +} + +// SetDevicePoolArn sets the DevicePoolArn field's value. +func (s *ScheduleRunInput) SetDevicePoolArn(v string) *ScheduleRunInput { + s.DevicePoolArn = &v + return s +} + +// SetExecutionConfiguration sets the ExecutionConfiguration field's value. +func (s *ScheduleRunInput) SetExecutionConfiguration(v *ExecutionConfiguration) *ScheduleRunInput { + s.ExecutionConfiguration = v + return s +} + +// SetName sets the Name field's value. +func (s *ScheduleRunInput) SetName(v string) *ScheduleRunInput { + s.Name = &v + return s +} + +// SetProjectArn sets the ProjectArn field's value. +func (s *ScheduleRunInput) SetProjectArn(v string) *ScheduleRunInput { + s.ProjectArn = &v + return s +} + +// SetTest sets the Test field's value. +func (s *ScheduleRunInput) SetTest(v *ScheduleRunTest) *ScheduleRunInput { + s.Test = v + return s +} + +// Represents the result of a schedule run request. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/ScheduleRunResult +type ScheduleRunOutput struct { + _ struct{} `type:"structure"` + + // Information about the scheduled run. + Run *Run `locationName:"run" type:"structure"` +} + +// String returns the string representation +func (s ScheduleRunOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ScheduleRunOutput) GoString() string { + return s.String() +} + +// SetRun sets the Run field's value. +func (s *ScheduleRunOutput) SetRun(v *Run) *ScheduleRunOutput { + s.Run = v + return s +} + +// Represents additional test settings. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/ScheduleRunTest +type ScheduleRunTest struct { + _ struct{} `type:"structure"` + + // The test's filter. + Filter *string `locationName:"filter" type:"string"` + + // The test's parameters, such as the following test framework parameters and + // fixture settings: + // + // For Calabash tests: + // + // * profile: A cucumber profile, for example, "my_profile_name". + // + // * tags: You can limit execution to features or scenarios that have (or + // don't have) certain tags, for example, "@smoke" or "@smoke,~@wip". + // + // For Appium tests (all types): + // + // * appium_version: The Appium version. Currently supported values are "1.4.16", + // "1.6.3", "latest", and "default". + // + // “latest” will run the latest Appium version supported by Device Farm (1.6.3). + // + // For “default”, Device Farm will choose a compatible version of Appium for + // the device. The current behavior is to run 1.4.16 on Android devices and + // iOS 9 and earlier, 1.6.3 for iOS 10 and later. + // + // This behavior is subject to change. + // + // For Fuzz tests (Android only): + // + // * event_count: The number of events, between 1 and 10000, that the UI + // fuzz test should perform. + // + // * throttle: The time, in ms, between 0 and 1000, that the UI fuzz test + // should wait between events. + // + // * seed: A seed to use for randomizing the UI fuzz test. Using the same + // seed value between tests ensures identical event sequences. + // + // For Explorer tests: + // + // * username: A username to use if the Explorer encounters a login form. + // If not supplied, no username will be inserted. + // + // * password: A password to use if the Explorer encounters a login form. + // If not supplied, no password will be inserted. + // + // For Instrumentation: + // + // * filter: A test filter string. Examples: + // + // Running a single test case: "com.android.abc.Test1" + // + // Running a single test: "com.android.abc.Test1#smoke" + // + // Running multiple tests: "com.android.abc.Test1,com.android.abc.Test2" + // + // For XCTest and XCTestUI: + // + // * filter: A test filter string. Examples: + // + // Running a single test class: "LoginTests" + // + // Running a multiple test classes: "LoginTests,SmokeTests" + // + // Running a single test: "LoginTests/testValid" + // + // Running multiple tests: "LoginTests/testValid,LoginTests/testInvalid" + // + // For UIAutomator: + // + // * filter: A test filter string. Examples: + // + // Running a single test case: "com.android.abc.Test1" + // + // Running a single test: "com.android.abc.Test1#smoke" + // + // Running multiple tests: "com.android.abc.Test1,com.android.abc.Test2" + Parameters map[string]*string `locationName:"parameters" type:"map"` + + // The ARN of the uploaded test that will be run. + TestPackageArn *string `locationName:"testPackageArn" min:"32" type:"string"` + + // The test's type. + // + // Must be one of the following values: + // + // * BUILTIN_FUZZ: The built-in fuzz type. + // + // * BUILTIN_EXPLORER: For Android, an app explorer that will traverse an + // Android app, interacting with it and capturing screenshots at the same + // time. + // + // * APPIUM_JAVA_JUNIT: The Appium Java JUnit type. + // + // * APPIUM_JAVA_TESTNG: The Appium Java TestNG type. + // + // * APPIUM_PYTHON: The Appium Python type. + // + // * APPIUM_WEB_JAVA_JUNIT: The Appium Java JUnit type for Web apps. + // + // * APPIUM_WEB_JAVA_TESTNG: The Appium Java TestNG type for Web apps. + // + // * APPIUM_WEB_PYTHON: The Appium Python type for Web apps. + // + // * CALABASH: The Calabash type. + // + // * INSTRUMENTATION: The Instrumentation type. + // + // * UIAUTOMATION: The uiautomation type. + // + // * UIAUTOMATOR: The uiautomator type. + // + // * XCTEST: The XCode test type. + // + // * XCTEST_UI: The XCode UI test type. + // + // Type is a required field + Type *string `locationName:"type" type:"string" required:"true" enum:"TestType"` +} + +// String returns the string representation +func (s ScheduleRunTest) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ScheduleRunTest) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *ScheduleRunTest) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "ScheduleRunTest"} + if s.TestPackageArn != nil && len(*s.TestPackageArn) < 32 { + invalidParams.Add(request.NewErrParamMinLen("TestPackageArn", 32)) + } + if s.Type == nil { + invalidParams.Add(request.NewErrParamRequired("Type")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetFilter sets the Filter field's value. +func (s *ScheduleRunTest) SetFilter(v string) *ScheduleRunTest { + s.Filter = &v + return s +} + +// SetParameters sets the Parameters field's value. +func (s *ScheduleRunTest) SetParameters(v map[string]*string) *ScheduleRunTest { + s.Parameters = v + return s +} + +// SetTestPackageArn sets the TestPackageArn field's value. +func (s *ScheduleRunTest) SetTestPackageArn(v string) *ScheduleRunTest { + s.TestPackageArn = &v + return s +} + +// SetType sets the Type field's value. +func (s *ScheduleRunTest) SetType(v string) *ScheduleRunTest { + s.Type = &v + return s +} + +// Represents the request to stop the remote access session. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/StopRemoteAccessSessionRequest +type StopRemoteAccessSessionInput struct { + _ struct{} `type:"structure"` + + // The Amazon Resource Name (ARN) of the remote access session you wish to stop. + // + // Arn is a required field + Arn *string `locationName:"arn" min:"32" type:"string" required:"true"` +} + +// String returns the string representation +func (s StopRemoteAccessSessionInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s StopRemoteAccessSessionInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *StopRemoteAccessSessionInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "StopRemoteAccessSessionInput"} + if s.Arn == nil { + invalidParams.Add(request.NewErrParamRequired("Arn")) + } + if s.Arn != nil && len(*s.Arn) < 32 { + invalidParams.Add(request.NewErrParamMinLen("Arn", 32)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetArn sets the Arn field's value. +func (s *StopRemoteAccessSessionInput) SetArn(v string) *StopRemoteAccessSessionInput { + s.Arn = &v + return s +} + +// Represents the response from the server that describes the remote access +// session when AWS Device Farm stops the session. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/StopRemoteAccessSessionResult +type StopRemoteAccessSessionOutput struct { + _ struct{} `type:"structure"` + + // A container representing the metadata from the service about the remote access + // session you are stopping. + RemoteAccessSession *RemoteAccessSession `locationName:"remoteAccessSession" type:"structure"` +} + +// String returns the string representation +func (s StopRemoteAccessSessionOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s StopRemoteAccessSessionOutput) GoString() string { + return s.String() +} + +// SetRemoteAccessSession sets the RemoteAccessSession field's value. +func (s *StopRemoteAccessSessionOutput) SetRemoteAccessSession(v *RemoteAccessSession) *StopRemoteAccessSessionOutput { + s.RemoteAccessSession = v + return s +} + +// Represents the request to stop a specific run. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/StopRunRequest +type StopRunInput struct { + _ struct{} `type:"structure"` + + // Represents the Amazon Resource Name (ARN) of the Device Farm run you wish + // to stop. + // + // Arn is a required field + Arn *string `locationName:"arn" min:"32" type:"string" required:"true"` +} + +// String returns the string representation +func (s StopRunInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s StopRunInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *StopRunInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "StopRunInput"} + if s.Arn == nil { + invalidParams.Add(request.NewErrParamRequired("Arn")) + } + if s.Arn != nil && len(*s.Arn) < 32 { + invalidParams.Add(request.NewErrParamMinLen("Arn", 32)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetArn sets the Arn field's value. +func (s *StopRunInput) SetArn(v string) *StopRunInput { + s.Arn = &v + return s +} + +// Represents the results of your stop run attempt. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/StopRunResult +type StopRunOutput struct { + _ struct{} `type:"structure"` + + // The run that was stopped. + Run *Run `locationName:"run" type:"structure"` +} + +// String returns the string representation +func (s StopRunOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s StopRunOutput) GoString() string { + return s.String() +} + +// SetRun sets the Run field's value. +func (s *StopRunOutput) SetRun(v *Run) *StopRunOutput { + s.Run = v + return s +} + +// Represents a collection of one or more tests. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/Suite +type Suite struct { + _ struct{} `type:"structure"` + + // The suite's ARN. + Arn *string `locationName:"arn" min:"32" type:"string"` + + // The suite's result counters. + Counters *Counters `locationName:"counters" type:"structure"` + + // When the suite was created. + Created *time.Time `locationName:"created" type:"timestamp" timestampFormat:"unix"` + + // Represents the total (metered or unmetered) minutes used by the test suite. + DeviceMinutes *DeviceMinutes `locationName:"deviceMinutes" type:"structure"` + + // A message about the suite's result. + Message *string `locationName:"message" type:"string"` + + // The suite's name. + Name *string `locationName:"name" type:"string"` + + // The suite's result. + // + // Allowed values include: + // + // * PENDING: A pending condition. + // + // * PASSED: A passing condition. + // + // * WARNED: A warning condition. + // + // * FAILED: A failed condition. + // + // * SKIPPED: A skipped condition. + // + // * ERRORED: An error condition. + // + // * STOPPED: A stopped condition. + Result *string `locationName:"result" type:"string" enum:"ExecutionResult"` + + // The suite's start time. + Started *time.Time `locationName:"started" type:"timestamp" timestampFormat:"unix"` + + // The suite's status. + // + // Allowed values include: + // + // * PENDING: A pending status. + // + // * PENDING_CONCURRENCY: A pending concurrency status. + // + // * PENDING_DEVICE: A pending device status. + // + // * PROCESSING: A processing status. + // + // * SCHEDULING: A scheduling status. + // + // * PREPARING: A preparing status. + // + // * RUNNING: A running status. + // + // * COMPLETED: A completed status. + // + // * STOPPING: A stopping status. + Status *string `locationName:"status" type:"string" enum:"ExecutionStatus"` + + // The suite's stop time. + Stopped *time.Time `locationName:"stopped" type:"timestamp" timestampFormat:"unix"` + + // The suite's type. + // + // Must be one of the following values: + // + // * BUILTIN_FUZZ: The built-in fuzz type. + // + // * BUILTIN_EXPLORER: For Android, an app explorer that will traverse an + // Android app, interacting with it and capturing screenshots at the same + // time. + // + // * APPIUM_JAVA_JUNIT: The Appium Java JUnit type. + // + // * APPIUM_JAVA_TESTNG: The Appium Java TestNG type. + // + // * APPIUM_PYTHON: The Appium Python type. + // + // * APPIUM_WEB_JAVA_JUNIT: The Appium Java JUnit type for Web apps. + // + // * APPIUM_WEB_JAVA_TESTNG: The Appium Java TestNG type for Web apps. + // + // * APPIUM_WEB_PYTHON: The Appium Python type for Web apps. + // + // * CALABASH: The Calabash type. + // + // * INSTRUMENTATION: The Instrumentation type. + // + // * UIAUTOMATION: The uiautomation type. + // + // * UIAUTOMATOR: The uiautomator type. + // + // * XCTEST: The XCode test type. + // + // * XCTEST_UI: The XCode UI test type. + Type *string `locationName:"type" type:"string" enum:"TestType"` +} + +// String returns the string representation +func (s Suite) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s Suite) GoString() string { + return s.String() +} + +// SetArn sets the Arn field's value. +func (s *Suite) SetArn(v string) *Suite { + s.Arn = &v + return s +} + +// SetCounters sets the Counters field's value. +func (s *Suite) SetCounters(v *Counters) *Suite { + s.Counters = v + return s +} + +// SetCreated sets the Created field's value. +func (s *Suite) SetCreated(v time.Time) *Suite { + s.Created = &v + return s +} + +// SetDeviceMinutes sets the DeviceMinutes field's value. +func (s *Suite) SetDeviceMinutes(v *DeviceMinutes) *Suite { + s.DeviceMinutes = v + return s +} + +// SetMessage sets the Message field's value. +func (s *Suite) SetMessage(v string) *Suite { + s.Message = &v + return s +} + +// SetName sets the Name field's value. +func (s *Suite) SetName(v string) *Suite { + s.Name = &v + return s +} + +// SetResult sets the Result field's value. +func (s *Suite) SetResult(v string) *Suite { + s.Result = &v + return s +} + +// SetStarted sets the Started field's value. +func (s *Suite) SetStarted(v time.Time) *Suite { + s.Started = &v + return s +} + +// SetStatus sets the Status field's value. +func (s *Suite) SetStatus(v string) *Suite { + s.Status = &v + return s +} + +// SetStopped sets the Stopped field's value. +func (s *Suite) SetStopped(v time.Time) *Suite { + s.Stopped = &v + return s +} + +// SetType sets the Type field's value. +func (s *Suite) SetType(v string) *Suite { + s.Type = &v + return s +} + +// Represents a condition that is evaluated. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/Test +type Test struct { + _ struct{} `type:"structure"` + + // The test's ARN. + Arn *string `locationName:"arn" min:"32" type:"string"` + + // The test's result counters. + Counters *Counters `locationName:"counters" type:"structure"` + + // When the test was created. + Created *time.Time `locationName:"created" type:"timestamp" timestampFormat:"unix"` + + // Represents the total (metered or unmetered) minutes used by the test. + DeviceMinutes *DeviceMinutes `locationName:"deviceMinutes" type:"structure"` + + // A message about the test's result. + Message *string `locationName:"message" type:"string"` + + // The test's name. + Name *string `locationName:"name" type:"string"` + + // The test's result. + // + // Allowed values include: + // + // * PENDING: A pending condition. + // + // * PASSED: A passing condition. + // + // * WARNED: A warning condition. + // + // * FAILED: A failed condition. + // + // * SKIPPED: A skipped condition. + // + // * ERRORED: An error condition. + // + // * STOPPED: A stopped condition. + Result *string `locationName:"result" type:"string" enum:"ExecutionResult"` + + // The test's start time. + Started *time.Time `locationName:"started" type:"timestamp" timestampFormat:"unix"` + + // The test's status. + // + // Allowed values include: + // + // * PENDING: A pending status. + // + // * PENDING_CONCURRENCY: A pending concurrency status. + // + // * PENDING_DEVICE: A pending device status. + // + // * PROCESSING: A processing status. + // + // * SCHEDULING: A scheduling status. + // + // * PREPARING: A preparing status. + // + // * RUNNING: A running status. + // + // * COMPLETED: A completed status. + // + // * STOPPING: A stopping status. + Status *string `locationName:"status" type:"string" enum:"ExecutionStatus"` + + // The test's stop time. + Stopped *time.Time `locationName:"stopped" type:"timestamp" timestampFormat:"unix"` + + // The test's type. + // + // Must be one of the following values: + // + // * BUILTIN_FUZZ: The built-in fuzz type. + // + // * BUILTIN_EXPLORER: For Android, an app explorer that will traverse an + // Android app, interacting with it and capturing screenshots at the same + // time. + // + // * APPIUM_JAVA_JUNIT: The Appium Java JUnit type. + // + // * APPIUM_JAVA_TESTNG: The Appium Java TestNG type. + // + // * APPIUM_PYTHON: The Appium Python type. + // + // * APPIUM_WEB_JAVA_JUNIT: The Appium Java JUnit type for Web apps. + // + // * APPIUM_WEB_JAVA_TESTNG: The Appium Java TestNG type for Web apps. + // + // * APPIUM_WEB_PYTHON: The Appium Python type for Web apps. + // + // * CALABASH: The Calabash type. + // + // * INSTRUMENTATION: The Instrumentation type. + // + // * UIAUTOMATION: The uiautomation type. + // + // * UIAUTOMATOR: The uiautomator type. + // + // * XCTEST: The XCode test type. + // + // * XCTEST_UI: The XCode UI test type. + Type *string `locationName:"type" type:"string" enum:"TestType"` +} + +// String returns the string representation +func (s Test) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s Test) GoString() string { + return s.String() +} + +// SetArn sets the Arn field's value. +func (s *Test) SetArn(v string) *Test { + s.Arn = &v + return s +} + +// SetCounters sets the Counters field's value. +func (s *Test) SetCounters(v *Counters) *Test { + s.Counters = v + return s +} + +// SetCreated sets the Created field's value. +func (s *Test) SetCreated(v time.Time) *Test { + s.Created = &v + return s +} + +// SetDeviceMinutes sets the DeviceMinutes field's value. +func (s *Test) SetDeviceMinutes(v *DeviceMinutes) *Test { + s.DeviceMinutes = v + return s +} + +// SetMessage sets the Message field's value. +func (s *Test) SetMessage(v string) *Test { + s.Message = &v + return s +} + +// SetName sets the Name field's value. +func (s *Test) SetName(v string) *Test { + s.Name = &v + return s +} + +// SetResult sets the Result field's value. +func (s *Test) SetResult(v string) *Test { + s.Result = &v + return s +} + +// SetStarted sets the Started field's value. +func (s *Test) SetStarted(v time.Time) *Test { + s.Started = &v + return s +} + +// SetStatus sets the Status field's value. +func (s *Test) SetStatus(v string) *Test { + s.Status = &v + return s +} + +// SetStopped sets the Stopped field's value. +func (s *Test) SetStopped(v time.Time) *Test { + s.Stopped = &v + return s +} + +// SetType sets the Type field's value. +func (s *Test) SetType(v string) *Test { + s.Type = &v + return s +} + +// Represents information about free trial device minutes for an AWS account. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/TrialMinutes +type TrialMinutes struct { + _ struct{} `type:"structure"` + + // The number of free trial minutes remaining in the account. + Remaining *float64 `locationName:"remaining" type:"double"` + + // The total number of free trial minutes that the account started with. + Total *float64 `locationName:"total" type:"double"` +} + +// String returns the string representation +func (s TrialMinutes) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s TrialMinutes) GoString() string { + return s.String() +} + +// SetRemaining sets the Remaining field's value. +func (s *TrialMinutes) SetRemaining(v float64) *TrialMinutes { + s.Remaining = &v + return s +} + +// SetTotal sets the Total field's value. +func (s *TrialMinutes) SetTotal(v float64) *TrialMinutes { + s.Total = &v + return s +} + +// A collection of one or more problems, grouped by their result. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/UniqueProblem +type UniqueProblem struct { + _ struct{} `type:"structure"` + + // A message about the unique problems' result. + Message *string `locationName:"message" type:"string"` + + // Information about the problems. + Problems []*Problem `locationName:"problems" type:"list"` +} + +// String returns the string representation +func (s UniqueProblem) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s UniqueProblem) GoString() string { + return s.String() +} + +// SetMessage sets the Message field's value. +func (s *UniqueProblem) SetMessage(v string) *UniqueProblem { + s.Message = &v + return s +} + +// SetProblems sets the Problems field's value. +func (s *UniqueProblem) SetProblems(v []*Problem) *UniqueProblem { + s.Problems = v + return s +} + +// Represents a request to the update device pool operation. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/UpdateDevicePoolRequest +type UpdateDevicePoolInput struct { + _ struct{} `type:"structure"` + + // The Amazon Resourc Name (ARN) of the Device Farm device pool you wish to + // update. + // + // Arn is a required field + Arn *string `locationName:"arn" min:"32" type:"string" required:"true"` + + // A description of the device pool you wish to update. + Description *string `locationName:"description" type:"string"` + + // A string representing the name of the device pool you wish to update. + Name *string `locationName:"name" type:"string"` + + // Represents the rules you wish to modify for the device pool. Updating rules + // is optional; however, if you choose to update rules for your request, the + // update will replace the existing rules. + Rules []*Rule `locationName:"rules" type:"list"` +} + +// String returns the string representation +func (s UpdateDevicePoolInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s UpdateDevicePoolInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *UpdateDevicePoolInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "UpdateDevicePoolInput"} + if s.Arn == nil { + invalidParams.Add(request.NewErrParamRequired("Arn")) + } + if s.Arn != nil && len(*s.Arn) < 32 { + invalidParams.Add(request.NewErrParamMinLen("Arn", 32)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetArn sets the Arn field's value. +func (s *UpdateDevicePoolInput) SetArn(v string) *UpdateDevicePoolInput { + s.Arn = &v + return s +} + +// SetDescription sets the Description field's value. +func (s *UpdateDevicePoolInput) SetDescription(v string) *UpdateDevicePoolInput { + s.Description = &v + return s +} + +// SetName sets the Name field's value. +func (s *UpdateDevicePoolInput) SetName(v string) *UpdateDevicePoolInput { + s.Name = &v + return s +} + +// SetRules sets the Rules field's value. +func (s *UpdateDevicePoolInput) SetRules(v []*Rule) *UpdateDevicePoolInput { + s.Rules = v + return s +} + +// Represents the result of an update device pool request. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/UpdateDevicePoolResult +type UpdateDevicePoolOutput struct { + _ struct{} `type:"structure"` + + // The device pool you just updated. + DevicePool *DevicePool `locationName:"devicePool" type:"structure"` +} + +// String returns the string representation +func (s UpdateDevicePoolOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s UpdateDevicePoolOutput) GoString() string { + return s.String() +} + +// SetDevicePool sets the DevicePool field's value. +func (s *UpdateDevicePoolOutput) SetDevicePool(v *DevicePool) *UpdateDevicePoolOutput { + s.DevicePool = v + return s +} + +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/UpdateNetworkProfileRequest +type UpdateNetworkProfileInput struct { + _ struct{} `type:"structure"` + + // The Amazon Resource Name (ARN) of the project that you wish to update network + // profile settings. + // + // Arn is a required field + Arn *string `locationName:"arn" min:"32" type:"string" required:"true"` + + // The descriptoin of the network profile about which you are returning information. + Description *string `locationName:"description" type:"string"` + + // The data throughput rate in bits per second, as an integer from 0 to 104857600. + DownlinkBandwidthBits *int64 `locationName:"downlinkBandwidthBits" type:"long"` + + // Delay time for all packets to destination in milliseconds as an integer from + // 0 to 2000. + DownlinkDelayMs *int64 `locationName:"downlinkDelayMs" type:"long"` + + // Time variation in the delay of received packets in milliseconds as an integer + // from 0 to 2000. + DownlinkJitterMs *int64 `locationName:"downlinkJitterMs" type:"long"` + + // Proportion of received packets that fail to arrive from 0 to 100 percent. + DownlinkLossPercent *int64 `locationName:"downlinkLossPercent" type:"integer"` + + // The name of the network profile about which you are returning information. + Name *string `locationName:"name" type:"string"` + + // The type of network profile you wish to return information about. Valid values + // are listed below. + Type *string `locationName:"type" type:"string" enum:"NetworkProfileType"` + + // The data throughput rate in bits per second, as an integer from 0 to 104857600. + UplinkBandwidthBits *int64 `locationName:"uplinkBandwidthBits" type:"long"` + + // Delay time for all packets to destination in milliseconds as an integer from + // 0 to 2000. + UplinkDelayMs *int64 `locationName:"uplinkDelayMs" type:"long"` + + // Time variation in the delay of received packets in milliseconds as an integer + // from 0 to 2000. + UplinkJitterMs *int64 `locationName:"uplinkJitterMs" type:"long"` + + // Proportion of transmitted packets that fail to arrive from 0 to 100 percent. + UplinkLossPercent *int64 `locationName:"uplinkLossPercent" type:"integer"` +} + +// String returns the string representation +func (s UpdateNetworkProfileInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s UpdateNetworkProfileInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *UpdateNetworkProfileInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "UpdateNetworkProfileInput"} + if s.Arn == nil { + invalidParams.Add(request.NewErrParamRequired("Arn")) + } + if s.Arn != nil && len(*s.Arn) < 32 { + invalidParams.Add(request.NewErrParamMinLen("Arn", 32)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetArn sets the Arn field's value. +func (s *UpdateNetworkProfileInput) SetArn(v string) *UpdateNetworkProfileInput { + s.Arn = &v + return s +} + +// SetDescription sets the Description field's value. +func (s *UpdateNetworkProfileInput) SetDescription(v string) *UpdateNetworkProfileInput { + s.Description = &v + return s +} + +// SetDownlinkBandwidthBits sets the DownlinkBandwidthBits field's value. +func (s *UpdateNetworkProfileInput) SetDownlinkBandwidthBits(v int64) *UpdateNetworkProfileInput { + s.DownlinkBandwidthBits = &v + return s +} + +// SetDownlinkDelayMs sets the DownlinkDelayMs field's value. +func (s *UpdateNetworkProfileInput) SetDownlinkDelayMs(v int64) *UpdateNetworkProfileInput { + s.DownlinkDelayMs = &v + return s +} + +// SetDownlinkJitterMs sets the DownlinkJitterMs field's value. +func (s *UpdateNetworkProfileInput) SetDownlinkJitterMs(v int64) *UpdateNetworkProfileInput { + s.DownlinkJitterMs = &v + return s +} + +// SetDownlinkLossPercent sets the DownlinkLossPercent field's value. +func (s *UpdateNetworkProfileInput) SetDownlinkLossPercent(v int64) *UpdateNetworkProfileInput { + s.DownlinkLossPercent = &v + return s +} + +// SetName sets the Name field's value. +func (s *UpdateNetworkProfileInput) SetName(v string) *UpdateNetworkProfileInput { + s.Name = &v + return s +} + +// SetType sets the Type field's value. +func (s *UpdateNetworkProfileInput) SetType(v string) *UpdateNetworkProfileInput { + s.Type = &v + return s +} + +// SetUplinkBandwidthBits sets the UplinkBandwidthBits field's value. +func (s *UpdateNetworkProfileInput) SetUplinkBandwidthBits(v int64) *UpdateNetworkProfileInput { + s.UplinkBandwidthBits = &v + return s +} + +// SetUplinkDelayMs sets the UplinkDelayMs field's value. +func (s *UpdateNetworkProfileInput) SetUplinkDelayMs(v int64) *UpdateNetworkProfileInput { + s.UplinkDelayMs = &v + return s +} + +// SetUplinkJitterMs sets the UplinkJitterMs field's value. +func (s *UpdateNetworkProfileInput) SetUplinkJitterMs(v int64) *UpdateNetworkProfileInput { + s.UplinkJitterMs = &v + return s +} + +// SetUplinkLossPercent sets the UplinkLossPercent field's value. +func (s *UpdateNetworkProfileInput) SetUplinkLossPercent(v int64) *UpdateNetworkProfileInput { + s.UplinkLossPercent = &v + return s +} + +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/UpdateNetworkProfileResult +type UpdateNetworkProfileOutput struct { + _ struct{} `type:"structure"` + + // A list of the available network profiles. + NetworkProfile *NetworkProfile `locationName:"networkProfile" type:"structure"` +} + +// String returns the string representation +func (s UpdateNetworkProfileOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s UpdateNetworkProfileOutput) GoString() string { + return s.String() +} + +// SetNetworkProfile sets the NetworkProfile field's value. +func (s *UpdateNetworkProfileOutput) SetNetworkProfile(v *NetworkProfile) *UpdateNetworkProfileOutput { + s.NetworkProfile = v + return s +} + +// Represents a request to the update project operation. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/UpdateProjectRequest +type UpdateProjectInput struct { + _ struct{} `type:"structure"` + + // The Amazon Resource Name (ARN) of the project whose name you wish to update. + // + // Arn is a required field + Arn *string `locationName:"arn" min:"32" type:"string" required:"true"` + + // The number of minutes a test run in the project will execute before it times + // out. + DefaultJobTimeoutMinutes *int64 `locationName:"defaultJobTimeoutMinutes" type:"integer"` + + // A string representing the new name of the project that you are updating. + Name *string `locationName:"name" type:"string"` +} + +// String returns the string representation +func (s UpdateProjectInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s UpdateProjectInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *UpdateProjectInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "UpdateProjectInput"} + if s.Arn == nil { + invalidParams.Add(request.NewErrParamRequired("Arn")) + } + if s.Arn != nil && len(*s.Arn) < 32 { + invalidParams.Add(request.NewErrParamMinLen("Arn", 32)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetArn sets the Arn field's value. +func (s *UpdateProjectInput) SetArn(v string) *UpdateProjectInput { + s.Arn = &v + return s +} + +// SetDefaultJobTimeoutMinutes sets the DefaultJobTimeoutMinutes field's value. +func (s *UpdateProjectInput) SetDefaultJobTimeoutMinutes(v int64) *UpdateProjectInput { + s.DefaultJobTimeoutMinutes = &v + return s +} + +// SetName sets the Name field's value. +func (s *UpdateProjectInput) SetName(v string) *UpdateProjectInput { + s.Name = &v + return s +} + +// Represents the result of an update project request. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/UpdateProjectResult +type UpdateProjectOutput struct { + _ struct{} `type:"structure"` + + // The project you wish to update. + Project *Project `locationName:"project" type:"structure"` +} + +// String returns the string representation +func (s UpdateProjectOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s UpdateProjectOutput) GoString() string { + return s.String() +} + +// SetProject sets the Project field's value. +func (s *UpdateProjectOutput) SetProject(v *Project) *UpdateProjectOutput { + s.Project = v + return s +} + +// An app or a set of one or more tests to upload or that have been uploaded. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/Upload +type Upload struct { + _ struct{} `type:"structure"` + + // The upload's ARN. + Arn *string `locationName:"arn" min:"32" type:"string"` + + // The upload's content type (for example, "application/octet-stream"). + ContentType *string `locationName:"contentType" type:"string"` + + // When the upload was created. + Created *time.Time `locationName:"created" type:"timestamp" timestampFormat:"unix"` + + // A message about the upload's result. + Message *string `locationName:"message" type:"string"` + + // The upload's metadata. For example, for Android, this contains information + // that is parsed from the manifest and is displayed in the AWS Device Farm + // console after the associated app is uploaded. + Metadata *string `locationName:"metadata" type:"string"` + + // The upload's file name. + Name *string `locationName:"name" type:"string"` + + // The upload's status. + // + // Must be one of the following values: + // + // * FAILED: A failed status. + // + // * INITIALIZED: An initialized status. + // + // * PROCESSING: A processing status. + // + // * SUCCEEDED: A succeeded status. + Status *string `locationName:"status" type:"string" enum:"UploadStatus"` + + // The upload's type. + // + // Must be one of the following values: + // + // * ANDROID_APP: An Android upload. + // + // * IOS_APP: An iOS upload. + // + // * WEB_APP: A web appliction upload. + // + // * EXTERNAL_DATA: An external data upload. + // + // * APPIUM_JAVA_JUNIT_TEST_PACKAGE: An Appium Java JUnit test package upload. + // + // * APPIUM_JAVA_TESTNG_TEST_PACKAGE: An Appium Java TestNG test package + // upload. + // + // * APPIUM_PYTHON_TEST_PACKAGE: An Appium Python test package upload. + // + // * APPIUM_WEB_JAVA_JUNIT_TEST_PACKAGE: An Appium Java JUnit test package + // upload. + // + // * APPIUM_WEB_JAVA_TESTNG_TEST_PACKAGE: An Appium Java TestNG test package + // upload. + // + // * APPIUM_WEB_PYTHON_TEST_PACKAGE: An Appium Python test package upload. + // + // * CALABASH_TEST_PACKAGE: A Calabash test package upload. + // + // * INSTRUMENTATION_TEST_PACKAGE: An instrumentation upload. + // + // * UIAUTOMATION_TEST_PACKAGE: A uiautomation test package upload. + // + // * UIAUTOMATOR_TEST_PACKAGE: A uiautomator test package upload. + // + // * XCTEST_TEST_PACKAGE: An XCode test package upload. + // + // * XCTEST_UI_TEST_PACKAGE: An XCode UI test package upload. + Type *string `locationName:"type" type:"string" enum:"UploadType"` + + // The pre-signed Amazon S3 URL that was used to store a file through a corresponding + // PUT request. + Url *string `locationName:"url" type:"string"` +} + +// String returns the string representation +func (s Upload) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s Upload) GoString() string { + return s.String() +} + +// SetArn sets the Arn field's value. +func (s *Upload) SetArn(v string) *Upload { + s.Arn = &v + return s +} + +// SetContentType sets the ContentType field's value. +func (s *Upload) SetContentType(v string) *Upload { + s.ContentType = &v + return s +} + +// SetCreated sets the Created field's value. +func (s *Upload) SetCreated(v time.Time) *Upload { + s.Created = &v + return s +} + +// SetMessage sets the Message field's value. +func (s *Upload) SetMessage(v string) *Upload { + s.Message = &v + return s +} + +// SetMetadata sets the Metadata field's value. +func (s *Upload) SetMetadata(v string) *Upload { + s.Metadata = &v + return s +} + +// SetName sets the Name field's value. +func (s *Upload) SetName(v string) *Upload { + s.Name = &v + return s +} + +// SetStatus sets the Status field's value. +func (s *Upload) SetStatus(v string) *Upload { + s.Status = &v + return s +} + +// SetType sets the Type field's value. +func (s *Upload) SetType(v string) *Upload { + s.Type = &v + return s +} + +// SetUrl sets the Url field's value. +func (s *Upload) SetUrl(v string) *Upload { + s.Url = &v + return s +} + +const ( + // ArtifactCategoryScreenshot is a ArtifactCategory enum value + ArtifactCategoryScreenshot = "SCREENSHOT" + + // ArtifactCategoryFile is a ArtifactCategory enum value + ArtifactCategoryFile = "FILE" + + // ArtifactCategoryLog is a ArtifactCategory enum value + ArtifactCategoryLog = "LOG" +) + +const ( + // ArtifactTypeUnknown is a ArtifactType enum value + ArtifactTypeUnknown = "UNKNOWN" + + // ArtifactTypeScreenshot is a ArtifactType enum value + ArtifactTypeScreenshot = "SCREENSHOT" + + // ArtifactTypeDeviceLog is a ArtifactType enum value + ArtifactTypeDeviceLog = "DEVICE_LOG" + + // ArtifactTypeMessageLog is a ArtifactType enum value + ArtifactTypeMessageLog = "MESSAGE_LOG" + + // ArtifactTypeVideoLog is a ArtifactType enum value + ArtifactTypeVideoLog = "VIDEO_LOG" + + // ArtifactTypeResultLog is a ArtifactType enum value + ArtifactTypeResultLog = "RESULT_LOG" + + // ArtifactTypeServiceLog is a ArtifactType enum value + ArtifactTypeServiceLog = "SERVICE_LOG" + + // ArtifactTypeWebkitLog is a ArtifactType enum value + ArtifactTypeWebkitLog = "WEBKIT_LOG" + + // ArtifactTypeInstrumentationOutput is a ArtifactType enum value + ArtifactTypeInstrumentationOutput = "INSTRUMENTATION_OUTPUT" + + // ArtifactTypeExerciserMonkeyOutput is a ArtifactType enum value + ArtifactTypeExerciserMonkeyOutput = "EXERCISER_MONKEY_OUTPUT" + + // ArtifactTypeCalabashJsonOutput is a ArtifactType enum value + ArtifactTypeCalabashJsonOutput = "CALABASH_JSON_OUTPUT" + + // ArtifactTypeCalabashPrettyOutput is a ArtifactType enum value + ArtifactTypeCalabashPrettyOutput = "CALABASH_PRETTY_OUTPUT" + + // ArtifactTypeCalabashStandardOutput is a ArtifactType enum value + ArtifactTypeCalabashStandardOutput = "CALABASH_STANDARD_OUTPUT" + + // ArtifactTypeCalabashJavaXmlOutput is a ArtifactType enum value + ArtifactTypeCalabashJavaXmlOutput = "CALABASH_JAVA_XML_OUTPUT" + + // ArtifactTypeAutomationOutput is a ArtifactType enum value + ArtifactTypeAutomationOutput = "AUTOMATION_OUTPUT" + + // ArtifactTypeAppiumServerOutput is a ArtifactType enum value + ArtifactTypeAppiumServerOutput = "APPIUM_SERVER_OUTPUT" + + // ArtifactTypeAppiumJavaOutput is a ArtifactType enum value + ArtifactTypeAppiumJavaOutput = "APPIUM_JAVA_OUTPUT" + + // ArtifactTypeAppiumJavaXmlOutput is a ArtifactType enum value + ArtifactTypeAppiumJavaXmlOutput = "APPIUM_JAVA_XML_OUTPUT" + + // ArtifactTypeAppiumPythonOutput is a ArtifactType enum value + ArtifactTypeAppiumPythonOutput = "APPIUM_PYTHON_OUTPUT" + + // ArtifactTypeAppiumPythonXmlOutput is a ArtifactType enum value + ArtifactTypeAppiumPythonXmlOutput = "APPIUM_PYTHON_XML_OUTPUT" + + // ArtifactTypeExplorerEventLog is a ArtifactType enum value + ArtifactTypeExplorerEventLog = "EXPLORER_EVENT_LOG" + + // ArtifactTypeExplorerSummaryLog is a ArtifactType enum value + ArtifactTypeExplorerSummaryLog = "EXPLORER_SUMMARY_LOG" + + // ArtifactTypeApplicationCrashReport is a ArtifactType enum value + ArtifactTypeApplicationCrashReport = "APPLICATION_CRASH_REPORT" + + // ArtifactTypeXctestLog is a ArtifactType enum value + ArtifactTypeXctestLog = "XCTEST_LOG" + + // ArtifactTypeVideo is a ArtifactType enum value + ArtifactTypeVideo = "VIDEO" +) + +const ( + // BillingMethodMetered is a BillingMethod enum value + BillingMethodMetered = "METERED" + + // BillingMethodUnmetered is a BillingMethod enum value + BillingMethodUnmetered = "UNMETERED" +) + +const ( + // CurrencyCodeUsd is a CurrencyCode enum value + CurrencyCodeUsd = "USD" +) + +const ( + // DeviceAttributeArn is a DeviceAttribute enum value + DeviceAttributeArn = "ARN" + + // DeviceAttributePlatform is a DeviceAttribute enum value + DeviceAttributePlatform = "PLATFORM" + + // DeviceAttributeFormFactor is a DeviceAttribute enum value + DeviceAttributeFormFactor = "FORM_FACTOR" + + // DeviceAttributeManufacturer is a DeviceAttribute enum value + DeviceAttributeManufacturer = "MANUFACTURER" + + // DeviceAttributeRemoteAccessEnabled is a DeviceAttribute enum value + DeviceAttributeRemoteAccessEnabled = "REMOTE_ACCESS_ENABLED" + + // DeviceAttributeAppiumVersion is a DeviceAttribute enum value + DeviceAttributeAppiumVersion = "APPIUM_VERSION" +) + +const ( + // DeviceFormFactorPhone is a DeviceFormFactor enum value + DeviceFormFactorPhone = "PHONE" + + // DeviceFormFactorTablet is a DeviceFormFactor enum value + DeviceFormFactorTablet = "TABLET" +) + +const ( + // DevicePlatformAndroid is a DevicePlatform enum value + DevicePlatformAndroid = "ANDROID" + + // DevicePlatformIos is a DevicePlatform enum value + DevicePlatformIos = "IOS" +) + +const ( + // DevicePoolTypeCurated is a DevicePoolType enum value + DevicePoolTypeCurated = "CURATED" + + // DevicePoolTypePrivate is a DevicePoolType enum value + DevicePoolTypePrivate = "PRIVATE" +) + +const ( + // ExecutionResultPending is a ExecutionResult enum value + ExecutionResultPending = "PENDING" + + // ExecutionResultPassed is a ExecutionResult enum value + ExecutionResultPassed = "PASSED" + + // ExecutionResultWarned is a ExecutionResult enum value + ExecutionResultWarned = "WARNED" + + // ExecutionResultFailed is a ExecutionResult enum value + ExecutionResultFailed = "FAILED" + + // ExecutionResultSkipped is a ExecutionResult enum value + ExecutionResultSkipped = "SKIPPED" + + // ExecutionResultErrored is a ExecutionResult enum value + ExecutionResultErrored = "ERRORED" + + // ExecutionResultStopped is a ExecutionResult enum value + ExecutionResultStopped = "STOPPED" +) + +const ( + // ExecutionStatusPending is a ExecutionStatus enum value + ExecutionStatusPending = "PENDING" + + // ExecutionStatusPendingConcurrency is a ExecutionStatus enum value + ExecutionStatusPendingConcurrency = "PENDING_CONCURRENCY" + + // ExecutionStatusPendingDevice is a ExecutionStatus enum value + ExecutionStatusPendingDevice = "PENDING_DEVICE" + + // ExecutionStatusProcessing is a ExecutionStatus enum value + ExecutionStatusProcessing = "PROCESSING" + + // ExecutionStatusScheduling is a ExecutionStatus enum value + ExecutionStatusScheduling = "SCHEDULING" + + // ExecutionStatusPreparing is a ExecutionStatus enum value + ExecutionStatusPreparing = "PREPARING" + + // ExecutionStatusRunning is a ExecutionStatus enum value + ExecutionStatusRunning = "RUNNING" + + // ExecutionStatusCompleted is a ExecutionStatus enum value + ExecutionStatusCompleted = "COMPLETED" + + // ExecutionStatusStopping is a ExecutionStatus enum value + ExecutionStatusStopping = "STOPPING" +) + +const ( + // NetworkProfileTypeCurated is a NetworkProfileType enum value + NetworkProfileTypeCurated = "CURATED" + + // NetworkProfileTypePrivate is a NetworkProfileType enum value + NetworkProfileTypePrivate = "PRIVATE" +) + +const ( + // OfferingTransactionTypePurchase is a OfferingTransactionType enum value + OfferingTransactionTypePurchase = "PURCHASE" + + // OfferingTransactionTypeRenew is a OfferingTransactionType enum value + OfferingTransactionTypeRenew = "RENEW" + + // OfferingTransactionTypeSystem is a OfferingTransactionType enum value + OfferingTransactionTypeSystem = "SYSTEM" +) + +const ( + // OfferingTypeRecurring is a OfferingType enum value + OfferingTypeRecurring = "RECURRING" +) + +const ( + // RecurringChargeFrequencyMonthly is a RecurringChargeFrequency enum value + RecurringChargeFrequencyMonthly = "MONTHLY" +) + +const ( + // RuleOperatorEquals is a RuleOperator enum value + RuleOperatorEquals = "EQUALS" + + // RuleOperatorLessThan is a RuleOperator enum value + RuleOperatorLessThan = "LESS_THAN" + + // RuleOperatorGreaterThan is a RuleOperator enum value + RuleOperatorGreaterThan = "GREATER_THAN" + + // RuleOperatorIn is a RuleOperator enum value + RuleOperatorIn = "IN" + + // RuleOperatorNotIn is a RuleOperator enum value + RuleOperatorNotIn = "NOT_IN" + + // RuleOperatorContains is a RuleOperator enum value + RuleOperatorContains = "CONTAINS" +) + +const ( + // SampleTypeCpu is a SampleType enum value + SampleTypeCpu = "CPU" + + // SampleTypeMemory is a SampleType enum value + SampleTypeMemory = "MEMORY" + + // SampleTypeThreads is a SampleType enum value + SampleTypeThreads = "THREADS" + + // SampleTypeRxRate is a SampleType enum value + SampleTypeRxRate = "RX_RATE" + + // SampleTypeTxRate is a SampleType enum value + SampleTypeTxRate = "TX_RATE" + + // SampleTypeRx is a SampleType enum value + SampleTypeRx = "RX" + + // SampleTypeTx is a SampleType enum value + SampleTypeTx = "TX" + + // SampleTypeNativeFrames is a SampleType enum value + SampleTypeNativeFrames = "NATIVE_FRAMES" + + // SampleTypeNativeFps is a SampleType enum value + SampleTypeNativeFps = "NATIVE_FPS" + + // SampleTypeNativeMinDrawtime is a SampleType enum value + SampleTypeNativeMinDrawtime = "NATIVE_MIN_DRAWTIME" + + // SampleTypeNativeAvgDrawtime is a SampleType enum value + SampleTypeNativeAvgDrawtime = "NATIVE_AVG_DRAWTIME" + + // SampleTypeNativeMaxDrawtime is a SampleType enum value + SampleTypeNativeMaxDrawtime = "NATIVE_MAX_DRAWTIME" + + // SampleTypeOpenglFrames is a SampleType enum value + SampleTypeOpenglFrames = "OPENGL_FRAMES" + + // SampleTypeOpenglFps is a SampleType enum value + SampleTypeOpenglFps = "OPENGL_FPS" + + // SampleTypeOpenglMinDrawtime is a SampleType enum value + SampleTypeOpenglMinDrawtime = "OPENGL_MIN_DRAWTIME" + + // SampleTypeOpenglAvgDrawtime is a SampleType enum value + SampleTypeOpenglAvgDrawtime = "OPENGL_AVG_DRAWTIME" + + // SampleTypeOpenglMaxDrawtime is a SampleType enum value + SampleTypeOpenglMaxDrawtime = "OPENGL_MAX_DRAWTIME" +) + +const ( + // TestTypeBuiltinFuzz is a TestType enum value + TestTypeBuiltinFuzz = "BUILTIN_FUZZ" + + // TestTypeBuiltinExplorer is a TestType enum value + TestTypeBuiltinExplorer = "BUILTIN_EXPLORER" + + // TestTypeAppiumJavaJunit is a TestType enum value + TestTypeAppiumJavaJunit = "APPIUM_JAVA_JUNIT" + + // TestTypeAppiumJavaTestng is a TestType enum value + TestTypeAppiumJavaTestng = "APPIUM_JAVA_TESTNG" + + // TestTypeAppiumPython is a TestType enum value + TestTypeAppiumPython = "APPIUM_PYTHON" + + // TestTypeAppiumWebJavaJunit is a TestType enum value + TestTypeAppiumWebJavaJunit = "APPIUM_WEB_JAVA_JUNIT" + + // TestTypeAppiumWebJavaTestng is a TestType enum value + TestTypeAppiumWebJavaTestng = "APPIUM_WEB_JAVA_TESTNG" + + // TestTypeAppiumWebPython is a TestType enum value + TestTypeAppiumWebPython = "APPIUM_WEB_PYTHON" + + // TestTypeCalabash is a TestType enum value + TestTypeCalabash = "CALABASH" + + // TestTypeInstrumentation is a TestType enum value + TestTypeInstrumentation = "INSTRUMENTATION" + + // TestTypeUiautomation is a TestType enum value + TestTypeUiautomation = "UIAUTOMATION" + + // TestTypeUiautomator is a TestType enum value + TestTypeUiautomator = "UIAUTOMATOR" + + // TestTypeXctest is a TestType enum value + TestTypeXctest = "XCTEST" + + // TestTypeXctestUi is a TestType enum value + TestTypeXctestUi = "XCTEST_UI" +) + +const ( + // UploadStatusInitialized is a UploadStatus enum value + UploadStatusInitialized = "INITIALIZED" + + // UploadStatusProcessing is a UploadStatus enum value + UploadStatusProcessing = "PROCESSING" + + // UploadStatusSucceeded is a UploadStatus enum value + UploadStatusSucceeded = "SUCCEEDED" + + // UploadStatusFailed is a UploadStatus enum value + UploadStatusFailed = "FAILED" +) + +const ( + // UploadTypeAndroidApp is a UploadType enum value + UploadTypeAndroidApp = "ANDROID_APP" + + // UploadTypeIosApp is a UploadType enum value + UploadTypeIosApp = "IOS_APP" + + // UploadTypeWebApp is a UploadType enum value + UploadTypeWebApp = "WEB_APP" + + // UploadTypeExternalData is a UploadType enum value + UploadTypeExternalData = "EXTERNAL_DATA" + + // UploadTypeAppiumJavaJunitTestPackage is a UploadType enum value + UploadTypeAppiumJavaJunitTestPackage = "APPIUM_JAVA_JUNIT_TEST_PACKAGE" + + // UploadTypeAppiumJavaTestngTestPackage is a UploadType enum value + UploadTypeAppiumJavaTestngTestPackage = "APPIUM_JAVA_TESTNG_TEST_PACKAGE" + + // UploadTypeAppiumPythonTestPackage is a UploadType enum value + UploadTypeAppiumPythonTestPackage = "APPIUM_PYTHON_TEST_PACKAGE" + + // UploadTypeAppiumWebJavaJunitTestPackage is a UploadType enum value + UploadTypeAppiumWebJavaJunitTestPackage = "APPIUM_WEB_JAVA_JUNIT_TEST_PACKAGE" + + // UploadTypeAppiumWebJavaTestngTestPackage is a UploadType enum value + UploadTypeAppiumWebJavaTestngTestPackage = "APPIUM_WEB_JAVA_TESTNG_TEST_PACKAGE" + + // UploadTypeAppiumWebPythonTestPackage is a UploadType enum value + UploadTypeAppiumWebPythonTestPackage = "APPIUM_WEB_PYTHON_TEST_PACKAGE" + + // UploadTypeCalabashTestPackage is a UploadType enum value + UploadTypeCalabashTestPackage = "CALABASH_TEST_PACKAGE" + + // UploadTypeInstrumentationTestPackage is a UploadType enum value + UploadTypeInstrumentationTestPackage = "INSTRUMENTATION_TEST_PACKAGE" + + // UploadTypeUiautomationTestPackage is a UploadType enum value + UploadTypeUiautomationTestPackage = "UIAUTOMATION_TEST_PACKAGE" + + // UploadTypeUiautomatorTestPackage is a UploadType enum value + UploadTypeUiautomatorTestPackage = "UIAUTOMATOR_TEST_PACKAGE" + + // UploadTypeXctestTestPackage is a UploadType enum value + UploadTypeXctestTestPackage = "XCTEST_TEST_PACKAGE" + + // UploadTypeXctestUiTestPackage is a UploadType enum value + UploadTypeXctestUiTestPackage = "XCTEST_UI_TEST_PACKAGE" +) diff --git a/vendor/github.com/aws/aws-sdk-go/service/devicefarm/doc.go b/vendor/github.com/aws/aws-sdk-go/service/devicefarm/doc.go new file mode 100644 index 000000000..2a1ad1e64 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/service/devicefarm/doc.go @@ -0,0 +1,82 @@ +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. + +// Package devicefarm provides the client and types for making API +// requests to AWS Device Farm. +// +// AWS Device Farm is a service that enables mobile app developers to test Android, +// iOS, and Fire OS apps on physical phones, tablets, and other devices in the +// cloud. +// +// See https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23 for more information on this service. +// +// See devicefarm package documentation for more information. +// https://docs.aws.amazon.com/sdk-for-go/api/service/devicefarm/ +// +// Using the Client +// +// To use the client for AWS Device Farm you will first need +// to create a new instance of it. +// +// When creating a client for an AWS service you'll first need to have a Session +// already created. The Session provides configuration that can be shared +// between multiple service clients. Additional configuration can be applied to +// the Session and service's client when they are constructed. The aws package's +// Config type contains several fields such as Region for the AWS Region the +// client should make API requests too. The optional Config value can be provided +// as the variadic argument for Sessions and client creation. +// +// Once the service's client is created you can use it to make API requests the +// AWS service. These clients are safe to use concurrently. +// +// // Create a session to share configuration, and load external configuration. +// sess := session.Must(session.NewSession()) +// +// // Create the service's client with the session. +// svc := devicefarm.New(sess) +// +// See the SDK's documentation for more information on how to use service clients. +// https://docs.aws.amazon.com/sdk-for-go/api/ +// +// See aws package's Config type for more information on configuration options. +// https://docs.aws.amazon.com/sdk-for-go/api/aws/#Config +// +// See the AWS Device Farm client DeviceFarm for more +// information on creating the service's client. +// https://docs.aws.amazon.com/sdk-for-go/api/service/devicefarm/#New +// +// Once the client is created you can make an API request to the service. +// Each API method takes a input parameter, and returns the service response +// and an error. +// +// The API method will document which error codes the service can be returned +// by the operation if the service models the API operation's errors. These +// errors will also be available as const strings prefixed with "ErrCode". +// +// result, err := svc.CreateDevicePool(params) +// if err != nil { +// // Cast err to awserr.Error to handle specific error codes. +// aerr, ok := err.(awserr.Error) +// if ok && aerr.Code() == { +// // Specific error code handling +// } +// return err +// } +// +// fmt.Println("CreateDevicePool result:") +// fmt.Println(result) +// +// Using the Client with Context +// +// The service's client also provides methods to make API requests with a Context +// value. This allows you to control the timeout, and cancellation of pending +// requests. These methods also take request Option as variadic parameter to apply +// additional configuration to the API request. +// +// ctx := context.Background() +// +// result, err := svc.CreateDevicePoolWithContext(ctx, params) +// +// See the request package documentation for more information on using Context pattern +// with the SDK. +// https://docs.aws.amazon.com/sdk-for-go/api/aws/request/ +package devicefarm diff --git a/vendor/github.com/aws/aws-sdk-go/service/devicefarm/errors.go b/vendor/github.com/aws/aws-sdk-go/service/devicefarm/errors.go new file mode 100644 index 000000000..bcb0d4601 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/service/devicefarm/errors.go @@ -0,0 +1,43 @@ +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. + +package devicefarm + +const ( + + // ErrCodeArgumentException for service response error code + // "ArgumentException". + // + // An invalid argument was specified. + ErrCodeArgumentException = "ArgumentException" + + // ErrCodeIdempotencyException for service response error code + // "IdempotencyException". + // + // An entity with the same name already exists. + ErrCodeIdempotencyException = "IdempotencyException" + + // ErrCodeLimitExceededException for service response error code + // "LimitExceededException". + // + // A limit was exceeded. + ErrCodeLimitExceededException = "LimitExceededException" + + // ErrCodeNotEligibleException for service response error code + // "NotEligibleException". + // + // Exception gets thrown when a user is not eligible to perform the specified + // transaction. + ErrCodeNotEligibleException = "NotEligibleException" + + // ErrCodeNotFoundException for service response error code + // "NotFoundException". + // + // The specified entity was not found. + ErrCodeNotFoundException = "NotFoundException" + + // ErrCodeServiceAccountException for service response error code + // "ServiceAccountException". + // + // There was a problem with the service account. + ErrCodeServiceAccountException = "ServiceAccountException" +) diff --git a/vendor/github.com/aws/aws-sdk-go/service/devicefarm/service.go b/vendor/github.com/aws/aws-sdk-go/service/devicefarm/service.go new file mode 100644 index 000000000..76cf7ca61 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/service/devicefarm/service.go @@ -0,0 +1,95 @@ +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. + +package devicefarm + +import ( + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/client" + "github.com/aws/aws-sdk-go/aws/client/metadata" + "github.com/aws/aws-sdk-go/aws/request" + "github.com/aws/aws-sdk-go/aws/signer/v4" + "github.com/aws/aws-sdk-go/private/protocol/jsonrpc" +) + +// DeviceFarm provides the API operation methods for making requests to +// AWS Device Farm. See this package's package overview docs +// for details on the service. +// +// DeviceFarm methods are safe to use concurrently. It is not safe to +// modify mutate any of the struct's properties though. +type DeviceFarm struct { + *client.Client +} + +// Used for custom client initialization logic +var initClient func(*client.Client) + +// Used for custom request initialization logic +var initRequest func(*request.Request) + +// Service information constants +const ( + ServiceName = "devicefarm" // Service endpoint prefix API calls made to. + EndpointsID = ServiceName // Service ID for Regions and Endpoints metadata. +) + +// New creates a new instance of the DeviceFarm client with a session. +// If additional configuration is needed for the client instance use the optional +// aws.Config parameter to add your extra config. +// +// Example: +// // Create a DeviceFarm client from just a session. +// svc := devicefarm.New(mySession) +// +// // Create a DeviceFarm client with additional configuration +// svc := devicefarm.New(mySession, aws.NewConfig().WithRegion("us-west-2")) +func New(p client.ConfigProvider, cfgs ...*aws.Config) *DeviceFarm { + c := p.ClientConfig(EndpointsID, cfgs...) + return newClient(*c.Config, c.Handlers, c.Endpoint, c.SigningRegion, c.SigningName) +} + +// newClient creates, initializes and returns a new service client instance. +func newClient(cfg aws.Config, handlers request.Handlers, endpoint, signingRegion, signingName string) *DeviceFarm { + svc := &DeviceFarm{ + Client: client.New( + cfg, + metadata.ClientInfo{ + ServiceName: ServiceName, + SigningName: signingName, + SigningRegion: signingRegion, + Endpoint: endpoint, + APIVersion: "2015-06-23", + JSONVersion: "1.1", + TargetPrefix: "DeviceFarm_20150623", + }, + handlers, + ), + } + + // Handlers + svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler) + svc.Handlers.Build.PushBackNamed(jsonrpc.BuildHandler) + svc.Handlers.Unmarshal.PushBackNamed(jsonrpc.UnmarshalHandler) + svc.Handlers.UnmarshalMeta.PushBackNamed(jsonrpc.UnmarshalMetaHandler) + svc.Handlers.UnmarshalError.PushBackNamed(jsonrpc.UnmarshalErrorHandler) + + // Run custom client initialization if present + if initClient != nil { + initClient(svc.Client) + } + + return svc +} + +// newRequest creates a new request for a DeviceFarm operation and runs any +// custom request initialization. +func (c *DeviceFarm) newRequest(op *request.Operation, params, data interface{}) *request.Request { + req := c.NewRequest(op, params, data) + + // Run custom request initialization if present + if initRequest != nil { + initRequest(req) + } + + return req +} diff --git a/vendor/github.com/aws/aws-sdk-go/service/directoryservice/api.go b/vendor/github.com/aws/aws-sdk-go/service/directoryservice/api.go index 436175a5a..cfc8bb057 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/directoryservice/api.go +++ b/vendor/github.com/aws/aws-sdk-go/service/directoryservice/api.go @@ -1,12 +1,12 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. -// Package directoryservice provides a client for AWS Directory Service. package directoryservice import ( "fmt" "time" + "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awsutil" "github.com/aws/aws-sdk-go/aws/request" ) @@ -100,8 +100,23 @@ func (c *DirectoryService) AddIpRoutesRequest(input *AddIpRoutesInput) (req *req // Please also see https://docs.aws.amazon.com/goto/WebAPI/ds-2015-04-16/AddIpRoutes func (c *DirectoryService) AddIpRoutes(input *AddIpRoutesInput) (*AddIpRoutesOutput, error) { req, out := c.AddIpRoutesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// AddIpRoutesWithContext is the same as AddIpRoutes with the addition of +// the ability to pass a context and additional request options. +// +// See AddIpRoutes 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 *DirectoryService) AddIpRoutesWithContext(ctx aws.Context, input *AddIpRoutesInput, opts ...request.Option) (*AddIpRoutesOutput, error) { + req, out := c.AddIpRoutesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opAddTagsToResource = "AddTagsToResource" @@ -179,8 +194,23 @@ func (c *DirectoryService) AddTagsToResourceRequest(input *AddTagsToResourceInpu // Please also see https://docs.aws.amazon.com/goto/WebAPI/ds-2015-04-16/AddTagsToResource func (c *DirectoryService) AddTagsToResource(input *AddTagsToResourceInput) (*AddTagsToResourceOutput, error) { req, out := c.AddTagsToResourceRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// AddTagsToResourceWithContext is the same as AddTagsToResource with the addition of +// the ability to pass a context and additional request options. +// +// See AddTagsToResource 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 *DirectoryService) AddTagsToResourceWithContext(ctx aws.Context, input *AddTagsToResourceInput, opts ...request.Option) (*AddTagsToResourceOutput, error) { + req, out := c.AddTagsToResourceRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCancelSchemaExtension = "CancelSchemaExtension" @@ -253,8 +283,23 @@ func (c *DirectoryService) CancelSchemaExtensionRequest(input *CancelSchemaExten // Please also see https://docs.aws.amazon.com/goto/WebAPI/ds-2015-04-16/CancelSchemaExtension func (c *DirectoryService) CancelSchemaExtension(input *CancelSchemaExtensionInput) (*CancelSchemaExtensionOutput, error) { req, out := c.CancelSchemaExtensionRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CancelSchemaExtensionWithContext is the same as CancelSchemaExtension with the addition of +// the ability to pass a context and additional request options. +// +// See CancelSchemaExtension 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 *DirectoryService) CancelSchemaExtensionWithContext(ctx aws.Context, input *CancelSchemaExtensionInput, opts ...request.Option) (*CancelSchemaExtensionOutput, error) { + req, out := c.CancelSchemaExtensionRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opConnectDirectory = "ConnectDirectory" @@ -334,8 +379,23 @@ func (c *DirectoryService) ConnectDirectoryRequest(input *ConnectDirectoryInput) // Please also see https://docs.aws.amazon.com/goto/WebAPI/ds-2015-04-16/ConnectDirectory func (c *DirectoryService) ConnectDirectory(input *ConnectDirectoryInput) (*ConnectDirectoryOutput, error) { req, out := c.ConnectDirectoryRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ConnectDirectoryWithContext is the same as ConnectDirectory with the addition of +// the ability to pass a context and additional request options. +// +// See ConnectDirectory 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 *DirectoryService) ConnectDirectoryWithContext(ctx aws.Context, input *ConnectDirectoryInput, opts ...request.Option) (*ConnectDirectoryOutput, error) { + req, out := c.ConnectDirectoryRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateAlias = "CreateAlias" @@ -416,8 +476,23 @@ func (c *DirectoryService) CreateAliasRequest(input *CreateAliasInput) (req *req // Please also see https://docs.aws.amazon.com/goto/WebAPI/ds-2015-04-16/CreateAlias func (c *DirectoryService) CreateAlias(input *CreateAliasInput) (*CreateAliasOutput, error) { req, out := c.CreateAliasRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateAliasWithContext is the same as CreateAlias with the addition of +// the ability to pass a context and additional request options. +// +// See CreateAlias for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *DirectoryService) CreateAliasWithContext(ctx aws.Context, input *CreateAliasInput, opts ...request.Option) (*CreateAliasOutput, error) { + req, out := c.CreateAliasRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateComputer = "CreateComputer" @@ -503,8 +578,23 @@ func (c *DirectoryService) CreateComputerRequest(input *CreateComputerInput) (re // Please also see https://docs.aws.amazon.com/goto/WebAPI/ds-2015-04-16/CreateComputer func (c *DirectoryService) CreateComputer(input *CreateComputerInput) (*CreateComputerOutput, error) { req, out := c.CreateComputerRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateComputerWithContext is the same as CreateComputer with the addition of +// the ability to pass a context and additional request options. +// +// See CreateComputer 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 *DirectoryService) CreateComputerWithContext(ctx aws.Context, input *CreateComputerInput, opts ...request.Option) (*CreateComputerOutput, error) { + req, out := c.CreateComputerRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateConditionalForwarder = "CreateConditionalForwarder" @@ -588,8 +678,23 @@ func (c *DirectoryService) CreateConditionalForwarderRequest(input *CreateCondit // Please also see https://docs.aws.amazon.com/goto/WebAPI/ds-2015-04-16/CreateConditionalForwarder func (c *DirectoryService) CreateConditionalForwarder(input *CreateConditionalForwarderInput) (*CreateConditionalForwarderOutput, error) { req, out := c.CreateConditionalForwarderRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateConditionalForwarderWithContext is the same as CreateConditionalForwarder with the addition of +// the ability to pass a context and additional request options. +// +// See CreateConditionalForwarder 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 *DirectoryService) CreateConditionalForwarderWithContext(ctx aws.Context, input *CreateConditionalForwarderInput, opts ...request.Option) (*CreateConditionalForwarderOutput, error) { + req, out := c.CreateConditionalForwarderRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateDirectory = "CreateDirectory" @@ -669,8 +774,23 @@ func (c *DirectoryService) CreateDirectoryRequest(input *CreateDirectoryInput) ( // Please also see https://docs.aws.amazon.com/goto/WebAPI/ds-2015-04-16/CreateDirectory func (c *DirectoryService) CreateDirectory(input *CreateDirectoryInput) (*CreateDirectoryOutput, error) { req, out := c.CreateDirectoryRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateDirectoryWithContext is the same as CreateDirectory with the addition of +// the ability to pass a context and additional request options. +// +// See CreateDirectory 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 *DirectoryService) CreateDirectoryWithContext(ctx aws.Context, input *CreateDirectoryInput, opts ...request.Option) (*CreateDirectoryOutput, error) { + req, out := c.CreateDirectoryRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateMicrosoftAD = "CreateMicrosoftAD" @@ -753,8 +873,23 @@ func (c *DirectoryService) CreateMicrosoftADRequest(input *CreateMicrosoftADInpu // Please also see https://docs.aws.amazon.com/goto/WebAPI/ds-2015-04-16/CreateMicrosoftAD func (c *DirectoryService) CreateMicrosoftAD(input *CreateMicrosoftADInput) (*CreateMicrosoftADOutput, error) { req, out := c.CreateMicrosoftADRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateMicrosoftADWithContext is the same as CreateMicrosoftAD with the addition of +// the ability to pass a context and additional request options. +// +// See CreateMicrosoftAD 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 *DirectoryService) CreateMicrosoftADWithContext(ctx aws.Context, input *CreateMicrosoftADInput, opts ...request.Option) (*CreateMicrosoftADOutput, error) { + req, out := c.CreateMicrosoftADRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateSnapshot = "CreateSnapshot" @@ -834,8 +969,23 @@ func (c *DirectoryService) CreateSnapshotRequest(input *CreateSnapshotInput) (re // Please also see https://docs.aws.amazon.com/goto/WebAPI/ds-2015-04-16/CreateSnapshot func (c *DirectoryService) CreateSnapshot(input *CreateSnapshotInput) (*CreateSnapshotOutput, error) { req, out := c.CreateSnapshotRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateSnapshotWithContext is the same as CreateSnapshot with the addition of +// the ability to pass a context and additional request options. +// +// See CreateSnapshot 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 *DirectoryService) CreateSnapshotWithContext(ctx aws.Context, input *CreateSnapshotInput, opts ...request.Option) (*CreateSnapshotOutput, error) { + req, out := c.CreateSnapshotRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateTrust = "CreateTrust" @@ -921,8 +1071,23 @@ func (c *DirectoryService) CreateTrustRequest(input *CreateTrustInput) (req *req // Please also see https://docs.aws.amazon.com/goto/WebAPI/ds-2015-04-16/CreateTrust func (c *DirectoryService) CreateTrust(input *CreateTrustInput) (*CreateTrustOutput, error) { req, out := c.CreateTrustRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateTrustWithContext is the same as CreateTrust with the addition of +// the ability to pass a context and additional request options. +// +// See CreateTrust 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 *DirectoryService) CreateTrustWithContext(ctx aws.Context, input *CreateTrustInput, opts ...request.Option) (*CreateTrustOutput, error) { + req, out := c.CreateTrustRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteConditionalForwarder = "DeleteConditionalForwarder" @@ -1001,8 +1166,23 @@ func (c *DirectoryService) DeleteConditionalForwarderRequest(input *DeleteCondit // Please also see https://docs.aws.amazon.com/goto/WebAPI/ds-2015-04-16/DeleteConditionalForwarder func (c *DirectoryService) DeleteConditionalForwarder(input *DeleteConditionalForwarderInput) (*DeleteConditionalForwarderOutput, error) { req, out := c.DeleteConditionalForwarderRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteConditionalForwarderWithContext is the same as DeleteConditionalForwarder with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteConditionalForwarder 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 *DirectoryService) DeleteConditionalForwarderWithContext(ctx aws.Context, input *DeleteConditionalForwarderInput, opts ...request.Option) (*DeleteConditionalForwarderOutput, error) { + req, out := c.DeleteConditionalForwarderRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteDirectory = "DeleteDirectory" @@ -1077,8 +1257,23 @@ func (c *DirectoryService) DeleteDirectoryRequest(input *DeleteDirectoryInput) ( // Please also see https://docs.aws.amazon.com/goto/WebAPI/ds-2015-04-16/DeleteDirectory func (c *DirectoryService) DeleteDirectory(input *DeleteDirectoryInput) (*DeleteDirectoryOutput, error) { req, out := c.DeleteDirectoryRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteDirectoryWithContext is the same as DeleteDirectory with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteDirectory 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 *DirectoryService) DeleteDirectoryWithContext(ctx aws.Context, input *DeleteDirectoryInput, opts ...request.Option) (*DeleteDirectoryOutput, error) { + req, out := c.DeleteDirectoryRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteSnapshot = "DeleteSnapshot" @@ -1151,8 +1346,23 @@ func (c *DirectoryService) DeleteSnapshotRequest(input *DeleteSnapshotInput) (re // Please also see https://docs.aws.amazon.com/goto/WebAPI/ds-2015-04-16/DeleteSnapshot func (c *DirectoryService) DeleteSnapshot(input *DeleteSnapshotInput) (*DeleteSnapshotOutput, error) { req, out := c.DeleteSnapshotRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteSnapshotWithContext is the same as DeleteSnapshot with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteSnapshot 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 *DirectoryService) DeleteSnapshotWithContext(ctx aws.Context, input *DeleteSnapshotInput, opts ...request.Option) (*DeleteSnapshotOutput, error) { + req, out := c.DeleteSnapshotRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteTrust = "DeleteTrust" @@ -1229,8 +1439,23 @@ func (c *DirectoryService) DeleteTrustRequest(input *DeleteTrustInput) (req *req // Please also see https://docs.aws.amazon.com/goto/WebAPI/ds-2015-04-16/DeleteTrust func (c *DirectoryService) DeleteTrust(input *DeleteTrustInput) (*DeleteTrustOutput, error) { req, out := c.DeleteTrustRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteTrustWithContext is the same as DeleteTrust with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteTrust 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 *DirectoryService) DeleteTrustWithContext(ctx aws.Context, input *DeleteTrustInput, opts ...request.Option) (*DeleteTrustOutput, error) { + req, out := c.DeleteTrustRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeregisterEventTopic = "DeregisterEventTopic" @@ -1303,8 +1528,23 @@ func (c *DirectoryService) DeregisterEventTopicRequest(input *DeregisterEventTop // Please also see https://docs.aws.amazon.com/goto/WebAPI/ds-2015-04-16/DeregisterEventTopic func (c *DirectoryService) DeregisterEventTopic(input *DeregisterEventTopicInput) (*DeregisterEventTopicOutput, error) { req, out := c.DeregisterEventTopicRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeregisterEventTopicWithContext is the same as DeregisterEventTopic with the addition of +// the ability to pass a context and additional request options. +// +// See DeregisterEventTopic 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 *DirectoryService) DeregisterEventTopicWithContext(ctx aws.Context, input *DeregisterEventTopicInput, opts ...request.Option) (*DeregisterEventTopicOutput, error) { + req, out := c.DeregisterEventTopicRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeConditionalForwarders = "DescribeConditionalForwarders" @@ -1386,8 +1626,23 @@ func (c *DirectoryService) DescribeConditionalForwardersRequest(input *DescribeC // Please also see https://docs.aws.amazon.com/goto/WebAPI/ds-2015-04-16/DescribeConditionalForwarders func (c *DirectoryService) DescribeConditionalForwarders(input *DescribeConditionalForwardersInput) (*DescribeConditionalForwardersOutput, error) { req, out := c.DescribeConditionalForwardersRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeConditionalForwardersWithContext is the same as DescribeConditionalForwarders with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeConditionalForwarders 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 *DirectoryService) DescribeConditionalForwardersWithContext(ctx aws.Context, input *DescribeConditionalForwardersInput, opts ...request.Option) (*DescribeConditionalForwardersOutput, error) { + req, out := c.DescribeConditionalForwardersRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeDirectories = "DescribeDirectories" @@ -1474,8 +1729,23 @@ func (c *DirectoryService) DescribeDirectoriesRequest(input *DescribeDirectories // Please also see https://docs.aws.amazon.com/goto/WebAPI/ds-2015-04-16/DescribeDirectories func (c *DirectoryService) DescribeDirectories(input *DescribeDirectoriesInput) (*DescribeDirectoriesOutput, error) { req, out := c.DescribeDirectoriesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeDirectoriesWithContext is the same as DescribeDirectories with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeDirectories 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 *DirectoryService) DescribeDirectoriesWithContext(ctx aws.Context, input *DescribeDirectoriesInput, opts ...request.Option) (*DescribeDirectoriesOutput, error) { + req, out := c.DescribeDirectoriesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeEventTopics = "DescribeEventTopics" @@ -1552,8 +1822,23 @@ func (c *DirectoryService) DescribeEventTopicsRequest(input *DescribeEventTopics // Please also see https://docs.aws.amazon.com/goto/WebAPI/ds-2015-04-16/DescribeEventTopics func (c *DirectoryService) DescribeEventTopics(input *DescribeEventTopicsInput) (*DescribeEventTopicsOutput, error) { req, out := c.DescribeEventTopicsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeEventTopicsWithContext is the same as DescribeEventTopics with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeEventTopics 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 *DirectoryService) DescribeEventTopicsWithContext(ctx aws.Context, input *DescribeEventTopicsInput, opts ...request.Option) (*DescribeEventTopicsOutput, error) { + req, out := c.DescribeEventTopicsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeSnapshots = "DescribeSnapshots" @@ -1636,8 +1921,23 @@ func (c *DirectoryService) DescribeSnapshotsRequest(input *DescribeSnapshotsInpu // Please also see https://docs.aws.amazon.com/goto/WebAPI/ds-2015-04-16/DescribeSnapshots func (c *DirectoryService) DescribeSnapshots(input *DescribeSnapshotsInput) (*DescribeSnapshotsOutput, error) { req, out := c.DescribeSnapshotsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeSnapshotsWithContext is the same as DescribeSnapshots with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeSnapshots 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 *DirectoryService) DescribeSnapshotsWithContext(ctx aws.Context, input *DescribeSnapshotsInput, opts ...request.Option) (*DescribeSnapshotsOutput, error) { + req, out := c.DescribeSnapshotsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeTrusts = "DescribeTrusts" @@ -1719,8 +2019,23 @@ func (c *DirectoryService) DescribeTrustsRequest(input *DescribeTrustsInput) (re // Please also see https://docs.aws.amazon.com/goto/WebAPI/ds-2015-04-16/DescribeTrusts func (c *DirectoryService) DescribeTrusts(input *DescribeTrustsInput) (*DescribeTrustsOutput, error) { req, out := c.DescribeTrustsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeTrustsWithContext is the same as DescribeTrusts with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeTrusts 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 *DirectoryService) DescribeTrustsWithContext(ctx aws.Context, input *DescribeTrustsInput, opts ...request.Option) (*DescribeTrustsOutput, error) { + req, out := c.DescribeTrustsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDisableRadius = "DisableRadius" @@ -1791,8 +2106,23 @@ func (c *DirectoryService) DisableRadiusRequest(input *DisableRadiusInput) (req // Please also see https://docs.aws.amazon.com/goto/WebAPI/ds-2015-04-16/DisableRadius func (c *DirectoryService) DisableRadius(input *DisableRadiusInput) (*DisableRadiusOutput, error) { req, out := c.DisableRadiusRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DisableRadiusWithContext is the same as DisableRadius with the addition of +// the ability to pass a context and additional request options. +// +// See DisableRadius 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 *DirectoryService) DisableRadiusWithContext(ctx aws.Context, input *DisableRadiusInput, opts ...request.Option) (*DisableRadiusOutput, error) { + req, out := c.DisableRadiusRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDisableSso = "DisableSso" @@ -1868,8 +2198,23 @@ func (c *DirectoryService) DisableSsoRequest(input *DisableSsoInput) (req *reque // Please also see https://docs.aws.amazon.com/goto/WebAPI/ds-2015-04-16/DisableSso func (c *DirectoryService) DisableSso(input *DisableSsoInput) (*DisableSsoOutput, error) { req, out := c.DisableSsoRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DisableSsoWithContext is the same as DisableSso with the addition of +// the ability to pass a context and additional request options. +// +// See DisableSso 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 *DirectoryService) DisableSsoWithContext(ctx aws.Context, input *DisableSsoInput, opts ...request.Option) (*DisableSsoOutput, error) { + req, out := c.DisableSsoRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opEnableRadius = "EnableRadius" @@ -1946,8 +2291,23 @@ func (c *DirectoryService) EnableRadiusRequest(input *EnableRadiusInput) (req *r // Please also see https://docs.aws.amazon.com/goto/WebAPI/ds-2015-04-16/EnableRadius func (c *DirectoryService) EnableRadius(input *EnableRadiusInput) (*EnableRadiusOutput, error) { req, out := c.EnableRadiusRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// EnableRadiusWithContext is the same as EnableRadius with the addition of +// the ability to pass a context and additional request options. +// +// See EnableRadius 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 *DirectoryService) EnableRadiusWithContext(ctx aws.Context, input *EnableRadiusInput, opts ...request.Option) (*EnableRadiusOutput, error) { + req, out := c.EnableRadiusRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opEnableSso = "EnableSso" @@ -2023,8 +2383,23 @@ func (c *DirectoryService) EnableSsoRequest(input *EnableSsoInput) (req *request // Please also see https://docs.aws.amazon.com/goto/WebAPI/ds-2015-04-16/EnableSso func (c *DirectoryService) EnableSso(input *EnableSsoInput) (*EnableSsoOutput, error) { req, out := c.EnableSsoRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// EnableSsoWithContext is the same as EnableSso with the addition of +// the ability to pass a context and additional request options. +// +// See EnableSso 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 *DirectoryService) EnableSsoWithContext(ctx aws.Context, input *EnableSsoInput, opts ...request.Option) (*EnableSsoOutput, error) { + req, out := c.EnableSsoRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetDirectoryLimits = "GetDirectoryLimits" @@ -2094,8 +2469,23 @@ func (c *DirectoryService) GetDirectoryLimitsRequest(input *GetDirectoryLimitsIn // Please also see https://docs.aws.amazon.com/goto/WebAPI/ds-2015-04-16/GetDirectoryLimits func (c *DirectoryService) GetDirectoryLimits(input *GetDirectoryLimitsInput) (*GetDirectoryLimitsOutput, error) { req, out := c.GetDirectoryLimitsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetDirectoryLimitsWithContext is the same as GetDirectoryLimits with the addition of +// the ability to pass a context and additional request options. +// +// See GetDirectoryLimits 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 *DirectoryService) GetDirectoryLimitsWithContext(ctx aws.Context, input *GetDirectoryLimitsInput, opts ...request.Option) (*GetDirectoryLimitsOutput, error) { + req, out := c.GetDirectoryLimitsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetSnapshotLimits = "GetSnapshotLimits" @@ -2165,8 +2555,23 @@ func (c *DirectoryService) GetSnapshotLimitsRequest(input *GetSnapshotLimitsInpu // Please also see https://docs.aws.amazon.com/goto/WebAPI/ds-2015-04-16/GetSnapshotLimits func (c *DirectoryService) GetSnapshotLimits(input *GetSnapshotLimitsInput) (*GetSnapshotLimitsOutput, error) { req, out := c.GetSnapshotLimitsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetSnapshotLimitsWithContext is the same as GetSnapshotLimits with the addition of +// the ability to pass a context and additional request options. +// +// See GetSnapshotLimits 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 *DirectoryService) GetSnapshotLimitsWithContext(ctx aws.Context, input *GetSnapshotLimitsInput, opts ...request.Option) (*GetSnapshotLimitsOutput, error) { + req, out := c.GetSnapshotLimitsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opListIpRoutes = "ListIpRoutes" @@ -2242,8 +2647,23 @@ func (c *DirectoryService) ListIpRoutesRequest(input *ListIpRoutesInput) (req *r // Please also see https://docs.aws.amazon.com/goto/WebAPI/ds-2015-04-16/ListIpRoutes func (c *DirectoryService) ListIpRoutes(input *ListIpRoutesInput) (*ListIpRoutesOutput, error) { req, out := c.ListIpRoutesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListIpRoutesWithContext is the same as ListIpRoutes with the addition of +// the ability to pass a context and additional request options. +// +// See ListIpRoutes 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 *DirectoryService) ListIpRoutesWithContext(ctx aws.Context, input *ListIpRoutesInput, opts ...request.Option) (*ListIpRoutesOutput, error) { + req, out := c.ListIpRoutesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opListSchemaExtensions = "ListSchemaExtensions" @@ -2316,8 +2736,23 @@ func (c *DirectoryService) ListSchemaExtensionsRequest(input *ListSchemaExtensio // Please also see https://docs.aws.amazon.com/goto/WebAPI/ds-2015-04-16/ListSchemaExtensions func (c *DirectoryService) ListSchemaExtensions(input *ListSchemaExtensionsInput) (*ListSchemaExtensionsOutput, error) { req, out := c.ListSchemaExtensionsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListSchemaExtensionsWithContext is the same as ListSchemaExtensions with the addition of +// the ability to pass a context and additional request options. +// +// See ListSchemaExtensions 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 *DirectoryService) ListSchemaExtensionsWithContext(ctx aws.Context, input *ListSchemaExtensionsInput, opts ...request.Option) (*ListSchemaExtensionsOutput, error) { + req, out := c.ListSchemaExtensionsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opListTagsForResource = "ListTagsForResource" @@ -2393,8 +2828,23 @@ func (c *DirectoryService) ListTagsForResourceRequest(input *ListTagsForResource // Please also see https://docs.aws.amazon.com/goto/WebAPI/ds-2015-04-16/ListTagsForResource func (c *DirectoryService) ListTagsForResource(input *ListTagsForResourceInput) (*ListTagsForResourceOutput, error) { req, out := c.ListTagsForResourceRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListTagsForResourceWithContext is the same as ListTagsForResource with the addition of +// the ability to pass a context and additional request options. +// +// See ListTagsForResource 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 *DirectoryService) ListTagsForResourceWithContext(ctx aws.Context, input *ListTagsForResourceInput, opts ...request.Option) (*ListTagsForResourceOutput, error) { + req, out := c.ListTagsForResourceRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opRegisterEventTopic = "RegisterEventTopic" @@ -2472,8 +2922,23 @@ func (c *DirectoryService) RegisterEventTopicRequest(input *RegisterEventTopicIn // Please also see https://docs.aws.amazon.com/goto/WebAPI/ds-2015-04-16/RegisterEventTopic func (c *DirectoryService) RegisterEventTopic(input *RegisterEventTopicInput) (*RegisterEventTopicOutput, error) { req, out := c.RegisterEventTopicRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// RegisterEventTopicWithContext is the same as RegisterEventTopic with the addition of +// the ability to pass a context and additional request options. +// +// See RegisterEventTopic 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 *DirectoryService) RegisterEventTopicWithContext(ctx aws.Context, input *RegisterEventTopicInput, opts ...request.Option) (*RegisterEventTopicOutput, error) { + req, out := c.RegisterEventTopicRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opRemoveIpRoutes = "RemoveIpRoutes" @@ -2549,8 +3014,23 @@ func (c *DirectoryService) RemoveIpRoutesRequest(input *RemoveIpRoutesInput) (re // Please also see https://docs.aws.amazon.com/goto/WebAPI/ds-2015-04-16/RemoveIpRoutes func (c *DirectoryService) RemoveIpRoutes(input *RemoveIpRoutesInput) (*RemoveIpRoutesOutput, error) { req, out := c.RemoveIpRoutesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// RemoveIpRoutesWithContext is the same as RemoveIpRoutes with the addition of +// the ability to pass a context and additional request options. +// +// See RemoveIpRoutes 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 *DirectoryService) RemoveIpRoutesWithContext(ctx aws.Context, input *RemoveIpRoutesInput, opts ...request.Option) (*RemoveIpRoutesOutput, error) { + req, out := c.RemoveIpRoutesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opRemoveTagsFromResource = "RemoveTagsFromResource" @@ -2623,8 +3103,23 @@ func (c *DirectoryService) RemoveTagsFromResourceRequest(input *RemoveTagsFromRe // Please also see https://docs.aws.amazon.com/goto/WebAPI/ds-2015-04-16/RemoveTagsFromResource func (c *DirectoryService) RemoveTagsFromResource(input *RemoveTagsFromResourceInput) (*RemoveTagsFromResourceOutput, error) { req, out := c.RemoveTagsFromResourceRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// RemoveTagsFromResourceWithContext is the same as RemoveTagsFromResource with the addition of +// the ability to pass a context and additional request options. +// +// See RemoveTagsFromResource 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 *DirectoryService) RemoveTagsFromResourceWithContext(ctx aws.Context, input *RemoveTagsFromResourceInput, opts ...request.Option) (*RemoveTagsFromResourceOutput, error) { + req, out := c.RemoveTagsFromResourceRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opRestoreFromSnapshot = "RestoreFromSnapshot" @@ -2705,8 +3200,23 @@ func (c *DirectoryService) RestoreFromSnapshotRequest(input *RestoreFromSnapshot // Please also see https://docs.aws.amazon.com/goto/WebAPI/ds-2015-04-16/RestoreFromSnapshot func (c *DirectoryService) RestoreFromSnapshot(input *RestoreFromSnapshotInput) (*RestoreFromSnapshotOutput, error) { req, out := c.RestoreFromSnapshotRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// RestoreFromSnapshotWithContext is the same as RestoreFromSnapshot with the addition of +// the ability to pass a context and additional request options. +// +// See RestoreFromSnapshot 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 *DirectoryService) RestoreFromSnapshotWithContext(ctx aws.Context, input *RestoreFromSnapshotInput, opts ...request.Option) (*RestoreFromSnapshotOutput, error) { + req, out := c.RestoreFromSnapshotRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opStartSchemaExtension = "StartSchemaExtension" @@ -2787,8 +3297,23 @@ func (c *DirectoryService) StartSchemaExtensionRequest(input *StartSchemaExtensi // Please also see https://docs.aws.amazon.com/goto/WebAPI/ds-2015-04-16/StartSchemaExtension func (c *DirectoryService) StartSchemaExtension(input *StartSchemaExtensionInput) (*StartSchemaExtensionOutput, error) { req, out := c.StartSchemaExtensionRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// StartSchemaExtensionWithContext is the same as StartSchemaExtension with the addition of +// the ability to pass a context and additional request options. +// +// See StartSchemaExtension 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 *DirectoryService) StartSchemaExtensionWithContext(ctx aws.Context, input *StartSchemaExtensionInput, opts ...request.Option) (*StartSchemaExtensionOutput, error) { + req, out := c.StartSchemaExtensionRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opUpdateConditionalForwarder = "UpdateConditionalForwarder" @@ -2867,8 +3392,23 @@ func (c *DirectoryService) UpdateConditionalForwarderRequest(input *UpdateCondit // Please also see https://docs.aws.amazon.com/goto/WebAPI/ds-2015-04-16/UpdateConditionalForwarder func (c *DirectoryService) UpdateConditionalForwarder(input *UpdateConditionalForwarderInput) (*UpdateConditionalForwarderOutput, error) { req, out := c.UpdateConditionalForwarderRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// UpdateConditionalForwarderWithContext is the same as UpdateConditionalForwarder with the addition of +// the ability to pass a context and additional request options. +// +// See UpdateConditionalForwarder 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 *DirectoryService) UpdateConditionalForwarderWithContext(ctx aws.Context, input *UpdateConditionalForwarderInput, opts ...request.Option) (*UpdateConditionalForwarderOutput, error) { + req, out := c.UpdateConditionalForwarderRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opUpdateRadius = "UpdateRadius" @@ -2942,8 +3482,23 @@ func (c *DirectoryService) UpdateRadiusRequest(input *UpdateRadiusInput) (req *r // Please also see https://docs.aws.amazon.com/goto/WebAPI/ds-2015-04-16/UpdateRadius func (c *DirectoryService) UpdateRadius(input *UpdateRadiusInput) (*UpdateRadiusOutput, error) { req, out := c.UpdateRadiusRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// UpdateRadiusWithContext is the same as UpdateRadius with the addition of +// the ability to pass a context and additional request options. +// +// See UpdateRadius 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 *DirectoryService) UpdateRadiusWithContext(ctx aws.Context, input *UpdateRadiusInput, opts ...request.Option) (*UpdateRadiusOutput, error) { + req, out := c.UpdateRadiusRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opVerifyTrust = "VerifyTrust" @@ -3023,8 +3578,23 @@ func (c *DirectoryService) VerifyTrustRequest(input *VerifyTrustInput) (req *req // Please also see https://docs.aws.amazon.com/goto/WebAPI/ds-2015-04-16/VerifyTrust func (c *DirectoryService) VerifyTrust(input *VerifyTrustInput) (*VerifyTrustOutput, error) { req, out := c.VerifyTrustRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// VerifyTrustWithContext is the same as VerifyTrust with the addition of +// the ability to pass a context and additional request options. +// +// See VerifyTrust 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 *DirectoryService) VerifyTrustWithContext(ctx aws.Context, input *VerifyTrustInput, opts ...request.Option) (*VerifyTrustOutput, error) { + req, out := c.VerifyTrustRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // Please also see https://docs.aws.amazon.com/goto/WebAPI/ds-2015-04-16/AddIpRoutesRequest diff --git a/vendor/github.com/aws/aws-sdk-go/service/directoryservice/doc.go b/vendor/github.com/aws/aws-sdk-go/service/directoryservice/doc.go new file mode 100644 index 000000000..35aa7b366 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/service/directoryservice/doc.go @@ -0,0 +1,92 @@ +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. + +// Package directoryservice provides the client and types for making API +// requests to AWS Directory Service. +// +// AWS Directory Service is a web service that makes it easy for you to setup +// and run directories in the AWS cloud, or connect your AWS resources with +// an existing on-premises Microsoft Active Directory. This guide provides detailed +// information about AWS Directory Service operations, data types, parameters, +// and errors. For information about AWS Directory Services features, see AWS +// Directory Service (https://aws.amazon.com/directoryservice/) and the AWS +// Directory Service Administration Guide (http://docs.aws.amazon.com/directoryservice/latest/admin-guide/what_is.html). +// +// 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 AWS Directory Service +// and other AWS services. 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/). +// +// See https://docs.aws.amazon.com/goto/WebAPI/ds-2015-04-16 for more information on this service. +// +// See directoryservice package documentation for more information. +// https://docs.aws.amazon.com/sdk-for-go/api/service/directoryservice/ +// +// Using the Client +// +// To use the client for AWS Directory Service you will first need +// to create a new instance of it. +// +// When creating a client for an AWS service you'll first need to have a Session +// already created. The Session provides configuration that can be shared +// between multiple service clients. Additional configuration can be applied to +// the Session and service's client when they are constructed. The aws package's +// Config type contains several fields such as Region for the AWS Region the +// client should make API requests too. The optional Config value can be provided +// as the variadic argument for Sessions and client creation. +// +// Once the service's client is created you can use it to make API requests the +// AWS service. These clients are safe to use concurrently. +// +// // Create a session to share configuration, and load external configuration. +// sess := session.Must(session.NewSession()) +// +// // Create the service's client with the session. +// svc := directoryservice.New(sess) +// +// See the SDK's documentation for more information on how to use service clients. +// https://docs.aws.amazon.com/sdk-for-go/api/ +// +// See aws package's Config type for more information on configuration options. +// https://docs.aws.amazon.com/sdk-for-go/api/aws/#Config +// +// See the AWS Directory Service client DirectoryService for more +// information on creating the service's client. +// https://docs.aws.amazon.com/sdk-for-go/api/service/directoryservice/#New +// +// Once the client is created you can make an API request to the service. +// Each API method takes a input parameter, and returns the service response +// and an error. +// +// The API method will document which error codes the service can be returned +// by the operation if the service models the API operation's errors. These +// errors will also be available as const strings prefixed with "ErrCode". +// +// result, err := svc.AddIpRoutes(params) +// if err != nil { +// // Cast err to awserr.Error to handle specific error codes. +// aerr, ok := err.(awserr.Error) +// if ok && aerr.Code() == { +// // Specific error code handling +// } +// return err +// } +// +// fmt.Println("AddIpRoutes result:") +// fmt.Println(result) +// +// Using the Client with Context +// +// The service's client also provides methods to make API requests with a Context +// value. This allows you to control the timeout, and cancellation of pending +// requests. These methods also take request Option as variadic parameter to apply +// additional configuration to the API request. +// +// ctx := context.Background() +// +// result, err := svc.AddIpRoutesWithContext(ctx, params) +// +// See the request package documentation for more information on using Context pattern +// with the SDK. +// https://docs.aws.amazon.com/sdk-for-go/api/aws/request/ +package directoryservice diff --git a/vendor/github.com/aws/aws-sdk-go/service/directoryservice/errors.go b/vendor/github.com/aws/aws-sdk-go/service/directoryservice/errors.go index d8d9fa52a..64ba6fd0a 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/directoryservice/errors.go +++ b/vendor/github.com/aws/aws-sdk-go/service/directoryservice/errors.go @@ -1,4 +1,4 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. package directoryservice diff --git a/vendor/github.com/aws/aws-sdk-go/service/directoryservice/service.go b/vendor/github.com/aws/aws-sdk-go/service/directoryservice/service.go index 950ed3bef..59299ae5d 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/directoryservice/service.go +++ b/vendor/github.com/aws/aws-sdk-go/service/directoryservice/service.go @@ -1,4 +1,4 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. package directoryservice @@ -11,22 +11,12 @@ import ( "github.com/aws/aws-sdk-go/private/protocol/jsonrpc" ) -// AWS Directory Service is a web service that makes it easy for you to setup -// and run directories in the AWS cloud, or connect your AWS resources with -// an existing on-premises Microsoft Active Directory. This guide provides detailed -// information about AWS Directory Service operations, data types, parameters, -// and errors. For information about AWS Directory Services features, see AWS -// Directory Service (https://aws.amazon.com/directoryservice/) and the AWS -// Directory Service Administration Guide (http://docs.aws.amazon.com/directoryservice/latest/admin-guide/what_is.html). +// DirectoryService provides the API operation methods for making requests to +// AWS Directory Service. See this package's package overview docs +// for details on the service. // -// 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 AWS Directory Service -// and other AWS services. 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/). -// The service client's operations are safe to be used concurrently. -// It is not safe to mutate any of the client's properties though. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/ds-2015-04-16 +// DirectoryService methods are safe to use concurrently. It is not safe to +// modify mutate any of the struct's properties though. type DirectoryService struct { *client.Client } diff --git a/vendor/github.com/aws/aws-sdk-go/service/dynamodb/api.go b/vendor/github.com/aws/aws-sdk-go/service/dynamodb/api.go index 55dfb23c1..47c637bb5 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/dynamodb/api.go +++ b/vendor/github.com/aws/aws-sdk-go/service/dynamodb/api.go @@ -1,12 +1,12 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. -// Package dynamodb provides a client for Amazon DynamoDB. package dynamodb import ( "fmt" "time" + "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awsutil" "github.com/aws/aws-sdk-go/aws/request" "github.com/aws/aws-sdk-go/private/protocol" @@ -140,8 +140,23 @@ func (c *DynamoDB) BatchGetItemRequest(input *BatchGetItemInput) (req *request.R // Please also see https://docs.aws.amazon.com/goto/WebAPI/dynamodb-2012-08-10/BatchGetItem func (c *DynamoDB) BatchGetItem(input *BatchGetItemInput) (*BatchGetItemOutput, error) { req, out := c.BatchGetItemRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// BatchGetItemWithContext is the same as BatchGetItem with the addition of +// the ability to pass a context and additional request options. +// +// See BatchGetItem for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *DynamoDB) BatchGetItemWithContext(ctx aws.Context, input *BatchGetItemInput, opts ...request.Option) (*BatchGetItemOutput, error) { + req, out := c.BatchGetItemRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // BatchGetItemPages iterates over the pages of a BatchGetItem operation, @@ -161,12 +176,37 @@ func (c *DynamoDB) BatchGetItem(input *BatchGetItemInput) (*BatchGetItemOutput, // return pageNum <= 3 // }) // -func (c *DynamoDB) BatchGetItemPages(input *BatchGetItemInput, fn func(p *BatchGetItemOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.BatchGetItemRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*BatchGetItemOutput), lastPage) - }) +func (c *DynamoDB) BatchGetItemPages(input *BatchGetItemInput, fn func(*BatchGetItemOutput, bool) bool) error { + return c.BatchGetItemPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// BatchGetItemPagesWithContext same as BatchGetItemPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *DynamoDB) BatchGetItemPagesWithContext(ctx aws.Context, input *BatchGetItemInput, fn func(*BatchGetItemOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *BatchGetItemInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.BatchGetItemRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*BatchGetItemOutput), !p.HasNextPage()) + } + return p.Err() } const opBatchWriteItem = "BatchWriteItem" @@ -314,8 +354,23 @@ func (c *DynamoDB) BatchWriteItemRequest(input *BatchWriteItemInput) (req *reque // Please also see https://docs.aws.amazon.com/goto/WebAPI/dynamodb-2012-08-10/BatchWriteItem func (c *DynamoDB) BatchWriteItem(input *BatchWriteItemInput) (*BatchWriteItemOutput, error) { req, out := c.BatchWriteItemRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// BatchWriteItemWithContext is the same as BatchWriteItem with the addition of +// the ability to pass a context and additional request options. +// +// See BatchWriteItem for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *DynamoDB) BatchWriteItemWithContext(ctx aws.Context, input *BatchWriteItemInput, opts ...request.Option) (*BatchWriteItemOutput, error) { + req, out := c.BatchWriteItemRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateTable = "CreateTable" @@ -408,8 +463,23 @@ func (c *DynamoDB) CreateTableRequest(input *CreateTableInput) (req *request.Req // Please also see https://docs.aws.amazon.com/goto/WebAPI/dynamodb-2012-08-10/CreateTable func (c *DynamoDB) CreateTable(input *CreateTableInput) (*CreateTableOutput, error) { req, out := c.CreateTableRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateTableWithContext is the same as CreateTable with the addition of +// the ability to pass a context and additional request options. +// +// See CreateTable for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *DynamoDB) CreateTableWithContext(ctx aws.Context, input *CreateTableInput, opts ...request.Option) (*CreateTableOutput, error) { + req, out := c.CreateTableRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteItem = "DeleteItem" @@ -505,8 +575,23 @@ func (c *DynamoDB) DeleteItemRequest(input *DeleteItemInput) (req *request.Reque // Please also see https://docs.aws.amazon.com/goto/WebAPI/dynamodb-2012-08-10/DeleteItem func (c *DynamoDB) DeleteItem(input *DeleteItemInput) (*DeleteItemOutput, error) { req, out := c.DeleteItemRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteItemWithContext is the same as DeleteItem with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteItem for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *DynamoDB) DeleteItemWithContext(ctx aws.Context, input *DeleteItemInput, opts ...request.Option) (*DeleteItemOutput, error) { + req, out := c.DeleteItemRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteTable = "DeleteTable" @@ -606,8 +691,23 @@ func (c *DynamoDB) DeleteTableRequest(input *DeleteTableInput) (req *request.Req // Please also see https://docs.aws.amazon.com/goto/WebAPI/dynamodb-2012-08-10/DeleteTable func (c *DynamoDB) DeleteTable(input *DeleteTableInput) (*DeleteTableOutput, error) { req, out := c.DeleteTableRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteTableWithContext is the same as DeleteTable with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteTable for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *DynamoDB) DeleteTableWithContext(ctx aws.Context, input *DeleteTableInput, opts ...request.Option) (*DeleteTableOutput, error) { + req, out := c.DeleteTableRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeLimits = "DescribeLimits" @@ -727,8 +827,23 @@ func (c *DynamoDB) DescribeLimitsRequest(input *DescribeLimitsInput) (req *reque // Please also see https://docs.aws.amazon.com/goto/WebAPI/dynamodb-2012-08-10/DescribeLimits func (c *DynamoDB) DescribeLimits(input *DescribeLimitsInput) (*DescribeLimitsOutput, error) { req, out := c.DescribeLimitsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeLimitsWithContext is the same as DescribeLimits with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeLimits for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *DynamoDB) DescribeLimitsWithContext(ctx aws.Context, input *DescribeLimitsInput, opts ...request.Option) (*DescribeLimitsOutput, error) { + req, out := c.DescribeLimitsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeTable = "DescribeTable" @@ -804,8 +919,23 @@ func (c *DynamoDB) DescribeTableRequest(input *DescribeTableInput) (req *request // Please also see https://docs.aws.amazon.com/goto/WebAPI/dynamodb-2012-08-10/DescribeTable func (c *DynamoDB) DescribeTable(input *DescribeTableInput) (*DescribeTableOutput, error) { req, out := c.DescribeTableRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeTableWithContext is the same as DescribeTable with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeTable for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *DynamoDB) DescribeTableWithContext(ctx aws.Context, input *DescribeTableInput, opts ...request.Option) (*DescribeTableOutput, error) { + req, out := c.DescribeTableRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeTimeToLive = "DescribeTimeToLive" @@ -873,8 +1003,23 @@ func (c *DynamoDB) DescribeTimeToLiveRequest(input *DescribeTimeToLiveInput) (re // Please also see https://docs.aws.amazon.com/goto/WebAPI/dynamodb-2012-08-10/DescribeTimeToLive func (c *DynamoDB) DescribeTimeToLive(input *DescribeTimeToLiveInput) (*DescribeTimeToLiveOutput, error) { req, out := c.DescribeTimeToLiveRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeTimeToLiveWithContext is the same as DescribeTimeToLive with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeTimeToLive for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *DynamoDB) DescribeTimeToLiveWithContext(ctx aws.Context, input *DescribeTimeToLiveInput, opts ...request.Option) (*DescribeTimeToLiveOutput, error) { + req, out := c.DescribeTimeToLiveRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetItem = "GetItem" @@ -957,8 +1102,23 @@ func (c *DynamoDB) GetItemRequest(input *GetItemInput) (req *request.Request, ou // Please also see https://docs.aws.amazon.com/goto/WebAPI/dynamodb-2012-08-10/GetItem func (c *DynamoDB) GetItem(input *GetItemInput) (*GetItemOutput, error) { req, out := c.GetItemRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetItemWithContext is the same as GetItem with the addition of +// the ability to pass a context and additional request options. +// +// See GetItem for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *DynamoDB) GetItemWithContext(ctx aws.Context, input *GetItemInput, opts ...request.Option) (*GetItemOutput, error) { + req, out := c.GetItemRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opListTables = "ListTables" @@ -1030,8 +1190,23 @@ func (c *DynamoDB) ListTablesRequest(input *ListTablesInput) (req *request.Reque // Please also see https://docs.aws.amazon.com/goto/WebAPI/dynamodb-2012-08-10/ListTables func (c *DynamoDB) ListTables(input *ListTablesInput) (*ListTablesOutput, error) { req, out := c.ListTablesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListTablesWithContext is the same as ListTables with the addition of +// the ability to pass a context and additional request options. +// +// See ListTables for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *DynamoDB) ListTablesWithContext(ctx aws.Context, input *ListTablesInput, opts ...request.Option) (*ListTablesOutput, error) { + req, out := c.ListTablesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // ListTablesPages iterates over the pages of a ListTables operation, @@ -1051,12 +1226,37 @@ func (c *DynamoDB) ListTables(input *ListTablesInput) (*ListTablesOutput, error) // return pageNum <= 3 // }) // -func (c *DynamoDB) ListTablesPages(input *ListTablesInput, fn func(p *ListTablesOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.ListTablesRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*ListTablesOutput), lastPage) - }) +func (c *DynamoDB) ListTablesPages(input *ListTablesInput, fn func(*ListTablesOutput, bool) bool) error { + return c.ListTablesPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListTablesPagesWithContext same as ListTablesPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *DynamoDB) ListTablesPagesWithContext(ctx aws.Context, input *ListTablesInput, fn func(*ListTablesOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListTablesInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListTablesRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*ListTablesOutput), !p.HasNextPage()) + } + return p.Err() } const opListTagsOfResource = "ListTagsOfResource" @@ -1128,8 +1328,23 @@ func (c *DynamoDB) ListTagsOfResourceRequest(input *ListTagsOfResourceInput) (re // Please also see https://docs.aws.amazon.com/goto/WebAPI/dynamodb-2012-08-10/ListTagsOfResource func (c *DynamoDB) ListTagsOfResource(input *ListTagsOfResourceInput) (*ListTagsOfResourceOutput, error) { req, out := c.ListTagsOfResourceRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListTagsOfResourceWithContext is the same as ListTagsOfResource with the addition of +// the ability to pass a context and additional request options. +// +// See ListTagsOfResource for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *DynamoDB) ListTagsOfResourceWithContext(ctx aws.Context, input *ListTagsOfResourceInput, opts ...request.Option) (*ListTagsOfResourceOutput, error) { + req, out := c.ListTagsOfResourceRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opPutItem = "PutItem" @@ -1234,8 +1449,23 @@ func (c *DynamoDB) PutItemRequest(input *PutItemInput) (req *request.Request, ou // Please also see https://docs.aws.amazon.com/goto/WebAPI/dynamodb-2012-08-10/PutItem func (c *DynamoDB) PutItem(input *PutItemInput) (*PutItemOutput, error) { req, out := c.PutItemRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// PutItemWithContext is the same as PutItem with the addition of +// the ability to pass a context and additional request options. +// +// See PutItem for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *DynamoDB) PutItemWithContext(ctx aws.Context, input *PutItemInput, opts ...request.Option) (*PutItemOutput, error) { + req, out := c.PutItemRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opQuery = "Query" @@ -1342,8 +1572,23 @@ func (c *DynamoDB) QueryRequest(input *QueryInput) (req *request.Request, output // Please also see https://docs.aws.amazon.com/goto/WebAPI/dynamodb-2012-08-10/Query func (c *DynamoDB) Query(input *QueryInput) (*QueryOutput, error) { req, out := c.QueryRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// QueryWithContext is the same as Query with the addition of +// the ability to pass a context and additional request options. +// +// See Query for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *DynamoDB) QueryWithContext(ctx aws.Context, input *QueryInput, opts ...request.Option) (*QueryOutput, error) { + req, out := c.QueryRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // QueryPages iterates over the pages of a Query operation, @@ -1363,12 +1608,37 @@ func (c *DynamoDB) Query(input *QueryInput) (*QueryOutput, error) { // return pageNum <= 3 // }) // -func (c *DynamoDB) QueryPages(input *QueryInput, fn func(p *QueryOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.QueryRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*QueryOutput), lastPage) - }) +func (c *DynamoDB) QueryPages(input *QueryInput, fn func(*QueryOutput, bool) bool) error { + return c.QueryPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// QueryPagesWithContext same as QueryPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *DynamoDB) QueryPagesWithContext(ctx aws.Context, input *QueryInput, fn func(*QueryOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *QueryInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.QueryRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*QueryOutput), !p.HasNextPage()) + } + return p.Err() } const opScan = "Scan" @@ -1470,8 +1740,23 @@ func (c *DynamoDB) ScanRequest(input *ScanInput) (req *request.Request, output * // Please also see https://docs.aws.amazon.com/goto/WebAPI/dynamodb-2012-08-10/Scan func (c *DynamoDB) Scan(input *ScanInput) (*ScanOutput, error) { req, out := c.ScanRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ScanWithContext is the same as Scan with the addition of +// the ability to pass a context and additional request options. +// +// See Scan for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *DynamoDB) ScanWithContext(ctx aws.Context, input *ScanInput, opts ...request.Option) (*ScanOutput, error) { + req, out := c.ScanRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // ScanPages iterates over the pages of a Scan operation, @@ -1491,12 +1776,37 @@ func (c *DynamoDB) Scan(input *ScanInput) (*ScanOutput, error) { // return pageNum <= 3 // }) // -func (c *DynamoDB) ScanPages(input *ScanInput, fn func(p *ScanOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.ScanRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*ScanOutput), lastPage) - }) +func (c *DynamoDB) ScanPages(input *ScanInput, fn func(*ScanOutput, bool) bool) error { + return c.ScanPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ScanPagesWithContext same as ScanPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *DynamoDB) ScanPagesWithContext(ctx aws.Context, input *ScanInput, fn func(*ScanOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ScanInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ScanRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*ScanOutput), !p.HasNextPage()) + } + return p.Err() } const opTagResource = "TagResource" @@ -1587,8 +1897,23 @@ func (c *DynamoDB) TagResourceRequest(input *TagResourceInput) (req *request.Req // Please also see https://docs.aws.amazon.com/goto/WebAPI/dynamodb-2012-08-10/TagResource func (c *DynamoDB) TagResource(input *TagResourceInput) (*TagResourceOutput, error) { req, out := c.TagResourceRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// TagResourceWithContext is the same as TagResource with the addition of +// the ability to pass a context and additional request options. +// +// See TagResource for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *DynamoDB) TagResourceWithContext(ctx aws.Context, input *TagResourceInput, opts ...request.Option) (*TagResourceOutput, error) { + req, out := c.TagResourceRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opUntagResource = "UntagResource" @@ -1677,8 +2002,23 @@ func (c *DynamoDB) UntagResourceRequest(input *UntagResourceInput) (req *request // Please also see https://docs.aws.amazon.com/goto/WebAPI/dynamodb-2012-08-10/UntagResource func (c *DynamoDB) UntagResource(input *UntagResourceInput) (*UntagResourceOutput, error) { req, out := c.UntagResourceRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// UntagResourceWithContext is the same as UntagResource with the addition of +// the ability to pass a context and additional request options. +// +// See UntagResource for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *DynamoDB) UntagResourceWithContext(ctx aws.Context, input *UntagResourceInput, opts ...request.Option) (*UntagResourceOutput, error) { + req, out := c.UntagResourceRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opUpdateItem = "UpdateItem" @@ -1768,8 +2108,23 @@ func (c *DynamoDB) UpdateItemRequest(input *UpdateItemInput) (req *request.Reque // Please also see https://docs.aws.amazon.com/goto/WebAPI/dynamodb-2012-08-10/UpdateItem func (c *DynamoDB) UpdateItem(input *UpdateItemInput) (*UpdateItemOutput, error) { req, out := c.UpdateItemRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// UpdateItemWithContext is the same as UpdateItem with the addition of +// the ability to pass a context and additional request options. +// +// See UpdateItem for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *DynamoDB) UpdateItemWithContext(ctx aws.Context, input *UpdateItemInput, opts ...request.Option) (*UpdateItemOutput, error) { + req, out := c.UpdateItemRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opUpdateTable = "UpdateTable" @@ -1869,8 +2224,23 @@ func (c *DynamoDB) UpdateTableRequest(input *UpdateTableInput) (req *request.Req // Please also see https://docs.aws.amazon.com/goto/WebAPI/dynamodb-2012-08-10/UpdateTable func (c *DynamoDB) UpdateTable(input *UpdateTableInput) (*UpdateTableOutput, error) { req, out := c.UpdateTableRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// UpdateTableWithContext is the same as UpdateTable with the addition of +// the ability to pass a context and additional request options. +// +// See UpdateTable for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *DynamoDB) UpdateTableWithContext(ctx aws.Context, input *UpdateTableInput, opts ...request.Option) (*UpdateTableOutput, error) { + req, out := c.UpdateTableRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opUpdateTimeToLive = "UpdateTimeToLive" @@ -1980,8 +2350,23 @@ func (c *DynamoDB) UpdateTimeToLiveRequest(input *UpdateTimeToLiveInput) (req *r // Please also see https://docs.aws.amazon.com/goto/WebAPI/dynamodb-2012-08-10/UpdateTimeToLive func (c *DynamoDB) UpdateTimeToLive(input *UpdateTimeToLiveInput) (*UpdateTimeToLiveOutput, error) { req, out := c.UpdateTimeToLiveRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// UpdateTimeToLiveWithContext is the same as UpdateTimeToLive with the addition of +// the ability to pass a context and additional request options. +// +// See UpdateTimeToLive for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *DynamoDB) UpdateTimeToLiveWithContext(ctx aws.Context, input *UpdateTimeToLiveInput, opts ...request.Option) (*UpdateTimeToLiveOutput, error) { + req, out := c.UpdateTimeToLiveRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // Represents an attribute for describing the key schema for the table and indexes. @@ -3959,6 +4344,7 @@ func (s *DescribeTimeToLiveInput) SetTableName(v string) *DescribeTimeToLiveInpu type DescribeTimeToLiveOutput struct { _ struct{} `type:"structure"` + // The description of the Time to Live (TTL) status on the specified table. TimeToLiveDescription *TimeToLiveDescription `type:"structure"` } diff --git a/vendor/github.com/aws/aws-sdk-go/service/dynamodb/customizations.go b/vendor/github.com/aws/aws-sdk-go/service/dynamodb/customizations.go index 51843cd7a..333e61bfc 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/dynamodb/customizations.go +++ b/vendor/github.com/aws/aws-sdk-go/service/dynamodb/customizations.go @@ -26,19 +26,30 @@ func (d retryer) RetryRules(r *request.Request) time.Duration { func init() { initClient = func(c *client.Client) { - r := retryer{} - if c.Config.MaxRetries == nil || aws.IntValue(c.Config.MaxRetries) == aws.UseServiceDefaultRetries { - r.NumMaxRetries = 10 - } else { - r.NumMaxRetries = *c.Config.MaxRetries + if c.Config.Retryer == nil { + // Only override the retryer with a custom one if the config + // does not already contain a retryer + setCustomRetryer(c) } - c.Retryer = r c.Handlers.Build.PushBack(disableCompression) c.Handlers.Unmarshal.PushFront(validateCRC32) } } +func setCustomRetryer(c *client.Client) { + maxRetries := aws.IntValue(c.Config.MaxRetries) + if c.Config.MaxRetries == nil || maxRetries == aws.UseServiceDefaultRetries { + maxRetries = 10 + } + + c.Retryer = retryer{ + DefaultRetryer: client.DefaultRetryer{ + NumMaxRetries: maxRetries, + }, + } +} + func drainBody(b io.ReadCloser, length int64) (out *bytes.Buffer, err error) { if length < 0 { length = 0 diff --git a/vendor/github.com/aws/aws-sdk-go/service/dynamodb/doc.go b/vendor/github.com/aws/aws-sdk-go/service/dynamodb/doc.go new file mode 100644 index 000000000..256ef93e5 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/service/dynamodb/doc.go @@ -0,0 +1,97 @@ +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. + +// Package dynamodb provides the client and types for making API +// requests to Amazon DynamoDB. +// +// Amazon DynamoDB is a fully managed NoSQL database service that provides fast +// and predictable performance with seamless scalability. DynamoDB lets you +// offload the administrative burdens of operating and scaling a distributed +// database, so that you don't have to worry about hardware provisioning, setup +// and configuration, replication, software patching, or cluster scaling. +// +// With DynamoDB, you can create database tables that can store and retrieve +// any amount of data, and serve any level of request traffic. You can scale +// up or scale down your tables' throughput capacity without downtime or performance +// degradation, and use the AWS Management Console to monitor resource utilization +// and performance metrics. +// +// DynamoDB automatically spreads the data and traffic for your tables over +// a sufficient number of servers to handle your throughput and storage requirements, +// while maintaining consistent and fast performance. All of your data is stored +// on solid state disks (SSDs) and automatically replicated across multiple +// Availability Zones in an AWS region, providing built-in high availability +// and data durability. +// +// See https://docs.aws.amazon.com/goto/WebAPI/dynamodb-2012-08-10 for more information on this service. +// +// See dynamodb package documentation for more information. +// https://docs.aws.amazon.com/sdk-for-go/api/service/dynamodb/ +// +// Using the Client +// +// To use the client for Amazon DynamoDB you will first need +// to create a new instance of it. +// +// When creating a client for an AWS service you'll first need to have a Session +// already created. The Session provides configuration that can be shared +// between multiple service clients. Additional configuration can be applied to +// the Session and service's client when they are constructed. The aws package's +// Config type contains several fields such as Region for the AWS Region the +// client should make API requests too. The optional Config value can be provided +// as the variadic argument for Sessions and client creation. +// +// Once the service's client is created you can use it to make API requests the +// AWS service. These clients are safe to use concurrently. +// +// // Create a session to share configuration, and load external configuration. +// sess := session.Must(session.NewSession()) +// +// // Create the service's client with the session. +// svc := dynamodb.New(sess) +// +// See the SDK's documentation for more information on how to use service clients. +// https://docs.aws.amazon.com/sdk-for-go/api/ +// +// See aws package's Config type for more information on configuration options. +// https://docs.aws.amazon.com/sdk-for-go/api/aws/#Config +// +// See the Amazon DynamoDB client DynamoDB for more +// information on creating the service's client. +// https://docs.aws.amazon.com/sdk-for-go/api/service/dynamodb/#New +// +// Once the client is created you can make an API request to the service. +// Each API method takes a input parameter, and returns the service response +// and an error. +// +// The API method will document which error codes the service can be returned +// by the operation if the service models the API operation's errors. These +// errors will also be available as const strings prefixed with "ErrCode". +// +// result, err := svc.BatchGetItem(params) +// if err != nil { +// // Cast err to awserr.Error to handle specific error codes. +// aerr, ok := err.(awserr.Error) +// if ok && aerr.Code() == { +// // Specific error code handling +// } +// return err +// } +// +// fmt.Println("BatchGetItem result:") +// fmt.Println(result) +// +// Using the Client with Context +// +// The service's client also provides methods to make API requests with a Context +// value. This allows you to control the timeout, and cancellation of pending +// requests. These methods also take request Option as variadic parameter to apply +// additional configuration to the API request. +// +// ctx := context.Background() +// +// result, err := svc.BatchGetItemWithContext(ctx, params) +// +// See the request package documentation for more information on using Context pattern +// with the SDK. +// https://docs.aws.amazon.com/sdk-for-go/api/aws/request/ +package dynamodb diff --git a/vendor/github.com/aws/aws-sdk-go/service/dynamodb/doc_custom.go b/vendor/github.com/aws/aws-sdk-go/service/dynamodb/doc_custom.go new file mode 100644 index 000000000..53639be53 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/service/dynamodb/doc_custom.go @@ -0,0 +1,84 @@ +// AttributeValue Marshaling and Unmarshaling Helpers +// +// Utility helpers to marshal and unmarshal AttributeValue to and +// from Go types can be found in the dynamodbattribute sub package. This package +// provides has specialized functions for the common ways of working with +// AttributeValues. Such as map[string]*AttributeValue, []*AttributeValue, and +// directly with *AttributeValue. This is helpful for marshaling Go types for API +// operations such as PutItem, and unmarshaling Query and Scan APIs' responses. +// +// See the dynamodbattribute package documentation for more information. +// https://docs.aws.amazon.com/sdk-for-go/api/service/dynamodb/dynamodbattribute/ +// +// AttributeValue Marshaling +// +// To marshal a Go type to an AttributeValue you can use the Marshal +// functions in the dynamodbattribute package. There are specialized versions +// of these functions for collections of AttributeValue, such as maps and lists. +// +// The following example uses MarshalMap to convert the Record Go type to a +// dynamodb.AttributeValue type and use the value to make a PutItem API request. +// +// type Record struct { +// ID string +// URLs []string +// } +// +// //... +// +// r := Record{ +// ID: "ABC123", +// URLs: []string{ +// "https://example.com/first/link", +// "https://example.com/second/url", +// }, +// } +// av, err := dynamodbattribute.MarshalMap(r) +// if err != nil { +// panic(fmt.Sprintf("failed to DynamoDB marshal Record, %v", err)) +// } +// +// _, err = svc.PutItem(&dynamodb.PutItemInput{ +// TableName: aws.String(myTableName), +// Item: av, +// }) +// if err != nil { +// panic(fmt.Sprintf("failed to put Record to DynamoDB, %v", err)) +// } +// +// AttributeValue Unmarshaling +// +// To unmarshal a dynamodb.AttributeValue to a Go type you can use the Unmarshal +// functions in the dynamodbattribute package. There are specialized versions +// of these functions for collections of AttributeValue, such as maps and lists. +// +// The following example will unmarshal the DynamoDB's Scan API operation. The +// Items returned by the operation will be unmarshaled into the slice of Records +// Go type. +// +// type Record struct { +// ID string +// URLs []string +// } +// +// //... +// +// var records []Record +// +// // Use the ScanPages method to perform the scan with pagination. Use +// // just Scan method to make the API call without pagination. +// err := svc.ScanPages(&dynamodb.ScanInput{ +// TableName: aws.String(myTableName), +// }, func(page *dynamodb.ScanOutput, last bool) bool { +// recs := []Record{} +// +// err := dynamodbattribute.UnmarshalListOfMaps(page.Items, &recs) +// if err != nil { +// panic(fmt.Sprintf("failed to unmarshal Dynamodb Scan Items, %v", err)) +// } +// +// records = append(records, recs...) +// +// return true // keep paging +// }) +package dynamodb diff --git a/vendor/github.com/aws/aws-sdk-go/service/dynamodb/errors.go b/vendor/github.com/aws/aws-sdk-go/service/dynamodb/errors.go index 05a9ee84c..d47a10486 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/dynamodb/errors.go +++ b/vendor/github.com/aws/aws-sdk-go/service/dynamodb/errors.go @@ -1,4 +1,4 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. package dynamodb diff --git a/vendor/github.com/aws/aws-sdk-go/service/dynamodb/service.go b/vendor/github.com/aws/aws-sdk-go/service/dynamodb/service.go index b8765f033..80dcd19fd 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/dynamodb/service.go +++ b/vendor/github.com/aws/aws-sdk-go/service/dynamodb/service.go @@ -1,4 +1,4 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. package dynamodb @@ -11,27 +11,12 @@ import ( "github.com/aws/aws-sdk-go/private/protocol/jsonrpc" ) -// Amazon DynamoDB is a fully managed NoSQL database service that provides fast -// and predictable performance with seamless scalability. DynamoDB lets you -// offload the administrative burdens of operating and scaling a distributed -// database, so that you don't have to worry about hardware provisioning, setup -// and configuration, replication, software patching, or cluster scaling. +// DynamoDB provides the API operation methods for making requests to +// Amazon DynamoDB. See this package's package overview docs +// for details on the service. // -// With DynamoDB, you can create database tables that can store and retrieve -// any amount of data, and serve any level of request traffic. You can scale -// up or scale down your tables' throughput capacity without downtime or performance -// degradation, and use the AWS Management Console to monitor resource utilization -// and performance metrics. -// -// DynamoDB automatically spreads the data and traffic for your tables over -// a sufficient number of servers to handle your throughput and storage requirements, -// while maintaining consistent and fast performance. All of your data is stored -// on solid state disks (SSDs) and automatically replicated across multiple -// Availability Zones in an AWS region, providing built-in high availability -// and data durability. -// The service client's operations are safe to be used concurrently. -// It is not safe to mutate any of the client's properties though. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/dynamodb-2012-08-10 +// DynamoDB methods are safe to use concurrently. It is not safe to +// modify mutate any of the struct's properties though. type DynamoDB struct { *client.Client } diff --git a/vendor/github.com/aws/aws-sdk-go/service/dynamodb/waiters.go b/vendor/github.com/aws/aws-sdk-go/service/dynamodb/waiters.go index 57e1264b7..07c75c428 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/dynamodb/waiters.go +++ b/vendor/github.com/aws/aws-sdk-go/service/dynamodb/waiters.go @@ -1,9 +1,12 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. package dynamodb import ( - "github.com/aws/aws-sdk-go/private/waiter" + "time" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/request" ) // WaitUntilTableExists uses the DynamoDB API operation @@ -11,32 +14,50 @@ import ( // If the condition is not meet within the max attempt window an error will // be returned. func (c *DynamoDB) WaitUntilTableExists(input *DescribeTableInput) error { - waiterCfg := waiter.Config{ - Operation: "DescribeTable", - Delay: 20, + return c.WaitUntilTableExistsWithContext(aws.BackgroundContext(), input) +} + +// WaitUntilTableExistsWithContext is an extended version of WaitUntilTableExists. +// With the support for passing in a context and options to configure the +// Waiter and the underlying request options. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *DynamoDB) WaitUntilTableExistsWithContext(ctx aws.Context, input *DescribeTableInput, opts ...request.WaiterOption) error { + w := request.Waiter{ + Name: "WaitUntilTableExists", MaxAttempts: 25, - Acceptors: []waiter.WaitAcceptor{ + Delay: request.ConstantWaiterDelay(20 * time.Second), + Acceptors: []request.WaiterAcceptor{ { - State: "success", - Matcher: "path", - Argument: "Table.TableStatus", + State: request.SuccessWaiterState, + Matcher: request.PathWaiterMatch, Argument: "Table.TableStatus", Expected: "ACTIVE", }, { - State: "retry", - Matcher: "error", - Argument: "", + State: request.RetryWaiterState, + Matcher: request.ErrorWaiterMatch, Expected: "ResourceNotFoundException", }, }, + Logger: c.Config.Logger, + NewRequest: func(opts []request.Option) (*request.Request, error) { + var inCpy *DescribeTableInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeTableRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, } + w.ApplyOptions(opts...) - w := waiter.Waiter{ - Client: c, - Input: input, - Config: waiterCfg, - } - return w.Wait() + return w.WaitWithContext(ctx) } // WaitUntilTableNotExists uses the DynamoDB API operation @@ -44,24 +65,43 @@ func (c *DynamoDB) WaitUntilTableExists(input *DescribeTableInput) error { // If the condition is not meet within the max attempt window an error will // be returned. func (c *DynamoDB) WaitUntilTableNotExists(input *DescribeTableInput) error { - waiterCfg := waiter.Config{ - Operation: "DescribeTable", - Delay: 20, + return c.WaitUntilTableNotExistsWithContext(aws.BackgroundContext(), input) +} + +// WaitUntilTableNotExistsWithContext is an extended version of WaitUntilTableNotExists. +// With the support for passing in a context and options to configure the +// Waiter and the underlying request options. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *DynamoDB) WaitUntilTableNotExistsWithContext(ctx aws.Context, input *DescribeTableInput, opts ...request.WaiterOption) error { + w := request.Waiter{ + Name: "WaitUntilTableNotExists", MaxAttempts: 25, - Acceptors: []waiter.WaitAcceptor{ + Delay: request.ConstantWaiterDelay(20 * time.Second), + Acceptors: []request.WaiterAcceptor{ { - State: "success", - Matcher: "error", - Argument: "", + State: request.SuccessWaiterState, + Matcher: request.ErrorWaiterMatch, Expected: "ResourceNotFoundException", }, }, + Logger: c.Config.Logger, + NewRequest: func(opts []request.Option) (*request.Request, error) { + var inCpy *DescribeTableInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeTableRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, } + w.ApplyOptions(opts...) - w := waiter.Waiter{ - Client: c, - Input: input, - Config: waiterCfg, - } - return w.Wait() + return w.WaitWithContext(ctx) } diff --git a/vendor/github.com/aws/aws-sdk-go/service/ec2/api.go b/vendor/github.com/aws/aws-sdk-go/service/ec2/api.go index 83191e2d7..54338f0c2 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 @@ -1,12 +1,12 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. -// Package ec2 provides a client for Amazon Elastic Compute Cloud. package ec2 import ( "fmt" "time" + "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awsutil" "github.com/aws/aws-sdk-go/aws/request" "github.com/aws/aws-sdk-go/private/protocol" @@ -70,8 +70,23 @@ func (c *EC2) AcceptReservedInstancesExchangeQuoteRequest(input *AcceptReservedI // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/AcceptReservedInstancesExchangeQuote func (c *EC2) AcceptReservedInstancesExchangeQuote(input *AcceptReservedInstancesExchangeQuoteInput) (*AcceptReservedInstancesExchangeQuoteOutput, error) { req, out := c.AcceptReservedInstancesExchangeQuoteRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// AcceptReservedInstancesExchangeQuoteWithContext is the same as AcceptReservedInstancesExchangeQuote with the addition of +// the ability to pass a context and additional request options. +// +// See AcceptReservedInstancesExchangeQuote 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) AcceptReservedInstancesExchangeQuoteWithContext(ctx aws.Context, input *AcceptReservedInstancesExchangeQuoteInput, opts ...request.Option) (*AcceptReservedInstancesExchangeQuoteOutput, error) { + req, out := c.AcceptReservedInstancesExchangeQuoteRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opAcceptVpcPeeringConnection = "AcceptVpcPeeringConnection" @@ -121,8 +136,8 @@ func (c *EC2) AcceptVpcPeeringConnectionRequest(input *AcceptVpcPeeringConnectio // // Accept a VPC peering connection request. To accept a request, the VPC peering // connection must be in the pending-acceptance state, and you must be the owner -// of the peer VPC. Use the DescribeVpcPeeringConnections request to view your -// outstanding VPC peering connection requests. +// of the peer VPC. Use DescribeVpcPeeringConnections to view your outstanding +// VPC peering connection requests. // // 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 @@ -133,8 +148,23 @@ func (c *EC2) AcceptVpcPeeringConnectionRequest(input *AcceptVpcPeeringConnectio // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/AcceptVpcPeeringConnection func (c *EC2) AcceptVpcPeeringConnection(input *AcceptVpcPeeringConnectionInput) (*AcceptVpcPeeringConnectionOutput, error) { req, out := c.AcceptVpcPeeringConnectionRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// AcceptVpcPeeringConnectionWithContext is the same as AcceptVpcPeeringConnection with the addition of +// the ability to pass a context and additional request options. +// +// See AcceptVpcPeeringConnection 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) AcceptVpcPeeringConnectionWithContext(ctx aws.Context, input *AcceptVpcPeeringConnectionInput, opts ...request.Option) (*AcceptVpcPeeringConnectionOutput, error) { + req, out := c.AcceptVpcPeeringConnectionRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opAllocateAddress = "AllocateAddress" @@ -197,8 +227,23 @@ func (c *EC2) AllocateAddressRequest(input *AllocateAddressInput) (req *request. // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/AllocateAddress func (c *EC2) AllocateAddress(input *AllocateAddressInput) (*AllocateAddressOutput, error) { req, out := c.AllocateAddressRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// AllocateAddressWithContext is the same as AllocateAddress with the addition of +// the ability to pass a context and additional request options. +// +// See AllocateAddress 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) AllocateAddressWithContext(ctx aws.Context, input *AllocateAddressInput, opts ...request.Option) (*AllocateAddressOutput, error) { + req, out := c.AllocateAddressRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opAllocateHosts = "AllocateHosts" @@ -259,8 +304,23 @@ func (c *EC2) AllocateHostsRequest(input *AllocateHostsInput) (req *request.Requ // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/AllocateHosts func (c *EC2) AllocateHosts(input *AllocateHostsInput) (*AllocateHostsOutput, error) { req, out := c.AllocateHostsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// AllocateHostsWithContext is the same as AllocateHosts with the addition of +// the ability to pass a context and additional request options. +// +// See AllocateHosts 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) AllocateHostsWithContext(ctx aws.Context, input *AllocateHostsInput, opts ...request.Option) (*AllocateHostsOutput, error) { + req, out := c.AllocateHostsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opAssignIpv6Addresses = "AssignIpv6Addresses" @@ -326,8 +386,23 @@ func (c *EC2) AssignIpv6AddressesRequest(input *AssignIpv6AddressesInput) (req * // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/AssignIpv6Addresses func (c *EC2) AssignIpv6Addresses(input *AssignIpv6AddressesInput) (*AssignIpv6AddressesOutput, error) { req, out := c.AssignIpv6AddressesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// AssignIpv6AddressesWithContext is the same as AssignIpv6Addresses with the addition of +// the ability to pass a context and additional request options. +// +// See AssignIpv6Addresses 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) AssignIpv6AddressesWithContext(ctx aws.Context, input *AssignIpv6AddressesInput, opts ...request.Option) (*AssignIpv6AddressesOutput, error) { + req, out := c.AssignIpv6AddressesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opAssignPrivateIpAddresses = "AssignPrivateIpAddresses" @@ -398,8 +473,23 @@ func (c *EC2) AssignPrivateIpAddressesRequest(input *AssignPrivateIpAddressesInp // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/AssignPrivateIpAddresses func (c *EC2) AssignPrivateIpAddresses(input *AssignPrivateIpAddressesInput) (*AssignPrivateIpAddressesOutput, error) { req, out := c.AssignPrivateIpAddressesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// AssignPrivateIpAddressesWithContext is the same as AssignPrivateIpAddresses with the addition of +// the ability to pass a context and additional request options. +// +// See AssignPrivateIpAddresses 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) AssignPrivateIpAddressesWithContext(ctx aws.Context, input *AssignPrivateIpAddressesInput, opts ...request.Option) (*AssignPrivateIpAddressesOutput, error) { + req, out := c.AssignPrivateIpAddressesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opAssociateAddress = "AssociateAddress" @@ -455,12 +545,17 @@ func (c *EC2) AssociateAddressRequest(input *AssociateAddressInput) (req *reques // // [EC2-Classic, VPC in an EC2-VPC-only account] If the Elastic IP address is // already associated with a different instance, it is disassociated from that -// instance and associated with the specified instance. +// instance and associated with the specified instance. If you associate an +// Elastic IP address with an instance that has an existing Elastic IP address, +// the existing address is disassociated from the instance, but remains allocated +// to your account. // // [VPC in an EC2-Classic account] If you don't specify a private IP address, // the Elastic IP address is associated with the primary IP address. If the // Elastic IP address is already associated with a different instance or a network -// interface, you get an error unless you allow reassociation. +// interface, you get an error unless you allow reassociation. You cannot associate +// an Elastic IP address with an instance or network interface that has an existing +// Elastic IP address. // // This is an idempotent operation. If you perform the operation more than once, // Amazon EC2 doesn't return an error, and you may be charged for each time @@ -476,8 +571,23 @@ func (c *EC2) AssociateAddressRequest(input *AssociateAddressInput) (req *reques // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/AssociateAddress func (c *EC2) AssociateAddress(input *AssociateAddressInput) (*AssociateAddressOutput, error) { req, out := c.AssociateAddressRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// AssociateAddressWithContext is the same as AssociateAddress with the addition of +// the ability to pass a context and additional request options. +// +// See AssociateAddress 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) AssociateAddressWithContext(ctx aws.Context, input *AssociateAddressInput, opts ...request.Option) (*AssociateAddressOutput, error) { + req, out := c.AssociateAddressRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opAssociateDhcpOptions = "AssociateDhcpOptions" @@ -549,8 +659,23 @@ func (c *EC2) AssociateDhcpOptionsRequest(input *AssociateDhcpOptionsInput) (req // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/AssociateDhcpOptions func (c *EC2) AssociateDhcpOptions(input *AssociateDhcpOptionsInput) (*AssociateDhcpOptionsOutput, error) { req, out := c.AssociateDhcpOptionsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// AssociateDhcpOptionsWithContext is the same as AssociateDhcpOptions with the addition of +// the ability to pass a context and additional request options. +// +// See AssociateDhcpOptions 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) AssociateDhcpOptionsWithContext(ctx aws.Context, input *AssociateDhcpOptionsInput, opts ...request.Option) (*AssociateDhcpOptionsOutput, error) { + req, out := c.AssociateDhcpOptionsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opAssociateIamInstanceProfile = "AssociateIamInstanceProfile" @@ -610,8 +735,23 @@ func (c *EC2) AssociateIamInstanceProfileRequest(input *AssociateIamInstanceProf // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/AssociateIamInstanceProfile func (c *EC2) AssociateIamInstanceProfile(input *AssociateIamInstanceProfileInput) (*AssociateIamInstanceProfileOutput, error) { req, out := c.AssociateIamInstanceProfileRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// AssociateIamInstanceProfileWithContext is the same as AssociateIamInstanceProfile with the addition of +// the ability to pass a context and additional request options. +// +// See AssociateIamInstanceProfile 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) AssociateIamInstanceProfileWithContext(ctx aws.Context, input *AssociateIamInstanceProfileInput, opts ...request.Option) (*AssociateIamInstanceProfileOutput, error) { + req, out := c.AssociateIamInstanceProfileRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opAssociateRouteTable = "AssociateRouteTable" @@ -677,8 +817,23 @@ func (c *EC2) AssociateRouteTableRequest(input *AssociateRouteTableInput) (req * // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/AssociateRouteTable func (c *EC2) AssociateRouteTable(input *AssociateRouteTableInput) (*AssociateRouteTableOutput, error) { req, out := c.AssociateRouteTableRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// AssociateRouteTableWithContext is the same as AssociateRouteTable with the addition of +// the ability to pass a context and additional request options. +// +// See AssociateRouteTable 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) AssociateRouteTableWithContext(ctx aws.Context, input *AssociateRouteTableInput, opts ...request.Option) (*AssociateRouteTableOutput, error) { + req, out := c.AssociateRouteTableRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opAssociateSubnetCidrBlock = "AssociateSubnetCidrBlock" @@ -739,8 +894,23 @@ func (c *EC2) AssociateSubnetCidrBlockRequest(input *AssociateSubnetCidrBlockInp // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/AssociateSubnetCidrBlock func (c *EC2) AssociateSubnetCidrBlock(input *AssociateSubnetCidrBlockInput) (*AssociateSubnetCidrBlockOutput, error) { req, out := c.AssociateSubnetCidrBlockRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// AssociateSubnetCidrBlockWithContext is the same as AssociateSubnetCidrBlock with the addition of +// the ability to pass a context and additional request options. +// +// See AssociateSubnetCidrBlock 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) AssociateSubnetCidrBlockWithContext(ctx aws.Context, input *AssociateSubnetCidrBlockInput, opts ...request.Option) (*AssociateSubnetCidrBlockOutput, error) { + req, out := c.AssociateSubnetCidrBlockRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opAssociateVpcCidrBlock = "AssociateVpcCidrBlock" @@ -800,8 +970,23 @@ func (c *EC2) AssociateVpcCidrBlockRequest(input *AssociateVpcCidrBlockInput) (r // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/AssociateVpcCidrBlock func (c *EC2) AssociateVpcCidrBlock(input *AssociateVpcCidrBlockInput) (*AssociateVpcCidrBlockOutput, error) { req, out := c.AssociateVpcCidrBlockRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// AssociateVpcCidrBlockWithContext is the same as AssociateVpcCidrBlock with the addition of +// the ability to pass a context and additional request options. +// +// See AssociateVpcCidrBlock 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) AssociateVpcCidrBlockWithContext(ctx aws.Context, input *AssociateVpcCidrBlockInput, opts ...request.Option) (*AssociateVpcCidrBlockOutput, error) { + req, out := c.AssociateVpcCidrBlockRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opAttachClassicLinkVpc = "AttachClassicLinkVpc" @@ -871,8 +1056,23 @@ func (c *EC2) AttachClassicLinkVpcRequest(input *AttachClassicLinkVpcInput) (req // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/AttachClassicLinkVpc func (c *EC2) AttachClassicLinkVpc(input *AttachClassicLinkVpcInput) (*AttachClassicLinkVpcOutput, error) { req, out := c.AttachClassicLinkVpcRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// AttachClassicLinkVpcWithContext is the same as AttachClassicLinkVpc with the addition of +// the ability to pass a context and additional request options. +// +// See AttachClassicLinkVpc 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) AttachClassicLinkVpcWithContext(ctx aws.Context, input *AttachClassicLinkVpcInput, opts ...request.Option) (*AttachClassicLinkVpcOutput, error) { + req, out := c.AttachClassicLinkVpcRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opAttachInternetGateway = "AttachInternetGateway" @@ -935,8 +1135,23 @@ func (c *EC2) AttachInternetGatewayRequest(input *AttachInternetGatewayInput) (r // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/AttachInternetGateway func (c *EC2) AttachInternetGateway(input *AttachInternetGatewayInput) (*AttachInternetGatewayOutput, error) { req, out := c.AttachInternetGatewayRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// AttachInternetGatewayWithContext is the same as AttachInternetGateway with the addition of +// the ability to pass a context and additional request options. +// +// See AttachInternetGateway 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) AttachInternetGatewayWithContext(ctx aws.Context, input *AttachInternetGatewayInput, opts ...request.Option) (*AttachInternetGatewayOutput, error) { + req, out := c.AttachInternetGatewayRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opAttachNetworkInterface = "AttachNetworkInterface" @@ -995,8 +1210,23 @@ func (c *EC2) AttachNetworkInterfaceRequest(input *AttachNetworkInterfaceInput) // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/AttachNetworkInterface func (c *EC2) AttachNetworkInterface(input *AttachNetworkInterfaceInput) (*AttachNetworkInterfaceOutput, error) { req, out := c.AttachNetworkInterfaceRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// AttachNetworkInterfaceWithContext is the same as AttachNetworkInterface with the addition of +// the ability to pass a context and additional request options. +// +// See AttachNetworkInterface 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) AttachNetworkInterfaceWithContext(ctx aws.Context, input *AttachNetworkInterfaceInput, opts ...request.Option) (*AttachNetworkInterfaceOutput, error) { + req, out := c.AttachNetworkInterfaceRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opAttachVolume = "AttachVolume" @@ -1084,8 +1314,23 @@ func (c *EC2) AttachVolumeRequest(input *AttachVolumeInput) (req *request.Reques // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/AttachVolume func (c *EC2) AttachVolume(input *AttachVolumeInput) (*VolumeAttachment, error) { req, out := c.AttachVolumeRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// AttachVolumeWithContext is the same as AttachVolume with the addition of +// the ability to pass a context and additional request options. +// +// See AttachVolume 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) AttachVolumeWithContext(ctx aws.Context, input *AttachVolumeInput, opts ...request.Option) (*VolumeAttachment, error) { + req, out := c.AttachVolumeRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opAttachVpnGateway = "AttachVpnGateway" @@ -1133,8 +1378,11 @@ func (c *EC2) AttachVpnGatewayRequest(input *AttachVpnGatewayInput) (req *reques // AttachVpnGateway API operation for Amazon Elastic Compute Cloud. // -// Attaches a virtual private gateway to a VPC. For more information, see Adding -// a Hardware Virtual Private Gateway to Your VPC (http://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/VPC_VPN.html) +// Attaches a virtual private gateway to a VPC. You can attach one virtual private +// gateway to one VPC at a time. +// +// For more information, see Adding a Hardware Virtual Private Gateway to Your +// VPC (http://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/VPC_VPN.html) // in the Amazon Virtual Private Cloud User Guide. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions @@ -1146,8 +1394,23 @@ func (c *EC2) AttachVpnGatewayRequest(input *AttachVpnGatewayInput) (req *reques // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/AttachVpnGateway func (c *EC2) AttachVpnGateway(input *AttachVpnGatewayInput) (*AttachVpnGatewayOutput, error) { req, out := c.AttachVpnGatewayRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// AttachVpnGatewayWithContext is the same as AttachVpnGateway with the addition of +// the ability to pass a context and additional request options. +// +// See AttachVpnGateway 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) AttachVpnGatewayWithContext(ctx aws.Context, input *AttachVpnGatewayInput, opts ...request.Option) (*AttachVpnGatewayOutput, error) { + req, out := c.AttachVpnGatewayRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opAuthorizeSecurityGroupEgress = "AuthorizeSecurityGroupEgress" @@ -1224,8 +1487,23 @@ func (c *EC2) AuthorizeSecurityGroupEgressRequest(input *AuthorizeSecurityGroupE // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/AuthorizeSecurityGroupEgress func (c *EC2) AuthorizeSecurityGroupEgress(input *AuthorizeSecurityGroupEgressInput) (*AuthorizeSecurityGroupEgressOutput, error) { req, out := c.AuthorizeSecurityGroupEgressRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// AuthorizeSecurityGroupEgressWithContext is the same as AuthorizeSecurityGroupEgress with the addition of +// the ability to pass a context and additional request options. +// +// See AuthorizeSecurityGroupEgress 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) AuthorizeSecurityGroupEgressWithContext(ctx aws.Context, input *AuthorizeSecurityGroupEgressInput, opts ...request.Option) (*AuthorizeSecurityGroupEgressOutput, error) { + req, out := c.AuthorizeSecurityGroupEgressRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opAuthorizeSecurityGroupIngress = "AuthorizeSecurityGroupIngress" @@ -1302,8 +1580,23 @@ func (c *EC2) AuthorizeSecurityGroupIngressRequest(input *AuthorizeSecurityGroup // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/AuthorizeSecurityGroupIngress func (c *EC2) AuthorizeSecurityGroupIngress(input *AuthorizeSecurityGroupIngressInput) (*AuthorizeSecurityGroupIngressOutput, error) { req, out := c.AuthorizeSecurityGroupIngressRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// AuthorizeSecurityGroupIngressWithContext is the same as AuthorizeSecurityGroupIngress with the addition of +// the ability to pass a context and additional request options. +// +// See AuthorizeSecurityGroupIngress 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) AuthorizeSecurityGroupIngressWithContext(ctx aws.Context, input *AuthorizeSecurityGroupIngressInput, opts ...request.Option) (*AuthorizeSecurityGroupIngressOutput, error) { + req, out := c.AuthorizeSecurityGroupIngressRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opBundleInstance = "BundleInstance" @@ -1370,8 +1663,23 @@ func (c *EC2) BundleInstanceRequest(input *BundleInstanceInput) (req *request.Re // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/BundleInstance func (c *EC2) BundleInstance(input *BundleInstanceInput) (*BundleInstanceOutput, error) { req, out := c.BundleInstanceRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// BundleInstanceWithContext is the same as BundleInstance with the addition of +// the ability to pass a context and additional request options. +// +// See BundleInstance 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) BundleInstanceWithContext(ctx aws.Context, input *BundleInstanceInput, opts ...request.Option) (*BundleInstanceOutput, error) { + req, out := c.BundleInstanceRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCancelBundleTask = "CancelBundleTask" @@ -1430,8 +1738,23 @@ func (c *EC2) CancelBundleTaskRequest(input *CancelBundleTaskInput) (req *reques // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CancelBundleTask func (c *EC2) CancelBundleTask(input *CancelBundleTaskInput) (*CancelBundleTaskOutput, error) { req, out := c.CancelBundleTaskRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CancelBundleTaskWithContext is the same as CancelBundleTask with the addition of +// the ability to pass a context and additional request options. +// +// See CancelBundleTask 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) CancelBundleTaskWithContext(ctx aws.Context, input *CancelBundleTaskInput, opts ...request.Option) (*CancelBundleTaskOutput, error) { + req, out := c.CancelBundleTaskRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCancelConversionTask = "CancelConversionTask" @@ -1499,8 +1822,23 @@ func (c *EC2) CancelConversionTaskRequest(input *CancelConversionTaskInput) (req // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CancelConversionTask func (c *EC2) CancelConversionTask(input *CancelConversionTaskInput) (*CancelConversionTaskOutput, error) { req, out := c.CancelConversionTaskRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CancelConversionTaskWithContext is the same as CancelConversionTask with the addition of +// the ability to pass a context and additional request options. +// +// See CancelConversionTask 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) CancelConversionTaskWithContext(ctx aws.Context, input *CancelConversionTaskInput, opts ...request.Option) (*CancelConversionTaskOutput, error) { + req, out := c.CancelConversionTaskRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCancelExportTask = "CancelExportTask" @@ -1564,8 +1902,23 @@ func (c *EC2) CancelExportTaskRequest(input *CancelExportTaskInput) (req *reques // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CancelExportTask func (c *EC2) CancelExportTask(input *CancelExportTaskInput) (*CancelExportTaskOutput, error) { req, out := c.CancelExportTaskRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CancelExportTaskWithContext is the same as CancelExportTask with the addition of +// the ability to pass a context and additional request options. +// +// See CancelExportTask 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) CancelExportTaskWithContext(ctx aws.Context, input *CancelExportTaskInput, opts ...request.Option) (*CancelExportTaskOutput, error) { + req, out := c.CancelExportTaskRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCancelImportTask = "CancelImportTask" @@ -1624,8 +1977,23 @@ func (c *EC2) CancelImportTaskRequest(input *CancelImportTaskInput) (req *reques // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CancelImportTask func (c *EC2) CancelImportTask(input *CancelImportTaskInput) (*CancelImportTaskOutput, error) { req, out := c.CancelImportTaskRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CancelImportTaskWithContext is the same as CancelImportTask with the addition of +// the ability to pass a context and additional request options. +// +// See CancelImportTask 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) CancelImportTaskWithContext(ctx aws.Context, input *CancelImportTaskInput, opts ...request.Option) (*CancelImportTaskOutput, error) { + req, out := c.CancelImportTaskRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCancelReservedInstancesListing = "CancelReservedInstancesListing" @@ -1688,8 +2056,23 @@ func (c *EC2) CancelReservedInstancesListingRequest(input *CancelReservedInstanc // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CancelReservedInstancesListing func (c *EC2) CancelReservedInstancesListing(input *CancelReservedInstancesListingInput) (*CancelReservedInstancesListingOutput, error) { req, out := c.CancelReservedInstancesListingRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CancelReservedInstancesListingWithContext is the same as CancelReservedInstancesListing with the addition of +// the ability to pass a context and additional request options. +// +// See CancelReservedInstancesListing 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) CancelReservedInstancesListingWithContext(ctx aws.Context, input *CancelReservedInstancesListingInput, opts ...request.Option) (*CancelReservedInstancesListingOutput, error) { + req, out := c.CancelReservedInstancesListingRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCancelSpotFleetRequests = "CancelSpotFleetRequests" @@ -1755,8 +2138,23 @@ func (c *EC2) CancelSpotFleetRequestsRequest(input *CancelSpotFleetRequestsInput // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CancelSpotFleetRequests func (c *EC2) CancelSpotFleetRequests(input *CancelSpotFleetRequestsInput) (*CancelSpotFleetRequestsOutput, error) { req, out := c.CancelSpotFleetRequestsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CancelSpotFleetRequestsWithContext is the same as CancelSpotFleetRequests with the addition of +// the ability to pass a context and additional request options. +// +// See CancelSpotFleetRequests 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) CancelSpotFleetRequestsWithContext(ctx aws.Context, input *CancelSpotFleetRequestsInput, opts ...request.Option) (*CancelSpotFleetRequestsOutput, error) { + req, out := c.CancelSpotFleetRequestsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCancelSpotInstanceRequests = "CancelSpotInstanceRequests" @@ -1823,8 +2221,23 @@ func (c *EC2) CancelSpotInstanceRequestsRequest(input *CancelSpotInstanceRequest // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CancelSpotInstanceRequests func (c *EC2) CancelSpotInstanceRequests(input *CancelSpotInstanceRequestsInput) (*CancelSpotInstanceRequestsOutput, error) { req, out := c.CancelSpotInstanceRequestsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CancelSpotInstanceRequestsWithContext is the same as CancelSpotInstanceRequests with the addition of +// the ability to pass a context and additional request options. +// +// See CancelSpotInstanceRequests 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) CancelSpotInstanceRequestsWithContext(ctx aws.Context, input *CancelSpotInstanceRequestsInput, opts ...request.Option) (*CancelSpotInstanceRequestsOutput, error) { + req, out := c.CancelSpotInstanceRequestsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opConfirmProductInstance = "ConfirmProductInstance" @@ -1886,8 +2299,23 @@ func (c *EC2) ConfirmProductInstanceRequest(input *ConfirmProductInstanceInput) // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ConfirmProductInstance func (c *EC2) ConfirmProductInstance(input *ConfirmProductInstanceInput) (*ConfirmProductInstanceOutput, error) { req, out := c.ConfirmProductInstanceRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ConfirmProductInstanceWithContext is the same as ConfirmProductInstance with the addition of +// the ability to pass a context and additional request options. +// +// See ConfirmProductInstance 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) ConfirmProductInstanceWithContext(ctx aws.Context, input *ConfirmProductInstanceInput, opts ...request.Option) (*ConfirmProductInstanceOutput, error) { + req, out := c.ConfirmProductInstanceRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCopyImage = "CopyImage" @@ -1951,8 +2379,23 @@ func (c *EC2) CopyImageRequest(input *CopyImageInput) (req *request.Request, out // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CopyImage func (c *EC2) CopyImage(input *CopyImageInput) (*CopyImageOutput, error) { req, out := c.CopyImageRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CopyImageWithContext is the same as CopyImage with the addition of +// the ability to pass a context and additional request options. +// +// See CopyImage 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) CopyImageWithContext(ctx aws.Context, input *CopyImageInput, opts ...request.Option) (*CopyImageOutput, error) { + req, out := c.CopyImageRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCopySnapshot = "CopySnapshot" @@ -2030,8 +2473,23 @@ func (c *EC2) CopySnapshotRequest(input *CopySnapshotInput) (req *request.Reques // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CopySnapshot func (c *EC2) CopySnapshot(input *CopySnapshotInput) (*CopySnapshotOutput, error) { req, out := c.CopySnapshotRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CopySnapshotWithContext is the same as CopySnapshot with the addition of +// the ability to pass a context and additional request options. +// +// See CopySnapshot 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) CopySnapshotWithContext(ctx aws.Context, input *CopySnapshotInput, opts ...request.Option) (*CopySnapshotOutput, error) { + req, out := c.CopySnapshotRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateCustomerGateway = "CreateCustomerGateway" @@ -2114,8 +2572,23 @@ func (c *EC2) CreateCustomerGatewayRequest(input *CreateCustomerGatewayInput) (r // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateCustomerGateway func (c *EC2) CreateCustomerGateway(input *CreateCustomerGatewayInput) (*CreateCustomerGatewayOutput, error) { req, out := c.CreateCustomerGatewayRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateCustomerGatewayWithContext is the same as CreateCustomerGateway with the addition of +// the ability to pass a context and additional request options. +// +// See CreateCustomerGateway 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) CreateCustomerGatewayWithContext(ctx aws.Context, input *CreateCustomerGatewayInput, opts ...request.Option) (*CreateCustomerGatewayOutput, error) { + req, out := c.CreateCustomerGatewayRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateDhcpOptions = "CreateDhcpOptions" @@ -2176,16 +2649,16 @@ func (c *EC2) CreateDhcpOptionsRequest(input *CreateDhcpOptionsInput) (req *requ // to receive a custom DNS hostname as specified in domain-name, you must // set domain-name-servers to a custom DNS server. // -// * 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. +// * 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. // // * ntp-servers - The IP addresses of up to four Network Time Protocol (NTP) // servers. @@ -2213,8 +2686,23 @@ func (c *EC2) CreateDhcpOptionsRequest(input *CreateDhcpOptionsInput) (req *requ // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateDhcpOptions func (c *EC2) CreateDhcpOptions(input *CreateDhcpOptionsInput) (*CreateDhcpOptionsOutput, error) { req, out := c.CreateDhcpOptionsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateDhcpOptionsWithContext is the same as CreateDhcpOptions with the addition of +// the ability to pass a context and additional request options. +// +// See CreateDhcpOptions 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) CreateDhcpOptionsWithContext(ctx aws.Context, input *CreateDhcpOptionsInput, opts ...request.Option) (*CreateDhcpOptionsOutput, error) { + req, out := c.CreateDhcpOptionsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateEgressOnlyInternetGateway = "CreateEgressOnlyInternetGateway" @@ -2276,8 +2764,23 @@ func (c *EC2) CreateEgressOnlyInternetGatewayRequest(input *CreateEgressOnlyInte // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateEgressOnlyInternetGateway func (c *EC2) CreateEgressOnlyInternetGateway(input *CreateEgressOnlyInternetGatewayInput) (*CreateEgressOnlyInternetGatewayOutput, error) { req, out := c.CreateEgressOnlyInternetGatewayRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateEgressOnlyInternetGatewayWithContext is the same as CreateEgressOnlyInternetGateway with the addition of +// the ability to pass a context and additional request options. +// +// See CreateEgressOnlyInternetGateway 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) CreateEgressOnlyInternetGatewayWithContext(ctx aws.Context, input *CreateEgressOnlyInternetGatewayInput, opts ...request.Option) (*CreateEgressOnlyInternetGatewayOutput, error) { + req, out := c.CreateEgressOnlyInternetGatewayRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateFlowLogs = "CreateFlowLogs" @@ -2345,8 +2848,105 @@ func (c *EC2) CreateFlowLogsRequest(input *CreateFlowLogsInput) (req *request.Re // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateFlowLogs func (c *EC2) CreateFlowLogs(input *CreateFlowLogsInput) (*CreateFlowLogsOutput, error) { req, out := c.CreateFlowLogsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateFlowLogsWithContext is the same as CreateFlowLogs with the addition of +// the ability to pass a context and additional request options. +// +// See CreateFlowLogs 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) CreateFlowLogsWithContext(ctx aws.Context, input *CreateFlowLogsInput, opts ...request.Option) (*CreateFlowLogsOutput, error) { + req, out := c.CreateFlowLogsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opCreateFpgaImage = "CreateFpgaImage" + +// CreateFpgaImageRequest generates a "aws/request.Request" representing the +// client's request for the CreateFpgaImage operation. The "output" return +// value can be used to capture response data after the request's "Send" method +// is called. +// +// See CreateFpgaImage for usage and error information. +// +// Creating a request object using this method should be used when you want to inject +// custom logic into the request's lifecycle using a custom handler, or if you want to +// access properties on the request object before or after sending the request. If +// you just want the service response, call the CreateFpgaImage method directly +// instead. +// +// Note: You must call the "Send" method on the returned request object in order +// to execute the request. +// +// // Example sending a request using the CreateFpgaImageRequest method. +// req, resp := client.CreateFpgaImageRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateFpgaImage +func (c *EC2) CreateFpgaImageRequest(input *CreateFpgaImageInput) (req *request.Request, output *CreateFpgaImageOutput) { + op := &request.Operation{ + Name: opCreateFpgaImage, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &CreateFpgaImageInput{} + } + + output = &CreateFpgaImageOutput{} + req = c.newRequest(op, input, output) + return +} + +// CreateFpgaImage API operation for Amazon Elastic Compute Cloud. +// +// Creates an Amazon FPGA Image (AFI) from the specified design checkpoint (DCP). +// +// The create operation is asynchronous. To verify that the AFI is ready for +// use, check the output logs. +// +// An AFI contains the FPGA bitstream that is ready to download to an FPGA. +// You can securely deploy an AFI on one or more FPGA-accelerated instances. +// For more information, see the AWS FPGA Hardware Development Kit (https://github.com/aws/aws-fpga/). +// +// 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 CreateFpgaImage for usage and error information. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateFpgaImage +func (c *EC2) CreateFpgaImage(input *CreateFpgaImageInput) (*CreateFpgaImageOutput, error) { + req, out := c.CreateFpgaImageRequest(input) + return out, req.Send() +} + +// CreateFpgaImageWithContext is the same as CreateFpgaImage with the addition of +// the ability to pass a context and additional request options. +// +// See CreateFpgaImage 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) CreateFpgaImageWithContext(ctx aws.Context, input *CreateFpgaImageInput, opts ...request.Option) (*CreateFpgaImageOutput, error) { + req, out := c.CreateFpgaImageRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateImage = "CreateImage" @@ -2414,8 +3014,23 @@ func (c *EC2) CreateImageRequest(input *CreateImageInput) (req *request.Request, // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateImage func (c *EC2) CreateImage(input *CreateImageInput) (*CreateImageOutput, error) { req, out := c.CreateImageRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateImageWithContext is the same as CreateImage with the addition of +// the ability to pass a context and additional request options. +// +// See CreateImage 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) CreateImageWithContext(ctx aws.Context, input *CreateImageInput, opts ...request.Option) (*CreateImageOutput, error) { + req, out := c.CreateImageRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateInstanceExportTask = "CreateInstanceExportTask" @@ -2479,8 +3094,23 @@ func (c *EC2) CreateInstanceExportTaskRequest(input *CreateInstanceExportTaskInp // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateInstanceExportTask func (c *EC2) CreateInstanceExportTask(input *CreateInstanceExportTaskInput) (*CreateInstanceExportTaskOutput, error) { req, out := c.CreateInstanceExportTaskRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateInstanceExportTaskWithContext is the same as CreateInstanceExportTask with the addition of +// the ability to pass a context and additional request options. +// +// See CreateInstanceExportTask 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) CreateInstanceExportTaskWithContext(ctx aws.Context, input *CreateInstanceExportTaskInput, opts ...request.Option) (*CreateInstanceExportTaskOutput, error) { + req, out := c.CreateInstanceExportTaskRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateInternetGateway = "CreateInternetGateway" @@ -2543,8 +3173,23 @@ func (c *EC2) CreateInternetGatewayRequest(input *CreateInternetGatewayInput) (r // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateInternetGateway func (c *EC2) CreateInternetGateway(input *CreateInternetGatewayInput) (*CreateInternetGatewayOutput, error) { req, out := c.CreateInternetGatewayRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateInternetGatewayWithContext is the same as CreateInternetGateway with the addition of +// the ability to pass a context and additional request options. +// +// See CreateInternetGateway 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) CreateInternetGatewayWithContext(ctx aws.Context, input *CreateInternetGatewayInput, opts ...request.Option) (*CreateInternetGatewayOutput, error) { + req, out := c.CreateInternetGatewayRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateKeyPair = "CreateKeyPair" @@ -2614,8 +3259,23 @@ func (c *EC2) CreateKeyPairRequest(input *CreateKeyPairInput) (req *request.Requ // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateKeyPair func (c *EC2) CreateKeyPair(input *CreateKeyPairInput) (*CreateKeyPairOutput, error) { req, out := c.CreateKeyPairRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateKeyPairWithContext is the same as CreateKeyPair with the addition of +// the ability to pass a context and additional request options. +// +// See CreateKeyPair 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) CreateKeyPairWithContext(ctx aws.Context, input *CreateKeyPairInput, opts ...request.Option) (*CreateKeyPairOutput, error) { + req, out := c.CreateKeyPairRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateNatGateway = "CreateNatGateway" @@ -2679,8 +3339,23 @@ func (c *EC2) CreateNatGatewayRequest(input *CreateNatGatewayInput) (req *reques // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateNatGateway func (c *EC2) CreateNatGateway(input *CreateNatGatewayInput) (*CreateNatGatewayOutput, error) { req, out := c.CreateNatGatewayRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateNatGatewayWithContext is the same as CreateNatGateway with the addition of +// the ability to pass a context and additional request options. +// +// See CreateNatGateway 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) CreateNatGatewayWithContext(ctx aws.Context, input *CreateNatGatewayInput, opts ...request.Option) (*CreateNatGatewayOutput, error) { + req, out := c.CreateNatGatewayRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateNetworkAcl = "CreateNetworkAcl" @@ -2743,8 +3418,23 @@ func (c *EC2) CreateNetworkAclRequest(input *CreateNetworkAclInput) (req *reques // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateNetworkAcl func (c *EC2) CreateNetworkAcl(input *CreateNetworkAclInput) (*CreateNetworkAclOutput, error) { req, out := c.CreateNetworkAclRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateNetworkAclWithContext is the same as CreateNetworkAcl with the addition of +// the ability to pass a context and additional request options. +// +// See CreateNetworkAcl 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) CreateNetworkAclWithContext(ctx aws.Context, input *CreateNetworkAclInput, opts ...request.Option) (*CreateNetworkAclOutput, error) { + req, out := c.CreateNetworkAclRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateNetworkAclEntry = "CreateNetworkAclEntry" @@ -2821,8 +3511,23 @@ func (c *EC2) CreateNetworkAclEntryRequest(input *CreateNetworkAclEntryInput) (r // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateNetworkAclEntry func (c *EC2) CreateNetworkAclEntry(input *CreateNetworkAclEntryInput) (*CreateNetworkAclEntryOutput, error) { req, out := c.CreateNetworkAclEntryRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateNetworkAclEntryWithContext is the same as CreateNetworkAclEntry with the addition of +// the ability to pass a context and additional request options. +// +// See CreateNetworkAclEntry 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) CreateNetworkAclEntryWithContext(ctx aws.Context, input *CreateNetworkAclEntryInput, opts ...request.Option) (*CreateNetworkAclEntryOutput, error) { + req, out := c.CreateNetworkAclEntryRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateNetworkInterface = "CreateNetworkInterface" @@ -2885,8 +3590,23 @@ func (c *EC2) CreateNetworkInterfaceRequest(input *CreateNetworkInterfaceInput) // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateNetworkInterface func (c *EC2) CreateNetworkInterface(input *CreateNetworkInterfaceInput) (*CreateNetworkInterfaceOutput, error) { req, out := c.CreateNetworkInterfaceRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateNetworkInterfaceWithContext is the same as CreateNetworkInterface with the addition of +// the ability to pass a context and additional request options. +// +// See CreateNetworkInterface 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) CreateNetworkInterfaceWithContext(ctx aws.Context, input *CreateNetworkInterfaceInput, opts ...request.Option) (*CreateNetworkInterfaceOutput, error) { + req, out := c.CreateNetworkInterfaceRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreatePlacementGroup = "CreatePlacementGroup" @@ -2952,8 +3672,23 @@ func (c *EC2) CreatePlacementGroupRequest(input *CreatePlacementGroupInput) (req // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreatePlacementGroup func (c *EC2) CreatePlacementGroup(input *CreatePlacementGroupInput) (*CreatePlacementGroupOutput, error) { req, out := c.CreatePlacementGroupRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreatePlacementGroupWithContext is the same as CreatePlacementGroup with the addition of +// the ability to pass a context and additional request options. +// +// See CreatePlacementGroup 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) CreatePlacementGroupWithContext(ctx aws.Context, input *CreatePlacementGroupInput, opts ...request.Option) (*CreatePlacementGroupOutput, error) { + req, out := c.CreatePlacementGroupRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateReservedInstancesListing = "CreateReservedInstancesListing" @@ -3035,8 +3770,23 @@ func (c *EC2) CreateReservedInstancesListingRequest(input *CreateReservedInstanc // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateReservedInstancesListing func (c *EC2) CreateReservedInstancesListing(input *CreateReservedInstancesListingInput) (*CreateReservedInstancesListingOutput, error) { req, out := c.CreateReservedInstancesListingRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateReservedInstancesListingWithContext is the same as CreateReservedInstancesListing with the addition of +// the ability to pass a context and additional request options. +// +// See CreateReservedInstancesListing 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) CreateReservedInstancesListingWithContext(ctx aws.Context, input *CreateReservedInstancesListingInput, opts ...request.Option) (*CreateReservedInstancesListingOutput, error) { + req, out := c.CreateReservedInstancesListingRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateRoute = "CreateRoute" @@ -3114,8 +3864,23 @@ func (c *EC2) CreateRouteRequest(input *CreateRouteInput) (req *request.Request, // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateRoute func (c *EC2) CreateRoute(input *CreateRouteInput) (*CreateRouteOutput, error) { req, out := c.CreateRouteRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateRouteWithContext is the same as CreateRoute with the addition of +// the ability to pass a context and additional request options. +// +// See CreateRoute 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) CreateRouteWithContext(ctx aws.Context, input *CreateRouteInput, opts ...request.Option) (*CreateRouteOutput, error) { + req, out := c.CreateRouteRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateRouteTable = "CreateRouteTable" @@ -3178,8 +3943,23 @@ func (c *EC2) CreateRouteTableRequest(input *CreateRouteTableInput) (req *reques // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateRouteTable func (c *EC2) CreateRouteTable(input *CreateRouteTableInput) (*CreateRouteTableOutput, error) { req, out := c.CreateRouteTableRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateRouteTableWithContext is the same as CreateRouteTable with the addition of +// the ability to pass a context and additional request options. +// +// See CreateRouteTable 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) CreateRouteTableWithContext(ctx aws.Context, input *CreateRouteTableInput, opts ...request.Option) (*CreateRouteTableOutput, error) { + req, out := c.CreateRouteTableRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateSecurityGroup = "CreateSecurityGroup" @@ -3264,8 +4044,23 @@ func (c *EC2) CreateSecurityGroupRequest(input *CreateSecurityGroupInput) (req * // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateSecurityGroup func (c *EC2) CreateSecurityGroup(input *CreateSecurityGroupInput) (*CreateSecurityGroupOutput, error) { req, out := c.CreateSecurityGroupRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateSecurityGroupWithContext is the same as CreateSecurityGroup with the addition of +// the ability to pass a context and additional request options. +// +// See CreateSecurityGroup 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) CreateSecurityGroupWithContext(ctx aws.Context, input *CreateSecurityGroupInput, opts ...request.Option) (*CreateSecurityGroupOutput, error) { + req, out := c.CreateSecurityGroupRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateSnapshot = "CreateSnapshot" @@ -3351,8 +4146,23 @@ func (c *EC2) CreateSnapshotRequest(input *CreateSnapshotInput) (req *request.Re // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateSnapshot func (c *EC2) CreateSnapshot(input *CreateSnapshotInput) (*Snapshot, error) { req, out := c.CreateSnapshotRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateSnapshotWithContext is the same as CreateSnapshot with the addition of +// the ability to pass a context and additional request options. +// +// See CreateSnapshot 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) CreateSnapshotWithContext(ctx aws.Context, input *CreateSnapshotInput, opts ...request.Option) (*Snapshot, error) { + req, out := c.CreateSnapshotRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateSpotDatafeedSubscription = "CreateSpotDatafeedSubscription" @@ -3414,8 +4224,23 @@ func (c *EC2) CreateSpotDatafeedSubscriptionRequest(input *CreateSpotDatafeedSub // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateSpotDatafeedSubscription func (c *EC2) CreateSpotDatafeedSubscription(input *CreateSpotDatafeedSubscriptionInput) (*CreateSpotDatafeedSubscriptionOutput, error) { req, out := c.CreateSpotDatafeedSubscriptionRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateSpotDatafeedSubscriptionWithContext is the same as CreateSpotDatafeedSubscription with the addition of +// the ability to pass a context and additional request options. +// +// See CreateSpotDatafeedSubscription 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) CreateSpotDatafeedSubscriptionWithContext(ctx aws.Context, input *CreateSpotDatafeedSubscriptionInput, opts ...request.Option) (*CreateSpotDatafeedSubscriptionOutput, error) { + req, out := c.CreateSpotDatafeedSubscriptionRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateSubnet = "CreateSubnet" @@ -3477,7 +4302,7 @@ func (c *EC2) CreateSubnetRequest(input *CreateSubnetInput) (req *request.Reques // 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. // -// AWS reserves both the first four and the last IP address in each subnet's +// AWS reserves both the first four and the last IPv4 address in each subnet's // CIDR block. They're not available for use. // // If you add more than one subnet to a VPC, they're set up in a star topology @@ -3501,8 +4326,23 @@ func (c *EC2) CreateSubnetRequest(input *CreateSubnetInput) (req *request.Reques // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateSubnet func (c *EC2) CreateSubnet(input *CreateSubnetInput) (*CreateSubnetOutput, error) { req, out := c.CreateSubnetRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateSubnetWithContext is the same as CreateSubnet with the addition of +// the ability to pass a context and additional request options. +// +// See CreateSubnet 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) CreateSubnetWithContext(ctx aws.Context, input *CreateSubnetInput, opts ...request.Option) (*CreateSubnetOutput, error) { + req, out := c.CreateSubnetRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateTags = "CreateTags" @@ -3571,8 +4411,23 @@ func (c *EC2) CreateTagsRequest(input *CreateTagsInput) (req *request.Request, o // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateTags func (c *EC2) CreateTags(input *CreateTagsInput) (*CreateTagsOutput, error) { req, out := c.CreateTagsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateTagsWithContext is the same as CreateTags with the addition of +// the ability to pass a context and additional request options. +// +// See CreateTags 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) CreateTagsWithContext(ctx aws.Context, input *CreateTagsInput, opts ...request.Option) (*CreateTagsOutput, error) { + req, out := c.CreateTagsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateVolume = "CreateVolume" @@ -3634,7 +4489,10 @@ func (c *EC2) CreateVolumeRequest(input *CreateVolumeInput) (req *request.Reques // encrypted. For more information, see Amazon EBS Encryption (http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSEncryption.html) // in the Amazon Elastic Compute Cloud User Guide. // -// For more information, see Creating or Restoring an Amazon EBS Volume (http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-creating-volume.html) +// You can tag your volumes during creation. For more information, see Tagging +// Your Amazon EC2 Resources (http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html). +// +// For more information, see Creating an Amazon EBS Volume (http://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 @@ -3646,8 +4504,23 @@ func (c *EC2) CreateVolumeRequest(input *CreateVolumeInput) (req *request.Reques // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateVolume func (c *EC2) CreateVolume(input *CreateVolumeInput) (*Volume, error) { req, out := c.CreateVolumeRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateVolumeWithContext is the same as CreateVolume with the addition of +// the ability to pass a context and additional request options. +// +// See CreateVolume 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) CreateVolumeWithContext(ctx aws.Context, input *CreateVolumeInput, opts ...request.Option) (*Volume, error) { + req, out := c.CreateVolumeRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateVpc = "CreateVpc" @@ -3724,8 +4597,23 @@ func (c *EC2) CreateVpcRequest(input *CreateVpcInput) (req *request.Request, out // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateVpc func (c *EC2) CreateVpc(input *CreateVpcInput) (*CreateVpcOutput, error) { req, out := c.CreateVpcRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateVpcWithContext is the same as CreateVpc with the addition of +// the ability to pass a context and additional request options. +// +// See CreateVpc 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) CreateVpcWithContext(ctx aws.Context, input *CreateVpcInput, opts ...request.Option) (*CreateVpcOutput, error) { + req, out := c.CreateVpcRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateVpcEndpoint = "CreateVpcEndpoint" @@ -3790,8 +4678,23 @@ func (c *EC2) CreateVpcEndpointRequest(input *CreateVpcEndpointInput) (req *requ // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateVpcEndpoint func (c *EC2) CreateVpcEndpoint(input *CreateVpcEndpointInput) (*CreateVpcEndpointOutput, error) { req, out := c.CreateVpcEndpointRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateVpcEndpointWithContext is the same as CreateVpcEndpoint with the addition of +// the ability to pass a context and additional request options. +// +// See CreateVpcEndpoint 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) CreateVpcEndpointWithContext(ctx aws.Context, input *CreateVpcEndpointInput, opts ...request.Option) (*CreateVpcEndpointOutput, error) { + req, out := c.CreateVpcEndpointRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateVpcPeeringConnection = "CreateVpcPeeringConnection" @@ -3848,8 +4751,8 @@ func (c *EC2) CreateVpcPeeringConnectionRequest(input *CreateVpcPeeringConnectio // peering connection. The VPC peering connection request expires after 7 days, // after which it cannot be accepted or rejected. // -// A CreateVpcPeeringConnection request between VPCs with overlapping CIDR blocks -// results in the VPC peering connection having a status of failed. +// If you try to create a VPC peering connection between VPCs that have overlapping +// CIDR blocks, the VPC peering connection status goes to failed. // // 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 @@ -3860,8 +4763,23 @@ func (c *EC2) CreateVpcPeeringConnectionRequest(input *CreateVpcPeeringConnectio // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateVpcPeeringConnection func (c *EC2) CreateVpcPeeringConnection(input *CreateVpcPeeringConnectionInput) (*CreateVpcPeeringConnectionOutput, error) { req, out := c.CreateVpcPeeringConnectionRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateVpcPeeringConnectionWithContext is the same as CreateVpcPeeringConnection with the addition of +// the ability to pass a context and additional request options. +// +// See CreateVpcPeeringConnection 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) CreateVpcPeeringConnectionWithContext(ctx aws.Context, input *CreateVpcPeeringConnectionInput, opts ...request.Option) (*CreateVpcPeeringConnectionOutput, error) { + req, out := c.CreateVpcPeeringConnectionRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateVpnConnection = "CreateVpnConnection" @@ -3939,8 +4857,23 @@ func (c *EC2) CreateVpnConnectionRequest(input *CreateVpnConnectionInput) (req * // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateVpnConnection func (c *EC2) CreateVpnConnection(input *CreateVpnConnectionInput) (*CreateVpnConnectionOutput, error) { req, out := c.CreateVpnConnectionRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateVpnConnectionWithContext is the same as CreateVpnConnection with the addition of +// the ability to pass a context and additional request options. +// +// See CreateVpnConnection 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) CreateVpnConnectionWithContext(ctx aws.Context, input *CreateVpnConnectionInput, opts ...request.Option) (*CreateVpnConnectionOutput, error) { + req, out := c.CreateVpnConnectionRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateVpnConnectionRoute = "CreateVpnConnectionRoute" @@ -4008,8 +4941,23 @@ func (c *EC2) CreateVpnConnectionRouteRequest(input *CreateVpnConnectionRouteInp // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateVpnConnectionRoute func (c *EC2) CreateVpnConnectionRoute(input *CreateVpnConnectionRouteInput) (*CreateVpnConnectionRouteOutput, error) { req, out := c.CreateVpnConnectionRouteRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateVpnConnectionRouteWithContext is the same as CreateVpnConnectionRoute with the addition of +// the ability to pass a context and additional request options. +// +// See CreateVpnConnectionRoute 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) CreateVpnConnectionRouteWithContext(ctx aws.Context, input *CreateVpnConnectionRouteInput, opts ...request.Option) (*CreateVpnConnectionRouteOutput, error) { + req, out := c.CreateVpnConnectionRouteRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateVpnGateway = "CreateVpnGateway" @@ -4074,8 +5022,23 @@ func (c *EC2) CreateVpnGatewayRequest(input *CreateVpnGatewayInput) (req *reques // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateVpnGateway func (c *EC2) CreateVpnGateway(input *CreateVpnGatewayInput) (*CreateVpnGatewayOutput, error) { req, out := c.CreateVpnGatewayRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateVpnGatewayWithContext is the same as CreateVpnGateway with the addition of +// the ability to pass a context and additional request options. +// +// See CreateVpnGateway 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) CreateVpnGatewayWithContext(ctx aws.Context, input *CreateVpnGatewayInput, opts ...request.Option) (*CreateVpnGatewayOutput, error) { + req, out := c.CreateVpnGatewayRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteCustomerGateway = "DeleteCustomerGateway" @@ -4137,8 +5100,23 @@ func (c *EC2) DeleteCustomerGatewayRequest(input *DeleteCustomerGatewayInput) (r // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeleteCustomerGateway func (c *EC2) DeleteCustomerGateway(input *DeleteCustomerGatewayInput) (*DeleteCustomerGatewayOutput, error) { req, out := c.DeleteCustomerGatewayRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteCustomerGatewayWithContext is the same as DeleteCustomerGateway with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteCustomerGateway 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) DeleteCustomerGatewayWithContext(ctx aws.Context, input *DeleteCustomerGatewayInput, opts ...request.Option) (*DeleteCustomerGatewayOutput, error) { + req, out := c.DeleteCustomerGatewayRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteDhcpOptions = "DeleteDhcpOptions" @@ -4202,8 +5180,23 @@ func (c *EC2) DeleteDhcpOptionsRequest(input *DeleteDhcpOptionsInput) (req *requ // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeleteDhcpOptions func (c *EC2) DeleteDhcpOptions(input *DeleteDhcpOptionsInput) (*DeleteDhcpOptionsOutput, error) { req, out := c.DeleteDhcpOptionsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteDhcpOptionsWithContext is the same as DeleteDhcpOptions with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteDhcpOptions 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) DeleteDhcpOptionsWithContext(ctx aws.Context, input *DeleteDhcpOptionsInput, opts ...request.Option) (*DeleteDhcpOptionsOutput, error) { + req, out := c.DeleteDhcpOptionsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteEgressOnlyInternetGateway = "DeleteEgressOnlyInternetGateway" @@ -4262,8 +5255,23 @@ func (c *EC2) DeleteEgressOnlyInternetGatewayRequest(input *DeleteEgressOnlyInte // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeleteEgressOnlyInternetGateway func (c *EC2) DeleteEgressOnlyInternetGateway(input *DeleteEgressOnlyInternetGatewayInput) (*DeleteEgressOnlyInternetGatewayOutput, error) { req, out := c.DeleteEgressOnlyInternetGatewayRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteEgressOnlyInternetGatewayWithContext is the same as DeleteEgressOnlyInternetGateway with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteEgressOnlyInternetGateway 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) DeleteEgressOnlyInternetGatewayWithContext(ctx aws.Context, input *DeleteEgressOnlyInternetGatewayInput, opts ...request.Option) (*DeleteEgressOnlyInternetGatewayOutput, error) { + req, out := c.DeleteEgressOnlyInternetGatewayRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteFlowLogs = "DeleteFlowLogs" @@ -4322,8 +5330,23 @@ func (c *EC2) DeleteFlowLogsRequest(input *DeleteFlowLogsInput) (req *request.Re // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeleteFlowLogs func (c *EC2) DeleteFlowLogs(input *DeleteFlowLogsInput) (*DeleteFlowLogsOutput, error) { req, out := c.DeleteFlowLogsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteFlowLogsWithContext is the same as DeleteFlowLogs with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteFlowLogs 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) DeleteFlowLogsWithContext(ctx aws.Context, input *DeleteFlowLogsInput, opts ...request.Option) (*DeleteFlowLogsOutput, error) { + req, out := c.DeleteFlowLogsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteInternetGateway = "DeleteInternetGateway" @@ -4385,8 +5408,23 @@ func (c *EC2) DeleteInternetGatewayRequest(input *DeleteInternetGatewayInput) (r // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeleteInternetGateway func (c *EC2) DeleteInternetGateway(input *DeleteInternetGatewayInput) (*DeleteInternetGatewayOutput, error) { req, out := c.DeleteInternetGatewayRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteInternetGatewayWithContext is the same as DeleteInternetGateway with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteInternetGateway 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) DeleteInternetGatewayWithContext(ctx aws.Context, input *DeleteInternetGatewayInput, opts ...request.Option) (*DeleteInternetGatewayOutput, error) { + req, out := c.DeleteInternetGatewayRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteKeyPair = "DeleteKeyPair" @@ -4447,8 +5485,23 @@ func (c *EC2) DeleteKeyPairRequest(input *DeleteKeyPairInput) (req *request.Requ // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeleteKeyPair func (c *EC2) DeleteKeyPair(input *DeleteKeyPairInput) (*DeleteKeyPairOutput, error) { req, out := c.DeleteKeyPairRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteKeyPairWithContext is the same as DeleteKeyPair with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteKeyPair 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) DeleteKeyPairWithContext(ctx aws.Context, input *DeleteKeyPairInput, opts ...request.Option) (*DeleteKeyPairOutput, error) { + req, out := c.DeleteKeyPairRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteNatGateway = "DeleteNatGateway" @@ -4509,8 +5562,23 @@ func (c *EC2) DeleteNatGatewayRequest(input *DeleteNatGatewayInput) (req *reques // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeleteNatGateway func (c *EC2) DeleteNatGateway(input *DeleteNatGatewayInput) (*DeleteNatGatewayOutput, error) { req, out := c.DeleteNatGatewayRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteNatGatewayWithContext is the same as DeleteNatGateway with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteNatGateway 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) DeleteNatGatewayWithContext(ctx aws.Context, input *DeleteNatGatewayInput, opts ...request.Option) (*DeleteNatGatewayOutput, error) { + req, out := c.DeleteNatGatewayRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteNetworkAcl = "DeleteNetworkAcl" @@ -4572,8 +5640,23 @@ func (c *EC2) DeleteNetworkAclRequest(input *DeleteNetworkAclInput) (req *reques // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeleteNetworkAcl func (c *EC2) DeleteNetworkAcl(input *DeleteNetworkAclInput) (*DeleteNetworkAclOutput, error) { req, out := c.DeleteNetworkAclRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteNetworkAclWithContext is the same as DeleteNetworkAcl with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteNetworkAcl 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) DeleteNetworkAclWithContext(ctx aws.Context, input *DeleteNetworkAclInput, opts ...request.Option) (*DeleteNetworkAclOutput, error) { + req, out := c.DeleteNetworkAclRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteNetworkAclEntry = "DeleteNetworkAclEntry" @@ -4635,8 +5718,23 @@ func (c *EC2) DeleteNetworkAclEntryRequest(input *DeleteNetworkAclEntryInput) (r // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeleteNetworkAclEntry func (c *EC2) DeleteNetworkAclEntry(input *DeleteNetworkAclEntryInput) (*DeleteNetworkAclEntryOutput, error) { req, out := c.DeleteNetworkAclEntryRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteNetworkAclEntryWithContext is the same as DeleteNetworkAclEntry with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteNetworkAclEntry 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) DeleteNetworkAclEntryWithContext(ctx aws.Context, input *DeleteNetworkAclEntryInput, opts ...request.Option) (*DeleteNetworkAclEntryOutput, error) { + req, out := c.DeleteNetworkAclEntryRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteNetworkInterface = "DeleteNetworkInterface" @@ -4698,8 +5796,23 @@ func (c *EC2) DeleteNetworkInterfaceRequest(input *DeleteNetworkInterfaceInput) // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeleteNetworkInterface func (c *EC2) DeleteNetworkInterface(input *DeleteNetworkInterfaceInput) (*DeleteNetworkInterfaceOutput, error) { req, out := c.DeleteNetworkInterfaceRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteNetworkInterfaceWithContext is the same as DeleteNetworkInterface with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteNetworkInterface 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) DeleteNetworkInterfaceWithContext(ctx aws.Context, input *DeleteNetworkInterfaceInput, opts ...request.Option) (*DeleteNetworkInterfaceOutput, error) { + req, out := c.DeleteNetworkInterfaceRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeletePlacementGroup = "DeletePlacementGroup" @@ -4763,8 +5876,23 @@ func (c *EC2) DeletePlacementGroupRequest(input *DeletePlacementGroupInput) (req // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeletePlacementGroup func (c *EC2) DeletePlacementGroup(input *DeletePlacementGroupInput) (*DeletePlacementGroupOutput, error) { req, out := c.DeletePlacementGroupRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeletePlacementGroupWithContext is the same as DeletePlacementGroup with the addition of +// the ability to pass a context and additional request options. +// +// See DeletePlacementGroup 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) DeletePlacementGroupWithContext(ctx aws.Context, input *DeletePlacementGroupInput, opts ...request.Option) (*DeletePlacementGroupOutput, error) { + req, out := c.DeletePlacementGroupRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteRoute = "DeleteRoute" @@ -4825,8 +5953,23 @@ func (c *EC2) DeleteRouteRequest(input *DeleteRouteInput) (req *request.Request, // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeleteRoute func (c *EC2) DeleteRoute(input *DeleteRouteInput) (*DeleteRouteOutput, error) { req, out := c.DeleteRouteRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteRouteWithContext is the same as DeleteRoute with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteRoute 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) DeleteRouteWithContext(ctx aws.Context, input *DeleteRouteInput, opts ...request.Option) (*DeleteRouteOutput, error) { + req, out := c.DeleteRouteRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteRouteTable = "DeleteRouteTable" @@ -4889,8 +6032,23 @@ func (c *EC2) DeleteRouteTableRequest(input *DeleteRouteTableInput) (req *reques // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeleteRouteTable func (c *EC2) DeleteRouteTable(input *DeleteRouteTableInput) (*DeleteRouteTableOutput, error) { req, out := c.DeleteRouteTableRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteRouteTableWithContext is the same as DeleteRouteTable with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteRouteTable 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) DeleteRouteTableWithContext(ctx aws.Context, input *DeleteRouteTableInput, opts ...request.Option) (*DeleteRouteTableOutput, error) { + req, out := c.DeleteRouteTableRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteSecurityGroup = "DeleteSecurityGroup" @@ -4955,8 +6113,23 @@ func (c *EC2) DeleteSecurityGroupRequest(input *DeleteSecurityGroupInput) (req * // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeleteSecurityGroup func (c *EC2) DeleteSecurityGroup(input *DeleteSecurityGroupInput) (*DeleteSecurityGroupOutput, error) { req, out := c.DeleteSecurityGroupRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteSecurityGroupWithContext is the same as DeleteSecurityGroup with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteSecurityGroup 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) DeleteSecurityGroupWithContext(ctx aws.Context, input *DeleteSecurityGroupInput, opts ...request.Option) (*DeleteSecurityGroupOutput, error) { + req, out := c.DeleteSecurityGroupRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteSnapshot = "DeleteSnapshot" @@ -5031,8 +6204,23 @@ func (c *EC2) DeleteSnapshotRequest(input *DeleteSnapshotInput) (req *request.Re // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeleteSnapshot func (c *EC2) DeleteSnapshot(input *DeleteSnapshotInput) (*DeleteSnapshotOutput, error) { req, out := c.DeleteSnapshotRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteSnapshotWithContext is the same as DeleteSnapshot with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteSnapshot 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) DeleteSnapshotWithContext(ctx aws.Context, input *DeleteSnapshotInput, opts ...request.Option) (*DeleteSnapshotOutput, error) { + req, out := c.DeleteSnapshotRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteSpotDatafeedSubscription = "DeleteSpotDatafeedSubscription" @@ -5093,8 +6281,23 @@ func (c *EC2) DeleteSpotDatafeedSubscriptionRequest(input *DeleteSpotDatafeedSub // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeleteSpotDatafeedSubscription func (c *EC2) DeleteSpotDatafeedSubscription(input *DeleteSpotDatafeedSubscriptionInput) (*DeleteSpotDatafeedSubscriptionOutput, error) { req, out := c.DeleteSpotDatafeedSubscriptionRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteSpotDatafeedSubscriptionWithContext is the same as DeleteSpotDatafeedSubscription with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteSpotDatafeedSubscription 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) DeleteSpotDatafeedSubscriptionWithContext(ctx aws.Context, input *DeleteSpotDatafeedSubscriptionInput, opts ...request.Option) (*DeleteSpotDatafeedSubscriptionOutput, error) { + req, out := c.DeleteSpotDatafeedSubscriptionRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteSubnet = "DeleteSubnet" @@ -5156,8 +6359,23 @@ func (c *EC2) DeleteSubnetRequest(input *DeleteSubnetInput) (req *request.Reques // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeleteSubnet func (c *EC2) DeleteSubnet(input *DeleteSubnetInput) (*DeleteSubnetOutput, error) { req, out := c.DeleteSubnetRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteSubnetWithContext is the same as DeleteSubnet with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteSubnet 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) DeleteSubnetWithContext(ctx aws.Context, input *DeleteSubnetInput, opts ...request.Option) (*DeleteSubnetOutput, error) { + req, out := c.DeleteSubnetRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteTags = "DeleteTags" @@ -5222,8 +6440,23 @@ func (c *EC2) DeleteTagsRequest(input *DeleteTagsInput) (req *request.Request, o // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeleteTags func (c *EC2) DeleteTags(input *DeleteTagsInput) (*DeleteTagsOutput, error) { req, out := c.DeleteTagsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteTagsWithContext is the same as DeleteTags with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteTags 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) DeleteTagsWithContext(ctx aws.Context, input *DeleteTagsInput, opts ...request.Option) (*DeleteTagsOutput, error) { + req, out := c.DeleteTagsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteVolume = "DeleteVolume" @@ -5290,8 +6523,23 @@ func (c *EC2) DeleteVolumeRequest(input *DeleteVolumeInput) (req *request.Reques // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeleteVolume func (c *EC2) DeleteVolume(input *DeleteVolumeInput) (*DeleteVolumeOutput, error) { req, out := c.DeleteVolumeRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteVolumeWithContext is the same as DeleteVolume with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteVolume 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) DeleteVolumeWithContext(ctx aws.Context, input *DeleteVolumeInput, opts ...request.Option) (*DeleteVolumeOutput, error) { + req, out := c.DeleteVolumeRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteVpc = "DeleteVpc" @@ -5356,8 +6604,23 @@ func (c *EC2) DeleteVpcRequest(input *DeleteVpcInput) (req *request.Request, out // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeleteVpc func (c *EC2) DeleteVpc(input *DeleteVpcInput) (*DeleteVpcOutput, error) { req, out := c.DeleteVpcRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteVpcWithContext is the same as DeleteVpc with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteVpc 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) DeleteVpcWithContext(ctx aws.Context, input *DeleteVpcInput, opts ...request.Option) (*DeleteVpcOutput, error) { + req, out := c.DeleteVpcRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteVpcEndpoints = "DeleteVpcEndpoints" @@ -5417,8 +6680,23 @@ func (c *EC2) DeleteVpcEndpointsRequest(input *DeleteVpcEndpointsInput) (req *re // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeleteVpcEndpoints func (c *EC2) DeleteVpcEndpoints(input *DeleteVpcEndpointsInput) (*DeleteVpcEndpointsOutput, error) { req, out := c.DeleteVpcEndpointsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteVpcEndpointsWithContext is the same as DeleteVpcEndpoints with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteVpcEndpoints 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) DeleteVpcEndpointsWithContext(ctx aws.Context, input *DeleteVpcEndpointsInput, opts ...request.Option) (*DeleteVpcEndpointsOutput, error) { + req, out := c.DeleteVpcEndpointsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteVpcPeeringConnection = "DeleteVpcPeeringConnection" @@ -5480,8 +6758,23 @@ func (c *EC2) DeleteVpcPeeringConnectionRequest(input *DeleteVpcPeeringConnectio // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeleteVpcPeeringConnection func (c *EC2) DeleteVpcPeeringConnection(input *DeleteVpcPeeringConnectionInput) (*DeleteVpcPeeringConnectionOutput, error) { req, out := c.DeleteVpcPeeringConnectionRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteVpcPeeringConnectionWithContext is the same as DeleteVpcPeeringConnection with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteVpcPeeringConnection 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) DeleteVpcPeeringConnectionWithContext(ctx aws.Context, input *DeleteVpcPeeringConnectionInput, opts ...request.Option) (*DeleteVpcPeeringConnectionOutput, error) { + req, out := c.DeleteVpcPeeringConnectionRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteVpnConnection = "DeleteVpnConnection" @@ -5551,8 +6844,23 @@ func (c *EC2) DeleteVpnConnectionRequest(input *DeleteVpnConnectionInput) (req * // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeleteVpnConnection func (c *EC2) DeleteVpnConnection(input *DeleteVpnConnectionInput) (*DeleteVpnConnectionOutput, error) { req, out := c.DeleteVpnConnectionRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteVpnConnectionWithContext is the same as DeleteVpnConnection with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteVpnConnection 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) DeleteVpnConnectionWithContext(ctx aws.Context, input *DeleteVpnConnectionInput, opts ...request.Option) (*DeleteVpnConnectionOutput, error) { + req, out := c.DeleteVpnConnectionRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteVpnConnectionRoute = "DeleteVpnConnectionRoute" @@ -5616,8 +6924,23 @@ func (c *EC2) DeleteVpnConnectionRouteRequest(input *DeleteVpnConnectionRouteInp // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeleteVpnConnectionRoute func (c *EC2) DeleteVpnConnectionRoute(input *DeleteVpnConnectionRouteInput) (*DeleteVpnConnectionRouteOutput, error) { req, out := c.DeleteVpnConnectionRouteRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteVpnConnectionRouteWithContext is the same as DeleteVpnConnectionRoute with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteVpnConnectionRoute 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) DeleteVpnConnectionRouteWithContext(ctx aws.Context, input *DeleteVpnConnectionRouteInput, opts ...request.Option) (*DeleteVpnConnectionRouteOutput, error) { + req, out := c.DeleteVpnConnectionRouteRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteVpnGateway = "DeleteVpnGateway" @@ -5682,8 +7005,23 @@ func (c *EC2) DeleteVpnGatewayRequest(input *DeleteVpnGatewayInput) (req *reques // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeleteVpnGateway func (c *EC2) DeleteVpnGateway(input *DeleteVpnGatewayInput) (*DeleteVpnGatewayOutput, error) { req, out := c.DeleteVpnGatewayRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteVpnGatewayWithContext is the same as DeleteVpnGateway with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteVpnGateway 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) DeleteVpnGatewayWithContext(ctx aws.Context, input *DeleteVpnGatewayInput, opts ...request.Option) (*DeleteVpnGatewayOutput, error) { + req, out := c.DeleteVpnGatewayRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeregisterImage = "DeregisterImage" @@ -5747,8 +7085,23 @@ func (c *EC2) DeregisterImageRequest(input *DeregisterImageInput) (req *request. // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeregisterImage func (c *EC2) DeregisterImage(input *DeregisterImageInput) (*DeregisterImageOutput, error) { req, out := c.DeregisterImageRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeregisterImageWithContext is the same as DeregisterImage with the addition of +// the ability to pass a context and additional request options. +// +// See DeregisterImage 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) DeregisterImageWithContext(ctx aws.Context, input *DeregisterImageInput, opts ...request.Option) (*DeregisterImageOutput, error) { + req, out := c.DeregisterImageRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeAccountAttributes = "DescribeAccountAttributes" @@ -5825,8 +7178,23 @@ func (c *EC2) DescribeAccountAttributesRequest(input *DescribeAccountAttributesI // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeAccountAttributes func (c *EC2) DescribeAccountAttributes(input *DescribeAccountAttributesInput) (*DescribeAccountAttributesOutput, error) { req, out := c.DescribeAccountAttributesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeAccountAttributesWithContext is the same as DescribeAccountAttributes with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeAccountAttributes 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) DescribeAccountAttributesWithContext(ctx aws.Context, input *DescribeAccountAttributesInput, opts ...request.Option) (*DescribeAccountAttributesOutput, error) { + req, out := c.DescribeAccountAttributesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeAddresses = "DescribeAddresses" @@ -5889,8 +7257,23 @@ func (c *EC2) DescribeAddressesRequest(input *DescribeAddressesInput) (req *requ // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeAddresses func (c *EC2) DescribeAddresses(input *DescribeAddressesInput) (*DescribeAddressesOutput, error) { req, out := c.DescribeAddressesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeAddressesWithContext is the same as DescribeAddresses with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeAddresses 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) DescribeAddressesWithContext(ctx aws.Context, input *DescribeAddressesInput, opts ...request.Option) (*DescribeAddressesOutput, error) { + req, out := c.DescribeAddressesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeAvailabilityZones = "DescribeAvailabilityZones" @@ -5955,8 +7338,23 @@ func (c *EC2) DescribeAvailabilityZonesRequest(input *DescribeAvailabilityZonesI // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeAvailabilityZones func (c *EC2) DescribeAvailabilityZones(input *DescribeAvailabilityZonesInput) (*DescribeAvailabilityZonesOutput, error) { req, out := c.DescribeAvailabilityZonesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeAvailabilityZonesWithContext is the same as DescribeAvailabilityZones with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeAvailabilityZones 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) DescribeAvailabilityZonesWithContext(ctx aws.Context, input *DescribeAvailabilityZonesInput, opts ...request.Option) (*DescribeAvailabilityZonesOutput, error) { + req, out := c.DescribeAvailabilityZonesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeBundleTasks = "DescribeBundleTasks" @@ -6020,8 +7418,23 @@ func (c *EC2) DescribeBundleTasksRequest(input *DescribeBundleTasksInput) (req * // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeBundleTasks func (c *EC2) DescribeBundleTasks(input *DescribeBundleTasksInput) (*DescribeBundleTasksOutput, error) { req, out := c.DescribeBundleTasksRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeBundleTasksWithContext is the same as DescribeBundleTasks with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeBundleTasks 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) DescribeBundleTasksWithContext(ctx aws.Context, input *DescribeBundleTasksInput, opts ...request.Option) (*DescribeBundleTasksOutput, error) { + req, out := c.DescribeBundleTasksRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeClassicLinkInstances = "DescribeClassicLinkInstances" @@ -6083,8 +7496,23 @@ func (c *EC2) DescribeClassicLinkInstancesRequest(input *DescribeClassicLinkInst // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeClassicLinkInstances func (c *EC2) DescribeClassicLinkInstances(input *DescribeClassicLinkInstancesInput) (*DescribeClassicLinkInstancesOutput, error) { req, out := c.DescribeClassicLinkInstancesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeClassicLinkInstancesWithContext is the same as DescribeClassicLinkInstances with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeClassicLinkInstances 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) DescribeClassicLinkInstancesWithContext(ctx aws.Context, input *DescribeClassicLinkInstancesInput, opts ...request.Option) (*DescribeClassicLinkInstancesOutput, error) { + req, out := c.DescribeClassicLinkInstancesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeConversionTasks = "DescribeConversionTasks" @@ -6147,8 +7575,23 @@ func (c *EC2) DescribeConversionTasksRequest(input *DescribeConversionTasksInput // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeConversionTasks func (c *EC2) DescribeConversionTasks(input *DescribeConversionTasksInput) (*DescribeConversionTasksOutput, error) { req, out := c.DescribeConversionTasksRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeConversionTasksWithContext is the same as DescribeConversionTasks with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeConversionTasks 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) DescribeConversionTasksWithContext(ctx aws.Context, input *DescribeConversionTasksInput, opts ...request.Option) (*DescribeConversionTasksOutput, error) { + req, out := c.DescribeConversionTasksRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeCustomerGateways = "DescribeCustomerGateways" @@ -6211,8 +7654,23 @@ func (c *EC2) DescribeCustomerGatewaysRequest(input *DescribeCustomerGatewaysInp // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeCustomerGateways func (c *EC2) DescribeCustomerGateways(input *DescribeCustomerGatewaysInput) (*DescribeCustomerGatewaysOutput, error) { req, out := c.DescribeCustomerGatewaysRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeCustomerGatewaysWithContext is the same as DescribeCustomerGateways with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeCustomerGateways 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) DescribeCustomerGatewaysWithContext(ctx aws.Context, input *DescribeCustomerGatewaysInput, opts ...request.Option) (*DescribeCustomerGatewaysOutput, error) { + req, out := c.DescribeCustomerGatewaysRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeDhcpOptions = "DescribeDhcpOptions" @@ -6274,8 +7732,23 @@ func (c *EC2) DescribeDhcpOptionsRequest(input *DescribeDhcpOptionsInput) (req * // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeDhcpOptions func (c *EC2) DescribeDhcpOptions(input *DescribeDhcpOptionsInput) (*DescribeDhcpOptionsOutput, error) { req, out := c.DescribeDhcpOptionsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeDhcpOptionsWithContext is the same as DescribeDhcpOptions with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeDhcpOptions 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) DescribeDhcpOptionsWithContext(ctx aws.Context, input *DescribeDhcpOptionsInput, opts ...request.Option) (*DescribeDhcpOptionsOutput, error) { + req, out := c.DescribeDhcpOptionsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeEgressOnlyInternetGateways = "DescribeEgressOnlyInternetGateways" @@ -6334,8 +7807,23 @@ func (c *EC2) DescribeEgressOnlyInternetGatewaysRequest(input *DescribeEgressOnl // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeEgressOnlyInternetGateways func (c *EC2) DescribeEgressOnlyInternetGateways(input *DescribeEgressOnlyInternetGatewaysInput) (*DescribeEgressOnlyInternetGatewaysOutput, error) { req, out := c.DescribeEgressOnlyInternetGatewaysRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeEgressOnlyInternetGatewaysWithContext is the same as DescribeEgressOnlyInternetGateways with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeEgressOnlyInternetGateways 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) DescribeEgressOnlyInternetGatewaysWithContext(ctx aws.Context, input *DescribeEgressOnlyInternetGatewaysInput, opts ...request.Option) (*DescribeEgressOnlyInternetGatewaysOutput, error) { + req, out := c.DescribeEgressOnlyInternetGatewaysRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeExportTasks = "DescribeExportTasks" @@ -6394,8 +7882,23 @@ func (c *EC2) DescribeExportTasksRequest(input *DescribeExportTasksInput) (req * // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeExportTasks func (c *EC2) DescribeExportTasks(input *DescribeExportTasksInput) (*DescribeExportTasksOutput, error) { req, out := c.DescribeExportTasksRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeExportTasksWithContext is the same as DescribeExportTasks with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeExportTasks 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) DescribeExportTasksWithContext(ctx aws.Context, input *DescribeExportTasksInput, opts ...request.Option) (*DescribeExportTasksOutput, error) { + req, out := c.DescribeExportTasksRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeFlowLogs = "DescribeFlowLogs" @@ -6456,8 +7959,23 @@ func (c *EC2) DescribeFlowLogsRequest(input *DescribeFlowLogsInput) (req *reques // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeFlowLogs func (c *EC2) DescribeFlowLogs(input *DescribeFlowLogsInput) (*DescribeFlowLogsOutput, error) { req, out := c.DescribeFlowLogsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeFlowLogsWithContext is the same as DescribeFlowLogs with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeFlowLogs 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) DescribeFlowLogsWithContext(ctx aws.Context, input *DescribeFlowLogsInput, opts ...request.Option) (*DescribeFlowLogsOutput, error) { + req, out := c.DescribeFlowLogsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeHostReservationOfferings = "DescribeHostReservationOfferings" @@ -6524,8 +8042,23 @@ func (c *EC2) DescribeHostReservationOfferingsRequest(input *DescribeHostReserva // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeHostReservationOfferings func (c *EC2) DescribeHostReservationOfferings(input *DescribeHostReservationOfferingsInput) (*DescribeHostReservationOfferingsOutput, error) { req, out := c.DescribeHostReservationOfferingsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeHostReservationOfferingsWithContext is the same as DescribeHostReservationOfferings with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeHostReservationOfferings 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) DescribeHostReservationOfferingsWithContext(ctx aws.Context, input *DescribeHostReservationOfferingsInput, opts ...request.Option) (*DescribeHostReservationOfferingsOutput, error) { + req, out := c.DescribeHostReservationOfferingsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeHostReservations = "DescribeHostReservations" @@ -6585,8 +8118,23 @@ func (c *EC2) DescribeHostReservationsRequest(input *DescribeHostReservationsInp // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeHostReservations func (c *EC2) DescribeHostReservations(input *DescribeHostReservationsInput) (*DescribeHostReservationsOutput, error) { req, out := c.DescribeHostReservationsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeHostReservationsWithContext is the same as DescribeHostReservations with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeHostReservations 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) DescribeHostReservationsWithContext(ctx aws.Context, input *DescribeHostReservationsInput, opts ...request.Option) (*DescribeHostReservationsOutput, error) { + req, out := c.DescribeHostReservationsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeHosts = "DescribeHosts" @@ -6649,8 +8197,23 @@ func (c *EC2) DescribeHostsRequest(input *DescribeHostsInput) (req *request.Requ // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeHosts func (c *EC2) DescribeHosts(input *DescribeHostsInput) (*DescribeHostsOutput, error) { req, out := c.DescribeHostsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeHostsWithContext is the same as DescribeHosts with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeHosts 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) DescribeHostsWithContext(ctx aws.Context, input *DescribeHostsInput, opts ...request.Option) (*DescribeHostsOutput, error) { + req, out := c.DescribeHostsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeIamInstanceProfileAssociations = "DescribeIamInstanceProfileAssociations" @@ -6709,8 +8272,23 @@ func (c *EC2) DescribeIamInstanceProfileAssociationsRequest(input *DescribeIamIn // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeIamInstanceProfileAssociations func (c *EC2) DescribeIamInstanceProfileAssociations(input *DescribeIamInstanceProfileAssociationsInput) (*DescribeIamInstanceProfileAssociationsOutput, error) { req, out := c.DescribeIamInstanceProfileAssociationsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeIamInstanceProfileAssociationsWithContext is the same as DescribeIamInstanceProfileAssociations with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeIamInstanceProfileAssociations 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) DescribeIamInstanceProfileAssociationsWithContext(ctx aws.Context, input *DescribeIamInstanceProfileAssociationsInput, opts ...request.Option) (*DescribeIamInstanceProfileAssociationsOutput, error) { + req, out := c.DescribeIamInstanceProfileAssociationsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeIdFormat = "DescribeIdFormat" @@ -6782,8 +8360,23 @@ func (c *EC2) DescribeIdFormatRequest(input *DescribeIdFormatInput) (req *reques // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeIdFormat func (c *EC2) DescribeIdFormat(input *DescribeIdFormatInput) (*DescribeIdFormatOutput, error) { req, out := c.DescribeIdFormatRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeIdFormatWithContext is the same as DescribeIdFormat with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeIdFormat 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) DescribeIdFormatWithContext(ctx aws.Context, input *DescribeIdFormatInput, opts ...request.Option) (*DescribeIdFormatOutput, error) { + req, out := c.DescribeIdFormatRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeIdentityIdFormat = "DescribeIdentityIdFormat" @@ -6853,8 +8446,23 @@ func (c *EC2) DescribeIdentityIdFormatRequest(input *DescribeIdentityIdFormatInp // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeIdentityIdFormat func (c *EC2) DescribeIdentityIdFormat(input *DescribeIdentityIdFormatInput) (*DescribeIdentityIdFormatOutput, error) { req, out := c.DescribeIdentityIdFormatRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeIdentityIdFormatWithContext is the same as DescribeIdentityIdFormat with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeIdentityIdFormat 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) DescribeIdentityIdFormatWithContext(ctx aws.Context, input *DescribeIdentityIdFormatInput, opts ...request.Option) (*DescribeIdentityIdFormatOutput, error) { + req, out := c.DescribeIdentityIdFormatRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeImageAttribute = "DescribeImageAttribute" @@ -6914,8 +8522,23 @@ func (c *EC2) DescribeImageAttributeRequest(input *DescribeImageAttributeInput) // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeImageAttribute func (c *EC2) DescribeImageAttribute(input *DescribeImageAttributeInput) (*DescribeImageAttributeOutput, error) { req, out := c.DescribeImageAttributeRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeImageAttributeWithContext is the same as DescribeImageAttribute with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeImageAttribute 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) DescribeImageAttributeWithContext(ctx aws.Context, input *DescribeImageAttributeInput, opts ...request.Option) (*DescribeImageAttributeOutput, error) { + req, out := c.DescribeImageAttributeRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeImages = "DescribeImages" @@ -6980,8 +8603,23 @@ func (c *EC2) DescribeImagesRequest(input *DescribeImagesInput) (req *request.Re // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeImages func (c *EC2) DescribeImages(input *DescribeImagesInput) (*DescribeImagesOutput, error) { req, out := c.DescribeImagesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeImagesWithContext is the same as DescribeImages with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeImages 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) DescribeImagesWithContext(ctx aws.Context, input *DescribeImagesInput, opts ...request.Option) (*DescribeImagesOutput, error) { + req, out := c.DescribeImagesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeImportImageTasks = "DescribeImportImageTasks" @@ -7041,8 +8679,23 @@ func (c *EC2) DescribeImportImageTasksRequest(input *DescribeImportImageTasksInp // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeImportImageTasks func (c *EC2) DescribeImportImageTasks(input *DescribeImportImageTasksInput) (*DescribeImportImageTasksOutput, error) { req, out := c.DescribeImportImageTasksRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeImportImageTasksWithContext is the same as DescribeImportImageTasks with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeImportImageTasks 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) DescribeImportImageTasksWithContext(ctx aws.Context, input *DescribeImportImageTasksInput, opts ...request.Option) (*DescribeImportImageTasksOutput, error) { + req, out := c.DescribeImportImageTasksRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeImportSnapshotTasks = "DescribeImportSnapshotTasks" @@ -7101,8 +8754,23 @@ func (c *EC2) DescribeImportSnapshotTasksRequest(input *DescribeImportSnapshotTa // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeImportSnapshotTasks func (c *EC2) DescribeImportSnapshotTasks(input *DescribeImportSnapshotTasksInput) (*DescribeImportSnapshotTasksOutput, error) { req, out := c.DescribeImportSnapshotTasksRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeImportSnapshotTasksWithContext is the same as DescribeImportSnapshotTasks with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeImportSnapshotTasks 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) DescribeImportSnapshotTasksWithContext(ctx aws.Context, input *DescribeImportSnapshotTasksInput, opts ...request.Option) (*DescribeImportSnapshotTasksOutput, error) { + req, out := c.DescribeImportSnapshotTasksRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeInstanceAttribute = "DescribeInstanceAttribute" @@ -7165,8 +8833,23 @@ func (c *EC2) DescribeInstanceAttributeRequest(input *DescribeInstanceAttributeI // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeInstanceAttribute func (c *EC2) DescribeInstanceAttribute(input *DescribeInstanceAttributeInput) (*DescribeInstanceAttributeOutput, error) { req, out := c.DescribeInstanceAttributeRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeInstanceAttributeWithContext is the same as DescribeInstanceAttribute with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeInstanceAttribute 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) DescribeInstanceAttributeWithContext(ctx aws.Context, input *DescribeInstanceAttributeInput, opts ...request.Option) (*DescribeInstanceAttributeOutput, error) { + req, out := c.DescribeInstanceAttributeRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeInstanceStatus = "DescribeInstanceStatus" @@ -7251,8 +8934,23 @@ func (c *EC2) DescribeInstanceStatusRequest(input *DescribeInstanceStatusInput) // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeInstanceStatus func (c *EC2) DescribeInstanceStatus(input *DescribeInstanceStatusInput) (*DescribeInstanceStatusOutput, error) { req, out := c.DescribeInstanceStatusRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeInstanceStatusWithContext is the same as DescribeInstanceStatus with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeInstanceStatus 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) DescribeInstanceStatusWithContext(ctx aws.Context, input *DescribeInstanceStatusInput, opts ...request.Option) (*DescribeInstanceStatusOutput, error) { + req, out := c.DescribeInstanceStatusRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // DescribeInstanceStatusPages iterates over the pages of a DescribeInstanceStatus operation, @@ -7272,12 +8970,37 @@ func (c *EC2) DescribeInstanceStatus(input *DescribeInstanceStatusInput) (*Descr // return pageNum <= 3 // }) // -func (c *EC2) DescribeInstanceStatusPages(input *DescribeInstanceStatusInput, fn func(p *DescribeInstanceStatusOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.DescribeInstanceStatusRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*DescribeInstanceStatusOutput), lastPage) - }) +func (c *EC2) DescribeInstanceStatusPages(input *DescribeInstanceStatusInput, fn func(*DescribeInstanceStatusOutput, bool) bool) error { + return c.DescribeInstanceStatusPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// DescribeInstanceStatusPagesWithContext same as DescribeInstanceStatusPages 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) DescribeInstanceStatusPagesWithContext(ctx aws.Context, input *DescribeInstanceStatusInput, fn func(*DescribeInstanceStatusOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *DescribeInstanceStatusInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeInstanceStatusRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*DescribeInstanceStatusOutput), !p.HasNextPage()) + } + return p.Err() } const opDescribeInstances = "DescribeInstances" @@ -7357,8 +9080,23 @@ func (c *EC2) DescribeInstancesRequest(input *DescribeInstancesInput) (req *requ // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeInstances func (c *EC2) DescribeInstances(input *DescribeInstancesInput) (*DescribeInstancesOutput, error) { req, out := c.DescribeInstancesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeInstancesWithContext is the same as DescribeInstances with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeInstances 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) DescribeInstancesWithContext(ctx aws.Context, input *DescribeInstancesInput, opts ...request.Option) (*DescribeInstancesOutput, error) { + req, out := c.DescribeInstancesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // DescribeInstancesPages iterates over the pages of a DescribeInstances operation, @@ -7378,12 +9116,37 @@ func (c *EC2) DescribeInstances(input *DescribeInstancesInput) (*DescribeInstanc // return pageNum <= 3 // }) // -func (c *EC2) DescribeInstancesPages(input *DescribeInstancesInput, fn func(p *DescribeInstancesOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.DescribeInstancesRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*DescribeInstancesOutput), lastPage) - }) +func (c *EC2) DescribeInstancesPages(input *DescribeInstancesInput, fn func(*DescribeInstancesOutput, bool) bool) error { + return c.DescribeInstancesPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// DescribeInstancesPagesWithContext same as DescribeInstancesPages 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) DescribeInstancesPagesWithContext(ctx aws.Context, input *DescribeInstancesInput, fn func(*DescribeInstancesOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *DescribeInstancesInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeInstancesRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*DescribeInstancesOutput), !p.HasNextPage()) + } + return p.Err() } const opDescribeInternetGateways = "DescribeInternetGateways" @@ -7442,8 +9205,23 @@ func (c *EC2) DescribeInternetGatewaysRequest(input *DescribeInternetGatewaysInp // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeInternetGateways func (c *EC2) DescribeInternetGateways(input *DescribeInternetGatewaysInput) (*DescribeInternetGatewaysOutput, error) { req, out := c.DescribeInternetGatewaysRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeInternetGatewaysWithContext is the same as DescribeInternetGateways with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeInternetGateways 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) DescribeInternetGatewaysWithContext(ctx aws.Context, input *DescribeInternetGatewaysInput, opts ...request.Option) (*DescribeInternetGatewaysOutput, error) { + req, out := c.DescribeInternetGatewaysRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeKeyPairs = "DescribeKeyPairs" @@ -7505,8 +9283,23 @@ func (c *EC2) DescribeKeyPairsRequest(input *DescribeKeyPairsInput) (req *reques // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeKeyPairs func (c *EC2) DescribeKeyPairs(input *DescribeKeyPairsInput) (*DescribeKeyPairsOutput, error) { req, out := c.DescribeKeyPairsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeKeyPairsWithContext is the same as DescribeKeyPairs with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeKeyPairs 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) DescribeKeyPairsWithContext(ctx aws.Context, input *DescribeKeyPairsInput, opts ...request.Option) (*DescribeKeyPairsOutput, error) { + req, out := c.DescribeKeyPairsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeMovingAddresses = "DescribeMovingAddresses" @@ -7567,8 +9360,23 @@ func (c *EC2) DescribeMovingAddressesRequest(input *DescribeMovingAddressesInput // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeMovingAddresses func (c *EC2) DescribeMovingAddresses(input *DescribeMovingAddressesInput) (*DescribeMovingAddressesOutput, error) { req, out := c.DescribeMovingAddressesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeMovingAddressesWithContext is the same as DescribeMovingAddresses with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeMovingAddresses 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) DescribeMovingAddressesWithContext(ctx aws.Context, input *DescribeMovingAddressesInput, opts ...request.Option) (*DescribeMovingAddressesOutput, error) { + req, out := c.DescribeMovingAddressesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeNatGateways = "DescribeNatGateways" @@ -7633,8 +9441,23 @@ func (c *EC2) DescribeNatGatewaysRequest(input *DescribeNatGatewaysInput) (req * // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeNatGateways func (c *EC2) DescribeNatGateways(input *DescribeNatGatewaysInput) (*DescribeNatGatewaysOutput, error) { req, out := c.DescribeNatGatewaysRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeNatGatewaysWithContext is the same as DescribeNatGateways with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeNatGateways 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) DescribeNatGatewaysWithContext(ctx aws.Context, input *DescribeNatGatewaysInput, opts ...request.Option) (*DescribeNatGatewaysOutput, error) { + req, out := c.DescribeNatGatewaysRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // DescribeNatGatewaysPages iterates over the pages of a DescribeNatGateways operation, @@ -7654,12 +9477,37 @@ func (c *EC2) DescribeNatGateways(input *DescribeNatGatewaysInput) (*DescribeNat // return pageNum <= 3 // }) // -func (c *EC2) DescribeNatGatewaysPages(input *DescribeNatGatewaysInput, fn func(p *DescribeNatGatewaysOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.DescribeNatGatewaysRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*DescribeNatGatewaysOutput), lastPage) - }) +func (c *EC2) DescribeNatGatewaysPages(input *DescribeNatGatewaysInput, fn func(*DescribeNatGatewaysOutput, bool) bool) error { + return c.DescribeNatGatewaysPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// DescribeNatGatewaysPagesWithContext same as DescribeNatGatewaysPages 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) DescribeNatGatewaysPagesWithContext(ctx aws.Context, input *DescribeNatGatewaysInput, fn func(*DescribeNatGatewaysOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *DescribeNatGatewaysInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeNatGatewaysRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*DescribeNatGatewaysOutput), !p.HasNextPage()) + } + return p.Err() } const opDescribeNetworkAcls = "DescribeNetworkAcls" @@ -7721,8 +9569,23 @@ func (c *EC2) DescribeNetworkAclsRequest(input *DescribeNetworkAclsInput) (req * // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeNetworkAcls func (c *EC2) DescribeNetworkAcls(input *DescribeNetworkAclsInput) (*DescribeNetworkAclsOutput, error) { req, out := c.DescribeNetworkAclsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeNetworkAclsWithContext is the same as DescribeNetworkAcls with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeNetworkAcls 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) DescribeNetworkAclsWithContext(ctx aws.Context, input *DescribeNetworkAclsInput, opts ...request.Option) (*DescribeNetworkAclsOutput, error) { + req, out := c.DescribeNetworkAclsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeNetworkInterfaceAttribute = "DescribeNetworkInterfaceAttribute" @@ -7782,8 +9645,23 @@ func (c *EC2) DescribeNetworkInterfaceAttributeRequest(input *DescribeNetworkInt // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeNetworkInterfaceAttribute func (c *EC2) DescribeNetworkInterfaceAttribute(input *DescribeNetworkInterfaceAttributeInput) (*DescribeNetworkInterfaceAttributeOutput, error) { req, out := c.DescribeNetworkInterfaceAttributeRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeNetworkInterfaceAttributeWithContext is the same as DescribeNetworkInterfaceAttribute with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeNetworkInterfaceAttribute 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) DescribeNetworkInterfaceAttributeWithContext(ctx aws.Context, input *DescribeNetworkInterfaceAttributeInput, opts ...request.Option) (*DescribeNetworkInterfaceAttributeOutput, error) { + req, out := c.DescribeNetworkInterfaceAttributeRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeNetworkInterfaces = "DescribeNetworkInterfaces" @@ -7842,8 +9720,23 @@ func (c *EC2) DescribeNetworkInterfacesRequest(input *DescribeNetworkInterfacesI // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeNetworkInterfaces func (c *EC2) DescribeNetworkInterfaces(input *DescribeNetworkInterfacesInput) (*DescribeNetworkInterfacesOutput, error) { req, out := c.DescribeNetworkInterfacesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeNetworkInterfacesWithContext is the same as DescribeNetworkInterfaces with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeNetworkInterfaces 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) DescribeNetworkInterfacesWithContext(ctx aws.Context, input *DescribeNetworkInterfacesInput, opts ...request.Option) (*DescribeNetworkInterfacesOutput, error) { + req, out := c.DescribeNetworkInterfacesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribePlacementGroups = "DescribePlacementGroups" @@ -7904,8 +9797,23 @@ func (c *EC2) DescribePlacementGroupsRequest(input *DescribePlacementGroupsInput // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribePlacementGroups func (c *EC2) DescribePlacementGroups(input *DescribePlacementGroupsInput) (*DescribePlacementGroupsOutput, error) { req, out := c.DescribePlacementGroupsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribePlacementGroupsWithContext is the same as DescribePlacementGroups with the addition of +// the ability to pass a context and additional request options. +// +// See DescribePlacementGroups 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) DescribePlacementGroupsWithContext(ctx aws.Context, input *DescribePlacementGroupsInput, opts ...request.Option) (*DescribePlacementGroupsOutput, error) { + req, out := c.DescribePlacementGroupsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribePrefixLists = "DescribePrefixLists" @@ -7968,8 +9876,23 @@ func (c *EC2) DescribePrefixListsRequest(input *DescribePrefixListsInput) (req * // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribePrefixLists func (c *EC2) DescribePrefixLists(input *DescribePrefixListsInput) (*DescribePrefixListsOutput, error) { req, out := c.DescribePrefixListsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribePrefixListsWithContext is the same as DescribePrefixLists with the addition of +// the ability to pass a context and additional request options. +// +// See DescribePrefixLists 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) DescribePrefixListsWithContext(ctx aws.Context, input *DescribePrefixListsInput, opts ...request.Option) (*DescribePrefixListsOutput, error) { + req, out := c.DescribePrefixListsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeRegions = "DescribeRegions" @@ -8031,8 +9954,23 @@ func (c *EC2) DescribeRegionsRequest(input *DescribeRegionsInput) (req *request. // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeRegions func (c *EC2) DescribeRegions(input *DescribeRegionsInput) (*DescribeRegionsOutput, error) { req, out := c.DescribeRegionsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeRegionsWithContext is the same as DescribeRegions with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeRegions 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) DescribeRegionsWithContext(ctx aws.Context, input *DescribeRegionsInput, opts ...request.Option) (*DescribeRegionsOutput, error) { + req, out := c.DescribeRegionsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeReservedInstances = "DescribeReservedInstances" @@ -8094,8 +10032,23 @@ func (c *EC2) DescribeReservedInstancesRequest(input *DescribeReservedInstancesI // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeReservedInstances func (c *EC2) DescribeReservedInstances(input *DescribeReservedInstancesInput) (*DescribeReservedInstancesOutput, error) { req, out := c.DescribeReservedInstancesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeReservedInstancesWithContext is the same as DescribeReservedInstances with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeReservedInstances 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) DescribeReservedInstancesWithContext(ctx aws.Context, input *DescribeReservedInstancesInput, opts ...request.Option) (*DescribeReservedInstancesOutput, error) { + req, out := c.DescribeReservedInstancesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeReservedInstancesListings = "DescribeReservedInstancesListings" @@ -8175,8 +10128,23 @@ func (c *EC2) DescribeReservedInstancesListingsRequest(input *DescribeReservedIn // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeReservedInstancesListings func (c *EC2) DescribeReservedInstancesListings(input *DescribeReservedInstancesListingsInput) (*DescribeReservedInstancesListingsOutput, error) { req, out := c.DescribeReservedInstancesListingsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeReservedInstancesListingsWithContext is the same as DescribeReservedInstancesListings with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeReservedInstancesListings 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) DescribeReservedInstancesListingsWithContext(ctx aws.Context, input *DescribeReservedInstancesListingsInput, opts ...request.Option) (*DescribeReservedInstancesListingsOutput, error) { + req, out := c.DescribeReservedInstancesListingsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeReservedInstancesModifications = "DescribeReservedInstancesModifications" @@ -8247,8 +10215,23 @@ func (c *EC2) DescribeReservedInstancesModificationsRequest(input *DescribeReser // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeReservedInstancesModifications func (c *EC2) DescribeReservedInstancesModifications(input *DescribeReservedInstancesModificationsInput) (*DescribeReservedInstancesModificationsOutput, error) { req, out := c.DescribeReservedInstancesModificationsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeReservedInstancesModificationsWithContext is the same as DescribeReservedInstancesModifications with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeReservedInstancesModifications 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) DescribeReservedInstancesModificationsWithContext(ctx aws.Context, input *DescribeReservedInstancesModificationsInput, opts ...request.Option) (*DescribeReservedInstancesModificationsOutput, error) { + req, out := c.DescribeReservedInstancesModificationsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // DescribeReservedInstancesModificationsPages iterates over the pages of a DescribeReservedInstancesModifications operation, @@ -8268,12 +10251,37 @@ func (c *EC2) DescribeReservedInstancesModifications(input *DescribeReservedInst // return pageNum <= 3 // }) // -func (c *EC2) DescribeReservedInstancesModificationsPages(input *DescribeReservedInstancesModificationsInput, fn func(p *DescribeReservedInstancesModificationsOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.DescribeReservedInstancesModificationsRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*DescribeReservedInstancesModificationsOutput), lastPage) - }) +func (c *EC2) DescribeReservedInstancesModificationsPages(input *DescribeReservedInstancesModificationsInput, fn func(*DescribeReservedInstancesModificationsOutput, bool) bool) error { + return c.DescribeReservedInstancesModificationsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// DescribeReservedInstancesModificationsPagesWithContext same as DescribeReservedInstancesModificationsPages 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) DescribeReservedInstancesModificationsPagesWithContext(ctx aws.Context, input *DescribeReservedInstancesModificationsInput, fn func(*DescribeReservedInstancesModificationsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *DescribeReservedInstancesModificationsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeReservedInstancesModificationsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*DescribeReservedInstancesModificationsOutput), !p.HasNextPage()) + } + return p.Err() } const opDescribeReservedInstancesOfferings = "DescribeReservedInstancesOfferings" @@ -8349,8 +10357,23 @@ func (c *EC2) DescribeReservedInstancesOfferingsRequest(input *DescribeReservedI // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeReservedInstancesOfferings func (c *EC2) DescribeReservedInstancesOfferings(input *DescribeReservedInstancesOfferingsInput) (*DescribeReservedInstancesOfferingsOutput, error) { req, out := c.DescribeReservedInstancesOfferingsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeReservedInstancesOfferingsWithContext is the same as DescribeReservedInstancesOfferings with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeReservedInstancesOfferings 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) DescribeReservedInstancesOfferingsWithContext(ctx aws.Context, input *DescribeReservedInstancesOfferingsInput, opts ...request.Option) (*DescribeReservedInstancesOfferingsOutput, error) { + req, out := c.DescribeReservedInstancesOfferingsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // DescribeReservedInstancesOfferingsPages iterates over the pages of a DescribeReservedInstancesOfferings operation, @@ -8370,12 +10393,37 @@ func (c *EC2) DescribeReservedInstancesOfferings(input *DescribeReservedInstance // return pageNum <= 3 // }) // -func (c *EC2) DescribeReservedInstancesOfferingsPages(input *DescribeReservedInstancesOfferingsInput, fn func(p *DescribeReservedInstancesOfferingsOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.DescribeReservedInstancesOfferingsRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*DescribeReservedInstancesOfferingsOutput), lastPage) - }) +func (c *EC2) DescribeReservedInstancesOfferingsPages(input *DescribeReservedInstancesOfferingsInput, fn func(*DescribeReservedInstancesOfferingsOutput, bool) bool) error { + return c.DescribeReservedInstancesOfferingsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// DescribeReservedInstancesOfferingsPagesWithContext same as DescribeReservedInstancesOfferingsPages 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) DescribeReservedInstancesOfferingsPagesWithContext(ctx aws.Context, input *DescribeReservedInstancesOfferingsInput, fn func(*DescribeReservedInstancesOfferingsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *DescribeReservedInstancesOfferingsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeReservedInstancesOfferingsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*DescribeReservedInstancesOfferingsOutput), !p.HasNextPage()) + } + return p.Err() } const opDescribeRouteTables = "DescribeRouteTables" @@ -8442,8 +10490,23 @@ func (c *EC2) DescribeRouteTablesRequest(input *DescribeRouteTablesInput) (req * // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeRouteTables func (c *EC2) DescribeRouteTables(input *DescribeRouteTablesInput) (*DescribeRouteTablesOutput, error) { req, out := c.DescribeRouteTablesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeRouteTablesWithContext is the same as DescribeRouteTables with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeRouteTables 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) DescribeRouteTablesWithContext(ctx aws.Context, input *DescribeRouteTablesInput, opts ...request.Option) (*DescribeRouteTablesOutput, error) { + req, out := c.DescribeRouteTablesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeScheduledInstanceAvailability = "DescribeScheduledInstanceAvailability" @@ -8510,8 +10573,23 @@ func (c *EC2) DescribeScheduledInstanceAvailabilityRequest(input *DescribeSchedu // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeScheduledInstanceAvailability func (c *EC2) DescribeScheduledInstanceAvailability(input *DescribeScheduledInstanceAvailabilityInput) (*DescribeScheduledInstanceAvailabilityOutput, error) { req, out := c.DescribeScheduledInstanceAvailabilityRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeScheduledInstanceAvailabilityWithContext is the same as DescribeScheduledInstanceAvailability with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeScheduledInstanceAvailability 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) DescribeScheduledInstanceAvailabilityWithContext(ctx aws.Context, input *DescribeScheduledInstanceAvailabilityInput, opts ...request.Option) (*DescribeScheduledInstanceAvailabilityOutput, error) { + req, out := c.DescribeScheduledInstanceAvailabilityRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeScheduledInstances = "DescribeScheduledInstances" @@ -8570,8 +10648,23 @@ func (c *EC2) DescribeScheduledInstancesRequest(input *DescribeScheduledInstance // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeScheduledInstances func (c *EC2) DescribeScheduledInstances(input *DescribeScheduledInstancesInput) (*DescribeScheduledInstancesOutput, error) { req, out := c.DescribeScheduledInstancesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeScheduledInstancesWithContext is the same as DescribeScheduledInstances with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeScheduledInstances 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) DescribeScheduledInstancesWithContext(ctx aws.Context, input *DescribeScheduledInstancesInput, opts ...request.Option) (*DescribeScheduledInstancesOutput, error) { + req, out := c.DescribeScheduledInstancesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeSecurityGroupReferences = "DescribeSecurityGroupReferences" @@ -8631,8 +10724,23 @@ func (c *EC2) DescribeSecurityGroupReferencesRequest(input *DescribeSecurityGrou // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeSecurityGroupReferences func (c *EC2) DescribeSecurityGroupReferences(input *DescribeSecurityGroupReferencesInput) (*DescribeSecurityGroupReferencesOutput, error) { req, out := c.DescribeSecurityGroupReferencesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeSecurityGroupReferencesWithContext is the same as DescribeSecurityGroupReferences with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeSecurityGroupReferences 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) DescribeSecurityGroupReferencesWithContext(ctx aws.Context, input *DescribeSecurityGroupReferencesInput, opts ...request.Option) (*DescribeSecurityGroupReferencesOutput, error) { + req, out := c.DescribeSecurityGroupReferencesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeSecurityGroups = "DescribeSecurityGroups" @@ -8698,8 +10806,23 @@ func (c *EC2) DescribeSecurityGroupsRequest(input *DescribeSecurityGroupsInput) // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeSecurityGroups func (c *EC2) DescribeSecurityGroups(input *DescribeSecurityGroupsInput) (*DescribeSecurityGroupsOutput, error) { req, out := c.DescribeSecurityGroupsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeSecurityGroupsWithContext is the same as DescribeSecurityGroups with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeSecurityGroups 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) DescribeSecurityGroupsWithContext(ctx aws.Context, input *DescribeSecurityGroupsInput, opts ...request.Option) (*DescribeSecurityGroupsOutput, error) { + req, out := c.DescribeSecurityGroupsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeSnapshotAttribute = "DescribeSnapshotAttribute" @@ -8762,8 +10885,23 @@ func (c *EC2) DescribeSnapshotAttributeRequest(input *DescribeSnapshotAttributeI // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeSnapshotAttribute func (c *EC2) DescribeSnapshotAttribute(input *DescribeSnapshotAttributeInput) (*DescribeSnapshotAttributeOutput, error) { req, out := c.DescribeSnapshotAttributeRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeSnapshotAttributeWithContext is the same as DescribeSnapshotAttribute with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeSnapshotAttribute 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) DescribeSnapshotAttributeWithContext(ctx aws.Context, input *DescribeSnapshotAttributeInput, opts ...request.Option) (*DescribeSnapshotAttributeOutput, error) { + req, out := c.DescribeSnapshotAttributeRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeSnapshots = "DescribeSnapshots" @@ -8873,8 +11011,23 @@ func (c *EC2) DescribeSnapshotsRequest(input *DescribeSnapshotsInput) (req *requ // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeSnapshots func (c *EC2) DescribeSnapshots(input *DescribeSnapshotsInput) (*DescribeSnapshotsOutput, error) { req, out := c.DescribeSnapshotsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeSnapshotsWithContext is the same as DescribeSnapshots with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeSnapshots 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) DescribeSnapshotsWithContext(ctx aws.Context, input *DescribeSnapshotsInput, opts ...request.Option) (*DescribeSnapshotsOutput, error) { + req, out := c.DescribeSnapshotsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // DescribeSnapshotsPages iterates over the pages of a DescribeSnapshots operation, @@ -8894,12 +11047,37 @@ func (c *EC2) DescribeSnapshots(input *DescribeSnapshotsInput) (*DescribeSnapsho // return pageNum <= 3 // }) // -func (c *EC2) DescribeSnapshotsPages(input *DescribeSnapshotsInput, fn func(p *DescribeSnapshotsOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.DescribeSnapshotsRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*DescribeSnapshotsOutput), lastPage) - }) +func (c *EC2) DescribeSnapshotsPages(input *DescribeSnapshotsInput, fn func(*DescribeSnapshotsOutput, bool) bool) error { + return c.DescribeSnapshotsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// DescribeSnapshotsPagesWithContext same as DescribeSnapshotsPages 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) DescribeSnapshotsPagesWithContext(ctx aws.Context, input *DescribeSnapshotsInput, fn func(*DescribeSnapshotsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *DescribeSnapshotsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeSnapshotsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*DescribeSnapshotsOutput), !p.HasNextPage()) + } + return p.Err() } const opDescribeSpotDatafeedSubscription = "DescribeSpotDatafeedSubscription" @@ -8960,8 +11138,23 @@ func (c *EC2) DescribeSpotDatafeedSubscriptionRequest(input *DescribeSpotDatafee // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeSpotDatafeedSubscription func (c *EC2) DescribeSpotDatafeedSubscription(input *DescribeSpotDatafeedSubscriptionInput) (*DescribeSpotDatafeedSubscriptionOutput, error) { req, out := c.DescribeSpotDatafeedSubscriptionRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeSpotDatafeedSubscriptionWithContext is the same as DescribeSpotDatafeedSubscription with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeSpotDatafeedSubscription 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) DescribeSpotDatafeedSubscriptionWithContext(ctx aws.Context, input *DescribeSpotDatafeedSubscriptionInput, opts ...request.Option) (*DescribeSpotDatafeedSubscriptionOutput, error) { + req, out := c.DescribeSpotDatafeedSubscriptionRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeSpotFleetInstances = "DescribeSpotFleetInstances" @@ -9020,8 +11213,23 @@ func (c *EC2) DescribeSpotFleetInstancesRequest(input *DescribeSpotFleetInstance // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeSpotFleetInstances func (c *EC2) DescribeSpotFleetInstances(input *DescribeSpotFleetInstancesInput) (*DescribeSpotFleetInstancesOutput, error) { req, out := c.DescribeSpotFleetInstancesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeSpotFleetInstancesWithContext is the same as DescribeSpotFleetInstances with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeSpotFleetInstances 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) DescribeSpotFleetInstancesWithContext(ctx aws.Context, input *DescribeSpotFleetInstancesInput, opts ...request.Option) (*DescribeSpotFleetInstancesOutput, error) { + req, out := c.DescribeSpotFleetInstancesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeSpotFleetRequestHistory = "DescribeSpotFleetRequestHistory" @@ -9085,8 +11293,23 @@ func (c *EC2) DescribeSpotFleetRequestHistoryRequest(input *DescribeSpotFleetReq // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeSpotFleetRequestHistory func (c *EC2) DescribeSpotFleetRequestHistory(input *DescribeSpotFleetRequestHistoryInput) (*DescribeSpotFleetRequestHistoryOutput, error) { req, out := c.DescribeSpotFleetRequestHistoryRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeSpotFleetRequestHistoryWithContext is the same as DescribeSpotFleetRequestHistory with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeSpotFleetRequestHistory 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) DescribeSpotFleetRequestHistoryWithContext(ctx aws.Context, input *DescribeSpotFleetRequestHistoryInput, opts ...request.Option) (*DescribeSpotFleetRequestHistoryOutput, error) { + req, out := c.DescribeSpotFleetRequestHistoryRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeSpotFleetRequests = "DescribeSpotFleetRequests" @@ -9154,8 +11377,23 @@ func (c *EC2) DescribeSpotFleetRequestsRequest(input *DescribeSpotFleetRequestsI // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeSpotFleetRequests func (c *EC2) DescribeSpotFleetRequests(input *DescribeSpotFleetRequestsInput) (*DescribeSpotFleetRequestsOutput, error) { req, out := c.DescribeSpotFleetRequestsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeSpotFleetRequestsWithContext is the same as DescribeSpotFleetRequests with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeSpotFleetRequests 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) DescribeSpotFleetRequestsWithContext(ctx aws.Context, input *DescribeSpotFleetRequestsInput, opts ...request.Option) (*DescribeSpotFleetRequestsOutput, error) { + req, out := c.DescribeSpotFleetRequestsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // DescribeSpotFleetRequestsPages iterates over the pages of a DescribeSpotFleetRequests operation, @@ -9175,12 +11413,37 @@ func (c *EC2) DescribeSpotFleetRequests(input *DescribeSpotFleetRequestsInput) ( // return pageNum <= 3 // }) // -func (c *EC2) DescribeSpotFleetRequestsPages(input *DescribeSpotFleetRequestsInput, fn func(p *DescribeSpotFleetRequestsOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.DescribeSpotFleetRequestsRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*DescribeSpotFleetRequestsOutput), lastPage) - }) +func (c *EC2) DescribeSpotFleetRequestsPages(input *DescribeSpotFleetRequestsInput, fn func(*DescribeSpotFleetRequestsOutput, bool) bool) error { + return c.DescribeSpotFleetRequestsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// DescribeSpotFleetRequestsPagesWithContext same as DescribeSpotFleetRequestsPages 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) DescribeSpotFleetRequestsPagesWithContext(ctx aws.Context, input *DescribeSpotFleetRequestsInput, fn func(*DescribeSpotFleetRequestsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *DescribeSpotFleetRequestsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeSpotFleetRequestsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*DescribeSpotFleetRequestsOutput), !p.HasNextPage()) + } + return p.Err() } const opDescribeSpotInstanceRequests = "DescribeSpotInstanceRequests" @@ -9253,8 +11516,23 @@ func (c *EC2) DescribeSpotInstanceRequestsRequest(input *DescribeSpotInstanceReq // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeSpotInstanceRequests func (c *EC2) DescribeSpotInstanceRequests(input *DescribeSpotInstanceRequestsInput) (*DescribeSpotInstanceRequestsOutput, error) { req, out := c.DescribeSpotInstanceRequestsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeSpotInstanceRequestsWithContext is the same as DescribeSpotInstanceRequests with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeSpotInstanceRequests 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) DescribeSpotInstanceRequestsWithContext(ctx aws.Context, input *DescribeSpotInstanceRequestsInput, opts ...request.Option) (*DescribeSpotInstanceRequestsOutput, error) { + req, out := c.DescribeSpotInstanceRequestsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeSpotPriceHistory = "DescribeSpotPriceHistory" @@ -9326,8 +11604,23 @@ func (c *EC2) DescribeSpotPriceHistoryRequest(input *DescribeSpotPriceHistoryInp // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeSpotPriceHistory func (c *EC2) DescribeSpotPriceHistory(input *DescribeSpotPriceHistoryInput) (*DescribeSpotPriceHistoryOutput, error) { req, out := c.DescribeSpotPriceHistoryRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeSpotPriceHistoryWithContext is the same as DescribeSpotPriceHistory with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeSpotPriceHistory 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) DescribeSpotPriceHistoryWithContext(ctx aws.Context, input *DescribeSpotPriceHistoryInput, opts ...request.Option) (*DescribeSpotPriceHistoryOutput, error) { + req, out := c.DescribeSpotPriceHistoryRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // DescribeSpotPriceHistoryPages iterates over the pages of a DescribeSpotPriceHistory operation, @@ -9347,12 +11640,37 @@ func (c *EC2) DescribeSpotPriceHistory(input *DescribeSpotPriceHistoryInput) (*D // return pageNum <= 3 // }) // -func (c *EC2) DescribeSpotPriceHistoryPages(input *DescribeSpotPriceHistoryInput, fn func(p *DescribeSpotPriceHistoryOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.DescribeSpotPriceHistoryRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*DescribeSpotPriceHistoryOutput), lastPage) - }) +func (c *EC2) DescribeSpotPriceHistoryPages(input *DescribeSpotPriceHistoryInput, fn func(*DescribeSpotPriceHistoryOutput, bool) bool) error { + return c.DescribeSpotPriceHistoryPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// DescribeSpotPriceHistoryPagesWithContext same as DescribeSpotPriceHistoryPages 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) DescribeSpotPriceHistoryPagesWithContext(ctx aws.Context, input *DescribeSpotPriceHistoryInput, fn func(*DescribeSpotPriceHistoryOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *DescribeSpotPriceHistoryInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeSpotPriceHistoryRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*DescribeSpotPriceHistoryOutput), !p.HasNextPage()) + } + return p.Err() } const opDescribeStaleSecurityGroups = "DescribeStaleSecurityGroups" @@ -9414,8 +11732,23 @@ func (c *EC2) DescribeStaleSecurityGroupsRequest(input *DescribeStaleSecurityGro // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeStaleSecurityGroups func (c *EC2) DescribeStaleSecurityGroups(input *DescribeStaleSecurityGroupsInput) (*DescribeStaleSecurityGroupsOutput, error) { req, out := c.DescribeStaleSecurityGroupsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeStaleSecurityGroupsWithContext is the same as DescribeStaleSecurityGroups with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeStaleSecurityGroups 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) DescribeStaleSecurityGroupsWithContext(ctx aws.Context, input *DescribeStaleSecurityGroupsInput, opts ...request.Option) (*DescribeStaleSecurityGroupsOutput, error) { + req, out := c.DescribeStaleSecurityGroupsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeSubnets = "DescribeSubnets" @@ -9477,8 +11810,23 @@ func (c *EC2) DescribeSubnetsRequest(input *DescribeSubnetsInput) (req *request. // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeSubnets func (c *EC2) DescribeSubnets(input *DescribeSubnetsInput) (*DescribeSubnetsOutput, error) { req, out := c.DescribeSubnetsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeSubnetsWithContext is the same as DescribeSubnets with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeSubnets 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) DescribeSubnetsWithContext(ctx aws.Context, input *DescribeSubnetsInput, opts ...request.Option) (*DescribeSubnetsOutput, error) { + req, out := c.DescribeSubnetsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeTags = "DescribeTags" @@ -9546,8 +11894,23 @@ func (c *EC2) DescribeTagsRequest(input *DescribeTagsInput) (req *request.Reques // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeTags func (c *EC2) DescribeTags(input *DescribeTagsInput) (*DescribeTagsOutput, error) { req, out := c.DescribeTagsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeTagsWithContext is the same as DescribeTags with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeTags 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) DescribeTagsWithContext(ctx aws.Context, input *DescribeTagsInput, opts ...request.Option) (*DescribeTagsOutput, error) { + req, out := c.DescribeTagsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // DescribeTagsPages iterates over the pages of a DescribeTags operation, @@ -9567,12 +11930,37 @@ func (c *EC2) DescribeTags(input *DescribeTagsInput) (*DescribeTagsOutput, error // return pageNum <= 3 // }) // -func (c *EC2) DescribeTagsPages(input *DescribeTagsInput, fn func(p *DescribeTagsOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.DescribeTagsRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*DescribeTagsOutput), lastPage) - }) +func (c *EC2) DescribeTagsPages(input *DescribeTagsInput, fn func(*DescribeTagsOutput, bool) bool) error { + return c.DescribeTagsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// DescribeTagsPagesWithContext same as DescribeTagsPages 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) DescribeTagsPagesWithContext(ctx aws.Context, input *DescribeTagsInput, fn func(*DescribeTagsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *DescribeTagsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeTagsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*DescribeTagsOutput), !p.HasNextPage()) + } + return p.Err() } const opDescribeVolumeAttribute = "DescribeVolumeAttribute" @@ -9635,8 +12023,23 @@ func (c *EC2) DescribeVolumeAttributeRequest(input *DescribeVolumeAttributeInput // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeVolumeAttribute func (c *EC2) DescribeVolumeAttribute(input *DescribeVolumeAttributeInput) (*DescribeVolumeAttributeOutput, error) { req, out := c.DescribeVolumeAttributeRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeVolumeAttributeWithContext is the same as DescribeVolumeAttribute with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeVolumeAttribute 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) DescribeVolumeAttributeWithContext(ctx aws.Context, input *DescribeVolumeAttributeInput, opts ...request.Option) (*DescribeVolumeAttributeOutput, error) { + req, out := c.DescribeVolumeAttributeRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeVolumeStatus = "DescribeVolumeStatus" @@ -9735,8 +12138,23 @@ func (c *EC2) DescribeVolumeStatusRequest(input *DescribeVolumeStatusInput) (req // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeVolumeStatus func (c *EC2) DescribeVolumeStatus(input *DescribeVolumeStatusInput) (*DescribeVolumeStatusOutput, error) { req, out := c.DescribeVolumeStatusRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeVolumeStatusWithContext is the same as DescribeVolumeStatus with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeVolumeStatus 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) DescribeVolumeStatusWithContext(ctx aws.Context, input *DescribeVolumeStatusInput, opts ...request.Option) (*DescribeVolumeStatusOutput, error) { + req, out := c.DescribeVolumeStatusRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // DescribeVolumeStatusPages iterates over the pages of a DescribeVolumeStatus operation, @@ -9756,12 +12174,37 @@ func (c *EC2) DescribeVolumeStatus(input *DescribeVolumeStatusInput) (*DescribeV // return pageNum <= 3 // }) // -func (c *EC2) DescribeVolumeStatusPages(input *DescribeVolumeStatusInput, fn func(p *DescribeVolumeStatusOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.DescribeVolumeStatusRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*DescribeVolumeStatusOutput), lastPage) - }) +func (c *EC2) DescribeVolumeStatusPages(input *DescribeVolumeStatusInput, fn func(*DescribeVolumeStatusOutput, bool) bool) error { + return c.DescribeVolumeStatusPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// DescribeVolumeStatusPagesWithContext same as DescribeVolumeStatusPages 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) DescribeVolumeStatusPagesWithContext(ctx aws.Context, input *DescribeVolumeStatusInput, fn func(*DescribeVolumeStatusOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *DescribeVolumeStatusInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeVolumeStatusRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*DescribeVolumeStatusOutput), !p.HasNextPage()) + } + return p.Err() } const opDescribeVolumes = "DescribeVolumes" @@ -9836,8 +12279,23 @@ func (c *EC2) DescribeVolumesRequest(input *DescribeVolumesInput) (req *request. // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeVolumes func (c *EC2) DescribeVolumes(input *DescribeVolumesInput) (*DescribeVolumesOutput, error) { req, out := c.DescribeVolumesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeVolumesWithContext is the same as DescribeVolumes with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeVolumes 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) DescribeVolumesWithContext(ctx aws.Context, input *DescribeVolumesInput, opts ...request.Option) (*DescribeVolumesOutput, error) { + req, out := c.DescribeVolumesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // DescribeVolumesPages iterates over the pages of a DescribeVolumes operation, @@ -9857,12 +12315,37 @@ func (c *EC2) DescribeVolumes(input *DescribeVolumesInput) (*DescribeVolumesOutp // return pageNum <= 3 // }) // -func (c *EC2) DescribeVolumesPages(input *DescribeVolumesInput, fn func(p *DescribeVolumesOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.DescribeVolumesRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*DescribeVolumesOutput), lastPage) - }) +func (c *EC2) DescribeVolumesPages(input *DescribeVolumesInput, fn func(*DescribeVolumesOutput, bool) bool) error { + return c.DescribeVolumesPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// DescribeVolumesPagesWithContext same as DescribeVolumesPages 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) DescribeVolumesPagesWithContext(ctx aws.Context, input *DescribeVolumesInput, fn func(*DescribeVolumesOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *DescribeVolumesInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeVolumesRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*DescribeVolumesOutput), !p.HasNextPage()) + } + return p.Err() } const opDescribeVolumesModifications = "DescribeVolumesModifications" @@ -9933,8 +12416,23 @@ func (c *EC2) DescribeVolumesModificationsRequest(input *DescribeVolumesModifica // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeVolumesModifications func (c *EC2) DescribeVolumesModifications(input *DescribeVolumesModificationsInput) (*DescribeVolumesModificationsOutput, error) { req, out := c.DescribeVolumesModificationsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeVolumesModificationsWithContext is the same as DescribeVolumesModifications with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeVolumesModifications 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) DescribeVolumesModificationsWithContext(ctx aws.Context, input *DescribeVolumesModificationsInput, opts ...request.Option) (*DescribeVolumesModificationsOutput, error) { + req, out := c.DescribeVolumesModificationsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeVpcAttribute = "DescribeVpcAttribute" @@ -9994,8 +12492,23 @@ func (c *EC2) DescribeVpcAttributeRequest(input *DescribeVpcAttributeInput) (req // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeVpcAttribute func (c *EC2) DescribeVpcAttribute(input *DescribeVpcAttributeInput) (*DescribeVpcAttributeOutput, error) { req, out := c.DescribeVpcAttributeRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeVpcAttributeWithContext is the same as DescribeVpcAttribute with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeVpcAttribute 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) DescribeVpcAttributeWithContext(ctx aws.Context, input *DescribeVpcAttributeInput, opts ...request.Option) (*DescribeVpcAttributeOutput, error) { + req, out := c.DescribeVpcAttributeRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeVpcClassicLink = "DescribeVpcClassicLink" @@ -10054,8 +12567,23 @@ func (c *EC2) DescribeVpcClassicLinkRequest(input *DescribeVpcClassicLinkInput) // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeVpcClassicLink func (c *EC2) DescribeVpcClassicLink(input *DescribeVpcClassicLinkInput) (*DescribeVpcClassicLinkOutput, error) { req, out := c.DescribeVpcClassicLinkRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeVpcClassicLinkWithContext is the same as DescribeVpcClassicLink with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeVpcClassicLink 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) DescribeVpcClassicLinkWithContext(ctx aws.Context, input *DescribeVpcClassicLinkInput, opts ...request.Option) (*DescribeVpcClassicLinkOutput, error) { + req, out := c.DescribeVpcClassicLinkRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeVpcClassicLinkDnsSupport = "DescribeVpcClassicLinkDnsSupport" @@ -10107,8 +12635,8 @@ func (c *EC2) DescribeVpcClassicLinkDnsSupportRequest(input *DescribeVpcClassicL // the DNS hostname of a linked EC2-Classic instance resolves to its private // IP address when addressed from an instance in the VPC to which it's linked. // Similarly, the DNS hostname of an instance in a VPC resolves to its private -// IP address when addressed from a linked EC2-Classic instance. For more information -// about ClassicLink, see ClassicLink (http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/vpc-classiclink.html) +// IP address when addressed from a linked EC2-Classic instance. For more information, +// see ClassicLink (http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/vpc-classiclink.html) // in the Amazon Elastic Compute Cloud User Guide. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions @@ -10120,8 +12648,23 @@ func (c *EC2) DescribeVpcClassicLinkDnsSupportRequest(input *DescribeVpcClassicL // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeVpcClassicLinkDnsSupport func (c *EC2) DescribeVpcClassicLinkDnsSupport(input *DescribeVpcClassicLinkDnsSupportInput) (*DescribeVpcClassicLinkDnsSupportOutput, error) { req, out := c.DescribeVpcClassicLinkDnsSupportRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeVpcClassicLinkDnsSupportWithContext is the same as DescribeVpcClassicLinkDnsSupport with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeVpcClassicLinkDnsSupport 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) DescribeVpcClassicLinkDnsSupportWithContext(ctx aws.Context, input *DescribeVpcClassicLinkDnsSupportInput, opts ...request.Option) (*DescribeVpcClassicLinkDnsSupportOutput, error) { + req, out := c.DescribeVpcClassicLinkDnsSupportRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeVpcEndpointServices = "DescribeVpcEndpointServices" @@ -10181,8 +12724,23 @@ func (c *EC2) DescribeVpcEndpointServicesRequest(input *DescribeVpcEndpointServi // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeVpcEndpointServices func (c *EC2) DescribeVpcEndpointServices(input *DescribeVpcEndpointServicesInput) (*DescribeVpcEndpointServicesOutput, error) { req, out := c.DescribeVpcEndpointServicesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeVpcEndpointServicesWithContext is the same as DescribeVpcEndpointServices with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeVpcEndpointServices 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) DescribeVpcEndpointServicesWithContext(ctx aws.Context, input *DescribeVpcEndpointServicesInput, opts ...request.Option) (*DescribeVpcEndpointServicesOutput, error) { + req, out := c.DescribeVpcEndpointServicesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeVpcEndpoints = "DescribeVpcEndpoints" @@ -10241,8 +12799,23 @@ func (c *EC2) DescribeVpcEndpointsRequest(input *DescribeVpcEndpointsInput) (req // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeVpcEndpoints func (c *EC2) DescribeVpcEndpoints(input *DescribeVpcEndpointsInput) (*DescribeVpcEndpointsOutput, error) { req, out := c.DescribeVpcEndpointsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeVpcEndpointsWithContext is the same as DescribeVpcEndpoints with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeVpcEndpoints 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) DescribeVpcEndpointsWithContext(ctx aws.Context, input *DescribeVpcEndpointsInput, opts ...request.Option) (*DescribeVpcEndpointsOutput, error) { + req, out := c.DescribeVpcEndpointsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeVpcPeeringConnections = "DescribeVpcPeeringConnections" @@ -10301,8 +12874,23 @@ func (c *EC2) DescribeVpcPeeringConnectionsRequest(input *DescribeVpcPeeringConn // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeVpcPeeringConnections func (c *EC2) DescribeVpcPeeringConnections(input *DescribeVpcPeeringConnectionsInput) (*DescribeVpcPeeringConnectionsOutput, error) { req, out := c.DescribeVpcPeeringConnectionsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeVpcPeeringConnectionsWithContext is the same as DescribeVpcPeeringConnections with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeVpcPeeringConnections 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) DescribeVpcPeeringConnectionsWithContext(ctx aws.Context, input *DescribeVpcPeeringConnectionsInput, opts ...request.Option) (*DescribeVpcPeeringConnectionsOutput, error) { + req, out := c.DescribeVpcPeeringConnectionsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeVpcs = "DescribeVpcs" @@ -10361,8 +12949,23 @@ func (c *EC2) DescribeVpcsRequest(input *DescribeVpcsInput) (req *request.Reques // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeVpcs func (c *EC2) DescribeVpcs(input *DescribeVpcsInput) (*DescribeVpcsOutput, error) { req, out := c.DescribeVpcsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeVpcsWithContext is the same as DescribeVpcs with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeVpcs 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) DescribeVpcsWithContext(ctx aws.Context, input *DescribeVpcsInput, opts ...request.Option) (*DescribeVpcsOutput, error) { + req, out := c.DescribeVpcsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeVpnConnections = "DescribeVpnConnections" @@ -10425,8 +13028,23 @@ func (c *EC2) DescribeVpnConnectionsRequest(input *DescribeVpnConnectionsInput) // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeVpnConnections func (c *EC2) DescribeVpnConnections(input *DescribeVpnConnectionsInput) (*DescribeVpnConnectionsOutput, error) { req, out := c.DescribeVpnConnectionsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeVpnConnectionsWithContext is the same as DescribeVpnConnections with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeVpnConnections 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) DescribeVpnConnectionsWithContext(ctx aws.Context, input *DescribeVpnConnectionsInput, opts ...request.Option) (*DescribeVpnConnectionsOutput, error) { + req, out := c.DescribeVpnConnectionsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeVpnGateways = "DescribeVpnGateways" @@ -10489,8 +13107,23 @@ func (c *EC2) DescribeVpnGatewaysRequest(input *DescribeVpnGatewaysInput) (req * // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeVpnGateways func (c *EC2) DescribeVpnGateways(input *DescribeVpnGatewaysInput) (*DescribeVpnGatewaysOutput, error) { req, out := c.DescribeVpnGatewaysRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeVpnGatewaysWithContext is the same as DescribeVpnGateways with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeVpnGateways 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) DescribeVpnGatewaysWithContext(ctx aws.Context, input *DescribeVpnGatewaysInput, opts ...request.Option) (*DescribeVpnGatewaysOutput, error) { + req, out := c.DescribeVpnGatewaysRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDetachClassicLinkVpc = "DetachClassicLinkVpc" @@ -10551,8 +13184,23 @@ func (c *EC2) DetachClassicLinkVpcRequest(input *DetachClassicLinkVpcInput) (req // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DetachClassicLinkVpc func (c *EC2) DetachClassicLinkVpc(input *DetachClassicLinkVpcInput) (*DetachClassicLinkVpcOutput, error) { req, out := c.DetachClassicLinkVpcRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DetachClassicLinkVpcWithContext is the same as DetachClassicLinkVpc with the addition of +// the ability to pass a context and additional request options. +// +// See DetachClassicLinkVpc 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) DetachClassicLinkVpcWithContext(ctx aws.Context, input *DetachClassicLinkVpcInput, opts ...request.Option) (*DetachClassicLinkVpcOutput, error) { + req, out := c.DetachClassicLinkVpcRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDetachInternetGateway = "DetachInternetGateway" @@ -10604,7 +13252,7 @@ func (c *EC2) DetachInternetGatewayRequest(input *DetachInternetGatewayInput) (r // // Detaches an Internet gateway from a VPC, disabling connectivity between the // Internet and the VPC. The VPC must not contain any running instances with -// Elastic IP addresses. +// Elastic IP addresses or public IPv4 addresses. // // 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 @@ -10615,8 +13263,23 @@ func (c *EC2) DetachInternetGatewayRequest(input *DetachInternetGatewayInput) (r // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DetachInternetGateway func (c *EC2) DetachInternetGateway(input *DetachInternetGatewayInput) (*DetachInternetGatewayOutput, error) { req, out := c.DetachInternetGatewayRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DetachInternetGatewayWithContext is the same as DetachInternetGateway with the addition of +// the ability to pass a context and additional request options. +// +// See DetachInternetGateway 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) DetachInternetGatewayWithContext(ctx aws.Context, input *DetachInternetGatewayInput, opts ...request.Option) (*DetachInternetGatewayOutput, error) { + req, out := c.DetachInternetGatewayRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDetachNetworkInterface = "DetachNetworkInterface" @@ -10677,8 +13340,23 @@ func (c *EC2) DetachNetworkInterfaceRequest(input *DetachNetworkInterfaceInput) // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DetachNetworkInterface func (c *EC2) DetachNetworkInterface(input *DetachNetworkInterfaceInput) (*DetachNetworkInterfaceOutput, error) { req, out := c.DetachNetworkInterfaceRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DetachNetworkInterfaceWithContext is the same as DetachNetworkInterface with the addition of +// the ability to pass a context and additional request options. +// +// See DetachNetworkInterface 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) DetachNetworkInterfaceWithContext(ctx aws.Context, input *DetachNetworkInterfaceInput, opts ...request.Option) (*DetachNetworkInterfaceOutput, error) { + req, out := c.DetachNetworkInterfaceRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDetachVolume = "DetachVolume" @@ -10750,8 +13428,23 @@ func (c *EC2) DetachVolumeRequest(input *DetachVolumeInput) (req *request.Reques // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DetachVolume func (c *EC2) DetachVolume(input *DetachVolumeInput) (*VolumeAttachment, error) { req, out := c.DetachVolumeRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DetachVolumeWithContext is the same as DetachVolume with the addition of +// the ability to pass a context and additional request options. +// +// See DetachVolume 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) DetachVolumeWithContext(ctx aws.Context, input *DetachVolumeInput, opts ...request.Option) (*VolumeAttachment, error) { + req, out := c.DetachVolumeRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDetachVpnGateway = "DetachVpnGateway" @@ -10819,8 +13512,23 @@ func (c *EC2) DetachVpnGatewayRequest(input *DetachVpnGatewayInput) (req *reques // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DetachVpnGateway func (c *EC2) DetachVpnGateway(input *DetachVpnGatewayInput) (*DetachVpnGatewayOutput, error) { req, out := c.DetachVpnGatewayRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DetachVpnGatewayWithContext is the same as DetachVpnGateway with the addition of +// the ability to pass a context and additional request options. +// +// See DetachVpnGateway 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) DetachVpnGatewayWithContext(ctx aws.Context, input *DetachVpnGatewayInput, opts ...request.Option) (*DetachVpnGatewayOutput, error) { + req, out := c.DetachVpnGatewayRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDisableVgwRoutePropagation = "DisableVgwRoutePropagation" @@ -10882,8 +13590,23 @@ func (c *EC2) DisableVgwRoutePropagationRequest(input *DisableVgwRoutePropagatio // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DisableVgwRoutePropagation func (c *EC2) DisableVgwRoutePropagation(input *DisableVgwRoutePropagationInput) (*DisableVgwRoutePropagationOutput, error) { req, out := c.DisableVgwRoutePropagationRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DisableVgwRoutePropagationWithContext is the same as DisableVgwRoutePropagation with the addition of +// the ability to pass a context and additional request options. +// +// See DisableVgwRoutePropagation 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) DisableVgwRoutePropagationWithContext(ctx aws.Context, input *DisableVgwRoutePropagationInput, opts ...request.Option) (*DisableVgwRoutePropagationOutput, error) { + req, out := c.DisableVgwRoutePropagationRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDisableVpcClassicLink = "DisableVpcClassicLink" @@ -10943,8 +13666,23 @@ func (c *EC2) DisableVpcClassicLinkRequest(input *DisableVpcClassicLinkInput) (r // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DisableVpcClassicLink func (c *EC2) DisableVpcClassicLink(input *DisableVpcClassicLinkInput) (*DisableVpcClassicLinkOutput, error) { req, out := c.DisableVpcClassicLinkRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DisableVpcClassicLinkWithContext is the same as DisableVpcClassicLink with the addition of +// the ability to pass a context and additional request options. +// +// See DisableVpcClassicLink 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) DisableVpcClassicLinkWithContext(ctx aws.Context, input *DisableVpcClassicLinkInput, opts ...request.Option) (*DisableVpcClassicLinkOutput, error) { + req, out := c.DisableVpcClassicLinkRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDisableVpcClassicLinkDnsSupport = "DisableVpcClassicLinkDnsSupport" @@ -11007,8 +13745,23 @@ func (c *EC2) DisableVpcClassicLinkDnsSupportRequest(input *DisableVpcClassicLin // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DisableVpcClassicLinkDnsSupport func (c *EC2) DisableVpcClassicLinkDnsSupport(input *DisableVpcClassicLinkDnsSupportInput) (*DisableVpcClassicLinkDnsSupportOutput, error) { req, out := c.DisableVpcClassicLinkDnsSupportRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DisableVpcClassicLinkDnsSupportWithContext is the same as DisableVpcClassicLinkDnsSupport with the addition of +// the ability to pass a context and additional request options. +// +// See DisableVpcClassicLinkDnsSupport 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) DisableVpcClassicLinkDnsSupportWithContext(ctx aws.Context, input *DisableVpcClassicLinkDnsSupportInput, opts ...request.Option) (*DisableVpcClassicLinkDnsSupportOutput, error) { + req, out := c.DisableVpcClassicLinkDnsSupportRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDisassociateAddress = "DisassociateAddress" @@ -11077,8 +13830,23 @@ func (c *EC2) DisassociateAddressRequest(input *DisassociateAddressInput) (req * // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DisassociateAddress func (c *EC2) DisassociateAddress(input *DisassociateAddressInput) (*DisassociateAddressOutput, error) { req, out := c.DisassociateAddressRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DisassociateAddressWithContext is the same as DisassociateAddress with the addition of +// the ability to pass a context and additional request options. +// +// See DisassociateAddress 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) DisassociateAddressWithContext(ctx aws.Context, input *DisassociateAddressInput, opts ...request.Option) (*DisassociateAddressOutput, error) { + req, out := c.DisassociateAddressRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDisassociateIamInstanceProfile = "DisassociateIamInstanceProfile" @@ -11139,8 +13907,23 @@ func (c *EC2) DisassociateIamInstanceProfileRequest(input *DisassociateIamInstan // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DisassociateIamInstanceProfile func (c *EC2) DisassociateIamInstanceProfile(input *DisassociateIamInstanceProfileInput) (*DisassociateIamInstanceProfileOutput, error) { req, out := c.DisassociateIamInstanceProfileRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DisassociateIamInstanceProfileWithContext is the same as DisassociateIamInstanceProfile with the addition of +// the ability to pass a context and additional request options. +// +// See DisassociateIamInstanceProfile 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) DisassociateIamInstanceProfileWithContext(ctx aws.Context, input *DisassociateIamInstanceProfileInput, opts ...request.Option) (*DisassociateIamInstanceProfileOutput, error) { + req, out := c.DisassociateIamInstanceProfileRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDisassociateRouteTable = "DisassociateRouteTable" @@ -11206,8 +13989,23 @@ func (c *EC2) DisassociateRouteTableRequest(input *DisassociateRouteTableInput) // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DisassociateRouteTable func (c *EC2) DisassociateRouteTable(input *DisassociateRouteTableInput) (*DisassociateRouteTableOutput, error) { req, out := c.DisassociateRouteTableRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DisassociateRouteTableWithContext is the same as DisassociateRouteTable with the addition of +// the ability to pass a context and additional request options. +// +// See DisassociateRouteTable 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) DisassociateRouteTableWithContext(ctx aws.Context, input *DisassociateRouteTableInput, opts ...request.Option) (*DisassociateRouteTableOutput, error) { + req, out := c.DisassociateRouteTableRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDisassociateSubnetCidrBlock = "DisassociateSubnetCidrBlock" @@ -11268,8 +14066,23 @@ func (c *EC2) DisassociateSubnetCidrBlockRequest(input *DisassociateSubnetCidrBl // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DisassociateSubnetCidrBlock func (c *EC2) DisassociateSubnetCidrBlock(input *DisassociateSubnetCidrBlockInput) (*DisassociateSubnetCidrBlockOutput, error) { req, out := c.DisassociateSubnetCidrBlockRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DisassociateSubnetCidrBlockWithContext is the same as DisassociateSubnetCidrBlock with the addition of +// the ability to pass a context and additional request options. +// +// See DisassociateSubnetCidrBlock 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) DisassociateSubnetCidrBlockWithContext(ctx aws.Context, input *DisassociateSubnetCidrBlockInput, opts ...request.Option) (*DisassociateSubnetCidrBlockOutput, error) { + req, out := c.DisassociateSubnetCidrBlockRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDisassociateVpcCidrBlock = "DisassociateVpcCidrBlock" @@ -11330,8 +14143,23 @@ func (c *EC2) DisassociateVpcCidrBlockRequest(input *DisassociateVpcCidrBlockInp // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DisassociateVpcCidrBlock func (c *EC2) DisassociateVpcCidrBlock(input *DisassociateVpcCidrBlockInput) (*DisassociateVpcCidrBlockOutput, error) { req, out := c.DisassociateVpcCidrBlockRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DisassociateVpcCidrBlockWithContext is the same as DisassociateVpcCidrBlock with the addition of +// the ability to pass a context and additional request options. +// +// See DisassociateVpcCidrBlock 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) DisassociateVpcCidrBlockWithContext(ctx aws.Context, input *DisassociateVpcCidrBlockInput, opts ...request.Option) (*DisassociateVpcCidrBlockOutput, error) { + req, out := c.DisassociateVpcCidrBlockRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opEnableVgwRoutePropagation = "EnableVgwRoutePropagation" @@ -11393,8 +14221,23 @@ func (c *EC2) EnableVgwRoutePropagationRequest(input *EnableVgwRoutePropagationI // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/EnableVgwRoutePropagation func (c *EC2) EnableVgwRoutePropagation(input *EnableVgwRoutePropagationInput) (*EnableVgwRoutePropagationOutput, error) { req, out := c.EnableVgwRoutePropagationRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// EnableVgwRoutePropagationWithContext is the same as EnableVgwRoutePropagation with the addition of +// the ability to pass a context and additional request options. +// +// See EnableVgwRoutePropagation 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) EnableVgwRoutePropagationWithContext(ctx aws.Context, input *EnableVgwRoutePropagationInput, opts ...request.Option) (*EnableVgwRoutePropagationOutput, error) { + req, out := c.EnableVgwRoutePropagationRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opEnableVolumeIO = "EnableVolumeIO" @@ -11456,8 +14299,23 @@ func (c *EC2) EnableVolumeIORequest(input *EnableVolumeIOInput) (req *request.Re // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/EnableVolumeIO func (c *EC2) EnableVolumeIO(input *EnableVolumeIOInput) (*EnableVolumeIOOutput, error) { req, out := c.EnableVolumeIORequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// EnableVolumeIOWithContext is the same as EnableVolumeIO with the addition of +// the ability to pass a context and additional request options. +// +// See EnableVolumeIO 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) EnableVolumeIOWithContext(ctx aws.Context, input *EnableVolumeIOInput, opts ...request.Option) (*EnableVolumeIOOutput, error) { + req, out := c.EnableVolumeIORequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opEnableVpcClassicLink = "EnableVpcClassicLink" @@ -11522,8 +14380,23 @@ func (c *EC2) EnableVpcClassicLinkRequest(input *EnableVpcClassicLinkInput) (req // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/EnableVpcClassicLink func (c *EC2) EnableVpcClassicLink(input *EnableVpcClassicLinkInput) (*EnableVpcClassicLinkOutput, error) { req, out := c.EnableVpcClassicLinkRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// EnableVpcClassicLinkWithContext is the same as EnableVpcClassicLink with the addition of +// the ability to pass a context and additional request options. +// +// See EnableVpcClassicLink 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) EnableVpcClassicLinkWithContext(ctx aws.Context, input *EnableVpcClassicLinkInput, opts ...request.Option) (*EnableVpcClassicLinkOutput, error) { + req, out := c.EnableVpcClassicLinkRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opEnableVpcClassicLinkDnsSupport = "EnableVpcClassicLinkDnsSupport" @@ -11588,8 +14461,23 @@ func (c *EC2) EnableVpcClassicLinkDnsSupportRequest(input *EnableVpcClassicLinkD // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/EnableVpcClassicLinkDnsSupport func (c *EC2) EnableVpcClassicLinkDnsSupport(input *EnableVpcClassicLinkDnsSupportInput) (*EnableVpcClassicLinkDnsSupportOutput, error) { req, out := c.EnableVpcClassicLinkDnsSupportRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// EnableVpcClassicLinkDnsSupportWithContext is the same as EnableVpcClassicLinkDnsSupport with the addition of +// the ability to pass a context and additional request options. +// +// See EnableVpcClassicLinkDnsSupport 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) EnableVpcClassicLinkDnsSupportWithContext(ctx aws.Context, input *EnableVpcClassicLinkDnsSupportInput, opts ...request.Option) (*EnableVpcClassicLinkDnsSupportOutput, error) { + req, out := c.EnableVpcClassicLinkDnsSupportRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetConsoleOutput = "GetConsoleOutput" @@ -11665,8 +14553,23 @@ func (c *EC2) GetConsoleOutputRequest(input *GetConsoleOutputInput) (req *reques // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/GetConsoleOutput func (c *EC2) GetConsoleOutput(input *GetConsoleOutputInput) (*GetConsoleOutputOutput, error) { req, out := c.GetConsoleOutputRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetConsoleOutputWithContext is the same as GetConsoleOutput with the addition of +// the ability to pass a context and additional request options. +// +// See GetConsoleOutput 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) GetConsoleOutputWithContext(ctx aws.Context, input *GetConsoleOutputInput, opts ...request.Option) (*GetConsoleOutputOutput, error) { + req, out := c.GetConsoleOutputRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetConsoleScreenshot = "GetConsoleScreenshot" @@ -11727,8 +14630,23 @@ func (c *EC2) GetConsoleScreenshotRequest(input *GetConsoleScreenshotInput) (req // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/GetConsoleScreenshot func (c *EC2) GetConsoleScreenshot(input *GetConsoleScreenshotInput) (*GetConsoleScreenshotOutput, error) { req, out := c.GetConsoleScreenshotRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetConsoleScreenshotWithContext is the same as GetConsoleScreenshot with the addition of +// the ability to pass a context and additional request options. +// +// See GetConsoleScreenshot 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) GetConsoleScreenshotWithContext(ctx aws.Context, input *GetConsoleScreenshotInput, opts ...request.Option) (*GetConsoleScreenshotOutput, error) { + req, out := c.GetConsoleScreenshotRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetHostReservationPurchasePreview = "GetHostReservationPurchasePreview" @@ -11792,8 +14710,23 @@ func (c *EC2) GetHostReservationPurchasePreviewRequest(input *GetHostReservation // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/GetHostReservationPurchasePreview func (c *EC2) GetHostReservationPurchasePreview(input *GetHostReservationPurchasePreviewInput) (*GetHostReservationPurchasePreviewOutput, error) { req, out := c.GetHostReservationPurchasePreviewRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetHostReservationPurchasePreviewWithContext is the same as GetHostReservationPurchasePreview with the addition of +// the ability to pass a context and additional request options. +// +// See GetHostReservationPurchasePreview 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) GetHostReservationPurchasePreviewWithContext(ctx aws.Context, input *GetHostReservationPurchasePreviewInput, opts ...request.Option) (*GetHostReservationPurchasePreviewOutput, error) { + req, out := c.GetHostReservationPurchasePreviewRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetPasswordData = "GetPasswordData" @@ -11865,8 +14798,23 @@ func (c *EC2) GetPasswordDataRequest(input *GetPasswordDataInput) (req *request. // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/GetPasswordData func (c *EC2) GetPasswordData(input *GetPasswordDataInput) (*GetPasswordDataOutput, error) { req, out := c.GetPasswordDataRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetPasswordDataWithContext is the same as GetPasswordData with the addition of +// the ability to pass a context and additional request options. +// +// See GetPasswordData 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) GetPasswordDataWithContext(ctx aws.Context, input *GetPasswordDataInput, opts ...request.Option) (*GetPasswordDataOutput, error) { + req, out := c.GetPasswordDataRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetReservedInstancesExchangeQuote = "GetReservedInstancesExchangeQuote" @@ -11927,8 +14875,23 @@ func (c *EC2) GetReservedInstancesExchangeQuoteRequest(input *GetReservedInstanc // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/GetReservedInstancesExchangeQuote func (c *EC2) GetReservedInstancesExchangeQuote(input *GetReservedInstancesExchangeQuoteInput) (*GetReservedInstancesExchangeQuoteOutput, error) { req, out := c.GetReservedInstancesExchangeQuoteRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetReservedInstancesExchangeQuoteWithContext is the same as GetReservedInstancesExchangeQuote with the addition of +// the ability to pass a context and additional request options. +// +// See GetReservedInstancesExchangeQuote 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) GetReservedInstancesExchangeQuoteWithContext(ctx aws.Context, input *GetReservedInstancesExchangeQuoteInput, opts ...request.Option) (*GetReservedInstancesExchangeQuoteOutput, error) { + req, out := c.GetReservedInstancesExchangeQuoteRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opImportImage = "ImportImage" @@ -11990,8 +14953,23 @@ func (c *EC2) ImportImageRequest(input *ImportImageInput) (req *request.Request, // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ImportImage func (c *EC2) ImportImage(input *ImportImageInput) (*ImportImageOutput, error) { req, out := c.ImportImageRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ImportImageWithContext is the same as ImportImage with the addition of +// the ability to pass a context and additional request options. +// +// See ImportImage 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) ImportImageWithContext(ctx aws.Context, input *ImportImageInput, opts ...request.Option) (*ImportImageOutput, error) { + req, out := c.ImportImageRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opImportInstance = "ImportInstance" @@ -12056,8 +15034,23 @@ func (c *EC2) ImportInstanceRequest(input *ImportInstanceInput) (req *request.Re // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ImportInstance func (c *EC2) ImportInstance(input *ImportInstanceInput) (*ImportInstanceOutput, error) { req, out := c.ImportInstanceRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ImportInstanceWithContext is the same as ImportInstance with the addition of +// the ability to pass a context and additional request options. +// +// See ImportInstance 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) ImportInstanceWithContext(ctx aws.Context, input *ImportInstanceInput, opts ...request.Option) (*ImportInstanceOutput, error) { + req, out := c.ImportInstanceRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opImportKeyPair = "ImportKeyPair" @@ -12123,8 +15116,23 @@ func (c *EC2) ImportKeyPairRequest(input *ImportKeyPairInput) (req *request.Requ // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ImportKeyPair func (c *EC2) ImportKeyPair(input *ImportKeyPairInput) (*ImportKeyPairOutput, error) { req, out := c.ImportKeyPairRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ImportKeyPairWithContext is the same as ImportKeyPair with the addition of +// the ability to pass a context and additional request options. +// +// See ImportKeyPair 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) ImportKeyPairWithContext(ctx aws.Context, input *ImportKeyPairInput, opts ...request.Option) (*ImportKeyPairOutput, error) { + req, out := c.ImportKeyPairRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opImportSnapshot = "ImportSnapshot" @@ -12183,8 +15191,23 @@ func (c *EC2) ImportSnapshotRequest(input *ImportSnapshotInput) (req *request.Re // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ImportSnapshot func (c *EC2) ImportSnapshot(input *ImportSnapshotInput) (*ImportSnapshotOutput, error) { req, out := c.ImportSnapshotRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ImportSnapshotWithContext is the same as ImportSnapshot with the addition of +// the ability to pass a context and additional request options. +// +// See ImportSnapshot 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) ImportSnapshotWithContext(ctx aws.Context, input *ImportSnapshotInput, opts ...request.Option) (*ImportSnapshotOutput, error) { + req, out := c.ImportSnapshotRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opImportVolume = "ImportVolume" @@ -12247,8 +15270,23 @@ func (c *EC2) ImportVolumeRequest(input *ImportVolumeInput) (req *request.Reques // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ImportVolume func (c *EC2) ImportVolume(input *ImportVolumeInput) (*ImportVolumeOutput, error) { req, out := c.ImportVolumeRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ImportVolumeWithContext is the same as ImportVolume with the addition of +// the ability to pass a context and additional request options. +// +// See ImportVolume 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) ImportVolumeWithContext(ctx aws.Context, input *ImportVolumeInput, opts ...request.Option) (*ImportVolumeOutput, error) { + req, out := c.ImportVolumeRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opModifyHosts = "ModifyHosts" @@ -12313,8 +15351,23 @@ func (c *EC2) ModifyHostsRequest(input *ModifyHostsInput) (req *request.Request, // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ModifyHosts func (c *EC2) ModifyHosts(input *ModifyHostsInput) (*ModifyHostsOutput, error) { req, out := c.ModifyHostsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ModifyHostsWithContext is the same as ModifyHosts with the addition of +// the ability to pass a context and additional request options. +// +// See ModifyHosts 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) ModifyHostsWithContext(ctx aws.Context, input *ModifyHostsInput, opts ...request.Option) (*ModifyHostsOutput, error) { + req, out := c.ModifyHostsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opModifyIdFormat = "ModifyIdFormat" @@ -12389,8 +15442,23 @@ func (c *EC2) ModifyIdFormatRequest(input *ModifyIdFormatInput) (req *request.Re // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ModifyIdFormat func (c *EC2) ModifyIdFormat(input *ModifyIdFormatInput) (*ModifyIdFormatOutput, error) { req, out := c.ModifyIdFormatRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ModifyIdFormatWithContext is the same as ModifyIdFormat with the addition of +// the ability to pass a context and additional request options. +// +// See ModifyIdFormat 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) ModifyIdFormatWithContext(ctx aws.Context, input *ModifyIdFormatInput, opts ...request.Option) (*ModifyIdFormatOutput, error) { + req, out := c.ModifyIdFormatRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opModifyIdentityIdFormat = "ModifyIdentityIdFormat" @@ -12465,8 +15533,23 @@ func (c *EC2) ModifyIdentityIdFormatRequest(input *ModifyIdentityIdFormatInput) // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ModifyIdentityIdFormat func (c *EC2) ModifyIdentityIdFormat(input *ModifyIdentityIdFormatInput) (*ModifyIdentityIdFormatOutput, error) { req, out := c.ModifyIdentityIdFormatRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ModifyIdentityIdFormatWithContext is the same as ModifyIdentityIdFormat with the addition of +// the ability to pass a context and additional request options. +// +// See ModifyIdentityIdFormat 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) ModifyIdentityIdFormatWithContext(ctx aws.Context, input *ModifyIdentityIdFormatInput, opts ...request.Option) (*ModifyIdentityIdFormatOutput, error) { + req, out := c.ModifyIdentityIdFormatRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opModifyImageAttribute = "ModifyImageAttribute" @@ -12536,8 +15619,23 @@ func (c *EC2) ModifyImageAttributeRequest(input *ModifyImageAttributeInput) (req // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ModifyImageAttribute func (c *EC2) ModifyImageAttribute(input *ModifyImageAttributeInput) (*ModifyImageAttributeOutput, error) { req, out := c.ModifyImageAttributeRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ModifyImageAttributeWithContext is the same as ModifyImageAttribute with the addition of +// the ability to pass a context and additional request options. +// +// See ModifyImageAttribute 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) ModifyImageAttributeWithContext(ctx aws.Context, input *ModifyImageAttributeInput, opts ...request.Option) (*ModifyImageAttributeOutput, error) { + req, out := c.ModifyImageAttributeRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opModifyInstanceAttribute = "ModifyInstanceAttribute" @@ -12603,8 +15701,23 @@ func (c *EC2) ModifyInstanceAttributeRequest(input *ModifyInstanceAttributeInput // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ModifyInstanceAttribute func (c *EC2) ModifyInstanceAttribute(input *ModifyInstanceAttributeInput) (*ModifyInstanceAttributeOutput, error) { req, out := c.ModifyInstanceAttributeRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ModifyInstanceAttributeWithContext is the same as ModifyInstanceAttribute with the addition of +// the ability to pass a context and additional request options. +// +// See ModifyInstanceAttribute 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) ModifyInstanceAttributeWithContext(ctx aws.Context, input *ModifyInstanceAttributeInput, opts ...request.Option) (*ModifyInstanceAttributeOutput, error) { + req, out := c.ModifyInstanceAttributeRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opModifyInstancePlacement = "ModifyInstancePlacement" @@ -12681,8 +15794,23 @@ func (c *EC2) ModifyInstancePlacementRequest(input *ModifyInstancePlacementInput // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ModifyInstancePlacement func (c *EC2) ModifyInstancePlacement(input *ModifyInstancePlacementInput) (*ModifyInstancePlacementOutput, error) { req, out := c.ModifyInstancePlacementRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ModifyInstancePlacementWithContext is the same as ModifyInstancePlacement with the addition of +// the ability to pass a context and additional request options. +// +// See ModifyInstancePlacement 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) ModifyInstancePlacementWithContext(ctx aws.Context, input *ModifyInstancePlacementInput, opts ...request.Option) (*ModifyInstancePlacementOutput, error) { + req, out := c.ModifyInstancePlacementRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opModifyNetworkInterfaceAttribute = "ModifyNetworkInterfaceAttribute" @@ -12744,8 +15872,23 @@ func (c *EC2) ModifyNetworkInterfaceAttributeRequest(input *ModifyNetworkInterfa // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ModifyNetworkInterfaceAttribute func (c *EC2) ModifyNetworkInterfaceAttribute(input *ModifyNetworkInterfaceAttributeInput) (*ModifyNetworkInterfaceAttributeOutput, error) { req, out := c.ModifyNetworkInterfaceAttributeRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ModifyNetworkInterfaceAttributeWithContext is the same as ModifyNetworkInterfaceAttribute with the addition of +// the ability to pass a context and additional request options. +// +// See ModifyNetworkInterfaceAttribute 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) ModifyNetworkInterfaceAttributeWithContext(ctx aws.Context, input *ModifyNetworkInterfaceAttributeInput, opts ...request.Option) (*ModifyNetworkInterfaceAttributeOutput, error) { + req, out := c.ModifyNetworkInterfaceAttributeRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opModifyReservedInstances = "ModifyReservedInstances" @@ -12810,8 +15953,23 @@ func (c *EC2) ModifyReservedInstancesRequest(input *ModifyReservedInstancesInput // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ModifyReservedInstances func (c *EC2) ModifyReservedInstances(input *ModifyReservedInstancesInput) (*ModifyReservedInstancesOutput, error) { req, out := c.ModifyReservedInstancesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ModifyReservedInstancesWithContext is the same as ModifyReservedInstances with the addition of +// the ability to pass a context and additional request options. +// +// See ModifyReservedInstances 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) ModifyReservedInstancesWithContext(ctx aws.Context, input *ModifyReservedInstancesInput, opts ...request.Option) (*ModifyReservedInstancesOutput, error) { + req, out := c.ModifyReservedInstancesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opModifySnapshotAttribute = "ModifySnapshotAttribute" @@ -12884,8 +16042,23 @@ func (c *EC2) ModifySnapshotAttributeRequest(input *ModifySnapshotAttributeInput // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ModifySnapshotAttribute func (c *EC2) ModifySnapshotAttribute(input *ModifySnapshotAttributeInput) (*ModifySnapshotAttributeOutput, error) { req, out := c.ModifySnapshotAttributeRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ModifySnapshotAttributeWithContext is the same as ModifySnapshotAttribute with the addition of +// the ability to pass a context and additional request options. +// +// See ModifySnapshotAttribute 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) ModifySnapshotAttributeWithContext(ctx aws.Context, input *ModifySnapshotAttributeInput, opts ...request.Option) (*ModifySnapshotAttributeOutput, error) { + req, out := c.ModifySnapshotAttributeRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opModifySpotFleetRequest = "ModifySpotFleetRequest" @@ -12963,8 +16136,23 @@ func (c *EC2) ModifySpotFleetRequestRequest(input *ModifySpotFleetRequestInput) // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ModifySpotFleetRequest func (c *EC2) ModifySpotFleetRequest(input *ModifySpotFleetRequestInput) (*ModifySpotFleetRequestOutput, error) { req, out := c.ModifySpotFleetRequestRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ModifySpotFleetRequestWithContext is the same as ModifySpotFleetRequest with the addition of +// the ability to pass a context and additional request options. +// +// See ModifySpotFleetRequest 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) ModifySpotFleetRequestWithContext(ctx aws.Context, input *ModifySpotFleetRequestInput, opts ...request.Option) (*ModifySpotFleetRequestOutput, error) { + req, out := c.ModifySpotFleetRequestRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opModifySubnetAttribute = "ModifySubnetAttribute" @@ -13025,8 +16213,23 @@ func (c *EC2) ModifySubnetAttributeRequest(input *ModifySubnetAttributeInput) (r // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ModifySubnetAttribute func (c *EC2) ModifySubnetAttribute(input *ModifySubnetAttributeInput) (*ModifySubnetAttributeOutput, error) { req, out := c.ModifySubnetAttributeRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ModifySubnetAttributeWithContext is the same as ModifySubnetAttribute with the addition of +// the ability to pass a context and additional request options. +// +// See ModifySubnetAttribute 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) ModifySubnetAttributeWithContext(ctx aws.Context, input *ModifySubnetAttributeInput, opts ...request.Option) (*ModifySubnetAttributeOutput, error) { + req, out := c.ModifySubnetAttributeRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opModifyVolume = "ModifyVolume" @@ -13117,8 +16320,23 @@ func (c *EC2) ModifyVolumeRequest(input *ModifyVolumeInput) (req *request.Reques // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ModifyVolume func (c *EC2) ModifyVolume(input *ModifyVolumeInput) (*ModifyVolumeOutput, error) { req, out := c.ModifyVolumeRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ModifyVolumeWithContext is the same as ModifyVolume with the addition of +// the ability to pass a context and additional request options. +// +// See ModifyVolume 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) ModifyVolumeWithContext(ctx aws.Context, input *ModifyVolumeInput, opts ...request.Option) (*ModifyVolumeOutput, error) { + req, out := c.ModifyVolumeRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opModifyVolumeAttribute = "ModifyVolumeAttribute" @@ -13188,8 +16406,23 @@ func (c *EC2) ModifyVolumeAttributeRequest(input *ModifyVolumeAttributeInput) (r // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ModifyVolumeAttribute func (c *EC2) ModifyVolumeAttribute(input *ModifyVolumeAttributeInput) (*ModifyVolumeAttributeOutput, error) { req, out := c.ModifyVolumeAttributeRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ModifyVolumeAttributeWithContext is the same as ModifyVolumeAttribute with the addition of +// the ability to pass a context and additional request options. +// +// See ModifyVolumeAttribute 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) ModifyVolumeAttributeWithContext(ctx aws.Context, input *ModifyVolumeAttributeInput, opts ...request.Option) (*ModifyVolumeAttributeOutput, error) { + req, out := c.ModifyVolumeAttributeRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opModifyVpcAttribute = "ModifyVpcAttribute" @@ -13250,8 +16483,23 @@ func (c *EC2) ModifyVpcAttributeRequest(input *ModifyVpcAttributeInput) (req *re // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ModifyVpcAttribute func (c *EC2) ModifyVpcAttribute(input *ModifyVpcAttributeInput) (*ModifyVpcAttributeOutput, error) { req, out := c.ModifyVpcAttributeRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ModifyVpcAttributeWithContext is the same as ModifyVpcAttribute with the addition of +// the ability to pass a context and additional request options. +// +// See ModifyVpcAttribute 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) ModifyVpcAttributeWithContext(ctx aws.Context, input *ModifyVpcAttributeInput, opts ...request.Option) (*ModifyVpcAttributeOutput, error) { + req, out := c.ModifyVpcAttributeRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opModifyVpcEndpoint = "ModifyVpcEndpoint" @@ -13312,8 +16560,23 @@ func (c *EC2) ModifyVpcEndpointRequest(input *ModifyVpcEndpointInput) (req *requ // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ModifyVpcEndpoint func (c *EC2) ModifyVpcEndpoint(input *ModifyVpcEndpointInput) (*ModifyVpcEndpointOutput, error) { req, out := c.ModifyVpcEndpointRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ModifyVpcEndpointWithContext is the same as ModifyVpcEndpoint with the addition of +// the ability to pass a context and additional request options. +// +// See ModifyVpcEndpoint 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) ModifyVpcEndpointWithContext(ctx aws.Context, input *ModifyVpcEndpointInput, opts ...request.Option) (*ModifyVpcEndpointOutput, error) { + req, out := c.ModifyVpcEndpointRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opModifyVpcPeeringConnectionOptions = "ModifyVpcPeeringConnectionOptions" @@ -13391,8 +16654,23 @@ func (c *EC2) ModifyVpcPeeringConnectionOptionsRequest(input *ModifyVpcPeeringCo // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ModifyVpcPeeringConnectionOptions func (c *EC2) ModifyVpcPeeringConnectionOptions(input *ModifyVpcPeeringConnectionOptionsInput) (*ModifyVpcPeeringConnectionOptionsOutput, error) { req, out := c.ModifyVpcPeeringConnectionOptionsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ModifyVpcPeeringConnectionOptionsWithContext is the same as ModifyVpcPeeringConnectionOptions with the addition of +// the ability to pass a context and additional request options. +// +// See ModifyVpcPeeringConnectionOptions 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) ModifyVpcPeeringConnectionOptionsWithContext(ctx aws.Context, input *ModifyVpcPeeringConnectionOptionsInput, opts ...request.Option) (*ModifyVpcPeeringConnectionOptionsOutput, error) { + req, out := c.ModifyVpcPeeringConnectionOptionsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opMonitorInstances = "MonitorInstances" @@ -13456,8 +16734,23 @@ func (c *EC2) MonitorInstancesRequest(input *MonitorInstancesInput) (req *reques // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/MonitorInstances func (c *EC2) MonitorInstances(input *MonitorInstancesInput) (*MonitorInstancesOutput, error) { req, out := c.MonitorInstancesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// MonitorInstancesWithContext is the same as MonitorInstances with the addition of +// the ability to pass a context and additional request options. +// +// See MonitorInstances 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) MonitorInstancesWithContext(ctx aws.Context, input *MonitorInstancesInput, opts ...request.Option) (*MonitorInstancesOutput, error) { + req, out := c.MonitorInstancesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opMoveAddressToVpc = "MoveAddressToVpc" @@ -13522,8 +16815,23 @@ func (c *EC2) MoveAddressToVpcRequest(input *MoveAddressToVpcInput) (req *reques // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/MoveAddressToVpc func (c *EC2) MoveAddressToVpc(input *MoveAddressToVpcInput) (*MoveAddressToVpcOutput, error) { req, out := c.MoveAddressToVpcRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// MoveAddressToVpcWithContext is the same as MoveAddressToVpc with the addition of +// the ability to pass a context and additional request options. +// +// See MoveAddressToVpc 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) MoveAddressToVpcWithContext(ctx aws.Context, input *MoveAddressToVpcInput, opts ...request.Option) (*MoveAddressToVpcOutput, error) { + req, out := c.MoveAddressToVpcRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opPurchaseHostReservation = "PurchaseHostReservation" @@ -13585,8 +16893,23 @@ func (c *EC2) PurchaseHostReservationRequest(input *PurchaseHostReservationInput // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/PurchaseHostReservation func (c *EC2) PurchaseHostReservation(input *PurchaseHostReservationInput) (*PurchaseHostReservationOutput, error) { req, out := c.PurchaseHostReservationRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// PurchaseHostReservationWithContext is the same as PurchaseHostReservation with the addition of +// the ability to pass a context and additional request options. +// +// See PurchaseHostReservation 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) PurchaseHostReservationWithContext(ctx aws.Context, input *PurchaseHostReservationInput, opts ...request.Option) (*PurchaseHostReservationOutput, error) { + req, out := c.PurchaseHostReservationRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opPurchaseReservedInstancesOffering = "PurchaseReservedInstancesOffering" @@ -13654,8 +16977,23 @@ func (c *EC2) PurchaseReservedInstancesOfferingRequest(input *PurchaseReservedIn // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/PurchaseReservedInstancesOffering func (c *EC2) PurchaseReservedInstancesOffering(input *PurchaseReservedInstancesOfferingInput) (*PurchaseReservedInstancesOfferingOutput, error) { req, out := c.PurchaseReservedInstancesOfferingRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// PurchaseReservedInstancesOfferingWithContext is the same as PurchaseReservedInstancesOffering with the addition of +// the ability to pass a context and additional request options. +// +// See PurchaseReservedInstancesOffering 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) PurchaseReservedInstancesOfferingWithContext(ctx aws.Context, input *PurchaseReservedInstancesOfferingInput, opts ...request.Option) (*PurchaseReservedInstancesOfferingOutput, error) { + req, out := c.PurchaseReservedInstancesOfferingRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opPurchaseScheduledInstances = "PurchaseScheduledInstances" @@ -13723,8 +17061,23 @@ func (c *EC2) PurchaseScheduledInstancesRequest(input *PurchaseScheduledInstance // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/PurchaseScheduledInstances func (c *EC2) PurchaseScheduledInstances(input *PurchaseScheduledInstancesInput) (*PurchaseScheduledInstancesOutput, error) { req, out := c.PurchaseScheduledInstancesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// PurchaseScheduledInstancesWithContext is the same as PurchaseScheduledInstances with the addition of +// the ability to pass a context and additional request options. +// +// See PurchaseScheduledInstances 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) PurchaseScheduledInstancesWithContext(ctx aws.Context, input *PurchaseScheduledInstancesInput, opts ...request.Option) (*PurchaseScheduledInstancesOutput, error) { + req, out := c.PurchaseScheduledInstancesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opRebootInstances = "RebootInstances" @@ -13795,8 +17148,23 @@ func (c *EC2) RebootInstancesRequest(input *RebootInstancesInput) (req *request. // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/RebootInstances func (c *EC2) RebootInstances(input *RebootInstancesInput) (*RebootInstancesOutput, error) { req, out := c.RebootInstancesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// RebootInstancesWithContext is the same as RebootInstances with the addition of +// the ability to pass a context and additional request options. +// +// See RebootInstances 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) RebootInstancesWithContext(ctx aws.Context, input *RebootInstancesInput, opts ...request.Option) (*RebootInstancesOutput, error) { + req, out := c.RebootInstancesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opRegisterImage = "RegisterImage" @@ -13854,8 +17222,8 @@ 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 an Instance from a Snapshot -// (http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_LaunchingInstanceFromSnapshot.html) +// device mapping. For more information, see Launching a Linux Instance from +// a Backup (http://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 @@ -13883,8 +17251,23 @@ func (c *EC2) RegisterImageRequest(input *RegisterImageInput) (req *request.Requ // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/RegisterImage func (c *EC2) RegisterImage(input *RegisterImageInput) (*RegisterImageOutput, error) { req, out := c.RegisterImageRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// RegisterImageWithContext is the same as RegisterImage with the addition of +// the ability to pass a context and additional request options. +// +// See RegisterImage 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) RegisterImageWithContext(ctx aws.Context, input *RegisterImageInput, opts ...request.Option) (*RegisterImageOutput, error) { + req, out := c.RegisterImageRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opRejectVpcPeeringConnection = "RejectVpcPeeringConnection" @@ -13947,8 +17330,23 @@ func (c *EC2) RejectVpcPeeringConnectionRequest(input *RejectVpcPeeringConnectio // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/RejectVpcPeeringConnection func (c *EC2) RejectVpcPeeringConnection(input *RejectVpcPeeringConnectionInput) (*RejectVpcPeeringConnectionOutput, error) { req, out := c.RejectVpcPeeringConnectionRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// RejectVpcPeeringConnectionWithContext is the same as RejectVpcPeeringConnection with the addition of +// the ability to pass a context and additional request options. +// +// See RejectVpcPeeringConnection 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) RejectVpcPeeringConnectionWithContext(ctx aws.Context, input *RejectVpcPeeringConnectionInput, opts ...request.Option) (*RejectVpcPeeringConnectionOutput, error) { + req, out := c.RejectVpcPeeringConnectionRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opReleaseAddress = "ReleaseAddress" @@ -14023,8 +17421,23 @@ func (c *EC2) ReleaseAddressRequest(input *ReleaseAddressInput) (req *request.Re // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ReleaseAddress func (c *EC2) ReleaseAddress(input *ReleaseAddressInput) (*ReleaseAddressOutput, error) { req, out := c.ReleaseAddressRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ReleaseAddressWithContext is the same as ReleaseAddress with the addition of +// the ability to pass a context and additional request options. +// +// See ReleaseAddress 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) ReleaseAddressWithContext(ctx aws.Context, input *ReleaseAddressInput, opts ...request.Option) (*ReleaseAddressOutput, error) { + req, out := c.ReleaseAddressRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opReleaseHosts = "ReleaseHosts" @@ -14094,8 +17507,23 @@ func (c *EC2) ReleaseHostsRequest(input *ReleaseHostsInput) (req *request.Reques // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ReleaseHosts func (c *EC2) ReleaseHosts(input *ReleaseHostsInput) (*ReleaseHostsOutput, error) { req, out := c.ReleaseHostsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ReleaseHostsWithContext is the same as ReleaseHosts with the addition of +// the ability to pass a context and additional request options. +// +// See ReleaseHosts 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) ReleaseHostsWithContext(ctx aws.Context, input *ReleaseHostsInput, opts ...request.Option) (*ReleaseHostsOutput, error) { + req, out := c.ReleaseHostsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opReplaceIamInstanceProfileAssociation = "ReplaceIamInstanceProfileAssociation" @@ -14159,8 +17587,23 @@ func (c *EC2) ReplaceIamInstanceProfileAssociationRequest(input *ReplaceIamInsta // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ReplaceIamInstanceProfileAssociation func (c *EC2) ReplaceIamInstanceProfileAssociation(input *ReplaceIamInstanceProfileAssociationInput) (*ReplaceIamInstanceProfileAssociationOutput, error) { req, out := c.ReplaceIamInstanceProfileAssociationRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ReplaceIamInstanceProfileAssociationWithContext is the same as ReplaceIamInstanceProfileAssociation with the addition of +// the ability to pass a context and additional request options. +// +// See ReplaceIamInstanceProfileAssociation 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) ReplaceIamInstanceProfileAssociationWithContext(ctx aws.Context, input *ReplaceIamInstanceProfileAssociationInput, opts ...request.Option) (*ReplaceIamInstanceProfileAssociationOutput, error) { + req, out := c.ReplaceIamInstanceProfileAssociationRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opReplaceNetworkAclAssociation = "ReplaceNetworkAclAssociation" @@ -14222,8 +17665,23 @@ func (c *EC2) ReplaceNetworkAclAssociationRequest(input *ReplaceNetworkAclAssoci // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ReplaceNetworkAclAssociation func (c *EC2) ReplaceNetworkAclAssociation(input *ReplaceNetworkAclAssociationInput) (*ReplaceNetworkAclAssociationOutput, error) { req, out := c.ReplaceNetworkAclAssociationRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ReplaceNetworkAclAssociationWithContext is the same as ReplaceNetworkAclAssociation with the addition of +// the ability to pass a context and additional request options. +// +// See ReplaceNetworkAclAssociation 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) ReplaceNetworkAclAssociationWithContext(ctx aws.Context, input *ReplaceNetworkAclAssociationInput, opts ...request.Option) (*ReplaceNetworkAclAssociationOutput, error) { + req, out := c.ReplaceNetworkAclAssociationRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opReplaceNetworkAclEntry = "ReplaceNetworkAclEntry" @@ -14286,8 +17744,23 @@ func (c *EC2) ReplaceNetworkAclEntryRequest(input *ReplaceNetworkAclEntryInput) // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ReplaceNetworkAclEntry func (c *EC2) ReplaceNetworkAclEntry(input *ReplaceNetworkAclEntryInput) (*ReplaceNetworkAclEntryOutput, error) { req, out := c.ReplaceNetworkAclEntryRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ReplaceNetworkAclEntryWithContext is the same as ReplaceNetworkAclEntry with the addition of +// the ability to pass a context and additional request options. +// +// See ReplaceNetworkAclEntry 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) ReplaceNetworkAclEntryWithContext(ctx aws.Context, input *ReplaceNetworkAclEntryInput, opts ...request.Option) (*ReplaceNetworkAclEntryOutput, error) { + req, out := c.ReplaceNetworkAclEntryRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opReplaceRoute = "ReplaceRoute" @@ -14354,8 +17827,23 @@ func (c *EC2) ReplaceRouteRequest(input *ReplaceRouteInput) (req *request.Reques // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ReplaceRoute func (c *EC2) ReplaceRoute(input *ReplaceRouteInput) (*ReplaceRouteOutput, error) { req, out := c.ReplaceRouteRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ReplaceRouteWithContext is the same as ReplaceRoute with the addition of +// the ability to pass a context and additional request options. +// +// See ReplaceRoute 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) ReplaceRouteWithContext(ctx aws.Context, input *ReplaceRouteInput, opts ...request.Option) (*ReplaceRouteOutput, error) { + req, out := c.ReplaceRouteRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opReplaceRouteTableAssociation = "ReplaceRouteTableAssociation" @@ -14422,8 +17910,23 @@ func (c *EC2) ReplaceRouteTableAssociationRequest(input *ReplaceRouteTableAssoci // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ReplaceRouteTableAssociation func (c *EC2) ReplaceRouteTableAssociation(input *ReplaceRouteTableAssociationInput) (*ReplaceRouteTableAssociationOutput, error) { req, out := c.ReplaceRouteTableAssociationRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ReplaceRouteTableAssociationWithContext is the same as ReplaceRouteTableAssociation with the addition of +// the ability to pass a context and additional request options. +// +// See ReplaceRouteTableAssociation 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) ReplaceRouteTableAssociationWithContext(ctx aws.Context, input *ReplaceRouteTableAssociationInput, opts ...request.Option) (*ReplaceRouteTableAssociationOutput, error) { + req, out := c.ReplaceRouteTableAssociationRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opReportInstanceStatus = "ReportInstanceStatus" @@ -14490,8 +17993,23 @@ func (c *EC2) ReportInstanceStatusRequest(input *ReportInstanceStatusInput) (req // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ReportInstanceStatus func (c *EC2) ReportInstanceStatus(input *ReportInstanceStatusInput) (*ReportInstanceStatusOutput, error) { req, out := c.ReportInstanceStatusRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ReportInstanceStatusWithContext is the same as ReportInstanceStatus with the addition of +// the ability to pass a context and additional request options. +// +// See ReportInstanceStatus 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) ReportInstanceStatusWithContext(ctx aws.Context, input *ReportInstanceStatusInput, opts ...request.Option) (*ReportInstanceStatusOutput, error) { + req, out := c.ReportInstanceStatusRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opRequestSpotFleet = "RequestSpotFleet" @@ -14566,8 +18084,23 @@ func (c *EC2) RequestSpotFleetRequest(input *RequestSpotFleetInput) (req *reques // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/RequestSpotFleet func (c *EC2) RequestSpotFleet(input *RequestSpotFleetInput) (*RequestSpotFleetOutput, error) { req, out := c.RequestSpotFleetRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// RequestSpotFleetWithContext is the same as RequestSpotFleet with the addition of +// the ability to pass a context and additional request options. +// +// See RequestSpotFleet 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) RequestSpotFleetWithContext(ctx aws.Context, input *RequestSpotFleetInput, opts ...request.Option) (*RequestSpotFleetOutput, error) { + req, out := c.RequestSpotFleetRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opRequestSpotInstances = "RequestSpotInstances" @@ -14631,8 +18164,23 @@ func (c *EC2) RequestSpotInstancesRequest(input *RequestSpotInstancesInput) (req // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/RequestSpotInstances func (c *EC2) RequestSpotInstances(input *RequestSpotInstancesInput) (*RequestSpotInstancesOutput, error) { req, out := c.RequestSpotInstancesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// RequestSpotInstancesWithContext is the same as RequestSpotInstances with the addition of +// the ability to pass a context and additional request options. +// +// See RequestSpotInstances 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) RequestSpotInstancesWithContext(ctx aws.Context, input *RequestSpotInstancesInput, opts ...request.Option) (*RequestSpotInstancesOutput, error) { + req, out := c.RequestSpotInstancesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opResetImageAttribute = "ResetImageAttribute" @@ -14695,8 +18243,23 @@ func (c *EC2) ResetImageAttributeRequest(input *ResetImageAttributeInput) (req * // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ResetImageAttribute func (c *EC2) ResetImageAttribute(input *ResetImageAttributeInput) (*ResetImageAttributeOutput, error) { req, out := c.ResetImageAttributeRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ResetImageAttributeWithContext is the same as ResetImageAttribute with the addition of +// the ability to pass a context and additional request options. +// +// See ResetImageAttribute 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) ResetImageAttributeWithContext(ctx aws.Context, input *ResetImageAttributeInput, opts ...request.Option) (*ResetImageAttributeOutput, error) { + req, out := c.ResetImageAttributeRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opResetInstanceAttribute = "ResetInstanceAttribute" @@ -14765,8 +18328,23 @@ func (c *EC2) ResetInstanceAttributeRequest(input *ResetInstanceAttributeInput) // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ResetInstanceAttribute func (c *EC2) ResetInstanceAttribute(input *ResetInstanceAttributeInput) (*ResetInstanceAttributeOutput, error) { req, out := c.ResetInstanceAttributeRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ResetInstanceAttributeWithContext is the same as ResetInstanceAttribute with the addition of +// the ability to pass a context and additional request options. +// +// See ResetInstanceAttribute 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) ResetInstanceAttributeWithContext(ctx aws.Context, input *ResetInstanceAttributeInput, opts ...request.Option) (*ResetInstanceAttributeOutput, error) { + req, out := c.ResetInstanceAttributeRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opResetNetworkInterfaceAttribute = "ResetNetworkInterfaceAttribute" @@ -14828,8 +18406,23 @@ func (c *EC2) ResetNetworkInterfaceAttributeRequest(input *ResetNetworkInterface // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ResetNetworkInterfaceAttribute func (c *EC2) ResetNetworkInterfaceAttribute(input *ResetNetworkInterfaceAttributeInput) (*ResetNetworkInterfaceAttributeOutput, error) { req, out := c.ResetNetworkInterfaceAttributeRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ResetNetworkInterfaceAttributeWithContext is the same as ResetNetworkInterfaceAttribute with the addition of +// the ability to pass a context and additional request options. +// +// See ResetNetworkInterfaceAttribute 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) ResetNetworkInterfaceAttributeWithContext(ctx aws.Context, input *ResetNetworkInterfaceAttributeInput, opts ...request.Option) (*ResetNetworkInterfaceAttributeOutput, error) { + req, out := c.ResetNetworkInterfaceAttributeRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opResetSnapshotAttribute = "ResetSnapshotAttribute" @@ -14894,8 +18487,23 @@ func (c *EC2) ResetSnapshotAttributeRequest(input *ResetSnapshotAttributeInput) // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ResetSnapshotAttribute func (c *EC2) ResetSnapshotAttribute(input *ResetSnapshotAttributeInput) (*ResetSnapshotAttributeOutput, error) { req, out := c.ResetSnapshotAttributeRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ResetSnapshotAttributeWithContext is the same as ResetSnapshotAttribute with the addition of +// the ability to pass a context and additional request options. +// +// See ResetSnapshotAttribute 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) ResetSnapshotAttributeWithContext(ctx aws.Context, input *ResetSnapshotAttributeInput, opts ...request.Option) (*ResetSnapshotAttributeOutput, error) { + req, out := c.ResetSnapshotAttributeRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opRestoreAddressToClassic = "RestoreAddressToClassic" @@ -14957,8 +18565,23 @@ func (c *EC2) RestoreAddressToClassicRequest(input *RestoreAddressToClassicInput // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/RestoreAddressToClassic func (c *EC2) RestoreAddressToClassic(input *RestoreAddressToClassicInput) (*RestoreAddressToClassicOutput, error) { req, out := c.RestoreAddressToClassicRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// RestoreAddressToClassicWithContext is the same as RestoreAddressToClassic with the addition of +// the ability to pass a context and additional request options. +// +// See RestoreAddressToClassic 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) RestoreAddressToClassicWithContext(ctx aws.Context, input *RestoreAddressToClassicInput, opts ...request.Option) (*RestoreAddressToClassicOutput, error) { + req, out := c.RestoreAddressToClassicRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opRevokeSecurityGroupEgress = "RevokeSecurityGroupEgress" @@ -15030,8 +18653,23 @@ func (c *EC2) RevokeSecurityGroupEgressRequest(input *RevokeSecurityGroupEgressI // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/RevokeSecurityGroupEgress func (c *EC2) RevokeSecurityGroupEgress(input *RevokeSecurityGroupEgressInput) (*RevokeSecurityGroupEgressOutput, error) { req, out := c.RevokeSecurityGroupEgressRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// RevokeSecurityGroupEgressWithContext is the same as RevokeSecurityGroupEgress with the addition of +// the ability to pass a context and additional request options. +// +// See RevokeSecurityGroupEgress 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) RevokeSecurityGroupEgressWithContext(ctx aws.Context, input *RevokeSecurityGroupEgressInput, opts ...request.Option) (*RevokeSecurityGroupEgressOutput, error) { + req, out := c.RevokeSecurityGroupEgressRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opRevokeSecurityGroupIngress = "RevokeSecurityGroupIngress" @@ -15102,8 +18740,23 @@ func (c *EC2) RevokeSecurityGroupIngressRequest(input *RevokeSecurityGroupIngres // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/RevokeSecurityGroupIngress func (c *EC2) RevokeSecurityGroupIngress(input *RevokeSecurityGroupIngressInput) (*RevokeSecurityGroupIngressOutput, error) { req, out := c.RevokeSecurityGroupIngressRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// RevokeSecurityGroupIngressWithContext is the same as RevokeSecurityGroupIngress with the addition of +// the ability to pass a context and additional request options. +// +// See RevokeSecurityGroupIngress 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) RevokeSecurityGroupIngressWithContext(ctx aws.Context, input *RevokeSecurityGroupIngressInput, opts ...request.Option) (*RevokeSecurityGroupIngressOutput, error) { + req, out := c.RevokeSecurityGroupIngressRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opRunInstances = "RunInstances" @@ -15186,9 +18839,9 @@ func (c *EC2) RunInstancesRequest(input *RunInstancesInput) (req *request.Reques // each instead of 1 launch request for 500 instances. // // 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. After launch, you -// can apply tags to your running instance (requires a resource ID). For more -// information, see CreateTags and Tagging Your Amazon EC2 Resources (http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html). +// 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 (http://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 @@ -15210,8 +18863,23 @@ func (c *EC2) RunInstancesRequest(input *RunInstancesInput) (req *request.Reques // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/RunInstances func (c *EC2) RunInstances(input *RunInstancesInput) (*Reservation, error) { req, out := c.RunInstancesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// RunInstancesWithContext is the same as RunInstances with the addition of +// the ability to pass a context and additional request options. +// +// See RunInstances 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) RunInstancesWithContext(ctx aws.Context, input *RunInstancesInput, opts ...request.Option) (*Reservation, error) { + req, out := c.RunInstancesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opRunScheduledInstances = "RunScheduledInstances" @@ -15280,8 +18948,23 @@ func (c *EC2) RunScheduledInstancesRequest(input *RunScheduledInstancesInput) (r // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/RunScheduledInstances func (c *EC2) RunScheduledInstances(input *RunScheduledInstancesInput) (*RunScheduledInstancesOutput, error) { req, out := c.RunScheduledInstancesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// RunScheduledInstancesWithContext is the same as RunScheduledInstances with the addition of +// the ability to pass a context and additional request options. +// +// See RunScheduledInstances 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) RunScheduledInstancesWithContext(ctx aws.Context, input *RunScheduledInstancesInput, opts ...request.Option) (*RunScheduledInstancesOutput, error) { + req, out := c.RunScheduledInstancesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opStartInstances = "StartInstances" @@ -15358,8 +19041,23 @@ func (c *EC2) StartInstancesRequest(input *StartInstancesInput) (req *request.Re // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/StartInstances func (c *EC2) StartInstances(input *StartInstancesInput) (*StartInstancesOutput, error) { req, out := c.StartInstancesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// StartInstancesWithContext is the same as StartInstances with the addition of +// the ability to pass a context and additional request options. +// +// See StartInstances 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) StartInstancesWithContext(ctx aws.Context, input *StartInstancesInput, opts ...request.Option) (*StartInstancesOutput, error) { + req, out := c.StartInstancesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opStopInstances = "StopInstances" @@ -15447,8 +19145,23 @@ func (c *EC2) StopInstancesRequest(input *StopInstancesInput) (req *request.Requ // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/StopInstances func (c *EC2) StopInstances(input *StopInstancesInput) (*StopInstancesOutput, error) { req, out := c.StopInstancesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// StopInstancesWithContext is the same as StopInstances with the addition of +// the ability to pass a context and additional request options. +// +// See StopInstances 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) StopInstancesWithContext(ctx aws.Context, input *StopInstancesInput, opts ...request.Option) (*StopInstancesOutput, error) { + req, out := c.StopInstancesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opTerminateInstances = "TerminateInstances" @@ -15531,8 +19244,23 @@ func (c *EC2) TerminateInstancesRequest(input *TerminateInstancesInput) (req *re // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/TerminateInstances func (c *EC2) TerminateInstances(input *TerminateInstancesInput) (*TerminateInstancesOutput, error) { req, out := c.TerminateInstancesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// TerminateInstancesWithContext is the same as TerminateInstances with the addition of +// the ability to pass a context and additional request options. +// +// See TerminateInstances 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) TerminateInstancesWithContext(ctx aws.Context, input *TerminateInstancesInput, opts ...request.Option) (*TerminateInstancesOutput, error) { + req, out := c.TerminateInstancesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opUnassignIpv6Addresses = "UnassignIpv6Addresses" @@ -15591,8 +19319,23 @@ func (c *EC2) UnassignIpv6AddressesRequest(input *UnassignIpv6AddressesInput) (r // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/UnassignIpv6Addresses func (c *EC2) UnassignIpv6Addresses(input *UnassignIpv6AddressesInput) (*UnassignIpv6AddressesOutput, error) { req, out := c.UnassignIpv6AddressesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// UnassignIpv6AddressesWithContext is the same as UnassignIpv6Addresses with the addition of +// the ability to pass a context and additional request options. +// +// See UnassignIpv6Addresses 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) UnassignIpv6AddressesWithContext(ctx aws.Context, input *UnassignIpv6AddressesInput, opts ...request.Option) (*UnassignIpv6AddressesOutput, error) { + req, out := c.UnassignIpv6AddressesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opUnassignPrivateIpAddresses = "UnassignPrivateIpAddresses" @@ -15653,8 +19396,23 @@ func (c *EC2) UnassignPrivateIpAddressesRequest(input *UnassignPrivateIpAddresse // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/UnassignPrivateIpAddresses func (c *EC2) UnassignPrivateIpAddresses(input *UnassignPrivateIpAddressesInput) (*UnassignPrivateIpAddressesOutput, error) { req, out := c.UnassignPrivateIpAddressesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// UnassignPrivateIpAddressesWithContext is the same as UnassignPrivateIpAddresses with the addition of +// the ability to pass a context and additional request options. +// +// See UnassignPrivateIpAddresses 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) UnassignPrivateIpAddressesWithContext(ctx aws.Context, input *UnassignPrivateIpAddressesInput, opts ...request.Option) (*UnassignPrivateIpAddressesOutput, error) { + req, out := c.UnassignPrivateIpAddressesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opUnmonitorInstances = "UnmonitorInstances" @@ -15715,8 +19473,23 @@ func (c *EC2) UnmonitorInstancesRequest(input *UnmonitorInstancesInput) (req *re // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/UnmonitorInstances func (c *EC2) UnmonitorInstances(input *UnmonitorInstancesInput) (*UnmonitorInstancesOutput, error) { req, out := c.UnmonitorInstancesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// UnmonitorInstancesWithContext is the same as UnmonitorInstances with the addition of +// the ability to pass a context and additional request options. +// +// See UnmonitorInstances 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) UnmonitorInstancesWithContext(ctx aws.Context, input *UnmonitorInstancesInput, opts ...request.Option) (*UnmonitorInstancesOutput, error) { + req, out := c.UnmonitorInstancesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // Contains the parameters for accepting the quote. @@ -15943,8 +19716,8 @@ func (s *AccountAttributeValue) SetAttributeValue(v string) *AccountAttributeVal type ActiveInstance struct { _ struct{} `type:"structure"` - // The health status of the instance. If the status of both the instance status - // check and the system status check is impaired, the health status of the instance + // The health status of the instance. If the status of either the instance status + // check or the system status check is impaired, the health status of the instance // is unhealthy. Otherwise, the health status is healthy. InstanceHealth *string `locationName:"instanceHealth" type:"string" enum:"InstanceHealthStatus"` @@ -20002,6 +23775,128 @@ func (s *CreateFlowLogsOutput) SetUnsuccessful(v []*UnsuccessfulItem) *CreateFlo return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateFpgaImageRequest +type CreateFpgaImageInput struct { + _ struct{} `type:"structure"` + + // Unique, case-sensitive identifier that you provide to ensure the idempotency + // of the request. For more information, see Ensuring Idempotency (http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Run_Instance_Idempotency.html). + ClientToken *string `type:"string"` + + // A description for the AFI. + 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 location of the encrypted design checkpoint in Amazon S3. The input must + // be a tarball. + // + // InputStorageLocation is a required field + InputStorageLocation *StorageLocation `type:"structure" required:"true"` + + // The location in Amazon S3 for the output logs. + LogsStorageLocation *StorageLocation `type:"structure"` + + // A name for the AFI. + Name *string `type:"string"` +} + +// String returns the string representation +func (s CreateFpgaImageInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s CreateFpgaImageInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *CreateFpgaImageInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "CreateFpgaImageInput"} + if s.InputStorageLocation == nil { + invalidParams.Add(request.NewErrParamRequired("InputStorageLocation")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetClientToken sets the ClientToken field's value. +func (s *CreateFpgaImageInput) SetClientToken(v string) *CreateFpgaImageInput { + s.ClientToken = &v + return s +} + +// SetDescription sets the Description field's value. +func (s *CreateFpgaImageInput) SetDescription(v string) *CreateFpgaImageInput { + s.Description = &v + return s +} + +// SetDryRun sets the DryRun field's value. +func (s *CreateFpgaImageInput) SetDryRun(v bool) *CreateFpgaImageInput { + s.DryRun = &v + return s +} + +// SetInputStorageLocation sets the InputStorageLocation field's value. +func (s *CreateFpgaImageInput) SetInputStorageLocation(v *StorageLocation) *CreateFpgaImageInput { + s.InputStorageLocation = v + return s +} + +// SetLogsStorageLocation sets the LogsStorageLocation field's value. +func (s *CreateFpgaImageInput) SetLogsStorageLocation(v *StorageLocation) *CreateFpgaImageInput { + s.LogsStorageLocation = v + return s +} + +// SetName sets the Name field's value. +func (s *CreateFpgaImageInput) SetName(v string) *CreateFpgaImageInput { + s.Name = &v + return s +} + +// Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateFpgaImageResult +type CreateFpgaImageOutput struct { + _ struct{} `type:"structure"` + + // The global FPGA image identifier (AGFI ID). + FpgaImageGlobalId *string `locationName:"fpgaImageGlobalId" type:"string"` + + // The FPGA image identifier (AFI ID). + FpgaImageId *string `locationName:"fpgaImageId" type:"string"` +} + +// String returns the string representation +func (s CreateFpgaImageOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s CreateFpgaImageOutput) GoString() string { + return s.String() +} + +// SetFpgaImageGlobalId sets the FpgaImageGlobalId field's value. +func (s *CreateFpgaImageOutput) SetFpgaImageGlobalId(v string) *CreateFpgaImageOutput { + s.FpgaImageGlobalId = &v + return s +} + +// SetFpgaImageId sets the FpgaImageId field's value. +func (s *CreateFpgaImageOutput) SetFpgaImageId(v string) *CreateFpgaImageOutput { + s.FpgaImageId = &v + return s +} + // Contains the parameters for CreateImage. // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateImageRequest type CreateImageInput struct { @@ -21824,6 +25719,9 @@ type CreateVolumeInput struct { // The snapshot from which to create the volume. SnapshotId *string `type:"string"` + // 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. @@ -21897,6 +25795,12 @@ func (s *CreateVolumeInput) SetSnapshotId(v string) *CreateVolumeInput { return s } +// SetTagSpecifications sets the TagSpecifications field's value. +func (s *CreateVolumeInput) SetTagSpecifications(v []*TagSpecification) *CreateVolumeInput { + s.TagSpecifications = v + return s +} + // SetVolumeType sets the VolumeType field's value. func (s *CreateVolumeInput) SetVolumeType(v string) *CreateVolumeInput { s.VolumeType = &v @@ -26891,18 +30795,6 @@ type DescribeInstancesInput struct { // // * architecture - The instance architecture (i386 | x86_64). // - // * association.public-ip - The address of the Elastic IP address (IPv4) - // bound to the network interface. - // - // * association.ip-owner-id - The owner of the Elastic IP address (IPv4) - // associated with the network interface. - // - // * association.allocation-id - The allocation ID returned when you allocated - // the Elastic IP address (IPv4) for your network interface. - // - // * association.association-id - The association ID returned when the network - // interface was associated with an IPv4 address. - // // * availability-zone - The Availability Zone of the instance. // // * block-device-mapping.attach-time - The attach time for an EBS volume @@ -26988,6 +30880,18 @@ type DescribeInstancesInput struct { // * network-interface.addresses.association.ip-owner-id - The owner ID of // the private IPv4 address associated with the network interface. // + // * network-interface.association.public-ip - The address of the Elastic + // IP address (IPv4) bound to the network interface. + // + // * network-interface.association.ip-owner-id - The owner of the Elastic + // IP address (IPv4) associated with the network interface. + // + // * network-interface.association.allocation-id - The allocation ID returned + // when you allocated the Elastic IP address (IPv4) for your network interface. + // + // * network-interface.association.association-id - The association ID returned + // when the network interface was associated with an IPv4 address. + // // * network-interface.attachment.attachment-id - The ID of the interface // attachment. // @@ -27729,7 +31633,7 @@ func (s *DescribeNetworkAclsOutput) SetNetworkAcls(v []*NetworkAcl) *DescribeNet type DescribeNetworkInterfaceAttributeInput struct { _ struct{} `type:"structure"` - // The attribute of the network interface. + // The attribute of the network interface. This parameter is required. Attribute *string `locationName:"attribute" type:"string" enum:"NetworkInterfaceAttribute"` // Checks whether you have the required permissions for the action, without @@ -28659,6 +32563,9 @@ type DescribeReservedInstancesOfferingsInput struct { // with a tenancy of dedicated is applied to instances that run in a VPC on // single-tenant hardware (i.e., Dedicated Instances). // + // Important: The host value cannot be used with this parameter. Use the default + // or dedicated values only. + // // Default: default InstanceTenancy *string `locationName:"instanceTenancy" type:"string" enum:"Tenancy"` @@ -28890,7 +32797,8 @@ type DescribeRouteTablesInput struct { // * association.subnet-id - The ID of the subnet involved in the association. // // * association.main - Indicates whether the route table is the main route - // table for the VPC (true | false). + // table for the VPC (true | false). Route tables that do not have an association + // ID are not returned in the response. // // * route-table-id - The ID of the route table. // @@ -30886,7 +34794,7 @@ func (s *DescribeTagsOutput) SetTags(v []*TagDescription) *DescribeTagsOutput { type DescribeVolumeAttributeInput struct { _ struct{} `type:"structure"` - // The instance attribute. + // The attribute of the volume. This parameter is required. Attribute *string `type:"string" enum:"VolumeAttributeName"` // Checks whether you have the required permissions for the action, without @@ -43245,7 +47153,9 @@ type RegisterImageInput struct { // the architecture specified in the manifest file. Architecture *string `locationName:"architecture" type:"string" enum:"ArchitectureValues"` - // The billing product codes. + // The billing product codes. Your account must be authorized to specify billing + // product codes. Otherwise, you can use the AWS Marketplace to bill for the + // use of an AMI. BillingProducts []*string `locationName:"BillingProduct" locationNameList:"item" type:"list"` // One or more block device mapping entries. @@ -46794,6 +50704,11 @@ type RunInstancesInput struct { // [EC2-VPC] The ID of the subnet to launch the instance into. SubnetId *string `type:"string"` + // The tags to apply to the resources during launch. You can tag instances and + // volumes. The specified tags are applied to all instances or volumes that + // are created during launch. + 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 (http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/user-data.html) // (Linux) and Adding User Data (http://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/ec2-instance-metadata.html#instancedata-add-user-data) @@ -46991,6 +50906,12 @@ func (s *RunInstancesInput) SetSubnetId(v string) *RunInstancesInput { return s } +// SetTagSpecifications sets the TagSpecifications field's value. +func (s *RunInstancesInput) SetTagSpecifications(v []*TagSpecification) *RunInstancesInput { + s.TagSpecifications = v + return s +} + // SetUserData sets the UserData field's value. func (s *RunInstancesInput) SetUserData(v string) *RunInstancesInput { s.UserData = &v @@ -50244,6 +54165,40 @@ func (s *Storage) SetS3(v *S3Storage) *Storage { return s } +// Describes a storage location in Amazon S3. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/StorageLocation +type StorageLocation struct { + _ struct{} `type:"structure"` + + // The name of the S3 bucket. + Bucket *string `type:"string"` + + // The key. + Key *string `type:"string"` +} + +// String returns the string representation +func (s StorageLocation) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s StorageLocation) GoString() string { + return s.String() +} + +// SetBucket sets the Bucket field's value. +func (s *StorageLocation) SetBucket(v string) *StorageLocation { + s.Bucket = &v + return s +} + +// SetKey sets the Key field's value. +func (s *StorageLocation) SetKey(v string) *StorageLocation { + s.Key = &v + return s +} + // Describes a subnet. // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/Subnet type Subnet struct { @@ -50531,6 +54486,41 @@ func (s *TagDescription) SetValue(v string) *TagDescription { return s } +// The tags to apply to a resource when the resource is being created. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/TagSpecification +type TagSpecification struct { + _ struct{} `type:"structure"` + + // The type of resource to tag. Currently, the resource types that support tagging + // on creation are instance and volume. + ResourceType *string `locationName:"resourceType" type:"string" enum:"ResourceType"` + + // The tags to apply to the resource. + Tags []*Tag `locationName:"Tag" locationNameList:"item" type:"list"` +} + +// String returns the string representation +func (s TagSpecification) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s TagSpecification) GoString() string { + return s.String() +} + +// SetResourceType sets the ResourceType field's value. +func (s *TagSpecification) SetResourceType(v string) *TagSpecification { + s.ResourceType = &v + return s +} + +// SetTags sets the Tags field's value. +func (s *TagSpecification) SetTags(v []*Tag) *TagSpecification { + s.Tags = v + return s +} + // Information about the Convertible Reserved Instance offering. // Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/TargetConfiguration type TargetConfiguration struct { diff --git a/vendor/github.com/aws/aws-sdk-go/service/ec2/doc.go b/vendor/github.com/aws/aws-sdk-go/service/ec2/doc.go new file mode 100644 index 000000000..4aa6618b4 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/service/ec2/doc.go @@ -0,0 +1,83 @@ +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. + +// Package ec2 provides the client and types for making API +// requests to Amazon Elastic Compute Cloud. +// +// Amazon Elastic Compute Cloud (Amazon EC2) provides resizable computing capacity +// in the Amazon Web Services (AWS) cloud. Using Amazon EC2 eliminates your +// need to invest in hardware up front, so you can develop and deploy applications +// faster. +// +// See https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15 for more information on this service. +// +// See ec2 package documentation for more information. +// https://docs.aws.amazon.com/sdk-for-go/api/service/ec2/ +// +// Using the Client +// +// To use the client for Amazon Elastic Compute Cloud you will first need +// to create a new instance of it. +// +// When creating a client for an AWS service you'll first need to have a Session +// already created. The Session provides configuration that can be shared +// between multiple service clients. Additional configuration can be applied to +// the Session and service's client when they are constructed. The aws package's +// Config type contains several fields such as Region for the AWS Region the +// client should make API requests too. The optional Config value can be provided +// as the variadic argument for Sessions and client creation. +// +// Once the service's client is created you can use it to make API requests the +// AWS service. These clients are safe to use concurrently. +// +// // Create a session to share configuration, and load external configuration. +// sess := session.Must(session.NewSession()) +// +// // Create the service's client with the session. +// svc := ec2.New(sess) +// +// See the SDK's documentation for more information on how to use service clients. +// https://docs.aws.amazon.com/sdk-for-go/api/ +// +// See aws package's Config type for more information on configuration options. +// https://docs.aws.amazon.com/sdk-for-go/api/aws/#Config +// +// See the Amazon Elastic Compute Cloud client EC2 for more +// information on creating the service's client. +// https://docs.aws.amazon.com/sdk-for-go/api/service/ec2/#New +// +// Once the client is created you can make an API request to the service. +// Each API method takes a input parameter, and returns the service response +// and an error. +// +// The API method will document which error codes the service can be returned +// by the operation if the service models the API operation's errors. These +// errors will also be available as const strings prefixed with "ErrCode". +// +// result, err := svc.AcceptReservedInstancesExchangeQuote(params) +// if err != nil { +// // Cast err to awserr.Error to handle specific error codes. +// aerr, ok := err.(awserr.Error) +// if ok && aerr.Code() == { +// // Specific error code handling +// } +// return err +// } +// +// fmt.Println("AcceptReservedInstancesExchangeQuote result:") +// fmt.Println(result) +// +// Using the Client with Context +// +// The service's client also provides methods to make API requests with a Context +// value. This allows you to control the timeout, and cancellation of pending +// requests. These methods also take request Option as variadic parameter to apply +// additional configuration to the API request. +// +// ctx := context.Background() +// +// result, err := svc.AcceptReservedInstancesExchangeQuoteWithContext(ctx, params) +// +// See the request package documentation for more information on using Context pattern +// with the SDK. +// https://docs.aws.amazon.com/sdk-for-go/api/aws/request/ +package ec2 diff --git a/vendor/github.com/aws/aws-sdk-go/service/ec2/errors.go b/vendor/github.com/aws/aws-sdk-go/service/ec2/errors.go index f90fa6ec5..3d61d7e35 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/ec2/errors.go +++ b/vendor/github.com/aws/aws-sdk-go/service/ec2/errors.go @@ -1,3 +1,3 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. package ec2 diff --git a/vendor/github.com/aws/aws-sdk-go/service/ec2/service.go b/vendor/github.com/aws/aws-sdk-go/service/ec2/service.go index c289b5b04..ba4433d38 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/ec2/service.go +++ b/vendor/github.com/aws/aws-sdk-go/service/ec2/service.go @@ -1,4 +1,4 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. package ec2 @@ -11,13 +11,12 @@ import ( "github.com/aws/aws-sdk-go/private/protocol/ec2query" ) -// Amazon Elastic Compute Cloud (Amazon EC2) provides resizable computing capacity -// in the Amazon Web Services (AWS) cloud. Using Amazon EC2 eliminates your -// need to invest in hardware up front, so you can develop and deploy applications -// faster. -// The service client's operations are safe to be used concurrently. -// It is not safe to mutate any of the client's properties though. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15 +// EC2 provides the API operation methods for making requests to +// Amazon Elastic Compute Cloud. See this package's package overview docs +// for details on the service. +// +// EC2 methods are safe to use concurrently. It is not safe to +// modify mutate any of the struct's properties though. type EC2 struct { *client.Client } diff --git a/vendor/github.com/aws/aws-sdk-go/service/ec2/waiters.go b/vendor/github.com/aws/aws-sdk-go/service/ec2/waiters.go index 7917cbdaf..c0a655fa0 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/ec2/waiters.go +++ b/vendor/github.com/aws/aws-sdk-go/service/ec2/waiters.go @@ -1,9 +1,12 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. package ec2 import ( - "github.com/aws/aws-sdk-go/private/waiter" + "time" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/request" ) // WaitUntilBundleTaskComplete uses the Amazon EC2 API operation @@ -11,32 +14,50 @@ import ( // If the condition is not meet within the max attempt window an error will // be returned. func (c *EC2) WaitUntilBundleTaskComplete(input *DescribeBundleTasksInput) error { - waiterCfg := waiter.Config{ - Operation: "DescribeBundleTasks", - Delay: 15, + return c.WaitUntilBundleTaskCompleteWithContext(aws.BackgroundContext(), input) +} + +// WaitUntilBundleTaskCompleteWithContext is an extended version of WaitUntilBundleTaskComplete. +// 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 *EC2) WaitUntilBundleTaskCompleteWithContext(ctx aws.Context, input *DescribeBundleTasksInput, opts ...request.WaiterOption) error { + w := request.Waiter{ + Name: "WaitUntilBundleTaskComplete", MaxAttempts: 40, - Acceptors: []waiter.WaitAcceptor{ + Delay: request.ConstantWaiterDelay(15 * time.Second), + Acceptors: []request.WaiterAcceptor{ { - State: "success", - Matcher: "pathAll", - Argument: "BundleTasks[].State", + State: request.SuccessWaiterState, + Matcher: request.PathAllWaiterMatch, Argument: "BundleTasks[].State", Expected: "complete", }, { - State: "failure", - Matcher: "pathAny", - Argument: "BundleTasks[].State", + State: request.FailureWaiterState, + Matcher: request.PathAnyWaiterMatch, Argument: "BundleTasks[].State", Expected: "failed", }, }, + Logger: c.Config.Logger, + NewRequest: func(opts []request.Option) (*request.Request, error) { + var inCpy *DescribeBundleTasksInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeBundleTasksRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, } + w.ApplyOptions(opts...) - w := waiter.Waiter{ - Client: c, - Input: input, - Config: waiterCfg, - } - return w.Wait() + return w.WaitWithContext(ctx) } // WaitUntilConversionTaskCancelled uses the Amazon EC2 API operation @@ -44,26 +65,45 @@ func (c *EC2) WaitUntilBundleTaskComplete(input *DescribeBundleTasksInput) error // If the condition is not meet within the max attempt window an error will // be returned. func (c *EC2) WaitUntilConversionTaskCancelled(input *DescribeConversionTasksInput) error { - waiterCfg := waiter.Config{ - Operation: "DescribeConversionTasks", - Delay: 15, + return c.WaitUntilConversionTaskCancelledWithContext(aws.BackgroundContext(), input) +} + +// WaitUntilConversionTaskCancelledWithContext is an extended version of WaitUntilConversionTaskCancelled. +// 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 *EC2) WaitUntilConversionTaskCancelledWithContext(ctx aws.Context, input *DescribeConversionTasksInput, opts ...request.WaiterOption) error { + w := request.Waiter{ + Name: "WaitUntilConversionTaskCancelled", MaxAttempts: 40, - Acceptors: []waiter.WaitAcceptor{ + Delay: request.ConstantWaiterDelay(15 * time.Second), + Acceptors: []request.WaiterAcceptor{ { - State: "success", - Matcher: "pathAll", - Argument: "ConversionTasks[].State", + State: request.SuccessWaiterState, + Matcher: request.PathAllWaiterMatch, Argument: "ConversionTasks[].State", Expected: "cancelled", }, }, + Logger: c.Config.Logger, + NewRequest: func(opts []request.Option) (*request.Request, error) { + var inCpy *DescribeConversionTasksInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeConversionTasksRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, } + w.ApplyOptions(opts...) - w := waiter.Waiter{ - Client: c, - Input: input, - Config: waiterCfg, - } - return w.Wait() + return w.WaitWithContext(ctx) } // WaitUntilConversionTaskCompleted uses the Amazon EC2 API operation @@ -71,38 +111,55 @@ func (c *EC2) WaitUntilConversionTaskCancelled(input *DescribeConversionTasksInp // If the condition is not meet within the max attempt window an error will // be returned. func (c *EC2) WaitUntilConversionTaskCompleted(input *DescribeConversionTasksInput) error { - waiterCfg := waiter.Config{ - Operation: "DescribeConversionTasks", - Delay: 15, + return c.WaitUntilConversionTaskCompletedWithContext(aws.BackgroundContext(), input) +} + +// WaitUntilConversionTaskCompletedWithContext is an extended version of WaitUntilConversionTaskCompleted. +// 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 *EC2) WaitUntilConversionTaskCompletedWithContext(ctx aws.Context, input *DescribeConversionTasksInput, opts ...request.WaiterOption) error { + w := request.Waiter{ + Name: "WaitUntilConversionTaskCompleted", MaxAttempts: 40, - Acceptors: []waiter.WaitAcceptor{ + Delay: request.ConstantWaiterDelay(15 * time.Second), + Acceptors: []request.WaiterAcceptor{ { - State: "success", - Matcher: "pathAll", - Argument: "ConversionTasks[].State", + State: request.SuccessWaiterState, + Matcher: request.PathAllWaiterMatch, Argument: "ConversionTasks[].State", Expected: "completed", }, { - State: "failure", - Matcher: "pathAny", - Argument: "ConversionTasks[].State", + State: request.FailureWaiterState, + Matcher: request.PathAnyWaiterMatch, Argument: "ConversionTasks[].State", Expected: "cancelled", }, { - State: "failure", - Matcher: "pathAny", - Argument: "ConversionTasks[].State", + State: request.FailureWaiterState, + Matcher: request.PathAnyWaiterMatch, Argument: "ConversionTasks[].State", Expected: "cancelling", }, }, + Logger: c.Config.Logger, + NewRequest: func(opts []request.Option) (*request.Request, error) { + var inCpy *DescribeConversionTasksInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeConversionTasksRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, } + w.ApplyOptions(opts...) - w := waiter.Waiter{ - Client: c, - Input: input, - Config: waiterCfg, - } - return w.Wait() + return w.WaitWithContext(ctx) } // WaitUntilConversionTaskDeleted uses the Amazon EC2 API operation @@ -110,26 +167,45 @@ func (c *EC2) WaitUntilConversionTaskCompleted(input *DescribeConversionTasksInp // If the condition is not meet within the max attempt window an error will // be returned. func (c *EC2) WaitUntilConversionTaskDeleted(input *DescribeConversionTasksInput) error { - waiterCfg := waiter.Config{ - Operation: "DescribeConversionTasks", - Delay: 15, + return c.WaitUntilConversionTaskDeletedWithContext(aws.BackgroundContext(), input) +} + +// WaitUntilConversionTaskDeletedWithContext is an extended version of WaitUntilConversionTaskDeleted. +// 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 *EC2) WaitUntilConversionTaskDeletedWithContext(ctx aws.Context, input *DescribeConversionTasksInput, opts ...request.WaiterOption) error { + w := request.Waiter{ + Name: "WaitUntilConversionTaskDeleted", MaxAttempts: 40, - Acceptors: []waiter.WaitAcceptor{ + Delay: request.ConstantWaiterDelay(15 * time.Second), + Acceptors: []request.WaiterAcceptor{ { - State: "success", - Matcher: "pathAll", - Argument: "ConversionTasks[].State", + State: request.SuccessWaiterState, + Matcher: request.PathAllWaiterMatch, Argument: "ConversionTasks[].State", Expected: "deleted", }, }, + Logger: c.Config.Logger, + NewRequest: func(opts []request.Option) (*request.Request, error) { + var inCpy *DescribeConversionTasksInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeConversionTasksRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, } + w.ApplyOptions(opts...) - w := waiter.Waiter{ - Client: c, - Input: input, - Config: waiterCfg, - } - return w.Wait() + return w.WaitWithContext(ctx) } // WaitUntilCustomerGatewayAvailable uses the Amazon EC2 API operation @@ -137,38 +213,55 @@ func (c *EC2) WaitUntilConversionTaskDeleted(input *DescribeConversionTasksInput // If the condition is not meet within the max attempt window an error will // be returned. func (c *EC2) WaitUntilCustomerGatewayAvailable(input *DescribeCustomerGatewaysInput) error { - waiterCfg := waiter.Config{ - Operation: "DescribeCustomerGateways", - Delay: 15, + return c.WaitUntilCustomerGatewayAvailableWithContext(aws.BackgroundContext(), input) +} + +// WaitUntilCustomerGatewayAvailableWithContext is an extended version of WaitUntilCustomerGatewayAvailable. +// 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 *EC2) WaitUntilCustomerGatewayAvailableWithContext(ctx aws.Context, input *DescribeCustomerGatewaysInput, opts ...request.WaiterOption) error { + w := request.Waiter{ + Name: "WaitUntilCustomerGatewayAvailable", MaxAttempts: 40, - Acceptors: []waiter.WaitAcceptor{ + Delay: request.ConstantWaiterDelay(15 * time.Second), + Acceptors: []request.WaiterAcceptor{ { - State: "success", - Matcher: "pathAll", - Argument: "CustomerGateways[].State", + State: request.SuccessWaiterState, + Matcher: request.PathAllWaiterMatch, Argument: "CustomerGateways[].State", Expected: "available", }, { - State: "failure", - Matcher: "pathAny", - Argument: "CustomerGateways[].State", + State: request.FailureWaiterState, + Matcher: request.PathAnyWaiterMatch, Argument: "CustomerGateways[].State", Expected: "deleted", }, { - State: "failure", - Matcher: "pathAny", - Argument: "CustomerGateways[].State", + State: request.FailureWaiterState, + Matcher: request.PathAnyWaiterMatch, Argument: "CustomerGateways[].State", Expected: "deleting", }, }, + Logger: c.Config.Logger, + NewRequest: func(opts []request.Option) (*request.Request, error) { + var inCpy *DescribeCustomerGatewaysInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeCustomerGatewaysRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, } + w.ApplyOptions(opts...) - w := waiter.Waiter{ - Client: c, - Input: input, - Config: waiterCfg, - } - return w.Wait() + return w.WaitWithContext(ctx) } // WaitUntilExportTaskCancelled uses the Amazon EC2 API operation @@ -176,26 +269,45 @@ func (c *EC2) WaitUntilCustomerGatewayAvailable(input *DescribeCustomerGatewaysI // If the condition is not meet within the max attempt window an error will // be returned. func (c *EC2) WaitUntilExportTaskCancelled(input *DescribeExportTasksInput) error { - waiterCfg := waiter.Config{ - Operation: "DescribeExportTasks", - Delay: 15, + return c.WaitUntilExportTaskCancelledWithContext(aws.BackgroundContext(), input) +} + +// WaitUntilExportTaskCancelledWithContext is an extended version of WaitUntilExportTaskCancelled. +// 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 *EC2) WaitUntilExportTaskCancelledWithContext(ctx aws.Context, input *DescribeExportTasksInput, opts ...request.WaiterOption) error { + w := request.Waiter{ + Name: "WaitUntilExportTaskCancelled", MaxAttempts: 40, - Acceptors: []waiter.WaitAcceptor{ + Delay: request.ConstantWaiterDelay(15 * time.Second), + Acceptors: []request.WaiterAcceptor{ { - State: "success", - Matcher: "pathAll", - Argument: "ExportTasks[].State", + State: request.SuccessWaiterState, + Matcher: request.PathAllWaiterMatch, Argument: "ExportTasks[].State", Expected: "cancelled", }, }, + Logger: c.Config.Logger, + NewRequest: func(opts []request.Option) (*request.Request, error) { + var inCpy *DescribeExportTasksInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeExportTasksRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, } + w.ApplyOptions(opts...) - w := waiter.Waiter{ - Client: c, - Input: input, - Config: waiterCfg, - } - return w.Wait() + return w.WaitWithContext(ctx) } // WaitUntilExportTaskCompleted uses the Amazon EC2 API operation @@ -203,26 +315,45 @@ func (c *EC2) WaitUntilExportTaskCancelled(input *DescribeExportTasksInput) erro // If the condition is not meet within the max attempt window an error will // be returned. func (c *EC2) WaitUntilExportTaskCompleted(input *DescribeExportTasksInput) error { - waiterCfg := waiter.Config{ - Operation: "DescribeExportTasks", - Delay: 15, + return c.WaitUntilExportTaskCompletedWithContext(aws.BackgroundContext(), input) +} + +// WaitUntilExportTaskCompletedWithContext is an extended version of WaitUntilExportTaskCompleted. +// 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 *EC2) WaitUntilExportTaskCompletedWithContext(ctx aws.Context, input *DescribeExportTasksInput, opts ...request.WaiterOption) error { + w := request.Waiter{ + Name: "WaitUntilExportTaskCompleted", MaxAttempts: 40, - Acceptors: []waiter.WaitAcceptor{ + Delay: request.ConstantWaiterDelay(15 * time.Second), + Acceptors: []request.WaiterAcceptor{ { - State: "success", - Matcher: "pathAll", - Argument: "ExportTasks[].State", + State: request.SuccessWaiterState, + Matcher: request.PathAllWaiterMatch, Argument: "ExportTasks[].State", Expected: "completed", }, }, + Logger: c.Config.Logger, + NewRequest: func(opts []request.Option) (*request.Request, error) { + var inCpy *DescribeExportTasksInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeExportTasksRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, } + w.ApplyOptions(opts...) - w := waiter.Waiter{ - Client: c, - Input: input, - Config: waiterCfg, - } - return w.Wait() + return w.WaitWithContext(ctx) } // WaitUntilImageAvailable uses the Amazon EC2 API operation @@ -230,32 +361,50 @@ func (c *EC2) WaitUntilExportTaskCompleted(input *DescribeExportTasksInput) erro // If the condition is not meet within the max attempt window an error will // be returned. func (c *EC2) WaitUntilImageAvailable(input *DescribeImagesInput) error { - waiterCfg := waiter.Config{ - Operation: "DescribeImages", - Delay: 15, + return c.WaitUntilImageAvailableWithContext(aws.BackgroundContext(), input) +} + +// WaitUntilImageAvailableWithContext is an extended version of WaitUntilImageAvailable. +// 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 *EC2) WaitUntilImageAvailableWithContext(ctx aws.Context, input *DescribeImagesInput, opts ...request.WaiterOption) error { + w := request.Waiter{ + Name: "WaitUntilImageAvailable", MaxAttempts: 40, - Acceptors: []waiter.WaitAcceptor{ + Delay: request.ConstantWaiterDelay(15 * time.Second), + Acceptors: []request.WaiterAcceptor{ { - State: "success", - Matcher: "pathAll", - Argument: "Images[].State", + State: request.SuccessWaiterState, + Matcher: request.PathAllWaiterMatch, Argument: "Images[].State", Expected: "available", }, { - State: "failure", - Matcher: "pathAny", - Argument: "Images[].State", + State: request.FailureWaiterState, + Matcher: request.PathAnyWaiterMatch, Argument: "Images[].State", Expected: "failed", }, }, + Logger: c.Config.Logger, + NewRequest: func(opts []request.Option) (*request.Request, error) { + var inCpy *DescribeImagesInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeImagesRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, } + w.ApplyOptions(opts...) - w := waiter.Waiter{ - Client: c, - Input: input, - Config: waiterCfg, - } - return w.Wait() + return w.WaitWithContext(ctx) } // WaitUntilImageExists uses the Amazon EC2 API operation @@ -263,32 +412,50 @@ func (c *EC2) WaitUntilImageAvailable(input *DescribeImagesInput) error { // If the condition is not meet within the max attempt window an error will // be returned. func (c *EC2) WaitUntilImageExists(input *DescribeImagesInput) error { - waiterCfg := waiter.Config{ - Operation: "DescribeImages", - Delay: 15, + return c.WaitUntilImageExistsWithContext(aws.BackgroundContext(), input) +} + +// WaitUntilImageExistsWithContext is an extended version of WaitUntilImageExists. +// 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 *EC2) WaitUntilImageExistsWithContext(ctx aws.Context, input *DescribeImagesInput, opts ...request.WaiterOption) error { + w := request.Waiter{ + Name: "WaitUntilImageExists", MaxAttempts: 40, - Acceptors: []waiter.WaitAcceptor{ + Delay: request.ConstantWaiterDelay(15 * time.Second), + Acceptors: []request.WaiterAcceptor{ { - State: "success", - Matcher: "path", - Argument: "length(Images[]) > `0`", + State: request.SuccessWaiterState, + Matcher: request.PathWaiterMatch, Argument: "length(Images[]) > `0`", Expected: true, }, { - State: "retry", - Matcher: "error", - Argument: "", + State: request.RetryWaiterState, + Matcher: request.ErrorWaiterMatch, Expected: "InvalidAMIID.NotFound", }, }, + Logger: c.Config.Logger, + NewRequest: func(opts []request.Option) (*request.Request, error) { + var inCpy *DescribeImagesInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeImagesRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, } + w.ApplyOptions(opts...) - w := waiter.Waiter{ - Client: c, - Input: input, - Config: waiterCfg, - } - return w.Wait() + return w.WaitWithContext(ctx) } // WaitUntilInstanceExists uses the Amazon EC2 API operation @@ -296,32 +463,50 @@ func (c *EC2) WaitUntilImageExists(input *DescribeImagesInput) error { // If the condition is not meet within the max attempt window an error will // be returned. func (c *EC2) WaitUntilInstanceExists(input *DescribeInstancesInput) error { - waiterCfg := waiter.Config{ - Operation: "DescribeInstances", - Delay: 5, + return c.WaitUntilInstanceExistsWithContext(aws.BackgroundContext(), input) +} + +// WaitUntilInstanceExistsWithContext is an extended version of WaitUntilInstanceExists. +// 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 *EC2) WaitUntilInstanceExistsWithContext(ctx aws.Context, input *DescribeInstancesInput, opts ...request.WaiterOption) error { + w := request.Waiter{ + Name: "WaitUntilInstanceExists", MaxAttempts: 40, - Acceptors: []waiter.WaitAcceptor{ + Delay: request.ConstantWaiterDelay(5 * time.Second), + Acceptors: []request.WaiterAcceptor{ { - State: "success", - Matcher: "path", - Argument: "length(Reservations[]) > `0`", + State: request.SuccessWaiterState, + Matcher: request.PathWaiterMatch, Argument: "length(Reservations[]) > `0`", Expected: true, }, { - State: "retry", - Matcher: "error", - Argument: "", + State: request.RetryWaiterState, + Matcher: request.ErrorWaiterMatch, Expected: "InvalidInstanceID.NotFound", }, }, + Logger: c.Config.Logger, + NewRequest: func(opts []request.Option) (*request.Request, error) { + var inCpy *DescribeInstancesInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeInstancesRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, } + w.ApplyOptions(opts...) - w := waiter.Waiter{ - Client: c, - Input: input, - Config: waiterCfg, - } - return w.Wait() + return w.WaitWithContext(ctx) } // WaitUntilInstanceRunning uses the Amazon EC2 API operation @@ -329,50 +514,65 @@ func (c *EC2) WaitUntilInstanceExists(input *DescribeInstancesInput) error { // If the condition is not meet within the max attempt window an error will // be returned. func (c *EC2) WaitUntilInstanceRunning(input *DescribeInstancesInput) error { - waiterCfg := waiter.Config{ - Operation: "DescribeInstances", - Delay: 15, + return c.WaitUntilInstanceRunningWithContext(aws.BackgroundContext(), input) +} + +// WaitUntilInstanceRunningWithContext is an extended version of WaitUntilInstanceRunning. +// 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 *EC2) WaitUntilInstanceRunningWithContext(ctx aws.Context, input *DescribeInstancesInput, opts ...request.WaiterOption) error { + w := request.Waiter{ + Name: "WaitUntilInstanceRunning", MaxAttempts: 40, - Acceptors: []waiter.WaitAcceptor{ + Delay: request.ConstantWaiterDelay(15 * time.Second), + Acceptors: []request.WaiterAcceptor{ { - State: "success", - Matcher: "pathAll", - Argument: "Reservations[].Instances[].State.Name", + State: request.SuccessWaiterState, + Matcher: request.PathAllWaiterMatch, Argument: "Reservations[].Instances[].State.Name", Expected: "running", }, { - State: "failure", - Matcher: "pathAny", - Argument: "Reservations[].Instances[].State.Name", + State: request.FailureWaiterState, + Matcher: request.PathAnyWaiterMatch, Argument: "Reservations[].Instances[].State.Name", Expected: "shutting-down", }, { - State: "failure", - Matcher: "pathAny", - Argument: "Reservations[].Instances[].State.Name", + State: request.FailureWaiterState, + Matcher: request.PathAnyWaiterMatch, Argument: "Reservations[].Instances[].State.Name", Expected: "terminated", }, { - State: "failure", - Matcher: "pathAny", - Argument: "Reservations[].Instances[].State.Name", + State: request.FailureWaiterState, + Matcher: request.PathAnyWaiterMatch, Argument: "Reservations[].Instances[].State.Name", Expected: "stopping", }, { - State: "retry", - Matcher: "error", - Argument: "", + State: request.RetryWaiterState, + Matcher: request.ErrorWaiterMatch, Expected: "InvalidInstanceID.NotFound", }, }, + Logger: c.Config.Logger, + NewRequest: func(opts []request.Option) (*request.Request, error) { + var inCpy *DescribeInstancesInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeInstancesRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, } + w.ApplyOptions(opts...) - w := waiter.Waiter{ - Client: c, - Input: input, - Config: waiterCfg, - } - return w.Wait() + return w.WaitWithContext(ctx) } // WaitUntilInstanceStatusOk uses the Amazon EC2 API operation @@ -380,32 +580,50 @@ func (c *EC2) WaitUntilInstanceRunning(input *DescribeInstancesInput) error { // If the condition is not meet within the max attempt window an error will // be returned. func (c *EC2) WaitUntilInstanceStatusOk(input *DescribeInstanceStatusInput) error { - waiterCfg := waiter.Config{ - Operation: "DescribeInstanceStatus", - Delay: 15, + return c.WaitUntilInstanceStatusOkWithContext(aws.BackgroundContext(), input) +} + +// WaitUntilInstanceStatusOkWithContext is an extended version of WaitUntilInstanceStatusOk. +// 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 *EC2) WaitUntilInstanceStatusOkWithContext(ctx aws.Context, input *DescribeInstanceStatusInput, opts ...request.WaiterOption) error { + w := request.Waiter{ + Name: "WaitUntilInstanceStatusOk", MaxAttempts: 40, - Acceptors: []waiter.WaitAcceptor{ + Delay: request.ConstantWaiterDelay(15 * time.Second), + Acceptors: []request.WaiterAcceptor{ { - State: "success", - Matcher: "pathAll", - Argument: "InstanceStatuses[].InstanceStatus.Status", + State: request.SuccessWaiterState, + Matcher: request.PathAllWaiterMatch, Argument: "InstanceStatuses[].InstanceStatus.Status", Expected: "ok", }, { - State: "retry", - Matcher: "error", - Argument: "", + State: request.RetryWaiterState, + Matcher: request.ErrorWaiterMatch, Expected: "InvalidInstanceID.NotFound", }, }, + Logger: c.Config.Logger, + NewRequest: func(opts []request.Option) (*request.Request, error) { + var inCpy *DescribeInstanceStatusInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeInstanceStatusRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, } + w.ApplyOptions(opts...) - w := waiter.Waiter{ - Client: c, - Input: input, - Config: waiterCfg, - } - return w.Wait() + return w.WaitWithContext(ctx) } // WaitUntilInstanceStopped uses the Amazon EC2 API operation @@ -413,38 +631,55 @@ func (c *EC2) WaitUntilInstanceStatusOk(input *DescribeInstanceStatusInput) erro // If the condition is not meet within the max attempt window an error will // be returned. func (c *EC2) WaitUntilInstanceStopped(input *DescribeInstancesInput) error { - waiterCfg := waiter.Config{ - Operation: "DescribeInstances", - Delay: 15, + return c.WaitUntilInstanceStoppedWithContext(aws.BackgroundContext(), input) +} + +// WaitUntilInstanceStoppedWithContext is an extended version of WaitUntilInstanceStopped. +// 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 *EC2) WaitUntilInstanceStoppedWithContext(ctx aws.Context, input *DescribeInstancesInput, opts ...request.WaiterOption) error { + w := request.Waiter{ + Name: "WaitUntilInstanceStopped", MaxAttempts: 40, - Acceptors: []waiter.WaitAcceptor{ + Delay: request.ConstantWaiterDelay(15 * time.Second), + Acceptors: []request.WaiterAcceptor{ { - State: "success", - Matcher: "pathAll", - Argument: "Reservations[].Instances[].State.Name", + State: request.SuccessWaiterState, + Matcher: request.PathAllWaiterMatch, Argument: "Reservations[].Instances[].State.Name", Expected: "stopped", }, { - State: "failure", - Matcher: "pathAny", - Argument: "Reservations[].Instances[].State.Name", + State: request.FailureWaiterState, + Matcher: request.PathAnyWaiterMatch, Argument: "Reservations[].Instances[].State.Name", Expected: "pending", }, { - State: "failure", - Matcher: "pathAny", - Argument: "Reservations[].Instances[].State.Name", + State: request.FailureWaiterState, + Matcher: request.PathAnyWaiterMatch, Argument: "Reservations[].Instances[].State.Name", Expected: "terminated", }, }, + Logger: c.Config.Logger, + NewRequest: func(opts []request.Option) (*request.Request, error) { + var inCpy *DescribeInstancesInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeInstancesRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, } + w.ApplyOptions(opts...) - w := waiter.Waiter{ - Client: c, - Input: input, - Config: waiterCfg, - } - return w.Wait() + return w.WaitWithContext(ctx) } // WaitUntilInstanceTerminated uses the Amazon EC2 API operation @@ -452,38 +687,55 @@ func (c *EC2) WaitUntilInstanceStopped(input *DescribeInstancesInput) error { // If the condition is not meet within the max attempt window an error will // be returned. func (c *EC2) WaitUntilInstanceTerminated(input *DescribeInstancesInput) error { - waiterCfg := waiter.Config{ - Operation: "DescribeInstances", - Delay: 15, + return c.WaitUntilInstanceTerminatedWithContext(aws.BackgroundContext(), input) +} + +// WaitUntilInstanceTerminatedWithContext is an extended version of WaitUntilInstanceTerminated. +// 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 *EC2) WaitUntilInstanceTerminatedWithContext(ctx aws.Context, input *DescribeInstancesInput, opts ...request.WaiterOption) error { + w := request.Waiter{ + Name: "WaitUntilInstanceTerminated", MaxAttempts: 40, - Acceptors: []waiter.WaitAcceptor{ + Delay: request.ConstantWaiterDelay(15 * time.Second), + Acceptors: []request.WaiterAcceptor{ { - State: "success", - Matcher: "pathAll", - Argument: "Reservations[].Instances[].State.Name", + State: request.SuccessWaiterState, + Matcher: request.PathAllWaiterMatch, Argument: "Reservations[].Instances[].State.Name", Expected: "terminated", }, { - State: "failure", - Matcher: "pathAny", - Argument: "Reservations[].Instances[].State.Name", + State: request.FailureWaiterState, + Matcher: request.PathAnyWaiterMatch, Argument: "Reservations[].Instances[].State.Name", Expected: "pending", }, { - State: "failure", - Matcher: "pathAny", - Argument: "Reservations[].Instances[].State.Name", + State: request.FailureWaiterState, + Matcher: request.PathAnyWaiterMatch, Argument: "Reservations[].Instances[].State.Name", Expected: "stopping", }, }, + Logger: c.Config.Logger, + NewRequest: func(opts []request.Option) (*request.Request, error) { + var inCpy *DescribeInstancesInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeInstancesRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, } + w.ApplyOptions(opts...) - w := waiter.Waiter{ - Client: c, - Input: input, - Config: waiterCfg, - } - return w.Wait() + return w.WaitWithContext(ctx) } // WaitUntilKeyPairExists uses the Amazon EC2 API operation @@ -491,32 +743,50 @@ func (c *EC2) WaitUntilInstanceTerminated(input *DescribeInstancesInput) error { // If the condition is not meet within the max attempt window an error will // be returned. func (c *EC2) WaitUntilKeyPairExists(input *DescribeKeyPairsInput) error { - waiterCfg := waiter.Config{ - Operation: "DescribeKeyPairs", - Delay: 5, + return c.WaitUntilKeyPairExistsWithContext(aws.BackgroundContext(), input) +} + +// WaitUntilKeyPairExistsWithContext is an extended version of WaitUntilKeyPairExists. +// 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 *EC2) WaitUntilKeyPairExistsWithContext(ctx aws.Context, input *DescribeKeyPairsInput, opts ...request.WaiterOption) error { + w := request.Waiter{ + Name: "WaitUntilKeyPairExists", MaxAttempts: 6, - Acceptors: []waiter.WaitAcceptor{ + Delay: request.ConstantWaiterDelay(5 * time.Second), + Acceptors: []request.WaiterAcceptor{ { - State: "success", - Matcher: "path", - Argument: "length(KeyPairs[].KeyName) > `0`", + State: request.SuccessWaiterState, + Matcher: request.PathWaiterMatch, Argument: "length(KeyPairs[].KeyName) > `0`", Expected: true, }, { - State: "retry", - Matcher: "error", - Argument: "", + State: request.RetryWaiterState, + Matcher: request.ErrorWaiterMatch, Expected: "InvalidKeyPair.NotFound", }, }, + Logger: c.Config.Logger, + NewRequest: func(opts []request.Option) (*request.Request, error) { + var inCpy *DescribeKeyPairsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeKeyPairsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, } + w.ApplyOptions(opts...) - w := waiter.Waiter{ - Client: c, - Input: input, - Config: waiterCfg, - } - return w.Wait() + return w.WaitWithContext(ctx) } // WaitUntilNatGatewayAvailable uses the Amazon EC2 API operation @@ -524,50 +794,65 @@ func (c *EC2) WaitUntilKeyPairExists(input *DescribeKeyPairsInput) error { // If the condition is not meet within the max attempt window an error will // be returned. func (c *EC2) WaitUntilNatGatewayAvailable(input *DescribeNatGatewaysInput) error { - waiterCfg := waiter.Config{ - Operation: "DescribeNatGateways", - Delay: 15, + return c.WaitUntilNatGatewayAvailableWithContext(aws.BackgroundContext(), input) +} + +// WaitUntilNatGatewayAvailableWithContext is an extended version of WaitUntilNatGatewayAvailable. +// 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 *EC2) WaitUntilNatGatewayAvailableWithContext(ctx aws.Context, input *DescribeNatGatewaysInput, opts ...request.WaiterOption) error { + w := request.Waiter{ + Name: "WaitUntilNatGatewayAvailable", MaxAttempts: 40, - Acceptors: []waiter.WaitAcceptor{ + Delay: request.ConstantWaiterDelay(15 * time.Second), + Acceptors: []request.WaiterAcceptor{ { - State: "success", - Matcher: "pathAll", - Argument: "NatGateways[].State", + State: request.SuccessWaiterState, + Matcher: request.PathAllWaiterMatch, Argument: "NatGateways[].State", Expected: "available", }, { - State: "failure", - Matcher: "pathAny", - Argument: "NatGateways[].State", + State: request.FailureWaiterState, + Matcher: request.PathAnyWaiterMatch, Argument: "NatGateways[].State", Expected: "failed", }, { - State: "failure", - Matcher: "pathAny", - Argument: "NatGateways[].State", + State: request.FailureWaiterState, + Matcher: request.PathAnyWaiterMatch, Argument: "NatGateways[].State", Expected: "deleting", }, { - State: "failure", - Matcher: "pathAny", - Argument: "NatGateways[].State", + State: request.FailureWaiterState, + Matcher: request.PathAnyWaiterMatch, Argument: "NatGateways[].State", Expected: "deleted", }, { - State: "retry", - Matcher: "error", - Argument: "", + State: request.RetryWaiterState, + Matcher: request.ErrorWaiterMatch, Expected: "NatGatewayNotFound", }, }, + Logger: c.Config.Logger, + NewRequest: func(opts []request.Option) (*request.Request, error) { + var inCpy *DescribeNatGatewaysInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeNatGatewaysRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, } + w.ApplyOptions(opts...) - w := waiter.Waiter{ - Client: c, - Input: input, - Config: waiterCfg, - } - return w.Wait() + return w.WaitWithContext(ctx) } // WaitUntilNetworkInterfaceAvailable uses the Amazon EC2 API operation @@ -575,32 +860,50 @@ func (c *EC2) WaitUntilNatGatewayAvailable(input *DescribeNatGatewaysInput) erro // If the condition is not meet within the max attempt window an error will // be returned. func (c *EC2) WaitUntilNetworkInterfaceAvailable(input *DescribeNetworkInterfacesInput) error { - waiterCfg := waiter.Config{ - Operation: "DescribeNetworkInterfaces", - Delay: 20, + return c.WaitUntilNetworkInterfaceAvailableWithContext(aws.BackgroundContext(), input) +} + +// WaitUntilNetworkInterfaceAvailableWithContext is an extended version of WaitUntilNetworkInterfaceAvailable. +// 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 *EC2) WaitUntilNetworkInterfaceAvailableWithContext(ctx aws.Context, input *DescribeNetworkInterfacesInput, opts ...request.WaiterOption) error { + w := request.Waiter{ + Name: "WaitUntilNetworkInterfaceAvailable", MaxAttempts: 10, - Acceptors: []waiter.WaitAcceptor{ + Delay: request.ConstantWaiterDelay(20 * time.Second), + Acceptors: []request.WaiterAcceptor{ { - State: "success", - Matcher: "pathAll", - Argument: "NetworkInterfaces[].Status", + State: request.SuccessWaiterState, + Matcher: request.PathAllWaiterMatch, Argument: "NetworkInterfaces[].Status", Expected: "available", }, { - State: "failure", - Matcher: "error", - Argument: "", + State: request.FailureWaiterState, + Matcher: request.ErrorWaiterMatch, Expected: "InvalidNetworkInterfaceID.NotFound", }, }, + Logger: c.Config.Logger, + NewRequest: func(opts []request.Option) (*request.Request, error) { + var inCpy *DescribeNetworkInterfacesInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeNetworkInterfacesRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, } + w.ApplyOptions(opts...) - w := waiter.Waiter{ - Client: c, - Input: input, - Config: waiterCfg, - } - return w.Wait() + return w.WaitWithContext(ctx) } // WaitUntilPasswordDataAvailable uses the Amazon EC2 API operation @@ -608,26 +911,45 @@ func (c *EC2) WaitUntilNetworkInterfaceAvailable(input *DescribeNetworkInterface // If the condition is not meet within the max attempt window an error will // be returned. func (c *EC2) WaitUntilPasswordDataAvailable(input *GetPasswordDataInput) error { - waiterCfg := waiter.Config{ - Operation: "GetPasswordData", - Delay: 15, + return c.WaitUntilPasswordDataAvailableWithContext(aws.BackgroundContext(), input) +} + +// WaitUntilPasswordDataAvailableWithContext is an extended version of WaitUntilPasswordDataAvailable. +// 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 *EC2) WaitUntilPasswordDataAvailableWithContext(ctx aws.Context, input *GetPasswordDataInput, opts ...request.WaiterOption) error { + w := request.Waiter{ + Name: "WaitUntilPasswordDataAvailable", MaxAttempts: 40, - Acceptors: []waiter.WaitAcceptor{ + Delay: request.ConstantWaiterDelay(15 * time.Second), + Acceptors: []request.WaiterAcceptor{ { - State: "success", - Matcher: "path", - Argument: "length(PasswordData) > `0`", + State: request.SuccessWaiterState, + Matcher: request.PathWaiterMatch, Argument: "length(PasswordData) > `0`", Expected: true, }, }, + Logger: c.Config.Logger, + NewRequest: func(opts []request.Option) (*request.Request, error) { + var inCpy *GetPasswordDataInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.GetPasswordDataRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, } + w.ApplyOptions(opts...) - w := waiter.Waiter{ - Client: c, - Input: input, - Config: waiterCfg, - } - return w.Wait() + return w.WaitWithContext(ctx) } // WaitUntilSnapshotCompleted uses the Amazon EC2 API operation @@ -635,26 +957,45 @@ func (c *EC2) WaitUntilPasswordDataAvailable(input *GetPasswordDataInput) error // If the condition is not meet within the max attempt window an error will // be returned. func (c *EC2) WaitUntilSnapshotCompleted(input *DescribeSnapshotsInput) error { - waiterCfg := waiter.Config{ - Operation: "DescribeSnapshots", - Delay: 15, + return c.WaitUntilSnapshotCompletedWithContext(aws.BackgroundContext(), input) +} + +// WaitUntilSnapshotCompletedWithContext is an extended version of WaitUntilSnapshotCompleted. +// 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 *EC2) WaitUntilSnapshotCompletedWithContext(ctx aws.Context, input *DescribeSnapshotsInput, opts ...request.WaiterOption) error { + w := request.Waiter{ + Name: "WaitUntilSnapshotCompleted", MaxAttempts: 40, - Acceptors: []waiter.WaitAcceptor{ + Delay: request.ConstantWaiterDelay(15 * time.Second), + Acceptors: []request.WaiterAcceptor{ { - State: "success", - Matcher: "pathAll", - Argument: "Snapshots[].State", + State: request.SuccessWaiterState, + Matcher: request.PathAllWaiterMatch, Argument: "Snapshots[].State", Expected: "completed", }, }, + Logger: c.Config.Logger, + NewRequest: func(opts []request.Option) (*request.Request, error) { + var inCpy *DescribeSnapshotsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeSnapshotsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, } + w.ApplyOptions(opts...) - w := waiter.Waiter{ - Client: c, - Input: input, - Config: waiterCfg, - } - return w.Wait() + return w.WaitWithContext(ctx) } // WaitUntilSpotInstanceRequestFulfilled uses the Amazon EC2 API operation @@ -662,50 +1003,65 @@ func (c *EC2) WaitUntilSnapshotCompleted(input *DescribeSnapshotsInput) error { // If the condition is not meet within the max attempt window an error will // be returned. func (c *EC2) WaitUntilSpotInstanceRequestFulfilled(input *DescribeSpotInstanceRequestsInput) error { - waiterCfg := waiter.Config{ - Operation: "DescribeSpotInstanceRequests", - Delay: 15, + return c.WaitUntilSpotInstanceRequestFulfilledWithContext(aws.BackgroundContext(), input) +} + +// WaitUntilSpotInstanceRequestFulfilledWithContext is an extended version of WaitUntilSpotInstanceRequestFulfilled. +// 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 *EC2) WaitUntilSpotInstanceRequestFulfilledWithContext(ctx aws.Context, input *DescribeSpotInstanceRequestsInput, opts ...request.WaiterOption) error { + w := request.Waiter{ + Name: "WaitUntilSpotInstanceRequestFulfilled", MaxAttempts: 40, - Acceptors: []waiter.WaitAcceptor{ + Delay: request.ConstantWaiterDelay(15 * time.Second), + Acceptors: []request.WaiterAcceptor{ { - State: "success", - Matcher: "pathAll", - Argument: "SpotInstanceRequests[].Status.Code", + State: request.SuccessWaiterState, + Matcher: request.PathAllWaiterMatch, Argument: "SpotInstanceRequests[].Status.Code", Expected: "fulfilled", }, { - State: "failure", - Matcher: "pathAny", - Argument: "SpotInstanceRequests[].Status.Code", + State: request.FailureWaiterState, + Matcher: request.PathAnyWaiterMatch, Argument: "SpotInstanceRequests[].Status.Code", Expected: "schedule-expired", }, { - State: "failure", - Matcher: "pathAny", - Argument: "SpotInstanceRequests[].Status.Code", + State: request.FailureWaiterState, + Matcher: request.PathAnyWaiterMatch, Argument: "SpotInstanceRequests[].Status.Code", Expected: "canceled-before-fulfillment", }, { - State: "failure", - Matcher: "pathAny", - Argument: "SpotInstanceRequests[].Status.Code", + State: request.FailureWaiterState, + Matcher: request.PathAnyWaiterMatch, Argument: "SpotInstanceRequests[].Status.Code", Expected: "bad-parameters", }, { - State: "failure", - Matcher: "pathAny", - Argument: "SpotInstanceRequests[].Status.Code", + State: request.FailureWaiterState, + Matcher: request.PathAnyWaiterMatch, Argument: "SpotInstanceRequests[].Status.Code", Expected: "system-error", }, }, + Logger: c.Config.Logger, + NewRequest: func(opts []request.Option) (*request.Request, error) { + var inCpy *DescribeSpotInstanceRequestsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeSpotInstanceRequestsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, } + w.ApplyOptions(opts...) - w := waiter.Waiter{ - Client: c, - Input: input, - Config: waiterCfg, - } - return w.Wait() + return w.WaitWithContext(ctx) } // WaitUntilSubnetAvailable uses the Amazon EC2 API operation @@ -713,26 +1069,45 @@ func (c *EC2) WaitUntilSpotInstanceRequestFulfilled(input *DescribeSpotInstanceR // If the condition is not meet within the max attempt window an error will // be returned. func (c *EC2) WaitUntilSubnetAvailable(input *DescribeSubnetsInput) error { - waiterCfg := waiter.Config{ - Operation: "DescribeSubnets", - Delay: 15, + return c.WaitUntilSubnetAvailableWithContext(aws.BackgroundContext(), input) +} + +// WaitUntilSubnetAvailableWithContext is an extended version of WaitUntilSubnetAvailable. +// 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 *EC2) WaitUntilSubnetAvailableWithContext(ctx aws.Context, input *DescribeSubnetsInput, opts ...request.WaiterOption) error { + w := request.Waiter{ + Name: "WaitUntilSubnetAvailable", MaxAttempts: 40, - Acceptors: []waiter.WaitAcceptor{ + Delay: request.ConstantWaiterDelay(15 * time.Second), + Acceptors: []request.WaiterAcceptor{ { - State: "success", - Matcher: "pathAll", - Argument: "Subnets[].State", + State: request.SuccessWaiterState, + Matcher: request.PathAllWaiterMatch, Argument: "Subnets[].State", Expected: "available", }, }, + Logger: c.Config.Logger, + NewRequest: func(opts []request.Option) (*request.Request, error) { + var inCpy *DescribeSubnetsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeSubnetsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, } + w.ApplyOptions(opts...) - w := waiter.Waiter{ - Client: c, - Input: input, - Config: waiterCfg, - } - return w.Wait() + return w.WaitWithContext(ctx) } // WaitUntilSystemStatusOk uses the Amazon EC2 API operation @@ -740,26 +1115,45 @@ func (c *EC2) WaitUntilSubnetAvailable(input *DescribeSubnetsInput) error { // If the condition is not meet within the max attempt window an error will // be returned. func (c *EC2) WaitUntilSystemStatusOk(input *DescribeInstanceStatusInput) error { - waiterCfg := waiter.Config{ - Operation: "DescribeInstanceStatus", - Delay: 15, + return c.WaitUntilSystemStatusOkWithContext(aws.BackgroundContext(), input) +} + +// WaitUntilSystemStatusOkWithContext is an extended version of WaitUntilSystemStatusOk. +// 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 *EC2) WaitUntilSystemStatusOkWithContext(ctx aws.Context, input *DescribeInstanceStatusInput, opts ...request.WaiterOption) error { + w := request.Waiter{ + Name: "WaitUntilSystemStatusOk", MaxAttempts: 40, - Acceptors: []waiter.WaitAcceptor{ + Delay: request.ConstantWaiterDelay(15 * time.Second), + Acceptors: []request.WaiterAcceptor{ { - State: "success", - Matcher: "pathAll", - Argument: "InstanceStatuses[].SystemStatus.Status", + State: request.SuccessWaiterState, + Matcher: request.PathAllWaiterMatch, Argument: "InstanceStatuses[].SystemStatus.Status", Expected: "ok", }, }, + Logger: c.Config.Logger, + NewRequest: func(opts []request.Option) (*request.Request, error) { + var inCpy *DescribeInstanceStatusInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeInstanceStatusRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, } + w.ApplyOptions(opts...) - w := waiter.Waiter{ - Client: c, - Input: input, - Config: waiterCfg, - } - return w.Wait() + return w.WaitWithContext(ctx) } // WaitUntilVolumeAvailable uses the Amazon EC2 API operation @@ -767,32 +1161,50 @@ func (c *EC2) WaitUntilSystemStatusOk(input *DescribeInstanceStatusInput) error // If the condition is not meet within the max attempt window an error will // be returned. func (c *EC2) WaitUntilVolumeAvailable(input *DescribeVolumesInput) error { - waiterCfg := waiter.Config{ - Operation: "DescribeVolumes", - Delay: 15, + return c.WaitUntilVolumeAvailableWithContext(aws.BackgroundContext(), input) +} + +// WaitUntilVolumeAvailableWithContext is an extended version of WaitUntilVolumeAvailable. +// 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 *EC2) WaitUntilVolumeAvailableWithContext(ctx aws.Context, input *DescribeVolumesInput, opts ...request.WaiterOption) error { + w := request.Waiter{ + Name: "WaitUntilVolumeAvailable", MaxAttempts: 40, - Acceptors: []waiter.WaitAcceptor{ + Delay: request.ConstantWaiterDelay(15 * time.Second), + Acceptors: []request.WaiterAcceptor{ { - State: "success", - Matcher: "pathAll", - Argument: "Volumes[].State", + State: request.SuccessWaiterState, + Matcher: request.PathAllWaiterMatch, Argument: "Volumes[].State", Expected: "available", }, { - State: "failure", - Matcher: "pathAny", - Argument: "Volumes[].State", + State: request.FailureWaiterState, + Matcher: request.PathAnyWaiterMatch, Argument: "Volumes[].State", Expected: "deleted", }, }, + Logger: c.Config.Logger, + NewRequest: func(opts []request.Option) (*request.Request, error) { + var inCpy *DescribeVolumesInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeVolumesRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, } + w.ApplyOptions(opts...) - w := waiter.Waiter{ - Client: c, - Input: input, - Config: waiterCfg, - } - return w.Wait() + return w.WaitWithContext(ctx) } // WaitUntilVolumeDeleted uses the Amazon EC2 API operation @@ -800,32 +1212,50 @@ func (c *EC2) WaitUntilVolumeAvailable(input *DescribeVolumesInput) error { // If the condition is not meet within the max attempt window an error will // be returned. func (c *EC2) WaitUntilVolumeDeleted(input *DescribeVolumesInput) error { - waiterCfg := waiter.Config{ - Operation: "DescribeVolumes", - Delay: 15, + return c.WaitUntilVolumeDeletedWithContext(aws.BackgroundContext(), input) +} + +// WaitUntilVolumeDeletedWithContext is an extended version of WaitUntilVolumeDeleted. +// 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 *EC2) WaitUntilVolumeDeletedWithContext(ctx aws.Context, input *DescribeVolumesInput, opts ...request.WaiterOption) error { + w := request.Waiter{ + Name: "WaitUntilVolumeDeleted", MaxAttempts: 40, - Acceptors: []waiter.WaitAcceptor{ + Delay: request.ConstantWaiterDelay(15 * time.Second), + Acceptors: []request.WaiterAcceptor{ { - State: "success", - Matcher: "pathAll", - Argument: "Volumes[].State", + State: request.SuccessWaiterState, + Matcher: request.PathAllWaiterMatch, Argument: "Volumes[].State", Expected: "deleted", }, { - State: "success", - Matcher: "error", - Argument: "", + State: request.SuccessWaiterState, + Matcher: request.ErrorWaiterMatch, Expected: "InvalidVolume.NotFound", }, }, + Logger: c.Config.Logger, + NewRequest: func(opts []request.Option) (*request.Request, error) { + var inCpy *DescribeVolumesInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeVolumesRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, } + w.ApplyOptions(opts...) - w := waiter.Waiter{ - Client: c, - Input: input, - Config: waiterCfg, - } - return w.Wait() + return w.WaitWithContext(ctx) } // WaitUntilVolumeInUse uses the Amazon EC2 API operation @@ -833,32 +1263,50 @@ func (c *EC2) WaitUntilVolumeDeleted(input *DescribeVolumesInput) error { // If the condition is not meet within the max attempt window an error will // be returned. func (c *EC2) WaitUntilVolumeInUse(input *DescribeVolumesInput) error { - waiterCfg := waiter.Config{ - Operation: "DescribeVolumes", - Delay: 15, + return c.WaitUntilVolumeInUseWithContext(aws.BackgroundContext(), input) +} + +// WaitUntilVolumeInUseWithContext is an extended version of WaitUntilVolumeInUse. +// 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 *EC2) WaitUntilVolumeInUseWithContext(ctx aws.Context, input *DescribeVolumesInput, opts ...request.WaiterOption) error { + w := request.Waiter{ + Name: "WaitUntilVolumeInUse", MaxAttempts: 40, - Acceptors: []waiter.WaitAcceptor{ + Delay: request.ConstantWaiterDelay(15 * time.Second), + Acceptors: []request.WaiterAcceptor{ { - State: "success", - Matcher: "pathAll", - Argument: "Volumes[].State", + State: request.SuccessWaiterState, + Matcher: request.PathAllWaiterMatch, Argument: "Volumes[].State", Expected: "in-use", }, { - State: "failure", - Matcher: "pathAny", - Argument: "Volumes[].State", + State: request.FailureWaiterState, + Matcher: request.PathAnyWaiterMatch, Argument: "Volumes[].State", Expected: "deleted", }, }, + Logger: c.Config.Logger, + NewRequest: func(opts []request.Option) (*request.Request, error) { + var inCpy *DescribeVolumesInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeVolumesRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, } + w.ApplyOptions(opts...) - w := waiter.Waiter{ - Client: c, - Input: input, - Config: waiterCfg, - } - return w.Wait() + return w.WaitWithContext(ctx) } // WaitUntilVpcAvailable uses the Amazon EC2 API operation @@ -866,26 +1314,45 @@ func (c *EC2) WaitUntilVolumeInUse(input *DescribeVolumesInput) error { // If the condition is not meet within the max attempt window an error will // be returned. func (c *EC2) WaitUntilVpcAvailable(input *DescribeVpcsInput) error { - waiterCfg := waiter.Config{ - Operation: "DescribeVpcs", - Delay: 15, + return c.WaitUntilVpcAvailableWithContext(aws.BackgroundContext(), input) +} + +// WaitUntilVpcAvailableWithContext is an extended version of WaitUntilVpcAvailable. +// 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 *EC2) WaitUntilVpcAvailableWithContext(ctx aws.Context, input *DescribeVpcsInput, opts ...request.WaiterOption) error { + w := request.Waiter{ + Name: "WaitUntilVpcAvailable", MaxAttempts: 40, - Acceptors: []waiter.WaitAcceptor{ + Delay: request.ConstantWaiterDelay(15 * time.Second), + Acceptors: []request.WaiterAcceptor{ { - State: "success", - Matcher: "pathAll", - Argument: "Vpcs[].State", + State: request.SuccessWaiterState, + Matcher: request.PathAllWaiterMatch, Argument: "Vpcs[].State", Expected: "available", }, }, + Logger: c.Config.Logger, + NewRequest: func(opts []request.Option) (*request.Request, error) { + var inCpy *DescribeVpcsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeVpcsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, } + w.ApplyOptions(opts...) - w := waiter.Waiter{ - Client: c, - Input: input, - Config: waiterCfg, - } - return w.Wait() + return w.WaitWithContext(ctx) } // WaitUntilVpcExists uses the Amazon EC2 API operation @@ -893,32 +1360,50 @@ func (c *EC2) WaitUntilVpcAvailable(input *DescribeVpcsInput) error { // If the condition is not meet within the max attempt window an error will // be returned. func (c *EC2) WaitUntilVpcExists(input *DescribeVpcsInput) error { - waiterCfg := waiter.Config{ - Operation: "DescribeVpcs", - Delay: 1, + return c.WaitUntilVpcExistsWithContext(aws.BackgroundContext(), input) +} + +// WaitUntilVpcExistsWithContext is an extended version of WaitUntilVpcExists. +// 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 *EC2) WaitUntilVpcExistsWithContext(ctx aws.Context, input *DescribeVpcsInput, opts ...request.WaiterOption) error { + w := request.Waiter{ + Name: "WaitUntilVpcExists", MaxAttempts: 5, - Acceptors: []waiter.WaitAcceptor{ + Delay: request.ConstantWaiterDelay(1 * time.Second), + Acceptors: []request.WaiterAcceptor{ { - State: "success", - Matcher: "status", - Argument: "", + State: request.SuccessWaiterState, + Matcher: request.StatusWaiterMatch, Expected: 200, }, { - State: "retry", - Matcher: "error", - Argument: "", + State: request.RetryWaiterState, + Matcher: request.ErrorWaiterMatch, Expected: "InvalidVpcID.NotFound", }, }, + Logger: c.Config.Logger, + NewRequest: func(opts []request.Option) (*request.Request, error) { + var inCpy *DescribeVpcsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeVpcsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, } + w.ApplyOptions(opts...) - w := waiter.Waiter{ - Client: c, - Input: input, - Config: waiterCfg, - } - return w.Wait() + return w.WaitWithContext(ctx) } // WaitUntilVpcPeeringConnectionDeleted uses the Amazon EC2 API operation @@ -926,32 +1411,50 @@ func (c *EC2) WaitUntilVpcExists(input *DescribeVpcsInput) error { // If the condition is not meet within the max attempt window an error will // be returned. func (c *EC2) WaitUntilVpcPeeringConnectionDeleted(input *DescribeVpcPeeringConnectionsInput) error { - waiterCfg := waiter.Config{ - Operation: "DescribeVpcPeeringConnections", - Delay: 15, + return c.WaitUntilVpcPeeringConnectionDeletedWithContext(aws.BackgroundContext(), input) +} + +// WaitUntilVpcPeeringConnectionDeletedWithContext is an extended version of WaitUntilVpcPeeringConnectionDeleted. +// 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 *EC2) WaitUntilVpcPeeringConnectionDeletedWithContext(ctx aws.Context, input *DescribeVpcPeeringConnectionsInput, opts ...request.WaiterOption) error { + w := request.Waiter{ + Name: "WaitUntilVpcPeeringConnectionDeleted", MaxAttempts: 40, - Acceptors: []waiter.WaitAcceptor{ + Delay: request.ConstantWaiterDelay(15 * time.Second), + Acceptors: []request.WaiterAcceptor{ { - State: "success", - Matcher: "pathAll", - Argument: "VpcPeeringConnections[].Status.Code", + State: request.SuccessWaiterState, + Matcher: request.PathAllWaiterMatch, Argument: "VpcPeeringConnections[].Status.Code", Expected: "deleted", }, { - State: "success", - Matcher: "error", - Argument: "", + State: request.SuccessWaiterState, + Matcher: request.ErrorWaiterMatch, Expected: "InvalidVpcPeeringConnectionID.NotFound", }, }, + Logger: c.Config.Logger, + NewRequest: func(opts []request.Option) (*request.Request, error) { + var inCpy *DescribeVpcPeeringConnectionsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeVpcPeeringConnectionsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, } + w.ApplyOptions(opts...) - w := waiter.Waiter{ - Client: c, - Input: input, - Config: waiterCfg, - } - return w.Wait() + return w.WaitWithContext(ctx) } // WaitUntilVpcPeeringConnectionExists uses the Amazon EC2 API operation @@ -959,32 +1462,50 @@ func (c *EC2) WaitUntilVpcPeeringConnectionDeleted(input *DescribeVpcPeeringConn // If the condition is not meet within the max attempt window an error will // be returned. func (c *EC2) WaitUntilVpcPeeringConnectionExists(input *DescribeVpcPeeringConnectionsInput) error { - waiterCfg := waiter.Config{ - Operation: "DescribeVpcPeeringConnections", - Delay: 15, + return c.WaitUntilVpcPeeringConnectionExistsWithContext(aws.BackgroundContext(), input) +} + +// WaitUntilVpcPeeringConnectionExistsWithContext is an extended version of WaitUntilVpcPeeringConnectionExists. +// 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 *EC2) WaitUntilVpcPeeringConnectionExistsWithContext(ctx aws.Context, input *DescribeVpcPeeringConnectionsInput, opts ...request.WaiterOption) error { + w := request.Waiter{ + Name: "WaitUntilVpcPeeringConnectionExists", MaxAttempts: 40, - Acceptors: []waiter.WaitAcceptor{ + Delay: request.ConstantWaiterDelay(15 * time.Second), + Acceptors: []request.WaiterAcceptor{ { - State: "success", - Matcher: "status", - Argument: "", + State: request.SuccessWaiterState, + Matcher: request.StatusWaiterMatch, Expected: 200, }, { - State: "retry", - Matcher: "error", - Argument: "", + State: request.RetryWaiterState, + Matcher: request.ErrorWaiterMatch, Expected: "InvalidVpcPeeringConnectionID.NotFound", }, }, + Logger: c.Config.Logger, + NewRequest: func(opts []request.Option) (*request.Request, error) { + var inCpy *DescribeVpcPeeringConnectionsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeVpcPeeringConnectionsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, } + w.ApplyOptions(opts...) - w := waiter.Waiter{ - Client: c, - Input: input, - Config: waiterCfg, - } - return w.Wait() + return w.WaitWithContext(ctx) } // WaitUntilVpnConnectionAvailable uses the Amazon EC2 API operation @@ -992,38 +1513,55 @@ func (c *EC2) WaitUntilVpcPeeringConnectionExists(input *DescribeVpcPeeringConne // If the condition is not meet within the max attempt window an error will // be returned. func (c *EC2) WaitUntilVpnConnectionAvailable(input *DescribeVpnConnectionsInput) error { - waiterCfg := waiter.Config{ - Operation: "DescribeVpnConnections", - Delay: 15, + return c.WaitUntilVpnConnectionAvailableWithContext(aws.BackgroundContext(), input) +} + +// WaitUntilVpnConnectionAvailableWithContext is an extended version of WaitUntilVpnConnectionAvailable. +// 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 *EC2) WaitUntilVpnConnectionAvailableWithContext(ctx aws.Context, input *DescribeVpnConnectionsInput, opts ...request.WaiterOption) error { + w := request.Waiter{ + Name: "WaitUntilVpnConnectionAvailable", MaxAttempts: 40, - Acceptors: []waiter.WaitAcceptor{ + Delay: request.ConstantWaiterDelay(15 * time.Second), + Acceptors: []request.WaiterAcceptor{ { - State: "success", - Matcher: "pathAll", - Argument: "VpnConnections[].State", + State: request.SuccessWaiterState, + Matcher: request.PathAllWaiterMatch, Argument: "VpnConnections[].State", Expected: "available", }, { - State: "failure", - Matcher: "pathAny", - Argument: "VpnConnections[].State", + State: request.FailureWaiterState, + Matcher: request.PathAnyWaiterMatch, Argument: "VpnConnections[].State", Expected: "deleting", }, { - State: "failure", - Matcher: "pathAny", - Argument: "VpnConnections[].State", + State: request.FailureWaiterState, + Matcher: request.PathAnyWaiterMatch, Argument: "VpnConnections[].State", Expected: "deleted", }, }, + Logger: c.Config.Logger, + NewRequest: func(opts []request.Option) (*request.Request, error) { + var inCpy *DescribeVpnConnectionsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeVpnConnectionsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, } + w.ApplyOptions(opts...) - w := waiter.Waiter{ - Client: c, - Input: input, - Config: waiterCfg, - } - return w.Wait() + return w.WaitWithContext(ctx) } // WaitUntilVpnConnectionDeleted uses the Amazon EC2 API operation @@ -1031,30 +1569,48 @@ func (c *EC2) WaitUntilVpnConnectionAvailable(input *DescribeVpnConnectionsInput // If the condition is not meet within the max attempt window an error will // be returned. func (c *EC2) WaitUntilVpnConnectionDeleted(input *DescribeVpnConnectionsInput) error { - waiterCfg := waiter.Config{ - Operation: "DescribeVpnConnections", - Delay: 15, + return c.WaitUntilVpnConnectionDeletedWithContext(aws.BackgroundContext(), input) +} + +// WaitUntilVpnConnectionDeletedWithContext is an extended version of WaitUntilVpnConnectionDeleted. +// 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 *EC2) WaitUntilVpnConnectionDeletedWithContext(ctx aws.Context, input *DescribeVpnConnectionsInput, opts ...request.WaiterOption) error { + w := request.Waiter{ + Name: "WaitUntilVpnConnectionDeleted", MaxAttempts: 40, - Acceptors: []waiter.WaitAcceptor{ + Delay: request.ConstantWaiterDelay(15 * time.Second), + Acceptors: []request.WaiterAcceptor{ { - State: "success", - Matcher: "pathAll", - Argument: "VpnConnections[].State", + State: request.SuccessWaiterState, + Matcher: request.PathAllWaiterMatch, Argument: "VpnConnections[].State", Expected: "deleted", }, { - State: "failure", - Matcher: "pathAny", - Argument: "VpnConnections[].State", + State: request.FailureWaiterState, + Matcher: request.PathAnyWaiterMatch, Argument: "VpnConnections[].State", Expected: "pending", }, }, + Logger: c.Config.Logger, + NewRequest: func(opts []request.Option) (*request.Request, error) { + var inCpy *DescribeVpnConnectionsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeVpnConnectionsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, } + w.ApplyOptions(opts...) - w := waiter.Waiter{ - Client: c, - Input: input, - Config: waiterCfg, - } - return w.Wait() + return w.WaitWithContext(ctx) } diff --git a/vendor/github.com/aws/aws-sdk-go/service/ecr/api.go b/vendor/github.com/aws/aws-sdk-go/service/ecr/api.go index fc46f5145..c06242daa 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 @@ -1,11 +1,11 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. -// Package ecr provides a client for Amazon EC2 Container Registry. package ecr import ( "time" + "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awsutil" "github.com/aws/aws-sdk-go/aws/request" ) @@ -84,8 +84,23 @@ func (c *ECR) BatchCheckLayerAvailabilityRequest(input *BatchCheckLayerAvailabil // Please also see https://docs.aws.amazon.com/goto/WebAPI/ecr-2015-09-21/BatchCheckLayerAvailability func (c *ECR) BatchCheckLayerAvailability(input *BatchCheckLayerAvailabilityInput) (*BatchCheckLayerAvailabilityOutput, error) { req, out := c.BatchCheckLayerAvailabilityRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// BatchCheckLayerAvailabilityWithContext is the same as BatchCheckLayerAvailability with the addition of +// the ability to pass a context and additional request options. +// +// See BatchCheckLayerAvailability 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 *ECR) BatchCheckLayerAvailabilityWithContext(ctx aws.Context, input *BatchCheckLayerAvailabilityInput, opts ...request.Option) (*BatchCheckLayerAvailabilityOutput, error) { + req, out := c.BatchCheckLayerAvailabilityRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opBatchDeleteImage = "BatchDeleteImage" @@ -165,8 +180,23 @@ func (c *ECR) BatchDeleteImageRequest(input *BatchDeleteImageInput) (req *reques // Please also see https://docs.aws.amazon.com/goto/WebAPI/ecr-2015-09-21/BatchDeleteImage func (c *ECR) BatchDeleteImage(input *BatchDeleteImageInput) (*BatchDeleteImageOutput, error) { req, out := c.BatchDeleteImageRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// BatchDeleteImageWithContext is the same as BatchDeleteImage with the addition of +// the ability to pass a context and additional request options. +// +// See BatchDeleteImage 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 *ECR) BatchDeleteImageWithContext(ctx aws.Context, input *BatchDeleteImageInput, opts ...request.Option) (*BatchDeleteImageOutput, error) { + req, out := c.BatchDeleteImageRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opBatchGetImage = "BatchGetImage" @@ -239,8 +269,23 @@ func (c *ECR) BatchGetImageRequest(input *BatchGetImageInput) (req *request.Requ // Please also see https://docs.aws.amazon.com/goto/WebAPI/ecr-2015-09-21/BatchGetImage func (c *ECR) BatchGetImage(input *BatchGetImageInput) (*BatchGetImageOutput, error) { req, out := c.BatchGetImageRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// BatchGetImageWithContext is the same as BatchGetImage with the addition of +// the ability to pass a context and additional request options. +// +// See BatchGetImage 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 *ECR) BatchGetImageWithContext(ctx aws.Context, input *BatchGetImageInput, opts ...request.Option) (*BatchGetImageOutput, error) { + req, out := c.BatchGetImageRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCompleteLayerUpload = "CompleteLayerUpload" @@ -335,8 +380,23 @@ func (c *ECR) CompleteLayerUploadRequest(input *CompleteLayerUploadInput) (req * // Please also see 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) - err := req.Send() - return out, err + return out, req.Send() +} + +// CompleteLayerUploadWithContext is the same as CompleteLayerUpload with the addition of +// the ability to pass a context and additional request options. +// +// See CompleteLayerUpload 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 *ECR) CompleteLayerUploadWithContext(ctx aws.Context, input *CompleteLayerUploadInput, opts ...request.Option) (*CompleteLayerUploadOutput, error) { + req, out := c.CompleteLayerUploadRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateRepository = "CreateRepository" @@ -413,8 +473,23 @@ func (c *ECR) CreateRepositoryRequest(input *CreateRepositoryInput) (req *reques // Please also see 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) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateRepositoryWithContext is the same as CreateRepository with the addition of +// the ability to pass a context and additional request options. +// +// See CreateRepository 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 *ECR) CreateRepositoryWithContext(ctx aws.Context, input *CreateRepositoryInput, opts ...request.Option) (*CreateRepositoryOutput, error) { + req, out := c.CreateRepositoryRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteRepository = "DeleteRepository" @@ -491,8 +566,23 @@ func (c *ECR) DeleteRepositoryRequest(input *DeleteRepositoryInput) (req *reques // Please also see 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) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteRepositoryWithContext is the same as DeleteRepository with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteRepository 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 *ECR) DeleteRepositoryWithContext(ctx aws.Context, input *DeleteRepositoryInput, opts ...request.Option) (*DeleteRepositoryOutput, error) { + req, out := c.DeleteRepositoryRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteRepositoryPolicy = "DeleteRepositoryPolicy" @@ -568,8 +658,23 @@ func (c *ECR) DeleteRepositoryPolicyRequest(input *DeleteRepositoryPolicyInput) // Please also see https://docs.aws.amazon.com/goto/WebAPI/ecr-2015-09-21/DeleteRepositoryPolicy func (c *ECR) DeleteRepositoryPolicy(input *DeleteRepositoryPolicyInput) (*DeleteRepositoryPolicyOutput, error) { req, out := c.DeleteRepositoryPolicyRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteRepositoryPolicyWithContext is the same as DeleteRepositoryPolicy with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteRepositoryPolicy 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 *ECR) DeleteRepositoryPolicyWithContext(ctx aws.Context, input *DeleteRepositoryPolicyInput, opts ...request.Option) (*DeleteRepositoryPolicyOutput, error) { + req, out := c.DeleteRepositoryPolicyRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeImages = "DescribeImages" @@ -656,8 +761,23 @@ func (c *ECR) DescribeImagesRequest(input *DescribeImagesInput) (req *request.Re // Please also see https://docs.aws.amazon.com/goto/WebAPI/ecr-2015-09-21/DescribeImages func (c *ECR) DescribeImages(input *DescribeImagesInput) (*DescribeImagesOutput, error) { req, out := c.DescribeImagesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeImagesWithContext is the same as DescribeImages with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeImages 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 *ECR) DescribeImagesWithContext(ctx aws.Context, input *DescribeImagesInput, opts ...request.Option) (*DescribeImagesOutput, error) { + req, out := c.DescribeImagesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // DescribeImagesPages iterates over the pages of a DescribeImages operation, @@ -677,12 +797,37 @@ func (c *ECR) DescribeImages(input *DescribeImagesInput) (*DescribeImagesOutput, // return pageNum <= 3 // }) // -func (c *ECR) DescribeImagesPages(input *DescribeImagesInput, fn func(p *DescribeImagesOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.DescribeImagesRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*DescribeImagesOutput), lastPage) - }) +func (c *ECR) DescribeImagesPages(input *DescribeImagesInput, fn func(*DescribeImagesOutput, bool) bool) error { + return c.DescribeImagesPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// DescribeImagesPagesWithContext same as DescribeImagesPages 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 *ECR) DescribeImagesPagesWithContext(ctx aws.Context, input *DescribeImagesInput, fn func(*DescribeImagesOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *DescribeImagesInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeImagesRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*DescribeImagesOutput), !p.HasNextPage()) + } + return p.Err() } const opDescribeRepositories = "DescribeRepositories" @@ -760,8 +905,23 @@ func (c *ECR) DescribeRepositoriesRequest(input *DescribeRepositoriesInput) (req // Please also see https://docs.aws.amazon.com/goto/WebAPI/ecr-2015-09-21/DescribeRepositories func (c *ECR) DescribeRepositories(input *DescribeRepositoriesInput) (*DescribeRepositoriesOutput, error) { req, out := c.DescribeRepositoriesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeRepositoriesWithContext is the same as DescribeRepositories with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeRepositories 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 *ECR) DescribeRepositoriesWithContext(ctx aws.Context, input *DescribeRepositoriesInput, opts ...request.Option) (*DescribeRepositoriesOutput, error) { + req, out := c.DescribeRepositoriesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // DescribeRepositoriesPages iterates over the pages of a DescribeRepositories operation, @@ -781,12 +941,37 @@ func (c *ECR) DescribeRepositories(input *DescribeRepositoriesInput) (*DescribeR // return pageNum <= 3 // }) // -func (c *ECR) DescribeRepositoriesPages(input *DescribeRepositoriesInput, fn func(p *DescribeRepositoriesOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.DescribeRepositoriesRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*DescribeRepositoriesOutput), lastPage) - }) +func (c *ECR) DescribeRepositoriesPages(input *DescribeRepositoriesInput, fn func(*DescribeRepositoriesOutput, bool) bool) error { + return c.DescribeRepositoriesPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// DescribeRepositoriesPagesWithContext same as DescribeRepositoriesPages 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 *ECR) DescribeRepositoriesPagesWithContext(ctx aws.Context, input *DescribeRepositoriesInput, fn func(*DescribeRepositoriesOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *DescribeRepositoriesInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeRepositoriesRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*DescribeRepositoriesOutput), !p.HasNextPage()) + } + return p.Err() } const opGetAuthorizationToken = "GetAuthorizationToken" @@ -861,8 +1046,23 @@ func (c *ECR) GetAuthorizationTokenRequest(input *GetAuthorizationTokenInput) (r // Please also see https://docs.aws.amazon.com/goto/WebAPI/ecr-2015-09-21/GetAuthorizationToken func (c *ECR) GetAuthorizationToken(input *GetAuthorizationTokenInput) (*GetAuthorizationTokenOutput, error) { req, out := c.GetAuthorizationTokenRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetAuthorizationTokenWithContext is the same as GetAuthorizationToken with the addition of +// the ability to pass a context and additional request options. +// +// See GetAuthorizationToken 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 *ECR) GetAuthorizationTokenWithContext(ctx aws.Context, input *GetAuthorizationTokenInput, opts ...request.Option) (*GetAuthorizationTokenOutput, error) { + req, out := c.GetAuthorizationTokenRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetDownloadUrlForLayer = "GetDownloadUrlForLayer" @@ -947,8 +1147,23 @@ func (c *ECR) GetDownloadUrlForLayerRequest(input *GetDownloadUrlForLayerInput) // Please also see https://docs.aws.amazon.com/goto/WebAPI/ecr-2015-09-21/GetDownloadUrlForLayer func (c *ECR) GetDownloadUrlForLayer(input *GetDownloadUrlForLayerInput) (*GetDownloadUrlForLayerOutput, error) { req, out := c.GetDownloadUrlForLayerRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetDownloadUrlForLayerWithContext is the same as GetDownloadUrlForLayer with the addition of +// the ability to pass a context and additional request options. +// +// See GetDownloadUrlForLayer 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 *ECR) GetDownloadUrlForLayerWithContext(ctx aws.Context, input *GetDownloadUrlForLayerInput, opts ...request.Option) (*GetDownloadUrlForLayerOutput, error) { + req, out := c.GetDownloadUrlForLayerRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetRepositoryPolicy = "GetRepositoryPolicy" @@ -1024,8 +1239,23 @@ func (c *ECR) GetRepositoryPolicyRequest(input *GetRepositoryPolicyInput) (req * // Please also see https://docs.aws.amazon.com/goto/WebAPI/ecr-2015-09-21/GetRepositoryPolicy func (c *ECR) GetRepositoryPolicy(input *GetRepositoryPolicyInput) (*GetRepositoryPolicyOutput, error) { req, out := c.GetRepositoryPolicyRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetRepositoryPolicyWithContext is the same as GetRepositoryPolicy with the addition of +// the ability to pass a context and additional request options. +// +// See GetRepositoryPolicy 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 *ECR) GetRepositoryPolicyWithContext(ctx aws.Context, input *GetRepositoryPolicyInput, opts ...request.Option) (*GetRepositoryPolicyOutput, error) { + req, out := c.GetRepositoryPolicyRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opInitiateLayerUpload = "InitiateLayerUpload" @@ -1101,8 +1331,23 @@ func (c *ECR) InitiateLayerUploadRequest(input *InitiateLayerUploadInput) (req * // Please also see 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) - err := req.Send() - return out, err + return out, req.Send() +} + +// InitiateLayerUploadWithContext is the same as InitiateLayerUpload with the addition of +// the ability to pass a context and additional request options. +// +// See InitiateLayerUpload 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 *ECR) InitiateLayerUploadWithContext(ctx aws.Context, input *InitiateLayerUploadInput, opts ...request.Option) (*InitiateLayerUploadOutput, error) { + req, out := c.InitiateLayerUploadRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opListImages = "ListImages" @@ -1186,8 +1431,23 @@ func (c *ECR) ListImagesRequest(input *ListImagesInput) (req *request.Request, o // Please also see https://docs.aws.amazon.com/goto/WebAPI/ecr-2015-09-21/ListImages func (c *ECR) ListImages(input *ListImagesInput) (*ListImagesOutput, error) { req, out := c.ListImagesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListImagesWithContext is the same as ListImages with the addition of +// the ability to pass a context and additional request options. +// +// See ListImages 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 *ECR) ListImagesWithContext(ctx aws.Context, input *ListImagesInput, opts ...request.Option) (*ListImagesOutput, error) { + req, out := c.ListImagesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // ListImagesPages iterates over the pages of a ListImages operation, @@ -1207,12 +1467,37 @@ func (c *ECR) ListImages(input *ListImagesInput) (*ListImagesOutput, error) { // return pageNum <= 3 // }) // -func (c *ECR) ListImagesPages(input *ListImagesInput, fn func(p *ListImagesOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.ListImagesRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*ListImagesOutput), lastPage) - }) +func (c *ECR) ListImagesPages(input *ListImagesInput, fn func(*ListImagesOutput, bool) bool) error { + return c.ListImagesPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListImagesPagesWithContext same as ListImagesPages 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 *ECR) ListImagesPagesWithContext(ctx aws.Context, input *ListImagesInput, fn func(*ListImagesOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListImagesInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListImagesRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*ListImagesOutput), !p.HasNextPage()) + } + return p.Err() } const opPutImage = "PutImage" @@ -1302,8 +1587,23 @@ func (c *ECR) PutImageRequest(input *PutImageInput) (req *request.Request, outpu // Please also see 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) - err := req.Send() - return out, err + return out, req.Send() +} + +// PutImageWithContext is the same as PutImage with the addition of +// the ability to pass a context and additional request options. +// +// See PutImage 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 *ECR) PutImageWithContext(ctx aws.Context, input *PutImageInput, opts ...request.Option) (*PutImageOutput, error) { + req, out := c.PutImageRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opSetRepositoryPolicy = "SetRepositoryPolicy" @@ -1375,8 +1675,23 @@ func (c *ECR) SetRepositoryPolicyRequest(input *SetRepositoryPolicyInput) (req * // Please also see https://docs.aws.amazon.com/goto/WebAPI/ecr-2015-09-21/SetRepositoryPolicy func (c *ECR) SetRepositoryPolicy(input *SetRepositoryPolicyInput) (*SetRepositoryPolicyOutput, error) { req, out := c.SetRepositoryPolicyRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// SetRepositoryPolicyWithContext is the same as SetRepositoryPolicy with the addition of +// the ability to pass a context and additional request options. +// +// See SetRepositoryPolicy 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 *ECR) SetRepositoryPolicyWithContext(ctx aws.Context, input *SetRepositoryPolicyInput, opts ...request.Option) (*SetRepositoryPolicyOutput, error) { + req, out := c.SetRepositoryPolicyRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opUploadLayerPart = "UploadLayerPart" @@ -1466,8 +1781,23 @@ func (c *ECR) UploadLayerPartRequest(input *UploadLayerPartInput) (req *request. // Please also see 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) - err := req.Send() - return out, err + return out, req.Send() +} + +// UploadLayerPartWithContext is the same as UploadLayerPart with the addition of +// the ability to pass a context and additional request options. +// +// See UploadLayerPart 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 *ECR) UploadLayerPartWithContext(ctx aws.Context, input *UploadLayerPartInput, opts ...request.Option) (*UploadLayerPartOutput, error) { + req, out := c.UploadLayerPartRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // An object representing authorization data for an Amazon ECR registry. 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 new file mode 100644 index 000000000..004e50f0a --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/service/ecr/doc.go @@ -0,0 +1,85 @@ +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. + +// Package ecr provides the client and types for making API +// requests to Amazon EC2 Container Registry. +// +// Amazon EC2 Container Registry (Amazon ECR) is a managed AWS 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 +// using AWS 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. +// +// See https://docs.aws.amazon.com/goto/WebAPI/ecr-2015-09-21 for more information on this service. +// +// See ecr package documentation for more information. +// https://docs.aws.amazon.com/sdk-for-go/api/service/ecr/ +// +// Using the Client +// +// To use the client for Amazon EC2 Container Registry you will first need +// to create a new instance of it. +// +// When creating a client for an AWS service you'll first need to have a Session +// already created. The Session provides configuration that can be shared +// between multiple service clients. Additional configuration can be applied to +// the Session and service's client when they are constructed. The aws package's +// Config type contains several fields such as Region for the AWS Region the +// client should make API requests too. The optional Config value can be provided +// as the variadic argument for Sessions and client creation. +// +// Once the service's client is created you can use it to make API requests the +// AWS service. These clients are safe to use concurrently. +// +// // Create a session to share configuration, and load external configuration. +// sess := session.Must(session.NewSession()) +// +// // Create the service's client with the session. +// svc := ecr.New(sess) +// +// See the SDK's documentation for more information on how to use service clients. +// https://docs.aws.amazon.com/sdk-for-go/api/ +// +// See aws package's Config type for more information on configuration options. +// https://docs.aws.amazon.com/sdk-for-go/api/aws/#Config +// +// See the Amazon EC2 Container Registry client ECR for more +// information on creating the service's client. +// https://docs.aws.amazon.com/sdk-for-go/api/service/ecr/#New +// +// Once the client is created you can make an API request to the service. +// Each API method takes a input parameter, and returns the service response +// and an error. +// +// The API method will document which error codes the service can be returned +// by the operation if the service models the API operation's errors. These +// errors will also be available as const strings prefixed with "ErrCode". +// +// result, err := svc.BatchCheckLayerAvailability(params) +// if err != nil { +// // Cast err to awserr.Error to handle specific error codes. +// aerr, ok := err.(awserr.Error) +// if ok && aerr.Code() == { +// // Specific error code handling +// } +// return err +// } +// +// fmt.Println("BatchCheckLayerAvailability result:") +// fmt.Println(result) +// +// Using the Client with Context +// +// The service's client also provides methods to make API requests with a Context +// value. This allows you to control the timeout, and cancellation of pending +// requests. These methods also take request Option as variadic parameter to apply +// additional configuration to the API request. +// +// ctx := context.Background() +// +// result, err := svc.BatchCheckLayerAvailabilityWithContext(ctx, params) +// +// See the request package documentation for more information on using Context pattern +// with the SDK. +// https://docs.aws.amazon.com/sdk-for-go/api/aws/request/ +package ecr 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 c51948bc7..4399e6a29 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 @@ -1,4 +1,4 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. package ecr diff --git a/vendor/github.com/aws/aws-sdk-go/service/ecr/service.go b/vendor/github.com/aws/aws-sdk-go/service/ecr/service.go index 2c7904b75..95de12e25 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/ecr/service.go +++ b/vendor/github.com/aws/aws-sdk-go/service/ecr/service.go @@ -1,4 +1,4 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. package ecr @@ -11,15 +11,12 @@ import ( "github.com/aws/aws-sdk-go/private/protocol/jsonrpc" ) -// Amazon EC2 Container Registry (Amazon ECR) is a managed AWS 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 -// using AWS 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. -// The service client's operations are safe to be used concurrently. -// It is not safe to mutate any of the client's properties though. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/ecr-2015-09-21 +// ECR provides the API operation methods for making requests to +// Amazon EC2 Container Registry. See this package's package overview docs +// for details on the service. +// +// ECR methods are safe to use concurrently. It is not safe to +// modify mutate any of the struct's properties though. type ECR struct { *client.Client } diff --git a/vendor/github.com/aws/aws-sdk-go/service/ecs/api.go b/vendor/github.com/aws/aws-sdk-go/service/ecs/api.go index 68ccbd511..5ad7c3672 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/ecs/api.go +++ b/vendor/github.com/aws/aws-sdk-go/service/ecs/api.go @@ -1,12 +1,12 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. -// Package ecs provides a client for Amazon EC2 Container Service. package ecs import ( "fmt" "time" + "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awsutil" "github.com/aws/aws-sdk-go/aws/request" ) @@ -83,8 +83,23 @@ func (c *ECS) CreateClusterRequest(input *CreateClusterInput) (req *request.Requ // Please also see https://docs.aws.amazon.com/goto/WebAPI/ecs-2014-11-13/CreateCluster func (c *ECS) CreateCluster(input *CreateClusterInput) (*CreateClusterOutput, error) { req, out := c.CreateClusterRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateClusterWithContext is the same as CreateCluster with the addition of +// the ability to pass a context and additional request options. +// +// See CreateCluster 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 *ECS) CreateClusterWithContext(ctx aws.Context, input *CreateClusterInput, opts ...request.Option) (*CreateClusterOutput, error) { + req, out := c.CreateClusterRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateService = "CreateService" @@ -153,23 +168,23 @@ func (c *ECS) CreateServiceRequest(input *CreateServiceInput) (req *request.Requ // service's tasks that must remain in the RUNNING state during a deployment, // as a percentage of the desiredCount (rounded up to the nearest integer). // This parameter enables you to deploy without using additional cluster capacity. -// For example, if desiredCount is four tasks and the minimum is 50%, the scheduler -// can stop two existing tasks to free up cluster capacity before starting two -// new tasks. Tasks for services that do not use a load balancer are considered -// healthy if they are in the RUNNING state. Tasks for services that use a load -// balancer are considered healthy if they are in the RUNNING state and the -// container instance they are hosted on is reported as healthy by the load -// balancer. The default value is 50% in the console and 100% for the AWS CLI, -// the AWS SDKs, and the APIs. +// For example, if your service has a desiredCount of four tasks and a minimumHealthyPercent +// of 50%, the scheduler can stop two existing tasks to free up cluster capacity +// before starting two new tasks. Tasks for services that do not use a load +// balancer are considered healthy if they are in the RUNNING state. Tasks for +// services that do use a load balancer are considered healthy if they are in +// the RUNNING state and the container instance they are hosted on is reported +// as healthy by the load balancer. The default value for minimumHealthyPercent +// is 50% in the console and 100% for the AWS CLI, the AWS SDKs, and the APIs. // // The maximumPercent parameter represents an upper limit on the number of your // service's tasks that are allowed in the RUNNING or PENDING state during a // deployment, as a percentage of the desiredCount (rounded down to the nearest // integer). This parameter enables you to define the deployment batch size. -// For example, if desiredCount is four tasks and the maximum is 200%, the scheduler -// can start four new tasks before stopping the four older tasks (provided that -// the cluster resources required to do this are available). The default value -// is 200%. +// For example, if your service has a desiredCount of four tasks and a maximumPercent +// value of 200%, the scheduler can start four new tasks before stopping the +// four older tasks (provided that the cluster resources required to do this +// are available). The default value for maximumPercent is 200%. // // When the service scheduler launches new tasks, it determines task placement // in your cluster using the following logic: @@ -179,7 +194,8 @@ func (c *ECS) CreateServiceRequest(input *CreateServiceInput) (req *request.Requ // memory, ports, and container instance attributes). // // * By default, the service scheduler attempts to balance tasks across Availability -// Zones in this manner (although you can choose a different placement strategy): +// Zones in this manner (although you can choose a different placement strategy) +// with the placementStrategy parameter): // // Sort the valid container instances by the fewest number of running tasks // for this service in the same Availability Zone as the instance. For example, @@ -218,8 +234,23 @@ func (c *ECS) CreateServiceRequest(input *CreateServiceInput) (req *request.Requ // Please also see https://docs.aws.amazon.com/goto/WebAPI/ecs-2014-11-13/CreateService func (c *ECS) CreateService(input *CreateServiceInput) (*CreateServiceOutput, error) { req, out := c.CreateServiceRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateServiceWithContext is the same as CreateService with the addition of +// the ability to pass a context and additional request options. +// +// See CreateService 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 *ECS) CreateServiceWithContext(ctx aws.Context, input *CreateServiceInput, opts ...request.Option) (*CreateServiceOutput, error) { + req, out := c.CreateServiceRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteAttributes = "DeleteAttributes" @@ -293,8 +324,23 @@ func (c *ECS) DeleteAttributesRequest(input *DeleteAttributesInput) (req *reques // Please also see https://docs.aws.amazon.com/goto/WebAPI/ecs-2014-11-13/DeleteAttributes func (c *ECS) DeleteAttributes(input *DeleteAttributesInput) (*DeleteAttributesOutput, error) { req, out := c.DeleteAttributesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteAttributesWithContext is the same as DeleteAttributes with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteAttributes 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 *ECS) DeleteAttributesWithContext(ctx aws.Context, input *DeleteAttributesInput, opts ...request.Option) (*DeleteAttributesOutput, error) { + req, out := c.DeleteAttributesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteCluster = "DeleteCluster" @@ -383,8 +429,23 @@ func (c *ECS) DeleteClusterRequest(input *DeleteClusterInput) (req *request.Requ // Please also see https://docs.aws.amazon.com/goto/WebAPI/ecs-2014-11-13/DeleteCluster func (c *ECS) DeleteCluster(input *DeleteClusterInput) (*DeleteClusterOutput, error) { req, out := c.DeleteClusterRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteClusterWithContext is the same as DeleteCluster with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteCluster 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 *ECS) DeleteClusterWithContext(ctx aws.Context, input *DeleteClusterInput, opts ...request.Option) (*DeleteClusterOutput, error) { + req, out := c.DeleteClusterRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteService = "DeleteService" @@ -478,8 +539,23 @@ func (c *ECS) DeleteServiceRequest(input *DeleteServiceInput) (req *request.Requ // Please also see https://docs.aws.amazon.com/goto/WebAPI/ecs-2014-11-13/DeleteService func (c *ECS) DeleteService(input *DeleteServiceInput) (*DeleteServiceOutput, error) { req, out := c.DeleteServiceRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteServiceWithContext is the same as DeleteService with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteService 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 *ECS) DeleteServiceWithContext(ctx aws.Context, input *DeleteServiceInput, opts ...request.Option) (*DeleteServiceOutput, error) { + req, out := c.DeleteServiceRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeregisterContainerInstance = "DeregisterContainerInstance" @@ -570,8 +646,23 @@ func (c *ECS) DeregisterContainerInstanceRequest(input *DeregisterContainerInsta // Please also see https://docs.aws.amazon.com/goto/WebAPI/ecs-2014-11-13/DeregisterContainerInstance func (c *ECS) DeregisterContainerInstance(input *DeregisterContainerInstanceInput) (*DeregisterContainerInstanceOutput, error) { req, out := c.DeregisterContainerInstanceRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeregisterContainerInstanceWithContext is the same as DeregisterContainerInstance with the addition of +// the ability to pass a context and additional request options. +// +// See DeregisterContainerInstance 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 *ECS) DeregisterContainerInstanceWithContext(ctx aws.Context, input *DeregisterContainerInstanceInput, opts ...request.Option) (*DeregisterContainerInstanceOutput, error) { + req, out := c.DeregisterContainerInstanceRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeregisterTaskDefinition = "DeregisterTaskDefinition" @@ -630,6 +721,11 @@ func (c *ECS) DeregisterTaskDefinitionRequest(input *DeregisterTaskDefinitionInp // task definition (although there may be up to a 10 minute window following // deregistration where these restrictions have not yet taken effect). // +// At this time, INACTIVE task definitions remain discoverable in your account +// indefinitely; however, this behavior is subject to change in the future, +// so you should not rely on INACTIVE task definitions persisting beyond the +// life cycle of any associated tasks and services. +// // 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. @@ -653,8 +749,23 @@ func (c *ECS) DeregisterTaskDefinitionRequest(input *DeregisterTaskDefinitionInp // Please also see https://docs.aws.amazon.com/goto/WebAPI/ecs-2014-11-13/DeregisterTaskDefinition func (c *ECS) DeregisterTaskDefinition(input *DeregisterTaskDefinitionInput) (*DeregisterTaskDefinitionOutput, error) { req, out := c.DeregisterTaskDefinitionRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeregisterTaskDefinitionWithContext is the same as DeregisterTaskDefinition with the addition of +// the ability to pass a context and additional request options. +// +// See DeregisterTaskDefinition 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 *ECS) DeregisterTaskDefinitionWithContext(ctx aws.Context, input *DeregisterTaskDefinitionInput, opts ...request.Option) (*DeregisterTaskDefinitionOutput, error) { + req, out := c.DeregisterTaskDefinitionRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeClusters = "DescribeClusters" @@ -727,8 +838,23 @@ func (c *ECS) DescribeClustersRequest(input *DescribeClustersInput) (req *reques // Please also see https://docs.aws.amazon.com/goto/WebAPI/ecs-2014-11-13/DescribeClusters func (c *ECS) DescribeClusters(input *DescribeClustersInput) (*DescribeClustersOutput, error) { req, out := c.DescribeClustersRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeClustersWithContext is the same as DescribeClusters with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeClusters 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 *ECS) DescribeClustersWithContext(ctx aws.Context, input *DescribeClustersInput, opts ...request.Option) (*DescribeClustersOutput, error) { + req, out := c.DescribeClustersRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeContainerInstances = "DescribeContainerInstances" @@ -806,8 +932,23 @@ func (c *ECS) DescribeContainerInstancesRequest(input *DescribeContainerInstance // Please also see https://docs.aws.amazon.com/goto/WebAPI/ecs-2014-11-13/DescribeContainerInstances func (c *ECS) DescribeContainerInstances(input *DescribeContainerInstancesInput) (*DescribeContainerInstancesOutput, error) { req, out := c.DescribeContainerInstancesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeContainerInstancesWithContext is the same as DescribeContainerInstances with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeContainerInstances 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 *ECS) DescribeContainerInstancesWithContext(ctx aws.Context, input *DescribeContainerInstancesInput, opts ...request.Option) (*DescribeContainerInstancesOutput, error) { + req, out := c.DescribeContainerInstancesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeServices = "DescribeServices" @@ -884,8 +1025,23 @@ func (c *ECS) DescribeServicesRequest(input *DescribeServicesInput) (req *reques // Please also see https://docs.aws.amazon.com/goto/WebAPI/ecs-2014-11-13/DescribeServices func (c *ECS) DescribeServices(input *DescribeServicesInput) (*DescribeServicesOutput, error) { req, out := c.DescribeServicesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeServicesWithContext is the same as DescribeServices with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeServices 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 *ECS) DescribeServicesWithContext(ctx aws.Context, input *DescribeServicesInput, opts ...request.Option) (*DescribeServicesOutput, error) { + req, out := c.DescribeServicesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeTaskDefinition = "DescribeTaskDefinition" @@ -963,8 +1119,23 @@ func (c *ECS) DescribeTaskDefinitionRequest(input *DescribeTaskDefinitionInput) // Please also see https://docs.aws.amazon.com/goto/WebAPI/ecs-2014-11-13/DescribeTaskDefinition func (c *ECS) DescribeTaskDefinition(input *DescribeTaskDefinitionInput) (*DescribeTaskDefinitionOutput, error) { req, out := c.DescribeTaskDefinitionRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeTaskDefinitionWithContext is the same as DescribeTaskDefinition with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeTaskDefinition 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 *ECS) DescribeTaskDefinitionWithContext(ctx aws.Context, input *DescribeTaskDefinitionInput, opts ...request.Option) (*DescribeTaskDefinitionOutput, error) { + req, out := c.DescribeTaskDefinitionRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeTasks = "DescribeTasks" @@ -1041,8 +1212,23 @@ func (c *ECS) DescribeTasksRequest(input *DescribeTasksInput) (req *request.Requ // Please also see https://docs.aws.amazon.com/goto/WebAPI/ecs-2014-11-13/DescribeTasks func (c *ECS) DescribeTasks(input *DescribeTasksInput) (*DescribeTasksOutput, error) { req, out := c.DescribeTasksRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeTasksWithContext is the same as DescribeTasks with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeTasks 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 *ECS) DescribeTasksWithContext(ctx aws.Context, input *DescribeTasksInput, opts ...request.Option) (*DescribeTasksOutput, error) { + req, out := c.DescribeTasksRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDiscoverPollEndpoint = "DiscoverPollEndpoint" @@ -1115,8 +1301,23 @@ func (c *ECS) DiscoverPollEndpointRequest(input *DiscoverPollEndpointInput) (req // Please also see https://docs.aws.amazon.com/goto/WebAPI/ecs-2014-11-13/DiscoverPollEndpoint func (c *ECS) DiscoverPollEndpoint(input *DiscoverPollEndpointInput) (*DiscoverPollEndpointOutput, error) { req, out := c.DiscoverPollEndpointRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DiscoverPollEndpointWithContext is the same as DiscoverPollEndpoint with the addition of +// the ability to pass a context and additional request options. +// +// See DiscoverPollEndpoint 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 *ECS) DiscoverPollEndpointWithContext(ctx aws.Context, input *DiscoverPollEndpointInput, opts ...request.Option) (*DiscoverPollEndpointOutput, error) { + req, out := c.DiscoverPollEndpointRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opListAttributes = "ListAttributes" @@ -1165,7 +1366,7 @@ func (c *ECS) ListAttributesRequest(input *ListAttributesInput) (req *request.Re // ListAttributes API operation for Amazon EC2 Container Service. // // Lists the attributes for Amazon ECS resources within a specified target type -// and cluster. When you specify a target type and cluster, LisAttributes returns +// and cluster. When you specify a target type and cluster, ListAttributes returns // a list of attribute objects, one for each attribute on each resource. You // can filter the list of results to a single attribute name to only return // results that have that name. You can also filter the results by attribute @@ -1191,8 +1392,23 @@ func (c *ECS) ListAttributesRequest(input *ListAttributesInput) (req *request.Re // Please also see https://docs.aws.amazon.com/goto/WebAPI/ecs-2014-11-13/ListAttributes func (c *ECS) ListAttributes(input *ListAttributesInput) (*ListAttributesOutput, error) { req, out := c.ListAttributesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListAttributesWithContext is the same as ListAttributes with the addition of +// the ability to pass a context and additional request options. +// +// See ListAttributes 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 *ECS) ListAttributesWithContext(ctx aws.Context, input *ListAttributesInput, opts ...request.Option) (*ListAttributesOutput, error) { + req, out := c.ListAttributesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opListClusters = "ListClusters" @@ -1271,8 +1487,23 @@ func (c *ECS) ListClustersRequest(input *ListClustersInput) (req *request.Reques // Please also see https://docs.aws.amazon.com/goto/WebAPI/ecs-2014-11-13/ListClusters func (c *ECS) ListClusters(input *ListClustersInput) (*ListClustersOutput, error) { req, out := c.ListClustersRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListClustersWithContext is the same as ListClusters with the addition of +// the ability to pass a context and additional request options. +// +// See ListClusters 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 *ECS) ListClustersWithContext(ctx aws.Context, input *ListClustersInput, opts ...request.Option) (*ListClustersOutput, error) { + req, out := c.ListClustersRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // ListClustersPages iterates over the pages of a ListClusters operation, @@ -1292,12 +1523,37 @@ func (c *ECS) ListClusters(input *ListClustersInput) (*ListClustersOutput, error // return pageNum <= 3 // }) // -func (c *ECS) ListClustersPages(input *ListClustersInput, fn func(p *ListClustersOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.ListClustersRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*ListClustersOutput), lastPage) - }) +func (c *ECS) ListClustersPages(input *ListClustersInput, fn func(*ListClustersOutput, bool) bool) error { + return c.ListClustersPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListClustersPagesWithContext same as ListClustersPages 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 *ECS) ListClustersPagesWithContext(ctx aws.Context, input *ListClustersInput, fn func(*ListClustersOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListClustersInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListClustersRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*ListClustersOutput), !p.HasNextPage()) + } + return p.Err() } const opListContainerInstances = "ListContainerInstances" @@ -1384,8 +1640,23 @@ func (c *ECS) ListContainerInstancesRequest(input *ListContainerInstancesInput) // Please also see https://docs.aws.amazon.com/goto/WebAPI/ecs-2014-11-13/ListContainerInstances func (c *ECS) ListContainerInstances(input *ListContainerInstancesInput) (*ListContainerInstancesOutput, error) { req, out := c.ListContainerInstancesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListContainerInstancesWithContext is the same as ListContainerInstances with the addition of +// the ability to pass a context and additional request options. +// +// See ListContainerInstances 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 *ECS) ListContainerInstancesWithContext(ctx aws.Context, input *ListContainerInstancesInput, opts ...request.Option) (*ListContainerInstancesOutput, error) { + req, out := c.ListContainerInstancesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // ListContainerInstancesPages iterates over the pages of a ListContainerInstances operation, @@ -1405,12 +1676,37 @@ func (c *ECS) ListContainerInstances(input *ListContainerInstancesInput) (*ListC // return pageNum <= 3 // }) // -func (c *ECS) ListContainerInstancesPages(input *ListContainerInstancesInput, fn func(p *ListContainerInstancesOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.ListContainerInstancesRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*ListContainerInstancesOutput), lastPage) - }) +func (c *ECS) ListContainerInstancesPages(input *ListContainerInstancesInput, fn func(*ListContainerInstancesOutput, bool) bool) error { + return c.ListContainerInstancesPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListContainerInstancesPagesWithContext same as ListContainerInstancesPages 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 *ECS) ListContainerInstancesPagesWithContext(ctx aws.Context, input *ListContainerInstancesInput, fn func(*ListContainerInstancesOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListContainerInstancesInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListContainerInstancesRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*ListContainerInstancesOutput), !p.HasNextPage()) + } + return p.Err() } const opListServices = "ListServices" @@ -1493,8 +1789,23 @@ func (c *ECS) ListServicesRequest(input *ListServicesInput) (req *request.Reques // Please also see https://docs.aws.amazon.com/goto/WebAPI/ecs-2014-11-13/ListServices func (c *ECS) ListServices(input *ListServicesInput) (*ListServicesOutput, error) { req, out := c.ListServicesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListServicesWithContext is the same as ListServices with the addition of +// the ability to pass a context and additional request options. +// +// See ListServices 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 *ECS) ListServicesWithContext(ctx aws.Context, input *ListServicesInput, opts ...request.Option) (*ListServicesOutput, error) { + req, out := c.ListServicesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // ListServicesPages iterates over the pages of a ListServices operation, @@ -1514,12 +1825,37 @@ func (c *ECS) ListServices(input *ListServicesInput) (*ListServicesOutput, error // return pageNum <= 3 // }) // -func (c *ECS) ListServicesPages(input *ListServicesInput, fn func(p *ListServicesOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.ListServicesRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*ListServicesOutput), lastPage) - }) +func (c *ECS) ListServicesPages(input *ListServicesInput, fn func(*ListServicesOutput, bool) bool) error { + return c.ListServicesPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListServicesPagesWithContext same as ListServicesPages 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 *ECS) ListServicesPagesWithContext(ctx aws.Context, input *ListServicesInput, fn func(*ListServicesOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListServicesInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListServicesRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*ListServicesOutput), !p.HasNextPage()) + } + return p.Err() } const opListTaskDefinitionFamilies = "ListTaskDefinitionFamilies" @@ -1604,8 +1940,23 @@ func (c *ECS) ListTaskDefinitionFamiliesRequest(input *ListTaskDefinitionFamilie // Please also see https://docs.aws.amazon.com/goto/WebAPI/ecs-2014-11-13/ListTaskDefinitionFamilies func (c *ECS) ListTaskDefinitionFamilies(input *ListTaskDefinitionFamiliesInput) (*ListTaskDefinitionFamiliesOutput, error) { req, out := c.ListTaskDefinitionFamiliesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListTaskDefinitionFamiliesWithContext is the same as ListTaskDefinitionFamilies with the addition of +// the ability to pass a context and additional request options. +// +// See ListTaskDefinitionFamilies 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 *ECS) ListTaskDefinitionFamiliesWithContext(ctx aws.Context, input *ListTaskDefinitionFamiliesInput, opts ...request.Option) (*ListTaskDefinitionFamiliesOutput, error) { + req, out := c.ListTaskDefinitionFamiliesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // ListTaskDefinitionFamiliesPages iterates over the pages of a ListTaskDefinitionFamilies operation, @@ -1625,12 +1976,37 @@ func (c *ECS) ListTaskDefinitionFamilies(input *ListTaskDefinitionFamiliesInput) // return pageNum <= 3 // }) // -func (c *ECS) ListTaskDefinitionFamiliesPages(input *ListTaskDefinitionFamiliesInput, fn func(p *ListTaskDefinitionFamiliesOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.ListTaskDefinitionFamiliesRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*ListTaskDefinitionFamiliesOutput), lastPage) - }) +func (c *ECS) ListTaskDefinitionFamiliesPages(input *ListTaskDefinitionFamiliesInput, fn func(*ListTaskDefinitionFamiliesOutput, bool) bool) error { + return c.ListTaskDefinitionFamiliesPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListTaskDefinitionFamiliesPagesWithContext same as ListTaskDefinitionFamiliesPages 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 *ECS) ListTaskDefinitionFamiliesPagesWithContext(ctx aws.Context, input *ListTaskDefinitionFamiliesInput, fn func(*ListTaskDefinitionFamiliesOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListTaskDefinitionFamiliesInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListTaskDefinitionFamiliesRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*ListTaskDefinitionFamiliesOutput), !p.HasNextPage()) + } + return p.Err() } const opListTaskDefinitions = "ListTaskDefinitions" @@ -1711,8 +2087,23 @@ func (c *ECS) ListTaskDefinitionsRequest(input *ListTaskDefinitionsInput) (req * // Please also see https://docs.aws.amazon.com/goto/WebAPI/ecs-2014-11-13/ListTaskDefinitions func (c *ECS) ListTaskDefinitions(input *ListTaskDefinitionsInput) (*ListTaskDefinitionsOutput, error) { req, out := c.ListTaskDefinitionsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListTaskDefinitionsWithContext is the same as ListTaskDefinitions with the addition of +// the ability to pass a context and additional request options. +// +// See ListTaskDefinitions 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 *ECS) ListTaskDefinitionsWithContext(ctx aws.Context, input *ListTaskDefinitionsInput, opts ...request.Option) (*ListTaskDefinitionsOutput, error) { + req, out := c.ListTaskDefinitionsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // ListTaskDefinitionsPages iterates over the pages of a ListTaskDefinitions operation, @@ -1732,12 +2123,37 @@ func (c *ECS) ListTaskDefinitions(input *ListTaskDefinitionsInput) (*ListTaskDef // return pageNum <= 3 // }) // -func (c *ECS) ListTaskDefinitionsPages(input *ListTaskDefinitionsInput, fn func(p *ListTaskDefinitionsOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.ListTaskDefinitionsRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*ListTaskDefinitionsOutput), lastPage) - }) +func (c *ECS) ListTaskDefinitionsPages(input *ListTaskDefinitionsInput, fn func(*ListTaskDefinitionsOutput, bool) bool) error { + return c.ListTaskDefinitionsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListTaskDefinitionsPagesWithContext same as ListTaskDefinitionsPages 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 *ECS) ListTaskDefinitionsPagesWithContext(ctx aws.Context, input *ListTaskDefinitionsInput, fn func(*ListTaskDefinitionsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListTaskDefinitionsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListTaskDefinitionsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*ListTaskDefinitionsOutput), !p.HasNextPage()) + } + return p.Err() } const opListTasks = "ListTasks" @@ -1829,8 +2245,23 @@ func (c *ECS) ListTasksRequest(input *ListTasksInput) (req *request.Request, out // Please also see https://docs.aws.amazon.com/goto/WebAPI/ecs-2014-11-13/ListTasks func (c *ECS) ListTasks(input *ListTasksInput) (*ListTasksOutput, error) { req, out := c.ListTasksRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListTasksWithContext is the same as ListTasks with the addition of +// the ability to pass a context and additional request options. +// +// See ListTasks 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 *ECS) ListTasksWithContext(ctx aws.Context, input *ListTasksInput, opts ...request.Option) (*ListTasksOutput, error) { + req, out := c.ListTasksRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // ListTasksPages iterates over the pages of a ListTasks operation, @@ -1850,12 +2281,37 @@ func (c *ECS) ListTasks(input *ListTasksInput) (*ListTasksOutput, error) { // return pageNum <= 3 // }) // -func (c *ECS) ListTasksPages(input *ListTasksInput, fn func(p *ListTasksOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.ListTasksRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*ListTasksOutput), lastPage) - }) +func (c *ECS) ListTasksPages(input *ListTasksInput, fn func(*ListTasksOutput, bool) bool) error { + return c.ListTasksPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListTasksPagesWithContext same as ListTasksPages 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 *ECS) ListTasksPagesWithContext(ctx aws.Context, input *ListTasksInput, fn func(*ListTasksOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListTasksInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListTasksRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*ListTasksOutput), !p.HasNextPage()) + } + return p.Err() } const opPutAttributes = "PutAttributes" @@ -1938,8 +2394,23 @@ func (c *ECS) PutAttributesRequest(input *PutAttributesInput) (req *request.Requ // Please also see https://docs.aws.amazon.com/goto/WebAPI/ecs-2014-11-13/PutAttributes func (c *ECS) PutAttributes(input *PutAttributesInput) (*PutAttributesOutput, error) { req, out := c.PutAttributesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// PutAttributesWithContext is the same as PutAttributes with the addition of +// the ability to pass a context and additional request options. +// +// See PutAttributes 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 *ECS) PutAttributesWithContext(ctx aws.Context, input *PutAttributesInput, opts ...request.Option) (*PutAttributesOutput, error) { + req, out := c.PutAttributesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opRegisterContainerInstance = "RegisterContainerInstance" @@ -2012,8 +2483,23 @@ func (c *ECS) RegisterContainerInstanceRequest(input *RegisterContainerInstanceI // Please also see https://docs.aws.amazon.com/goto/WebAPI/ecs-2014-11-13/RegisterContainerInstance func (c *ECS) RegisterContainerInstance(input *RegisterContainerInstanceInput) (*RegisterContainerInstanceOutput, error) { req, out := c.RegisterContainerInstanceRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// RegisterContainerInstanceWithContext is the same as RegisterContainerInstance with the addition of +// the ability to pass a context and additional request options. +// +// See RegisterContainerInstance 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 *ECS) RegisterContainerInstanceWithContext(ctx aws.Context, input *RegisterContainerInstanceInput, opts ...request.Option) (*RegisterContainerInstanceOutput, error) { + req, out := c.RegisterContainerInstanceRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opRegisterTaskDefinition = "RegisterTaskDefinition" @@ -2102,8 +2588,23 @@ func (c *ECS) RegisterTaskDefinitionRequest(input *RegisterTaskDefinitionInput) // Please also see https://docs.aws.amazon.com/goto/WebAPI/ecs-2014-11-13/RegisterTaskDefinition func (c *ECS) RegisterTaskDefinition(input *RegisterTaskDefinitionInput) (*RegisterTaskDefinitionOutput, error) { req, out := c.RegisterTaskDefinitionRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// RegisterTaskDefinitionWithContext is the same as RegisterTaskDefinition with the addition of +// the ability to pass a context and additional request options. +// +// See RegisterTaskDefinition 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 *ECS) RegisterTaskDefinitionWithContext(ctx aws.Context, input *RegisterTaskDefinitionInput, opts ...request.Option) (*RegisterTaskDefinitionOutput, error) { + req, out := c.RegisterTaskDefinitionRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opRunTask = "RunTask" @@ -2188,8 +2689,23 @@ func (c *ECS) RunTaskRequest(input *RunTaskInput) (req *request.Request, output // Please also see https://docs.aws.amazon.com/goto/WebAPI/ecs-2014-11-13/RunTask func (c *ECS) RunTask(input *RunTaskInput) (*RunTaskOutput, error) { req, out := c.RunTaskRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// RunTaskWithContext is the same as RunTask with the addition of +// the ability to pass a context and additional request options. +// +// See RunTask 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 *ECS) RunTaskWithContext(ctx aws.Context, input *RunTaskInput, opts ...request.Option) (*RunTaskOutput, error) { + req, out := c.RunTaskRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opStartTask = "StartTask" @@ -2271,8 +2787,23 @@ func (c *ECS) StartTaskRequest(input *StartTaskInput) (req *request.Request, out // Please also see https://docs.aws.amazon.com/goto/WebAPI/ecs-2014-11-13/StartTask func (c *ECS) StartTask(input *StartTaskInput) (*StartTaskOutput, error) { req, out := c.StartTaskRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// StartTaskWithContext is the same as StartTask with the addition of +// the ability to pass a context and additional request options. +// +// See StartTask 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 *ECS) StartTaskWithContext(ctx aws.Context, input *StartTaskInput, opts ...request.Option) (*StartTaskOutput, error) { + req, out := c.StartTaskRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opStopTask = "StopTask" @@ -2323,10 +2854,15 @@ func (c *ECS) StopTaskRequest(input *StopTaskInput) (req *request.Request, outpu // Stops a running task. // // When StopTask is called on a task, the equivalent of docker stop is issued -// to the containers running in the task. This results in a SIGTERM and a 30-second -// timeout, after which SIGKILL is sent and the containers are forcibly stopped. -// If the container handles the SIGTERM gracefully and exits within 30 seconds -// from receiving it, no SIGKILL is sent. +// to the containers running in the task. This results in a SIGTERM and a default +// 30-second timeout, after which SIGKILL is sent and the containers are forcibly +// stopped. If the container handles the SIGTERM gracefully and exits within +// 30 seconds from receiving it, no SIGKILL is sent. +// +// The default 30-second timeout can be configured on the Amazon ECS container +// agent with the ECS_CONTAINER_STOP_TIMEOUT variable. For more information, +// see Amazon ECS Container Agent Configuration (http://docs.aws.amazon.com/AmazonECS/latest/developerguide/ecs-agent-config.html) +// in the Amazon EC2 Container 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 @@ -2355,8 +2891,23 @@ func (c *ECS) StopTaskRequest(input *StopTaskInput) (req *request.Request, outpu // Please also see https://docs.aws.amazon.com/goto/WebAPI/ecs-2014-11-13/StopTask func (c *ECS) StopTask(input *StopTaskInput) (*StopTaskOutput, error) { req, out := c.StopTaskRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// StopTaskWithContext is the same as StopTask with the addition of +// the ability to pass a context and additional request options. +// +// See StopTask 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 *ECS) StopTaskWithContext(ctx aws.Context, input *StopTaskInput, opts ...request.Option) (*StopTaskOutput, error) { + req, out := c.StopTaskRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opSubmitContainerStateChange = "SubmitContainerStateChange" @@ -2428,8 +2979,23 @@ func (c *ECS) SubmitContainerStateChangeRequest(input *SubmitContainerStateChang // Please also see https://docs.aws.amazon.com/goto/WebAPI/ecs-2014-11-13/SubmitContainerStateChange func (c *ECS) SubmitContainerStateChange(input *SubmitContainerStateChangeInput) (*SubmitContainerStateChangeOutput, error) { req, out := c.SubmitContainerStateChangeRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// SubmitContainerStateChangeWithContext is the same as SubmitContainerStateChange with the addition of +// the ability to pass a context and additional request options. +// +// See SubmitContainerStateChange 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 *ECS) SubmitContainerStateChangeWithContext(ctx aws.Context, input *SubmitContainerStateChangeInput, opts ...request.Option) (*SubmitContainerStateChangeOutput, error) { + req, out := c.SubmitContainerStateChangeRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opSubmitTaskStateChange = "SubmitTaskStateChange" @@ -2501,8 +3067,23 @@ func (c *ECS) SubmitTaskStateChangeRequest(input *SubmitTaskStateChangeInput) (r // Please also see https://docs.aws.amazon.com/goto/WebAPI/ecs-2014-11-13/SubmitTaskStateChange func (c *ECS) SubmitTaskStateChange(input *SubmitTaskStateChangeInput) (*SubmitTaskStateChangeOutput, error) { req, out := c.SubmitTaskStateChangeRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// SubmitTaskStateChangeWithContext is the same as SubmitTaskStateChange with the addition of +// the ability to pass a context and additional request options. +// +// See SubmitTaskStateChange 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 *ECS) SubmitTaskStateChangeWithContext(ctx aws.Context, input *SubmitTaskStateChangeInput, opts ...request.Option) (*SubmitTaskStateChangeOutput, error) { + req, out := c.SubmitTaskStateChangeRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opUpdateContainerAgent = "UpdateContainerAgent" @@ -2607,8 +3188,23 @@ func (c *ECS) UpdateContainerAgentRequest(input *UpdateContainerAgentInput) (req // Please also see https://docs.aws.amazon.com/goto/WebAPI/ecs-2014-11-13/UpdateContainerAgent func (c *ECS) UpdateContainerAgent(input *UpdateContainerAgentInput) (*UpdateContainerAgentOutput, error) { req, out := c.UpdateContainerAgentRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// UpdateContainerAgentWithContext is the same as UpdateContainerAgent with the addition of +// the ability to pass a context and additional request options. +// +// See UpdateContainerAgent 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 *ECS) UpdateContainerAgentWithContext(ctx aws.Context, input *UpdateContainerAgentInput, opts ...request.Option) (*UpdateContainerAgentOutput, error) { + req, out := c.UpdateContainerAgentRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opUpdateContainerInstancesState = "UpdateContainerInstancesState" @@ -2728,8 +3324,23 @@ func (c *ECS) UpdateContainerInstancesStateRequest(input *UpdateContainerInstanc // Please also see https://docs.aws.amazon.com/goto/WebAPI/ecs-2014-11-13/UpdateContainerInstancesState func (c *ECS) UpdateContainerInstancesState(input *UpdateContainerInstancesStateInput) (*UpdateContainerInstancesStateOutput, error) { req, out := c.UpdateContainerInstancesStateRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// UpdateContainerInstancesStateWithContext is the same as UpdateContainerInstancesState with the addition of +// the ability to pass a context and additional request options. +// +// See UpdateContainerInstancesState 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 *ECS) UpdateContainerInstancesStateWithContext(ctx aws.Context, input *UpdateContainerInstancesStateInput, opts ...request.Option) (*UpdateContainerInstancesStateOutput, error) { + req, out := c.UpdateContainerInstancesStateRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opUpdateService = "UpdateService" @@ -2881,8 +3492,23 @@ func (c *ECS) UpdateServiceRequest(input *UpdateServiceInput) (req *request.Requ // Please also see https://docs.aws.amazon.com/goto/WebAPI/ecs-2014-11-13/UpdateService func (c *ECS) UpdateService(input *UpdateServiceInput) (*UpdateServiceOutput, error) { req, out := c.UpdateServiceRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// UpdateServiceWithContext is the same as UpdateService with the addition of +// the ability to pass a context and additional request options. +// +// See UpdateService 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 *ECS) UpdateServiceWithContext(ctx aws.Context, input *UpdateServiceInput, opts ...request.Option) (*UpdateServiceOutput, error) { + req, out := c.UpdateServiceRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // An attribute is a name-value pair associated with an Amazon ECS object. Attributes @@ -3694,6 +4320,9 @@ type ContainerInstance struct { // The number of tasks on the container instance that are in the PENDING status. PendingTasksCount *int64 `locationName:"pendingTasksCount" type:"integer"` + // The Unix timestamp for when the container instance was registered. + RegisteredAt *time.Time `locationName:"registeredAt" type:"timestamp" timestampFormat:"unix"` + // For most resource types, this parameter describes the registered resources // on the container instance that are in use by current tasks. For port resource // types, this parameter describes the ports that were reserved by the Amazon @@ -3711,8 +4340,12 @@ type ContainerInstance struct { // The number of tasks on the container instance that are in the RUNNING status. RunningTasksCount *int64 `locationName:"runningTasksCount" type:"integer"` - // The status of the container instance. The valid values are ACTIVE or INACTIVE. - // ACTIVE indicates that the container instance can accept tasks. + // The status of the container instance. The valid values are ACTIVE, INACTIVE, + // or DRAINING. ACTIVE indicates that the container instance can accept tasks. + // DRAINING indicates that new tasks are not placed on the container instance + // and any service tasks running on the container instance are removed if possible. + // For more information, see Container Instance Draining (http://docs.aws.amazon.com/AmazonECS/latest/developerguide/container-instance-draining.html) + // in the Amazon EC2 Container Service Developer Guide. Status *string `locationName:"status" type:"string"` // The version counter for the container instance. Every time a container instance @@ -3775,6 +4408,12 @@ func (s *ContainerInstance) SetPendingTasksCount(v int64) *ContainerInstance { return s } +// SetRegisteredAt sets the RegisteredAt field's value. +func (s *ContainerInstance) SetRegisteredAt(v time.Time) *ContainerInstance { + s.RegisteredAt = &v + return s +} + // SetRegisteredResources sets the RegisteredResources field's value. func (s *ContainerInstance) SetRegisteredResources(v []*Resource) *ContainerInstance { s.RegisteredResources = v @@ -3817,15 +4456,18 @@ type ContainerOverride struct { _ struct{} `type:"structure"` // The command to send to the container that overrides the default command from - // the Docker image or the task definition. + // the Docker image or the task definition. You must also specify a container + // name. Command []*string `locationName:"command" type:"list"` // The environment variables to send to the container. You can add new environment // variables, which are added to the container at launch, or you can override // the existing environment variables from the Docker image or the task definition. + // You must also specify a container name. Environment []*KeyValuePair `locationName:"environment" type:"list"` - // The name of the container that receives the override. + // The name of the container that receives the override. This parameter is required + // if a command or environment variable is specified. Name *string `locationName:"name" type:"string"` } @@ -4114,7 +4756,7 @@ type DeleteAttributesInput struct { Attributes []*Attribute `locationName:"attributes" type:"list" required:"true"` // The short name or full Amazon Resource Name (ARN) of the cluster that contains - // the resource to apply attributes. If you do not specify a cluster, the default + // the resource to delete attributes. If you do not specify a cluster, the default // cluster is assumed. Cluster *string `locationName:"cluster" type:"string"` } @@ -4255,8 +4897,9 @@ func (s *DeleteClusterOutput) SetCluster(v *Cluster) *DeleteClusterOutput { type DeleteServiceInput struct { _ struct{} `type:"structure"` - // The name of the cluster that hosts the service to delete. If you do not specify - // a cluster, the default cluster is assumed. + // The short name or full Amazon Resource Name (ARN) of the cluster that hosts + // the service to delete. If you do not specify a cluster, the default cluster + // is assumed. Cluster *string `locationName:"cluster" type:"string"` // The name of the service to delete. @@ -4624,9 +5267,8 @@ func (s *DeregisterTaskDefinitionOutput) SetTaskDefinition(v *TaskDefinition) *D type DescribeClustersInput struct { _ struct{} `type:"structure"` - // A space-separated list of up to 100 cluster names or full cluster Amazon - // Resource Name (ARN) entries. If you do not specify a cluster, the default - // cluster is assumed. + // A list of up to 100 cluster names or full cluster Amazon Resource Name (ARN) + // entries. If you do not specify a cluster, the default cluster is assumed. Clusters []*string `locationName:"clusters" type:"list"` } @@ -4688,8 +5330,7 @@ type DescribeContainerInstancesInput struct { // default cluster is assumed. Cluster *string `locationName:"cluster" type:"string"` - // A space-separated list of container instance IDs or full Amazon Resource - // Name (ARN) entries. + // A list of container instance IDs or full Amazon Resource Name (ARN) entries. // // ContainerInstances is a required field ContainerInstances []*string `locationName:"containerInstances" type:"list" required:"true"` @@ -4767,8 +5408,9 @@ func (s *DescribeContainerInstancesOutput) SetFailures(v []*Failure) *DescribeCo type DescribeServicesInput struct { _ struct{} `type:"structure"` - // The name of the cluster that hosts the service to describe. If you do not - // specify a cluster, the default cluster is assumed. + // The short name or full Amazon Resource Name (ARN)the cluster that hosts the + // service to describe. If you do not specify a cluster, the default cluster + // is assumed. Cluster *string `locationName:"cluster" type:"string"` // A list of services to describe. You may specify up to 10 services to describe @@ -4920,7 +5562,7 @@ type DescribeTasksInput struct { // is assumed. Cluster *string `locationName:"cluster" type:"string"` - // A space-separated list of task IDs or full Amazon Resource Name (ARN) entries. + // A list of up to 100 task IDs or full Amazon Resource Name (ARN) entries. // // Tasks is a required field Tasks []*string `locationName:"tasks" type:"list" required:"true"` @@ -4998,7 +5640,8 @@ func (s *DescribeTasksOutput) SetTasks(v []*Task) *DescribeTasksOutput { type DiscoverPollEndpointInput struct { _ struct{} `type:"structure"` - // The cluster that the container instance belongs to. + // The short name or full Amazon Resource Name (ARN) of the cluster that the + // container instance belongs to. Cluster *string `locationName:"cluster" type:"string"` // The container instance ID or full Amazon Resource Name (ARN) of the container @@ -5471,10 +6114,11 @@ type ListContainerInstancesInput struct { // retrieve the next items in a list and not for other programmatic purposes. NextToken *string `locationName:"nextToken" type:"string"` - // The container instance status with which to filter the ListContainerInstances - // results. Specifying a container instance status of DRAINING limits the results - // to container instances that have been set to drain with the UpdateContainerInstancesState - // operation. + // Filters the container instances by status. For example, if you specify the + // DRAINING status, the results include only container instances that have been + // set to DRAINING using UpdateContainerInstancesState. If you do not specify + // this parameter, the default is to include container instances set to ACTIVE + // and DRAINING. Status *string `locationName:"status" type:"string" enum:"ContainerInstanceStatus"` } @@ -6044,7 +6688,7 @@ type LoadBalancer struct { // mapping. ContainerPort *int64 `locationName:"containerPort" type:"integer"` - // The name of the load balancer. + // The name of a Classic load balancer. LoadBalancerName *string `locationName:"loadBalancerName" type:"string"` // The full Amazon Resource Name (ARN) of the Elastic Load Balancing target @@ -8164,8 +8808,7 @@ type UpdateContainerInstancesStateInput struct { // cluster is assumed. Cluster *string `locationName:"cluster" type:"string"` - // A space-separated list of container instance IDs or full Amazon Resource - // Name (ARN) entries. + // A list of container instance IDs or full Amazon Resource Name (ARN) entries. // // ContainerInstances is a required field ContainerInstances []*string `locationName:"containerInstances" type:"list" required:"true"` @@ -8445,7 +9088,7 @@ func (s *Volume) SetName(v string) *Volume { return s } -// Details on a data volume from another container. +// Details on a data volume from another container in the same task definition. // Please also see https://docs.aws.amazon.com/goto/WebAPI/ecs-2014-11-13/VolumeFrom type VolumeFrom struct { _ struct{} `type:"structure"` @@ -8455,7 +9098,8 @@ type VolumeFrom struct { // value is false. ReadOnly *bool `locationName:"readOnly" type:"boolean"` - // The name of the container to mount volumes from. + // The name of another container within the same task definition to mount volumes + // from. SourceContainer *string `locationName:"sourceContainer" type:"string"` } diff --git a/vendor/github.com/aws/aws-sdk-go/service/ecs/doc.go b/vendor/github.com/aws/aws-sdk-go/service/ecs/doc.go new file mode 100644 index 000000000..590b62e41 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/service/ecs/doc.go @@ -0,0 +1,91 @@ +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. + +// Package ecs provides the client and types for making API +// requests to Amazon EC2 Container Service. +// +// Amazon EC2 Container Service (Amazon ECS) is a highly scalable, fast, container +// management service that makes it easy to run, stop, and manage Docker containers +// on a cluster of EC2 instances. Amazon ECS lets you launch and stop container-enabled +// applications with simple API calls, allows you to get the state of your cluster +// from a centralized service, and gives you access to many familiar Amazon +// EC2 features like security groups, Amazon EBS volumes, and IAM roles. +// +// You can use Amazon ECS to schedule the placement of containers across your +// cluster based on your resource needs, isolation policies, and availability +// requirements. Amazon EC2 Container Service eliminates the need for you to +// operate your own cluster management and configuration management systems +// or worry about scaling your management infrastructure. +// +// See https://docs.aws.amazon.com/goto/WebAPI/ecs-2014-11-13 for more information on this service. +// +// See ecs package documentation for more information. +// https://docs.aws.amazon.com/sdk-for-go/api/service/ecs/ +// +// Using the Client +// +// To use the client for Amazon EC2 Container Service you will first need +// to create a new instance of it. +// +// When creating a client for an AWS service you'll first need to have a Session +// already created. The Session provides configuration that can be shared +// between multiple service clients. Additional configuration can be applied to +// the Session and service's client when they are constructed. The aws package's +// Config type contains several fields such as Region for the AWS Region the +// client should make API requests too. The optional Config value can be provided +// as the variadic argument for Sessions and client creation. +// +// Once the service's client is created you can use it to make API requests the +// AWS service. These clients are safe to use concurrently. +// +// // Create a session to share configuration, and load external configuration. +// sess := session.Must(session.NewSession()) +// +// // Create the service's client with the session. +// svc := ecs.New(sess) +// +// See the SDK's documentation for more information on how to use service clients. +// https://docs.aws.amazon.com/sdk-for-go/api/ +// +// See aws package's Config type for more information on configuration options. +// https://docs.aws.amazon.com/sdk-for-go/api/aws/#Config +// +// See the Amazon EC2 Container Service client ECS for more +// information on creating the service's client. +// https://docs.aws.amazon.com/sdk-for-go/api/service/ecs/#New +// +// Once the client is created you can make an API request to the service. +// Each API method takes a input parameter, and returns the service response +// and an error. +// +// The API method will document which error codes the service can be returned +// by the operation if the service models the API operation's errors. These +// errors will also be available as const strings prefixed with "ErrCode". +// +// result, err := svc.CreateCluster(params) +// if err != nil { +// // Cast err to awserr.Error to handle specific error codes. +// aerr, ok := err.(awserr.Error) +// if ok && aerr.Code() == { +// // Specific error code handling +// } +// return err +// } +// +// fmt.Println("CreateCluster result:") +// fmt.Println(result) +// +// Using the Client with Context +// +// The service's client also provides methods to make API requests with a Context +// value. This allows you to control the timeout, and cancellation of pending +// requests. These methods also take request Option as variadic parameter to apply +// additional configuration to the API request. +// +// ctx := context.Background() +// +// result, err := svc.CreateClusterWithContext(ctx, params) +// +// See the request package documentation for more information on using Context pattern +// with the SDK. +// https://docs.aws.amazon.com/sdk-for-go/api/aws/request/ +package ecs diff --git a/vendor/github.com/aws/aws-sdk-go/service/ecs/errors.go b/vendor/github.com/aws/aws-sdk-go/service/ecs/errors.go index 02d4d4ab5..1e32412ac 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/ecs/errors.go +++ b/vendor/github.com/aws/aws-sdk-go/service/ecs/errors.go @@ -1,4 +1,4 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. package ecs diff --git a/vendor/github.com/aws/aws-sdk-go/service/ecs/service.go b/vendor/github.com/aws/aws-sdk-go/service/ecs/service.go index 4998b15fd..6082b9282 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/ecs/service.go +++ b/vendor/github.com/aws/aws-sdk-go/service/ecs/service.go @@ -1,4 +1,4 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. package ecs @@ -11,21 +11,12 @@ import ( "github.com/aws/aws-sdk-go/private/protocol/jsonrpc" ) -// Amazon EC2 Container Service (Amazon ECS) is a highly scalable, fast, container -// management service that makes it easy to run, stop, and manage Docker containers -// on a cluster of EC2 instances. Amazon ECS lets you launch and stop container-enabled -// applications with simple API calls, allows you to get the state of your cluster -// from a centralized service, and gives you access to many familiar Amazon -// EC2 features like security groups, Amazon EBS volumes, and IAM roles. +// ECS provides the API operation methods for making requests to +// Amazon EC2 Container Service. See this package's package overview docs +// for details on the service. // -// You can use Amazon ECS to schedule the placement of containers across your -// cluster based on your resource needs, isolation policies, and availability -// requirements. Amazon EC2 Container Service eliminates the need for you to -// operate your own cluster management and configuration management systems -// or worry about scaling your management infrastructure. -// The service client's operations are safe to be used concurrently. -// It is not safe to mutate any of the client's properties though. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/ecs-2014-11-13 +// ECS methods are safe to use concurrently. It is not safe to +// modify mutate any of the struct's properties though. type ECS struct { *client.Client } diff --git a/vendor/github.com/aws/aws-sdk-go/service/ecs/waiters.go b/vendor/github.com/aws/aws-sdk-go/service/ecs/waiters.go index cbc6f76e1..007b21614 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/ecs/waiters.go +++ b/vendor/github.com/aws/aws-sdk-go/service/ecs/waiters.go @@ -1,9 +1,12 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. package ecs import ( - "github.com/aws/aws-sdk-go/private/waiter" + "time" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/request" ) // WaitUntilServicesInactive uses the Amazon ECS API operation @@ -11,32 +14,50 @@ import ( // If the condition is not meet within the max attempt window an error will // be returned. func (c *ECS) WaitUntilServicesInactive(input *DescribeServicesInput) error { - waiterCfg := waiter.Config{ - Operation: "DescribeServices", - Delay: 15, + return c.WaitUntilServicesInactiveWithContext(aws.BackgroundContext(), input) +} + +// WaitUntilServicesInactiveWithContext is an extended version of WaitUntilServicesInactive. +// 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 *ECS) WaitUntilServicesInactiveWithContext(ctx aws.Context, input *DescribeServicesInput, opts ...request.WaiterOption) error { + w := request.Waiter{ + Name: "WaitUntilServicesInactive", MaxAttempts: 40, - Acceptors: []waiter.WaitAcceptor{ + Delay: request.ConstantWaiterDelay(15 * time.Second), + Acceptors: []request.WaiterAcceptor{ { - State: "failure", - Matcher: "pathAny", - Argument: "failures[].reason", + State: request.FailureWaiterState, + Matcher: request.PathAnyWaiterMatch, Argument: "failures[].reason", Expected: "MISSING", }, { - State: "success", - Matcher: "pathAny", - Argument: "services[].status", + State: request.SuccessWaiterState, + Matcher: request.PathAnyWaiterMatch, Argument: "services[].status", Expected: "INACTIVE", }, }, + Logger: c.Config.Logger, + NewRequest: func(opts []request.Option) (*request.Request, error) { + var inCpy *DescribeServicesInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeServicesRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, } + w.ApplyOptions(opts...) - w := waiter.Waiter{ - Client: c, - Input: input, - Config: waiterCfg, - } - return w.Wait() + return w.WaitWithContext(ctx) } // WaitUntilServicesStable uses the Amazon ECS API operation @@ -44,44 +65,60 @@ func (c *ECS) WaitUntilServicesInactive(input *DescribeServicesInput) error { // If the condition is not meet within the max attempt window an error will // be returned. func (c *ECS) WaitUntilServicesStable(input *DescribeServicesInput) error { - waiterCfg := waiter.Config{ - Operation: "DescribeServices", - Delay: 15, + return c.WaitUntilServicesStableWithContext(aws.BackgroundContext(), input) +} + +// WaitUntilServicesStableWithContext is an extended version of WaitUntilServicesStable. +// 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 *ECS) WaitUntilServicesStableWithContext(ctx aws.Context, input *DescribeServicesInput, opts ...request.WaiterOption) error { + w := request.Waiter{ + Name: "WaitUntilServicesStable", MaxAttempts: 40, - Acceptors: []waiter.WaitAcceptor{ + Delay: request.ConstantWaiterDelay(15 * time.Second), + Acceptors: []request.WaiterAcceptor{ { - State: "failure", - Matcher: "pathAny", - Argument: "failures[].reason", + State: request.FailureWaiterState, + Matcher: request.PathAnyWaiterMatch, Argument: "failures[].reason", Expected: "MISSING", }, { - State: "failure", - Matcher: "pathAny", - Argument: "services[].status", + State: request.FailureWaiterState, + Matcher: request.PathAnyWaiterMatch, Argument: "services[].status", Expected: "DRAINING", }, { - State: "failure", - Matcher: "pathAny", - Argument: "services[].status", + State: request.FailureWaiterState, + Matcher: request.PathAnyWaiterMatch, Argument: "services[].status", Expected: "INACTIVE", }, { - State: "success", - Matcher: "path", - Argument: "length(services[?!(length(deployments) == `1` && runningCount == desiredCount)]) == `0`", + State: request.SuccessWaiterState, + Matcher: request.PathWaiterMatch, Argument: "length(services[?!(length(deployments) == `1` && runningCount == desiredCount)]) == `0`", Expected: true, }, }, + Logger: c.Config.Logger, + NewRequest: func(opts []request.Option) (*request.Request, error) { + var inCpy *DescribeServicesInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeServicesRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, } + w.ApplyOptions(opts...) - w := waiter.Waiter{ - Client: c, - Input: input, - Config: waiterCfg, - } - return w.Wait() + return w.WaitWithContext(ctx) } // WaitUntilTasksRunning uses the Amazon ECS API operation @@ -89,38 +126,55 @@ func (c *ECS) WaitUntilServicesStable(input *DescribeServicesInput) error { // If the condition is not meet within the max attempt window an error will // be returned. func (c *ECS) WaitUntilTasksRunning(input *DescribeTasksInput) error { - waiterCfg := waiter.Config{ - Operation: "DescribeTasks", - Delay: 6, + return c.WaitUntilTasksRunningWithContext(aws.BackgroundContext(), input) +} + +// WaitUntilTasksRunningWithContext is an extended version of WaitUntilTasksRunning. +// 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 *ECS) WaitUntilTasksRunningWithContext(ctx aws.Context, input *DescribeTasksInput, opts ...request.WaiterOption) error { + w := request.Waiter{ + Name: "WaitUntilTasksRunning", MaxAttempts: 100, - Acceptors: []waiter.WaitAcceptor{ + Delay: request.ConstantWaiterDelay(6 * time.Second), + Acceptors: []request.WaiterAcceptor{ { - State: "failure", - Matcher: "pathAny", - Argument: "tasks[].lastStatus", + State: request.FailureWaiterState, + Matcher: request.PathAnyWaiterMatch, Argument: "tasks[].lastStatus", Expected: "STOPPED", }, { - State: "failure", - Matcher: "pathAny", - Argument: "failures[].reason", + State: request.FailureWaiterState, + Matcher: request.PathAnyWaiterMatch, Argument: "failures[].reason", Expected: "MISSING", }, { - State: "success", - Matcher: "pathAll", - Argument: "tasks[].lastStatus", + State: request.SuccessWaiterState, + Matcher: request.PathAllWaiterMatch, Argument: "tasks[].lastStatus", Expected: "RUNNING", }, }, + Logger: c.Config.Logger, + NewRequest: func(opts []request.Option) (*request.Request, error) { + var inCpy *DescribeTasksInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeTasksRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, } + w.ApplyOptions(opts...) - w := waiter.Waiter{ - Client: c, - Input: input, - Config: waiterCfg, - } - return w.Wait() + return w.WaitWithContext(ctx) } // WaitUntilTasksStopped uses the Amazon ECS API operation @@ -128,24 +182,43 @@ func (c *ECS) WaitUntilTasksRunning(input *DescribeTasksInput) error { // If the condition is not meet within the max attempt window an error will // be returned. func (c *ECS) WaitUntilTasksStopped(input *DescribeTasksInput) error { - waiterCfg := waiter.Config{ - Operation: "DescribeTasks", - Delay: 6, + return c.WaitUntilTasksStoppedWithContext(aws.BackgroundContext(), input) +} + +// WaitUntilTasksStoppedWithContext is an extended version of WaitUntilTasksStopped. +// 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 *ECS) WaitUntilTasksStoppedWithContext(ctx aws.Context, input *DescribeTasksInput, opts ...request.WaiterOption) error { + w := request.Waiter{ + Name: "WaitUntilTasksStopped", MaxAttempts: 100, - Acceptors: []waiter.WaitAcceptor{ + Delay: request.ConstantWaiterDelay(6 * time.Second), + Acceptors: []request.WaiterAcceptor{ { - State: "success", - Matcher: "pathAll", - Argument: "tasks[].lastStatus", + State: request.SuccessWaiterState, + Matcher: request.PathAllWaiterMatch, Argument: "tasks[].lastStatus", Expected: "STOPPED", }, }, + Logger: c.Config.Logger, + NewRequest: func(opts []request.Option) (*request.Request, error) { + var inCpy *DescribeTasksInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeTasksRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, } + w.ApplyOptions(opts...) - w := waiter.Waiter{ - Client: c, - Input: input, - Config: waiterCfg, - } - return w.Wait() + return w.WaitWithContext(ctx) } diff --git a/vendor/github.com/aws/aws-sdk-go/service/efs/api.go b/vendor/github.com/aws/aws-sdk-go/service/efs/api.go index f4c2ac141..11bf91f53 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/efs/api.go +++ b/vendor/github.com/aws/aws-sdk-go/service/efs/api.go @@ -1,12 +1,12 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. -// Package efs provides a client for Amazon Elastic File System. package efs import ( "fmt" "time" + "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awsutil" "github.com/aws/aws-sdk-go/aws/request" "github.com/aws/aws-sdk-go/private/protocol" @@ -131,8 +131,23 @@ func (c *EFS) CreateFileSystemRequest(input *CreateFileSystemInput) (req *reques // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticfilesystem-2015-02-01/CreateFileSystem func (c *EFS) CreateFileSystem(input *CreateFileSystemInput) (*FileSystemDescription, error) { req, out := c.CreateFileSystemRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateFileSystemWithContext is the same as CreateFileSystem with the addition of +// the ability to pass a context and additional request options. +// +// See CreateFileSystem 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 *EFS) CreateFileSystemWithContext(ctx aws.Context, input *CreateFileSystemInput, opts ...request.Option) (*FileSystemDescription, error) { + req, out := c.CreateFileSystemRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateMountTarget = "CreateMountTarget" @@ -333,8 +348,23 @@ func (c *EFS) CreateMountTargetRequest(input *CreateMountTargetInput) (req *requ // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticfilesystem-2015-02-01/CreateMountTarget func (c *EFS) CreateMountTarget(input *CreateMountTargetInput) (*MountTargetDescription, error) { req, out := c.CreateMountTargetRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateMountTargetWithContext is the same as CreateMountTarget with the addition of +// the ability to pass a context and additional request options. +// +// See CreateMountTarget 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 *EFS) CreateMountTargetWithContext(ctx aws.Context, input *CreateMountTargetInput, opts ...request.Option) (*MountTargetDescription, error) { + req, out := c.CreateMountTargetRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateTags = "CreateTags" @@ -414,8 +444,23 @@ func (c *EFS) CreateTagsRequest(input *CreateTagsInput) (req *request.Request, o // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticfilesystem-2015-02-01/CreateTags func (c *EFS) CreateTags(input *CreateTagsInput) (*CreateTagsOutput, error) { req, out := c.CreateTagsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateTagsWithContext is the same as CreateTags with the addition of +// the ability to pass a context and additional request options. +// +// See CreateTags 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 *EFS) CreateTagsWithContext(ctx aws.Context, input *CreateTagsInput, opts ...request.Option) (*CreateTagsOutput, error) { + req, out := c.CreateTagsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteFileSystem = "DeleteFileSystem" @@ -507,8 +552,23 @@ func (c *EFS) DeleteFileSystemRequest(input *DeleteFileSystemInput) (req *reques // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticfilesystem-2015-02-01/DeleteFileSystem func (c *EFS) DeleteFileSystem(input *DeleteFileSystemInput) (*DeleteFileSystemOutput, error) { req, out := c.DeleteFileSystemRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteFileSystemWithContext is the same as DeleteFileSystem with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteFileSystem 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 *EFS) DeleteFileSystemWithContext(ctx aws.Context, input *DeleteFileSystemInput, opts ...request.Option) (*DeleteFileSystemOutput, error) { + req, out := c.DeleteFileSystemRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteMountTarget = "DeleteMountTarget" @@ -610,8 +670,23 @@ func (c *EFS) DeleteMountTargetRequest(input *DeleteMountTargetInput) (req *requ // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticfilesystem-2015-02-01/DeleteMountTarget func (c *EFS) DeleteMountTarget(input *DeleteMountTargetInput) (*DeleteMountTargetOutput, error) { req, out := c.DeleteMountTargetRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteMountTargetWithContext is the same as DeleteMountTarget with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteMountTarget 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 *EFS) DeleteMountTargetWithContext(ctx aws.Context, input *DeleteMountTargetInput, opts ...request.Option) (*DeleteMountTargetOutput, error) { + req, out := c.DeleteMountTargetRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteTags = "DeleteTags" @@ -692,8 +767,23 @@ func (c *EFS) DeleteTagsRequest(input *DeleteTagsInput) (req *request.Request, o // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticfilesystem-2015-02-01/DeleteTags func (c *EFS) DeleteTags(input *DeleteTagsInput) (*DeleteTagsOutput, error) { req, out := c.DeleteTagsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteTagsWithContext is the same as DeleteTags with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteTags 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 *EFS) DeleteTagsWithContext(ctx aws.Context, input *DeleteTagsInput, opts ...request.Option) (*DeleteTagsOutput, error) { + req, out := c.DeleteTagsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeFileSystems = "DescribeFileSystems" @@ -790,8 +880,23 @@ func (c *EFS) DescribeFileSystemsRequest(input *DescribeFileSystemsInput) (req * // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticfilesystem-2015-02-01/DescribeFileSystems func (c *EFS) DescribeFileSystems(input *DescribeFileSystemsInput) (*DescribeFileSystemsOutput, error) { req, out := c.DescribeFileSystemsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeFileSystemsWithContext is the same as DescribeFileSystems with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeFileSystems 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 *EFS) DescribeFileSystemsWithContext(ctx aws.Context, input *DescribeFileSystemsInput, opts ...request.Option) (*DescribeFileSystemsOutput, error) { + req, out := c.DescribeFileSystemsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeMountTargetSecurityGroups = "DescribeMountTargetSecurityGroups" @@ -876,8 +981,23 @@ func (c *EFS) DescribeMountTargetSecurityGroupsRequest(input *DescribeMountTarge // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticfilesystem-2015-02-01/DescribeMountTargetSecurityGroups func (c *EFS) DescribeMountTargetSecurityGroups(input *DescribeMountTargetSecurityGroupsInput) (*DescribeMountTargetSecurityGroupsOutput, error) { req, out := c.DescribeMountTargetSecurityGroupsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeMountTargetSecurityGroupsWithContext is the same as DescribeMountTargetSecurityGroups with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeMountTargetSecurityGroups 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 *EFS) DescribeMountTargetSecurityGroupsWithContext(ctx aws.Context, input *DescribeMountTargetSecurityGroupsInput, opts ...request.Option) (*DescribeMountTargetSecurityGroupsOutput, error) { + req, out := c.DescribeMountTargetSecurityGroupsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeMountTargets = "DescribeMountTargets" @@ -959,8 +1079,23 @@ func (c *EFS) DescribeMountTargetsRequest(input *DescribeMountTargetsInput) (req // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticfilesystem-2015-02-01/DescribeMountTargets func (c *EFS) DescribeMountTargets(input *DescribeMountTargetsInput) (*DescribeMountTargetsOutput, error) { req, out := c.DescribeMountTargetsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeMountTargetsWithContext is the same as DescribeMountTargets with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeMountTargets 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 *EFS) DescribeMountTargetsWithContext(ctx aws.Context, input *DescribeMountTargetsInput, opts ...request.Option) (*DescribeMountTargetsOutput, error) { + req, out := c.DescribeMountTargetsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeTags = "DescribeTags" @@ -1037,8 +1172,23 @@ func (c *EFS) DescribeTagsRequest(input *DescribeTagsInput) (req *request.Reques // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticfilesystem-2015-02-01/DescribeTags func (c *EFS) DescribeTags(input *DescribeTagsInput) (*DescribeTagsOutput, error) { req, out := c.DescribeTagsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeTagsWithContext is the same as DescribeTags with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeTags 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 *EFS) DescribeTagsWithContext(ctx aws.Context, input *DescribeTagsInput, opts ...request.Option) (*DescribeTagsOutput, error) { + req, out := c.DescribeTagsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opModifyMountTargetSecurityGroups = "ModifyMountTargetSecurityGroups" @@ -1138,8 +1288,23 @@ func (c *EFS) ModifyMountTargetSecurityGroupsRequest(input *ModifyMountTargetSec // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticfilesystem-2015-02-01/ModifyMountTargetSecurityGroups func (c *EFS) ModifyMountTargetSecurityGroups(input *ModifyMountTargetSecurityGroupsInput) (*ModifyMountTargetSecurityGroupsOutput, error) { req, out := c.ModifyMountTargetSecurityGroupsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ModifyMountTargetSecurityGroupsWithContext is the same as ModifyMountTargetSecurityGroups with the addition of +// the ability to pass a context and additional request options. +// +// See ModifyMountTargetSecurityGroups 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 *EFS) ModifyMountTargetSecurityGroupsWithContext(ctx aws.Context, input *ModifyMountTargetSecurityGroupsInput, opts ...request.Option) (*ModifyMountTargetSecurityGroupsOutput, error) { + req, out := c.ModifyMountTargetSecurityGroupsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticfilesystem-2015-02-01/CreateFileSystemRequest diff --git a/vendor/github.com/aws/aws-sdk-go/service/efs/doc.go b/vendor/github.com/aws/aws-sdk-go/service/efs/doc.go new file mode 100644 index 000000000..c5e03b287 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/service/efs/doc.go @@ -0,0 +1,84 @@ +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. + +// Package efs provides the client and types for making API +// requests to Amazon Elastic File System. +// +// Amazon Elastic File System (Amazon EFS) provides simple, scalable file storage +// for use with Amazon EC2 instances in the AWS Cloud. With Amazon EFS, storage +// capacity is elastic, growing and shrinking automatically as you add and remove +// files, so your applications have the storage they need, when they need it. +// For more information, see the User Guide (http://docs.aws.amazon.com/efs/latest/ug/api-reference.html). +// +// See https://docs.aws.amazon.com/goto/WebAPI/elasticfilesystem-2015-02-01 for more information on this service. +// +// See efs package documentation for more information. +// https://docs.aws.amazon.com/sdk-for-go/api/service/efs/ +// +// Using the Client +// +// To use the client for Amazon Elastic File System you will first need +// to create a new instance of it. +// +// When creating a client for an AWS service you'll first need to have a Session +// already created. The Session provides configuration that can be shared +// between multiple service clients. Additional configuration can be applied to +// the Session and service's client when they are constructed. The aws package's +// Config type contains several fields such as Region for the AWS Region the +// client should make API requests too. The optional Config value can be provided +// as the variadic argument for Sessions and client creation. +// +// Once the service's client is created you can use it to make API requests the +// AWS service. These clients are safe to use concurrently. +// +// // Create a session to share configuration, and load external configuration. +// sess := session.Must(session.NewSession()) +// +// // Create the service's client with the session. +// svc := efs.New(sess) +// +// See the SDK's documentation for more information on how to use service clients. +// https://docs.aws.amazon.com/sdk-for-go/api/ +// +// See aws package's Config type for more information on configuration options. +// https://docs.aws.amazon.com/sdk-for-go/api/aws/#Config +// +// See the Amazon Elastic File System client EFS for more +// information on creating the service's client. +// https://docs.aws.amazon.com/sdk-for-go/api/service/efs/#New +// +// Once the client is created you can make an API request to the service. +// Each API method takes a input parameter, and returns the service response +// and an error. +// +// The API method will document which error codes the service can be returned +// by the operation if the service models the API operation's errors. These +// errors will also be available as const strings prefixed with "ErrCode". +// +// result, err := svc.CreateFileSystem(params) +// if err != nil { +// // Cast err to awserr.Error to handle specific error codes. +// aerr, ok := err.(awserr.Error) +// if ok && aerr.Code() == { +// // Specific error code handling +// } +// return err +// } +// +// fmt.Println("CreateFileSystem result:") +// fmt.Println(result) +// +// Using the Client with Context +// +// The service's client also provides methods to make API requests with a Context +// value. This allows you to control the timeout, and cancellation of pending +// requests. These methods also take request Option as variadic parameter to apply +// additional configuration to the API request. +// +// ctx := context.Background() +// +// result, err := svc.CreateFileSystemWithContext(ctx, params) +// +// See the request package documentation for more information on using Context pattern +// with the SDK. +// https://docs.aws.amazon.com/sdk-for-go/api/aws/request/ +package efs diff --git a/vendor/github.com/aws/aws-sdk-go/service/efs/errors.go b/vendor/github.com/aws/aws-sdk-go/service/efs/errors.go index 326ffa4b2..950e4ca5f 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/efs/errors.go +++ b/vendor/github.com/aws/aws-sdk-go/service/efs/errors.go @@ -1,4 +1,4 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. package efs diff --git a/vendor/github.com/aws/aws-sdk-go/service/efs/service.go b/vendor/github.com/aws/aws-sdk-go/service/efs/service.go index 583f08d39..4d6bb2cdc 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/efs/service.go +++ b/vendor/github.com/aws/aws-sdk-go/service/efs/service.go @@ -1,4 +1,4 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. package efs @@ -11,14 +11,12 @@ import ( "github.com/aws/aws-sdk-go/private/protocol/restjson" ) -// Amazon Elastic File System (Amazon EFS) provides simple, scalable file storage -// for use with Amazon EC2 instances in the AWS Cloud. With Amazon EFS, storage -// capacity is elastic, growing and shrinking automatically as you add and remove -// files, so your applications have the storage they need, when they need it. -// For more information, see the User Guide (http://docs.aws.amazon.com/efs/latest/ug/api-reference.html). -// The service client's operations are safe to be used concurrently. -// It is not safe to mutate any of the client's properties though. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticfilesystem-2015-02-01 +// EFS provides the API operation methods for making requests to +// Amazon Elastic File System. See this package's package overview docs +// for details on the service. +// +// EFS methods are safe to use concurrently. It is not safe to +// modify mutate any of the struct's properties though. type EFS struct { *client.Client } diff --git a/vendor/github.com/aws/aws-sdk-go/service/elasticache/api.go b/vendor/github.com/aws/aws-sdk-go/service/elasticache/api.go index 4eab1e4d0..3006029c0 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/elasticache/api.go +++ b/vendor/github.com/aws/aws-sdk-go/service/elasticache/api.go @@ -1,11 +1,11 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. -// Package elasticache provides a client for Amazon ElastiCache. package elasticache import ( "time" + "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awsutil" "github.com/aws/aws-sdk-go/aws/request" "github.com/aws/aws-sdk-go/private/protocol" @@ -57,7 +57,7 @@ func (c *ElastiCache) AddTagsToResourceRequest(input *AddTagsToResourceInput) (r // AddTagsToResource API operation for Amazon ElastiCache. // -// Adds up to 10 cost allocation tags to the named resource. A cost allocation +// Adds up to 50 cost allocation tags to the named resource. A cost allocation // tag is a key-value pair where the key and value are case-sensitive. You can // use cost allocation tags to categorize and track your AWS costs. // @@ -86,7 +86,7 @@ func (c *ElastiCache) AddTagsToResourceRequest(input *AddTagsToResourceInput) (r // * ErrCodeTagQuotaPerResourceExceeded "TagQuotaPerResourceExceeded" // The request cannot be processed because it would cause the resource to have // more than the allowed number of tags. The maximum number of tags permitted -// on a resource is 10. +// on a resource is 50. // // * ErrCodeInvalidARNFault "InvalidARN" // The requested Amazon Resource Name (ARN) does not refer to an existing resource. @@ -94,8 +94,23 @@ func (c *ElastiCache) AddTagsToResourceRequest(input *AddTagsToResourceInput) (r // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticache-2015-02-02/AddTagsToResource func (c *ElastiCache) AddTagsToResource(input *AddTagsToResourceInput) (*TagListMessage, error) { req, out := c.AddTagsToResourceRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// AddTagsToResourceWithContext is the same as AddTagsToResource with the addition of +// the ability to pass a context and additional request options. +// +// See AddTagsToResource 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 *ElastiCache) AddTagsToResourceWithContext(ctx aws.Context, input *AddTagsToResourceInput, opts ...request.Option) (*TagListMessage, error) { + req, out := c.AddTagsToResourceRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opAuthorizeCacheSecurityGroupIngress = "AuthorizeCacheSecurityGroupIngress" @@ -178,8 +193,23 @@ func (c *ElastiCache) AuthorizeCacheSecurityGroupIngressRequest(input *Authorize // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticache-2015-02-02/AuthorizeCacheSecurityGroupIngress func (c *ElastiCache) AuthorizeCacheSecurityGroupIngress(input *AuthorizeCacheSecurityGroupIngressInput) (*AuthorizeCacheSecurityGroupIngressOutput, error) { req, out := c.AuthorizeCacheSecurityGroupIngressRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// AuthorizeCacheSecurityGroupIngressWithContext is the same as AuthorizeCacheSecurityGroupIngress with the addition of +// the ability to pass a context and additional request options. +// +// See AuthorizeCacheSecurityGroupIngress 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 *ElastiCache) AuthorizeCacheSecurityGroupIngressWithContext(ctx aws.Context, input *AuthorizeCacheSecurityGroupIngressInput, opts ...request.Option) (*AuthorizeCacheSecurityGroupIngressOutput, error) { + req, out := c.AuthorizeCacheSecurityGroupIngressRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCopySnapshot = "CopySnapshot" @@ -324,8 +354,23 @@ func (c *ElastiCache) CopySnapshotRequest(input *CopySnapshotInput) (req *reques // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticache-2015-02-02/CopySnapshot func (c *ElastiCache) CopySnapshot(input *CopySnapshotInput) (*CopySnapshotOutput, error) { req, out := c.CopySnapshotRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CopySnapshotWithContext is the same as CopySnapshot with the addition of +// the ability to pass a context and additional request options. +// +// See CopySnapshot 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 *ElastiCache) CopySnapshotWithContext(ctx aws.Context, input *CopySnapshotInput, opts ...request.Option) (*CopySnapshotOutput, error) { + req, out := c.CopySnapshotRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateCacheCluster = "CreateCacheCluster" @@ -431,7 +476,7 @@ func (c *ElastiCache) CreateCacheClusterRequest(input *CreateCacheClusterInput) // * ErrCodeTagQuotaPerResourceExceeded "TagQuotaPerResourceExceeded" // The request cannot be processed because it would cause the resource to have // more than the allowed number of tags. The maximum number of tags permitted -// on a resource is 10. +// on a resource is 50. // // * ErrCodeInvalidParameterValueException "InvalidParameterValue" // The value for a parameter is invalid. @@ -442,8 +487,23 @@ func (c *ElastiCache) CreateCacheClusterRequest(input *CreateCacheClusterInput) // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticache-2015-02-02/CreateCacheCluster func (c *ElastiCache) CreateCacheCluster(input *CreateCacheClusterInput) (*CreateCacheClusterOutput, error) { req, out := c.CreateCacheClusterRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateCacheClusterWithContext is the same as CreateCacheCluster with the addition of +// the ability to pass a context and additional request options. +// +// See CreateCacheCluster 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 *ElastiCache) CreateCacheClusterWithContext(ctx aws.Context, input *CreateCacheClusterInput, opts ...request.Option) (*CreateCacheClusterOutput, error) { + req, out := c.CreateCacheClusterRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateCacheParameterGroup = "CreateCacheParameterGroup" @@ -491,8 +551,20 @@ func (c *ElastiCache) CreateCacheParameterGroupRequest(input *CreateCacheParamet // CreateCacheParameterGroup API operation for Amazon ElastiCache. // -// Creates a new cache parameter group. A cache parameter group is a collection -// of parameters that you apply to all of the nodes in a cache cluster. +// Creates a new Amazon ElastiCache cache parameter group. An ElastiCache cache +// parameter group is a collection of parameters and their values that are applied +// to all of the nodes in any cache cluster or replication group using the CacheParameterGroup. +// +// A newly created CacheParameterGroup is an exact duplicate of the default +// parameter group for the CacheParameterGroupFamily. To customize the newly +// created CacheParameterGroup you can change the values of specific parameters. +// For more information, see: +// +// * ModifyCacheParameterGroup (http://docs.aws.amazon.com/AmazonElastiCache/latest/APIReference/API_ModifyCacheParameterGroup.html) +// in the ElastiCache API Reference. +// +// * Parameters and Parameter Groups (http://docs.aws.amazon.com/AmazonElastiCache/latest/UserGuide/ParameterGroups.html) +// in the ElastiCache 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 @@ -522,8 +594,23 @@ func (c *ElastiCache) CreateCacheParameterGroupRequest(input *CreateCacheParamet // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticache-2015-02-02/CreateCacheParameterGroup func (c *ElastiCache) CreateCacheParameterGroup(input *CreateCacheParameterGroupInput) (*CreateCacheParameterGroupOutput, error) { req, out := c.CreateCacheParameterGroupRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateCacheParameterGroupWithContext is the same as CreateCacheParameterGroup with the addition of +// the ability to pass a context and additional request options. +// +// See CreateCacheParameterGroup 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 *ElastiCache) CreateCacheParameterGroupWithContext(ctx aws.Context, input *CreateCacheParameterGroupInput, opts ...request.Option) (*CreateCacheParameterGroupOutput, error) { + req, out := c.CreateCacheParameterGroupRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateCacheSecurityGroup = "CreateCacheSecurityGroup" @@ -603,8 +690,23 @@ func (c *ElastiCache) CreateCacheSecurityGroupRequest(input *CreateCacheSecurity // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticache-2015-02-02/CreateCacheSecurityGroup func (c *ElastiCache) CreateCacheSecurityGroup(input *CreateCacheSecurityGroupInput) (*CreateCacheSecurityGroupOutput, error) { req, out := c.CreateCacheSecurityGroupRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateCacheSecurityGroupWithContext is the same as CreateCacheSecurityGroup with the addition of +// the ability to pass a context and additional request options. +// +// See CreateCacheSecurityGroup 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 *ElastiCache) CreateCacheSecurityGroupWithContext(ctx aws.Context, input *CreateCacheSecurityGroupInput, opts ...request.Option) (*CreateCacheSecurityGroupOutput, error) { + req, out := c.CreateCacheSecurityGroupRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateCacheSubnetGroup = "CreateCacheSubnetGroup" @@ -683,8 +785,23 @@ func (c *ElastiCache) CreateCacheSubnetGroupRequest(input *CreateCacheSubnetGrou // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticache-2015-02-02/CreateCacheSubnetGroup func (c *ElastiCache) CreateCacheSubnetGroup(input *CreateCacheSubnetGroupInput) (*CreateCacheSubnetGroupOutput, error) { req, out := c.CreateCacheSubnetGroupRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateCacheSubnetGroupWithContext is the same as CreateCacheSubnetGroup with the addition of +// the ability to pass a context and additional request options. +// +// See CreateCacheSubnetGroup 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 *ElastiCache) CreateCacheSubnetGroupWithContext(ctx aws.Context, input *CreateCacheSubnetGroupInput, opts ...request.Option) (*CreateCacheSubnetGroupOutput, error) { + req, out := c.CreateCacheSubnetGroupRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateReplicationGroup = "CreateReplicationGroup" @@ -749,7 +866,11 @@ func (c *ElastiCache) CreateReplicationGroupRequest(input *CreateReplicationGrou // When a Redis (cluster mode disabled) replication group has been successfully // created, you can add one or more read replicas to it, up to a total of 5 // read replicas. You cannot alter a Redis (cluster mode enabled) replication -// group after it has been created. +// group after it has been created. However, if you need to increase or decrease +// the number of node groups (console: shards), you can avail yourself of ElastiCache +// for Redis' enhanced backup and restore. For more information, see Restoring +// From a Backup with Cluster Resizing (http://docs.aws.amazon.com/AmazonElastiCache/latest/UserGuide/backups-restoring.html) +// in the ElastiCache User Guide. // // This operation is valid for Redis only. // @@ -804,7 +925,7 @@ func (c *ElastiCache) CreateReplicationGroupRequest(input *CreateReplicationGrou // * ErrCodeTagQuotaPerResourceExceeded "TagQuotaPerResourceExceeded" // The request cannot be processed because it would cause the resource to have // more than the allowed number of tags. The maximum number of tags permitted -// on a resource is 10. +// on a resource is 50. // // * ErrCodeNodeGroupsPerReplicationGroupQuotaExceededFault "NodeGroupsPerReplicationGroupQuotaExceeded" // The request cannot be processed because it would exceed the maximum of 15 @@ -819,8 +940,23 @@ func (c *ElastiCache) CreateReplicationGroupRequest(input *CreateReplicationGrou // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticache-2015-02-02/CreateReplicationGroup func (c *ElastiCache) CreateReplicationGroup(input *CreateReplicationGroupInput) (*CreateReplicationGroupOutput, error) { req, out := c.CreateReplicationGroupRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateReplicationGroupWithContext is the same as CreateReplicationGroup with the addition of +// the ability to pass a context and additional request options. +// +// See CreateReplicationGroup 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 *ElastiCache) CreateReplicationGroupWithContext(ctx aws.Context, input *CreateReplicationGroupInput, opts ...request.Option) (*CreateReplicationGroupOutput, error) { + req, out := c.CreateReplicationGroupRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateSnapshot = "CreateSnapshot" @@ -920,8 +1056,23 @@ func (c *ElastiCache) CreateSnapshotRequest(input *CreateSnapshotInput) (req *re // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticache-2015-02-02/CreateSnapshot func (c *ElastiCache) CreateSnapshot(input *CreateSnapshotInput) (*CreateSnapshotOutput, error) { req, out := c.CreateSnapshotRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateSnapshotWithContext is the same as CreateSnapshot with the addition of +// the ability to pass a context and additional request options. +// +// See CreateSnapshot 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 *ElastiCache) CreateSnapshotWithContext(ctx aws.Context, input *CreateSnapshotInput, opts ...request.Option) (*CreateSnapshotOutput, error) { + req, out := c.CreateSnapshotRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteCacheCluster = "DeleteCacheCluster" @@ -1025,8 +1176,23 @@ func (c *ElastiCache) DeleteCacheClusterRequest(input *DeleteCacheClusterInput) // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticache-2015-02-02/DeleteCacheCluster func (c *ElastiCache) DeleteCacheCluster(input *DeleteCacheClusterInput) (*DeleteCacheClusterOutput, error) { req, out := c.DeleteCacheClusterRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteCacheClusterWithContext is the same as DeleteCacheCluster with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteCacheCluster 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 *ElastiCache) DeleteCacheClusterWithContext(ctx aws.Context, input *DeleteCacheClusterInput, opts ...request.Option) (*DeleteCacheClusterOutput, error) { + req, out := c.DeleteCacheClusterRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteCacheParameterGroup = "DeleteCacheParameterGroup" @@ -1104,8 +1270,23 @@ func (c *ElastiCache) DeleteCacheParameterGroupRequest(input *DeleteCacheParamet // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticache-2015-02-02/DeleteCacheParameterGroup func (c *ElastiCache) DeleteCacheParameterGroup(input *DeleteCacheParameterGroupInput) (*DeleteCacheParameterGroupOutput, error) { req, out := c.DeleteCacheParameterGroupRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteCacheParameterGroupWithContext is the same as DeleteCacheParameterGroup with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteCacheParameterGroup 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 *ElastiCache) DeleteCacheParameterGroupWithContext(ctx aws.Context, input *DeleteCacheParameterGroupInput, opts ...request.Option) (*DeleteCacheParameterGroupOutput, error) { + req, out := c.DeleteCacheParameterGroupRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteCacheSecurityGroup = "DeleteCacheSecurityGroup" @@ -1184,8 +1365,23 @@ func (c *ElastiCache) DeleteCacheSecurityGroupRequest(input *DeleteCacheSecurity // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticache-2015-02-02/DeleteCacheSecurityGroup func (c *ElastiCache) DeleteCacheSecurityGroup(input *DeleteCacheSecurityGroupInput) (*DeleteCacheSecurityGroupOutput, error) { req, out := c.DeleteCacheSecurityGroupRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteCacheSecurityGroupWithContext is the same as DeleteCacheSecurityGroup with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteCacheSecurityGroup 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 *ElastiCache) DeleteCacheSecurityGroupWithContext(ctx aws.Context, input *DeleteCacheSecurityGroupInput, opts ...request.Option) (*DeleteCacheSecurityGroupOutput, error) { + req, out := c.DeleteCacheSecurityGroupRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteCacheSubnetGroup = "DeleteCacheSubnetGroup" @@ -1258,8 +1454,23 @@ func (c *ElastiCache) DeleteCacheSubnetGroupRequest(input *DeleteCacheSubnetGrou // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticache-2015-02-02/DeleteCacheSubnetGroup func (c *ElastiCache) DeleteCacheSubnetGroup(input *DeleteCacheSubnetGroupInput) (*DeleteCacheSubnetGroupOutput, error) { req, out := c.DeleteCacheSubnetGroupRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteCacheSubnetGroupWithContext is the same as DeleteCacheSubnetGroup with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteCacheSubnetGroup 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 *ElastiCache) DeleteCacheSubnetGroupWithContext(ctx aws.Context, input *DeleteCacheSubnetGroupInput, opts ...request.Option) (*DeleteCacheSubnetGroupOutput, error) { + req, out := c.DeleteCacheSubnetGroupRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteReplicationGroup = "DeleteReplicationGroup" @@ -1360,8 +1571,23 @@ func (c *ElastiCache) DeleteReplicationGroupRequest(input *DeleteReplicationGrou // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticache-2015-02-02/DeleteReplicationGroup func (c *ElastiCache) DeleteReplicationGroup(input *DeleteReplicationGroupInput) (*DeleteReplicationGroupOutput, error) { req, out := c.DeleteReplicationGroupRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteReplicationGroupWithContext is the same as DeleteReplicationGroup with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteReplicationGroup 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 *ElastiCache) DeleteReplicationGroupWithContext(ctx aws.Context, input *DeleteReplicationGroupInput, opts ...request.Option) (*DeleteReplicationGroupOutput, error) { + req, out := c.DeleteReplicationGroupRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteSnapshot = "DeleteSnapshot" @@ -1439,8 +1665,23 @@ func (c *ElastiCache) DeleteSnapshotRequest(input *DeleteSnapshotInput) (req *re // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticache-2015-02-02/DeleteSnapshot func (c *ElastiCache) DeleteSnapshot(input *DeleteSnapshotInput) (*DeleteSnapshotOutput, error) { req, out := c.DeleteSnapshotRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteSnapshotWithContext is the same as DeleteSnapshot with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteSnapshot 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 *ElastiCache) DeleteSnapshotWithContext(ctx aws.Context, input *DeleteSnapshotInput, opts ...request.Option) (*DeleteSnapshotOutput, error) { + req, out := c.DeleteSnapshotRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeCacheClusters = "DescribeCacheClusters" @@ -1498,15 +1739,15 @@ func (c *ElastiCache) DescribeCacheClustersRequest(input *DescribeCacheClustersI // identifier is specified, or about a specific cache cluster if a cache cluster // identifier is supplied. // -// By default, abbreviated information about the cache clusters are returned. -// You can use the optional ShowDetails flag to retrieve detailed information +// By default, abbreviated information about the cache clusters is returned. +// You can use the optional ShowCacheNodeInfo flag to retrieve detailed information // about the cache nodes associated with the cache clusters. These details include // the DNS address and port for the cache node endpoint. // -// If the cluster is in the CREATING state, only cluster-level information is +// If the cluster is in the creating state, only cluster-level information is // displayed until all of the nodes are successfully provisioned. // -// If the cluster is in the DELETING state, only cluster-level information is +// If the cluster is in the deleting state, only cluster-level information is // displayed. // // If cache nodes are currently being added to the cache cluster, node endpoint @@ -1537,8 +1778,23 @@ func (c *ElastiCache) DescribeCacheClustersRequest(input *DescribeCacheClustersI // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticache-2015-02-02/DescribeCacheClusters func (c *ElastiCache) DescribeCacheClusters(input *DescribeCacheClustersInput) (*DescribeCacheClustersOutput, error) { req, out := c.DescribeCacheClustersRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeCacheClustersWithContext is the same as DescribeCacheClusters with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeCacheClusters 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 *ElastiCache) DescribeCacheClustersWithContext(ctx aws.Context, input *DescribeCacheClustersInput, opts ...request.Option) (*DescribeCacheClustersOutput, error) { + req, out := c.DescribeCacheClustersRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // DescribeCacheClustersPages iterates over the pages of a DescribeCacheClusters operation, @@ -1558,12 +1814,37 @@ func (c *ElastiCache) DescribeCacheClusters(input *DescribeCacheClustersInput) ( // return pageNum <= 3 // }) // -func (c *ElastiCache) DescribeCacheClustersPages(input *DescribeCacheClustersInput, fn func(p *DescribeCacheClustersOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.DescribeCacheClustersRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*DescribeCacheClustersOutput), lastPage) - }) +func (c *ElastiCache) DescribeCacheClustersPages(input *DescribeCacheClustersInput, fn func(*DescribeCacheClustersOutput, bool) bool) error { + return c.DescribeCacheClustersPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// DescribeCacheClustersPagesWithContext same as DescribeCacheClustersPages 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 *ElastiCache) DescribeCacheClustersPagesWithContext(ctx aws.Context, input *DescribeCacheClustersInput, fn func(*DescribeCacheClustersOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *DescribeCacheClustersInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeCacheClustersRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*DescribeCacheClustersOutput), !p.HasNextPage()) + } + return p.Err() } const opDescribeCacheEngineVersions = "DescribeCacheEngineVersions" @@ -1628,8 +1909,23 @@ func (c *ElastiCache) DescribeCacheEngineVersionsRequest(input *DescribeCacheEng // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticache-2015-02-02/DescribeCacheEngineVersions func (c *ElastiCache) DescribeCacheEngineVersions(input *DescribeCacheEngineVersionsInput) (*DescribeCacheEngineVersionsOutput, error) { req, out := c.DescribeCacheEngineVersionsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeCacheEngineVersionsWithContext is the same as DescribeCacheEngineVersions with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeCacheEngineVersions 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 *ElastiCache) DescribeCacheEngineVersionsWithContext(ctx aws.Context, input *DescribeCacheEngineVersionsInput, opts ...request.Option) (*DescribeCacheEngineVersionsOutput, error) { + req, out := c.DescribeCacheEngineVersionsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // DescribeCacheEngineVersionsPages iterates over the pages of a DescribeCacheEngineVersions operation, @@ -1649,12 +1945,37 @@ func (c *ElastiCache) DescribeCacheEngineVersions(input *DescribeCacheEngineVers // return pageNum <= 3 // }) // -func (c *ElastiCache) DescribeCacheEngineVersionsPages(input *DescribeCacheEngineVersionsInput, fn func(p *DescribeCacheEngineVersionsOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.DescribeCacheEngineVersionsRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*DescribeCacheEngineVersionsOutput), lastPage) - }) +func (c *ElastiCache) DescribeCacheEngineVersionsPages(input *DescribeCacheEngineVersionsInput, fn func(*DescribeCacheEngineVersionsOutput, bool) bool) error { + return c.DescribeCacheEngineVersionsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// DescribeCacheEngineVersionsPagesWithContext same as DescribeCacheEngineVersionsPages 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 *ElastiCache) DescribeCacheEngineVersionsPagesWithContext(ctx aws.Context, input *DescribeCacheEngineVersionsInput, fn func(*DescribeCacheEngineVersionsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *DescribeCacheEngineVersionsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeCacheEngineVersionsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*DescribeCacheEngineVersionsOutput), !p.HasNextPage()) + } + return p.Err() } const opDescribeCacheParameterGroups = "DescribeCacheParameterGroups" @@ -1733,8 +2054,23 @@ func (c *ElastiCache) DescribeCacheParameterGroupsRequest(input *DescribeCachePa // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticache-2015-02-02/DescribeCacheParameterGroups func (c *ElastiCache) DescribeCacheParameterGroups(input *DescribeCacheParameterGroupsInput) (*DescribeCacheParameterGroupsOutput, error) { req, out := c.DescribeCacheParameterGroupsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeCacheParameterGroupsWithContext is the same as DescribeCacheParameterGroups with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeCacheParameterGroups 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 *ElastiCache) DescribeCacheParameterGroupsWithContext(ctx aws.Context, input *DescribeCacheParameterGroupsInput, opts ...request.Option) (*DescribeCacheParameterGroupsOutput, error) { + req, out := c.DescribeCacheParameterGroupsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // DescribeCacheParameterGroupsPages iterates over the pages of a DescribeCacheParameterGroups operation, @@ -1754,12 +2090,37 @@ func (c *ElastiCache) DescribeCacheParameterGroups(input *DescribeCacheParameter // return pageNum <= 3 // }) // -func (c *ElastiCache) DescribeCacheParameterGroupsPages(input *DescribeCacheParameterGroupsInput, fn func(p *DescribeCacheParameterGroupsOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.DescribeCacheParameterGroupsRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*DescribeCacheParameterGroupsOutput), lastPage) - }) +func (c *ElastiCache) DescribeCacheParameterGroupsPages(input *DescribeCacheParameterGroupsInput, fn func(*DescribeCacheParameterGroupsOutput, bool) bool) error { + return c.DescribeCacheParameterGroupsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// DescribeCacheParameterGroupsPagesWithContext same as DescribeCacheParameterGroupsPages 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 *ElastiCache) DescribeCacheParameterGroupsPagesWithContext(ctx aws.Context, input *DescribeCacheParameterGroupsInput, fn func(*DescribeCacheParameterGroupsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *DescribeCacheParameterGroupsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeCacheParameterGroupsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*DescribeCacheParameterGroupsOutput), !p.HasNextPage()) + } + return p.Err() } const opDescribeCacheParameters = "DescribeCacheParameters" @@ -1836,8 +2197,23 @@ func (c *ElastiCache) DescribeCacheParametersRequest(input *DescribeCacheParamet // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticache-2015-02-02/DescribeCacheParameters func (c *ElastiCache) DescribeCacheParameters(input *DescribeCacheParametersInput) (*DescribeCacheParametersOutput, error) { req, out := c.DescribeCacheParametersRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeCacheParametersWithContext is the same as DescribeCacheParameters with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeCacheParameters 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 *ElastiCache) DescribeCacheParametersWithContext(ctx aws.Context, input *DescribeCacheParametersInput, opts ...request.Option) (*DescribeCacheParametersOutput, error) { + req, out := c.DescribeCacheParametersRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // DescribeCacheParametersPages iterates over the pages of a DescribeCacheParameters operation, @@ -1857,12 +2233,37 @@ func (c *ElastiCache) DescribeCacheParameters(input *DescribeCacheParametersInpu // return pageNum <= 3 // }) // -func (c *ElastiCache) DescribeCacheParametersPages(input *DescribeCacheParametersInput, fn func(p *DescribeCacheParametersOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.DescribeCacheParametersRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*DescribeCacheParametersOutput), lastPage) - }) +func (c *ElastiCache) DescribeCacheParametersPages(input *DescribeCacheParametersInput, fn func(*DescribeCacheParametersOutput, bool) bool) error { + return c.DescribeCacheParametersPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// DescribeCacheParametersPagesWithContext same as DescribeCacheParametersPages 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 *ElastiCache) DescribeCacheParametersPagesWithContext(ctx aws.Context, input *DescribeCacheParametersInput, fn func(*DescribeCacheParametersOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *DescribeCacheParametersInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeCacheParametersRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*DescribeCacheParametersOutput), !p.HasNextPage()) + } + return p.Err() } const opDescribeCacheSecurityGroups = "DescribeCacheSecurityGroups" @@ -1940,8 +2341,23 @@ func (c *ElastiCache) DescribeCacheSecurityGroupsRequest(input *DescribeCacheSec // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticache-2015-02-02/DescribeCacheSecurityGroups func (c *ElastiCache) DescribeCacheSecurityGroups(input *DescribeCacheSecurityGroupsInput) (*DescribeCacheSecurityGroupsOutput, error) { req, out := c.DescribeCacheSecurityGroupsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeCacheSecurityGroupsWithContext is the same as DescribeCacheSecurityGroups with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeCacheSecurityGroups 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 *ElastiCache) DescribeCacheSecurityGroupsWithContext(ctx aws.Context, input *DescribeCacheSecurityGroupsInput, opts ...request.Option) (*DescribeCacheSecurityGroupsOutput, error) { + req, out := c.DescribeCacheSecurityGroupsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // DescribeCacheSecurityGroupsPages iterates over the pages of a DescribeCacheSecurityGroups operation, @@ -1961,12 +2377,37 @@ func (c *ElastiCache) DescribeCacheSecurityGroups(input *DescribeCacheSecurityGr // return pageNum <= 3 // }) // -func (c *ElastiCache) DescribeCacheSecurityGroupsPages(input *DescribeCacheSecurityGroupsInput, fn func(p *DescribeCacheSecurityGroupsOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.DescribeCacheSecurityGroupsRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*DescribeCacheSecurityGroupsOutput), lastPage) - }) +func (c *ElastiCache) DescribeCacheSecurityGroupsPages(input *DescribeCacheSecurityGroupsInput, fn func(*DescribeCacheSecurityGroupsOutput, bool) bool) error { + return c.DescribeCacheSecurityGroupsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// DescribeCacheSecurityGroupsPagesWithContext same as DescribeCacheSecurityGroupsPages 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 *ElastiCache) DescribeCacheSecurityGroupsPagesWithContext(ctx aws.Context, input *DescribeCacheSecurityGroupsInput, fn func(*DescribeCacheSecurityGroupsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *DescribeCacheSecurityGroupsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeCacheSecurityGroupsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*DescribeCacheSecurityGroupsOutput), !p.HasNextPage()) + } + return p.Err() } const opDescribeCacheSubnetGroups = "DescribeCacheSubnetGroups" @@ -2038,8 +2479,23 @@ func (c *ElastiCache) DescribeCacheSubnetGroupsRequest(input *DescribeCacheSubne // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticache-2015-02-02/DescribeCacheSubnetGroups func (c *ElastiCache) DescribeCacheSubnetGroups(input *DescribeCacheSubnetGroupsInput) (*DescribeCacheSubnetGroupsOutput, error) { req, out := c.DescribeCacheSubnetGroupsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeCacheSubnetGroupsWithContext is the same as DescribeCacheSubnetGroups with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeCacheSubnetGroups 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 *ElastiCache) DescribeCacheSubnetGroupsWithContext(ctx aws.Context, input *DescribeCacheSubnetGroupsInput, opts ...request.Option) (*DescribeCacheSubnetGroupsOutput, error) { + req, out := c.DescribeCacheSubnetGroupsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // DescribeCacheSubnetGroupsPages iterates over the pages of a DescribeCacheSubnetGroups operation, @@ -2059,12 +2515,37 @@ func (c *ElastiCache) DescribeCacheSubnetGroups(input *DescribeCacheSubnetGroups // return pageNum <= 3 // }) // -func (c *ElastiCache) DescribeCacheSubnetGroupsPages(input *DescribeCacheSubnetGroupsInput, fn func(p *DescribeCacheSubnetGroupsOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.DescribeCacheSubnetGroupsRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*DescribeCacheSubnetGroupsOutput), lastPage) - }) +func (c *ElastiCache) DescribeCacheSubnetGroupsPages(input *DescribeCacheSubnetGroupsInput, fn func(*DescribeCacheSubnetGroupsOutput, bool) bool) error { + return c.DescribeCacheSubnetGroupsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// DescribeCacheSubnetGroupsPagesWithContext same as DescribeCacheSubnetGroupsPages 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 *ElastiCache) DescribeCacheSubnetGroupsPagesWithContext(ctx aws.Context, input *DescribeCacheSubnetGroupsInput, fn func(*DescribeCacheSubnetGroupsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *DescribeCacheSubnetGroupsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeCacheSubnetGroupsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*DescribeCacheSubnetGroupsOutput), !p.HasNextPage()) + } + return p.Err() } const opDescribeEngineDefaultParameters = "DescribeEngineDefaultParameters" @@ -2138,8 +2619,23 @@ func (c *ElastiCache) DescribeEngineDefaultParametersRequest(input *DescribeEngi // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticache-2015-02-02/DescribeEngineDefaultParameters func (c *ElastiCache) DescribeEngineDefaultParameters(input *DescribeEngineDefaultParametersInput) (*DescribeEngineDefaultParametersOutput, error) { req, out := c.DescribeEngineDefaultParametersRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeEngineDefaultParametersWithContext is the same as DescribeEngineDefaultParameters with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeEngineDefaultParameters 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 *ElastiCache) DescribeEngineDefaultParametersWithContext(ctx aws.Context, input *DescribeEngineDefaultParametersInput, opts ...request.Option) (*DescribeEngineDefaultParametersOutput, error) { + req, out := c.DescribeEngineDefaultParametersRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // DescribeEngineDefaultParametersPages iterates over the pages of a DescribeEngineDefaultParameters operation, @@ -2159,12 +2655,37 @@ func (c *ElastiCache) DescribeEngineDefaultParameters(input *DescribeEngineDefau // return pageNum <= 3 // }) // -func (c *ElastiCache) DescribeEngineDefaultParametersPages(input *DescribeEngineDefaultParametersInput, fn func(p *DescribeEngineDefaultParametersOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.DescribeEngineDefaultParametersRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*DescribeEngineDefaultParametersOutput), lastPage) - }) +func (c *ElastiCache) DescribeEngineDefaultParametersPages(input *DescribeEngineDefaultParametersInput, fn func(*DescribeEngineDefaultParametersOutput, bool) bool) error { + return c.DescribeEngineDefaultParametersPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// DescribeEngineDefaultParametersPagesWithContext same as DescribeEngineDefaultParametersPages 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 *ElastiCache) DescribeEngineDefaultParametersPagesWithContext(ctx aws.Context, input *DescribeEngineDefaultParametersInput, fn func(*DescribeEngineDefaultParametersOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *DescribeEngineDefaultParametersInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeEngineDefaultParametersRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*DescribeEngineDefaultParametersOutput), !p.HasNextPage()) + } + return p.Err() } const opDescribeEvents = "DescribeEvents" @@ -2243,8 +2764,23 @@ func (c *ElastiCache) DescribeEventsRequest(input *DescribeEventsInput) (req *re // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticache-2015-02-02/DescribeEvents func (c *ElastiCache) DescribeEvents(input *DescribeEventsInput) (*DescribeEventsOutput, error) { req, out := c.DescribeEventsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeEventsWithContext is the same as DescribeEvents with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeEvents 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 *ElastiCache) DescribeEventsWithContext(ctx aws.Context, input *DescribeEventsInput, opts ...request.Option) (*DescribeEventsOutput, error) { + req, out := c.DescribeEventsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // DescribeEventsPages iterates over the pages of a DescribeEvents operation, @@ -2264,12 +2800,37 @@ func (c *ElastiCache) DescribeEvents(input *DescribeEventsInput) (*DescribeEvent // return pageNum <= 3 // }) // -func (c *ElastiCache) DescribeEventsPages(input *DescribeEventsInput, fn func(p *DescribeEventsOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.DescribeEventsRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*DescribeEventsOutput), lastPage) - }) +func (c *ElastiCache) DescribeEventsPages(input *DescribeEventsInput, fn func(*DescribeEventsOutput, bool) bool) error { + return c.DescribeEventsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// DescribeEventsPagesWithContext same as DescribeEventsPages 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 *ElastiCache) DescribeEventsPagesWithContext(ctx aws.Context, input *DescribeEventsInput, fn func(*DescribeEventsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *DescribeEventsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeEventsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*DescribeEventsOutput), !p.HasNextPage()) + } + return p.Err() } const opDescribeReplicationGroups = "DescribeReplicationGroups" @@ -2349,8 +2910,23 @@ func (c *ElastiCache) DescribeReplicationGroupsRequest(input *DescribeReplicatio // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticache-2015-02-02/DescribeReplicationGroups func (c *ElastiCache) DescribeReplicationGroups(input *DescribeReplicationGroupsInput) (*DescribeReplicationGroupsOutput, error) { req, out := c.DescribeReplicationGroupsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeReplicationGroupsWithContext is the same as DescribeReplicationGroups with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeReplicationGroups 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 *ElastiCache) DescribeReplicationGroupsWithContext(ctx aws.Context, input *DescribeReplicationGroupsInput, opts ...request.Option) (*DescribeReplicationGroupsOutput, error) { + req, out := c.DescribeReplicationGroupsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // DescribeReplicationGroupsPages iterates over the pages of a DescribeReplicationGroups operation, @@ -2370,12 +2946,37 @@ func (c *ElastiCache) DescribeReplicationGroups(input *DescribeReplicationGroups // return pageNum <= 3 // }) // -func (c *ElastiCache) DescribeReplicationGroupsPages(input *DescribeReplicationGroupsInput, fn func(p *DescribeReplicationGroupsOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.DescribeReplicationGroupsRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*DescribeReplicationGroupsOutput), lastPage) - }) +func (c *ElastiCache) DescribeReplicationGroupsPages(input *DescribeReplicationGroupsInput, fn func(*DescribeReplicationGroupsOutput, bool) bool) error { + return c.DescribeReplicationGroupsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// DescribeReplicationGroupsPagesWithContext same as DescribeReplicationGroupsPages 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 *ElastiCache) DescribeReplicationGroupsPagesWithContext(ctx aws.Context, input *DescribeReplicationGroupsInput, fn func(*DescribeReplicationGroupsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *DescribeReplicationGroupsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeReplicationGroupsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*DescribeReplicationGroupsOutput), !p.HasNextPage()) + } + return p.Err() } const opDescribeReservedCacheNodes = "DescribeReservedCacheNodes" @@ -2452,8 +3053,23 @@ func (c *ElastiCache) DescribeReservedCacheNodesRequest(input *DescribeReservedC // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticache-2015-02-02/DescribeReservedCacheNodes func (c *ElastiCache) DescribeReservedCacheNodes(input *DescribeReservedCacheNodesInput) (*DescribeReservedCacheNodesOutput, error) { req, out := c.DescribeReservedCacheNodesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeReservedCacheNodesWithContext is the same as DescribeReservedCacheNodes with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeReservedCacheNodes 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 *ElastiCache) DescribeReservedCacheNodesWithContext(ctx aws.Context, input *DescribeReservedCacheNodesInput, opts ...request.Option) (*DescribeReservedCacheNodesOutput, error) { + req, out := c.DescribeReservedCacheNodesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // DescribeReservedCacheNodesPages iterates over the pages of a DescribeReservedCacheNodes operation, @@ -2473,12 +3089,37 @@ func (c *ElastiCache) DescribeReservedCacheNodes(input *DescribeReservedCacheNod // return pageNum <= 3 // }) // -func (c *ElastiCache) DescribeReservedCacheNodesPages(input *DescribeReservedCacheNodesInput, fn func(p *DescribeReservedCacheNodesOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.DescribeReservedCacheNodesRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*DescribeReservedCacheNodesOutput), lastPage) - }) +func (c *ElastiCache) DescribeReservedCacheNodesPages(input *DescribeReservedCacheNodesInput, fn func(*DescribeReservedCacheNodesOutput, bool) bool) error { + return c.DescribeReservedCacheNodesPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// DescribeReservedCacheNodesPagesWithContext same as DescribeReservedCacheNodesPages 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 *ElastiCache) DescribeReservedCacheNodesPagesWithContext(ctx aws.Context, input *DescribeReservedCacheNodesInput, fn func(*DescribeReservedCacheNodesOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *DescribeReservedCacheNodesInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeReservedCacheNodesRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*DescribeReservedCacheNodesOutput), !p.HasNextPage()) + } + return p.Err() } const opDescribeReservedCacheNodesOfferings = "DescribeReservedCacheNodesOfferings" @@ -2554,8 +3195,23 @@ func (c *ElastiCache) DescribeReservedCacheNodesOfferingsRequest(input *Describe // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticache-2015-02-02/DescribeReservedCacheNodesOfferings func (c *ElastiCache) DescribeReservedCacheNodesOfferings(input *DescribeReservedCacheNodesOfferingsInput) (*DescribeReservedCacheNodesOfferingsOutput, error) { req, out := c.DescribeReservedCacheNodesOfferingsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeReservedCacheNodesOfferingsWithContext is the same as DescribeReservedCacheNodesOfferings with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeReservedCacheNodesOfferings 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 *ElastiCache) DescribeReservedCacheNodesOfferingsWithContext(ctx aws.Context, input *DescribeReservedCacheNodesOfferingsInput, opts ...request.Option) (*DescribeReservedCacheNodesOfferingsOutput, error) { + req, out := c.DescribeReservedCacheNodesOfferingsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // DescribeReservedCacheNodesOfferingsPages iterates over the pages of a DescribeReservedCacheNodesOfferings operation, @@ -2575,12 +3231,37 @@ func (c *ElastiCache) DescribeReservedCacheNodesOfferings(input *DescribeReserve // return pageNum <= 3 // }) // -func (c *ElastiCache) DescribeReservedCacheNodesOfferingsPages(input *DescribeReservedCacheNodesOfferingsInput, fn func(p *DescribeReservedCacheNodesOfferingsOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.DescribeReservedCacheNodesOfferingsRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*DescribeReservedCacheNodesOfferingsOutput), lastPage) - }) +func (c *ElastiCache) DescribeReservedCacheNodesOfferingsPages(input *DescribeReservedCacheNodesOfferingsInput, fn func(*DescribeReservedCacheNodesOfferingsOutput, bool) bool) error { + return c.DescribeReservedCacheNodesOfferingsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// DescribeReservedCacheNodesOfferingsPagesWithContext same as DescribeReservedCacheNodesOfferingsPages 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 *ElastiCache) DescribeReservedCacheNodesOfferingsPagesWithContext(ctx aws.Context, input *DescribeReservedCacheNodesOfferingsInput, fn func(*DescribeReservedCacheNodesOfferingsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *DescribeReservedCacheNodesOfferingsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeReservedCacheNodesOfferingsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*DescribeReservedCacheNodesOfferingsOutput), !p.HasNextPage()) + } + return p.Err() } const opDescribeSnapshots = "DescribeSnapshots" @@ -2664,8 +3345,23 @@ func (c *ElastiCache) DescribeSnapshotsRequest(input *DescribeSnapshotsInput) (r // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticache-2015-02-02/DescribeSnapshots func (c *ElastiCache) DescribeSnapshots(input *DescribeSnapshotsInput) (*DescribeSnapshotsOutput, error) { req, out := c.DescribeSnapshotsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeSnapshotsWithContext is the same as DescribeSnapshots with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeSnapshots 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 *ElastiCache) DescribeSnapshotsWithContext(ctx aws.Context, input *DescribeSnapshotsInput, opts ...request.Option) (*DescribeSnapshotsOutput, error) { + req, out := c.DescribeSnapshotsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // DescribeSnapshotsPages iterates over the pages of a DescribeSnapshots operation, @@ -2685,12 +3381,37 @@ func (c *ElastiCache) DescribeSnapshots(input *DescribeSnapshotsInput) (*Describ // return pageNum <= 3 // }) // -func (c *ElastiCache) DescribeSnapshotsPages(input *DescribeSnapshotsInput, fn func(p *DescribeSnapshotsOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.DescribeSnapshotsRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*DescribeSnapshotsOutput), lastPage) - }) +func (c *ElastiCache) DescribeSnapshotsPages(input *DescribeSnapshotsInput, fn func(*DescribeSnapshotsOutput, bool) bool) error { + return c.DescribeSnapshotsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// DescribeSnapshotsPagesWithContext same as DescribeSnapshotsPages 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 *ElastiCache) DescribeSnapshotsPagesWithContext(ctx aws.Context, input *DescribeSnapshotsInput, fn func(*DescribeSnapshotsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *DescribeSnapshotsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeSnapshotsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*DescribeSnapshotsOutput), !p.HasNextPage()) + } + return p.Err() } const opListAllowedNodeTypeModifications = "ListAllowedNodeTypeModifications" @@ -2768,8 +3489,23 @@ func (c *ElastiCache) ListAllowedNodeTypeModificationsRequest(input *ListAllowed // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticache-2015-02-02/ListAllowedNodeTypeModifications func (c *ElastiCache) ListAllowedNodeTypeModifications(input *ListAllowedNodeTypeModificationsInput) (*ListAllowedNodeTypeModificationsOutput, error) { req, out := c.ListAllowedNodeTypeModificationsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListAllowedNodeTypeModificationsWithContext is the same as ListAllowedNodeTypeModifications with the addition of +// the ability to pass a context and additional request options. +// +// See ListAllowedNodeTypeModifications 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 *ElastiCache) ListAllowedNodeTypeModificationsWithContext(ctx aws.Context, input *ListAllowedNodeTypeModificationsInput, opts ...request.Option) (*ListAllowedNodeTypeModificationsOutput, error) { + req, out := c.ListAllowedNodeTypeModificationsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opListTagsForResource = "ListTagsForResource" @@ -2822,7 +3558,7 @@ func (c *ElastiCache) ListTagsForResourceRequest(input *ListTagsForResourceInput // optional. You can use cost allocation tags to categorize and track your AWS // costs. // -// You can have a maximum of 10 cost allocation tags on an ElastiCache resource. +// You can have a maximum of 50 cost allocation tags on an ElastiCache resource. // For more information, see Using Cost Allocation Tags in Amazon ElastiCache // (http://docs.aws.amazon.com/AmazonElastiCache/latest/UserGuide/BestPractices.html). // @@ -2846,8 +3582,23 @@ func (c *ElastiCache) ListTagsForResourceRequest(input *ListTagsForResourceInput // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticache-2015-02-02/ListTagsForResource func (c *ElastiCache) ListTagsForResource(input *ListTagsForResourceInput) (*TagListMessage, error) { req, out := c.ListTagsForResourceRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListTagsForResourceWithContext is the same as ListTagsForResource with the addition of +// the ability to pass a context and additional request options. +// +// See ListTagsForResource 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 *ElastiCache) ListTagsForResourceWithContext(ctx aws.Context, input *ListTagsForResourceInput, opts ...request.Option) (*TagListMessage, error) { + req, out := c.ListTagsForResourceRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opModifyCacheCluster = "ModifyCacheCluster" @@ -2948,8 +3699,23 @@ func (c *ElastiCache) ModifyCacheClusterRequest(input *ModifyCacheClusterInput) // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticache-2015-02-02/ModifyCacheCluster func (c *ElastiCache) ModifyCacheCluster(input *ModifyCacheClusterInput) (*ModifyCacheClusterOutput, error) { req, out := c.ModifyCacheClusterRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ModifyCacheClusterWithContext is the same as ModifyCacheCluster with the addition of +// the ability to pass a context and additional request options. +// +// See ModifyCacheCluster 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 *ElastiCache) ModifyCacheClusterWithContext(ctx aws.Context, input *ModifyCacheClusterInput, opts ...request.Option) (*ModifyCacheClusterOutput, error) { + req, out := c.ModifyCacheClusterRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opModifyCacheParameterGroup = "ModifyCacheParameterGroup" @@ -3026,8 +3792,23 @@ func (c *ElastiCache) ModifyCacheParameterGroupRequest(input *ModifyCacheParamet // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticache-2015-02-02/ModifyCacheParameterGroup func (c *ElastiCache) ModifyCacheParameterGroup(input *ModifyCacheParameterGroupInput) (*CacheParameterGroupNameMessage, error) { req, out := c.ModifyCacheParameterGroupRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ModifyCacheParameterGroupWithContext is the same as ModifyCacheParameterGroup with the addition of +// the ability to pass a context and additional request options. +// +// See ModifyCacheParameterGroup 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 *ElastiCache) ModifyCacheParameterGroupWithContext(ctx aws.Context, input *ModifyCacheParameterGroupInput, opts ...request.Option) (*CacheParameterGroupNameMessage, error) { + req, out := c.ModifyCacheParameterGroupRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opModifyCacheSubnetGroup = "ModifyCacheSubnetGroup" @@ -3102,8 +3883,23 @@ func (c *ElastiCache) ModifyCacheSubnetGroupRequest(input *ModifyCacheSubnetGrou // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticache-2015-02-02/ModifyCacheSubnetGroup func (c *ElastiCache) ModifyCacheSubnetGroup(input *ModifyCacheSubnetGroupInput) (*ModifyCacheSubnetGroupOutput, error) { req, out := c.ModifyCacheSubnetGroupRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ModifyCacheSubnetGroupWithContext is the same as ModifyCacheSubnetGroup with the addition of +// the ability to pass a context and additional request options. +// +// See ModifyCacheSubnetGroup 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 *ElastiCache) ModifyCacheSubnetGroupWithContext(ctx aws.Context, input *ModifyCacheSubnetGroupInput, opts ...request.Option) (*ModifyCacheSubnetGroupOutput, error) { + req, out := c.ModifyCacheSubnetGroupRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opModifyReplicationGroup = "ModifyReplicationGroup" @@ -3214,8 +4010,23 @@ func (c *ElastiCache) ModifyReplicationGroupRequest(input *ModifyReplicationGrou // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticache-2015-02-02/ModifyReplicationGroup func (c *ElastiCache) ModifyReplicationGroup(input *ModifyReplicationGroupInput) (*ModifyReplicationGroupOutput, error) { req, out := c.ModifyReplicationGroupRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ModifyReplicationGroupWithContext is the same as ModifyReplicationGroup with the addition of +// the ability to pass a context and additional request options. +// +// See ModifyReplicationGroup 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 *ElastiCache) ModifyReplicationGroupWithContext(ctx aws.Context, input *ModifyReplicationGroupInput, opts ...request.Option) (*ModifyReplicationGroupOutput, error) { + req, out := c.ModifyReplicationGroupRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opPurchaseReservedCacheNodesOffering = "PurchaseReservedCacheNodesOffering" @@ -3292,8 +4103,23 @@ func (c *ElastiCache) PurchaseReservedCacheNodesOfferingRequest(input *PurchaseR // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticache-2015-02-02/PurchaseReservedCacheNodesOffering func (c *ElastiCache) PurchaseReservedCacheNodesOffering(input *PurchaseReservedCacheNodesOfferingInput) (*PurchaseReservedCacheNodesOfferingOutput, error) { req, out := c.PurchaseReservedCacheNodesOfferingRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// PurchaseReservedCacheNodesOfferingWithContext is the same as PurchaseReservedCacheNodesOffering with the addition of +// the ability to pass a context and additional request options. +// +// See PurchaseReservedCacheNodesOffering 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 *ElastiCache) PurchaseReservedCacheNodesOfferingWithContext(ctx aws.Context, input *PurchaseReservedCacheNodesOfferingInput, opts ...request.Option) (*PurchaseReservedCacheNodesOfferingOutput, error) { + req, out := c.PurchaseReservedCacheNodesOfferingRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opRebootCacheCluster = "RebootCacheCluster" @@ -3369,8 +4195,23 @@ func (c *ElastiCache) RebootCacheClusterRequest(input *RebootCacheClusterInput) // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticache-2015-02-02/RebootCacheCluster func (c *ElastiCache) RebootCacheCluster(input *RebootCacheClusterInput) (*RebootCacheClusterOutput, error) { req, out := c.RebootCacheClusterRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// RebootCacheClusterWithContext is the same as RebootCacheCluster with the addition of +// the ability to pass a context and additional request options. +// +// See RebootCacheCluster 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 *ElastiCache) RebootCacheClusterWithContext(ctx aws.Context, input *RebootCacheClusterInput, opts ...request.Option) (*RebootCacheClusterOutput, error) { + req, out := c.RebootCacheClusterRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opRemoveTagsFromResource = "RemoveTagsFromResource" @@ -3443,8 +4284,23 @@ func (c *ElastiCache) RemoveTagsFromResourceRequest(input *RemoveTagsFromResourc // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticache-2015-02-02/RemoveTagsFromResource func (c *ElastiCache) RemoveTagsFromResource(input *RemoveTagsFromResourceInput) (*TagListMessage, error) { req, out := c.RemoveTagsFromResourceRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// RemoveTagsFromResourceWithContext is the same as RemoveTagsFromResource with the addition of +// the ability to pass a context and additional request options. +// +// See RemoveTagsFromResource 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 *ElastiCache) RemoveTagsFromResourceWithContext(ctx aws.Context, input *RemoveTagsFromResourceInput, opts ...request.Option) (*TagListMessage, error) { + req, out := c.RemoveTagsFromResourceRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opResetCacheParameterGroup = "ResetCacheParameterGroup" @@ -3522,8 +4378,23 @@ func (c *ElastiCache) ResetCacheParameterGroupRequest(input *ResetCacheParameter // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticache-2015-02-02/ResetCacheParameterGroup func (c *ElastiCache) ResetCacheParameterGroup(input *ResetCacheParameterGroupInput) (*CacheParameterGroupNameMessage, error) { req, out := c.ResetCacheParameterGroupRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ResetCacheParameterGroupWithContext is the same as ResetCacheParameterGroup with the addition of +// the ability to pass a context and additional request options. +// +// See ResetCacheParameterGroup 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 *ElastiCache) ResetCacheParameterGroupWithContext(ctx aws.Context, input *ResetCacheParameterGroupInput, opts ...request.Option) (*CacheParameterGroupNameMessage, error) { + req, out := c.ResetCacheParameterGroupRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opRevokeCacheSecurityGroupIngress = "RevokeCacheSecurityGroupIngress" @@ -3602,8 +4473,168 @@ func (c *ElastiCache) RevokeCacheSecurityGroupIngressRequest(input *RevokeCacheS // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticache-2015-02-02/RevokeCacheSecurityGroupIngress func (c *ElastiCache) RevokeCacheSecurityGroupIngress(input *RevokeCacheSecurityGroupIngressInput) (*RevokeCacheSecurityGroupIngressOutput, error) { req, out := c.RevokeCacheSecurityGroupIngressRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// RevokeCacheSecurityGroupIngressWithContext is the same as RevokeCacheSecurityGroupIngress with the addition of +// the ability to pass a context and additional request options. +// +// See RevokeCacheSecurityGroupIngress 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 *ElastiCache) RevokeCacheSecurityGroupIngressWithContext(ctx aws.Context, input *RevokeCacheSecurityGroupIngressInput, opts ...request.Option) (*RevokeCacheSecurityGroupIngressOutput, error) { + req, out := c.RevokeCacheSecurityGroupIngressRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opTestFailover = "TestFailover" + +// TestFailoverRequest generates a "aws/request.Request" representing the +// client's request for the TestFailover operation. The "output" return +// value can be used to capture response data after the request's "Send" method +// is called. +// +// See TestFailover for usage and error information. +// +// Creating a request object using this method should be used when you want to inject +// custom logic into the request's lifecycle using a custom handler, or if you want to +// access properties on the request object before or after sending the request. If +// you just want the service response, call the TestFailover method directly +// instead. +// +// Note: You must call the "Send" method on the returned request object in order +// to execute the request. +// +// // Example sending a request using the TestFailoverRequest method. +// req, resp := client.TestFailoverRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticache-2015-02-02/TestFailover +func (c *ElastiCache) TestFailoverRequest(input *TestFailoverInput) (req *request.Request, output *TestFailoverOutput) { + op := &request.Operation{ + Name: opTestFailover, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &TestFailoverInput{} + } + + output = &TestFailoverOutput{} + req = c.newRequest(op, input, output) + return +} + +// TestFailover API operation for Amazon ElastiCache. +// +// Represents the input of a TestFailover operation which test automatic failover +// on a specified node group (called shard in the console) in a replication +// group (called cluster in the console). +// +// Note the following +// +// * A customer can use this operation to test automatic failover on up to +// 5 shards (called node groups in the ElastiCache API and AWS CLI) in any +// rolling 24-hour period. +// +// * If calling this operation on shards in different clusters (called replication +// groups in the API and CLI), the calls can be made concurrently. +// +// * If calling this operation multiple times on different shards in the +// same Redis (cluster mode enabled) replication group, the first node replacement +// must complete before a subsequent call can be made. +// +// * To determine whether the node replacement is complete you can check +// Events using the Amazon ElastiCache console, the AWS CLI, or the ElastiCache +// API. Look for the following automatic failover related events, listed +// here in order of occurrance: +// +// Replication group message: Test Failover API called for node group +// +// Cache cluster message: Failover from master node to replica +// node completed +// +// Replication group message: Failover from master node to +// replica node completed +// +// Cache cluster message: Recovering cache nodes +// +// Cache cluster message: Finished recovery for cache nodes +// +// For more information see: +// +// Viewing ElastiCache Events (http://docs.aws.amazon.com/AmazonElastiCache/latest/UserGuide/ECEvents.Viewing.html) +// in the ElastiCache User Guide +// +// DescribeEvents (http://docs.aws.amazon.com/AmazonElastiCache/latest/APIReference/API_DescribeEvents.html) +// in the ElastiCache API Reference +// +// Also see, Testing Multi-AZ with Automatic Failover (http://docs.aws.amazon.com/AmazonElastiCache/latest/UserGuide/AutoFailover.html#auto-failover-test) +// in the ElastiCache 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. +// +// See the AWS API reference guide for Amazon ElastiCache's +// API operation TestFailover for usage and error information. +// +// Returned Error Codes: +// * ErrCodeAPICallRateForCustomerExceededFault "APICallRateForCustomerExceeded" +// The customer has exceeded the allowed rate of API calls. +// +// * ErrCodeInvalidCacheClusterStateFault "InvalidCacheClusterState" +// The requested cache cluster is not in the available state. +// +// * ErrCodeInvalidReplicationGroupStateFault "InvalidReplicationGroupState" +// The requested replication group is not in the available state. +// +// * ErrCodeNodeGroupNotFoundFault "NodeGroupNotFoundFault" +// The node group specified by the NodeGroupId parameter could not be found. +// Please verify that the node group exists and that you spelled the NodeGroupId +// value correctly. +// +// * ErrCodeReplicationGroupNotFoundFault "ReplicationGroupNotFoundFault" +// The specified replication group does not exist. +// +// * ErrCodeTestFailoverNotAvailableFault "TestFailoverNotAvailableFault" +// +// * ErrCodeInvalidParameterValueException "InvalidParameterValue" +// The value for a parameter is invalid. +// +// * ErrCodeInvalidParameterCombinationException "InvalidParameterCombination" +// Two or more incompatible parameters were specified. +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticache-2015-02-02/TestFailover +func (c *ElastiCache) TestFailover(input *TestFailoverInput) (*TestFailoverOutput, error) { + req, out := c.TestFailoverRequest(input) + return out, req.Send() +} + +// TestFailoverWithContext is the same as TestFailover with the addition of +// the ability to pass a context and additional request options. +// +// See TestFailover 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 *ElastiCache) TestFailoverWithContext(ctx aws.Context, input *TestFailoverInput, opts ...request.Option) (*TestFailoverOutput, error) { + req, out := c.TestFailoverRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // Represents the input of an AddTagsToResource operation. @@ -3868,8 +4899,11 @@ type CacheCluster struct { // library. ClientDownloadLandingPage *string `type:"string"` - // Represents the information required for client programs to connect to a cache - // node. + // Represents a Memcached cluster endpoint which, if Automatic Discovery is + // enabled on the cluster, can be used by an application to connect to any node + // in the cluster. The configuration endpoint will always have .cfg in it. + // + // Example: mem-3.9dvc4r.cfg.usw2.cache.amazonaws.com:11211 ConfigurationEndpoint *Endpoint `type:"structure"` // The name of the cache engine (memcached or redis) to be used for this cache @@ -5636,8 +6670,8 @@ type CreateReplicationGroupInput struct { // ReplicaCount. // // If you're creating a Redis (cluster mode disabled) or a Redis (cluster mode - // enabled) replication group, you can use this parameter to configure one node - // group (shard) or you can omit this parameter. + // enabled) replication group, you can use this parameter to individually configure + // each node group (shard), or you can omit this parameter. NodeGroupConfiguration []*NodeGroupConfiguration `locationNameList:"NodeGroupConfiguration" type:"list"` // The Amazon Resource Name (ARN) of the Amazon Simple Notification Service @@ -5651,7 +6685,10 @@ type CreateReplicationGroupInput struct { // This parameter is not used if there is more than one node group (shard). // You should use ReplicasPerNodeGroup instead. // - // If Multi-AZ is enabled, the value of this parameter must be at least 2. + // If AutomaticFailoverEnabled is true, the value of this parameter must be + // at least 2. If AutomaticFailoverEnabled is false you can omit this parameter + // (it will default to 1), or you can explicitly set it to a value between 2 + // and 6. // // The maximum permitted value for NumCacheClusters is 6 (primary plus 5 replicas). NumCacheClusters *int64 `type:"integer"` @@ -5749,9 +6786,11 @@ type CreateReplicationGroupInput struct { // A list of Amazon Resource Names (ARN) that uniquely identify the Redis RDB // snapshot files stored in Amazon S3. The snapshot files are used to populate - // the replication group. The Amazon S3 object name in the ARN cannot contain - // any commas. The list must match the number of node groups (shards) in the - // replication group, which means you cannot repartition. + // the new replication group. The Amazon S3 object name in the ARN cannot contain + // any commas. The new replication group will have the number of node groups + // (console: shards) specified by the parameter NumNodeGroups or the number + // of node groups configured by NodeGroupConfiguration regardless of the number + // of ARNs specified here. // // This parameter is only valid if the Engine parameter is redis. // @@ -6505,6 +7544,11 @@ type DescribeCacheClustersInput struct { // Constraints: minimum 20; maximum 100. MaxRecords *int64 `type:"integer"` + // An optional flag that can be included in the DescribeCacheCluster request + // to show only nodes (API/CLI: clusters) that are not members of a replication + // group. In practice, this mean Memcached and single node Redis clusters. + ShowCacheClustersNotInReplicationGroups *bool `type:"boolean"` + // An optional flag that can be included in the DescribeCacheCluster request // to retrieve information about the individual cache nodes. ShowCacheNodeInfo *bool `type:"boolean"` @@ -6538,6 +7582,12 @@ func (s *DescribeCacheClustersInput) SetMaxRecords(v int64) *DescribeCacheCluste return s } +// SetShowCacheClustersNotInReplicationGroups sets the ShowCacheClustersNotInReplicationGroups field's value. +func (s *DescribeCacheClustersInput) SetShowCacheClustersNotInReplicationGroups(v bool) *DescribeCacheClustersInput { + s.ShowCacheClustersNotInReplicationGroups = &v + return s +} + // SetShowCacheNodeInfo sets the ShowCacheNodeInfo field's value. func (s *DescribeCacheClustersInput) SetShowCacheNodeInfo(v bool) *DescribeCacheClustersInput { s.ShowCacheNodeInfo = &v @@ -7181,11 +8231,13 @@ func (s *DescribeEngineDefaultParametersOutput) SetEngineDefaults(v *EngineDefau type DescribeEventsInput struct { _ struct{} `type:"structure"` - // The number of minutes' worth of events to retrieve. + // The number of minutes worth of events to retrieve. Duration *int64 `type:"integer"` // The end of the time interval for which to retrieve events, specified in ISO // 8601 format. + // + // Example: 2017-03-30T07:03:49.555Z EndTime *time.Time `type:"timestamp" timestampFormat:"iso8601"` // An optional marker returned from a prior request. Use this marker for pagination @@ -7212,6 +8264,8 @@ type DescribeEventsInput struct { // The beginning of the time interval to retrieve events for, specified in ISO // 8601 format. + // + // Example: 2017-03-30T07:03:49.555Z StartTime *time.Time `type:"timestamp" timestampFormat:"iso8601"` } @@ -8106,10 +9160,18 @@ func (s *ListAllowedNodeTypeModificationsInput) SetReplicationGroupId(v string) return s } +// Represents the allowed node types you can use to modify your cache cluster +// or replication group. // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticache-2015-02-02/AllowedNodeTypeModificationsMessage type ListAllowedNodeTypeModificationsOutput struct { _ struct{} `type:"structure"` + // A string list, each element of which specifies a cache node type which you + // can use to scale your cache cluster or replication group. + // + // When scaling up a Redis cluster or replication group using ModifyCacheCluster + // or ModifyReplicationGroup, use a value from this list for the CacheNodeType + // parameter. ScaleUpModifications []*string `type:"list"` } @@ -8778,6 +9840,9 @@ type ModifyReplicationGroupInput struct { // and create it anew with the earlier engine version. EngineVersion *string `type:"string"` + // The name of the Node Group (called shard in the console). + NodeGroupId *string `type:"string"` + // The Amazon Resource Name (ARN) of the Amazon SNS topic to which notifications // are sent. // @@ -8923,6 +9988,12 @@ func (s *ModifyReplicationGroupInput) SetEngineVersion(v string) *ModifyReplicat return s } +// SetNodeGroupId sets the NodeGroupId field's value. +func (s *ModifyReplicationGroupInput) SetNodeGroupId(v string) *ModifyReplicationGroupInput { + s.NodeGroupId = &v + return s +} + // SetNotificationTopicArn sets the NotificationTopicArn field's value. func (s *ModifyReplicationGroupInput) SetNotificationTopicArn(v string) *ModifyReplicationGroupInput { s.NotificationTopicArn = &v @@ -9093,8 +10164,8 @@ type NodeGroupConfiguration struct { // The number of read replica nodes in this node group (shard). ReplicaCount *int64 `type:"integer"` - // A string that specifies the keyspaces as a series of comma separated values. - // Keyspaces are 0 to 16,383. The string is in the format startkey-endkey. + // A string that specifies the keyspace for a particular node group. Keyspaces + // range from 0 to 16,383. The string is in the format startkey-endkey. // // Example: "0-3999" Slots *string `type:"string"` @@ -9790,6 +10861,17 @@ type ReplicationGroup struct { // Redis (cluster mode enabled): T1 node types. AutomaticFailover *string `type:"string" enum:"AutomaticFailoverStatus"` + // The name of the compute and memory capacity node type for each node in the + // replication group. + CacheNodeType *string `type:"string"` + + // A flag indicating whether or not this replication group is cluster enabled; + // i.e., whether its data can be partitioned across multiple shards (API/CLI: + // node groups). + // + // Valid values: true | false + ClusterEnabled *bool `type:"boolean"` + // The configuration endpoint for this replicaiton group. Use the configuration // endpoint to connect to this replication group. ConfigurationEndpoint *Endpoint `type:"structure"` @@ -9856,6 +10938,18 @@ func (s *ReplicationGroup) SetAutomaticFailover(v string) *ReplicationGroup { return s } +// SetCacheNodeType sets the CacheNodeType field's value. +func (s *ReplicationGroup) SetCacheNodeType(v string) *ReplicationGroup { + s.CacheNodeType = &v + return s +} + +// SetClusterEnabled sets the ClusterEnabled field's value. +func (s *ReplicationGroup) SetClusterEnabled(v bool) *ReplicationGroup { + s.ClusterEnabled = &v + return s +} + // SetConfigurationEndpoint sets the ConfigurationEndpoint field's value. func (s *ReplicationGroup) SetConfigurationEndpoint(v *Endpoint) *ReplicationGroup { s.ConfigurationEndpoint = v @@ -10810,10 +11904,10 @@ func (s *Subnet) SetSubnetIdentifier(v string) *Subnet { type Tag struct { _ struct{} `type:"structure"` - // The key for the tag. + // The key for the tag. May not be null. Key *string `type:"string"` - // The tag's value. May not be null. + // The tag's value. May be null. Value *string `type:"string"` } @@ -10839,7 +11933,7 @@ func (s *Tag) SetValue(v string) *Tag { return s } -// Represents the output from the AddTagsToResource, ListTagsOnResource, and +// Represents the output from the AddTagsToResource, ListTagsForResource, and // RemoveTagsFromResource operations. // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticache-2015-02-02/TagListMessage type TagListMessage struct { @@ -10865,6 +11959,86 @@ func (s *TagListMessage) SetTagList(v []*Tag) *TagListMessage { return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticache-2015-02-02/TestFailoverMessage +type TestFailoverInput struct { + _ struct{} `type:"structure"` + + // The name of the node group (called shard in the console) in this replication + // group on which automatic failover is to be tested. You may test automatic + // failover on up to 5 node groups in any rolling 24-hour period. + // + // NodeGroupId is a required field + NodeGroupId *string `type:"string" required:"true"` + + // The name of the replication group (console: cluster) whose automatic failover + // is being tested by this operation. + // + // ReplicationGroupId is a required field + ReplicationGroupId *string `type:"string" required:"true"` +} + +// String returns the string representation +func (s TestFailoverInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s TestFailoverInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *TestFailoverInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "TestFailoverInput"} + if s.NodeGroupId == nil { + invalidParams.Add(request.NewErrParamRequired("NodeGroupId")) + } + if s.ReplicationGroupId == nil { + invalidParams.Add(request.NewErrParamRequired("ReplicationGroupId")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetNodeGroupId sets the NodeGroupId field's value. +func (s *TestFailoverInput) SetNodeGroupId(v string) *TestFailoverInput { + s.NodeGroupId = &v + return s +} + +// SetReplicationGroupId sets the ReplicationGroupId field's value. +func (s *TestFailoverInput) SetReplicationGroupId(v string) *TestFailoverInput { + s.ReplicationGroupId = &v + return s +} + +// Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticache-2015-02-02/TestFailoverResult +type TestFailoverOutput struct { + _ struct{} `type:"structure"` + + // Contains all of the attributes of a specific Redis replication group. + ReplicationGroup *ReplicationGroup `type:"structure"` +} + +// String returns the string representation +func (s TestFailoverOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s TestFailoverOutput) GoString() string { + return s.String() +} + +// SetReplicationGroup sets the ReplicationGroup field's value. +func (s *TestFailoverOutput) SetReplicationGroup(v *ReplicationGroup) *TestFailoverOutput { + s.ReplicationGroup = v + return s +} + const ( // AZModeSingleAz is a AZMode enum value AZModeSingleAz = "single-az" diff --git a/vendor/github.com/aws/aws-sdk-go/service/elasticache/doc.go b/vendor/github.com/aws/aws-sdk-go/service/elasticache/doc.go new file mode 100644 index 000000000..3abbaa264 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/service/elasticache/doc.go @@ -0,0 +1,90 @@ +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. + +// Package elasticache provides the client and types for making API +// requests to Amazon ElastiCache. +// +// Amazon ElastiCache is a web service that makes it easier to set up, operate, +// and scale a distributed cache in the cloud. +// +// With ElastiCache, customers get all of the benefits of a high-performance, +// in-memory cache with less of the administrative burden involved in launching +// and managing a distributed cache. The service makes setup, scaling, and cluster +// failure handling much simpler than in a self-managed cache deployment. +// +// In addition, through integration with Amazon CloudWatch, customers get enhanced +// visibility into the key performance statistics associated with their cache +// and can receive alarms if a part of their cache runs hot. +// +// See https://docs.aws.amazon.com/goto/WebAPI/elasticache-2015-02-02 for more information on this service. +// +// See elasticache package documentation for more information. +// https://docs.aws.amazon.com/sdk-for-go/api/service/elasticache/ +// +// Using the Client +// +// To use the client for Amazon ElastiCache you will first need +// to create a new instance of it. +// +// When creating a client for an AWS service you'll first need to have a Session +// already created. The Session provides configuration that can be shared +// between multiple service clients. Additional configuration can be applied to +// the Session and service's client when they are constructed. The aws package's +// Config type contains several fields such as Region for the AWS Region the +// client should make API requests too. The optional Config value can be provided +// as the variadic argument for Sessions and client creation. +// +// Once the service's client is created you can use it to make API requests the +// AWS service. These clients are safe to use concurrently. +// +// // Create a session to share configuration, and load external configuration. +// sess := session.Must(session.NewSession()) +// +// // Create the service's client with the session. +// svc := elasticache.New(sess) +// +// See the SDK's documentation for more information on how to use service clients. +// https://docs.aws.amazon.com/sdk-for-go/api/ +// +// See aws package's Config type for more information on configuration options. +// https://docs.aws.amazon.com/sdk-for-go/api/aws/#Config +// +// See the Amazon ElastiCache client ElastiCache for more +// information on creating the service's client. +// https://docs.aws.amazon.com/sdk-for-go/api/service/elasticache/#New +// +// Once the client is created you can make an API request to the service. +// Each API method takes a input parameter, and returns the service response +// and an error. +// +// The API method will document which error codes the service can be returned +// by the operation if the service models the API operation's errors. These +// errors will also be available as const strings prefixed with "ErrCode". +// +// result, err := svc.AddTagsToResource(params) +// if err != nil { +// // Cast err to awserr.Error to handle specific error codes. +// aerr, ok := err.(awserr.Error) +// if ok && aerr.Code() == { +// // Specific error code handling +// } +// return err +// } +// +// fmt.Println("AddTagsToResource result:") +// fmt.Println(result) +// +// Using the Client with Context +// +// The service's client also provides methods to make API requests with a Context +// value. This allows you to control the timeout, and cancellation of pending +// requests. These methods also take request Option as variadic parameter to apply +// additional configuration to the API request. +// +// ctx := context.Background() +// +// result, err := svc.AddTagsToResourceWithContext(ctx, params) +// +// See the request package documentation for more information on using Context pattern +// with the SDK. +// https://docs.aws.amazon.com/sdk-for-go/api/aws/request/ +package elasticache diff --git a/vendor/github.com/aws/aws-sdk-go/service/elasticache/errors.go b/vendor/github.com/aws/aws-sdk-go/service/elasticache/errors.go index f5cffec0a..668d6c52b 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/elasticache/errors.go +++ b/vendor/github.com/aws/aws-sdk-go/service/elasticache/errors.go @@ -1,9 +1,15 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. package elasticache const ( + // ErrCodeAPICallRateForCustomerExceededFault for service response error code + // "APICallRateForCustomerExceeded". + // + // The customer has exceeded the allowed rate of API calls. + ErrCodeAPICallRateForCustomerExceededFault = "APICallRateForCustomerExceeded" + // ErrCodeAuthorizationAlreadyExistsFault for service response error code // "AuthorizationAlreadyExists". // @@ -180,6 +186,14 @@ const ( // The VPC network is in an invalid state. ErrCodeInvalidVPCNetworkStateFault = "InvalidVPCNetworkStateFault" + // ErrCodeNodeGroupNotFoundFault for service response error code + // "NodeGroupNotFoundFault". + // + // The node group specified by the NodeGroupId parameter could not be found. + // Please verify that the node group exists and that you spelled the NodeGroupId + // value correctly. + ErrCodeNodeGroupNotFoundFault = "NodeGroupNotFoundFault" + // ErrCodeNodeGroupsPerReplicationGroupQuotaExceededFault for service response error code // "NodeGroupsPerReplicationGroupQuotaExceeded". // @@ -288,6 +302,10 @@ const ( // // The request cannot be processed because it would cause the resource to have // more than the allowed number of tags. The maximum number of tags permitted - // on a resource is 10. + // on a resource is 50. ErrCodeTagQuotaPerResourceExceeded = "TagQuotaPerResourceExceeded" + + // ErrCodeTestFailoverNotAvailableFault for service response error code + // "TestFailoverNotAvailableFault". + ErrCodeTestFailoverNotAvailableFault = "TestFailoverNotAvailableFault" ) diff --git a/vendor/github.com/aws/aws-sdk-go/service/elasticache/service.go b/vendor/github.com/aws/aws-sdk-go/service/elasticache/service.go index 7654b3bd7..40bed298a 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/elasticache/service.go +++ b/vendor/github.com/aws/aws-sdk-go/service/elasticache/service.go @@ -1,4 +1,4 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. package elasticache @@ -11,20 +11,12 @@ import ( "github.com/aws/aws-sdk-go/private/protocol/query" ) -// Amazon ElastiCache is a web service that makes it easier to set up, operate, -// and scale a distributed cache in the cloud. +// ElastiCache provides the API operation methods for making requests to +// Amazon ElastiCache. See this package's package overview docs +// for details on the service. // -// With ElastiCache, customers get all of the benefits of a high-performance, -// in-memory cache with less of the administrative burden involved in launching -// and managing a distributed cache. The service makes setup, scaling, and cluster -// failure handling much simpler than in a self-managed cache deployment. -// -// In addition, through integration with Amazon CloudWatch, customers get enhanced -// visibility into the key performance statistics associated with their cache -// and can receive alarms if a part of their cache runs hot. -// The service client's operations are safe to be used concurrently. -// It is not safe to mutate any of the client's properties though. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticache-2015-02-02 +// ElastiCache methods are safe to use concurrently. It is not safe to +// modify mutate any of the struct's properties though. type ElastiCache struct { *client.Client } diff --git a/vendor/github.com/aws/aws-sdk-go/service/elasticache/waiters.go b/vendor/github.com/aws/aws-sdk-go/service/elasticache/waiters.go index 2e25f84d6..d5ab1eedf 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/elasticache/waiters.go +++ b/vendor/github.com/aws/aws-sdk-go/service/elasticache/waiters.go @@ -1,9 +1,12 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. package elasticache import ( - "github.com/aws/aws-sdk-go/private/waiter" + "time" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/request" ) // WaitUntilCacheClusterAvailable uses the Amazon ElastiCache API operation @@ -11,50 +14,65 @@ import ( // If the condition is not meet within the max attempt window an error will // be returned. func (c *ElastiCache) WaitUntilCacheClusterAvailable(input *DescribeCacheClustersInput) error { - waiterCfg := waiter.Config{ - Operation: "DescribeCacheClusters", - Delay: 15, + return c.WaitUntilCacheClusterAvailableWithContext(aws.BackgroundContext(), input) +} + +// WaitUntilCacheClusterAvailableWithContext is an extended version of WaitUntilCacheClusterAvailable. +// 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 *ElastiCache) WaitUntilCacheClusterAvailableWithContext(ctx aws.Context, input *DescribeCacheClustersInput, opts ...request.WaiterOption) error { + w := request.Waiter{ + Name: "WaitUntilCacheClusterAvailable", MaxAttempts: 40, - Acceptors: []waiter.WaitAcceptor{ + Delay: request.ConstantWaiterDelay(15 * time.Second), + Acceptors: []request.WaiterAcceptor{ { - State: "success", - Matcher: "pathAll", - Argument: "CacheClusters[].CacheClusterStatus", + State: request.SuccessWaiterState, + Matcher: request.PathAllWaiterMatch, Argument: "CacheClusters[].CacheClusterStatus", Expected: "available", }, { - State: "failure", - Matcher: "pathAny", - Argument: "CacheClusters[].CacheClusterStatus", + State: request.FailureWaiterState, + Matcher: request.PathAnyWaiterMatch, Argument: "CacheClusters[].CacheClusterStatus", Expected: "deleted", }, { - State: "failure", - Matcher: "pathAny", - Argument: "CacheClusters[].CacheClusterStatus", + State: request.FailureWaiterState, + Matcher: request.PathAnyWaiterMatch, Argument: "CacheClusters[].CacheClusterStatus", Expected: "deleting", }, { - State: "failure", - Matcher: "pathAny", - Argument: "CacheClusters[].CacheClusterStatus", + State: request.FailureWaiterState, + Matcher: request.PathAnyWaiterMatch, Argument: "CacheClusters[].CacheClusterStatus", Expected: "incompatible-network", }, { - State: "failure", - Matcher: "pathAny", - Argument: "CacheClusters[].CacheClusterStatus", + State: request.FailureWaiterState, + Matcher: request.PathAnyWaiterMatch, Argument: "CacheClusters[].CacheClusterStatus", Expected: "restore-failed", }, }, + Logger: c.Config.Logger, + NewRequest: func(opts []request.Option) (*request.Request, error) { + var inCpy *DescribeCacheClustersInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeCacheClustersRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, } + w.ApplyOptions(opts...) - w := waiter.Waiter{ - Client: c, - Input: input, - Config: waiterCfg, - } - return w.Wait() + return w.WaitWithContext(ctx) } // WaitUntilCacheClusterDeleted uses the Amazon ElastiCache API operation @@ -62,68 +80,80 @@ func (c *ElastiCache) WaitUntilCacheClusterAvailable(input *DescribeCacheCluster // If the condition is not meet within the max attempt window an error will // be returned. func (c *ElastiCache) WaitUntilCacheClusterDeleted(input *DescribeCacheClustersInput) error { - waiterCfg := waiter.Config{ - Operation: "DescribeCacheClusters", - Delay: 15, + return c.WaitUntilCacheClusterDeletedWithContext(aws.BackgroundContext(), input) +} + +// WaitUntilCacheClusterDeletedWithContext is an extended version of WaitUntilCacheClusterDeleted. +// 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 *ElastiCache) WaitUntilCacheClusterDeletedWithContext(ctx aws.Context, input *DescribeCacheClustersInput, opts ...request.WaiterOption) error { + w := request.Waiter{ + Name: "WaitUntilCacheClusterDeleted", MaxAttempts: 40, - Acceptors: []waiter.WaitAcceptor{ + Delay: request.ConstantWaiterDelay(15 * time.Second), + Acceptors: []request.WaiterAcceptor{ { - State: "success", - Matcher: "pathAll", - Argument: "CacheClusters[].CacheClusterStatus", + State: request.SuccessWaiterState, + Matcher: request.PathAllWaiterMatch, Argument: "CacheClusters[].CacheClusterStatus", Expected: "deleted", }, { - State: "success", - Matcher: "error", - Argument: "", + State: request.SuccessWaiterState, + Matcher: request.ErrorWaiterMatch, Expected: "CacheClusterNotFound", }, { - State: "failure", - Matcher: "pathAny", - Argument: "CacheClusters[].CacheClusterStatus", + State: request.FailureWaiterState, + Matcher: request.PathAnyWaiterMatch, Argument: "CacheClusters[].CacheClusterStatus", Expected: "available", }, { - State: "failure", - Matcher: "pathAny", - Argument: "CacheClusters[].CacheClusterStatus", + State: request.FailureWaiterState, + Matcher: request.PathAnyWaiterMatch, Argument: "CacheClusters[].CacheClusterStatus", Expected: "creating", }, { - State: "failure", - Matcher: "pathAny", - Argument: "CacheClusters[].CacheClusterStatus", + State: request.FailureWaiterState, + Matcher: request.PathAnyWaiterMatch, Argument: "CacheClusters[].CacheClusterStatus", Expected: "incompatible-network", }, { - State: "failure", - Matcher: "pathAny", - Argument: "CacheClusters[].CacheClusterStatus", + State: request.FailureWaiterState, + Matcher: request.PathAnyWaiterMatch, Argument: "CacheClusters[].CacheClusterStatus", Expected: "modifying", }, { - State: "failure", - Matcher: "pathAny", - Argument: "CacheClusters[].CacheClusterStatus", + State: request.FailureWaiterState, + Matcher: request.PathAnyWaiterMatch, Argument: "CacheClusters[].CacheClusterStatus", Expected: "restore-failed", }, { - State: "failure", - Matcher: "pathAny", - Argument: "CacheClusters[].CacheClusterStatus", + State: request.FailureWaiterState, + Matcher: request.PathAnyWaiterMatch, Argument: "CacheClusters[].CacheClusterStatus", Expected: "snapshotting", }, }, + Logger: c.Config.Logger, + NewRequest: func(opts []request.Option) (*request.Request, error) { + var inCpy *DescribeCacheClustersInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeCacheClustersRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, } + w.ApplyOptions(opts...) - w := waiter.Waiter{ - Client: c, - Input: input, - Config: waiterCfg, - } - return w.Wait() + return w.WaitWithContext(ctx) } // WaitUntilReplicationGroupAvailable uses the Amazon ElastiCache API operation @@ -131,32 +161,50 @@ func (c *ElastiCache) WaitUntilCacheClusterDeleted(input *DescribeCacheClustersI // If the condition is not meet within the max attempt window an error will // be returned. func (c *ElastiCache) WaitUntilReplicationGroupAvailable(input *DescribeReplicationGroupsInput) error { - waiterCfg := waiter.Config{ - Operation: "DescribeReplicationGroups", - Delay: 15, + return c.WaitUntilReplicationGroupAvailableWithContext(aws.BackgroundContext(), input) +} + +// WaitUntilReplicationGroupAvailableWithContext is an extended version of WaitUntilReplicationGroupAvailable. +// 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 *ElastiCache) WaitUntilReplicationGroupAvailableWithContext(ctx aws.Context, input *DescribeReplicationGroupsInput, opts ...request.WaiterOption) error { + w := request.Waiter{ + Name: "WaitUntilReplicationGroupAvailable", MaxAttempts: 40, - Acceptors: []waiter.WaitAcceptor{ + Delay: request.ConstantWaiterDelay(15 * time.Second), + Acceptors: []request.WaiterAcceptor{ { - State: "success", - Matcher: "pathAll", - Argument: "ReplicationGroups[].Status", + State: request.SuccessWaiterState, + Matcher: request.PathAllWaiterMatch, Argument: "ReplicationGroups[].Status", Expected: "available", }, { - State: "failure", - Matcher: "pathAny", - Argument: "ReplicationGroups[].Status", + State: request.FailureWaiterState, + Matcher: request.PathAnyWaiterMatch, Argument: "ReplicationGroups[].Status", Expected: "deleted", }, }, + Logger: c.Config.Logger, + NewRequest: func(opts []request.Option) (*request.Request, error) { + var inCpy *DescribeReplicationGroupsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeReplicationGroupsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, } + w.ApplyOptions(opts...) - w := waiter.Waiter{ - Client: c, - Input: input, - Config: waiterCfg, - } - return w.Wait() + return w.WaitWithContext(ctx) } // WaitUntilReplicationGroupDeleted uses the Amazon ElastiCache API operation @@ -164,36 +212,53 @@ func (c *ElastiCache) WaitUntilReplicationGroupAvailable(input *DescribeReplicat // If the condition is not meet within the max attempt window an error will // be returned. func (c *ElastiCache) WaitUntilReplicationGroupDeleted(input *DescribeReplicationGroupsInput) error { - waiterCfg := waiter.Config{ - Operation: "DescribeReplicationGroups", - Delay: 15, + return c.WaitUntilReplicationGroupDeletedWithContext(aws.BackgroundContext(), input) +} + +// WaitUntilReplicationGroupDeletedWithContext is an extended version of WaitUntilReplicationGroupDeleted. +// 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 *ElastiCache) WaitUntilReplicationGroupDeletedWithContext(ctx aws.Context, input *DescribeReplicationGroupsInput, opts ...request.WaiterOption) error { + w := request.Waiter{ + Name: "WaitUntilReplicationGroupDeleted", MaxAttempts: 40, - Acceptors: []waiter.WaitAcceptor{ + Delay: request.ConstantWaiterDelay(15 * time.Second), + Acceptors: []request.WaiterAcceptor{ { - State: "success", - Matcher: "pathAll", - Argument: "ReplicationGroups[].Status", + State: request.SuccessWaiterState, + Matcher: request.PathAllWaiterMatch, Argument: "ReplicationGroups[].Status", Expected: "deleted", }, { - State: "failure", - Matcher: "pathAny", - Argument: "ReplicationGroups[].Status", + State: request.FailureWaiterState, + Matcher: request.PathAnyWaiterMatch, Argument: "ReplicationGroups[].Status", Expected: "available", }, { - State: "success", - Matcher: "error", - Argument: "", + State: request.SuccessWaiterState, + Matcher: request.ErrorWaiterMatch, Expected: "ReplicationGroupNotFoundFault", }, }, + Logger: c.Config.Logger, + NewRequest: func(opts []request.Option) (*request.Request, error) { + var inCpy *DescribeReplicationGroupsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeReplicationGroupsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, } + w.ApplyOptions(opts...) - w := waiter.Waiter{ - Client: c, - Input: input, - Config: waiterCfg, - } - return w.Wait() + return w.WaitWithContext(ctx) } diff --git a/vendor/github.com/aws/aws-sdk-go/service/elasticbeanstalk/api.go b/vendor/github.com/aws/aws-sdk-go/service/elasticbeanstalk/api.go index 7f4e1f137..cd2d0fb7f 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/elasticbeanstalk/api.go +++ b/vendor/github.com/aws/aws-sdk-go/service/elasticbeanstalk/api.go @@ -1,12 +1,12 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. -// Package elasticbeanstalk provides a client for AWS Elastic Beanstalk. package elasticbeanstalk import ( "fmt" "time" + "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awsutil" "github.com/aws/aws-sdk-go/aws/request" "github.com/aws/aws-sdk-go/private/protocol" @@ -78,8 +78,23 @@ func (c *ElasticBeanstalk) AbortEnvironmentUpdateRequest(input *AbortEnvironment // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticbeanstalk-2010-12-01/AbortEnvironmentUpdate func (c *ElasticBeanstalk) AbortEnvironmentUpdate(input *AbortEnvironmentUpdateInput) (*AbortEnvironmentUpdateOutput, error) { req, out := c.AbortEnvironmentUpdateRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// AbortEnvironmentUpdateWithContext is the same as AbortEnvironmentUpdate with the addition of +// the ability to pass a context and additional request options. +// +// See AbortEnvironmentUpdate 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 *ElasticBeanstalk) AbortEnvironmentUpdateWithContext(ctx aws.Context, input *AbortEnvironmentUpdateInput, opts ...request.Option) (*AbortEnvironmentUpdateOutput, error) { + req, out := c.AbortEnvironmentUpdateRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opApplyEnvironmentManagedAction = "ApplyEnvironmentManagedAction" @@ -148,8 +163,23 @@ func (c *ElasticBeanstalk) ApplyEnvironmentManagedActionRequest(input *ApplyEnvi // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticbeanstalk-2010-12-01/ApplyEnvironmentManagedAction func (c *ElasticBeanstalk) ApplyEnvironmentManagedAction(input *ApplyEnvironmentManagedActionInput) (*ApplyEnvironmentManagedActionOutput, error) { req, out := c.ApplyEnvironmentManagedActionRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ApplyEnvironmentManagedActionWithContext is the same as ApplyEnvironmentManagedAction with the addition of +// the ability to pass a context and additional request options. +// +// See ApplyEnvironmentManagedAction 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 *ElasticBeanstalk) ApplyEnvironmentManagedActionWithContext(ctx aws.Context, input *ApplyEnvironmentManagedActionInput, opts ...request.Option) (*ApplyEnvironmentManagedActionOutput, error) { + req, out := c.ApplyEnvironmentManagedActionRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCheckDNSAvailability = "CheckDNSAvailability" @@ -208,8 +238,23 @@ func (c *ElasticBeanstalk) CheckDNSAvailabilityRequest(input *CheckDNSAvailabili // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticbeanstalk-2010-12-01/CheckDNSAvailability func (c *ElasticBeanstalk) CheckDNSAvailability(input *CheckDNSAvailabilityInput) (*CheckDNSAvailabilityOutput, error) { req, out := c.CheckDNSAvailabilityRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CheckDNSAvailabilityWithContext is the same as CheckDNSAvailability with the addition of +// the ability to pass a context and additional request options. +// +// See CheckDNSAvailability 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 *ElasticBeanstalk) CheckDNSAvailabilityWithContext(ctx aws.Context, input *CheckDNSAvailabilityInput, opts ...request.Option) (*CheckDNSAvailabilityOutput, error) { + req, out := c.CheckDNSAvailabilityRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opComposeEnvironments = "ComposeEnvironments" @@ -283,8 +328,23 @@ func (c *ElasticBeanstalk) ComposeEnvironmentsRequest(input *ComposeEnvironments // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticbeanstalk-2010-12-01/ComposeEnvironments func (c *ElasticBeanstalk) ComposeEnvironments(input *ComposeEnvironmentsInput) (*EnvironmentDescriptionsMessage, error) { req, out := c.ComposeEnvironmentsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ComposeEnvironmentsWithContext is the same as ComposeEnvironments with the addition of +// the ability to pass a context and additional request options. +// +// See ComposeEnvironments 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 *ElasticBeanstalk) ComposeEnvironmentsWithContext(ctx aws.Context, input *ComposeEnvironmentsInput, opts ...request.Option) (*EnvironmentDescriptionsMessage, error) { + req, out := c.ComposeEnvironmentsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateApplication = "CreateApplication" @@ -349,8 +409,23 @@ func (c *ElasticBeanstalk) CreateApplicationRequest(input *CreateApplicationInpu // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticbeanstalk-2010-12-01/CreateApplication func (c *ElasticBeanstalk) CreateApplication(input *CreateApplicationInput) (*ApplicationDescriptionMessage, error) { req, out := c.CreateApplicationRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateApplicationWithContext is the same as CreateApplication with the addition of +// the ability to pass a context and additional request options. +// +// See CreateApplication 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 *ElasticBeanstalk) CreateApplicationWithContext(ctx aws.Context, input *CreateApplicationInput, opts ...request.Option) (*ApplicationDescriptionMessage, error) { + req, out := c.CreateApplicationRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateApplicationVersion = "CreateApplicationVersion" @@ -450,8 +525,23 @@ func (c *ElasticBeanstalk) CreateApplicationVersionRequest(input *CreateApplicat // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticbeanstalk-2010-12-01/CreateApplicationVersion func (c *ElasticBeanstalk) CreateApplicationVersion(input *CreateApplicationVersionInput) (*ApplicationVersionDescriptionMessage, error) { req, out := c.CreateApplicationVersionRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateApplicationVersionWithContext is the same as CreateApplicationVersion with the addition of +// the ability to pass a context and additional request options. +// +// See CreateApplicationVersion 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 *ElasticBeanstalk) CreateApplicationVersionWithContext(ctx aws.Context, input *CreateApplicationVersionInput, opts ...request.Option) (*ApplicationVersionDescriptionMessage, error) { + req, out := c.CreateApplicationVersionRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateConfigurationTemplate = "CreateConfigurationTemplate" @@ -532,8 +622,23 @@ func (c *ElasticBeanstalk) CreateConfigurationTemplateRequest(input *CreateConfi // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticbeanstalk-2010-12-01/CreateConfigurationTemplate func (c *ElasticBeanstalk) CreateConfigurationTemplate(input *CreateConfigurationTemplateInput) (*ConfigurationSettingsDescription, error) { req, out := c.CreateConfigurationTemplateRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateConfigurationTemplateWithContext is the same as CreateConfigurationTemplate with the addition of +// the ability to pass a context and additional request options. +// +// See CreateConfigurationTemplate 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 *ElasticBeanstalk) CreateConfigurationTemplateWithContext(ctx aws.Context, input *CreateConfigurationTemplateInput, opts ...request.Option) (*ConfigurationSettingsDescription, error) { + req, out := c.CreateConfigurationTemplateRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateEnvironment = "CreateEnvironment" @@ -602,8 +707,23 @@ func (c *ElasticBeanstalk) CreateEnvironmentRequest(input *CreateEnvironmentInpu // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticbeanstalk-2010-12-01/CreateEnvironment func (c *ElasticBeanstalk) CreateEnvironment(input *CreateEnvironmentInput) (*EnvironmentDescription, error) { req, out := c.CreateEnvironmentRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateEnvironmentWithContext is the same as CreateEnvironment with the addition of +// the ability to pass a context and additional request options. +// +// See CreateEnvironment 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 *ElasticBeanstalk) CreateEnvironmentWithContext(ctx aws.Context, input *CreateEnvironmentInput, opts ...request.Option) (*EnvironmentDescription, error) { + req, out := c.CreateEnvironmentRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreatePlatformVersion = "CreatePlatformVersion" @@ -675,8 +795,23 @@ func (c *ElasticBeanstalk) CreatePlatformVersionRequest(input *CreatePlatformVer // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticbeanstalk-2010-12-01/CreatePlatformVersion func (c *ElasticBeanstalk) CreatePlatformVersion(input *CreatePlatformVersionInput) (*CreatePlatformVersionOutput, error) { req, out := c.CreatePlatformVersionRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreatePlatformVersionWithContext is the same as CreatePlatformVersion with the addition of +// the ability to pass a context and additional request options. +// +// See CreatePlatformVersion 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 *ElasticBeanstalk) CreatePlatformVersionWithContext(ctx aws.Context, input *CreatePlatformVersionInput, opts ...request.Option) (*CreatePlatformVersionOutput, error) { + req, out := c.CreatePlatformVersionRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateStorageLocation = "CreateStorageLocation" @@ -749,8 +884,23 @@ func (c *ElasticBeanstalk) CreateStorageLocationRequest(input *CreateStorageLoca // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticbeanstalk-2010-12-01/CreateStorageLocation func (c *ElasticBeanstalk) CreateStorageLocation(input *CreateStorageLocationInput) (*CreateStorageLocationOutput, error) { req, out := c.CreateStorageLocationRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateStorageLocationWithContext is the same as CreateStorageLocation with the addition of +// the ability to pass a context and additional request options. +// +// See CreateStorageLocation 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 *ElasticBeanstalk) CreateStorageLocationWithContext(ctx aws.Context, input *CreateStorageLocationInput, opts ...request.Option) (*CreateStorageLocationOutput, error) { + req, out := c.CreateStorageLocationRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteApplication = "DeleteApplication" @@ -821,8 +971,23 @@ func (c *ElasticBeanstalk) DeleteApplicationRequest(input *DeleteApplicationInpu // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticbeanstalk-2010-12-01/DeleteApplication func (c *ElasticBeanstalk) DeleteApplication(input *DeleteApplicationInput) (*DeleteApplicationOutput, error) { req, out := c.DeleteApplicationRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteApplicationWithContext is the same as DeleteApplication with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteApplication 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 *ElasticBeanstalk) DeleteApplicationWithContext(ctx aws.Context, input *DeleteApplicationInput, opts ...request.Option) (*DeleteApplicationOutput, error) { + req, out := c.DeleteApplicationRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteApplicationVersion = "DeleteApplicationVersion" @@ -910,8 +1075,23 @@ func (c *ElasticBeanstalk) DeleteApplicationVersionRequest(input *DeleteApplicat // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticbeanstalk-2010-12-01/DeleteApplicationVersion func (c *ElasticBeanstalk) DeleteApplicationVersion(input *DeleteApplicationVersionInput) (*DeleteApplicationVersionOutput, error) { req, out := c.DeleteApplicationVersionRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteApplicationVersionWithContext is the same as DeleteApplicationVersion with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteApplicationVersion 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 *ElasticBeanstalk) DeleteApplicationVersionWithContext(ctx aws.Context, input *DeleteApplicationVersionInput, opts ...request.Option) (*DeleteApplicationVersionOutput, error) { + req, out := c.DeleteApplicationVersionRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteConfigurationTemplate = "DeleteConfigurationTemplate" @@ -982,8 +1162,23 @@ func (c *ElasticBeanstalk) DeleteConfigurationTemplateRequest(input *DeleteConfi // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticbeanstalk-2010-12-01/DeleteConfigurationTemplate func (c *ElasticBeanstalk) DeleteConfigurationTemplate(input *DeleteConfigurationTemplateInput) (*DeleteConfigurationTemplateOutput, error) { req, out := c.DeleteConfigurationTemplateRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteConfigurationTemplateWithContext is the same as DeleteConfigurationTemplate with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteConfigurationTemplate 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 *ElasticBeanstalk) DeleteConfigurationTemplateWithContext(ctx aws.Context, input *DeleteConfigurationTemplateInput, opts ...request.Option) (*DeleteConfigurationTemplateOutput, error) { + req, out := c.DeleteConfigurationTemplateRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteEnvironmentConfiguration = "DeleteEnvironmentConfiguration" @@ -1051,8 +1246,23 @@ func (c *ElasticBeanstalk) DeleteEnvironmentConfigurationRequest(input *DeleteEn // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticbeanstalk-2010-12-01/DeleteEnvironmentConfiguration func (c *ElasticBeanstalk) DeleteEnvironmentConfiguration(input *DeleteEnvironmentConfigurationInput) (*DeleteEnvironmentConfigurationOutput, error) { req, out := c.DeleteEnvironmentConfigurationRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteEnvironmentConfigurationWithContext is the same as DeleteEnvironmentConfiguration with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteEnvironmentConfiguration 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 *ElasticBeanstalk) DeleteEnvironmentConfigurationWithContext(ctx aws.Context, input *DeleteEnvironmentConfigurationInput, opts ...request.Option) (*DeleteEnvironmentConfigurationOutput, error) { + req, out := c.DeleteEnvironmentConfigurationRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeletePlatformVersion = "DeletePlatformVersion" @@ -1128,8 +1338,23 @@ func (c *ElasticBeanstalk) DeletePlatformVersionRequest(input *DeletePlatformVer // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticbeanstalk-2010-12-01/DeletePlatformVersion func (c *ElasticBeanstalk) DeletePlatformVersion(input *DeletePlatformVersionInput) (*DeletePlatformVersionOutput, error) { req, out := c.DeletePlatformVersionRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeletePlatformVersionWithContext is the same as DeletePlatformVersion with the addition of +// the ability to pass a context and additional request options. +// +// See DeletePlatformVersion 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 *ElasticBeanstalk) DeletePlatformVersionWithContext(ctx aws.Context, input *DeletePlatformVersionInput, opts ...request.Option) (*DeletePlatformVersionOutput, error) { + req, out := c.DeletePlatformVersionRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeApplicationVersions = "DescribeApplicationVersions" @@ -1188,8 +1413,23 @@ func (c *ElasticBeanstalk) DescribeApplicationVersionsRequest(input *DescribeApp // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticbeanstalk-2010-12-01/DescribeApplicationVersions func (c *ElasticBeanstalk) DescribeApplicationVersions(input *DescribeApplicationVersionsInput) (*DescribeApplicationVersionsOutput, error) { req, out := c.DescribeApplicationVersionsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeApplicationVersionsWithContext is the same as DescribeApplicationVersions with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeApplicationVersions 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 *ElasticBeanstalk) DescribeApplicationVersionsWithContext(ctx aws.Context, input *DescribeApplicationVersionsInput, opts ...request.Option) (*DescribeApplicationVersionsOutput, error) { + req, out := c.DescribeApplicationVersionsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeApplications = "DescribeApplications" @@ -1248,8 +1488,23 @@ func (c *ElasticBeanstalk) DescribeApplicationsRequest(input *DescribeApplicatio // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticbeanstalk-2010-12-01/DescribeApplications func (c *ElasticBeanstalk) DescribeApplications(input *DescribeApplicationsInput) (*DescribeApplicationsOutput, error) { req, out := c.DescribeApplicationsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeApplicationsWithContext is the same as DescribeApplications with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeApplications 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 *ElasticBeanstalk) DescribeApplicationsWithContext(ctx aws.Context, input *DescribeApplicationsInput, opts ...request.Option) (*DescribeApplicationsOutput, error) { + req, out := c.DescribeApplicationsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeConfigurationOptions = "DescribeConfigurationOptions" @@ -1317,8 +1572,23 @@ func (c *ElasticBeanstalk) DescribeConfigurationOptionsRequest(input *DescribeCo // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticbeanstalk-2010-12-01/DescribeConfigurationOptions func (c *ElasticBeanstalk) DescribeConfigurationOptions(input *DescribeConfigurationOptionsInput) (*DescribeConfigurationOptionsOutput, error) { req, out := c.DescribeConfigurationOptionsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeConfigurationOptionsWithContext is the same as DescribeConfigurationOptions with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeConfigurationOptions 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 *ElasticBeanstalk) DescribeConfigurationOptionsWithContext(ctx aws.Context, input *DescribeConfigurationOptionsInput, opts ...request.Option) (*DescribeConfigurationOptionsOutput, error) { + req, out := c.DescribeConfigurationOptionsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeConfigurationSettings = "DescribeConfigurationSettings" @@ -1394,8 +1664,23 @@ func (c *ElasticBeanstalk) DescribeConfigurationSettingsRequest(input *DescribeC // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticbeanstalk-2010-12-01/DescribeConfigurationSettings func (c *ElasticBeanstalk) DescribeConfigurationSettings(input *DescribeConfigurationSettingsInput) (*DescribeConfigurationSettingsOutput, error) { req, out := c.DescribeConfigurationSettingsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeConfigurationSettingsWithContext is the same as DescribeConfigurationSettings with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeConfigurationSettings 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 *ElasticBeanstalk) DescribeConfigurationSettingsWithContext(ctx aws.Context, input *DescribeConfigurationSettingsInput, opts ...request.Option) (*DescribeConfigurationSettingsOutput, error) { + req, out := c.DescribeConfigurationSettingsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeEnvironmentHealth = "DescribeEnvironmentHealth" @@ -1465,8 +1750,23 @@ func (c *ElasticBeanstalk) DescribeEnvironmentHealthRequest(input *DescribeEnvir // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticbeanstalk-2010-12-01/DescribeEnvironmentHealth func (c *ElasticBeanstalk) DescribeEnvironmentHealth(input *DescribeEnvironmentHealthInput) (*DescribeEnvironmentHealthOutput, error) { req, out := c.DescribeEnvironmentHealthRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeEnvironmentHealthWithContext is the same as DescribeEnvironmentHealth with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeEnvironmentHealth 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 *ElasticBeanstalk) DescribeEnvironmentHealthWithContext(ctx aws.Context, input *DescribeEnvironmentHealthInput, opts ...request.Option) (*DescribeEnvironmentHealthOutput, error) { + req, out := c.DescribeEnvironmentHealthRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeEnvironmentManagedActionHistory = "DescribeEnvironmentManagedActionHistory" @@ -1530,8 +1830,23 @@ func (c *ElasticBeanstalk) DescribeEnvironmentManagedActionHistoryRequest(input // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticbeanstalk-2010-12-01/DescribeEnvironmentManagedActionHistory func (c *ElasticBeanstalk) DescribeEnvironmentManagedActionHistory(input *DescribeEnvironmentManagedActionHistoryInput) (*DescribeEnvironmentManagedActionHistoryOutput, error) { req, out := c.DescribeEnvironmentManagedActionHistoryRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeEnvironmentManagedActionHistoryWithContext is the same as DescribeEnvironmentManagedActionHistory with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeEnvironmentManagedActionHistory 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 *ElasticBeanstalk) DescribeEnvironmentManagedActionHistoryWithContext(ctx aws.Context, input *DescribeEnvironmentManagedActionHistoryInput, opts ...request.Option) (*DescribeEnvironmentManagedActionHistoryOutput, error) { + req, out := c.DescribeEnvironmentManagedActionHistoryRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeEnvironmentManagedActions = "DescribeEnvironmentManagedActions" @@ -1595,8 +1910,23 @@ func (c *ElasticBeanstalk) DescribeEnvironmentManagedActionsRequest(input *Descr // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticbeanstalk-2010-12-01/DescribeEnvironmentManagedActions func (c *ElasticBeanstalk) DescribeEnvironmentManagedActions(input *DescribeEnvironmentManagedActionsInput) (*DescribeEnvironmentManagedActionsOutput, error) { req, out := c.DescribeEnvironmentManagedActionsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeEnvironmentManagedActionsWithContext is the same as DescribeEnvironmentManagedActions with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeEnvironmentManagedActions 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 *ElasticBeanstalk) DescribeEnvironmentManagedActionsWithContext(ctx aws.Context, input *DescribeEnvironmentManagedActionsInput, opts ...request.Option) (*DescribeEnvironmentManagedActionsOutput, error) { + req, out := c.DescribeEnvironmentManagedActionsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeEnvironmentResources = "DescribeEnvironmentResources" @@ -1661,8 +1991,23 @@ func (c *ElasticBeanstalk) DescribeEnvironmentResourcesRequest(input *DescribeEn // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticbeanstalk-2010-12-01/DescribeEnvironmentResources func (c *ElasticBeanstalk) DescribeEnvironmentResources(input *DescribeEnvironmentResourcesInput) (*DescribeEnvironmentResourcesOutput, error) { req, out := c.DescribeEnvironmentResourcesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeEnvironmentResourcesWithContext is the same as DescribeEnvironmentResources with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeEnvironmentResources 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 *ElasticBeanstalk) DescribeEnvironmentResourcesWithContext(ctx aws.Context, input *DescribeEnvironmentResourcesInput, opts ...request.Option) (*DescribeEnvironmentResourcesOutput, error) { + req, out := c.DescribeEnvironmentResourcesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeEnvironments = "DescribeEnvironments" @@ -1721,8 +2066,23 @@ func (c *ElasticBeanstalk) DescribeEnvironmentsRequest(input *DescribeEnvironmen // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticbeanstalk-2010-12-01/DescribeEnvironments func (c *ElasticBeanstalk) DescribeEnvironments(input *DescribeEnvironmentsInput) (*EnvironmentDescriptionsMessage, error) { req, out := c.DescribeEnvironmentsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeEnvironmentsWithContext is the same as DescribeEnvironments with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeEnvironments 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 *ElasticBeanstalk) DescribeEnvironmentsWithContext(ctx aws.Context, input *DescribeEnvironmentsInput, opts ...request.Option) (*EnvironmentDescriptionsMessage, error) { + req, out := c.DescribeEnvironmentsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeEvents = "DescribeEvents" @@ -1789,8 +2149,23 @@ func (c *ElasticBeanstalk) DescribeEventsRequest(input *DescribeEventsInput) (re // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticbeanstalk-2010-12-01/DescribeEvents func (c *ElasticBeanstalk) DescribeEvents(input *DescribeEventsInput) (*DescribeEventsOutput, error) { req, out := c.DescribeEventsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeEventsWithContext is the same as DescribeEvents with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeEvents 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 *ElasticBeanstalk) DescribeEventsWithContext(ctx aws.Context, input *DescribeEventsInput, opts ...request.Option) (*DescribeEventsOutput, error) { + req, out := c.DescribeEventsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // DescribeEventsPages iterates over the pages of a DescribeEvents operation, @@ -1810,12 +2185,37 @@ func (c *ElasticBeanstalk) DescribeEvents(input *DescribeEventsInput) (*Describe // return pageNum <= 3 // }) // -func (c *ElasticBeanstalk) DescribeEventsPages(input *DescribeEventsInput, fn func(p *DescribeEventsOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.DescribeEventsRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*DescribeEventsOutput), lastPage) - }) +func (c *ElasticBeanstalk) DescribeEventsPages(input *DescribeEventsInput, fn func(*DescribeEventsOutput, bool) bool) error { + return c.DescribeEventsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// DescribeEventsPagesWithContext same as DescribeEventsPages 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 *ElasticBeanstalk) DescribeEventsPagesWithContext(ctx aws.Context, input *DescribeEventsInput, fn func(*DescribeEventsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *DescribeEventsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeEventsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*DescribeEventsOutput), !p.HasNextPage()) + } + return p.Err() } const opDescribeInstancesHealth = "DescribeInstancesHealth" @@ -1884,8 +2284,23 @@ func (c *ElasticBeanstalk) DescribeInstancesHealthRequest(input *DescribeInstanc // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticbeanstalk-2010-12-01/DescribeInstancesHealth func (c *ElasticBeanstalk) DescribeInstancesHealth(input *DescribeInstancesHealthInput) (*DescribeInstancesHealthOutput, error) { req, out := c.DescribeInstancesHealthRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeInstancesHealthWithContext is the same as DescribeInstancesHealth with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeInstancesHealth 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 *ElasticBeanstalk) DescribeInstancesHealthWithContext(ctx aws.Context, input *DescribeInstancesHealthInput, opts ...request.Option) (*DescribeInstancesHealthOutput, error) { + req, out := c.DescribeInstancesHealthRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribePlatformVersion = "DescribePlatformVersion" @@ -1953,8 +2368,23 @@ func (c *ElasticBeanstalk) DescribePlatformVersionRequest(input *DescribePlatfor // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticbeanstalk-2010-12-01/DescribePlatformVersion func (c *ElasticBeanstalk) DescribePlatformVersion(input *DescribePlatformVersionInput) (*DescribePlatformVersionOutput, error) { req, out := c.DescribePlatformVersionRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribePlatformVersionWithContext is the same as DescribePlatformVersion with the addition of +// the ability to pass a context and additional request options. +// +// See DescribePlatformVersion 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 *ElasticBeanstalk) DescribePlatformVersionWithContext(ctx aws.Context, input *DescribePlatformVersionInput, opts ...request.Option) (*DescribePlatformVersionOutput, error) { + req, out := c.DescribePlatformVersionRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opListAvailableSolutionStacks = "ListAvailableSolutionStacks" @@ -2014,8 +2444,23 @@ func (c *ElasticBeanstalk) ListAvailableSolutionStacksRequest(input *ListAvailab // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticbeanstalk-2010-12-01/ListAvailableSolutionStacks func (c *ElasticBeanstalk) ListAvailableSolutionStacks(input *ListAvailableSolutionStacksInput) (*ListAvailableSolutionStacksOutput, error) { req, out := c.ListAvailableSolutionStacksRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListAvailableSolutionStacksWithContext is the same as ListAvailableSolutionStacks with the addition of +// the ability to pass a context and additional request options. +// +// See ListAvailableSolutionStacks 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 *ElasticBeanstalk) ListAvailableSolutionStacksWithContext(ctx aws.Context, input *ListAvailableSolutionStacksInput, opts ...request.Option) (*ListAvailableSolutionStacksOutput, error) { + req, out := c.ListAvailableSolutionStacksRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opListPlatformVersions = "ListPlatformVersions" @@ -2083,8 +2528,23 @@ func (c *ElasticBeanstalk) ListPlatformVersionsRequest(input *ListPlatformVersio // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticbeanstalk-2010-12-01/ListPlatformVersions func (c *ElasticBeanstalk) ListPlatformVersions(input *ListPlatformVersionsInput) (*ListPlatformVersionsOutput, error) { req, out := c.ListPlatformVersionsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListPlatformVersionsWithContext is the same as ListPlatformVersions with the addition of +// the ability to pass a context and additional request options. +// +// See ListPlatformVersions 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 *ElasticBeanstalk) ListPlatformVersionsWithContext(ctx aws.Context, input *ListPlatformVersionsInput, opts ...request.Option) (*ListPlatformVersionsOutput, error) { + req, out := c.ListPlatformVersionsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opRebuildEnvironment = "RebuildEnvironment" @@ -2152,8 +2612,23 @@ func (c *ElasticBeanstalk) RebuildEnvironmentRequest(input *RebuildEnvironmentIn // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticbeanstalk-2010-12-01/RebuildEnvironment func (c *ElasticBeanstalk) RebuildEnvironment(input *RebuildEnvironmentInput) (*RebuildEnvironmentOutput, error) { req, out := c.RebuildEnvironmentRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// RebuildEnvironmentWithContext is the same as RebuildEnvironment with the addition of +// the ability to pass a context and additional request options. +// +// See RebuildEnvironment 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 *ElasticBeanstalk) RebuildEnvironmentWithContext(ctx aws.Context, input *RebuildEnvironmentInput, opts ...request.Option) (*RebuildEnvironmentOutput, error) { + req, out := c.RebuildEnvironmentRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opRequestEnvironmentInfo = "RequestEnvironmentInfo" @@ -2228,8 +2703,23 @@ func (c *ElasticBeanstalk) RequestEnvironmentInfoRequest(input *RequestEnvironme // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticbeanstalk-2010-12-01/RequestEnvironmentInfo func (c *ElasticBeanstalk) RequestEnvironmentInfo(input *RequestEnvironmentInfoInput) (*RequestEnvironmentInfoOutput, error) { req, out := c.RequestEnvironmentInfoRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// RequestEnvironmentInfoWithContext is the same as RequestEnvironmentInfo with the addition of +// the ability to pass a context and additional request options. +// +// See RequestEnvironmentInfo 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 *ElasticBeanstalk) RequestEnvironmentInfoWithContext(ctx aws.Context, input *RequestEnvironmentInfoInput, opts ...request.Option) (*RequestEnvironmentInfoOutput, error) { + req, out := c.RequestEnvironmentInfoRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opRestartAppServer = "RestartAppServer" @@ -2291,8 +2781,23 @@ func (c *ElasticBeanstalk) RestartAppServerRequest(input *RestartAppServerInput) // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticbeanstalk-2010-12-01/RestartAppServer func (c *ElasticBeanstalk) RestartAppServer(input *RestartAppServerInput) (*RestartAppServerOutput, error) { req, out := c.RestartAppServerRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// RestartAppServerWithContext is the same as RestartAppServer with the addition of +// the ability to pass a context and additional request options. +// +// See RestartAppServer 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 *ElasticBeanstalk) RestartAppServerWithContext(ctx aws.Context, input *RestartAppServerInput, opts ...request.Option) (*RestartAppServerOutput, error) { + req, out := c.RestartAppServerRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opRetrieveEnvironmentInfo = "RetrieveEnvironmentInfo" @@ -2355,8 +2860,23 @@ func (c *ElasticBeanstalk) RetrieveEnvironmentInfoRequest(input *RetrieveEnviron // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticbeanstalk-2010-12-01/RetrieveEnvironmentInfo func (c *ElasticBeanstalk) RetrieveEnvironmentInfo(input *RetrieveEnvironmentInfoInput) (*RetrieveEnvironmentInfoOutput, error) { req, out := c.RetrieveEnvironmentInfoRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// RetrieveEnvironmentInfoWithContext is the same as RetrieveEnvironmentInfo with the addition of +// the ability to pass a context and additional request options. +// +// See RetrieveEnvironmentInfo 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 *ElasticBeanstalk) RetrieveEnvironmentInfoWithContext(ctx aws.Context, input *RetrieveEnvironmentInfoInput, opts ...request.Option) (*RetrieveEnvironmentInfoOutput, error) { + req, out := c.RetrieveEnvironmentInfoRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opSwapEnvironmentCNAMEs = "SwapEnvironmentCNAMEs" @@ -2417,8 +2937,23 @@ func (c *ElasticBeanstalk) SwapEnvironmentCNAMEsRequest(input *SwapEnvironmentCN // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticbeanstalk-2010-12-01/SwapEnvironmentCNAMEs func (c *ElasticBeanstalk) SwapEnvironmentCNAMEs(input *SwapEnvironmentCNAMEsInput) (*SwapEnvironmentCNAMEsOutput, error) { req, out := c.SwapEnvironmentCNAMEsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// SwapEnvironmentCNAMEsWithContext is the same as SwapEnvironmentCNAMEs with the addition of +// the ability to pass a context and additional request options. +// +// See SwapEnvironmentCNAMEs 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 *ElasticBeanstalk) SwapEnvironmentCNAMEsWithContext(ctx aws.Context, input *SwapEnvironmentCNAMEsInput, opts ...request.Option) (*SwapEnvironmentCNAMEsOutput, error) { + req, out := c.SwapEnvironmentCNAMEsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opTerminateEnvironment = "TerminateEnvironment" @@ -2483,8 +3018,23 @@ func (c *ElasticBeanstalk) TerminateEnvironmentRequest(input *TerminateEnvironme // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticbeanstalk-2010-12-01/TerminateEnvironment func (c *ElasticBeanstalk) TerminateEnvironment(input *TerminateEnvironmentInput) (*EnvironmentDescription, error) { req, out := c.TerminateEnvironmentRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// TerminateEnvironmentWithContext is the same as TerminateEnvironment with the addition of +// the ability to pass a context and additional request options. +// +// See TerminateEnvironment 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 *ElasticBeanstalk) TerminateEnvironmentWithContext(ctx aws.Context, input *TerminateEnvironmentInput, opts ...request.Option) (*EnvironmentDescription, error) { + req, out := c.TerminateEnvironmentRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opUpdateApplication = "UpdateApplication" @@ -2546,8 +3096,23 @@ func (c *ElasticBeanstalk) UpdateApplicationRequest(input *UpdateApplicationInpu // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticbeanstalk-2010-12-01/UpdateApplication func (c *ElasticBeanstalk) UpdateApplication(input *UpdateApplicationInput) (*ApplicationDescriptionMessage, error) { req, out := c.UpdateApplicationRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// UpdateApplicationWithContext is the same as UpdateApplication with the addition of +// the ability to pass a context and additional request options. +// +// See UpdateApplication 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 *ElasticBeanstalk) UpdateApplicationWithContext(ctx aws.Context, input *UpdateApplicationInput, opts ...request.Option) (*ApplicationDescriptionMessage, error) { + req, out := c.UpdateApplicationRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opUpdateApplicationResourceLifecycle = "UpdateApplicationResourceLifecycle" @@ -2612,8 +3177,23 @@ func (c *ElasticBeanstalk) UpdateApplicationResourceLifecycleRequest(input *Upda // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticbeanstalk-2010-12-01/UpdateApplicationResourceLifecycle func (c *ElasticBeanstalk) UpdateApplicationResourceLifecycle(input *UpdateApplicationResourceLifecycleInput) (*UpdateApplicationResourceLifecycleOutput, error) { req, out := c.UpdateApplicationResourceLifecycleRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// UpdateApplicationResourceLifecycleWithContext is the same as UpdateApplicationResourceLifecycle with the addition of +// the ability to pass a context and additional request options. +// +// See UpdateApplicationResourceLifecycle 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 *ElasticBeanstalk) UpdateApplicationResourceLifecycleWithContext(ctx aws.Context, input *UpdateApplicationResourceLifecycleInput, opts ...request.Option) (*UpdateApplicationResourceLifecycleOutput, error) { + req, out := c.UpdateApplicationResourceLifecycleRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opUpdateApplicationVersion = "UpdateApplicationVersion" @@ -2675,8 +3255,23 @@ func (c *ElasticBeanstalk) UpdateApplicationVersionRequest(input *UpdateApplicat // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticbeanstalk-2010-12-01/UpdateApplicationVersion func (c *ElasticBeanstalk) UpdateApplicationVersion(input *UpdateApplicationVersionInput) (*ApplicationVersionDescriptionMessage, error) { req, out := c.UpdateApplicationVersionRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// UpdateApplicationVersionWithContext is the same as UpdateApplicationVersion with the addition of +// the ability to pass a context and additional request options. +// +// See UpdateApplicationVersion 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 *ElasticBeanstalk) UpdateApplicationVersionWithContext(ctx aws.Context, input *UpdateApplicationVersionInput, opts ...request.Option) (*ApplicationVersionDescriptionMessage, error) { + req, out := c.UpdateApplicationVersionRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opUpdateConfigurationTemplate = "UpdateConfigurationTemplate" @@ -2752,8 +3347,23 @@ func (c *ElasticBeanstalk) UpdateConfigurationTemplateRequest(input *UpdateConfi // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticbeanstalk-2010-12-01/UpdateConfigurationTemplate func (c *ElasticBeanstalk) UpdateConfigurationTemplate(input *UpdateConfigurationTemplateInput) (*ConfigurationSettingsDescription, error) { req, out := c.UpdateConfigurationTemplateRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// UpdateConfigurationTemplateWithContext is the same as UpdateConfigurationTemplate with the addition of +// the ability to pass a context and additional request options. +// +// See UpdateConfigurationTemplate 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 *ElasticBeanstalk) UpdateConfigurationTemplateWithContext(ctx aws.Context, input *UpdateConfigurationTemplateInput, opts ...request.Option) (*ConfigurationSettingsDescription, error) { + req, out := c.UpdateConfigurationTemplateRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opUpdateEnvironment = "UpdateEnvironment" @@ -2831,8 +3441,23 @@ func (c *ElasticBeanstalk) UpdateEnvironmentRequest(input *UpdateEnvironmentInpu // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticbeanstalk-2010-12-01/UpdateEnvironment func (c *ElasticBeanstalk) UpdateEnvironment(input *UpdateEnvironmentInput) (*EnvironmentDescription, error) { req, out := c.UpdateEnvironmentRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// UpdateEnvironmentWithContext is the same as UpdateEnvironment with the addition of +// the ability to pass a context and additional request options. +// +// See UpdateEnvironment 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 *ElasticBeanstalk) UpdateEnvironmentWithContext(ctx aws.Context, input *UpdateEnvironmentInput, opts ...request.Option) (*EnvironmentDescription, error) { + req, out := c.UpdateEnvironmentRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opValidateConfigurationSettings = "ValidateConfigurationSettings" @@ -2904,8 +3529,23 @@ func (c *ElasticBeanstalk) ValidateConfigurationSettingsRequest(input *ValidateC // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticbeanstalk-2010-12-01/ValidateConfigurationSettings func (c *ElasticBeanstalk) ValidateConfigurationSettings(input *ValidateConfigurationSettingsInput) (*ValidateConfigurationSettingsOutput, error) { req, out := c.ValidateConfigurationSettingsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ValidateConfigurationSettingsWithContext is the same as ValidateConfigurationSettings with the addition of +// the ability to pass a context and additional request options. +// +// See ValidateConfigurationSettings 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 *ElasticBeanstalk) ValidateConfigurationSettingsWithContext(ctx aws.Context, input *ValidateConfigurationSettingsInput, opts ...request.Option) (*ValidateConfigurationSettingsOutput, error) { + req, out := c.ValidateConfigurationSettingsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticbeanstalk-2010-12-01/AbortEnvironmentUpdateMessage diff --git a/vendor/github.com/aws/aws-sdk-go/service/elasticbeanstalk/doc.go b/vendor/github.com/aws/aws-sdk-go/service/elasticbeanstalk/doc.go new file mode 100644 index 000000000..257afe092 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/service/elasticbeanstalk/doc.go @@ -0,0 +1,96 @@ +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. + +// Package elasticbeanstalk provides the client and types for making API +// requests to AWS Elastic Beanstalk. +// +// AWS Elastic Beanstalk makes it easy for you to create, deploy, and manage +// scalable, fault-tolerant applications running on the Amazon Web Services +// cloud. +// +// For more information about this product, go to the AWS Elastic Beanstalk +// (http://aws.amazon.com/elasticbeanstalk/) details page. The location of the +// latest AWS Elastic Beanstalk WSDL is http://elasticbeanstalk.s3.amazonaws.com/doc/2010-12-01/AWSElasticBeanstalk.wsdl +// (http://elasticbeanstalk.s3.amazonaws.com/doc/2010-12-01/AWSElasticBeanstalk.wsdl). +// To install the Software Development Kits (SDKs), Integrated Development Environment +// (IDE) Toolkits, and command line tools that enable you to access the API, +// go to Tools for Amazon Web Services (http://aws.amazon.com/tools/). +// +// Endpoints +// +// For a list of region-specific endpoints that AWS Elastic Beanstalk supports, +// go to Regions and Endpoints (http://docs.aws.amazon.com/general/latest/gr/rande.html#elasticbeanstalk_region) +// in the Amazon Web Services Glossary. +// +// See https://docs.aws.amazon.com/goto/WebAPI/elasticbeanstalk-2010-12-01 for more information on this service. +// +// See elasticbeanstalk package documentation for more information. +// https://docs.aws.amazon.com/sdk-for-go/api/service/elasticbeanstalk/ +// +// Using the Client +// +// To use the client for AWS Elastic Beanstalk you will first need +// to create a new instance of it. +// +// When creating a client for an AWS service you'll first need to have a Session +// already created. The Session provides configuration that can be shared +// between multiple service clients. Additional configuration can be applied to +// the Session and service's client when they are constructed. The aws package's +// Config type contains several fields such as Region for the AWS Region the +// client should make API requests too. The optional Config value can be provided +// as the variadic argument for Sessions and client creation. +// +// Once the service's client is created you can use it to make API requests the +// AWS service. These clients are safe to use concurrently. +// +// // Create a session to share configuration, and load external configuration. +// sess := session.Must(session.NewSession()) +// +// // Create the service's client with the session. +// svc := elasticbeanstalk.New(sess) +// +// See the SDK's documentation for more information on how to use service clients. +// https://docs.aws.amazon.com/sdk-for-go/api/ +// +// See aws package's Config type for more information on configuration options. +// https://docs.aws.amazon.com/sdk-for-go/api/aws/#Config +// +// See the AWS Elastic Beanstalk client ElasticBeanstalk for more +// information on creating the service's client. +// https://docs.aws.amazon.com/sdk-for-go/api/service/elasticbeanstalk/#New +// +// Once the client is created you can make an API request to the service. +// Each API method takes a input parameter, and returns the service response +// and an error. +// +// The API method will document which error codes the service can be returned +// by the operation if the service models the API operation's errors. These +// errors will also be available as const strings prefixed with "ErrCode". +// +// result, err := svc.AbortEnvironmentUpdate(params) +// if err != nil { +// // Cast err to awserr.Error to handle specific error codes. +// aerr, ok := err.(awserr.Error) +// if ok && aerr.Code() == { +// // Specific error code handling +// } +// return err +// } +// +// fmt.Println("AbortEnvironmentUpdate result:") +// fmt.Println(result) +// +// Using the Client with Context +// +// The service's client also provides methods to make API requests with a Context +// value. This allows you to control the timeout, and cancellation of pending +// requests. These methods also take request Option as variadic parameter to apply +// additional configuration to the API request. +// +// ctx := context.Background() +// +// result, err := svc.AbortEnvironmentUpdateWithContext(ctx, params) +// +// See the request package documentation for more information on using Context pattern +// with the SDK. +// https://docs.aws.amazon.com/sdk-for-go/api/aws/request/ +package elasticbeanstalk diff --git a/vendor/github.com/aws/aws-sdk-go/service/elasticbeanstalk/errors.go b/vendor/github.com/aws/aws-sdk-go/service/elasticbeanstalk/errors.go index f185a055c..0ed1bd633 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/elasticbeanstalk/errors.go +++ b/vendor/github.com/aws/aws-sdk-go/service/elasticbeanstalk/errors.go @@ -1,4 +1,4 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. package elasticbeanstalk diff --git a/vendor/github.com/aws/aws-sdk-go/service/elasticbeanstalk/service.go b/vendor/github.com/aws/aws-sdk-go/service/elasticbeanstalk/service.go index 2134341fb..e56509610 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/elasticbeanstalk/service.go +++ b/vendor/github.com/aws/aws-sdk-go/service/elasticbeanstalk/service.go @@ -1,4 +1,4 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. package elasticbeanstalk @@ -11,26 +11,12 @@ import ( "github.com/aws/aws-sdk-go/private/protocol/query" ) -// AWS Elastic Beanstalk makes it easy for you to create, deploy, and manage -// scalable, fault-tolerant applications running on the Amazon Web Services -// cloud. +// ElasticBeanstalk provides the API operation methods for making requests to +// AWS Elastic Beanstalk. See this package's package overview docs +// for details on the service. // -// For more information about this product, go to the AWS Elastic Beanstalk -// (http://aws.amazon.com/elasticbeanstalk/) details page. The location of the -// latest AWS Elastic Beanstalk WSDL is http://elasticbeanstalk.s3.amazonaws.com/doc/2010-12-01/AWSElasticBeanstalk.wsdl -// (http://elasticbeanstalk.s3.amazonaws.com/doc/2010-12-01/AWSElasticBeanstalk.wsdl). -// To install the Software Development Kits (SDKs), Integrated Development Environment -// (IDE) Toolkits, and command line tools that enable you to access the API, -// go to Tools for Amazon Web Services (http://aws.amazon.com/tools/). -// -// Endpoints -// -// For a list of region-specific endpoints that AWS Elastic Beanstalk supports, -// go to Regions and Endpoints (http://docs.aws.amazon.com/general/latest/gr/rande.html#elasticbeanstalk_region) -// in the Amazon Web Services Glossary. -// The service client's operations are safe to be used concurrently. -// It is not safe to mutate any of the client's properties though. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticbeanstalk-2010-12-01 +// ElasticBeanstalk methods are safe to use concurrently. It is not safe to +// modify mutate any of the struct's properties though. type ElasticBeanstalk struct { *client.Client } diff --git a/vendor/github.com/aws/aws-sdk-go/service/elasticsearchservice/api.go b/vendor/github.com/aws/aws-sdk-go/service/elasticsearchservice/api.go index 64f26f650..4a07953d2 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/elasticsearchservice/api.go +++ b/vendor/github.com/aws/aws-sdk-go/service/elasticsearchservice/api.go @@ -1,12 +1,12 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. -// Package elasticsearchservice provides a client for Amazon Elasticsearch Service. package elasticsearchservice import ( "fmt" "time" + "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awsutil" "github.com/aws/aws-sdk-go/aws/request" "github.com/aws/aws-sdk-go/private/protocol" @@ -91,8 +91,23 @@ func (c *ElasticsearchService) AddTagsRequest(input *AddTagsInput) (req *request // Please also see https://docs.aws.amazon.com/goto/WebAPI/es-2015-01-01/AddTags func (c *ElasticsearchService) AddTags(input *AddTagsInput) (*AddTagsOutput, error) { req, out := c.AddTagsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// AddTagsWithContext is the same as AddTags with the addition of +// the ability to pass a context and additional request options. +// +// See AddTags 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 *ElasticsearchService) AddTagsWithContext(ctx aws.Context, input *AddTagsInput, opts ...request.Option) (*AddTagsOutput, error) { + req, out := c.AddTagsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateElasticsearchDomain = "CreateElasticsearchDomain" @@ -183,8 +198,23 @@ func (c *ElasticsearchService) CreateElasticsearchDomainRequest(input *CreateEla // Please also see https://docs.aws.amazon.com/goto/WebAPI/es-2015-01-01/CreateElasticsearchDomain func (c *ElasticsearchService) CreateElasticsearchDomain(input *CreateElasticsearchDomainInput) (*CreateElasticsearchDomainOutput, error) { req, out := c.CreateElasticsearchDomainRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateElasticsearchDomainWithContext is the same as CreateElasticsearchDomain with the addition of +// the ability to pass a context and additional request options. +// +// See CreateElasticsearchDomain 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 *ElasticsearchService) CreateElasticsearchDomainWithContext(ctx aws.Context, input *CreateElasticsearchDomainInput, opts ...request.Option) (*CreateElasticsearchDomainOutput, error) { + req, out := c.CreateElasticsearchDomainRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteElasticsearchDomain = "DeleteElasticsearchDomain" @@ -262,8 +292,23 @@ func (c *ElasticsearchService) DeleteElasticsearchDomainRequest(input *DeleteEla // Please also see https://docs.aws.amazon.com/goto/WebAPI/es-2015-01-01/DeleteElasticsearchDomain func (c *ElasticsearchService) DeleteElasticsearchDomain(input *DeleteElasticsearchDomainInput) (*DeleteElasticsearchDomainOutput, error) { req, out := c.DeleteElasticsearchDomainRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteElasticsearchDomainWithContext is the same as DeleteElasticsearchDomain with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteElasticsearchDomain 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 *ElasticsearchService) DeleteElasticsearchDomainWithContext(ctx aws.Context, input *DeleteElasticsearchDomainInput, opts ...request.Option) (*DeleteElasticsearchDomainOutput, error) { + req, out := c.DeleteElasticsearchDomainRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeElasticsearchDomain = "DescribeElasticsearchDomain" @@ -341,8 +386,23 @@ func (c *ElasticsearchService) DescribeElasticsearchDomainRequest(input *Describ // Please also see https://docs.aws.amazon.com/goto/WebAPI/es-2015-01-01/DescribeElasticsearchDomain func (c *ElasticsearchService) DescribeElasticsearchDomain(input *DescribeElasticsearchDomainInput) (*DescribeElasticsearchDomainOutput, error) { req, out := c.DescribeElasticsearchDomainRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeElasticsearchDomainWithContext is the same as DescribeElasticsearchDomain with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeElasticsearchDomain 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 *ElasticsearchService) DescribeElasticsearchDomainWithContext(ctx aws.Context, input *DescribeElasticsearchDomainInput, opts ...request.Option) (*DescribeElasticsearchDomainOutput, error) { + req, out := c.DescribeElasticsearchDomainRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeElasticsearchDomainConfig = "DescribeElasticsearchDomainConfig" @@ -421,8 +481,23 @@ func (c *ElasticsearchService) DescribeElasticsearchDomainConfigRequest(input *D // Please also see https://docs.aws.amazon.com/goto/WebAPI/es-2015-01-01/DescribeElasticsearchDomainConfig func (c *ElasticsearchService) DescribeElasticsearchDomainConfig(input *DescribeElasticsearchDomainConfigInput) (*DescribeElasticsearchDomainConfigOutput, error) { req, out := c.DescribeElasticsearchDomainConfigRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeElasticsearchDomainConfigWithContext is the same as DescribeElasticsearchDomainConfig with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeElasticsearchDomainConfig 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 *ElasticsearchService) DescribeElasticsearchDomainConfigWithContext(ctx aws.Context, input *DescribeElasticsearchDomainConfigInput, opts ...request.Option) (*DescribeElasticsearchDomainConfigOutput, error) { + req, out := c.DescribeElasticsearchDomainConfigRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeElasticsearchDomains = "DescribeElasticsearchDomains" @@ -496,8 +571,23 @@ func (c *ElasticsearchService) DescribeElasticsearchDomainsRequest(input *Descri // Please also see https://docs.aws.amazon.com/goto/WebAPI/es-2015-01-01/DescribeElasticsearchDomains func (c *ElasticsearchService) DescribeElasticsearchDomains(input *DescribeElasticsearchDomainsInput) (*DescribeElasticsearchDomainsOutput, error) { req, out := c.DescribeElasticsearchDomainsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeElasticsearchDomainsWithContext is the same as DescribeElasticsearchDomains with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeElasticsearchDomains 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 *ElasticsearchService) DescribeElasticsearchDomainsWithContext(ctx aws.Context, input *DescribeElasticsearchDomainsInput, opts ...request.Option) (*DescribeElasticsearchDomainsOutput, error) { + req, out := c.DescribeElasticsearchDomainsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeElasticsearchInstanceTypeLimits = "DescribeElasticsearchInstanceTypeLimits" @@ -584,8 +674,23 @@ func (c *ElasticsearchService) DescribeElasticsearchInstanceTypeLimitsRequest(in // Please also see https://docs.aws.amazon.com/goto/WebAPI/es-2015-01-01/DescribeElasticsearchInstanceTypeLimits func (c *ElasticsearchService) DescribeElasticsearchInstanceTypeLimits(input *DescribeElasticsearchInstanceTypeLimitsInput) (*DescribeElasticsearchInstanceTypeLimitsOutput, error) { req, out := c.DescribeElasticsearchInstanceTypeLimitsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeElasticsearchInstanceTypeLimitsWithContext is the same as DescribeElasticsearchInstanceTypeLimits with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeElasticsearchInstanceTypeLimits 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 *ElasticsearchService) DescribeElasticsearchInstanceTypeLimitsWithContext(ctx aws.Context, input *DescribeElasticsearchInstanceTypeLimitsInput, opts ...request.Option) (*DescribeElasticsearchInstanceTypeLimitsOutput, error) { + req, out := c.DescribeElasticsearchInstanceTypeLimitsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opListDomainNames = "ListDomainNames" @@ -654,8 +759,23 @@ func (c *ElasticsearchService) ListDomainNamesRequest(input *ListDomainNamesInpu // Please also see https://docs.aws.amazon.com/goto/WebAPI/es-2015-01-01/ListDomainNames func (c *ElasticsearchService) ListDomainNames(input *ListDomainNamesInput) (*ListDomainNamesOutput, error) { req, out := c.ListDomainNamesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListDomainNamesWithContext is the same as ListDomainNames with the addition of +// the ability to pass a context and additional request options. +// +// See ListDomainNames 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 *ElasticsearchService) ListDomainNamesWithContext(ctx aws.Context, input *ListDomainNamesInput, opts ...request.Option) (*ListDomainNamesOutput, error) { + req, out := c.ListDomainNamesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opListElasticsearchInstanceTypes = "ListElasticsearchInstanceTypes" @@ -738,8 +858,23 @@ func (c *ElasticsearchService) ListElasticsearchInstanceTypesRequest(input *List // Please also see https://docs.aws.amazon.com/goto/WebAPI/es-2015-01-01/ListElasticsearchInstanceTypes func (c *ElasticsearchService) ListElasticsearchInstanceTypes(input *ListElasticsearchInstanceTypesInput) (*ListElasticsearchInstanceTypesOutput, error) { req, out := c.ListElasticsearchInstanceTypesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListElasticsearchInstanceTypesWithContext is the same as ListElasticsearchInstanceTypes with the addition of +// the ability to pass a context and additional request options. +// +// See ListElasticsearchInstanceTypes 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 *ElasticsearchService) ListElasticsearchInstanceTypesWithContext(ctx aws.Context, input *ListElasticsearchInstanceTypesInput, opts ...request.Option) (*ListElasticsearchInstanceTypesOutput, error) { + req, out := c.ListElasticsearchInstanceTypesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // ListElasticsearchInstanceTypesPages iterates over the pages of a ListElasticsearchInstanceTypes operation, @@ -759,12 +894,37 @@ func (c *ElasticsearchService) ListElasticsearchInstanceTypes(input *ListElastic // return pageNum <= 3 // }) // -func (c *ElasticsearchService) ListElasticsearchInstanceTypesPages(input *ListElasticsearchInstanceTypesInput, fn func(p *ListElasticsearchInstanceTypesOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.ListElasticsearchInstanceTypesRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*ListElasticsearchInstanceTypesOutput), lastPage) - }) +func (c *ElasticsearchService) ListElasticsearchInstanceTypesPages(input *ListElasticsearchInstanceTypesInput, fn func(*ListElasticsearchInstanceTypesOutput, bool) bool) error { + return c.ListElasticsearchInstanceTypesPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListElasticsearchInstanceTypesPagesWithContext same as ListElasticsearchInstanceTypesPages 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 *ElasticsearchService) ListElasticsearchInstanceTypesPagesWithContext(ctx aws.Context, input *ListElasticsearchInstanceTypesInput, fn func(*ListElasticsearchInstanceTypesOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListElasticsearchInstanceTypesInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListElasticsearchInstanceTypesRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*ListElasticsearchInstanceTypesOutput), !p.HasNextPage()) + } + return p.Err() } const opListElasticsearchVersions = "ListElasticsearchVersions" @@ -847,8 +1007,23 @@ func (c *ElasticsearchService) ListElasticsearchVersionsRequest(input *ListElast // Please also see https://docs.aws.amazon.com/goto/WebAPI/es-2015-01-01/ListElasticsearchVersions func (c *ElasticsearchService) ListElasticsearchVersions(input *ListElasticsearchVersionsInput) (*ListElasticsearchVersionsOutput, error) { req, out := c.ListElasticsearchVersionsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListElasticsearchVersionsWithContext is the same as ListElasticsearchVersions with the addition of +// the ability to pass a context and additional request options. +// +// See ListElasticsearchVersions 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 *ElasticsearchService) ListElasticsearchVersionsWithContext(ctx aws.Context, input *ListElasticsearchVersionsInput, opts ...request.Option) (*ListElasticsearchVersionsOutput, error) { + req, out := c.ListElasticsearchVersionsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // ListElasticsearchVersionsPages iterates over the pages of a ListElasticsearchVersions operation, @@ -868,12 +1043,37 @@ func (c *ElasticsearchService) ListElasticsearchVersions(input *ListElasticsearc // return pageNum <= 3 // }) // -func (c *ElasticsearchService) ListElasticsearchVersionsPages(input *ListElasticsearchVersionsInput, fn func(p *ListElasticsearchVersionsOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.ListElasticsearchVersionsRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*ListElasticsearchVersionsOutput), lastPage) - }) +func (c *ElasticsearchService) ListElasticsearchVersionsPages(input *ListElasticsearchVersionsInput, fn func(*ListElasticsearchVersionsOutput, bool) bool) error { + return c.ListElasticsearchVersionsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListElasticsearchVersionsPagesWithContext same as ListElasticsearchVersionsPages 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 *ElasticsearchService) ListElasticsearchVersionsPagesWithContext(ctx aws.Context, input *ListElasticsearchVersionsInput, fn func(*ListElasticsearchVersionsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListElasticsearchVersionsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListElasticsearchVersionsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*ListElasticsearchVersionsOutput), !p.HasNextPage()) + } + return p.Err() } const opListTags = "ListTags" @@ -950,8 +1150,23 @@ func (c *ElasticsearchService) ListTagsRequest(input *ListTagsInput) (req *reque // Please also see https://docs.aws.amazon.com/goto/WebAPI/es-2015-01-01/ListTags func (c *ElasticsearchService) ListTags(input *ListTagsInput) (*ListTagsOutput, error) { req, out := c.ListTagsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListTagsWithContext is the same as ListTags with the addition of +// the ability to pass a context and additional request options. +// +// See ListTags 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 *ElasticsearchService) ListTagsWithContext(ctx aws.Context, input *ListTagsInput, opts ...request.Option) (*ListTagsOutput, error) { + req, out := c.ListTagsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opRemoveTags = "RemoveTags" @@ -1026,8 +1241,23 @@ func (c *ElasticsearchService) RemoveTagsRequest(input *RemoveTagsInput) (req *r // Please also see https://docs.aws.amazon.com/goto/WebAPI/es-2015-01-01/RemoveTags func (c *ElasticsearchService) RemoveTags(input *RemoveTagsInput) (*RemoveTagsOutput, error) { req, out := c.RemoveTagsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// RemoveTagsWithContext is the same as RemoveTags with the addition of +// the ability to pass a context and additional request options. +// +// See RemoveTags 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 *ElasticsearchService) RemoveTagsWithContext(ctx aws.Context, input *RemoveTagsInput, opts ...request.Option) (*RemoveTagsOutput, error) { + req, out := c.RemoveTagsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opUpdateElasticsearchDomainConfig = "UpdateElasticsearchDomainConfig" @@ -1113,8 +1343,23 @@ func (c *ElasticsearchService) UpdateElasticsearchDomainConfigRequest(input *Upd // Please also see https://docs.aws.amazon.com/goto/WebAPI/es-2015-01-01/UpdateElasticsearchDomainConfig func (c *ElasticsearchService) UpdateElasticsearchDomainConfig(input *UpdateElasticsearchDomainConfigInput) (*UpdateElasticsearchDomainConfigOutput, error) { req, out := c.UpdateElasticsearchDomainConfigRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// UpdateElasticsearchDomainConfigWithContext is the same as UpdateElasticsearchDomainConfig with the addition of +// the ability to pass a context and additional request options. +// +// See UpdateElasticsearchDomainConfig 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 *ElasticsearchService) UpdateElasticsearchDomainConfigWithContext(ctx aws.Context, input *UpdateElasticsearchDomainConfigInput, opts ...request.Option) (*UpdateElasticsearchDomainConfigOutput, error) { + req, out := c.UpdateElasticsearchDomainConfigRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // The configured access rules for the domain's document and search endpoints, diff --git a/vendor/github.com/aws/aws-sdk-go/service/elasticsearchservice/doc.go b/vendor/github.com/aws/aws-sdk-go/service/elasticsearchservice/doc.go new file mode 100644 index 000000000..543a11aff --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/service/elasticsearchservice/doc.go @@ -0,0 +1,85 @@ +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. + +// Package elasticsearchservice provides the client and types for making API +// requests to Amazon Elasticsearch Service. +// +// Use the Amazon Elasticsearch configuration API to create, configure, and +// manage Elasticsearch domains. +// +// The endpoint for configuration service requests is region-specific: es.region.amazonaws.com. +// For example, es.us-east-1.amazonaws.com. For a current list of supported +// regions and endpoints, see Regions and Endpoints (http://docs.aws.amazon.com/general/latest/gr/rande.html#elasticsearch-service-regions). +// +// See https://docs.aws.amazon.com/goto/WebAPI/es-2015-01-01 for more information on this service. +// +// See elasticsearchservice package documentation for more information. +// https://docs.aws.amazon.com/sdk-for-go/api/service/elasticsearchservice/ +// +// Using the Client +// +// To use the client for Amazon Elasticsearch Service you will first need +// to create a new instance of it. +// +// When creating a client for an AWS service you'll first need to have a Session +// already created. The Session provides configuration that can be shared +// between multiple service clients. Additional configuration can be applied to +// the Session and service's client when they are constructed. The aws package's +// Config type contains several fields such as Region for the AWS Region the +// client should make API requests too. The optional Config value can be provided +// as the variadic argument for Sessions and client creation. +// +// Once the service's client is created you can use it to make API requests the +// AWS service. These clients are safe to use concurrently. +// +// // Create a session to share configuration, and load external configuration. +// sess := session.Must(session.NewSession()) +// +// // Create the service's client with the session. +// svc := elasticsearchservice.New(sess) +// +// See the SDK's documentation for more information on how to use service clients. +// https://docs.aws.amazon.com/sdk-for-go/api/ +// +// See aws package's Config type for more information on configuration options. +// https://docs.aws.amazon.com/sdk-for-go/api/aws/#Config +// +// See the Amazon Elasticsearch Service client ElasticsearchService for more +// information on creating the service's client. +// https://docs.aws.amazon.com/sdk-for-go/api/service/elasticsearchservice/#New +// +// Once the client is created you can make an API request to the service. +// Each API method takes a input parameter, and returns the service response +// and an error. +// +// The API method will document which error codes the service can be returned +// by the operation if the service models the API operation's errors. These +// errors will also be available as const strings prefixed with "ErrCode". +// +// result, err := svc.AddTags(params) +// if err != nil { +// // Cast err to awserr.Error to handle specific error codes. +// aerr, ok := err.(awserr.Error) +// if ok && aerr.Code() == { +// // Specific error code handling +// } +// return err +// } +// +// fmt.Println("AddTags result:") +// fmt.Println(result) +// +// Using the Client with Context +// +// The service's client also provides methods to make API requests with a Context +// value. This allows you to control the timeout, and cancellation of pending +// requests. These methods also take request Option as variadic parameter to apply +// additional configuration to the API request. +// +// ctx := context.Background() +// +// result, err := svc.AddTagsWithContext(ctx, params) +// +// See the request package documentation for more information on using Context pattern +// with the SDK. +// https://docs.aws.amazon.com/sdk-for-go/api/aws/request/ +package elasticsearchservice diff --git a/vendor/github.com/aws/aws-sdk-go/service/elasticsearchservice/errors.go b/vendor/github.com/aws/aws-sdk-go/service/elasticsearchservice/errors.go index 66c1650b0..332cf8d4f 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/elasticsearchservice/errors.go +++ b/vendor/github.com/aws/aws-sdk-go/service/elasticsearchservice/errors.go @@ -1,4 +1,4 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. package elasticsearchservice diff --git a/vendor/github.com/aws/aws-sdk-go/service/elasticsearchservice/service.go b/vendor/github.com/aws/aws-sdk-go/service/elasticsearchservice/service.go index 8ba1f8bf5..c4388e79b 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/elasticsearchservice/service.go +++ b/vendor/github.com/aws/aws-sdk-go/service/elasticsearchservice/service.go @@ -1,4 +1,4 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. package elasticsearchservice @@ -11,15 +11,12 @@ import ( "github.com/aws/aws-sdk-go/private/protocol/restjson" ) -// Use the Amazon Elasticsearch configuration API to create, configure, and -// manage Elasticsearch domains. +// ElasticsearchService provides the API operation methods for making requests to +// Amazon Elasticsearch Service. See this package's package overview docs +// for details on the service. // -// The endpoint for configuration service requests is region-specific: es.region.amazonaws.com. -// For example, es.us-east-1.amazonaws.com. For a current list of supported -// regions and endpoints, see Regions and Endpoints (http://docs.aws.amazon.com/general/latest/gr/rande.html#elasticsearch-service-regions). -// The service client's operations are safe to be used concurrently. -// It is not safe to mutate any of the client's properties though. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/es-2015-01-01 +// ElasticsearchService methods are safe to use concurrently. It is not safe to +// modify mutate any of the struct's properties though. type ElasticsearchService struct { *client.Client } diff --git a/vendor/github.com/aws/aws-sdk-go/service/elastictranscoder/api.go b/vendor/github.com/aws/aws-sdk-go/service/elastictranscoder/api.go index df4a29947..dc719ef05 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/elastictranscoder/api.go +++ b/vendor/github.com/aws/aws-sdk-go/service/elastictranscoder/api.go @@ -1,11 +1,11 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. -// Package elastictranscoder provides a client for Amazon Elastic Transcoder. package elastictranscoder import ( "fmt" + "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awsutil" "github.com/aws/aws-sdk-go/aws/request" ) @@ -90,8 +90,23 @@ func (c *ElasticTranscoder) CancelJobRequest(input *CancelJobInput) (req *reques // func (c *ElasticTranscoder) CancelJob(input *CancelJobInput) (*CancelJobOutput, error) { req, out := c.CancelJobRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CancelJobWithContext is the same as CancelJob with the addition of +// the ability to pass a context and additional request options. +// +// See CancelJob 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 *ElasticTranscoder) CancelJobWithContext(ctx aws.Context, input *CancelJobInput, opts ...request.Option) (*CancelJobOutput, error) { + req, out := c.CancelJobRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateJob = "CreateJob" @@ -176,8 +191,23 @@ func (c *ElasticTranscoder) CreateJobRequest(input *CreateJobInput) (req *reques // func (c *ElasticTranscoder) CreateJob(input *CreateJobInput) (*CreateJobResponse, error) { req, out := c.CreateJobRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateJobWithContext is the same as CreateJob with the addition of +// the ability to pass a context and additional request options. +// +// See CreateJob 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 *ElasticTranscoder) CreateJobWithContext(ctx aws.Context, input *CreateJobInput, opts ...request.Option) (*CreateJobResponse, error) { + req, out := c.CreateJobRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreatePipeline = "CreatePipeline" @@ -256,8 +286,23 @@ func (c *ElasticTranscoder) CreatePipelineRequest(input *CreatePipelineInput) (r // func (c *ElasticTranscoder) CreatePipeline(input *CreatePipelineInput) (*CreatePipelineOutput, error) { req, out := c.CreatePipelineRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreatePipelineWithContext is the same as CreatePipeline with the addition of +// the ability to pass a context and additional request options. +// +// See CreatePipeline 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 *ElasticTranscoder) CreatePipelineWithContext(ctx aws.Context, input *CreatePipelineInput, opts ...request.Option) (*CreatePipelineOutput, error) { + req, out := c.CreatePipelineRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreatePreset = "CreatePreset" @@ -345,8 +390,23 @@ func (c *ElasticTranscoder) CreatePresetRequest(input *CreatePresetInput) (req * // func (c *ElasticTranscoder) CreatePreset(input *CreatePresetInput) (*CreatePresetOutput, error) { req, out := c.CreatePresetRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreatePresetWithContext is the same as CreatePreset with the addition of +// the ability to pass a context and additional request options. +// +// See CreatePreset 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 *ElasticTranscoder) CreatePresetWithContext(ctx aws.Context, input *CreatePresetInput, opts ...request.Option) (*CreatePresetOutput, error) { + req, out := c.CreatePresetRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeletePipeline = "DeletePipeline" @@ -429,8 +489,23 @@ func (c *ElasticTranscoder) DeletePipelineRequest(input *DeletePipelineInput) (r // func (c *ElasticTranscoder) DeletePipeline(input *DeletePipelineInput) (*DeletePipelineOutput, error) { req, out := c.DeletePipelineRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeletePipelineWithContext is the same as DeletePipeline with the addition of +// the ability to pass a context and additional request options. +// +// See DeletePipeline 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 *ElasticTranscoder) DeletePipelineWithContext(ctx aws.Context, input *DeletePipelineInput, opts ...request.Option) (*DeletePipelineOutput, error) { + req, out := c.DeletePipelineRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeletePreset = "DeletePreset" @@ -507,8 +582,23 @@ func (c *ElasticTranscoder) DeletePresetRequest(input *DeletePresetInput) (req * // func (c *ElasticTranscoder) DeletePreset(input *DeletePresetInput) (*DeletePresetOutput, error) { req, out := c.DeletePresetRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeletePresetWithContext is the same as DeletePreset with the addition of +// the ability to pass a context and additional request options. +// +// See DeletePreset 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 *ElasticTranscoder) DeletePresetWithContext(ctx aws.Context, input *DeletePresetInput, opts ...request.Option) (*DeletePresetOutput, error) { + req, out := c.DeletePresetRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opListJobsByPipeline = "ListJobsByPipeline" @@ -593,8 +683,23 @@ func (c *ElasticTranscoder) ListJobsByPipelineRequest(input *ListJobsByPipelineI // func (c *ElasticTranscoder) ListJobsByPipeline(input *ListJobsByPipelineInput) (*ListJobsByPipelineOutput, error) { req, out := c.ListJobsByPipelineRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListJobsByPipelineWithContext is the same as ListJobsByPipeline with the addition of +// the ability to pass a context and additional request options. +// +// See ListJobsByPipeline 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 *ElasticTranscoder) ListJobsByPipelineWithContext(ctx aws.Context, input *ListJobsByPipelineInput, opts ...request.Option) (*ListJobsByPipelineOutput, error) { + req, out := c.ListJobsByPipelineRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // ListJobsByPipelinePages iterates over the pages of a ListJobsByPipeline operation, @@ -614,12 +719,37 @@ func (c *ElasticTranscoder) ListJobsByPipeline(input *ListJobsByPipelineInput) ( // return pageNum <= 3 // }) // -func (c *ElasticTranscoder) ListJobsByPipelinePages(input *ListJobsByPipelineInput, fn func(p *ListJobsByPipelineOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.ListJobsByPipelineRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*ListJobsByPipelineOutput), lastPage) - }) +func (c *ElasticTranscoder) ListJobsByPipelinePages(input *ListJobsByPipelineInput, fn func(*ListJobsByPipelineOutput, bool) bool) error { + return c.ListJobsByPipelinePagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListJobsByPipelinePagesWithContext same as ListJobsByPipelinePages 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 *ElasticTranscoder) ListJobsByPipelinePagesWithContext(ctx aws.Context, input *ListJobsByPipelineInput, fn func(*ListJobsByPipelineOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListJobsByPipelineInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListJobsByPipelineRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*ListJobsByPipelineOutput), !p.HasNextPage()) + } + return p.Err() } const opListJobsByStatus = "ListJobsByStatus" @@ -702,8 +832,23 @@ func (c *ElasticTranscoder) ListJobsByStatusRequest(input *ListJobsByStatusInput // func (c *ElasticTranscoder) ListJobsByStatus(input *ListJobsByStatusInput) (*ListJobsByStatusOutput, error) { req, out := c.ListJobsByStatusRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListJobsByStatusWithContext is the same as ListJobsByStatus with the addition of +// the ability to pass a context and additional request options. +// +// See ListJobsByStatus 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 *ElasticTranscoder) ListJobsByStatusWithContext(ctx aws.Context, input *ListJobsByStatusInput, opts ...request.Option) (*ListJobsByStatusOutput, error) { + req, out := c.ListJobsByStatusRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // ListJobsByStatusPages iterates over the pages of a ListJobsByStatus operation, @@ -723,12 +868,37 @@ func (c *ElasticTranscoder) ListJobsByStatus(input *ListJobsByStatusInput) (*Lis // return pageNum <= 3 // }) // -func (c *ElasticTranscoder) ListJobsByStatusPages(input *ListJobsByStatusInput, fn func(p *ListJobsByStatusOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.ListJobsByStatusRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*ListJobsByStatusOutput), lastPage) - }) +func (c *ElasticTranscoder) ListJobsByStatusPages(input *ListJobsByStatusInput, fn func(*ListJobsByStatusOutput, bool) bool) error { + return c.ListJobsByStatusPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListJobsByStatusPagesWithContext same as ListJobsByStatusPages 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 *ElasticTranscoder) ListJobsByStatusPagesWithContext(ctx aws.Context, input *ListJobsByStatusInput, fn func(*ListJobsByStatusOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListJobsByStatusInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListJobsByStatusRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*ListJobsByStatusOutput), !p.HasNextPage()) + } + return p.Err() } const opListPipelines = "ListPipelines" @@ -805,8 +975,23 @@ func (c *ElasticTranscoder) ListPipelinesRequest(input *ListPipelinesInput) (req // func (c *ElasticTranscoder) ListPipelines(input *ListPipelinesInput) (*ListPipelinesOutput, error) { req, out := c.ListPipelinesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListPipelinesWithContext is the same as ListPipelines with the addition of +// the ability to pass a context and additional request options. +// +// See ListPipelines 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 *ElasticTranscoder) ListPipelinesWithContext(ctx aws.Context, input *ListPipelinesInput, opts ...request.Option) (*ListPipelinesOutput, error) { + req, out := c.ListPipelinesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // ListPipelinesPages iterates over the pages of a ListPipelines operation, @@ -826,12 +1011,37 @@ func (c *ElasticTranscoder) ListPipelines(input *ListPipelinesInput) (*ListPipel // return pageNum <= 3 // }) // -func (c *ElasticTranscoder) ListPipelinesPages(input *ListPipelinesInput, fn func(p *ListPipelinesOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.ListPipelinesRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*ListPipelinesOutput), lastPage) - }) +func (c *ElasticTranscoder) ListPipelinesPages(input *ListPipelinesInput, fn func(*ListPipelinesOutput, bool) bool) error { + return c.ListPipelinesPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListPipelinesPagesWithContext same as ListPipelinesPages 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 *ElasticTranscoder) ListPipelinesPagesWithContext(ctx aws.Context, input *ListPipelinesInput, fn func(*ListPipelinesOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListPipelinesInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListPipelinesRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*ListPipelinesOutput), !p.HasNextPage()) + } + return p.Err() } const opListPresets = "ListPresets" @@ -908,8 +1118,23 @@ func (c *ElasticTranscoder) ListPresetsRequest(input *ListPresetsInput) (req *re // func (c *ElasticTranscoder) ListPresets(input *ListPresetsInput) (*ListPresetsOutput, error) { req, out := c.ListPresetsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListPresetsWithContext is the same as ListPresets with the addition of +// the ability to pass a context and additional request options. +// +// See ListPresets 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 *ElasticTranscoder) ListPresetsWithContext(ctx aws.Context, input *ListPresetsInput, opts ...request.Option) (*ListPresetsOutput, error) { + req, out := c.ListPresetsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // ListPresetsPages iterates over the pages of a ListPresets operation, @@ -929,12 +1154,37 @@ func (c *ElasticTranscoder) ListPresets(input *ListPresetsInput) (*ListPresetsOu // return pageNum <= 3 // }) // -func (c *ElasticTranscoder) ListPresetsPages(input *ListPresetsInput, fn func(p *ListPresetsOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.ListPresetsRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*ListPresetsOutput), lastPage) - }) +func (c *ElasticTranscoder) ListPresetsPages(input *ListPresetsInput, fn func(*ListPresetsOutput, bool) bool) error { + return c.ListPresetsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListPresetsPagesWithContext same as ListPresetsPages 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 *ElasticTranscoder) ListPresetsPagesWithContext(ctx aws.Context, input *ListPresetsInput, fn func(*ListPresetsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListPresetsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListPresetsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*ListPresetsOutput), !p.HasNextPage()) + } + return p.Err() } const opReadJob = "ReadJob" @@ -1009,8 +1259,23 @@ func (c *ElasticTranscoder) ReadJobRequest(input *ReadJobInput) (req *request.Re // func (c *ElasticTranscoder) ReadJob(input *ReadJobInput) (*ReadJobOutput, error) { req, out := c.ReadJobRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ReadJobWithContext is the same as ReadJob with the addition of +// the ability to pass a context and additional request options. +// +// See ReadJob 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 *ElasticTranscoder) ReadJobWithContext(ctx aws.Context, input *ReadJobInput, opts ...request.Option) (*ReadJobOutput, error) { + req, out := c.ReadJobRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opReadPipeline = "ReadPipeline" @@ -1085,8 +1350,23 @@ func (c *ElasticTranscoder) ReadPipelineRequest(input *ReadPipelineInput) (req * // func (c *ElasticTranscoder) ReadPipeline(input *ReadPipelineInput) (*ReadPipelineOutput, error) { req, out := c.ReadPipelineRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ReadPipelineWithContext is the same as ReadPipeline with the addition of +// the ability to pass a context and additional request options. +// +// See ReadPipeline 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 *ElasticTranscoder) ReadPipelineWithContext(ctx aws.Context, input *ReadPipelineInput, opts ...request.Option) (*ReadPipelineOutput, error) { + req, out := c.ReadPipelineRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opReadPreset = "ReadPreset" @@ -1161,8 +1441,23 @@ func (c *ElasticTranscoder) ReadPresetRequest(input *ReadPresetInput) (req *requ // func (c *ElasticTranscoder) ReadPreset(input *ReadPresetInput) (*ReadPresetOutput, error) { req, out := c.ReadPresetRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ReadPresetWithContext is the same as ReadPreset with the addition of +// the ability to pass a context and additional request options. +// +// See ReadPreset 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 *ElasticTranscoder) ReadPresetWithContext(ctx aws.Context, input *ReadPresetInput, opts ...request.Option) (*ReadPresetOutput, error) { + req, out := c.ReadPresetRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opTestRole = "TestRole" @@ -1246,8 +1541,23 @@ func (c *ElasticTranscoder) TestRoleRequest(input *TestRoleInput) (req *request. // func (c *ElasticTranscoder) TestRole(input *TestRoleInput) (*TestRoleOutput, error) { req, out := c.TestRoleRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// TestRoleWithContext is the same as TestRole with the addition of +// the ability to pass a context and additional request options. +// +// See TestRole 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 *ElasticTranscoder) TestRoleWithContext(ctx aws.Context, input *TestRoleInput, opts ...request.Option) (*TestRoleOutput, error) { + req, out := c.TestRoleRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opUpdatePipeline = "UpdatePipeline" @@ -1331,8 +1641,23 @@ func (c *ElasticTranscoder) UpdatePipelineRequest(input *UpdatePipelineInput) (r // func (c *ElasticTranscoder) UpdatePipeline(input *UpdatePipelineInput) (*UpdatePipelineOutput, error) { req, out := c.UpdatePipelineRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// UpdatePipelineWithContext is the same as UpdatePipeline with the addition of +// the ability to pass a context and additional request options. +// +// See UpdatePipeline 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 *ElasticTranscoder) UpdatePipelineWithContext(ctx aws.Context, input *UpdatePipelineInput, opts ...request.Option) (*UpdatePipelineOutput, error) { + req, out := c.UpdatePipelineRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opUpdatePipelineNotifications = "UpdatePipelineNotifications" @@ -1415,8 +1740,23 @@ func (c *ElasticTranscoder) UpdatePipelineNotificationsRequest(input *UpdatePipe // func (c *ElasticTranscoder) UpdatePipelineNotifications(input *UpdatePipelineNotificationsInput) (*UpdatePipelineNotificationsOutput, error) { req, out := c.UpdatePipelineNotificationsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// UpdatePipelineNotificationsWithContext is the same as UpdatePipelineNotifications with the addition of +// the ability to pass a context and additional request options. +// +// See UpdatePipelineNotifications 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 *ElasticTranscoder) UpdatePipelineNotificationsWithContext(ctx aws.Context, input *UpdatePipelineNotificationsInput, opts ...request.Option) (*UpdatePipelineNotificationsOutput, error) { + req, out := c.UpdatePipelineNotificationsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opUpdatePipelineStatus = "UpdatePipelineStatus" @@ -1502,8 +1842,23 @@ func (c *ElasticTranscoder) UpdatePipelineStatusRequest(input *UpdatePipelineSta // func (c *ElasticTranscoder) UpdatePipelineStatus(input *UpdatePipelineStatusInput) (*UpdatePipelineStatusOutput, error) { req, out := c.UpdatePipelineStatusRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// UpdatePipelineStatusWithContext is the same as UpdatePipelineStatus with the addition of +// the ability to pass a context and additional request options. +// +// See UpdatePipelineStatus 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 *ElasticTranscoder) UpdatePipelineStatusWithContext(ctx aws.Context, input *UpdatePipelineStatusInput, opts ...request.Option) (*UpdatePipelineStatusOutput, error) { + req, out := c.UpdatePipelineStatusRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // The file to be used as album art. There can be multiple artworks associated diff --git a/vendor/github.com/aws/aws-sdk-go/service/elastictranscoder/doc.go b/vendor/github.com/aws/aws-sdk-go/service/elastictranscoder/doc.go new file mode 100644 index 000000000..cfaacdf4e --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/service/elastictranscoder/doc.go @@ -0,0 +1,78 @@ +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. + +// Package elastictranscoder provides the client and types for making API +// requests to Amazon Elastic Transcoder. +// +// The AWS Elastic Transcoder Service. +// +// See elastictranscoder package documentation for more information. +// https://docs.aws.amazon.com/sdk-for-go/api/service/elastictranscoder/ +// +// Using the Client +// +// To use the client for Amazon Elastic Transcoder you will first need +// to create a new instance of it. +// +// When creating a client for an AWS service you'll first need to have a Session +// already created. The Session provides configuration that can be shared +// between multiple service clients. Additional configuration can be applied to +// the Session and service's client when they are constructed. The aws package's +// Config type contains several fields such as Region for the AWS Region the +// client should make API requests too. The optional Config value can be provided +// as the variadic argument for Sessions and client creation. +// +// Once the service's client is created you can use it to make API requests the +// AWS service. These clients are safe to use concurrently. +// +// // Create a session to share configuration, and load external configuration. +// sess := session.Must(session.NewSession()) +// +// // Create the service's client with the session. +// svc := elastictranscoder.New(sess) +// +// See the SDK's documentation for more information on how to use service clients. +// https://docs.aws.amazon.com/sdk-for-go/api/ +// +// See aws package's Config type for more information on configuration options. +// https://docs.aws.amazon.com/sdk-for-go/api/aws/#Config +// +// See the Amazon Elastic Transcoder client ElasticTranscoder for more +// information on creating the service's client. +// https://docs.aws.amazon.com/sdk-for-go/api/service/elastictranscoder/#New +// +// Once the client is created you can make an API request to the service. +// Each API method takes a input parameter, and returns the service response +// and an error. +// +// The API method will document which error codes the service can be returned +// by the operation if the service models the API operation's errors. These +// errors will also be available as const strings prefixed with "ErrCode". +// +// result, err := svc.CancelJob(params) +// if err != nil { +// // Cast err to awserr.Error to handle specific error codes. +// aerr, ok := err.(awserr.Error) +// if ok && aerr.Code() == { +// // Specific error code handling +// } +// return err +// } +// +// fmt.Println("CancelJob result:") +// fmt.Println(result) +// +// Using the Client with Context +// +// The service's client also provides methods to make API requests with a Context +// value. This allows you to control the timeout, and cancellation of pending +// requests. These methods also take request Option as variadic parameter to apply +// additional configuration to the API request. +// +// ctx := context.Background() +// +// result, err := svc.CancelJobWithContext(ctx, params) +// +// See the request package documentation for more information on using Context pattern +// with the SDK. +// https://docs.aws.amazon.com/sdk-for-go/api/aws/request/ +package elastictranscoder diff --git a/vendor/github.com/aws/aws-sdk-go/service/elastictranscoder/errors.go b/vendor/github.com/aws/aws-sdk-go/service/elastictranscoder/errors.go index 18374bc24..7c670785c 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/elastictranscoder/errors.go +++ b/vendor/github.com/aws/aws-sdk-go/service/elastictranscoder/errors.go @@ -1,4 +1,4 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. package elastictranscoder diff --git a/vendor/github.com/aws/aws-sdk-go/service/elastictranscoder/service.go b/vendor/github.com/aws/aws-sdk-go/service/elastictranscoder/service.go index bbd6e2479..29d15e2e7 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/elastictranscoder/service.go +++ b/vendor/github.com/aws/aws-sdk-go/service/elastictranscoder/service.go @@ -1,4 +1,4 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. package elastictranscoder @@ -11,9 +11,12 @@ import ( "github.com/aws/aws-sdk-go/private/protocol/restjson" ) -// The AWS Elastic Transcoder Service. -// The service client's operations are safe to be used concurrently. -// It is not safe to mutate any of the client's properties though. +// ElasticTranscoder provides the API operation methods for making requests to +// Amazon Elastic Transcoder. See this package's package overview docs +// for details on the service. +// +// ElasticTranscoder methods are safe to use concurrently. It is not safe to +// modify mutate any of the struct's properties though. type ElasticTranscoder struct { *client.Client } diff --git a/vendor/github.com/aws/aws-sdk-go/service/elastictranscoder/waiters.go b/vendor/github.com/aws/aws-sdk-go/service/elastictranscoder/waiters.go index 767462041..d4e2bf2ae 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/elastictranscoder/waiters.go +++ b/vendor/github.com/aws/aws-sdk-go/service/elastictranscoder/waiters.go @@ -1,9 +1,12 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. package elastictranscoder import ( - "github.com/aws/aws-sdk-go/private/waiter" + "time" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/request" ) // WaitUntilJobComplete uses the Amazon Elastic Transcoder API operation @@ -11,36 +14,53 @@ import ( // If the condition is not meet within the max attempt window an error will // be returned. func (c *ElasticTranscoder) WaitUntilJobComplete(input *ReadJobInput) error { - waiterCfg := waiter.Config{ - Operation: "ReadJob", - Delay: 30, + return c.WaitUntilJobCompleteWithContext(aws.BackgroundContext(), input) +} + +// WaitUntilJobCompleteWithContext is an extended version of WaitUntilJobComplete. +// 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 *ElasticTranscoder) WaitUntilJobCompleteWithContext(ctx aws.Context, input *ReadJobInput, opts ...request.WaiterOption) error { + w := request.Waiter{ + Name: "WaitUntilJobComplete", MaxAttempts: 120, - Acceptors: []waiter.WaitAcceptor{ + Delay: request.ConstantWaiterDelay(30 * time.Second), + Acceptors: []request.WaiterAcceptor{ { - State: "success", - Matcher: "path", - Argument: "Job.Status", + State: request.SuccessWaiterState, + Matcher: request.PathWaiterMatch, Argument: "Job.Status", Expected: "Complete", }, { - State: "failure", - Matcher: "path", - Argument: "Job.Status", + State: request.FailureWaiterState, + Matcher: request.PathWaiterMatch, Argument: "Job.Status", Expected: "Canceled", }, { - State: "failure", - Matcher: "path", - Argument: "Job.Status", + State: request.FailureWaiterState, + Matcher: request.PathWaiterMatch, Argument: "Job.Status", Expected: "Error", }, }, + Logger: c.Config.Logger, + NewRequest: func(opts []request.Option) (*request.Request, error) { + var inCpy *ReadJobInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ReadJobRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, } + w.ApplyOptions(opts...) - w := waiter.Waiter{ - Client: c, - Input: input, - Config: waiterCfg, - } - return w.Wait() + return w.WaitWithContext(ctx) } diff --git a/vendor/github.com/aws/aws-sdk-go/service/elb/api.go b/vendor/github.com/aws/aws-sdk-go/service/elb/api.go index b8c6d428e..d69d0fd75 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/elb/api.go +++ b/vendor/github.com/aws/aws-sdk-go/service/elb/api.go @@ -1,12 +1,12 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. -// Package elb provides a client for Elastic Load Balancing. package elb import ( "fmt" "time" + "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awsutil" "github.com/aws/aws-sdk-go/aws/request" ) @@ -86,8 +86,23 @@ func (c *ELB) AddTagsRequest(input *AddTagsInput) (req *request.Request, output // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancing-2012-06-01/AddTags func (c *ELB) AddTags(input *AddTagsInput) (*AddTagsOutput, error) { req, out := c.AddTagsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// AddTagsWithContext is the same as AddTags with the addition of +// the ability to pass a context and additional request options. +// +// See AddTags 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 *ELB) AddTagsWithContext(ctx aws.Context, input *AddTagsInput, opts ...request.Option) (*AddTagsOutput, error) { + req, out := c.AddTagsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opApplySecurityGroupsToLoadBalancer = "ApplySecurityGroupsToLoadBalancer" @@ -162,8 +177,23 @@ func (c *ELB) ApplySecurityGroupsToLoadBalancerRequest(input *ApplySecurityGroup // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancing-2012-06-01/ApplySecurityGroupsToLoadBalancer func (c *ELB) ApplySecurityGroupsToLoadBalancer(input *ApplySecurityGroupsToLoadBalancerInput) (*ApplySecurityGroupsToLoadBalancerOutput, error) { req, out := c.ApplySecurityGroupsToLoadBalancerRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ApplySecurityGroupsToLoadBalancerWithContext is the same as ApplySecurityGroupsToLoadBalancer with the addition of +// the ability to pass a context and additional request options. +// +// See ApplySecurityGroupsToLoadBalancer 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 *ELB) ApplySecurityGroupsToLoadBalancerWithContext(ctx aws.Context, input *ApplySecurityGroupsToLoadBalancerInput, opts ...request.Option) (*ApplySecurityGroupsToLoadBalancerOutput, error) { + req, out := c.ApplySecurityGroupsToLoadBalancerRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opAttachLoadBalancerToSubnets = "AttachLoadBalancerToSubnets" @@ -242,8 +272,23 @@ func (c *ELB) AttachLoadBalancerToSubnetsRequest(input *AttachLoadBalancerToSubn // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancing-2012-06-01/AttachLoadBalancerToSubnets func (c *ELB) AttachLoadBalancerToSubnets(input *AttachLoadBalancerToSubnetsInput) (*AttachLoadBalancerToSubnetsOutput, error) { req, out := c.AttachLoadBalancerToSubnetsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// AttachLoadBalancerToSubnetsWithContext is the same as AttachLoadBalancerToSubnets with the addition of +// the ability to pass a context and additional request options. +// +// See AttachLoadBalancerToSubnets 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 *ELB) AttachLoadBalancerToSubnetsWithContext(ctx aws.Context, input *AttachLoadBalancerToSubnetsInput, opts ...request.Option) (*AttachLoadBalancerToSubnetsOutput, error) { + req, out := c.AttachLoadBalancerToSubnetsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opConfigureHealthCheck = "ConfigureHealthCheck" @@ -312,8 +357,23 @@ func (c *ELB) ConfigureHealthCheckRequest(input *ConfigureHealthCheckInput) (req // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancing-2012-06-01/ConfigureHealthCheck func (c *ELB) ConfigureHealthCheck(input *ConfigureHealthCheckInput) (*ConfigureHealthCheckOutput, error) { req, out := c.ConfigureHealthCheckRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ConfigureHealthCheckWithContext is the same as ConfigureHealthCheck with the addition of +// the ability to pass a context and additional request options. +// +// See ConfigureHealthCheck 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 *ELB) ConfigureHealthCheckWithContext(ctx aws.Context, input *ConfigureHealthCheckInput, opts ...request.Option) (*ConfigureHealthCheckOutput, error) { + req, out := c.ConfigureHealthCheckRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateAppCookieStickinessPolicy = "CreateAppCookieStickinessPolicy" @@ -400,8 +460,23 @@ func (c *ELB) CreateAppCookieStickinessPolicyRequest(input *CreateAppCookieStick // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancing-2012-06-01/CreateAppCookieStickinessPolicy func (c *ELB) CreateAppCookieStickinessPolicy(input *CreateAppCookieStickinessPolicyInput) (*CreateAppCookieStickinessPolicyOutput, error) { req, out := c.CreateAppCookieStickinessPolicyRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateAppCookieStickinessPolicyWithContext is the same as CreateAppCookieStickinessPolicy with the addition of +// the ability to pass a context and additional request options. +// +// See CreateAppCookieStickinessPolicy 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 *ELB) CreateAppCookieStickinessPolicyWithContext(ctx aws.Context, input *CreateAppCookieStickinessPolicyInput, opts ...request.Option) (*CreateAppCookieStickinessPolicyOutput, error) { + req, out := c.CreateAppCookieStickinessPolicyRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateLBCookieStickinessPolicy = "CreateLBCookieStickinessPolicy" @@ -490,8 +565,23 @@ func (c *ELB) CreateLBCookieStickinessPolicyRequest(input *CreateLBCookieStickin // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancing-2012-06-01/CreateLBCookieStickinessPolicy func (c *ELB) CreateLBCookieStickinessPolicy(input *CreateLBCookieStickinessPolicyInput) (*CreateLBCookieStickinessPolicyOutput, error) { req, out := c.CreateLBCookieStickinessPolicyRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateLBCookieStickinessPolicyWithContext is the same as CreateLBCookieStickinessPolicy with the addition of +// the ability to pass a context and additional request options. +// +// See CreateLBCookieStickinessPolicy 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 *ELB) CreateLBCookieStickinessPolicyWithContext(ctx aws.Context, input *CreateLBCookieStickinessPolicyInput, opts ...request.Option) (*CreateLBCookieStickinessPolicyOutput, error) { + req, out := c.CreateLBCookieStickinessPolicyRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateLoadBalancer = "CreateLoadBalancer" @@ -601,8 +691,23 @@ func (c *ELB) CreateLoadBalancerRequest(input *CreateLoadBalancerInput) (req *re // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancing-2012-06-01/CreateLoadBalancer func (c *ELB) CreateLoadBalancer(input *CreateLoadBalancerInput) (*CreateLoadBalancerOutput, error) { req, out := c.CreateLoadBalancerRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateLoadBalancerWithContext is the same as CreateLoadBalancer with the addition of +// the ability to pass a context and additional request options. +// +// See CreateLoadBalancer 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 *ELB) CreateLoadBalancerWithContext(ctx aws.Context, input *CreateLoadBalancerInput, opts ...request.Option) (*CreateLoadBalancerOutput, error) { + req, out := c.CreateLoadBalancerRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateLoadBalancerListeners = "CreateLoadBalancerListeners" @@ -687,8 +792,23 @@ func (c *ELB) CreateLoadBalancerListenersRequest(input *CreateLoadBalancerListen // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancing-2012-06-01/CreateLoadBalancerListeners func (c *ELB) CreateLoadBalancerListeners(input *CreateLoadBalancerListenersInput) (*CreateLoadBalancerListenersOutput, error) { req, out := c.CreateLoadBalancerListenersRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateLoadBalancerListenersWithContext is the same as CreateLoadBalancerListeners with the addition of +// the ability to pass a context and additional request options. +// +// See CreateLoadBalancerListeners 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 *ELB) CreateLoadBalancerListenersWithContext(ctx aws.Context, input *CreateLoadBalancerListenersInput, opts ...request.Option) (*CreateLoadBalancerListenersOutput, error) { + req, out := c.CreateLoadBalancerListenersRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateLoadBalancerPolicy = "CreateLoadBalancerPolicy" @@ -768,8 +888,23 @@ func (c *ELB) CreateLoadBalancerPolicyRequest(input *CreateLoadBalancerPolicyInp // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancing-2012-06-01/CreateLoadBalancerPolicy func (c *ELB) CreateLoadBalancerPolicy(input *CreateLoadBalancerPolicyInput) (*CreateLoadBalancerPolicyOutput, error) { req, out := c.CreateLoadBalancerPolicyRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateLoadBalancerPolicyWithContext is the same as CreateLoadBalancerPolicy with the addition of +// the ability to pass a context and additional request options. +// +// See CreateLoadBalancerPolicy 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 *ELB) CreateLoadBalancerPolicyWithContext(ctx aws.Context, input *CreateLoadBalancerPolicyInput, opts ...request.Option) (*CreateLoadBalancerPolicyOutput, error) { + req, out := c.CreateLoadBalancerPolicyRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteLoadBalancer = "DeleteLoadBalancer" @@ -837,8 +972,23 @@ func (c *ELB) DeleteLoadBalancerRequest(input *DeleteLoadBalancerInput) (req *re // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancing-2012-06-01/DeleteLoadBalancer func (c *ELB) DeleteLoadBalancer(input *DeleteLoadBalancerInput) (*DeleteLoadBalancerOutput, error) { req, out := c.DeleteLoadBalancerRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteLoadBalancerWithContext is the same as DeleteLoadBalancer with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteLoadBalancer 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 *ELB) DeleteLoadBalancerWithContext(ctx aws.Context, input *DeleteLoadBalancerInput, opts ...request.Option) (*DeleteLoadBalancerOutput, error) { + req, out := c.DeleteLoadBalancerRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteLoadBalancerListeners = "DeleteLoadBalancerListeners" @@ -902,8 +1052,23 @@ func (c *ELB) DeleteLoadBalancerListenersRequest(input *DeleteLoadBalancerListen // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancing-2012-06-01/DeleteLoadBalancerListeners func (c *ELB) DeleteLoadBalancerListeners(input *DeleteLoadBalancerListenersInput) (*DeleteLoadBalancerListenersOutput, error) { req, out := c.DeleteLoadBalancerListenersRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteLoadBalancerListenersWithContext is the same as DeleteLoadBalancerListeners with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteLoadBalancerListeners 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 *ELB) DeleteLoadBalancerListenersWithContext(ctx aws.Context, input *DeleteLoadBalancerListenersInput, opts ...request.Option) (*DeleteLoadBalancerListenersOutput, error) { + req, out := c.DeleteLoadBalancerListenersRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteLoadBalancerPolicy = "DeleteLoadBalancerPolicy" @@ -971,8 +1136,23 @@ func (c *ELB) DeleteLoadBalancerPolicyRequest(input *DeleteLoadBalancerPolicyInp // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancing-2012-06-01/DeleteLoadBalancerPolicy func (c *ELB) DeleteLoadBalancerPolicy(input *DeleteLoadBalancerPolicyInput) (*DeleteLoadBalancerPolicyOutput, error) { req, out := c.DeleteLoadBalancerPolicyRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteLoadBalancerPolicyWithContext is the same as DeleteLoadBalancerPolicy with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteLoadBalancerPolicy 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 *ELB) DeleteLoadBalancerPolicyWithContext(ctx aws.Context, input *DeleteLoadBalancerPolicyInput, opts ...request.Option) (*DeleteLoadBalancerPolicyOutput, error) { + req, out := c.DeleteLoadBalancerPolicyRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeregisterInstancesFromLoadBalancer = "DeregisterInstancesFromLoadBalancer" @@ -1047,8 +1227,23 @@ func (c *ELB) DeregisterInstancesFromLoadBalancerRequest(input *DeregisterInstan // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancing-2012-06-01/DeregisterInstancesFromLoadBalancer func (c *ELB) DeregisterInstancesFromLoadBalancer(input *DeregisterInstancesFromLoadBalancerInput) (*DeregisterInstancesFromLoadBalancerOutput, error) { req, out := c.DeregisterInstancesFromLoadBalancerRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeregisterInstancesFromLoadBalancerWithContext is the same as DeregisterInstancesFromLoadBalancer with the addition of +// the ability to pass a context and additional request options. +// +// See DeregisterInstancesFromLoadBalancer 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 *ELB) DeregisterInstancesFromLoadBalancerWithContext(ctx aws.Context, input *DeregisterInstancesFromLoadBalancerInput, opts ...request.Option) (*DeregisterInstancesFromLoadBalancerOutput, error) { + req, out := c.DeregisterInstancesFromLoadBalancerRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeInstanceHealth = "DescribeInstanceHealth" @@ -1120,8 +1315,23 @@ func (c *ELB) DescribeInstanceHealthRequest(input *DescribeInstanceHealthInput) // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancing-2012-06-01/DescribeInstanceHealth func (c *ELB) DescribeInstanceHealth(input *DescribeInstanceHealthInput) (*DescribeInstanceHealthOutput, error) { req, out := c.DescribeInstanceHealthRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeInstanceHealthWithContext is the same as DescribeInstanceHealth with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeInstanceHealth 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 *ELB) DescribeInstanceHealthWithContext(ctx aws.Context, input *DescribeInstanceHealthInput, opts ...request.Option) (*DescribeInstanceHealthOutput, error) { + req, out := c.DescribeInstanceHealthRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeLoadBalancerAttributes = "DescribeLoadBalancerAttributes" @@ -1188,8 +1398,23 @@ func (c *ELB) DescribeLoadBalancerAttributesRequest(input *DescribeLoadBalancerA // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancing-2012-06-01/DescribeLoadBalancerAttributes func (c *ELB) DescribeLoadBalancerAttributes(input *DescribeLoadBalancerAttributesInput) (*DescribeLoadBalancerAttributesOutput, error) { req, out := c.DescribeLoadBalancerAttributesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeLoadBalancerAttributesWithContext is the same as DescribeLoadBalancerAttributes with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeLoadBalancerAttributes 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 *ELB) DescribeLoadBalancerAttributesWithContext(ctx aws.Context, input *DescribeLoadBalancerAttributesInput, opts ...request.Option) (*DescribeLoadBalancerAttributesOutput, error) { + req, out := c.DescribeLoadBalancerAttributesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeLoadBalancerPolicies = "DescribeLoadBalancerPolicies" @@ -1263,8 +1488,23 @@ func (c *ELB) DescribeLoadBalancerPoliciesRequest(input *DescribeLoadBalancerPol // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancing-2012-06-01/DescribeLoadBalancerPolicies func (c *ELB) DescribeLoadBalancerPolicies(input *DescribeLoadBalancerPoliciesInput) (*DescribeLoadBalancerPoliciesOutput, error) { req, out := c.DescribeLoadBalancerPoliciesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeLoadBalancerPoliciesWithContext is the same as DescribeLoadBalancerPolicies with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeLoadBalancerPolicies 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 *ELB) DescribeLoadBalancerPoliciesWithContext(ctx aws.Context, input *DescribeLoadBalancerPoliciesInput, opts ...request.Option) (*DescribeLoadBalancerPoliciesOutput, error) { + req, out := c.DescribeLoadBalancerPoliciesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeLoadBalancerPolicyTypes = "DescribeLoadBalancerPolicyTypes" @@ -1339,8 +1579,23 @@ func (c *ELB) DescribeLoadBalancerPolicyTypesRequest(input *DescribeLoadBalancer // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancing-2012-06-01/DescribeLoadBalancerPolicyTypes func (c *ELB) DescribeLoadBalancerPolicyTypes(input *DescribeLoadBalancerPolicyTypesInput) (*DescribeLoadBalancerPolicyTypesOutput, error) { req, out := c.DescribeLoadBalancerPolicyTypesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeLoadBalancerPolicyTypesWithContext is the same as DescribeLoadBalancerPolicyTypes with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeLoadBalancerPolicyTypes 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 *ELB) DescribeLoadBalancerPolicyTypesWithContext(ctx aws.Context, input *DescribeLoadBalancerPolicyTypesInput, opts ...request.Option) (*DescribeLoadBalancerPolicyTypesOutput, error) { + req, out := c.DescribeLoadBalancerPolicyTypesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeLoadBalancers = "DescribeLoadBalancers" @@ -1413,8 +1668,23 @@ func (c *ELB) DescribeLoadBalancersRequest(input *DescribeLoadBalancersInput) (r // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancing-2012-06-01/DescribeLoadBalancers func (c *ELB) DescribeLoadBalancers(input *DescribeLoadBalancersInput) (*DescribeLoadBalancersOutput, error) { req, out := c.DescribeLoadBalancersRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeLoadBalancersWithContext is the same as DescribeLoadBalancers with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeLoadBalancers 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 *ELB) DescribeLoadBalancersWithContext(ctx aws.Context, input *DescribeLoadBalancersInput, opts ...request.Option) (*DescribeLoadBalancersOutput, error) { + req, out := c.DescribeLoadBalancersRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // DescribeLoadBalancersPages iterates over the pages of a DescribeLoadBalancers operation, @@ -1434,12 +1704,37 @@ func (c *ELB) DescribeLoadBalancers(input *DescribeLoadBalancersInput) (*Describ // return pageNum <= 3 // }) // -func (c *ELB) DescribeLoadBalancersPages(input *DescribeLoadBalancersInput, fn func(p *DescribeLoadBalancersOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.DescribeLoadBalancersRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*DescribeLoadBalancersOutput), lastPage) - }) +func (c *ELB) DescribeLoadBalancersPages(input *DescribeLoadBalancersInput, fn func(*DescribeLoadBalancersOutput, bool) bool) error { + return c.DescribeLoadBalancersPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// DescribeLoadBalancersPagesWithContext same as DescribeLoadBalancersPages 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 *ELB) DescribeLoadBalancersPagesWithContext(ctx aws.Context, input *DescribeLoadBalancersInput, fn func(*DescribeLoadBalancersOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *DescribeLoadBalancersInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeLoadBalancersRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*DescribeLoadBalancersOutput), !p.HasNextPage()) + } + return p.Err() } const opDescribeTags = "DescribeTags" @@ -1503,8 +1798,23 @@ func (c *ELB) DescribeTagsRequest(input *DescribeTagsInput) (req *request.Reques // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancing-2012-06-01/DescribeTags func (c *ELB) DescribeTags(input *DescribeTagsInput) (*DescribeTagsOutput, error) { req, out := c.DescribeTagsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeTagsWithContext is the same as DescribeTags with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeTags 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 *ELB) DescribeTagsWithContext(ctx aws.Context, input *DescribeTagsInput, opts ...request.Option) (*DescribeTagsOutput, error) { + req, out := c.DescribeTagsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDetachLoadBalancerFromSubnets = "DetachLoadBalancerFromSubnets" @@ -1576,8 +1886,23 @@ func (c *ELB) DetachLoadBalancerFromSubnetsRequest(input *DetachLoadBalancerFrom // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancing-2012-06-01/DetachLoadBalancerFromSubnets func (c *ELB) DetachLoadBalancerFromSubnets(input *DetachLoadBalancerFromSubnetsInput) (*DetachLoadBalancerFromSubnetsOutput, error) { req, out := c.DetachLoadBalancerFromSubnetsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DetachLoadBalancerFromSubnetsWithContext is the same as DetachLoadBalancerFromSubnets with the addition of +// the ability to pass a context and additional request options. +// +// See DetachLoadBalancerFromSubnets 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 *ELB) DetachLoadBalancerFromSubnetsWithContext(ctx aws.Context, input *DetachLoadBalancerFromSubnetsInput, opts ...request.Option) (*DetachLoadBalancerFromSubnetsOutput, error) { + req, out := c.DetachLoadBalancerFromSubnetsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDisableAvailabilityZonesForLoadBalancer = "DisableAvailabilityZonesForLoadBalancer" @@ -1654,8 +1979,23 @@ func (c *ELB) DisableAvailabilityZonesForLoadBalancerRequest(input *DisableAvail // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancing-2012-06-01/DisableAvailabilityZonesForLoadBalancer func (c *ELB) DisableAvailabilityZonesForLoadBalancer(input *DisableAvailabilityZonesForLoadBalancerInput) (*DisableAvailabilityZonesForLoadBalancerOutput, error) { req, out := c.DisableAvailabilityZonesForLoadBalancerRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DisableAvailabilityZonesForLoadBalancerWithContext is the same as DisableAvailabilityZonesForLoadBalancer with the addition of +// the ability to pass a context and additional request options. +// +// See DisableAvailabilityZonesForLoadBalancer 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 *ELB) DisableAvailabilityZonesForLoadBalancerWithContext(ctx aws.Context, input *DisableAvailabilityZonesForLoadBalancerInput, opts ...request.Option) (*DisableAvailabilityZonesForLoadBalancerOutput, error) { + req, out := c.DisableAvailabilityZonesForLoadBalancerRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opEnableAvailabilityZonesForLoadBalancer = "EnableAvailabilityZonesForLoadBalancer" @@ -1726,8 +2066,23 @@ func (c *ELB) EnableAvailabilityZonesForLoadBalancerRequest(input *EnableAvailab // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancing-2012-06-01/EnableAvailabilityZonesForLoadBalancer func (c *ELB) EnableAvailabilityZonesForLoadBalancer(input *EnableAvailabilityZonesForLoadBalancerInput) (*EnableAvailabilityZonesForLoadBalancerOutput, error) { req, out := c.EnableAvailabilityZonesForLoadBalancerRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// EnableAvailabilityZonesForLoadBalancerWithContext is the same as EnableAvailabilityZonesForLoadBalancer with the addition of +// the ability to pass a context and additional request options. +// +// See EnableAvailabilityZonesForLoadBalancer 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 *ELB) EnableAvailabilityZonesForLoadBalancerWithContext(ctx aws.Context, input *EnableAvailabilityZonesForLoadBalancerInput, opts ...request.Option) (*EnableAvailabilityZonesForLoadBalancerOutput, error) { + req, out := c.EnableAvailabilityZonesForLoadBalancerRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opModifyLoadBalancerAttributes = "ModifyLoadBalancerAttributes" @@ -1812,8 +2167,23 @@ func (c *ELB) ModifyLoadBalancerAttributesRequest(input *ModifyLoadBalancerAttri // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancing-2012-06-01/ModifyLoadBalancerAttributes func (c *ELB) ModifyLoadBalancerAttributes(input *ModifyLoadBalancerAttributesInput) (*ModifyLoadBalancerAttributesOutput, error) { req, out := c.ModifyLoadBalancerAttributesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ModifyLoadBalancerAttributesWithContext is the same as ModifyLoadBalancerAttributes with the addition of +// the ability to pass a context and additional request options. +// +// See ModifyLoadBalancerAttributes 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 *ELB) ModifyLoadBalancerAttributesWithContext(ctx aws.Context, input *ModifyLoadBalancerAttributesInput, opts ...request.Option) (*ModifyLoadBalancerAttributesOutput, error) { + req, out := c.ModifyLoadBalancerAttributesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opRegisterInstancesWithLoadBalancer = "RegisterInstancesWithLoadBalancer" @@ -1902,8 +2272,23 @@ func (c *ELB) RegisterInstancesWithLoadBalancerRequest(input *RegisterInstancesW // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancing-2012-06-01/RegisterInstancesWithLoadBalancer func (c *ELB) RegisterInstancesWithLoadBalancer(input *RegisterInstancesWithLoadBalancerInput) (*RegisterInstancesWithLoadBalancerOutput, error) { req, out := c.RegisterInstancesWithLoadBalancerRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// RegisterInstancesWithLoadBalancerWithContext is the same as RegisterInstancesWithLoadBalancer with the addition of +// the ability to pass a context and additional request options. +// +// See RegisterInstancesWithLoadBalancer 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 *ELB) RegisterInstancesWithLoadBalancerWithContext(ctx aws.Context, input *RegisterInstancesWithLoadBalancerInput, opts ...request.Option) (*RegisterInstancesWithLoadBalancerOutput, error) { + req, out := c.RegisterInstancesWithLoadBalancerRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opRemoveTags = "RemoveTags" @@ -1967,8 +2352,23 @@ func (c *ELB) RemoveTagsRequest(input *RemoveTagsInput) (req *request.Request, o // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancing-2012-06-01/RemoveTags func (c *ELB) RemoveTags(input *RemoveTagsInput) (*RemoveTagsOutput, error) { req, out := c.RemoveTagsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// RemoveTagsWithContext is the same as RemoveTags with the addition of +// the ability to pass a context and additional request options. +// +// See RemoveTags 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 *ELB) RemoveTagsWithContext(ctx aws.Context, input *RemoveTagsInput, opts ...request.Option) (*RemoveTagsOutput, error) { + req, out := c.RemoveTagsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opSetLoadBalancerListenerSSLCertificate = "SetLoadBalancerListenerSSLCertificate" @@ -2052,8 +2452,23 @@ func (c *ELB) SetLoadBalancerListenerSSLCertificateRequest(input *SetLoadBalance // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancing-2012-06-01/SetLoadBalancerListenerSSLCertificate func (c *ELB) SetLoadBalancerListenerSSLCertificate(input *SetLoadBalancerListenerSSLCertificateInput) (*SetLoadBalancerListenerSSLCertificateOutput, error) { req, out := c.SetLoadBalancerListenerSSLCertificateRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// SetLoadBalancerListenerSSLCertificateWithContext is the same as SetLoadBalancerListenerSSLCertificate with the addition of +// the ability to pass a context and additional request options. +// +// See SetLoadBalancerListenerSSLCertificate 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 *ELB) SetLoadBalancerListenerSSLCertificateWithContext(ctx aws.Context, input *SetLoadBalancerListenerSSLCertificateInput, opts ...request.Option) (*SetLoadBalancerListenerSSLCertificateOutput, error) { + req, out := c.SetLoadBalancerListenerSSLCertificateRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opSetLoadBalancerPoliciesForBackendServer = "SetLoadBalancerPoliciesForBackendServer" @@ -2138,8 +2553,23 @@ func (c *ELB) SetLoadBalancerPoliciesForBackendServerRequest(input *SetLoadBalan // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancing-2012-06-01/SetLoadBalancerPoliciesForBackendServer func (c *ELB) SetLoadBalancerPoliciesForBackendServer(input *SetLoadBalancerPoliciesForBackendServerInput) (*SetLoadBalancerPoliciesForBackendServerOutput, error) { req, out := c.SetLoadBalancerPoliciesForBackendServerRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// SetLoadBalancerPoliciesForBackendServerWithContext is the same as SetLoadBalancerPoliciesForBackendServer with the addition of +// the ability to pass a context and additional request options. +// +// See SetLoadBalancerPoliciesForBackendServer 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 *ELB) SetLoadBalancerPoliciesForBackendServerWithContext(ctx aws.Context, input *SetLoadBalancerPoliciesForBackendServerInput, opts ...request.Option) (*SetLoadBalancerPoliciesForBackendServerOutput, error) { + req, out := c.SetLoadBalancerPoliciesForBackendServerRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opSetLoadBalancerPoliciesOfListener = "SetLoadBalancerPoliciesOfListener" @@ -2221,8 +2651,23 @@ func (c *ELB) SetLoadBalancerPoliciesOfListenerRequest(input *SetLoadBalancerPol // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancing-2012-06-01/SetLoadBalancerPoliciesOfListener func (c *ELB) SetLoadBalancerPoliciesOfListener(input *SetLoadBalancerPoliciesOfListenerInput) (*SetLoadBalancerPoliciesOfListenerOutput, error) { req, out := c.SetLoadBalancerPoliciesOfListenerRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// SetLoadBalancerPoliciesOfListenerWithContext is the same as SetLoadBalancerPoliciesOfListener with the addition of +// the ability to pass a context and additional request options. +// +// See SetLoadBalancerPoliciesOfListener 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 *ELB) SetLoadBalancerPoliciesOfListenerWithContext(ctx aws.Context, input *SetLoadBalancerPoliciesOfListenerInput, opts ...request.Option) (*SetLoadBalancerPoliciesOfListenerOutput, error) { + req, out := c.SetLoadBalancerPoliciesOfListenerRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // Information about the AccessLog attribute. diff --git a/vendor/github.com/aws/aws-sdk-go/service/elb/doc.go b/vendor/github.com/aws/aws-sdk-go/service/elb/doc.go new file mode 100644 index 000000000..5741768b1 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/service/elb/doc.go @@ -0,0 +1,106 @@ +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. + +// Package elb provides the client and types for making API +// requests to Elastic Load Balancing. +// +// A load balancer distributes incoming traffic across your EC2 instances. This +// enables you to increase the availability of your application. The load balancer +// also monitors the health of its registered instances and ensures that it +// routes traffic only to healthy instances. You configure your load balancer +// to accept incoming traffic by specifying one or more listeners, which are +// configured with a protocol and port number for connections from clients to +// the load balancer and a protocol and port number for connections from the +// load balancer to the instances. +// +// Elastic Load Balancing supports two types of load balancers: Classic load +// balancers and Application load balancers (new). A Classic load balancer makes +// routing and load balancing decisions either at the transport layer (TCP/SSL) +// or the application layer (HTTP/HTTPS), and supports either EC2-Classic or +// a VPC. An Application load balancer makes routing and load balancing decisions +// at the application layer (HTTP/HTTPS), supports path-based routing, and can +// route requests to one or more ports on each EC2 instance or container instance +// in your virtual private cloud (VPC). For more information, see the . +// +// This reference covers the 2012-06-01 API, which supports Classic load balancers. +// The 2015-12-01 API supports Application load balancers. +// +// To get started, create a load balancer with one or more listeners using CreateLoadBalancer. +// Register your instances with the load balancer using RegisterInstancesWithLoadBalancer. +// +// All Elastic Load Balancing operations are idempotent, which means that they +// complete at most one time. If you repeat an operation, it succeeds with a +// 200 OK response code. +// +// See https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancing-2012-06-01 for more information on this service. +// +// See elb package documentation for more information. +// https://docs.aws.amazon.com/sdk-for-go/api/service/elb/ +// +// Using the Client +// +// To use the client for Elastic Load Balancing you will first need +// to create a new instance of it. +// +// When creating a client for an AWS service you'll first need to have a Session +// already created. The Session provides configuration that can be shared +// between multiple service clients. Additional configuration can be applied to +// the Session and service's client when they are constructed. The aws package's +// Config type contains several fields such as Region for the AWS Region the +// client should make API requests too. The optional Config value can be provided +// as the variadic argument for Sessions and client creation. +// +// Once the service's client is created you can use it to make API requests the +// AWS service. These clients are safe to use concurrently. +// +// // Create a session to share configuration, and load external configuration. +// sess := session.Must(session.NewSession()) +// +// // Create the service's client with the session. +// svc := elb.New(sess) +// +// See the SDK's documentation for more information on how to use service clients. +// https://docs.aws.amazon.com/sdk-for-go/api/ +// +// See aws package's Config type for more information on configuration options. +// https://docs.aws.amazon.com/sdk-for-go/api/aws/#Config +// +// See the Elastic Load Balancing client ELB for more +// information on creating the service's client. +// https://docs.aws.amazon.com/sdk-for-go/api/service/elb/#New +// +// Once the client is created you can make an API request to the service. +// Each API method takes a input parameter, and returns the service response +// and an error. +// +// The API method will document which error codes the service can be returned +// by the operation if the service models the API operation's errors. These +// errors will also be available as const strings prefixed with "ErrCode". +// +// result, err := svc.AddTags(params) +// if err != nil { +// // Cast err to awserr.Error to handle specific error codes. +// aerr, ok := err.(awserr.Error) +// if ok && aerr.Code() == { +// // Specific error code handling +// } +// return err +// } +// +// fmt.Println("AddTags result:") +// fmt.Println(result) +// +// Using the Client with Context +// +// The service's client also provides methods to make API requests with a Context +// value. This allows you to control the timeout, and cancellation of pending +// requests. These methods also take request Option as variadic parameter to apply +// additional configuration to the API request. +// +// ctx := context.Background() +// +// result, err := svc.AddTagsWithContext(ctx, params) +// +// See the request package documentation for more information on using Context pattern +// with the SDK. +// https://docs.aws.amazon.com/sdk-for-go/api/aws/request/ +package elb diff --git a/vendor/github.com/aws/aws-sdk-go/service/elb/errors.go b/vendor/github.com/aws/aws-sdk-go/service/elb/errors.go index aab539987..97042c05a 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/elb/errors.go +++ b/vendor/github.com/aws/aws-sdk-go/service/elb/errors.go @@ -1,4 +1,4 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. package elb diff --git a/vendor/github.com/aws/aws-sdk-go/service/elb/service.go b/vendor/github.com/aws/aws-sdk-go/service/elb/service.go index 68d7e2ac0..057530f6c 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/elb/service.go +++ b/vendor/github.com/aws/aws-sdk-go/service/elb/service.go @@ -1,4 +1,4 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. package elb @@ -11,36 +11,12 @@ import ( "github.com/aws/aws-sdk-go/private/protocol/query" ) -// A load balancer distributes incoming traffic across your EC2 instances. This -// enables you to increase the availability of your application. The load balancer -// also monitors the health of its registered instances and ensures that it -// routes traffic only to healthy instances. You configure your load balancer -// to accept incoming traffic by specifying one or more listeners, which are -// configured with a protocol and port number for connections from clients to -// the load balancer and a protocol and port number for connections from the -// load balancer to the instances. +// ELB provides the API operation methods for making requests to +// Elastic Load Balancing. See this package's package overview docs +// for details on the service. // -// Elastic Load Balancing supports two types of load balancers: Classic load -// balancers and Application load balancers (new). A Classic load balancer makes -// routing and load balancing decisions either at the transport layer (TCP/SSL) -// or the application layer (HTTP/HTTPS), and supports either EC2-Classic or -// a VPC. An Application load balancer makes routing and load balancing decisions -// at the application layer (HTTP/HTTPS), supports path-based routing, and can -// route requests to one or more ports on each EC2 instance or container instance -// in your virtual private cloud (VPC). For more information, see the . -// -// This reference covers the 2012-06-01 API, which supports Classic load balancers. -// The 2015-12-01 API supports Application load balancers. -// -// To get started, create a load balancer with one or more listeners using CreateLoadBalancer. -// Register your instances with the load balancer using RegisterInstancesWithLoadBalancer. -// -// All Elastic Load Balancing operations are idempotent, which means that they -// complete at most one time. If you repeat an operation, it succeeds with a -// 200 OK response code. -// The service client's operations are safe to be used concurrently. -// It is not safe to mutate any of the client's properties though. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancing-2012-06-01 +// ELB methods are safe to use concurrently. It is not safe to +// modify mutate any of the struct's properties though. type ELB struct { *client.Client } diff --git a/vendor/github.com/aws/aws-sdk-go/service/elb/waiters.go b/vendor/github.com/aws/aws-sdk-go/service/elb/waiters.go index 89fc1d85b..aa0d7e157 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/elb/waiters.go +++ b/vendor/github.com/aws/aws-sdk-go/service/elb/waiters.go @@ -1,9 +1,12 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. package elb import ( - "github.com/aws/aws-sdk-go/private/waiter" + "time" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/request" ) // WaitUntilAnyInstanceInService uses the Elastic Load Balancing API operation @@ -11,26 +14,45 @@ import ( // If the condition is not meet within the max attempt window an error will // be returned. func (c *ELB) WaitUntilAnyInstanceInService(input *DescribeInstanceHealthInput) error { - waiterCfg := waiter.Config{ - Operation: "DescribeInstanceHealth", - Delay: 15, + return c.WaitUntilAnyInstanceInServiceWithContext(aws.BackgroundContext(), input) +} + +// WaitUntilAnyInstanceInServiceWithContext is an extended version of WaitUntilAnyInstanceInService. +// 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 *ELB) WaitUntilAnyInstanceInServiceWithContext(ctx aws.Context, input *DescribeInstanceHealthInput, opts ...request.WaiterOption) error { + w := request.Waiter{ + Name: "WaitUntilAnyInstanceInService", MaxAttempts: 40, - Acceptors: []waiter.WaitAcceptor{ + Delay: request.ConstantWaiterDelay(15 * time.Second), + Acceptors: []request.WaiterAcceptor{ { - State: "success", - Matcher: "pathAny", - Argument: "InstanceStates[].State", + State: request.SuccessWaiterState, + Matcher: request.PathAnyWaiterMatch, Argument: "InstanceStates[].State", Expected: "InService", }, }, + Logger: c.Config.Logger, + NewRequest: func(opts []request.Option) (*request.Request, error) { + var inCpy *DescribeInstanceHealthInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeInstanceHealthRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, } + w.ApplyOptions(opts...) - w := waiter.Waiter{ - Client: c, - Input: input, - Config: waiterCfg, - } - return w.Wait() + return w.WaitWithContext(ctx) } // WaitUntilInstanceDeregistered uses the Elastic Load Balancing API operation @@ -38,32 +60,50 @@ func (c *ELB) WaitUntilAnyInstanceInService(input *DescribeInstanceHealthInput) // If the condition is not meet within the max attempt window an error will // be returned. func (c *ELB) WaitUntilInstanceDeregistered(input *DescribeInstanceHealthInput) error { - waiterCfg := waiter.Config{ - Operation: "DescribeInstanceHealth", - Delay: 15, + return c.WaitUntilInstanceDeregisteredWithContext(aws.BackgroundContext(), input) +} + +// WaitUntilInstanceDeregisteredWithContext is an extended version of WaitUntilInstanceDeregistered. +// 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 *ELB) WaitUntilInstanceDeregisteredWithContext(ctx aws.Context, input *DescribeInstanceHealthInput, opts ...request.WaiterOption) error { + w := request.Waiter{ + Name: "WaitUntilInstanceDeregistered", MaxAttempts: 40, - Acceptors: []waiter.WaitAcceptor{ + Delay: request.ConstantWaiterDelay(15 * time.Second), + Acceptors: []request.WaiterAcceptor{ { - State: "success", - Matcher: "pathAll", - Argument: "InstanceStates[].State", + State: request.SuccessWaiterState, + Matcher: request.PathAllWaiterMatch, Argument: "InstanceStates[].State", Expected: "OutOfService", }, { - State: "success", - Matcher: "error", - Argument: "", + State: request.SuccessWaiterState, + Matcher: request.ErrorWaiterMatch, Expected: "InvalidInstance", }, }, + Logger: c.Config.Logger, + NewRequest: func(opts []request.Option) (*request.Request, error) { + var inCpy *DescribeInstanceHealthInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeInstanceHealthRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, } + w.ApplyOptions(opts...) - w := waiter.Waiter{ - Client: c, - Input: input, - Config: waiterCfg, - } - return w.Wait() + return w.WaitWithContext(ctx) } // WaitUntilInstanceInService uses the Elastic Load Balancing API operation @@ -71,24 +111,43 @@ func (c *ELB) WaitUntilInstanceDeregistered(input *DescribeInstanceHealthInput) // If the condition is not meet within the max attempt window an error will // be returned. func (c *ELB) WaitUntilInstanceInService(input *DescribeInstanceHealthInput) error { - waiterCfg := waiter.Config{ - Operation: "DescribeInstanceHealth", - Delay: 15, + return c.WaitUntilInstanceInServiceWithContext(aws.BackgroundContext(), input) +} + +// WaitUntilInstanceInServiceWithContext is an extended version of WaitUntilInstanceInService. +// 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 *ELB) WaitUntilInstanceInServiceWithContext(ctx aws.Context, input *DescribeInstanceHealthInput, opts ...request.WaiterOption) error { + w := request.Waiter{ + Name: "WaitUntilInstanceInService", MaxAttempts: 40, - Acceptors: []waiter.WaitAcceptor{ + Delay: request.ConstantWaiterDelay(15 * time.Second), + Acceptors: []request.WaiterAcceptor{ { - State: "success", - Matcher: "pathAll", - Argument: "InstanceStates[].State", + State: request.SuccessWaiterState, + Matcher: request.PathAllWaiterMatch, Argument: "InstanceStates[].State", Expected: "InService", }, }, + Logger: c.Config.Logger, + NewRequest: func(opts []request.Option) (*request.Request, error) { + var inCpy *DescribeInstanceHealthInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeInstanceHealthRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, } + w.ApplyOptions(opts...) - w := waiter.Waiter{ - Client: c, - Input: input, - Config: waiterCfg, - } - return w.Wait() + return w.WaitWithContext(ctx) } diff --git a/vendor/github.com/aws/aws-sdk-go/service/elbv2/api.go b/vendor/github.com/aws/aws-sdk-go/service/elbv2/api.go index 2098550c6..014ab7a5c 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/elbv2/api.go +++ b/vendor/github.com/aws/aws-sdk-go/service/elbv2/api.go @@ -1,12 +1,12 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. -// Package elbv2 provides a client for Elastic Load Balancing. package elbv2 import ( "fmt" "time" + "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awsutil" "github.com/aws/aws-sdk-go/aws/request" ) @@ -88,8 +88,23 @@ func (c *ELBV2) AddTagsRequest(input *AddTagsInput) (req *request.Request, outpu // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/AddTags func (c *ELBV2) AddTags(input *AddTagsInput) (*AddTagsOutput, error) { req, out := c.AddTagsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// AddTagsWithContext is the same as AddTags with the addition of +// the ability to pass a context and additional request options. +// +// See AddTags 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 *ELBV2) AddTagsWithContext(ctx aws.Context, input *AddTagsInput, opts ...request.Option) (*AddTagsOutput, error) { + req, out := c.AddTagsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateListener = "CreateListener" @@ -196,8 +211,23 @@ func (c *ELBV2) CreateListenerRequest(input *CreateListenerInput) (req *request. // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/CreateListener func (c *ELBV2) CreateListener(input *CreateListenerInput) (*CreateListenerOutput, error) { req, out := c.CreateListenerRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateListenerWithContext is the same as CreateListener with the addition of +// the ability to pass a context and additional request options. +// +// See CreateListener 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 *ELBV2) CreateListenerWithContext(ctx aws.Context, input *CreateListenerInput, opts ...request.Option) (*CreateListenerOutput, error) { + req, out := c.CreateListenerRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateLoadBalancer = "CreateLoadBalancer" @@ -272,7 +302,7 @@ func (c *ELBV2) CreateLoadBalancerRequest(input *CreateLoadBalancerInput) (req * // // Returned Error Codes: // * ErrCodeDuplicateLoadBalancerNameException "DuplicateLoadBalancerName" -// A load balancer with the specified name already exists for this account. +// A load balancer with the specified name already exists. // // * ErrCodeTooManyLoadBalancersException "TooManyLoadBalancers" // You've reached the limit on the number of load balancers for your AWS account. @@ -301,8 +331,23 @@ func (c *ELBV2) CreateLoadBalancerRequest(input *CreateLoadBalancerInput) (req * // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/CreateLoadBalancer func (c *ELBV2) CreateLoadBalancer(input *CreateLoadBalancerInput) (*CreateLoadBalancerOutput, error) { req, out := c.CreateLoadBalancerRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateLoadBalancerWithContext is the same as CreateLoadBalancer with the addition of +// the ability to pass a context and additional request options. +// +// See CreateLoadBalancer 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 *ELBV2) CreateLoadBalancerWithContext(ctx aws.Context, input *CreateLoadBalancerInput, opts ...request.Option) (*CreateLoadBalancerOutput, error) { + req, out := c.CreateLoadBalancerRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateRule = "CreateRule" @@ -399,8 +444,23 @@ func (c *ELBV2) CreateRuleRequest(input *CreateRuleInput) (req *request.Request, // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/CreateRule func (c *ELBV2) CreateRule(input *CreateRuleInput) (*CreateRuleOutput, error) { req, out := c.CreateRuleRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateRuleWithContext is the same as CreateRule with the addition of +// the ability to pass a context and additional request options. +// +// See CreateRule 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 *ELBV2) CreateRuleWithContext(ctx aws.Context, input *CreateRuleInput, opts ...request.Option) (*CreateRuleOutput, error) { + req, out := c.CreateRuleRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateTargetGroup = "CreateTargetGroup" @@ -480,8 +540,23 @@ func (c *ELBV2) CreateTargetGroupRequest(input *CreateTargetGroupInput) (req *re // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/CreateTargetGroup func (c *ELBV2) CreateTargetGroup(input *CreateTargetGroupInput) (*CreateTargetGroupOutput, error) { req, out := c.CreateTargetGroupRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateTargetGroupWithContext is the same as CreateTargetGroup with the addition of +// the ability to pass a context and additional request options. +// +// See CreateTargetGroup 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 *ELBV2) CreateTargetGroupWithContext(ctx aws.Context, input *CreateTargetGroupInput, opts ...request.Option) (*CreateTargetGroupOutput, error) { + req, out := c.CreateTargetGroupRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteListener = "DeleteListener" @@ -548,8 +623,23 @@ func (c *ELBV2) DeleteListenerRequest(input *DeleteListenerInput) (req *request. // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/DeleteListener func (c *ELBV2) DeleteListener(input *DeleteListenerInput) (*DeleteListenerOutput, error) { req, out := c.DeleteListenerRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteListenerWithContext is the same as DeleteListener with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteListener 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 *ELBV2) DeleteListenerWithContext(ctx aws.Context, input *DeleteListenerInput, opts ...request.Option) (*DeleteListenerOutput, error) { + req, out := c.DeleteListenerRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteLoadBalancer = "DeleteLoadBalancer" @@ -624,8 +714,23 @@ func (c *ELBV2) DeleteLoadBalancerRequest(input *DeleteLoadBalancerInput) (req * // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/DeleteLoadBalancer func (c *ELBV2) DeleteLoadBalancer(input *DeleteLoadBalancerInput) (*DeleteLoadBalancerOutput, error) { req, out := c.DeleteLoadBalancerRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteLoadBalancerWithContext is the same as DeleteLoadBalancer with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteLoadBalancer 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 *ELBV2) DeleteLoadBalancerWithContext(ctx aws.Context, input *DeleteLoadBalancerInput, opts ...request.Option) (*DeleteLoadBalancerOutput, error) { + req, out := c.DeleteLoadBalancerRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteRule = "DeleteRule" @@ -692,8 +797,23 @@ func (c *ELBV2) DeleteRuleRequest(input *DeleteRuleInput) (req *request.Request, // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/DeleteRule func (c *ELBV2) DeleteRule(input *DeleteRuleInput) (*DeleteRuleOutput, error) { req, out := c.DeleteRuleRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteRuleWithContext is the same as DeleteRule with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteRule 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 *ELBV2) DeleteRuleWithContext(ctx aws.Context, input *DeleteRuleInput, opts ...request.Option) (*DeleteRuleOutput, error) { + req, out := c.DeleteRuleRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteTargetGroup = "DeleteTargetGroup" @@ -760,8 +880,23 @@ func (c *ELBV2) DeleteTargetGroupRequest(input *DeleteTargetGroupInput) (req *re // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/DeleteTargetGroup func (c *ELBV2) DeleteTargetGroup(input *DeleteTargetGroupInput) (*DeleteTargetGroupOutput, error) { req, out := c.DeleteTargetGroupRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteTargetGroupWithContext is the same as DeleteTargetGroup with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteTargetGroup 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 *ELBV2) DeleteTargetGroupWithContext(ctx aws.Context, input *DeleteTargetGroupInput, opts ...request.Option) (*DeleteTargetGroupOutput, error) { + req, out := c.DeleteTargetGroupRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeregisterTargets = "DeregisterTargets" @@ -831,8 +966,23 @@ func (c *ELBV2) DeregisterTargetsRequest(input *DeregisterTargetsInput) (req *re // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/DeregisterTargets func (c *ELBV2) DeregisterTargets(input *DeregisterTargetsInput) (*DeregisterTargetsOutput, error) { req, out := c.DeregisterTargetsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeregisterTargetsWithContext is the same as DeregisterTargets with the addition of +// the ability to pass a context and additional request options. +// +// See DeregisterTargets 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 *ELBV2) DeregisterTargetsWithContext(ctx aws.Context, input *DeregisterTargetsInput, opts ...request.Option) (*DeregisterTargetsOutput, error) { + req, out := c.DeregisterTargetsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeListeners = "DescribeListeners" @@ -906,8 +1056,23 @@ func (c *ELBV2) DescribeListenersRequest(input *DescribeListenersInput) (req *re // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/DescribeListeners func (c *ELBV2) DescribeListeners(input *DescribeListenersInput) (*DescribeListenersOutput, error) { req, out := c.DescribeListenersRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeListenersWithContext is the same as DescribeListeners with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeListeners 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 *ELBV2) DescribeListenersWithContext(ctx aws.Context, input *DescribeListenersInput, opts ...request.Option) (*DescribeListenersOutput, error) { + req, out := c.DescribeListenersRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // DescribeListenersPages iterates over the pages of a DescribeListeners operation, @@ -927,12 +1092,37 @@ func (c *ELBV2) DescribeListeners(input *DescribeListenersInput) (*DescribeListe // return pageNum <= 3 // }) // -func (c *ELBV2) DescribeListenersPages(input *DescribeListenersInput, fn func(p *DescribeListenersOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.DescribeListenersRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*DescribeListenersOutput), lastPage) - }) +func (c *ELBV2) DescribeListenersPages(input *DescribeListenersInput, fn func(*DescribeListenersOutput, bool) bool) error { + return c.DescribeListenersPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// DescribeListenersPagesWithContext same as DescribeListenersPages 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 *ELBV2) DescribeListenersPagesWithContext(ctx aws.Context, input *DescribeListenersInput, fn func(*DescribeListenersOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *DescribeListenersInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeListenersRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*DescribeListenersOutput), !p.HasNextPage()) + } + return p.Err() } const opDescribeLoadBalancerAttributes = "DescribeLoadBalancerAttributes" @@ -996,8 +1186,23 @@ func (c *ELBV2) DescribeLoadBalancerAttributesRequest(input *DescribeLoadBalance // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/DescribeLoadBalancerAttributes func (c *ELBV2) DescribeLoadBalancerAttributes(input *DescribeLoadBalancerAttributesInput) (*DescribeLoadBalancerAttributesOutput, error) { req, out := c.DescribeLoadBalancerAttributesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeLoadBalancerAttributesWithContext is the same as DescribeLoadBalancerAttributes with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeLoadBalancerAttributes 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 *ELBV2) DescribeLoadBalancerAttributesWithContext(ctx aws.Context, input *DescribeLoadBalancerAttributesInput, opts ...request.Option) (*DescribeLoadBalancerAttributesOutput, error) { + req, out := c.DescribeLoadBalancerAttributesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeLoadBalancers = "DescribeLoadBalancers" @@ -1071,8 +1276,23 @@ func (c *ELBV2) DescribeLoadBalancersRequest(input *DescribeLoadBalancersInput) // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/DescribeLoadBalancers func (c *ELBV2) DescribeLoadBalancers(input *DescribeLoadBalancersInput) (*DescribeLoadBalancersOutput, error) { req, out := c.DescribeLoadBalancersRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeLoadBalancersWithContext is the same as DescribeLoadBalancers with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeLoadBalancers 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 *ELBV2) DescribeLoadBalancersWithContext(ctx aws.Context, input *DescribeLoadBalancersInput, opts ...request.Option) (*DescribeLoadBalancersOutput, error) { + req, out := c.DescribeLoadBalancersRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // DescribeLoadBalancersPages iterates over the pages of a DescribeLoadBalancers operation, @@ -1092,12 +1312,37 @@ func (c *ELBV2) DescribeLoadBalancers(input *DescribeLoadBalancersInput) (*Descr // return pageNum <= 3 // }) // -func (c *ELBV2) DescribeLoadBalancersPages(input *DescribeLoadBalancersInput, fn func(p *DescribeLoadBalancersOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.DescribeLoadBalancersRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*DescribeLoadBalancersOutput), lastPage) - }) +func (c *ELBV2) DescribeLoadBalancersPages(input *DescribeLoadBalancersInput, fn func(*DescribeLoadBalancersOutput, bool) bool) error { + return c.DescribeLoadBalancersPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// DescribeLoadBalancersPagesWithContext same as DescribeLoadBalancersPages 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 *ELBV2) DescribeLoadBalancersPagesWithContext(ctx aws.Context, input *DescribeLoadBalancersInput, fn func(*DescribeLoadBalancersOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *DescribeLoadBalancersInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeLoadBalancersRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*DescribeLoadBalancersOutput), !p.HasNextPage()) + } + return p.Err() } const opDescribeRules = "DescribeRules" @@ -1165,8 +1410,23 @@ func (c *ELBV2) DescribeRulesRequest(input *DescribeRulesInput) (req *request.Re // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/DescribeRules func (c *ELBV2) DescribeRules(input *DescribeRulesInput) (*DescribeRulesOutput, error) { req, out := c.DescribeRulesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeRulesWithContext is the same as DescribeRules with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeRules 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 *ELBV2) DescribeRulesWithContext(ctx aws.Context, input *DescribeRulesInput, opts ...request.Option) (*DescribeRulesOutput, error) { + req, out := c.DescribeRulesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeSSLPolicies = "DescribeSSLPolicies" @@ -1216,7 +1476,8 @@ func (c *ELBV2) DescribeSSLPoliciesRequest(input *DescribeSSLPoliciesInput) (req // // Describes the specified policies or all policies used for SSL negotiation. // -// Note that the only supported policy at this time is ELBSecurityPolicy-2015-05. +// For more information, see Security Policies (http://docs.aws.amazon.com/elasticloadbalancing/latest/application/create-https-listener.html#describe-ssl-policies) +// in the Application Load Balancers 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 @@ -1232,8 +1493,23 @@ func (c *ELBV2) DescribeSSLPoliciesRequest(input *DescribeSSLPoliciesInput) (req // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/DescribeSSLPolicies func (c *ELBV2) DescribeSSLPolicies(input *DescribeSSLPoliciesInput) (*DescribeSSLPoliciesOutput, error) { req, out := c.DescribeSSLPoliciesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeSSLPoliciesWithContext is the same as DescribeSSLPolicies with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeSSLPolicies 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 *ELBV2) DescribeSSLPoliciesWithContext(ctx aws.Context, input *DescribeSSLPoliciesInput, opts ...request.Option) (*DescribeSSLPoliciesOutput, error) { + req, out := c.DescribeSSLPoliciesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeTags = "DescribeTags" @@ -1281,7 +1557,8 @@ func (c *ELBV2) DescribeTagsRequest(input *DescribeTagsInput) (req *request.Requ // DescribeTags API operation for Elastic Load Balancing. // -// Describes the tags for the specified resources. +// Describes the tags for the specified resources. You can describe the tags +// for one or more Application Load Balancers and target groups. // // 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 @@ -1306,8 +1583,23 @@ func (c *ELBV2) DescribeTagsRequest(input *DescribeTagsInput) (req *request.Requ // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/DescribeTags func (c *ELBV2) DescribeTags(input *DescribeTagsInput) (*DescribeTagsOutput, error) { req, out := c.DescribeTagsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeTagsWithContext is the same as DescribeTags with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeTags 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 *ELBV2) DescribeTagsWithContext(ctx aws.Context, input *DescribeTagsInput, opts ...request.Option) (*DescribeTagsOutput, error) { + req, out := c.DescribeTagsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeTargetGroupAttributes = "DescribeTargetGroupAttributes" @@ -1371,8 +1663,23 @@ func (c *ELBV2) DescribeTargetGroupAttributesRequest(input *DescribeTargetGroupA // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/DescribeTargetGroupAttributes func (c *ELBV2) DescribeTargetGroupAttributes(input *DescribeTargetGroupAttributesInput) (*DescribeTargetGroupAttributesOutput, error) { req, out := c.DescribeTargetGroupAttributesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeTargetGroupAttributesWithContext is the same as DescribeTargetGroupAttributes with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeTargetGroupAttributes 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 *ELBV2) DescribeTargetGroupAttributesWithContext(ctx aws.Context, input *DescribeTargetGroupAttributesInput, opts ...request.Option) (*DescribeTargetGroupAttributesOutput, error) { + req, out := c.DescribeTargetGroupAttributesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeTargetGroups = "DescribeTargetGroups" @@ -1451,8 +1758,23 @@ func (c *ELBV2) DescribeTargetGroupsRequest(input *DescribeTargetGroupsInput) (r // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/DescribeTargetGroups func (c *ELBV2) DescribeTargetGroups(input *DescribeTargetGroupsInput) (*DescribeTargetGroupsOutput, error) { req, out := c.DescribeTargetGroupsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeTargetGroupsWithContext is the same as DescribeTargetGroups with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeTargetGroups 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 *ELBV2) DescribeTargetGroupsWithContext(ctx aws.Context, input *DescribeTargetGroupsInput, opts ...request.Option) (*DescribeTargetGroupsOutput, error) { + req, out := c.DescribeTargetGroupsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // DescribeTargetGroupsPages iterates over the pages of a DescribeTargetGroups operation, @@ -1472,12 +1794,37 @@ func (c *ELBV2) DescribeTargetGroups(input *DescribeTargetGroupsInput) (*Describ // return pageNum <= 3 // }) // -func (c *ELBV2) DescribeTargetGroupsPages(input *DescribeTargetGroupsInput, fn func(p *DescribeTargetGroupsOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.DescribeTargetGroupsRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*DescribeTargetGroupsOutput), lastPage) - }) +func (c *ELBV2) DescribeTargetGroupsPages(input *DescribeTargetGroupsInput, fn func(*DescribeTargetGroupsOutput, bool) bool) error { + return c.DescribeTargetGroupsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// DescribeTargetGroupsPagesWithContext same as DescribeTargetGroupsPages 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 *ELBV2) DescribeTargetGroupsPagesWithContext(ctx aws.Context, input *DescribeTargetGroupsInput, fn func(*DescribeTargetGroupsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *DescribeTargetGroupsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeTargetGroupsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*DescribeTargetGroupsOutput), !p.HasNextPage()) + } + return p.Err() } const opDescribeTargetHealth = "DescribeTargetHealth" @@ -1549,8 +1896,23 @@ func (c *ELBV2) DescribeTargetHealthRequest(input *DescribeTargetHealthInput) (r // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/DescribeTargetHealth func (c *ELBV2) DescribeTargetHealth(input *DescribeTargetHealthInput) (*DescribeTargetHealthOutput, error) { req, out := c.DescribeTargetHealthRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeTargetHealthWithContext is the same as DescribeTargetHealth with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeTargetHealth 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 *ELBV2) DescribeTargetHealthWithContext(ctx aws.Context, input *DescribeTargetHealthInput, opts ...request.Option) (*DescribeTargetHealthOutput, error) { + req, out := c.DescribeTargetHealthRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opModifyListener = "ModifyListener" @@ -1603,7 +1965,7 @@ func (c *ELBV2) ModifyListenerRequest(input *ModifyListenerInput) (req *request. // Any properties that you do not specify retain their current values. However, // changing the protocol from HTTPS to HTTP removes the security policy and // SSL certificate properties. If you change the protocol from HTTP to HTTPS, -// you must add the security policy. +// you must add the security policy and server certificate. // // 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 @@ -1653,8 +2015,23 @@ func (c *ELBV2) ModifyListenerRequest(input *ModifyListenerInput) (req *request. // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/ModifyListener func (c *ELBV2) ModifyListener(input *ModifyListenerInput) (*ModifyListenerOutput, error) { req, out := c.ModifyListenerRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ModifyListenerWithContext is the same as ModifyListener with the addition of +// the ability to pass a context and additional request options. +// +// See ModifyListener 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 *ELBV2) ModifyListenerWithContext(ctx aws.Context, input *ModifyListenerInput, opts ...request.Option) (*ModifyListenerOutput, error) { + req, out := c.ModifyListenerRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opModifyLoadBalancerAttributes = "ModifyLoadBalancerAttributes" @@ -1725,8 +2102,23 @@ func (c *ELBV2) ModifyLoadBalancerAttributesRequest(input *ModifyLoadBalancerAtt // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/ModifyLoadBalancerAttributes func (c *ELBV2) ModifyLoadBalancerAttributes(input *ModifyLoadBalancerAttributesInput) (*ModifyLoadBalancerAttributesOutput, error) { req, out := c.ModifyLoadBalancerAttributesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ModifyLoadBalancerAttributesWithContext is the same as ModifyLoadBalancerAttributes with the addition of +// the ability to pass a context and additional request options. +// +// See ModifyLoadBalancerAttributes 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 *ELBV2) ModifyLoadBalancerAttributesWithContext(ctx aws.Context, input *ModifyLoadBalancerAttributesInput, opts ...request.Option) (*ModifyLoadBalancerAttributesOutput, error) { + req, out := c.ModifyLoadBalancerAttributesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opModifyRule = "ModifyRule" @@ -1804,8 +2196,23 @@ func (c *ELBV2) ModifyRuleRequest(input *ModifyRuleInput) (req *request.Request, // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/ModifyRule func (c *ELBV2) ModifyRule(input *ModifyRuleInput) (*ModifyRuleOutput, error) { req, out := c.ModifyRuleRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ModifyRuleWithContext is the same as ModifyRule with the addition of +// the ability to pass a context and additional request options. +// +// See ModifyRule 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 *ELBV2) ModifyRuleWithContext(ctx aws.Context, input *ModifyRuleInput, opts ...request.Option) (*ModifyRuleOutput, error) { + req, out := c.ModifyRuleRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opModifyTargetGroup = "ModifyTargetGroup" @@ -1872,8 +2279,23 @@ func (c *ELBV2) ModifyTargetGroupRequest(input *ModifyTargetGroupInput) (req *re // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/ModifyTargetGroup func (c *ELBV2) ModifyTargetGroup(input *ModifyTargetGroupInput) (*ModifyTargetGroupOutput, error) { req, out := c.ModifyTargetGroupRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ModifyTargetGroupWithContext is the same as ModifyTargetGroup with the addition of +// the ability to pass a context and additional request options. +// +// See ModifyTargetGroup 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 *ELBV2) ModifyTargetGroupWithContext(ctx aws.Context, input *ModifyTargetGroupInput, opts ...request.Option) (*ModifyTargetGroupOutput, error) { + req, out := c.ModifyTargetGroupRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opModifyTargetGroupAttributes = "ModifyTargetGroupAttributes" @@ -1937,8 +2359,23 @@ func (c *ELBV2) ModifyTargetGroupAttributesRequest(input *ModifyTargetGroupAttri // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/ModifyTargetGroupAttributes func (c *ELBV2) ModifyTargetGroupAttributes(input *ModifyTargetGroupAttributesInput) (*ModifyTargetGroupAttributesOutput, error) { req, out := c.ModifyTargetGroupAttributesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ModifyTargetGroupAttributesWithContext is the same as ModifyTargetGroupAttributes with the addition of +// the ability to pass a context and additional request options. +// +// See ModifyTargetGroupAttributes 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 *ELBV2) ModifyTargetGroupAttributesWithContext(ctx aws.Context, input *ModifyTargetGroupAttributesInput, opts ...request.Option) (*ModifyTargetGroupAttributesOutput, error) { + req, out := c.ModifyTargetGroupAttributesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opRegisterTargets = "RegisterTargets" @@ -2023,8 +2460,23 @@ func (c *ELBV2) RegisterTargetsRequest(input *RegisterTargetsInput) (req *reques // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/RegisterTargets func (c *ELBV2) RegisterTargets(input *RegisterTargetsInput) (*RegisterTargetsOutput, error) { req, out := c.RegisterTargetsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// RegisterTargetsWithContext is the same as RegisterTargets with the addition of +// the ability to pass a context and additional request options. +// +// See RegisterTargets 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 *ELBV2) RegisterTargetsWithContext(ctx aws.Context, input *RegisterTargetsInput, opts ...request.Option) (*RegisterTargetsOutput, error) { + req, out := c.RegisterTargetsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opRemoveTags = "RemoveTags" @@ -2102,8 +2554,23 @@ func (c *ELBV2) RemoveTagsRequest(input *RemoveTagsInput) (req *request.Request, // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/RemoveTags func (c *ELBV2) RemoveTags(input *RemoveTagsInput) (*RemoveTagsOutput, error) { req, out := c.RemoveTagsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// RemoveTagsWithContext is the same as RemoveTags with the addition of +// the ability to pass a context and additional request options. +// +// See RemoveTags 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 *ELBV2) RemoveTagsWithContext(ctx aws.Context, input *RemoveTagsInput, opts ...request.Option) (*RemoveTagsOutput, error) { + req, out := c.RemoveTagsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opSetIpAddressType = "SetIpAddressType" @@ -2174,8 +2641,23 @@ func (c *ELBV2) SetIpAddressTypeRequest(input *SetIpAddressTypeInput) (req *requ // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/SetIpAddressType func (c *ELBV2) SetIpAddressType(input *SetIpAddressTypeInput) (*SetIpAddressTypeOutput, error) { req, out := c.SetIpAddressTypeRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// SetIpAddressTypeWithContext is the same as SetIpAddressType with the addition of +// the ability to pass a context and additional request options. +// +// See SetIpAddressType 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 *ELBV2) SetIpAddressTypeWithContext(ctx aws.Context, input *SetIpAddressTypeInput, opts ...request.Option) (*SetIpAddressTypeOutput, error) { + req, out := c.SetIpAddressTypeRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opSetRulePriorities = "SetRulePriorities" @@ -2249,8 +2731,23 @@ func (c *ELBV2) SetRulePrioritiesRequest(input *SetRulePrioritiesInput) (req *re // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/SetRulePriorities func (c *ELBV2) SetRulePriorities(input *SetRulePrioritiesInput) (*SetRulePrioritiesOutput, error) { req, out := c.SetRulePrioritiesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// SetRulePrioritiesWithContext is the same as SetRulePriorities with the addition of +// the ability to pass a context and additional request options. +// +// See SetRulePriorities 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 *ELBV2) SetRulePrioritiesWithContext(ctx aws.Context, input *SetRulePrioritiesInput, opts ...request.Option) (*SetRulePrioritiesOutput, error) { + req, out := c.SetRulePrioritiesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opSetSecurityGroups = "SetSecurityGroups" @@ -2322,8 +2819,23 @@ func (c *ELBV2) SetSecurityGroupsRequest(input *SetSecurityGroupsInput) (req *re // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/SetSecurityGroups func (c *ELBV2) SetSecurityGroups(input *SetSecurityGroupsInput) (*SetSecurityGroupsOutput, error) { req, out := c.SetSecurityGroupsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// SetSecurityGroupsWithContext is the same as SetSecurityGroups with the addition of +// the ability to pass a context and additional request options. +// +// See SetSecurityGroups 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 *ELBV2) SetSecurityGroupsWithContext(ctx aws.Context, input *SetSecurityGroupsInput, opts ...request.Option) (*SetSecurityGroupsOutput, error) { + req, out := c.SetSecurityGroupsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opSetSubnets = "SetSubnets" @@ -2397,8 +2909,23 @@ func (c *ELBV2) SetSubnetsRequest(input *SetSubnetsInput) (req *request.Request, // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/SetSubnets func (c *ELBV2) SetSubnets(input *SetSubnetsInput) (*SetSubnetsOutput, error) { req, out := c.SetSubnetsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// SetSubnetsWithContext is the same as SetSubnets with the addition of +// the ability to pass a context and additional request options. +// +// See SetSubnets 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 *ELBV2) SetSubnetsWithContext(ctx aws.Context, input *SetSubnetsInput, opts ...request.Option) (*SetSubnetsOutput, error) { + req, out := c.SetSubnetsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // Information about an action. @@ -2778,7 +3305,7 @@ type CreateLoadBalancerInput struct { // The name of the load balancer. // - // This name must be unique within your AWS account, can have a maximum of 32 + // This name must be unique per region per account, can have a maximum of 32 // characters, must contain only alphanumeric characters or hyphens, and must // not begin or end with a hyphen. // @@ -2920,10 +3447,25 @@ type CreateRuleInput struct { // Actions is a required field Actions []*Action `type:"list" required:"true"` - // A condition. Each condition has the field path-pattern and specifies one - // path pattern. A path pattern is case sensitive, can be up to 128 characters - // in length, and can contain any of the following characters. Note that you - // can include up to three wildcard characters in a path pattern. + // A condition. Each condition specifies a field name and a single value. + // + // If the field name is host-header, you can specify a single host name (for + // example, my.example.com). A host name is case insensitive, can be up to 128 + // characters in length, and can contain any of the following characters. Note + // that you can include up to three wildcard characters. + // + // * A-Z, a-z, 0-9 + // + // * - . + // + // * * (matches 0 or more characters) + // + // * ? (matches exactly 1 character) + // + // If the field name is path-pattern, you can specify a single path pattern. + // A path pattern is case sensitive, can be up to 128 characters in length, + // and can contain any of the following characters. Note that you can include + // up to three wildcard characters. // // * A-Z, a-z, 0-9 // @@ -3078,6 +3620,10 @@ type CreateTargetGroupInput struct { // The name of the target group. // + // This name must be unique per region per account, can have a maximum of 32 + // characters, must contain only alphanumeric characters or hyphens, and must + // not begin or end with a hyphen. + // // Name is a required field Name *string `type:"string" required:"true"` @@ -3714,7 +4260,8 @@ func (s *DescribeLoadBalancerAttributesOutput) SetAttributes(v []*LoadBalancerAt type DescribeLoadBalancersInput struct { _ struct{} `type:"structure"` - // The Amazon Resource Names (ARN) of the load balancers. + // The Amazon Resource Names (ARN) of the load balancers. You can specify up + // to 20 load balancers in a single call. LoadBalancerArns []*string `type:"list"` // The marker for the next set of results. (You received this marker from a @@ -4580,8 +5127,9 @@ func (s *LoadBalancerState) SetReason(v string) *LoadBalancerState { type Matcher struct { _ struct{} `type:"structure"` - // The HTTP codes. The default value is 200. You can specify multiple values - // (for example, "200,202") or a range of values (for example, "200-299"). + // The HTTP codes. You can specify values between 200 and 499. The default value + // is 200. You can specify multiple values (for example, "200,202") or a range + // of values (for example, "200-299"). // // HttpCode is a required field HttpCode *string `type:"string" required:"true"` @@ -4637,7 +5185,9 @@ type ModifyListenerInput struct { // The protocol for connections from clients to the load balancer. Protocol *string `type:"string" enum:"ProtocolEnum"` - // The security policy that defines which ciphers and protocols are supported. + // The security policy that defines which protocols and ciphers are supported. + // For more information, see Security Policies (http://docs.aws.amazon.com/elasticloadbalancing/latest/application/create-https-listener.html#describe-ssl-policies) + // in the Application Load Balancers Guide. SslPolicy *string `type:"string"` } @@ -5355,14 +5905,28 @@ func (s *Rule) SetRuleArn(v string) *Rule { type RuleCondition struct { _ struct{} `type:"structure"` - // The only possible value is path-pattern. + // The name of the field. The possible values are host-header and path-pattern. Field *string `type:"string"` - // The path pattern. You can specify a single path pattern. + // The condition value. // - // A path pattern is case sensitive, can be up to 128 characters in length, - // and can contain any of the following characters. Note that you can include - // up to three wildcard characters in a path pattern. + // If the field name is host-header, you can specify a single host name (for + // example, my.example.com). A host name is case insensitive, can be up to 128 + // characters in length, and can contain any of the following characters. Note + // that you can include up to three wildcard characters. + // + // * A-Z, a-z, 0-9 + // + // * - . + // + // * * (matches 0 or more characters) + // + // * ? (matches exactly 1 character) + // + // If the field name is path-pattern, you can specify a single path pattern + // (for example, /img/*). A path pattern is case sensitive, can be up to 128 + // characters in length, and can contain any of the following characters. Note + // that you can include up to three wildcard characters. // // * A-Z, a-z, 0-9 // diff --git a/vendor/github.com/aws/aws-sdk-go/service/elbv2/doc.go b/vendor/github.com/aws/aws-sdk-go/service/elbv2/doc.go new file mode 100644 index 000000000..4c8224cc9 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/service/elbv2/doc.go @@ -0,0 +1,125 @@ +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. + +// Package elbv2 provides the client and types for making API +// requests to Elastic Load Balancing. +// +// A load balancer distributes incoming traffic across targets, such as your +// EC2 instances. This enables you to increase the availability of your application. +// The load balancer also monitors the health of its registered targets and +// ensures that it routes traffic only to healthy targets. You configure your +// load balancer to accept incoming traffic by specifying one or more listeners, +// which are configured with a protocol and port number for connections from +// clients to the load balancer. You configure a target group with a protocol +// and port number for connections from the load balancer to the targets, and +// with health check settings to be used when checking the health status of +// the targets. +// +// Elastic Load Balancing supports two types of load balancers: Classic Load +// Balancers and Application Load Balancers. A Classic Load Balancer makes routing +// and load balancing decisions either at the transport layer (TCP/SSL) or the +// application layer (HTTP/HTTPS), and supports either EC2-Classic or a VPC. +// An Application Load Balancer makes routing and load balancing decisions at +// the application layer (HTTP/HTTPS), supports path-based routing, and can +// route requests to one or more ports on each EC2 instance or container instance +// in your virtual private cloud (VPC). For more information, see the Elastic +// Load Balancing User Guide (http://docs.aws.amazon.com/elasticloadbalancing/latest/userguide/). +// +// This reference covers the 2015-12-01 API, which supports Application Load +// Balancers. The 2012-06-01 API supports Classic Load Balancers. +// +// To get started, complete the following tasks: +// +// Create an Application Load Balancer using CreateLoadBalancer. +// +// Create a target group using CreateTargetGroup. +// +// Register targets for the target group using RegisterTargets. +// +// Create one or more listeners for your load balancer using CreateListener. +// +// (Optional) Create one or more rules for content routing based on URL using +// CreateRule. +// +// To delete an Application Load Balancer and its related resources, complete +// the following tasks: +// +// Delete the load balancer using DeleteLoadBalancer. +// +// Delete the target group using DeleteTargetGroup. +// +// All Elastic Load Balancing operations are idempotent, which means that they +// complete at most one time. If you repeat an operation, it succeeds. +// +// See https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01 for more information on this service. +// +// See elbv2 package documentation for more information. +// https://docs.aws.amazon.com/sdk-for-go/api/service/elbv2/ +// +// Using the Client +// +// To use the client for Elastic Load Balancing you will first need +// to create a new instance of it. +// +// When creating a client for an AWS service you'll first need to have a Session +// already created. The Session provides configuration that can be shared +// between multiple service clients. Additional configuration can be applied to +// the Session and service's client when they are constructed. The aws package's +// Config type contains several fields such as Region for the AWS Region the +// client should make API requests too. The optional Config value can be provided +// as the variadic argument for Sessions and client creation. +// +// Once the service's client is created you can use it to make API requests the +// AWS service. These clients are safe to use concurrently. +// +// // Create a session to share configuration, and load external configuration. +// sess := session.Must(session.NewSession()) +// +// // Create the service's client with the session. +// svc := elbv2.New(sess) +// +// See the SDK's documentation for more information on how to use service clients. +// https://docs.aws.amazon.com/sdk-for-go/api/ +// +// See aws package's Config type for more information on configuration options. +// https://docs.aws.amazon.com/sdk-for-go/api/aws/#Config +// +// See the Elastic Load Balancing client ELBV2 for more +// information on creating the service's client. +// https://docs.aws.amazon.com/sdk-for-go/api/service/elbv2/#New +// +// Once the client is created you can make an API request to the service. +// Each API method takes a input parameter, and returns the service response +// and an error. +// +// The API method will document which error codes the service can be returned +// by the operation if the service models the API operation's errors. These +// errors will also be available as const strings prefixed with "ErrCode". +// +// result, err := svc.AddTags(params) +// if err != nil { +// // Cast err to awserr.Error to handle specific error codes. +// aerr, ok := err.(awserr.Error) +// if ok && aerr.Code() == { +// // Specific error code handling +// } +// return err +// } +// +// fmt.Println("AddTags result:") +// fmt.Println(result) +// +// Using the Client with Context +// +// The service's client also provides methods to make API requests with a Context +// value. This allows you to control the timeout, and cancellation of pending +// requests. These methods also take request Option as variadic parameter to apply +// additional configuration to the API request. +// +// ctx := context.Background() +// +// result, err := svc.AddTagsWithContext(ctx, params) +// +// See the request package documentation for more information on using Context pattern +// with the SDK. +// https://docs.aws.amazon.com/sdk-for-go/api/aws/request/ +package elbv2 diff --git a/vendor/github.com/aws/aws-sdk-go/service/elbv2/errors.go b/vendor/github.com/aws/aws-sdk-go/service/elbv2/errors.go index 4f49c2f22..da661ba2c 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/elbv2/errors.go +++ b/vendor/github.com/aws/aws-sdk-go/service/elbv2/errors.go @@ -1,4 +1,4 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. package elbv2 @@ -19,7 +19,7 @@ const ( // ErrCodeDuplicateLoadBalancerNameException for service response error code // "DuplicateLoadBalancerName". // - // A load balancer with the specified name already exists for this account. + // A load balancer with the specified name already exists. ErrCodeDuplicateLoadBalancerNameException = "DuplicateLoadBalancerName" // ErrCodeDuplicateTagKeysException for service response error code diff --git a/vendor/github.com/aws/aws-sdk-go/service/elbv2/service.go b/vendor/github.com/aws/aws-sdk-go/service/elbv2/service.go index 3e2e79a89..c3733846c 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/elbv2/service.go +++ b/vendor/github.com/aws/aws-sdk-go/service/elbv2/service.go @@ -1,4 +1,4 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. package elbv2 @@ -11,55 +11,12 @@ import ( "github.com/aws/aws-sdk-go/private/protocol/query" ) -// A load balancer distributes incoming traffic across targets, such as your -// EC2 instances. This enables you to increase the availability of your application. -// The load balancer also monitors the health of its registered targets and -// ensures that it routes traffic only to healthy targets. You configure your -// load balancer to accept incoming traffic by specifying one or more listeners, -// which are configured with a protocol and port number for connections from -// clients to the load balancer. You configure a target group with a protocol -// and port number for connections from the load balancer to the targets, and -// with health check settings to be used when checking the health status of -// the targets. +// ELBV2 provides the API operation methods for making requests to +// Elastic Load Balancing. See this package's package overview docs +// for details on the service. // -// Elastic Load Balancing supports two types of load balancers: Classic Load -// Balancers and Application Load Balancers. A Classic Load Balancer makes routing -// and load balancing decisions either at the transport layer (TCP/SSL) or the -// application layer (HTTP/HTTPS), and supports either EC2-Classic or a VPC. -// An Application Load Balancer makes routing and load balancing decisions at -// the application layer (HTTP/HTTPS), supports path-based routing, and can -// route requests to one or more ports on each EC2 instance or container instance -// in your virtual private cloud (VPC). For more information, see the Elastic -// Load Balancing User Guide (http://docs.aws.amazon.com/elasticloadbalancing/latest/userguide/). -// -// This reference covers the 2015-12-01 API, which supports Application Load -// Balancers. The 2012-06-01 API supports Classic Load Balancers. -// -// To get started, complete the following tasks: -// -// Create an Application Load Balancer using CreateLoadBalancer. -// -// Create a target group using CreateTargetGroup. -// -// Register targets for the target group using RegisterTargets. -// -// Create one or more listeners for your load balancer using CreateListener. -// -// (Optional) Create one or more rules for content routing based on URL using -// CreateRule. -// -// To delete an Application Load Balancer and its related resources, complete -// the following tasks: -// -// Delete the load balancer using DeleteLoadBalancer. -// -// Delete the target group using DeleteTargetGroup. -// -// All Elastic Load Balancing operations are idempotent, which means that they -// complete at most one time. If you repeat an operation, it succeeds. -// The service client's operations are safe to be used concurrently. -// It is not safe to mutate any of the client's properties though. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01 +// ELBV2 methods are safe to use concurrently. It is not safe to +// modify mutate any of the struct's properties though. type ELBV2 struct { *client.Client } diff --git a/vendor/github.com/aws/aws-sdk-go/service/elbv2/waiters.go b/vendor/github.com/aws/aws-sdk-go/service/elbv2/waiters.go new file mode 100644 index 000000000..44fc1fc85 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/service/elbv2/waiters.go @@ -0,0 +1,168 @@ +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. + +package elbv2 + +import ( + "time" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/request" +) + +// WaitUntilLoadBalancerAvailable uses the Elastic Load Balancing v2 API operation +// DescribeLoadBalancers to wait for a condition to be met before returning. +// If the condition is not meet within the max attempt window an error will +// be returned. +func (c *ELBV2) WaitUntilLoadBalancerAvailable(input *DescribeLoadBalancersInput) error { + return c.WaitUntilLoadBalancerAvailableWithContext(aws.BackgroundContext(), input) +} + +// WaitUntilLoadBalancerAvailableWithContext is an extended version of WaitUntilLoadBalancerAvailable. +// 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 *ELBV2) WaitUntilLoadBalancerAvailableWithContext(ctx aws.Context, input *DescribeLoadBalancersInput, opts ...request.WaiterOption) error { + w := request.Waiter{ + Name: "WaitUntilLoadBalancerAvailable", + MaxAttempts: 40, + Delay: request.ConstantWaiterDelay(15 * time.Second), + Acceptors: []request.WaiterAcceptor{ + { + State: request.SuccessWaiterState, + Matcher: request.PathAllWaiterMatch, Argument: "LoadBalancers[].State.Code", + Expected: "active", + }, + { + State: request.RetryWaiterState, + Matcher: request.PathAnyWaiterMatch, Argument: "LoadBalancers[].State.Code", + Expected: "provisioning", + }, + { + State: request.RetryWaiterState, + Matcher: request.ErrorWaiterMatch, + Expected: "LoadBalancerNotFound", + }, + }, + Logger: c.Config.Logger, + NewRequest: func(opts []request.Option) (*request.Request, error) { + var inCpy *DescribeLoadBalancersInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeLoadBalancersRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + w.ApplyOptions(opts...) + + return w.WaitWithContext(ctx) +} + +// WaitUntilLoadBalancerExists uses the Elastic Load Balancing v2 API operation +// DescribeLoadBalancers to wait for a condition to be met before returning. +// If the condition is not meet within the max attempt window an error will +// be returned. +func (c *ELBV2) WaitUntilLoadBalancerExists(input *DescribeLoadBalancersInput) error { + return c.WaitUntilLoadBalancerExistsWithContext(aws.BackgroundContext(), input) +} + +// WaitUntilLoadBalancerExistsWithContext is an extended version of WaitUntilLoadBalancerExists. +// 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 *ELBV2) WaitUntilLoadBalancerExistsWithContext(ctx aws.Context, input *DescribeLoadBalancersInput, opts ...request.WaiterOption) error { + w := request.Waiter{ + Name: "WaitUntilLoadBalancerExists", + MaxAttempts: 40, + Delay: request.ConstantWaiterDelay(15 * time.Second), + Acceptors: []request.WaiterAcceptor{ + { + State: request.SuccessWaiterState, + Matcher: request.StatusWaiterMatch, + Expected: 200, + }, + { + State: request.RetryWaiterState, + Matcher: request.ErrorWaiterMatch, + Expected: "LoadBalancerNotFound", + }, + }, + Logger: c.Config.Logger, + NewRequest: func(opts []request.Option) (*request.Request, error) { + var inCpy *DescribeLoadBalancersInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeLoadBalancersRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + w.ApplyOptions(opts...) + + return w.WaitWithContext(ctx) +} + +// WaitUntilLoadBalancersDeleted uses the Elastic Load Balancing v2 API operation +// DescribeLoadBalancers to wait for a condition to be met before returning. +// If the condition is not meet within the max attempt window an error will +// be returned. +func (c *ELBV2) WaitUntilLoadBalancersDeleted(input *DescribeLoadBalancersInput) error { + return c.WaitUntilLoadBalancersDeletedWithContext(aws.BackgroundContext(), input) +} + +// WaitUntilLoadBalancersDeletedWithContext is an extended version of WaitUntilLoadBalancersDeleted. +// 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 *ELBV2) WaitUntilLoadBalancersDeletedWithContext(ctx aws.Context, input *DescribeLoadBalancersInput, opts ...request.WaiterOption) error { + w := request.Waiter{ + Name: "WaitUntilLoadBalancersDeleted", + MaxAttempts: 40, + Delay: request.ConstantWaiterDelay(15 * time.Second), + Acceptors: []request.WaiterAcceptor{ + { + State: request.RetryWaiterState, + Matcher: request.PathAllWaiterMatch, Argument: "LoadBalancers[].State.Code", + Expected: "active", + }, + { + State: request.SuccessWaiterState, + Matcher: request.ErrorWaiterMatch, + Expected: "LoadBalancerNotFound", + }, + }, + Logger: c.Config.Logger, + NewRequest: func(opts []request.Option) (*request.Request, error) { + var inCpy *DescribeLoadBalancersInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeLoadBalancersRequest(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/emr/api.go b/vendor/github.com/aws/aws-sdk-go/service/emr/api.go index 169ba4e3a..d7eb0abe5 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/emr/api.go +++ b/vendor/github.com/aws/aws-sdk-go/service/emr/api.go @@ -1,12 +1,12 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. -// Package emr provides a client for Amazon Elastic MapReduce. package emr import ( "fmt" "time" + "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awsutil" "github.com/aws/aws-sdk-go/aws/request" "github.com/aws/aws-sdk-go/private/protocol" @@ -80,8 +80,23 @@ func (c *EMR) AddInstanceFleetRequest(input *AddInstanceFleetInput) (req *reques // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticmapreduce-2009-03-31/AddInstanceFleet func (c *EMR) AddInstanceFleet(input *AddInstanceFleetInput) (*AddInstanceFleetOutput, error) { req, out := c.AddInstanceFleetRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// AddInstanceFleetWithContext is the same as AddInstanceFleet with the addition of +// the ability to pass a context and additional request options. +// +// See AddInstanceFleet 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 *EMR) AddInstanceFleetWithContext(ctx aws.Context, input *AddInstanceFleetInput, opts ...request.Option) (*AddInstanceFleetOutput, error) { + req, out := c.AddInstanceFleetRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opAddInstanceGroups = "AddInstanceGroups" @@ -146,8 +161,23 @@ func (c *EMR) AddInstanceGroupsRequest(input *AddInstanceGroupsInput) (req *requ // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticmapreduce-2009-03-31/AddInstanceGroups func (c *EMR) AddInstanceGroups(input *AddInstanceGroupsInput) (*AddInstanceGroupsOutput, error) { req, out := c.AddInstanceGroupsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// AddInstanceGroupsWithContext is the same as AddInstanceGroups with the addition of +// the ability to pass a context and additional request options. +// +// See AddInstanceGroups 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 *EMR) AddInstanceGroupsWithContext(ctx aws.Context, input *AddInstanceGroupsInput, opts ...request.Option) (*AddInstanceGroupsOutput, error) { + req, out := c.AddInstanceGroupsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opAddJobFlowSteps = "AddJobFlowSteps" @@ -234,8 +264,23 @@ func (c *EMR) AddJobFlowStepsRequest(input *AddJobFlowStepsInput) (req *request. // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticmapreduce-2009-03-31/AddJobFlowSteps func (c *EMR) AddJobFlowSteps(input *AddJobFlowStepsInput) (*AddJobFlowStepsOutput, error) { req, out := c.AddJobFlowStepsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// AddJobFlowStepsWithContext is the same as AddJobFlowSteps with the addition of +// the ability to pass a context and additional request options. +// +// See AddJobFlowSteps 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 *EMR) AddJobFlowStepsWithContext(ctx aws.Context, input *AddJobFlowStepsInput, opts ...request.Option) (*AddJobFlowStepsOutput, error) { + req, out := c.AddJobFlowStepsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opAddTags = "AddTags" @@ -305,8 +350,23 @@ func (c *EMR) AddTagsRequest(input *AddTagsInput) (req *request.Request, output // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticmapreduce-2009-03-31/AddTags func (c *EMR) AddTags(input *AddTagsInput) (*AddTagsOutput, error) { req, out := c.AddTagsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// AddTagsWithContext is the same as AddTags with the addition of +// the ability to pass a context and additional request options. +// +// See AddTags 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 *EMR) AddTagsWithContext(ctx aws.Context, input *AddTagsInput, opts ...request.Option) (*AddTagsOutput, error) { + req, out := c.AddTagsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCancelSteps = "CancelSteps" @@ -378,8 +438,23 @@ func (c *EMR) CancelStepsRequest(input *CancelStepsInput) (req *request.Request, // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticmapreduce-2009-03-31/CancelSteps func (c *EMR) CancelSteps(input *CancelStepsInput) (*CancelStepsOutput, error) { req, out := c.CancelStepsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CancelStepsWithContext is the same as CancelSteps with the addition of +// the ability to pass a context and additional request options. +// +// See CancelSteps 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 *EMR) CancelStepsWithContext(ctx aws.Context, input *CancelStepsInput, opts ...request.Option) (*CancelStepsOutput, error) { + req, out := c.CancelStepsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateSecurityConfiguration = "CreateSecurityConfiguration" @@ -447,8 +522,23 @@ func (c *EMR) CreateSecurityConfigurationRequest(input *CreateSecurityConfigurat // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticmapreduce-2009-03-31/CreateSecurityConfiguration func (c *EMR) CreateSecurityConfiguration(input *CreateSecurityConfigurationInput) (*CreateSecurityConfigurationOutput, error) { req, out := c.CreateSecurityConfigurationRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateSecurityConfigurationWithContext is the same as CreateSecurityConfiguration with the addition of +// the ability to pass a context and additional request options. +// +// See CreateSecurityConfiguration 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 *EMR) CreateSecurityConfigurationWithContext(ctx aws.Context, input *CreateSecurityConfigurationInput, opts ...request.Option) (*CreateSecurityConfigurationOutput, error) { + req, out := c.CreateSecurityConfigurationRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteSecurityConfiguration = "DeleteSecurityConfiguration" @@ -515,8 +605,23 @@ func (c *EMR) DeleteSecurityConfigurationRequest(input *DeleteSecurityConfigurat // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticmapreduce-2009-03-31/DeleteSecurityConfiguration func (c *EMR) DeleteSecurityConfiguration(input *DeleteSecurityConfigurationInput) (*DeleteSecurityConfigurationOutput, error) { req, out := c.DeleteSecurityConfigurationRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteSecurityConfigurationWithContext is the same as DeleteSecurityConfiguration with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteSecurityConfiguration 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 *EMR) DeleteSecurityConfigurationWithContext(ctx aws.Context, input *DeleteSecurityConfigurationInput, opts ...request.Option) (*DeleteSecurityConfigurationOutput, error) { + req, out := c.DeleteSecurityConfigurationRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeCluster = "DescribeCluster" @@ -584,8 +689,23 @@ func (c *EMR) DescribeClusterRequest(input *DescribeClusterInput) (req *request. // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticmapreduce-2009-03-31/DescribeCluster func (c *EMR) DescribeCluster(input *DescribeClusterInput) (*DescribeClusterOutput, error) { req, out := c.DescribeClusterRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeClusterWithContext is the same as DescribeCluster with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeCluster 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 *EMR) DescribeClusterWithContext(ctx aws.Context, input *DescribeClusterInput, opts ...request.Option) (*DescribeClusterOutput, error) { + req, out := c.DescribeClusterRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeJobFlows = "DescribeJobFlows" @@ -672,8 +792,23 @@ func (c *EMR) DescribeJobFlowsRequest(input *DescribeJobFlowsInput) (req *reques // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticmapreduce-2009-03-31/DescribeJobFlows func (c *EMR) DescribeJobFlows(input *DescribeJobFlowsInput) (*DescribeJobFlowsOutput, error) { req, out := c.DescribeJobFlowsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeJobFlowsWithContext is the same as DescribeJobFlows with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeJobFlows 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 *EMR) DescribeJobFlowsWithContext(ctx aws.Context, input *DescribeJobFlowsInput, opts ...request.Option) (*DescribeJobFlowsOutput, error) { + req, out := c.DescribeJobFlowsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeSecurityConfiguration = "DescribeSecurityConfiguration" @@ -741,8 +876,23 @@ func (c *EMR) DescribeSecurityConfigurationRequest(input *DescribeSecurityConfig // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticmapreduce-2009-03-31/DescribeSecurityConfiguration func (c *EMR) DescribeSecurityConfiguration(input *DescribeSecurityConfigurationInput) (*DescribeSecurityConfigurationOutput, error) { req, out := c.DescribeSecurityConfigurationRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeSecurityConfigurationWithContext is the same as DescribeSecurityConfiguration with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeSecurityConfiguration 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 *EMR) DescribeSecurityConfigurationWithContext(ctx aws.Context, input *DescribeSecurityConfigurationInput, opts ...request.Option) (*DescribeSecurityConfigurationOutput, error) { + req, out := c.DescribeSecurityConfigurationRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeStep = "DescribeStep" @@ -809,8 +959,23 @@ func (c *EMR) DescribeStepRequest(input *DescribeStepInput) (req *request.Reques // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticmapreduce-2009-03-31/DescribeStep func (c *EMR) DescribeStep(input *DescribeStepInput) (*DescribeStepOutput, error) { req, out := c.DescribeStepRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeStepWithContext is the same as DescribeStep with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeStep 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 *EMR) DescribeStepWithContext(ctx aws.Context, input *DescribeStepInput, opts ...request.Option) (*DescribeStepOutput, error) { + req, out := c.DescribeStepRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opListBootstrapActions = "ListBootstrapActions" @@ -883,8 +1048,23 @@ func (c *EMR) ListBootstrapActionsRequest(input *ListBootstrapActionsInput) (req // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticmapreduce-2009-03-31/ListBootstrapActions func (c *EMR) ListBootstrapActions(input *ListBootstrapActionsInput) (*ListBootstrapActionsOutput, error) { req, out := c.ListBootstrapActionsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListBootstrapActionsWithContext is the same as ListBootstrapActions with the addition of +// the ability to pass a context and additional request options. +// +// See ListBootstrapActions 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 *EMR) ListBootstrapActionsWithContext(ctx aws.Context, input *ListBootstrapActionsInput, opts ...request.Option) (*ListBootstrapActionsOutput, error) { + req, out := c.ListBootstrapActionsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // ListBootstrapActionsPages iterates over the pages of a ListBootstrapActions operation, @@ -904,12 +1084,37 @@ func (c *EMR) ListBootstrapActions(input *ListBootstrapActionsInput) (*ListBoots // return pageNum <= 3 // }) // -func (c *EMR) ListBootstrapActionsPages(input *ListBootstrapActionsInput, fn func(p *ListBootstrapActionsOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.ListBootstrapActionsRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*ListBootstrapActionsOutput), lastPage) - }) +func (c *EMR) ListBootstrapActionsPages(input *ListBootstrapActionsInput, fn func(*ListBootstrapActionsOutput, bool) bool) error { + return c.ListBootstrapActionsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListBootstrapActionsPagesWithContext same as ListBootstrapActionsPages 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 *EMR) ListBootstrapActionsPagesWithContext(ctx aws.Context, input *ListBootstrapActionsInput, fn func(*ListBootstrapActionsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListBootstrapActionsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListBootstrapActionsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*ListBootstrapActionsOutput), !p.HasNextPage()) + } + return p.Err() } const opListClusters = "ListClusters" @@ -986,8 +1191,23 @@ func (c *EMR) ListClustersRequest(input *ListClustersInput) (req *request.Reques // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticmapreduce-2009-03-31/ListClusters func (c *EMR) ListClusters(input *ListClustersInput) (*ListClustersOutput, error) { req, out := c.ListClustersRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListClustersWithContext is the same as ListClusters with the addition of +// the ability to pass a context and additional request options. +// +// See ListClusters 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 *EMR) ListClustersWithContext(ctx aws.Context, input *ListClustersInput, opts ...request.Option) (*ListClustersOutput, error) { + req, out := c.ListClustersRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // ListClustersPages iterates over the pages of a ListClusters operation, @@ -1007,12 +1227,37 @@ func (c *EMR) ListClusters(input *ListClustersInput) (*ListClustersOutput, error // return pageNum <= 3 // }) // -func (c *EMR) ListClustersPages(input *ListClustersInput, fn func(p *ListClustersOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.ListClustersRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*ListClustersOutput), lastPage) - }) +func (c *EMR) ListClustersPages(input *ListClustersInput, fn func(*ListClustersOutput, bool) bool) error { + return c.ListClustersPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListClustersPagesWithContext same as ListClustersPages 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 *EMR) ListClustersPagesWithContext(ctx aws.Context, input *ListClustersInput, fn func(*ListClustersOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListClustersInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListClustersRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*ListClustersOutput), !p.HasNextPage()) + } + return p.Err() } const opListInstanceFleets = "ListInstanceFleets" @@ -1088,8 +1333,23 @@ func (c *EMR) ListInstanceFleetsRequest(input *ListInstanceFleetsInput) (req *re // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticmapreduce-2009-03-31/ListInstanceFleets func (c *EMR) ListInstanceFleets(input *ListInstanceFleetsInput) (*ListInstanceFleetsOutput, error) { req, out := c.ListInstanceFleetsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListInstanceFleetsWithContext is the same as ListInstanceFleets with the addition of +// the ability to pass a context and additional request options. +// +// See ListInstanceFleets 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 *EMR) ListInstanceFleetsWithContext(ctx aws.Context, input *ListInstanceFleetsInput, opts ...request.Option) (*ListInstanceFleetsOutput, error) { + req, out := c.ListInstanceFleetsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // ListInstanceFleetsPages iterates over the pages of a ListInstanceFleets operation, @@ -1109,12 +1369,37 @@ func (c *EMR) ListInstanceFleets(input *ListInstanceFleetsInput) (*ListInstanceF // return pageNum <= 3 // }) // -func (c *EMR) ListInstanceFleetsPages(input *ListInstanceFleetsInput, fn func(p *ListInstanceFleetsOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.ListInstanceFleetsRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*ListInstanceFleetsOutput), lastPage) - }) +func (c *EMR) ListInstanceFleetsPages(input *ListInstanceFleetsInput, fn func(*ListInstanceFleetsOutput, bool) bool) error { + return c.ListInstanceFleetsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListInstanceFleetsPagesWithContext same as ListInstanceFleetsPages 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 *EMR) ListInstanceFleetsPagesWithContext(ctx aws.Context, input *ListInstanceFleetsInput, fn func(*ListInstanceFleetsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListInstanceFleetsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListInstanceFleetsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*ListInstanceFleetsOutput), !p.HasNextPage()) + } + return p.Err() } const opListInstanceGroups = "ListInstanceGroups" @@ -1187,8 +1472,23 @@ func (c *EMR) ListInstanceGroupsRequest(input *ListInstanceGroupsInput) (req *re // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticmapreduce-2009-03-31/ListInstanceGroups func (c *EMR) ListInstanceGroups(input *ListInstanceGroupsInput) (*ListInstanceGroupsOutput, error) { req, out := c.ListInstanceGroupsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListInstanceGroupsWithContext is the same as ListInstanceGroups with the addition of +// the ability to pass a context and additional request options. +// +// See ListInstanceGroups 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 *EMR) ListInstanceGroupsWithContext(ctx aws.Context, input *ListInstanceGroupsInput, opts ...request.Option) (*ListInstanceGroupsOutput, error) { + req, out := c.ListInstanceGroupsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // ListInstanceGroupsPages iterates over the pages of a ListInstanceGroups operation, @@ -1208,12 +1508,37 @@ func (c *EMR) ListInstanceGroups(input *ListInstanceGroupsInput) (*ListInstanceG // return pageNum <= 3 // }) // -func (c *EMR) ListInstanceGroupsPages(input *ListInstanceGroupsInput, fn func(p *ListInstanceGroupsOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.ListInstanceGroupsRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*ListInstanceGroupsOutput), lastPage) - }) +func (c *EMR) ListInstanceGroupsPages(input *ListInstanceGroupsInput, fn func(*ListInstanceGroupsOutput, bool) bool) error { + return c.ListInstanceGroupsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListInstanceGroupsPagesWithContext same as ListInstanceGroupsPages 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 *EMR) ListInstanceGroupsPagesWithContext(ctx aws.Context, input *ListInstanceGroupsInput, fn func(*ListInstanceGroupsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListInstanceGroupsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListInstanceGroupsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*ListInstanceGroupsOutput), !p.HasNextPage()) + } + return p.Err() } const opListInstances = "ListInstances" @@ -1290,8 +1615,23 @@ func (c *EMR) ListInstancesRequest(input *ListInstancesInput) (req *request.Requ // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticmapreduce-2009-03-31/ListInstances func (c *EMR) ListInstances(input *ListInstancesInput) (*ListInstancesOutput, error) { req, out := c.ListInstancesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListInstancesWithContext is the same as ListInstances with the addition of +// the ability to pass a context and additional request options. +// +// See ListInstances 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 *EMR) ListInstancesWithContext(ctx aws.Context, input *ListInstancesInput, opts ...request.Option) (*ListInstancesOutput, error) { + req, out := c.ListInstancesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // ListInstancesPages iterates over the pages of a ListInstances operation, @@ -1311,12 +1651,37 @@ func (c *EMR) ListInstances(input *ListInstancesInput) (*ListInstancesOutput, er // return pageNum <= 3 // }) // -func (c *EMR) ListInstancesPages(input *ListInstancesInput, fn func(p *ListInstancesOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.ListInstancesRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*ListInstancesOutput), lastPage) - }) +func (c *EMR) ListInstancesPages(input *ListInstancesInput, fn func(*ListInstancesOutput, bool) bool) error { + return c.ListInstancesPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListInstancesPagesWithContext same as ListInstancesPages 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 *EMR) ListInstancesPagesWithContext(ctx aws.Context, input *ListInstancesInput, fn func(*ListInstancesOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListInstancesInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListInstancesRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*ListInstancesOutput), !p.HasNextPage()) + } + return p.Err() } const opListSecurityConfigurations = "ListSecurityConfigurations" @@ -1386,8 +1751,23 @@ func (c *EMR) ListSecurityConfigurationsRequest(input *ListSecurityConfiguration // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticmapreduce-2009-03-31/ListSecurityConfigurations func (c *EMR) ListSecurityConfigurations(input *ListSecurityConfigurationsInput) (*ListSecurityConfigurationsOutput, error) { req, out := c.ListSecurityConfigurationsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListSecurityConfigurationsWithContext is the same as ListSecurityConfigurations with the addition of +// the ability to pass a context and additional request options. +// +// See ListSecurityConfigurations 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 *EMR) ListSecurityConfigurationsWithContext(ctx aws.Context, input *ListSecurityConfigurationsInput, opts ...request.Option) (*ListSecurityConfigurationsOutput, error) { + req, out := c.ListSecurityConfigurationsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opListSteps = "ListSteps" @@ -1461,8 +1841,23 @@ func (c *EMR) ListStepsRequest(input *ListStepsInput) (req *request.Request, out // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticmapreduce-2009-03-31/ListSteps func (c *EMR) ListSteps(input *ListStepsInput) (*ListStepsOutput, error) { req, out := c.ListStepsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListStepsWithContext is the same as ListSteps with the addition of +// the ability to pass a context and additional request options. +// +// See ListSteps 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 *EMR) ListStepsWithContext(ctx aws.Context, input *ListStepsInput, opts ...request.Option) (*ListStepsOutput, error) { + req, out := c.ListStepsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // ListStepsPages iterates over the pages of a ListSteps operation, @@ -1482,12 +1877,37 @@ func (c *EMR) ListSteps(input *ListStepsInput) (*ListStepsOutput, error) { // return pageNum <= 3 // }) // -func (c *EMR) ListStepsPages(input *ListStepsInput, fn func(p *ListStepsOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.ListStepsRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*ListStepsOutput), lastPage) - }) +func (c *EMR) ListStepsPages(input *ListStepsInput, fn func(*ListStepsOutput, bool) bool) error { + return c.ListStepsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListStepsPagesWithContext same as ListStepsPages 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 *EMR) ListStepsPagesWithContext(ctx aws.Context, input *ListStepsInput, fn func(*ListStepsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListStepsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListStepsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*ListStepsOutput), !p.HasNextPage()) + } + return p.Err() } const opModifyInstanceFleet = "ModifyInstanceFleet" @@ -1561,8 +1981,23 @@ func (c *EMR) ModifyInstanceFleetRequest(input *ModifyInstanceFleetInput) (req * // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticmapreduce-2009-03-31/ModifyInstanceFleet func (c *EMR) ModifyInstanceFleet(input *ModifyInstanceFleetInput) (*ModifyInstanceFleetOutput, error) { req, out := c.ModifyInstanceFleetRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ModifyInstanceFleetWithContext is the same as ModifyInstanceFleet with the addition of +// the ability to pass a context and additional request options. +// +// See ModifyInstanceFleet 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 *EMR) ModifyInstanceFleetWithContext(ctx aws.Context, input *ModifyInstanceFleetInput, opts ...request.Option) (*ModifyInstanceFleetOutput, error) { + req, out := c.ModifyInstanceFleetRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opModifyInstanceGroups = "ModifyInstanceGroups" @@ -1632,8 +2067,23 @@ func (c *EMR) ModifyInstanceGroupsRequest(input *ModifyInstanceGroupsInput) (req // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticmapreduce-2009-03-31/ModifyInstanceGroups func (c *EMR) ModifyInstanceGroups(input *ModifyInstanceGroupsInput) (*ModifyInstanceGroupsOutput, error) { req, out := c.ModifyInstanceGroupsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ModifyInstanceGroupsWithContext is the same as ModifyInstanceGroups with the addition of +// the ability to pass a context and additional request options. +// +// See ModifyInstanceGroups 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 *EMR) ModifyInstanceGroupsWithContext(ctx aws.Context, input *ModifyInstanceGroupsInput, opts ...request.Option) (*ModifyInstanceGroupsOutput, error) { + req, out := c.ModifyInstanceGroupsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opPutAutoScalingPolicy = "PutAutoScalingPolicy" @@ -1695,8 +2145,23 @@ func (c *EMR) PutAutoScalingPolicyRequest(input *PutAutoScalingPolicyInput) (req // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticmapreduce-2009-03-31/PutAutoScalingPolicy func (c *EMR) PutAutoScalingPolicy(input *PutAutoScalingPolicyInput) (*PutAutoScalingPolicyOutput, error) { req, out := c.PutAutoScalingPolicyRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// PutAutoScalingPolicyWithContext is the same as PutAutoScalingPolicy with the addition of +// the ability to pass a context and additional request options. +// +// See PutAutoScalingPolicy 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 *EMR) PutAutoScalingPolicyWithContext(ctx aws.Context, input *PutAutoScalingPolicyInput, opts ...request.Option) (*PutAutoScalingPolicyOutput, error) { + req, out := c.PutAutoScalingPolicyRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opRemoveAutoScalingPolicy = "RemoveAutoScalingPolicy" @@ -1756,8 +2221,23 @@ func (c *EMR) RemoveAutoScalingPolicyRequest(input *RemoveAutoScalingPolicyInput // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticmapreduce-2009-03-31/RemoveAutoScalingPolicy func (c *EMR) RemoveAutoScalingPolicy(input *RemoveAutoScalingPolicyInput) (*RemoveAutoScalingPolicyOutput, error) { req, out := c.RemoveAutoScalingPolicyRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// RemoveAutoScalingPolicyWithContext is the same as RemoveAutoScalingPolicy with the addition of +// the ability to pass a context and additional request options. +// +// See RemoveAutoScalingPolicy 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 *EMR) RemoveAutoScalingPolicyWithContext(ctx aws.Context, input *RemoveAutoScalingPolicyInput, opts ...request.Option) (*RemoveAutoScalingPolicyOutput, error) { + req, out := c.RemoveAutoScalingPolicyRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opRemoveTags = "RemoveTags" @@ -1829,8 +2309,23 @@ func (c *EMR) RemoveTagsRequest(input *RemoveTagsInput) (req *request.Request, o // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticmapreduce-2009-03-31/RemoveTags func (c *EMR) RemoveTags(input *RemoveTagsInput) (*RemoveTagsOutput, error) { req, out := c.RemoveTagsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// RemoveTagsWithContext is the same as RemoveTags with the addition of +// the ability to pass a context and additional request options. +// +// See RemoveTags 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 *EMR) RemoveTagsWithContext(ctx aws.Context, input *RemoveTagsInput, opts ...request.Option) (*RemoveTagsOutput, error) { + req, out := c.RemoveTagsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opRunJobFlow = "RunJobFlow" @@ -1921,8 +2416,23 @@ func (c *EMR) RunJobFlowRequest(input *RunJobFlowInput) (req *request.Request, o // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticmapreduce-2009-03-31/RunJobFlow func (c *EMR) RunJobFlow(input *RunJobFlowInput) (*RunJobFlowOutput, error) { req, out := c.RunJobFlowRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// RunJobFlowWithContext is the same as RunJobFlow with the addition of +// the ability to pass a context and additional request options. +// +// See RunJobFlow 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 *EMR) RunJobFlowWithContext(ctx aws.Context, input *RunJobFlowInput, opts ...request.Option) (*RunJobFlowOutput, error) { + req, out := c.RunJobFlowRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opSetTerminationProtection = "SetTerminationProtection" @@ -2005,8 +2515,23 @@ func (c *EMR) SetTerminationProtectionRequest(input *SetTerminationProtectionInp // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticmapreduce-2009-03-31/SetTerminationProtection func (c *EMR) SetTerminationProtection(input *SetTerminationProtectionInput) (*SetTerminationProtectionOutput, error) { req, out := c.SetTerminationProtectionRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// SetTerminationProtectionWithContext is the same as SetTerminationProtection with the addition of +// the ability to pass a context and additional request options. +// +// See SetTerminationProtection 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 *EMR) SetTerminationProtectionWithContext(ctx aws.Context, input *SetTerminationProtectionInput, opts ...request.Option) (*SetTerminationProtectionOutput, error) { + req, out := c.SetTerminationProtectionRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opSetVisibleToAllUsers = "SetVisibleToAllUsers" @@ -2078,8 +2603,23 @@ func (c *EMR) SetVisibleToAllUsersRequest(input *SetVisibleToAllUsersInput) (req // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticmapreduce-2009-03-31/SetVisibleToAllUsers func (c *EMR) SetVisibleToAllUsers(input *SetVisibleToAllUsersInput) (*SetVisibleToAllUsersOutput, error) { req, out := c.SetVisibleToAllUsersRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// SetVisibleToAllUsersWithContext is the same as SetVisibleToAllUsers with the addition of +// the ability to pass a context and additional request options. +// +// See SetVisibleToAllUsers 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 *EMR) SetVisibleToAllUsersWithContext(ctx aws.Context, input *SetVisibleToAllUsersInput, opts ...request.Option) (*SetVisibleToAllUsersOutput, error) { + req, out := c.SetVisibleToAllUsersRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opTerminateJobFlows = "TerminateJobFlows" @@ -2155,8 +2695,23 @@ func (c *EMR) TerminateJobFlowsRequest(input *TerminateJobFlowsInput) (req *requ // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticmapreduce-2009-03-31/TerminateJobFlows func (c *EMR) TerminateJobFlows(input *TerminateJobFlowsInput) (*TerminateJobFlowsOutput, error) { req, out := c.TerminateJobFlowsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// TerminateJobFlowsWithContext is the same as TerminateJobFlows with the addition of +// the ability to pass a context and additional request options. +// +// See TerminateJobFlows 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 *EMR) TerminateJobFlowsWithContext(ctx aws.Context, input *TerminateJobFlowsInput, opts ...request.Option) (*TerminateJobFlowsOutput, error) { + req, out := c.TerminateJobFlowsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticmapreduce-2009-03-31/AddInstanceFleetInput diff --git a/vendor/github.com/aws/aws-sdk-go/service/emr/doc.go b/vendor/github.com/aws/aws-sdk-go/service/emr/doc.go new file mode 100644 index 000000000..9b9fe1e70 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/service/emr/doc.go @@ -0,0 +1,83 @@ +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. + +// Package emr provides the client and types for making API +// requests to Amazon Elastic MapReduce. +// +// Amazon EMR is a web service that makes it easy to process large amounts of +// data efficiently. Amazon EMR uses Hadoop processing combined with several +// AWS products to do tasks such as web indexing, data mining, log file analysis, +// machine learning, scientific simulation, and data warehousing. +// +// See https://docs.aws.amazon.com/goto/WebAPI/elasticmapreduce-2009-03-31 for more information on this service. +// +// See emr package documentation for more information. +// https://docs.aws.amazon.com/sdk-for-go/api/service/emr/ +// +// Using the Client +// +// To use the client for Amazon Elastic MapReduce you will first need +// to create a new instance of it. +// +// When creating a client for an AWS service you'll first need to have a Session +// already created. The Session provides configuration that can be shared +// between multiple service clients. Additional configuration can be applied to +// the Session and service's client when they are constructed. The aws package's +// Config type contains several fields such as Region for the AWS Region the +// client should make API requests too. The optional Config value can be provided +// as the variadic argument for Sessions and client creation. +// +// Once the service's client is created you can use it to make API requests the +// AWS service. These clients are safe to use concurrently. +// +// // Create a session to share configuration, and load external configuration. +// sess := session.Must(session.NewSession()) +// +// // Create the service's client with the session. +// svc := emr.New(sess) +// +// See the SDK's documentation for more information on how to use service clients. +// https://docs.aws.amazon.com/sdk-for-go/api/ +// +// See aws package's Config type for more information on configuration options. +// https://docs.aws.amazon.com/sdk-for-go/api/aws/#Config +// +// See the Amazon Elastic MapReduce client EMR for more +// information on creating the service's client. +// https://docs.aws.amazon.com/sdk-for-go/api/service/emr/#New +// +// Once the client is created you can make an API request to the service. +// Each API method takes a input parameter, and returns the service response +// and an error. +// +// The API method will document which error codes the service can be returned +// by the operation if the service models the API operation's errors. These +// errors will also be available as const strings prefixed with "ErrCode". +// +// result, err := svc.AddInstanceFleet(params) +// if err != nil { +// // Cast err to awserr.Error to handle specific error codes. +// aerr, ok := err.(awserr.Error) +// if ok && aerr.Code() == { +// // Specific error code handling +// } +// return err +// } +// +// fmt.Println("AddInstanceFleet result:") +// fmt.Println(result) +// +// Using the Client with Context +// +// The service's client also provides methods to make API requests with a Context +// value. This allows you to control the timeout, and cancellation of pending +// requests. These methods also take request Option as variadic parameter to apply +// additional configuration to the API request. +// +// ctx := context.Background() +// +// result, err := svc.AddInstanceFleetWithContext(ctx, params) +// +// See the request package documentation for more information on using Context pattern +// with the SDK. +// https://docs.aws.amazon.com/sdk-for-go/api/aws/request/ +package emr diff --git a/vendor/github.com/aws/aws-sdk-go/service/emr/errors.go b/vendor/github.com/aws/aws-sdk-go/service/emr/errors.go index 7621ae662..b4bf33708 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/emr/errors.go +++ b/vendor/github.com/aws/aws-sdk-go/service/emr/errors.go @@ -1,4 +1,4 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. package emr diff --git a/vendor/github.com/aws/aws-sdk-go/service/emr/service.go b/vendor/github.com/aws/aws-sdk-go/service/emr/service.go index 610c46580..61fc42581 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/emr/service.go +++ b/vendor/github.com/aws/aws-sdk-go/service/emr/service.go @@ -1,4 +1,4 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. package emr @@ -11,13 +11,12 @@ import ( "github.com/aws/aws-sdk-go/private/protocol/jsonrpc" ) -// Amazon EMR is a web service that makes it easy to process large amounts of -// data efficiently. Amazon EMR uses Hadoop processing combined with several -// AWS products to do tasks such as web indexing, data mining, log file analysis, -// machine learning, scientific simulation, and data warehousing. -// The service client's operations are safe to be used concurrently. -// It is not safe to mutate any of the client's properties though. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/elasticmapreduce-2009-03-31 +// EMR provides the API operation methods for making requests to +// Amazon Elastic MapReduce. See this package's package overview docs +// for details on the service. +// +// EMR methods are safe to use concurrently. It is not safe to +// modify mutate any of the struct's properties though. type EMR struct { *client.Client } diff --git a/vendor/github.com/aws/aws-sdk-go/service/emr/waiters.go b/vendor/github.com/aws/aws-sdk-go/service/emr/waiters.go index 443240d3d..6e1b7ddec 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/emr/waiters.go +++ b/vendor/github.com/aws/aws-sdk-go/service/emr/waiters.go @@ -1,9 +1,12 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. package emr import ( - "github.com/aws/aws-sdk-go/private/waiter" + "time" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/request" ) // WaitUntilClusterRunning uses the Amazon EMR API operation @@ -11,50 +14,65 @@ import ( // If the condition is not meet within the max attempt window an error will // be returned. func (c *EMR) WaitUntilClusterRunning(input *DescribeClusterInput) error { - waiterCfg := waiter.Config{ - Operation: "DescribeCluster", - Delay: 30, + return c.WaitUntilClusterRunningWithContext(aws.BackgroundContext(), input) +} + +// WaitUntilClusterRunningWithContext is an extended version of WaitUntilClusterRunning. +// 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 *EMR) WaitUntilClusterRunningWithContext(ctx aws.Context, input *DescribeClusterInput, opts ...request.WaiterOption) error { + w := request.Waiter{ + Name: "WaitUntilClusterRunning", MaxAttempts: 60, - Acceptors: []waiter.WaitAcceptor{ + Delay: request.ConstantWaiterDelay(30 * time.Second), + Acceptors: []request.WaiterAcceptor{ { - State: "success", - Matcher: "path", - Argument: "Cluster.Status.State", + State: request.SuccessWaiterState, + Matcher: request.PathWaiterMatch, Argument: "Cluster.Status.State", Expected: "RUNNING", }, { - State: "success", - Matcher: "path", - Argument: "Cluster.Status.State", + State: request.SuccessWaiterState, + Matcher: request.PathWaiterMatch, Argument: "Cluster.Status.State", Expected: "WAITING", }, { - State: "failure", - Matcher: "path", - Argument: "Cluster.Status.State", + State: request.FailureWaiterState, + Matcher: request.PathWaiterMatch, Argument: "Cluster.Status.State", Expected: "TERMINATING", }, { - State: "failure", - Matcher: "path", - Argument: "Cluster.Status.State", + State: request.FailureWaiterState, + Matcher: request.PathWaiterMatch, Argument: "Cluster.Status.State", Expected: "TERMINATED", }, { - State: "failure", - Matcher: "path", - Argument: "Cluster.Status.State", + State: request.FailureWaiterState, + Matcher: request.PathWaiterMatch, Argument: "Cluster.Status.State", Expected: "TERMINATED_WITH_ERRORS", }, }, + Logger: c.Config.Logger, + NewRequest: func(opts []request.Option) (*request.Request, error) { + var inCpy *DescribeClusterInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeClusterRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, } + w.ApplyOptions(opts...) - w := waiter.Waiter{ - Client: c, - Input: input, - Config: waiterCfg, - } - return w.Wait() + return w.WaitWithContext(ctx) } // WaitUntilClusterTerminated uses the Amazon EMR API operation @@ -62,32 +80,50 @@ func (c *EMR) WaitUntilClusterRunning(input *DescribeClusterInput) error { // If the condition is not meet within the max attempt window an error will // be returned. func (c *EMR) WaitUntilClusterTerminated(input *DescribeClusterInput) error { - waiterCfg := waiter.Config{ - Operation: "DescribeCluster", - Delay: 30, + return c.WaitUntilClusterTerminatedWithContext(aws.BackgroundContext(), input) +} + +// WaitUntilClusterTerminatedWithContext is an extended version of WaitUntilClusterTerminated. +// 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 *EMR) WaitUntilClusterTerminatedWithContext(ctx aws.Context, input *DescribeClusterInput, opts ...request.WaiterOption) error { + w := request.Waiter{ + Name: "WaitUntilClusterTerminated", MaxAttempts: 60, - Acceptors: []waiter.WaitAcceptor{ + Delay: request.ConstantWaiterDelay(30 * time.Second), + Acceptors: []request.WaiterAcceptor{ { - State: "success", - Matcher: "path", - Argument: "Cluster.Status.State", + State: request.SuccessWaiterState, + Matcher: request.PathWaiterMatch, Argument: "Cluster.Status.State", Expected: "TERMINATED", }, { - State: "failure", - Matcher: "path", - Argument: "Cluster.Status.State", + State: request.FailureWaiterState, + Matcher: request.PathWaiterMatch, Argument: "Cluster.Status.State", Expected: "TERMINATED_WITH_ERRORS", }, }, + Logger: c.Config.Logger, + NewRequest: func(opts []request.Option) (*request.Request, error) { + var inCpy *DescribeClusterInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeClusterRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, } + w.ApplyOptions(opts...) - w := waiter.Waiter{ - Client: c, - Input: input, - Config: waiterCfg, - } - return w.Wait() + return w.WaitWithContext(ctx) } // WaitUntilStepComplete uses the Amazon EMR API operation @@ -95,36 +131,53 @@ func (c *EMR) WaitUntilClusterTerminated(input *DescribeClusterInput) error { // If the condition is not meet within the max attempt window an error will // be returned. func (c *EMR) WaitUntilStepComplete(input *DescribeStepInput) error { - waiterCfg := waiter.Config{ - Operation: "DescribeStep", - Delay: 30, + return c.WaitUntilStepCompleteWithContext(aws.BackgroundContext(), input) +} + +// WaitUntilStepCompleteWithContext is an extended version of WaitUntilStepComplete. +// 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 *EMR) WaitUntilStepCompleteWithContext(ctx aws.Context, input *DescribeStepInput, opts ...request.WaiterOption) error { + w := request.Waiter{ + Name: "WaitUntilStepComplete", MaxAttempts: 60, - Acceptors: []waiter.WaitAcceptor{ + Delay: request.ConstantWaiterDelay(30 * time.Second), + Acceptors: []request.WaiterAcceptor{ { - State: "success", - Matcher: "path", - Argument: "Step.Status.State", + State: request.SuccessWaiterState, + Matcher: request.PathWaiterMatch, Argument: "Step.Status.State", Expected: "COMPLETED", }, { - State: "failure", - Matcher: "path", - Argument: "Step.Status.State", + State: request.FailureWaiterState, + Matcher: request.PathWaiterMatch, Argument: "Step.Status.State", Expected: "FAILED", }, { - State: "failure", - Matcher: "path", - Argument: "Step.Status.State", + State: request.FailureWaiterState, + Matcher: request.PathWaiterMatch, Argument: "Step.Status.State", Expected: "CANCELLED", }, }, + Logger: c.Config.Logger, + NewRequest: func(opts []request.Option) (*request.Request, error) { + var inCpy *DescribeStepInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeStepRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, } + w.ApplyOptions(opts...) - w := waiter.Waiter{ - Client: c, - Input: input, - Config: waiterCfg, - } - return w.Wait() + return w.WaitWithContext(ctx) } diff --git a/vendor/github.com/aws/aws-sdk-go/service/firehose/api.go b/vendor/github.com/aws/aws-sdk-go/service/firehose/api.go index b22bb85d6..f404386c4 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/firehose/api.go +++ b/vendor/github.com/aws/aws-sdk-go/service/firehose/api.go @@ -1,12 +1,12 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. -// Package firehose provides a client for Amazon Kinesis Firehose. package firehose import ( "fmt" "time" + "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awsutil" "github.com/aws/aws-sdk-go/aws/request" ) @@ -122,8 +122,23 @@ func (c *Firehose) CreateDeliveryStreamRequest(input *CreateDeliveryStreamInput) // Please also see https://docs.aws.amazon.com/goto/WebAPI/firehose-2015-08-04/CreateDeliveryStream func (c *Firehose) CreateDeliveryStream(input *CreateDeliveryStreamInput) (*CreateDeliveryStreamOutput, error) { req, out := c.CreateDeliveryStreamRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateDeliveryStreamWithContext is the same as CreateDeliveryStream with the addition of +// the ability to pass a context and additional request options. +// +// See CreateDeliveryStream 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 *Firehose) CreateDeliveryStreamWithContext(ctx aws.Context, input *CreateDeliveryStreamInput, opts ...request.Option) (*CreateDeliveryStreamOutput, error) { + req, out := c.CreateDeliveryStreamRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteDeliveryStream = "DeleteDeliveryStream" @@ -201,8 +216,23 @@ func (c *Firehose) DeleteDeliveryStreamRequest(input *DeleteDeliveryStreamInput) // Please also see https://docs.aws.amazon.com/goto/WebAPI/firehose-2015-08-04/DeleteDeliveryStream func (c *Firehose) DeleteDeliveryStream(input *DeleteDeliveryStreamInput) (*DeleteDeliveryStreamOutput, error) { req, out := c.DeleteDeliveryStreamRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteDeliveryStreamWithContext is the same as DeleteDeliveryStream with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteDeliveryStream 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 *Firehose) DeleteDeliveryStreamWithContext(ctx aws.Context, input *DeleteDeliveryStreamInput, opts ...request.Option) (*DeleteDeliveryStreamOutput, error) { + req, out := c.DeleteDeliveryStreamRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeDeliveryStream = "DescribeDeliveryStream" @@ -269,8 +299,23 @@ func (c *Firehose) DescribeDeliveryStreamRequest(input *DescribeDeliveryStreamIn // Please also see https://docs.aws.amazon.com/goto/WebAPI/firehose-2015-08-04/DescribeDeliveryStream func (c *Firehose) DescribeDeliveryStream(input *DescribeDeliveryStreamInput) (*DescribeDeliveryStreamOutput, error) { req, out := c.DescribeDeliveryStreamRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeDeliveryStreamWithContext is the same as DescribeDeliveryStream with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeDeliveryStream 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 *Firehose) DescribeDeliveryStreamWithContext(ctx aws.Context, input *DescribeDeliveryStreamInput, opts ...request.Option) (*DescribeDeliveryStreamOutput, error) { + req, out := c.DescribeDeliveryStreamRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opListDeliveryStreams = "ListDeliveryStreams" @@ -337,8 +382,23 @@ func (c *Firehose) ListDeliveryStreamsRequest(input *ListDeliveryStreamsInput) ( // Please also see https://docs.aws.amazon.com/goto/WebAPI/firehose-2015-08-04/ListDeliveryStreams func (c *Firehose) ListDeliveryStreams(input *ListDeliveryStreamsInput) (*ListDeliveryStreamsOutput, error) { req, out := c.ListDeliveryStreamsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListDeliveryStreamsWithContext is the same as ListDeliveryStreams with the addition of +// the ability to pass a context and additional request options. +// +// See ListDeliveryStreams 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 *Firehose) ListDeliveryStreamsWithContext(ctx aws.Context, input *ListDeliveryStreamsInput, opts ...request.Option) (*ListDeliveryStreamsOutput, error) { + req, out := c.ListDeliveryStreamsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opPutRecord = "PutRecord" @@ -443,8 +503,23 @@ func (c *Firehose) PutRecordRequest(input *PutRecordInput) (req *request.Request // Please also see https://docs.aws.amazon.com/goto/WebAPI/firehose-2015-08-04/PutRecord func (c *Firehose) PutRecord(input *PutRecordInput) (*PutRecordOutput, error) { req, out := c.PutRecordRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// PutRecordWithContext is the same as PutRecord with the addition of +// the ability to pass a context and additional request options. +// +// See PutRecord 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 *Firehose) PutRecordWithContext(ctx aws.Context, input *PutRecordInput, opts ...request.Option) (*PutRecordOutput, error) { + req, out := c.PutRecordRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opPutRecordBatch = "PutRecordBatch" @@ -573,8 +648,23 @@ func (c *Firehose) PutRecordBatchRequest(input *PutRecordBatchInput) (req *reque // Please also see https://docs.aws.amazon.com/goto/WebAPI/firehose-2015-08-04/PutRecordBatch func (c *Firehose) PutRecordBatch(input *PutRecordBatchInput) (*PutRecordBatchOutput, error) { req, out := c.PutRecordBatchRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// PutRecordBatchWithContext is the same as PutRecordBatch with the addition of +// the ability to pass a context and additional request options. +// +// See PutRecordBatch 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 *Firehose) PutRecordBatchWithContext(ctx aws.Context, input *PutRecordBatchInput, opts ...request.Option) (*PutRecordBatchOutput, error) { + req, out := c.PutRecordBatchRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opUpdateDestination = "UpdateDestination" @@ -677,8 +767,23 @@ func (c *Firehose) UpdateDestinationRequest(input *UpdateDestinationInput) (req // Please also see https://docs.aws.amazon.com/goto/WebAPI/firehose-2015-08-04/UpdateDestination func (c *Firehose) UpdateDestination(input *UpdateDestinationInput) (*UpdateDestinationOutput, error) { req, out := c.UpdateDestinationRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// UpdateDestinationWithContext is the same as UpdateDestination with the addition of +// the ability to pass a context and additional request options. +// +// See UpdateDestination 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 *Firehose) UpdateDestinationWithContext(ctx aws.Context, input *UpdateDestinationInput, opts ...request.Option) (*UpdateDestinationOutput, error) { + req, out := c.UpdateDestinationRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // Describes hints for the buffering to perform before delivering data to the diff --git a/vendor/github.com/aws/aws-sdk-go/service/firehose/doc.go b/vendor/github.com/aws/aws-sdk-go/service/firehose/doc.go new file mode 100644 index 000000000..96f708afb --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/service/firehose/doc.go @@ -0,0 +1,82 @@ +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. + +// Package firehose provides the client and types for making API +// requests to Amazon Kinesis Firehose. +// +// Amazon Kinesis Firehose is a fully-managed service that delivers real-time +// streaming data to destinations such as Amazon Simple Storage Service (Amazon +// S3), Amazon Elasticsearch Service (Amazon ES), and Amazon Redshift. +// +// See https://docs.aws.amazon.com/goto/WebAPI/firehose-2015-08-04 for more information on this service. +// +// See firehose package documentation for more information. +// https://docs.aws.amazon.com/sdk-for-go/api/service/firehose/ +// +// Using the Client +// +// To use the client for Amazon Kinesis Firehose you will first need +// to create a new instance of it. +// +// When creating a client for an AWS service you'll first need to have a Session +// already created. The Session provides configuration that can be shared +// between multiple service clients. Additional configuration can be applied to +// the Session and service's client when they are constructed. The aws package's +// Config type contains several fields such as Region for the AWS Region the +// client should make API requests too. The optional Config value can be provided +// as the variadic argument for Sessions and client creation. +// +// Once the service's client is created you can use it to make API requests the +// AWS service. These clients are safe to use concurrently. +// +// // Create a session to share configuration, and load external configuration. +// sess := session.Must(session.NewSession()) +// +// // Create the service's client with the session. +// svc := firehose.New(sess) +// +// See the SDK's documentation for more information on how to use service clients. +// https://docs.aws.amazon.com/sdk-for-go/api/ +// +// See aws package's Config type for more information on configuration options. +// https://docs.aws.amazon.com/sdk-for-go/api/aws/#Config +// +// See the Amazon Kinesis Firehose client Firehose for more +// information on creating the service's client. +// https://docs.aws.amazon.com/sdk-for-go/api/service/firehose/#New +// +// Once the client is created you can make an API request to the service. +// Each API method takes a input parameter, and returns the service response +// and an error. +// +// The API method will document which error codes the service can be returned +// by the operation if the service models the API operation's errors. These +// errors will also be available as const strings prefixed with "ErrCode". +// +// result, err := svc.CreateDeliveryStream(params) +// if err != nil { +// // Cast err to awserr.Error to handle specific error codes. +// aerr, ok := err.(awserr.Error) +// if ok && aerr.Code() == { +// // Specific error code handling +// } +// return err +// } +// +// fmt.Println("CreateDeliveryStream result:") +// fmt.Println(result) +// +// Using the Client with Context +// +// The service's client also provides methods to make API requests with a Context +// value. This allows you to control the timeout, and cancellation of pending +// requests. These methods also take request Option as variadic parameter to apply +// additional configuration to the API request. +// +// ctx := context.Background() +// +// result, err := svc.CreateDeliveryStreamWithContext(ctx, params) +// +// See the request package documentation for more information on using Context pattern +// with the SDK. +// https://docs.aws.amazon.com/sdk-for-go/api/aws/request/ +package firehose diff --git a/vendor/github.com/aws/aws-sdk-go/service/firehose/errors.go b/vendor/github.com/aws/aws-sdk-go/service/firehose/errors.go index f541053f0..82bdcca24 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/firehose/errors.go +++ b/vendor/github.com/aws/aws-sdk-go/service/firehose/errors.go @@ -1,4 +1,4 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. package firehose diff --git a/vendor/github.com/aws/aws-sdk-go/service/firehose/service.go b/vendor/github.com/aws/aws-sdk-go/service/firehose/service.go index 930a4d428..973386c05 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/firehose/service.go +++ b/vendor/github.com/aws/aws-sdk-go/service/firehose/service.go @@ -1,4 +1,4 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. package firehose @@ -11,12 +11,12 @@ import ( "github.com/aws/aws-sdk-go/private/protocol/jsonrpc" ) -// Amazon Kinesis Firehose is a fully-managed service that delivers real-time -// streaming data to destinations such as Amazon Simple Storage Service (Amazon -// S3), Amazon Elasticsearch Service (Amazon ES), and Amazon Redshift. -// The service client's operations are safe to be used concurrently. -// It is not safe to mutate any of the client's properties though. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/firehose-2015-08-04 +// Firehose provides the API operation methods for making requests to +// Amazon Kinesis Firehose. See this package's package overview docs +// for details on the service. +// +// Firehose methods are safe to use concurrently. It is not safe to +// modify mutate any of the struct's properties though. type Firehose struct { *client.Client } diff --git a/vendor/github.com/aws/aws-sdk-go/service/glacier/api.go b/vendor/github.com/aws/aws-sdk-go/service/glacier/api.go index e48809ed0..d7f703757 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/glacier/api.go +++ b/vendor/github.com/aws/aws-sdk-go/service/glacier/api.go @@ -1,11 +1,11 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. -// Package glacier provides a client for Amazon Glacier. package glacier import ( "io" + "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awsutil" "github.com/aws/aws-sdk-go/aws/request" "github.com/aws/aws-sdk-go/private/protocol" @@ -101,8 +101,23 @@ func (c *Glacier) AbortMultipartUploadRequest(input *AbortMultipartUploadInput) // func (c *Glacier) AbortMultipartUpload(input *AbortMultipartUploadInput) (*AbortMultipartUploadOutput, error) { req, out := c.AbortMultipartUploadRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// AbortMultipartUploadWithContext is the same as AbortMultipartUpload with the addition of +// the ability to pass a context and additional request options. +// +// See AbortMultipartUpload for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *Glacier) AbortMultipartUploadWithContext(ctx aws.Context, input *AbortMultipartUploadInput, opts ...request.Option) (*AbortMultipartUploadOutput, error) { + req, out := c.AbortMultipartUploadRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opAbortVaultLock = "AbortVaultLock" @@ -190,8 +205,23 @@ func (c *Glacier) AbortVaultLockRequest(input *AbortVaultLockInput) (req *reques // func (c *Glacier) AbortVaultLock(input *AbortVaultLockInput) (*AbortVaultLockOutput, error) { req, out := c.AbortVaultLockRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// AbortVaultLockWithContext is the same as AbortVaultLock with the addition of +// the ability to pass a context and additional request options. +// +// See AbortVaultLock 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 *Glacier) AbortVaultLockWithContext(ctx aws.Context, input *AbortVaultLockInput, opts ...request.Option) (*AbortVaultLockOutput, error) { + req, out := c.AbortVaultLockRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opAddTagsToVault = "AddTagsToVault" @@ -272,8 +302,23 @@ func (c *Glacier) AddTagsToVaultRequest(input *AddTagsToVaultInput) (req *reques // func (c *Glacier) AddTagsToVault(input *AddTagsToVaultInput) (*AddTagsToVaultOutput, error) { req, out := c.AddTagsToVaultRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// AddTagsToVaultWithContext is the same as AddTagsToVault with the addition of +// the ability to pass a context and additional request options. +// +// See AddTagsToVault 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 *Glacier) AddTagsToVaultWithContext(ctx aws.Context, input *AddTagsToVaultInput, opts ...request.Option) (*AddTagsToVaultOutput, error) { + req, out := c.AddTagsToVaultRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCompleteMultipartUpload = "CompleteMultipartUpload" @@ -387,8 +432,23 @@ func (c *Glacier) CompleteMultipartUploadRequest(input *CompleteMultipartUploadI // func (c *Glacier) CompleteMultipartUpload(input *CompleteMultipartUploadInput) (*ArchiveCreationOutput, error) { req, out := c.CompleteMultipartUploadRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CompleteMultipartUploadWithContext is the same as CompleteMultipartUpload with the addition of +// the ability to pass a context and additional request options. +// +// See CompleteMultipartUpload for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *Glacier) CompleteMultipartUploadWithContext(ctx aws.Context, input *CompleteMultipartUploadInput, opts ...request.Option) (*ArchiveCreationOutput, error) { + req, out := c.CompleteMultipartUploadRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCompleteVaultLock = "CompleteVaultLock" @@ -475,8 +535,23 @@ func (c *Glacier) CompleteVaultLockRequest(input *CompleteVaultLockInput) (req * // func (c *Glacier) CompleteVaultLock(input *CompleteVaultLockInput) (*CompleteVaultLockOutput, error) { req, out := c.CompleteVaultLockRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CompleteVaultLockWithContext is the same as CompleteVaultLock with the addition of +// the ability to pass a context and additional request options. +// +// See CompleteVaultLock 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 *Glacier) CompleteVaultLockWithContext(ctx aws.Context, input *CompleteVaultLockInput, opts ...request.Option) (*CompleteVaultLockOutput, error) { + req, out := c.CompleteVaultLockRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateVault = "CreateVault" @@ -569,8 +644,23 @@ func (c *Glacier) CreateVaultRequest(input *CreateVaultInput) (req *request.Requ // func (c *Glacier) CreateVault(input *CreateVaultInput) (*CreateVaultOutput, error) { req, out := c.CreateVaultRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateVaultWithContext is the same as CreateVault with the addition of +// the ability to pass a context and additional request options. +// +// See CreateVault 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 *Glacier) CreateVaultWithContext(ctx aws.Context, input *CreateVaultInput, opts ...request.Option) (*CreateVaultOutput, error) { + req, out := c.CreateVaultRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteArchive = "DeleteArchive" @@ -667,8 +757,23 @@ func (c *Glacier) DeleteArchiveRequest(input *DeleteArchiveInput) (req *request. // func (c *Glacier) DeleteArchive(input *DeleteArchiveInput) (*DeleteArchiveOutput, error) { req, out := c.DeleteArchiveRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteArchiveWithContext is the same as DeleteArchive with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteArchive 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 *Glacier) DeleteArchiveWithContext(ctx aws.Context, input *DeleteArchiveInput, opts ...request.Option) (*DeleteArchiveOutput, error) { + req, out := c.DeleteArchiveRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteVault = "DeleteVault" @@ -763,8 +868,23 @@ func (c *Glacier) DeleteVaultRequest(input *DeleteVaultInput) (req *request.Requ // func (c *Glacier) DeleteVault(input *DeleteVaultInput) (*DeleteVaultOutput, error) { req, out := c.DeleteVaultRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteVaultWithContext is the same as DeleteVault with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteVault 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 *Glacier) DeleteVaultWithContext(ctx aws.Context, input *DeleteVaultInput, opts ...request.Option) (*DeleteVaultOutput, error) { + req, out := c.DeleteVaultRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteVaultAccessPolicy = "DeleteVaultAccessPolicy" @@ -846,8 +966,23 @@ func (c *Glacier) DeleteVaultAccessPolicyRequest(input *DeleteVaultAccessPolicyI // func (c *Glacier) DeleteVaultAccessPolicy(input *DeleteVaultAccessPolicyInput) (*DeleteVaultAccessPolicyOutput, error) { req, out := c.DeleteVaultAccessPolicyRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteVaultAccessPolicyWithContext is the same as DeleteVaultAccessPolicy with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteVaultAccessPolicy 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 *Glacier) DeleteVaultAccessPolicyWithContext(ctx aws.Context, input *DeleteVaultAccessPolicyInput, opts ...request.Option) (*DeleteVaultAccessPolicyOutput, error) { + req, out := c.DeleteVaultAccessPolicyRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteVaultNotifications = "DeleteVaultNotifications" @@ -934,8 +1069,23 @@ func (c *Glacier) DeleteVaultNotificationsRequest(input *DeleteVaultNotification // func (c *Glacier) DeleteVaultNotifications(input *DeleteVaultNotificationsInput) (*DeleteVaultNotificationsOutput, error) { req, out := c.DeleteVaultNotificationsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteVaultNotificationsWithContext is the same as DeleteVaultNotifications with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteVaultNotifications 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 *Glacier) DeleteVaultNotificationsWithContext(ctx aws.Context, input *DeleteVaultNotificationsInput, opts ...request.Option) (*DeleteVaultNotificationsOutput, error) { + req, out := c.DeleteVaultNotificationsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeJob = "DescribeJob" @@ -1027,8 +1177,23 @@ func (c *Glacier) DescribeJobRequest(input *DescribeJobInput) (req *request.Requ // func (c *Glacier) DescribeJob(input *DescribeJobInput) (*JobDescription, error) { req, out := c.DescribeJobRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeJobWithContext is the same as DescribeJob with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeJob 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 *Glacier) DescribeJobWithContext(ctx aws.Context, input *DescribeJobInput, opts ...request.Option) (*JobDescription, error) { + req, out := c.DescribeJobRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeVault = "DescribeVault" @@ -1118,8 +1283,23 @@ func (c *Glacier) DescribeVaultRequest(input *DescribeVaultInput) (req *request. // func (c *Glacier) DescribeVault(input *DescribeVaultInput) (*DescribeVaultOutput, error) { req, out := c.DescribeVaultRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeVaultWithContext is the same as DescribeVault with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeVault 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 *Glacier) DescribeVaultWithContext(ctx aws.Context, input *DescribeVaultInput, opts ...request.Option) (*DescribeVaultOutput, error) { + req, out := c.DescribeVaultRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetDataRetrievalPolicy = "GetDataRetrievalPolicy" @@ -1188,8 +1368,23 @@ func (c *Glacier) GetDataRetrievalPolicyRequest(input *GetDataRetrievalPolicyInp // func (c *Glacier) GetDataRetrievalPolicy(input *GetDataRetrievalPolicyInput) (*GetDataRetrievalPolicyOutput, error) { req, out := c.GetDataRetrievalPolicyRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetDataRetrievalPolicyWithContext is the same as GetDataRetrievalPolicy with the addition of +// the ability to pass a context and additional request options. +// +// See GetDataRetrievalPolicy 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 *Glacier) GetDataRetrievalPolicyWithContext(ctx aws.Context, input *GetDataRetrievalPolicyInput, opts ...request.Option) (*GetDataRetrievalPolicyOutput, error) { + req, out := c.GetDataRetrievalPolicyRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetJobOutput = "GetJobOutput" @@ -1303,8 +1498,23 @@ func (c *Glacier) GetJobOutputRequest(input *GetJobOutputInput) (req *request.Re // func (c *Glacier) GetJobOutput(input *GetJobOutputInput) (*GetJobOutputOutput, error) { req, out := c.GetJobOutputRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetJobOutputWithContext is the same as GetJobOutput with the addition of +// the ability to pass a context and additional request options. +// +// See GetJobOutput 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 *Glacier) GetJobOutputWithContext(ctx aws.Context, input *GetJobOutputInput, opts ...request.Option) (*GetJobOutputOutput, error) { + req, out := c.GetJobOutputRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetVaultAccessPolicy = "GetVaultAccessPolicy" @@ -1380,8 +1590,23 @@ func (c *Glacier) GetVaultAccessPolicyRequest(input *GetVaultAccessPolicyInput) // func (c *Glacier) GetVaultAccessPolicy(input *GetVaultAccessPolicyInput) (*GetVaultAccessPolicyOutput, error) { req, out := c.GetVaultAccessPolicyRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetVaultAccessPolicyWithContext is the same as GetVaultAccessPolicy with the addition of +// the ability to pass a context and additional request options. +// +// See GetVaultAccessPolicy 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 *Glacier) GetVaultAccessPolicyWithContext(ctx aws.Context, input *GetVaultAccessPolicyInput, opts ...request.Option) (*GetVaultAccessPolicyOutput, error) { + req, out := c.GetVaultAccessPolicyRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetVaultLock = "GetVaultLock" @@ -1471,8 +1696,23 @@ func (c *Glacier) GetVaultLockRequest(input *GetVaultLockInput) (req *request.Re // func (c *Glacier) GetVaultLock(input *GetVaultLockInput) (*GetVaultLockOutput, error) { req, out := c.GetVaultLockRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetVaultLockWithContext is the same as GetVaultLock with the addition of +// the ability to pass a context and additional request options. +// +// See GetVaultLock 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 *Glacier) GetVaultLockWithContext(ctx aws.Context, input *GetVaultLockInput, opts ...request.Option) (*GetVaultLockOutput, error) { + req, out := c.GetVaultLockRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetVaultNotifications = "GetVaultNotifications" @@ -1561,8 +1801,23 @@ func (c *Glacier) GetVaultNotificationsRequest(input *GetVaultNotificationsInput // func (c *Glacier) GetVaultNotifications(input *GetVaultNotificationsInput) (*GetVaultNotificationsOutput, error) { req, out := c.GetVaultNotificationsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetVaultNotificationsWithContext is the same as GetVaultNotifications with the addition of +// the ability to pass a context and additional request options. +// +// See GetVaultNotifications 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 *Glacier) GetVaultNotificationsWithContext(ctx aws.Context, input *GetVaultNotificationsInput, opts ...request.Option) (*GetVaultNotificationsOutput, error) { + req, out := c.GetVaultNotificationsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opInitiateJob = "InitiateJob" @@ -1777,8 +2032,23 @@ func (c *Glacier) InitiateJobRequest(input *InitiateJobInput) (req *request.Requ // func (c *Glacier) InitiateJob(input *InitiateJobInput) (*InitiateJobOutput, error) { req, out := c.InitiateJobRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// InitiateJobWithContext is the same as InitiateJob with the addition of +// the ability to pass a context and additional request options. +// +// See InitiateJob 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 *Glacier) InitiateJobWithContext(ctx aws.Context, input *InitiateJobInput, opts ...request.Option) (*InitiateJobOutput, error) { + req, out := c.InitiateJobRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opInitiateMultipartUpload = "InitiateMultipartUpload" @@ -1883,8 +2153,23 @@ func (c *Glacier) InitiateMultipartUploadRequest(input *InitiateMultipartUploadI // func (c *Glacier) InitiateMultipartUpload(input *InitiateMultipartUploadInput) (*InitiateMultipartUploadOutput, error) { req, out := c.InitiateMultipartUploadRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// InitiateMultipartUploadWithContext is the same as InitiateMultipartUpload with the addition of +// the ability to pass a context and additional request options. +// +// See InitiateMultipartUpload 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 *Glacier) InitiateMultipartUploadWithContext(ctx aws.Context, input *InitiateMultipartUploadInput, opts ...request.Option) (*InitiateMultipartUploadOutput, error) { + req, out := c.InitiateMultipartUploadRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opInitiateVaultLock = "InitiateVaultLock" @@ -1983,8 +2268,23 @@ func (c *Glacier) InitiateVaultLockRequest(input *InitiateVaultLockInput) (req * // func (c *Glacier) InitiateVaultLock(input *InitiateVaultLockInput) (*InitiateVaultLockOutput, error) { req, out := c.InitiateVaultLockRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// InitiateVaultLockWithContext is the same as InitiateVaultLock with the addition of +// the ability to pass a context and additional request options. +// +// See InitiateVaultLock 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 *Glacier) InitiateVaultLockWithContext(ctx aws.Context, input *InitiateVaultLockInput, opts ...request.Option) (*InitiateVaultLockOutput, error) { + req, out := c.InitiateVaultLockRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opListJobs = "ListJobs" @@ -2100,8 +2400,23 @@ func (c *Glacier) ListJobsRequest(input *ListJobsInput) (req *request.Request, o // func (c *Glacier) ListJobs(input *ListJobsInput) (*ListJobsOutput, error) { req, out := c.ListJobsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListJobsWithContext is the same as ListJobs with the addition of +// the ability to pass a context and additional request options. +// +// See ListJobs 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 *Glacier) ListJobsWithContext(ctx aws.Context, input *ListJobsInput, opts ...request.Option) (*ListJobsOutput, error) { + req, out := c.ListJobsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // ListJobsPages iterates over the pages of a ListJobs operation, @@ -2121,12 +2436,37 @@ func (c *Glacier) ListJobs(input *ListJobsInput) (*ListJobsOutput, error) { // return pageNum <= 3 // }) // -func (c *Glacier) ListJobsPages(input *ListJobsInput, fn func(p *ListJobsOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.ListJobsRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*ListJobsOutput), lastPage) - }) +func (c *Glacier) ListJobsPages(input *ListJobsInput, fn func(*ListJobsOutput, bool) bool) error { + return c.ListJobsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListJobsPagesWithContext same as ListJobsPages 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 *Glacier) ListJobsPagesWithContext(ctx aws.Context, input *ListJobsInput, fn func(*ListJobsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListJobsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListJobsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*ListJobsOutput), !p.HasNextPage()) + } + return p.Err() } const opListMultipartUploads = "ListMultipartUploads" @@ -2232,8 +2572,23 @@ func (c *Glacier) ListMultipartUploadsRequest(input *ListMultipartUploadsInput) // func (c *Glacier) ListMultipartUploads(input *ListMultipartUploadsInput) (*ListMultipartUploadsOutput, error) { req, out := c.ListMultipartUploadsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListMultipartUploadsWithContext is the same as ListMultipartUploads with the addition of +// the ability to pass a context and additional request options. +// +// See ListMultipartUploads for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *Glacier) ListMultipartUploadsWithContext(ctx aws.Context, input *ListMultipartUploadsInput, opts ...request.Option) (*ListMultipartUploadsOutput, error) { + req, out := c.ListMultipartUploadsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // ListMultipartUploadsPages iterates over the pages of a ListMultipartUploads operation, @@ -2253,12 +2608,37 @@ func (c *Glacier) ListMultipartUploads(input *ListMultipartUploadsInput) (*ListM // return pageNum <= 3 // }) // -func (c *Glacier) ListMultipartUploadsPages(input *ListMultipartUploadsInput, fn func(p *ListMultipartUploadsOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.ListMultipartUploadsRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*ListMultipartUploadsOutput), lastPage) - }) +func (c *Glacier) ListMultipartUploadsPages(input *ListMultipartUploadsInput, fn func(*ListMultipartUploadsOutput, bool) bool) error { + return c.ListMultipartUploadsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListMultipartUploadsPagesWithContext same as ListMultipartUploadsPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *Glacier) ListMultipartUploadsPagesWithContext(ctx aws.Context, input *ListMultipartUploadsInput, fn func(*ListMultipartUploadsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListMultipartUploadsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListMultipartUploadsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*ListMultipartUploadsOutput), !p.HasNextPage()) + } + return p.Err() } const opListParts = "ListParts" @@ -2358,8 +2738,23 @@ func (c *Glacier) ListPartsRequest(input *ListPartsInput) (req *request.Request, // func (c *Glacier) ListParts(input *ListPartsInput) (*ListPartsOutput, error) { req, out := c.ListPartsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListPartsWithContext is the same as ListParts with the addition of +// the ability to pass a context and additional request options. +// +// See ListParts for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *Glacier) ListPartsWithContext(ctx aws.Context, input *ListPartsInput, opts ...request.Option) (*ListPartsOutput, error) { + req, out := c.ListPartsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // ListPartsPages iterates over the pages of a ListParts operation, @@ -2379,12 +2774,37 @@ func (c *Glacier) ListParts(input *ListPartsInput) (*ListPartsOutput, error) { // return pageNum <= 3 // }) // -func (c *Glacier) ListPartsPages(input *ListPartsInput, fn func(p *ListPartsOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.ListPartsRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*ListPartsOutput), lastPage) - }) +func (c *Glacier) ListPartsPages(input *ListPartsInput, fn func(*ListPartsOutput, bool) bool) error { + return c.ListPartsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListPartsPagesWithContext same as ListPartsPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *Glacier) ListPartsPagesWithContext(ctx aws.Context, input *ListPartsInput, fn func(*ListPartsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListPartsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListPartsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*ListPartsOutput), !p.HasNextPage()) + } + return p.Err() } const opListProvisionedCapacity = "ListProvisionedCapacity" @@ -2451,8 +2871,23 @@ func (c *Glacier) ListProvisionedCapacityRequest(input *ListProvisionedCapacityI // func (c *Glacier) ListProvisionedCapacity(input *ListProvisionedCapacityInput) (*ListProvisionedCapacityOutput, error) { req, out := c.ListProvisionedCapacityRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListProvisionedCapacityWithContext is the same as ListProvisionedCapacity with the addition of +// the ability to pass a context and additional request options. +// +// See ListProvisionedCapacity 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 *Glacier) ListProvisionedCapacityWithContext(ctx aws.Context, input *ListProvisionedCapacityInput, opts ...request.Option) (*ListProvisionedCapacityOutput, error) { + req, out := c.ListProvisionedCapacityRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opListTagsForVault = "ListTagsForVault" @@ -2525,8 +2960,23 @@ func (c *Glacier) ListTagsForVaultRequest(input *ListTagsForVaultInput) (req *re // func (c *Glacier) ListTagsForVault(input *ListTagsForVaultInput) (*ListTagsForVaultOutput, error) { req, out := c.ListTagsForVaultRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListTagsForVaultWithContext is the same as ListTagsForVault with the addition of +// the ability to pass a context and additional request options. +// +// See ListTagsForVault 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 *Glacier) ListTagsForVaultWithContext(ctx aws.Context, input *ListTagsForVaultInput, opts ...request.Option) (*ListTagsForVaultOutput, error) { + req, out := c.ListTagsForVaultRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opListVaults = "ListVaults" @@ -2623,8 +3073,23 @@ func (c *Glacier) ListVaultsRequest(input *ListVaultsInput) (req *request.Reques // func (c *Glacier) ListVaults(input *ListVaultsInput) (*ListVaultsOutput, error) { req, out := c.ListVaultsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListVaultsWithContext is the same as ListVaults with the addition of +// the ability to pass a context and additional request options. +// +// See ListVaults 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 *Glacier) ListVaultsWithContext(ctx aws.Context, input *ListVaultsInput, opts ...request.Option) (*ListVaultsOutput, error) { + req, out := c.ListVaultsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // ListVaultsPages iterates over the pages of a ListVaults operation, @@ -2644,12 +3109,37 @@ func (c *Glacier) ListVaults(input *ListVaultsInput) (*ListVaultsOutput, error) // return pageNum <= 3 // }) // -func (c *Glacier) ListVaultsPages(input *ListVaultsInput, fn func(p *ListVaultsOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.ListVaultsRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*ListVaultsOutput), lastPage) - }) +func (c *Glacier) ListVaultsPages(input *ListVaultsInput, fn func(*ListVaultsOutput, bool) bool) error { + return c.ListVaultsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListVaultsPagesWithContext same as ListVaultsPages 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 *Glacier) ListVaultsPagesWithContext(ctx aws.Context, input *ListVaultsInput, fn func(*ListVaultsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListVaultsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListVaultsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*ListVaultsOutput), !p.HasNextPage()) + } + return p.Err() } const opPurchaseProvisionedCapacity = "PurchaseProvisionedCapacity" @@ -2719,8 +3209,23 @@ func (c *Glacier) PurchaseProvisionedCapacityRequest(input *PurchaseProvisionedC // func (c *Glacier) PurchaseProvisionedCapacity(input *PurchaseProvisionedCapacityInput) (*PurchaseProvisionedCapacityOutput, error) { req, out := c.PurchaseProvisionedCapacityRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// PurchaseProvisionedCapacityWithContext is the same as PurchaseProvisionedCapacity with the addition of +// the ability to pass a context and additional request options. +// +// See PurchaseProvisionedCapacity 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 *Glacier) PurchaseProvisionedCapacityWithContext(ctx aws.Context, input *PurchaseProvisionedCapacityInput, opts ...request.Option) (*PurchaseProvisionedCapacityOutput, error) { + req, out := c.PurchaseProvisionedCapacityRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opRemoveTagsFromVault = "RemoveTagsFromVault" @@ -2797,8 +3302,23 @@ func (c *Glacier) RemoveTagsFromVaultRequest(input *RemoveTagsFromVaultInput) (r // func (c *Glacier) RemoveTagsFromVault(input *RemoveTagsFromVaultInput) (*RemoveTagsFromVaultOutput, error) { req, out := c.RemoveTagsFromVaultRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// RemoveTagsFromVaultWithContext is the same as RemoveTagsFromVault with the addition of +// the ability to pass a context and additional request options. +// +// See RemoveTagsFromVault 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 *Glacier) RemoveTagsFromVaultWithContext(ctx aws.Context, input *RemoveTagsFromVaultInput, opts ...request.Option) (*RemoveTagsFromVaultOutput, error) { + req, out := c.RemoveTagsFromVaultRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opSetDataRetrievalPolicy = "SetDataRetrievalPolicy" @@ -2873,8 +3393,23 @@ func (c *Glacier) SetDataRetrievalPolicyRequest(input *SetDataRetrievalPolicyInp // func (c *Glacier) SetDataRetrievalPolicy(input *SetDataRetrievalPolicyInput) (*SetDataRetrievalPolicyOutput, error) { req, out := c.SetDataRetrievalPolicyRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// SetDataRetrievalPolicyWithContext is the same as SetDataRetrievalPolicy with the addition of +// the ability to pass a context and additional request options. +// +// See SetDataRetrievalPolicy 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 *Glacier) SetDataRetrievalPolicyWithContext(ctx aws.Context, input *SetDataRetrievalPolicyInput, opts ...request.Option) (*SetDataRetrievalPolicyOutput, error) { + req, out := c.SetDataRetrievalPolicyRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opSetVaultAccessPolicy = "SetVaultAccessPolicy" @@ -2953,8 +3488,23 @@ func (c *Glacier) SetVaultAccessPolicyRequest(input *SetVaultAccessPolicyInput) // func (c *Glacier) SetVaultAccessPolicy(input *SetVaultAccessPolicyInput) (*SetVaultAccessPolicyOutput, error) { req, out := c.SetVaultAccessPolicyRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// SetVaultAccessPolicyWithContext is the same as SetVaultAccessPolicy with the addition of +// the ability to pass a context and additional request options. +// +// See SetVaultAccessPolicy 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 *Glacier) SetVaultAccessPolicyWithContext(ctx aws.Context, input *SetVaultAccessPolicyInput, opts ...request.Option) (*SetVaultAccessPolicyOutput, error) { + req, out := c.SetVaultAccessPolicyRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opSetVaultNotifications = "SetVaultNotifications" @@ -3058,8 +3608,23 @@ func (c *Glacier) SetVaultNotificationsRequest(input *SetVaultNotificationsInput // func (c *Glacier) SetVaultNotifications(input *SetVaultNotificationsInput) (*SetVaultNotificationsOutput, error) { req, out := c.SetVaultNotificationsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// SetVaultNotificationsWithContext is the same as SetVaultNotifications with the addition of +// the ability to pass a context and additional request options. +// +// See SetVaultNotifications 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 *Glacier) SetVaultNotificationsWithContext(ctx aws.Context, input *SetVaultNotificationsInput, opts ...request.Option) (*SetVaultNotificationsOutput, error) { + req, out := c.SetVaultNotificationsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opUploadArchive = "UploadArchive" @@ -3169,8 +3734,23 @@ func (c *Glacier) UploadArchiveRequest(input *UploadArchiveInput) (req *request. // func (c *Glacier) UploadArchive(input *UploadArchiveInput) (*ArchiveCreationOutput, error) { req, out := c.UploadArchiveRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// UploadArchiveWithContext is the same as UploadArchive with the addition of +// the ability to pass a context and additional request options. +// +// See UploadArchive 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 *Glacier) UploadArchiveWithContext(ctx aws.Context, input *UploadArchiveInput, opts ...request.Option) (*ArchiveCreationOutput, error) { + req, out := c.UploadArchiveRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opUploadMultipartPart = "UploadMultipartPart" @@ -3290,8 +3870,23 @@ func (c *Glacier) UploadMultipartPartRequest(input *UploadMultipartPartInput) (r // func (c *Glacier) UploadMultipartPart(input *UploadMultipartPartInput) (*UploadMultipartPartOutput, error) { req, out := c.UploadMultipartPartRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// UploadMultipartPartWithContext is the same as UploadMultipartPart with the addition of +// the ability to pass a context and additional request options. +// +// See UploadMultipartPart 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 *Glacier) UploadMultipartPartWithContext(ctx aws.Context, input *UploadMultipartPartInput, opts ...request.Option) (*UploadMultipartPartOutput, error) { + req, out := c.UploadMultipartPartRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // Provides options to abort a multipart upload identified by the upload ID. diff --git a/vendor/github.com/aws/aws-sdk-go/service/glacier/doc.go b/vendor/github.com/aws/aws-sdk-go/service/glacier/doc.go new file mode 100644 index 000000000..1aa05e8e8 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/service/glacier/doc.go @@ -0,0 +1,108 @@ +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. + +// Package glacier provides the client and types for making API +// requests to Amazon Glacier. +// +// Amazon Glacier is a storage solution for "cold data." +// +// Amazon Glacier is an extremely low-cost storage service that provides secure, +// durable, and easy-to-use storage for data backup and archival. With Amazon +// Glacier, customers can store their data cost effectively for months, years, +// or decades. Amazon Glacier also enables customers to offload the administrative +// burdens of operating and scaling storage to AWS, so they don't have to worry +// about capacity planning, hardware provisioning, data replication, hardware +// failure and recovery, or time-consuming hardware migrations. +// +// Amazon Glacier is a great storage choice when low storage cost is paramount, +// your data is rarely retrieved, and retrieval latency of several hours is +// acceptable. If your application requires fast or frequent access to your +// data, consider using Amazon S3. For more information, see Amazon Simple Storage +// Service (Amazon S3) (http://aws.amazon.com/s3/). +// +// You can store any kind of data in any format. There is no maximum limit on +// the total amount of data you can store in Amazon Glacier. +// +// If you are a first-time user of Amazon Glacier, we recommend that you begin +// by reading the following sections in the Amazon Glacier Developer Guide: +// +// * What is Amazon Glacier (http://docs.aws.amazon.com/amazonglacier/latest/dev/introduction.html) +// - This section of the Developer Guide describes the underlying data model, +// the operations it supports, and the AWS SDKs that you can use to interact +// with the service. +// +// * Getting Started with Amazon Glacier (http://docs.aws.amazon.com/amazonglacier/latest/dev/amazon-glacier-getting-started.html) +// - The Getting Started section walks you through the process of creating +// a vault, uploading archives, creating jobs to download archives, retrieving +// the job output, and deleting archives. +// +// See glacier package documentation for more information. +// https://docs.aws.amazon.com/sdk-for-go/api/service/glacier/ +// +// Using the Client +// +// To use the client for Amazon Glacier you will first need +// to create a new instance of it. +// +// When creating a client for an AWS service you'll first need to have a Session +// already created. The Session provides configuration that can be shared +// between multiple service clients. Additional configuration can be applied to +// the Session and service's client when they are constructed. The aws package's +// Config type contains several fields such as Region for the AWS Region the +// client should make API requests too. The optional Config value can be provided +// as the variadic argument for Sessions and client creation. +// +// Once the service's client is created you can use it to make API requests the +// AWS service. These clients are safe to use concurrently. +// +// // Create a session to share configuration, and load external configuration. +// sess := session.Must(session.NewSession()) +// +// // Create the service's client with the session. +// svc := glacier.New(sess) +// +// See the SDK's documentation for more information on how to use service clients. +// https://docs.aws.amazon.com/sdk-for-go/api/ +// +// See aws package's Config type for more information on configuration options. +// https://docs.aws.amazon.com/sdk-for-go/api/aws/#Config +// +// See the Amazon Glacier client Glacier for more +// information on creating the service's client. +// https://docs.aws.amazon.com/sdk-for-go/api/service/glacier/#New +// +// Once the client is created you can make an API request to the service. +// Each API method takes a input parameter, and returns the service response +// and an error. +// +// The API method will document which error codes the service can be returned +// by the operation if the service models the API operation's errors. These +// errors will also be available as const strings prefixed with "ErrCode". +// +// result, err := svc.AbortMultipartUpload(params) +// if err != nil { +// // Cast err to awserr.Error to handle specific error codes. +// aerr, ok := err.(awserr.Error) +// if ok && aerr.Code() == { +// // Specific error code handling +// } +// return err +// } +// +// fmt.Println("AbortMultipartUpload result:") +// fmt.Println(result) +// +// Using the Client with Context +// +// The service's client also provides methods to make API requests with a Context +// value. This allows you to control the timeout, and cancellation of pending +// requests. These methods also take request Option as variadic parameter to apply +// additional configuration to the API request. +// +// ctx := context.Background() +// +// result, err := svc.AbortMultipartUploadWithContext(ctx, params) +// +// See the request package documentation for more information on using Context pattern +// with the SDK. +// https://docs.aws.amazon.com/sdk-for-go/api/aws/request/ +package glacier diff --git a/vendor/github.com/aws/aws-sdk-go/service/glacier/errors.go b/vendor/github.com/aws/aws-sdk-go/service/glacier/errors.go index 9ce95315a..c47e3bb30 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/glacier/errors.go +++ b/vendor/github.com/aws/aws-sdk-go/service/glacier/errors.go @@ -1,4 +1,4 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. package glacier diff --git a/vendor/github.com/aws/aws-sdk-go/service/glacier/service.go b/vendor/github.com/aws/aws-sdk-go/service/glacier/service.go index d668dde26..b875f0faf 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/glacier/service.go +++ b/vendor/github.com/aws/aws-sdk-go/service/glacier/service.go @@ -1,4 +1,4 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. package glacier @@ -11,39 +11,12 @@ import ( "github.com/aws/aws-sdk-go/private/protocol/restjson" ) -// Amazon Glacier is a storage solution for "cold data." +// Glacier provides the API operation methods for making requests to +// Amazon Glacier. See this package's package overview docs +// for details on the service. // -// Amazon Glacier is an extremely low-cost storage service that provides secure, -// durable, and easy-to-use storage for data backup and archival. With Amazon -// Glacier, customers can store their data cost effectively for months, years, -// or decades. Amazon Glacier also enables customers to offload the administrative -// burdens of operating and scaling storage to AWS, so they don't have to worry -// about capacity planning, hardware provisioning, data replication, hardware -// failure and recovery, or time-consuming hardware migrations. -// -// Amazon Glacier is a great storage choice when low storage cost is paramount, -// your data is rarely retrieved, and retrieval latency of several hours is -// acceptable. If your application requires fast or frequent access to your -// data, consider using Amazon S3. For more information, see Amazon Simple Storage -// Service (Amazon S3) (http://aws.amazon.com/s3/). -// -// You can store any kind of data in any format. There is no maximum limit on -// the total amount of data you can store in Amazon Glacier. -// -// If you are a first-time user of Amazon Glacier, we recommend that you begin -// by reading the following sections in the Amazon Glacier Developer Guide: -// -// * What is Amazon Glacier (http://docs.aws.amazon.com/amazonglacier/latest/dev/introduction.html) -// - This section of the Developer Guide describes the underlying data model, -// the operations it supports, and the AWS SDKs that you can use to interact -// with the service. -// -// * Getting Started with Amazon Glacier (http://docs.aws.amazon.com/amazonglacier/latest/dev/amazon-glacier-getting-started.html) -// - The Getting Started section walks you through the process of creating -// a vault, uploading archives, creating jobs to download archives, retrieving -// the job output, and deleting archives. -// The service client's operations are safe to be used concurrently. -// It is not safe to mutate any of the client's properties though. +// Glacier methods are safe to use concurrently. It is not safe to +// modify mutate any of the struct's properties though. type Glacier struct { *client.Client } diff --git a/vendor/github.com/aws/aws-sdk-go/service/glacier/treehash.go b/vendor/github.com/aws/aws-sdk-go/service/glacier/treehash.go index dac44baf5..e1ee0aa5b 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/glacier/treehash.go +++ b/vendor/github.com/aws/aws-sdk-go/service/glacier/treehash.go @@ -15,6 +15,8 @@ type Hash struct { } // ComputeHashes computes the tree-hash and linear hash of a seekable reader r. +// +// See http://docs.aws.amazon.com/amazonglacier/latest/dev/checksum-calculations.html for more information. func ComputeHashes(r io.ReadSeeker) Hash { r.Seek(0, 0) // Read the whole stream defer r.Seek(0, 0) // Rewind stream at end @@ -41,12 +43,16 @@ func ComputeHashes(r io.ReadSeeker) Hash { return Hash{ LinearHash: hsh.Sum(nil), - TreeHash: buildHashTree(hashes), + TreeHash: ComputeTreeHash(hashes), } } -// buildHashTree builds a hash tree root node given a set of hashes. -func buildHashTree(hashes [][]byte) []byte { +// ComputeTreeHash builds a tree hash root node given a slice of +// hashes. Glacier tree hash to be derived from SHA256 hashes of 1MB +// chucks of the data. +// +// See http://docs.aws.amazon.com/amazonglacier/latest/dev/checksum-calculations.html for more information. +func ComputeTreeHash(hashes [][]byte) []byte { if hashes == nil || len(hashes) == 0 { return nil } diff --git a/vendor/github.com/aws/aws-sdk-go/service/glacier/waiters.go b/vendor/github.com/aws/aws-sdk-go/service/glacier/waiters.go index fd33dc977..342fe25e7 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/glacier/waiters.go +++ b/vendor/github.com/aws/aws-sdk-go/service/glacier/waiters.go @@ -1,9 +1,12 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. package glacier import ( - "github.com/aws/aws-sdk-go/private/waiter" + "time" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/request" ) // WaitUntilVaultExists uses the Amazon Glacier API operation @@ -11,32 +14,50 @@ import ( // If the condition is not meet within the max attempt window an error will // be returned. func (c *Glacier) WaitUntilVaultExists(input *DescribeVaultInput) error { - waiterCfg := waiter.Config{ - Operation: "DescribeVault", - Delay: 3, + return c.WaitUntilVaultExistsWithContext(aws.BackgroundContext(), input) +} + +// WaitUntilVaultExistsWithContext is an extended version of WaitUntilVaultExists. +// 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 *Glacier) WaitUntilVaultExistsWithContext(ctx aws.Context, input *DescribeVaultInput, opts ...request.WaiterOption) error { + w := request.Waiter{ + Name: "WaitUntilVaultExists", MaxAttempts: 15, - Acceptors: []waiter.WaitAcceptor{ + Delay: request.ConstantWaiterDelay(3 * time.Second), + Acceptors: []request.WaiterAcceptor{ { - State: "success", - Matcher: "status", - Argument: "", + State: request.SuccessWaiterState, + Matcher: request.StatusWaiterMatch, Expected: 200, }, { - State: "retry", - Matcher: "error", - Argument: "", + State: request.RetryWaiterState, + Matcher: request.ErrorWaiterMatch, Expected: "ResourceNotFoundException", }, }, + Logger: c.Config.Logger, + NewRequest: func(opts []request.Option) (*request.Request, error) { + var inCpy *DescribeVaultInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeVaultRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, } + w.ApplyOptions(opts...) - w := waiter.Waiter{ - Client: c, - Input: input, - Config: waiterCfg, - } - return w.Wait() + return w.WaitWithContext(ctx) } // WaitUntilVaultNotExists uses the Amazon Glacier API operation @@ -44,30 +65,48 @@ func (c *Glacier) WaitUntilVaultExists(input *DescribeVaultInput) error { // If the condition is not meet within the max attempt window an error will // be returned. func (c *Glacier) WaitUntilVaultNotExists(input *DescribeVaultInput) error { - waiterCfg := waiter.Config{ - Operation: "DescribeVault", - Delay: 3, + return c.WaitUntilVaultNotExistsWithContext(aws.BackgroundContext(), input) +} + +// WaitUntilVaultNotExistsWithContext is an extended version of WaitUntilVaultNotExists. +// 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 *Glacier) WaitUntilVaultNotExistsWithContext(ctx aws.Context, input *DescribeVaultInput, opts ...request.WaiterOption) error { + w := request.Waiter{ + Name: "WaitUntilVaultNotExists", MaxAttempts: 15, - Acceptors: []waiter.WaitAcceptor{ + Delay: request.ConstantWaiterDelay(3 * time.Second), + Acceptors: []request.WaiterAcceptor{ { - State: "retry", - Matcher: "status", - Argument: "", + State: request.RetryWaiterState, + Matcher: request.StatusWaiterMatch, Expected: 200, }, { - State: "success", - Matcher: "error", - Argument: "", + State: request.SuccessWaiterState, + Matcher: request.ErrorWaiterMatch, Expected: "ResourceNotFoundException", }, }, + Logger: c.Config.Logger, + NewRequest: func(opts []request.Option) (*request.Request, error) { + var inCpy *DescribeVaultInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeVaultRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, } + w.ApplyOptions(opts...) - w := waiter.Waiter{ - Client: c, - Input: input, - Config: waiterCfg, - } - return w.Wait() + return w.WaitWithContext(ctx) } diff --git a/vendor/github.com/aws/aws-sdk-go/service/iam/api.go b/vendor/github.com/aws/aws-sdk-go/service/iam/api.go index e41818673..9e73c1108 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 @@ -1,12 +1,12 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. -// Package iam provides a client for AWS Identity and Access Management. package iam import ( "fmt" "time" + "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awsutil" "github.com/aws/aws-sdk-go/aws/request" "github.com/aws/aws-sdk-go/private/protocol" @@ -93,8 +93,23 @@ func (c *IAM) AddClientIDToOpenIDConnectProviderRequest(input *AddClientIDToOpen // Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/AddClientIDToOpenIDConnectProvider func (c *IAM) AddClientIDToOpenIDConnectProvider(input *AddClientIDToOpenIDConnectProviderInput) (*AddClientIDToOpenIDConnectProviderOutput, error) { req, out := c.AddClientIDToOpenIDConnectProviderRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// AddClientIDToOpenIDConnectProviderWithContext is the same as AddClientIDToOpenIDConnectProvider with the addition of +// the ability to pass a context and additional request options. +// +// See AddClientIDToOpenIDConnectProvider 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 *IAM) AddClientIDToOpenIDConnectProviderWithContext(ctx aws.Context, input *AddClientIDToOpenIDConnectProviderInput, opts ...request.Option) (*AddClientIDToOpenIDConnectProviderOutput, error) { + req, out := c.AddClientIDToOpenIDConnectProviderRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opAddRoleToInstanceProfile = "AddRoleToInstanceProfile" @@ -144,7 +159,8 @@ 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. +// Adds the specified IAM role to the specified instance profile. An instance +// profile can contain only one role, and this limit cannot be increased. // // The caller of this API must be granted the PassRole permission on the IAM // role by a permission policy. @@ -173,6 +189,12 @@ func (c *IAM) AddRoleToInstanceProfileRequest(input *AddRoleToInstanceProfileInp // The request was rejected because it attempted to create resources beyond // the current AWS account limits. The error message describes the limit exceeded. // +// * ErrCodeUnmodifiableEntityException "UnmodifiableEntity" +// The request was rejected because only the service that depends on the service-linked +// role can modify or delete the role on your behalf. The error message includes +// the name of the service that depends on this service-linked role. You must +// request the change through that service. +// // * ErrCodeServiceFailureException "ServiceFailure" // The request processing has failed because of an unknown error, exception // or failure. @@ -180,8 +202,23 @@ func (c *IAM) AddRoleToInstanceProfileRequest(input *AddRoleToInstanceProfileInp // Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/AddRoleToInstanceProfile func (c *IAM) AddRoleToInstanceProfile(input *AddRoleToInstanceProfileInput) (*AddRoleToInstanceProfileOutput, error) { req, out := c.AddRoleToInstanceProfileRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// AddRoleToInstanceProfileWithContext is the same as AddRoleToInstanceProfile with the addition of +// the ability to pass a context and additional request options. +// +// See AddRoleToInstanceProfile 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 *IAM) AddRoleToInstanceProfileWithContext(ctx aws.Context, input *AddRoleToInstanceProfileInput, opts ...request.Option) (*AddRoleToInstanceProfileOutput, error) { + req, out := c.AddRoleToInstanceProfileRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opAddUserToGroup = "AddUserToGroup" @@ -256,8 +293,23 @@ func (c *IAM) AddUserToGroupRequest(input *AddUserToGroupInput) (req *request.Re // Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/AddUserToGroup func (c *IAM) AddUserToGroup(input *AddUserToGroupInput) (*AddUserToGroupOutput, error) { req, out := c.AddUserToGroupRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// AddUserToGroupWithContext is the same as AddUserToGroup with the addition of +// the ability to pass a context and additional request options. +// +// See AddUserToGroup 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 *IAM) AddUserToGroupWithContext(ctx aws.Context, input *AddUserToGroupInput, opts ...request.Option) (*AddUserToGroupOutput, error) { + req, out := c.AddUserToGroupRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opAttachGroupPolicy = "AttachGroupPolicy" @@ -343,8 +395,23 @@ func (c *IAM) AttachGroupPolicyRequest(input *AttachGroupPolicyInput) (req *requ // Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/AttachGroupPolicy func (c *IAM) AttachGroupPolicy(input *AttachGroupPolicyInput) (*AttachGroupPolicyOutput, error) { req, out := c.AttachGroupPolicyRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// AttachGroupPolicyWithContext is the same as AttachGroupPolicy with the addition of +// the ability to pass a context and additional request options. +// +// See AttachGroupPolicy 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 *IAM) AttachGroupPolicyWithContext(ctx aws.Context, input *AttachGroupPolicyInput, opts ...request.Option) (*AttachGroupPolicyOutput, error) { + req, out := c.AttachGroupPolicyRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opAttachRolePolicy = "AttachRolePolicy" @@ -394,13 +461,13 @@ func (c *IAM) AttachRolePolicyRequest(input *AttachRolePolicyInput) (req *reques // AttachRolePolicy API operation for AWS Identity and Access Management. // -// Attaches the specified managed policy to the specified IAM role. +// Attaches the specified managed policy to the specified IAM role. When you +// attach a managed policy to a role, the managed policy becomes part of the +// role's permission (access) policy. // -// When you attach a managed policy to a role, the managed policy becomes part -// of the role's permission (access) policy. You cannot use a managed policy -// as the role's trust policy. The role's trust policy is created at the same -// time as the role, using CreateRole. You can update a role's trust policy -// using UpdateAssumeRolePolicy. +// You cannot use a managed policy as the role's trust policy. The role's trust +// policy is created at the same time as the role, using CreateRole. You can +// update a role's trust policy using UpdateAssumeRolePolicy. // // Use this API to attach a managed policy to a role. To embed an inline policy // in a role, use PutRolePolicy. For more information about policies, see Managed @@ -427,6 +494,12 @@ func (c *IAM) AttachRolePolicyRequest(input *AttachRolePolicyInput) (req *reques // The request was rejected because an invalid or out-of-range value was supplied // for an input parameter. // +// * ErrCodeUnmodifiableEntityException "UnmodifiableEntity" +// The request was rejected because only the service that depends on the service-linked +// role can modify or delete the role on your behalf. The error message includes +// the name of the service that depends on this service-linked role. You must +// request the change through that service. +// // * ErrCodeServiceFailureException "ServiceFailure" // The request processing has failed because of an unknown error, exception // or failure. @@ -434,8 +507,23 @@ func (c *IAM) AttachRolePolicyRequest(input *AttachRolePolicyInput) (req *reques // Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/AttachRolePolicy func (c *IAM) AttachRolePolicy(input *AttachRolePolicyInput) (*AttachRolePolicyOutput, error) { req, out := c.AttachRolePolicyRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// AttachRolePolicyWithContext is the same as AttachRolePolicy with the addition of +// the ability to pass a context and additional request options. +// +// See AttachRolePolicy 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 *IAM) AttachRolePolicyWithContext(ctx aws.Context, input *AttachRolePolicyInput, opts ...request.Option) (*AttachRolePolicyOutput, error) { + req, out := c.AttachRolePolicyRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opAttachUserPolicy = "AttachUserPolicy" @@ -521,8 +609,23 @@ func (c *IAM) AttachUserPolicyRequest(input *AttachUserPolicyInput) (req *reques // Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/AttachUserPolicy func (c *IAM) AttachUserPolicy(input *AttachUserPolicyInput) (*AttachUserPolicyOutput, error) { req, out := c.AttachUserPolicyRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// AttachUserPolicyWithContext is the same as AttachUserPolicy with the addition of +// the ability to pass a context and additional request options. +// +// See AttachUserPolicy 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 *IAM) AttachUserPolicyWithContext(ctx aws.Context, input *AttachUserPolicyInput, opts ...request.Option) (*AttachUserPolicyOutput, error) { + req, out := c.AttachUserPolicyRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opChangePassword = "ChangePassword" @@ -616,8 +719,23 @@ func (c *IAM) ChangePasswordRequest(input *ChangePasswordInput) (req *request.Re // Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ChangePassword func (c *IAM) ChangePassword(input *ChangePasswordInput) (*ChangePasswordOutput, error) { req, out := c.ChangePasswordRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ChangePasswordWithContext is the same as ChangePassword with the addition of +// the ability to pass a context and additional request options. +// +// See ChangePassword 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 *IAM) ChangePasswordWithContext(ctx aws.Context, input *ChangePasswordInput, opts ...request.Option) (*ChangePasswordOutput, error) { + req, out := c.ChangePasswordRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateAccessKey = "CreateAccessKey" @@ -706,8 +824,23 @@ func (c *IAM) CreateAccessKeyRequest(input *CreateAccessKeyInput) (req *request. // Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/CreateAccessKey func (c *IAM) CreateAccessKey(input *CreateAccessKeyInput) (*CreateAccessKeyOutput, error) { req, out := c.CreateAccessKeyRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateAccessKeyWithContext is the same as CreateAccessKey with the addition of +// the ability to pass a context and additional request options. +// +// See CreateAccessKey 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 *IAM) CreateAccessKeyWithContext(ctx aws.Context, input *CreateAccessKeyInput, opts ...request.Option) (*CreateAccessKeyOutput, error) { + req, out := c.CreateAccessKeyRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateAccountAlias = "CreateAccountAlias" @@ -784,8 +917,23 @@ func (c *IAM) CreateAccountAliasRequest(input *CreateAccountAliasInput) (req *re // Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/CreateAccountAlias func (c *IAM) CreateAccountAlias(input *CreateAccountAliasInput) (*CreateAccountAliasOutput, error) { req, out := c.CreateAccountAliasRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateAccountAliasWithContext is the same as CreateAccountAlias with the addition of +// the ability to pass a context and additional request options. +// +// See CreateAccountAlias 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 *IAM) CreateAccountAliasWithContext(ctx aws.Context, input *CreateAccountAliasInput, opts ...request.Option) (*CreateAccountAliasOutput, error) { + req, out := c.CreateAccountAliasRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateGroup = "CreateGroup" @@ -866,8 +1014,23 @@ func (c *IAM) CreateGroupRequest(input *CreateGroupInput) (req *request.Request, // Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/CreateGroup func (c *IAM) CreateGroup(input *CreateGroupInput) (*CreateGroupOutput, error) { req, out := c.CreateGroupRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateGroupWithContext is the same as CreateGroup with the addition of +// the ability to pass a context and additional request options. +// +// See CreateGroup 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 *IAM) CreateGroupWithContext(ctx aws.Context, input *CreateGroupInput, opts ...request.Option) (*CreateGroupOutput, error) { + req, out := c.CreateGroupRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateInstanceProfile = "CreateInstanceProfile" @@ -945,8 +1108,23 @@ func (c *IAM) CreateInstanceProfileRequest(input *CreateInstanceProfileInput) (r // Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/CreateInstanceProfile func (c *IAM) CreateInstanceProfile(input *CreateInstanceProfileInput) (*CreateInstanceProfileOutput, error) { req, out := c.CreateInstanceProfileRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateInstanceProfileWithContext is the same as CreateInstanceProfile with the addition of +// the ability to pass a context and additional request options. +// +// See CreateInstanceProfile 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 *IAM) CreateInstanceProfileWithContext(ctx aws.Context, input *CreateInstanceProfileInput, opts ...request.Option) (*CreateInstanceProfileOutput, error) { + req, out := c.CreateInstanceProfileRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateLoginProfile = "CreateLoginProfile" @@ -1030,8 +1208,23 @@ func (c *IAM) CreateLoginProfileRequest(input *CreateLoginProfileInput) (req *re // Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/CreateLoginProfile func (c *IAM) CreateLoginProfile(input *CreateLoginProfileInput) (*CreateLoginProfileOutput, error) { req, out := c.CreateLoginProfileRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateLoginProfileWithContext is the same as CreateLoginProfile with the addition of +// the ability to pass a context and additional request options. +// +// See CreateLoginProfile 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 *IAM) CreateLoginProfileWithContext(ctx aws.Context, input *CreateLoginProfileInput, opts ...request.Option) (*CreateLoginProfileOutput, error) { + req, out := c.CreateLoginProfileRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateOpenIDConnectProvider = "CreateOpenIDConnectProvider" @@ -1124,8 +1317,23 @@ func (c *IAM) CreateOpenIDConnectProviderRequest(input *CreateOpenIDConnectProvi // Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/CreateOpenIDConnectProvider func (c *IAM) CreateOpenIDConnectProvider(input *CreateOpenIDConnectProviderInput) (*CreateOpenIDConnectProviderOutput, error) { req, out := c.CreateOpenIDConnectProviderRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateOpenIDConnectProviderWithContext is the same as CreateOpenIDConnectProvider with the addition of +// the ability to pass a context and additional request options. +// +// See CreateOpenIDConnectProvider 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 *IAM) CreateOpenIDConnectProviderWithContext(ctx aws.Context, input *CreateOpenIDConnectProviderInput, opts ...request.Option) (*CreateOpenIDConnectProviderOutput, error) { + req, out := c.CreateOpenIDConnectProviderRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreatePolicy = "CreatePolicy" @@ -1215,8 +1423,23 @@ func (c *IAM) CreatePolicyRequest(input *CreatePolicyInput) (req *request.Reques // Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/CreatePolicy func (c *IAM) CreatePolicy(input *CreatePolicyInput) (*CreatePolicyOutput, error) { req, out := c.CreatePolicyRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreatePolicyWithContext is the same as CreatePolicy with the addition of +// the ability to pass a context and additional request options. +// +// See CreatePolicy 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 *IAM) CreatePolicyWithContext(ctx aws.Context, input *CreatePolicyInput, opts ...request.Option) (*CreatePolicyOutput, error) { + req, out := c.CreatePolicyRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreatePolicyVersion = "CreatePolicyVersion" @@ -1308,8 +1531,23 @@ func (c *IAM) CreatePolicyVersionRequest(input *CreatePolicyVersionInput) (req * // Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/CreatePolicyVersion func (c *IAM) CreatePolicyVersion(input *CreatePolicyVersionInput) (*CreatePolicyVersionOutput, error) { req, out := c.CreatePolicyVersionRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreatePolicyVersionWithContext is the same as CreatePolicyVersion with the addition of +// the ability to pass a context and additional request options. +// +// See CreatePolicyVersion 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 *IAM) CreatePolicyVersionWithContext(ctx aws.Context, input *CreatePolicyVersionInput, opts ...request.Option) (*CreatePolicyVersionOutput, error) { + req, out := c.CreatePolicyVersionRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateRole = "CreateRole" @@ -1375,6 +1613,10 @@ func (c *IAM) CreateRoleRequest(input *CreateRoleInput) (req *request.Request, o // The request was rejected because it attempted to create resources beyond // the current AWS account limits. The error message describes the limit exceeded. // +// * ErrCodeInvalidInputException "InvalidInput" +// The request was rejected because an invalid or out-of-range value was supplied +// for an input parameter. +// // * ErrCodeEntityAlreadyExistsException "EntityAlreadyExists" // The request was rejected because it attempted to create a resource that already // exists. @@ -1390,8 +1632,23 @@ func (c *IAM) CreateRoleRequest(input *CreateRoleInput) (req *request.Request, o // Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/CreateRole func (c *IAM) CreateRole(input *CreateRoleInput) (*CreateRoleOutput, error) { req, out := c.CreateRoleRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateRoleWithContext is the same as CreateRole with the addition of +// the ability to pass a context and additional request options. +// +// See CreateRole 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 *IAM) CreateRoleWithContext(ctx aws.Context, input *CreateRoleInput, opts ...request.Option) (*CreateRoleOutput, error) { + req, out := c.CreateRoleRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateSAMLProvider = "CreateSAMLProvider" @@ -1489,8 +1746,129 @@ func (c *IAM) CreateSAMLProviderRequest(input *CreateSAMLProviderInput) (req *re // Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/CreateSAMLProvider func (c *IAM) CreateSAMLProvider(input *CreateSAMLProviderInput) (*CreateSAMLProviderOutput, error) { req, out := c.CreateSAMLProviderRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateSAMLProviderWithContext is the same as CreateSAMLProvider with the addition of +// the ability to pass a context and additional request options. +// +// See CreateSAMLProvider 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 *IAM) CreateSAMLProviderWithContext(ctx aws.Context, input *CreateSAMLProviderInput, opts ...request.Option) (*CreateSAMLProviderOutput, error) { + req, out := c.CreateSAMLProviderRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opCreateServiceLinkedRole = "CreateServiceLinkedRole" + +// CreateServiceLinkedRoleRequest generates a "aws/request.Request" representing the +// client's request for the CreateServiceLinkedRole operation. The "output" return +// value can be used to capture response data after the request's "Send" method +// is called. +// +// See CreateServiceLinkedRole for usage and error information. +// +// Creating a request object using this method should be used when you want to inject +// custom logic into the request's lifecycle using a custom handler, or if you want to +// access properties on the request object before or after sending the request. If +// you just want the service response, call the CreateServiceLinkedRole method directly +// instead. +// +// Note: You must call the "Send" method on the returned request object in order +// to execute the request. +// +// // Example sending a request using the CreateServiceLinkedRoleRequest method. +// req, resp := client.CreateServiceLinkedRoleRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/CreateServiceLinkedRole +func (c *IAM) CreateServiceLinkedRoleRequest(input *CreateServiceLinkedRoleInput) (req *request.Request, output *CreateServiceLinkedRoleOutput) { + op := &request.Operation{ + Name: opCreateServiceLinkedRole, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &CreateServiceLinkedRoleInput{} + } + + output = &CreateServiceLinkedRoleOutput{} + req = c.newRequest(op, input, output) + return +} + +// CreateServiceLinkedRole API operation for AWS Identity and Access Management. +// +// Creates an IAM role that is linked to a specific AWS service. The service +// controls the attached policies and when the role can be deleted. This helps +// ensure that the service is not broken by an unexpectedly changed or deleted +// role, which could put your AWS resources into an unknown state. Allowing +// the service to control the role helps improve service stability and proper +// cleanup when a service and its role are no longer needed. +// +// The name of the role is autogenerated by combining the string that you specify +// for the AWSServiceName parameter with the string that you specify for the +// CustomSuffix parameter. The resulting name must be unique in your account +// or the request fails. +// +// To attach a policy to this service-linked role, you must make the request +// using the AWS service that depends on this role. +// +// 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 Identity and Access Management's +// API operation CreateServiceLinkedRole for usage and error information. +// +// Returned Error Codes: +// * ErrCodeInvalidInputException "InvalidInput" +// The request was rejected because an invalid or out-of-range value was supplied +// for an input parameter. +// +// * 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. +// +// * ErrCodeNoSuchEntityException "NoSuchEntity" +// The request was rejected because it referenced an entity that does not exist. +// The error message describes the entity. +// +// * ErrCodeServiceFailureException "ServiceFailure" +// The request processing has failed because of an unknown error, exception +// or failure. +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/CreateServiceLinkedRole +func (c *IAM) CreateServiceLinkedRole(input *CreateServiceLinkedRoleInput) (*CreateServiceLinkedRoleOutput, error) { + req, out := c.CreateServiceLinkedRoleRequest(input) + return out, req.Send() +} + +// CreateServiceLinkedRoleWithContext is the same as CreateServiceLinkedRole with the addition of +// the ability to pass a context and additional request options. +// +// See CreateServiceLinkedRole 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 *IAM) CreateServiceLinkedRoleWithContext(ctx aws.Context, input *CreateServiceLinkedRoleInput, opts ...request.Option) (*CreateServiceLinkedRoleOutput, error) { + req, out := c.CreateServiceLinkedRoleRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateServiceSpecificCredential = "CreateServiceSpecificCredential" @@ -1575,8 +1953,23 @@ func (c *IAM) CreateServiceSpecificCredentialRequest(input *CreateServiceSpecifi // Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/CreateServiceSpecificCredential func (c *IAM) CreateServiceSpecificCredential(input *CreateServiceSpecificCredentialInput) (*CreateServiceSpecificCredentialOutput, error) { req, out := c.CreateServiceSpecificCredentialRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateServiceSpecificCredentialWithContext is the same as CreateServiceSpecificCredential with the addition of +// the ability to pass a context and additional request options. +// +// See CreateServiceSpecificCredential 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 *IAM) CreateServiceSpecificCredentialWithContext(ctx aws.Context, input *CreateServiceSpecificCredentialInput, opts ...request.Option) (*CreateServiceSpecificCredentialOutput, error) { + req, out := c.CreateServiceSpecificCredentialRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateUser = "CreateUser" @@ -1657,8 +2050,23 @@ func (c *IAM) CreateUserRequest(input *CreateUserInput) (req *request.Request, o // Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/CreateUser func (c *IAM) CreateUser(input *CreateUserInput) (*CreateUserOutput, error) { req, out := c.CreateUserRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateUserWithContext is the same as CreateUser with the addition of +// the ability to pass a context and additional request options. +// +// See CreateUser 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 *IAM) CreateUserWithContext(ctx aws.Context, input *CreateUserInput, opts ...request.Option) (*CreateUserOutput, error) { + req, out := c.CreateUserRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateVirtualMFADevice = "CreateVirtualMFADevice" @@ -1744,8 +2152,23 @@ func (c *IAM) CreateVirtualMFADeviceRequest(input *CreateVirtualMFADeviceInput) // Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/CreateVirtualMFADevice func (c *IAM) CreateVirtualMFADevice(input *CreateVirtualMFADeviceInput) (*CreateVirtualMFADeviceOutput, error) { req, out := c.CreateVirtualMFADeviceRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateVirtualMFADeviceWithContext is the same as CreateVirtualMFADevice with the addition of +// the ability to pass a context and additional request options. +// +// See CreateVirtualMFADevice 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 *IAM) CreateVirtualMFADeviceWithContext(ctx aws.Context, input *CreateVirtualMFADeviceInput, opts ...request.Option) (*CreateVirtualMFADeviceOutput, error) { + req, out := c.CreateVirtualMFADeviceRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeactivateMFADevice = "DeactivateMFADevice" @@ -1831,8 +2254,23 @@ func (c *IAM) DeactivateMFADeviceRequest(input *DeactivateMFADeviceInput) (req * // Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DeactivateMFADevice func (c *IAM) DeactivateMFADevice(input *DeactivateMFADeviceInput) (*DeactivateMFADeviceOutput, error) { req, out := c.DeactivateMFADeviceRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeactivateMFADeviceWithContext is the same as DeactivateMFADevice with the addition of +// the ability to pass a context and additional request options. +// +// See DeactivateMFADevice 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 *IAM) DeactivateMFADeviceWithContext(ctx aws.Context, input *DeactivateMFADeviceInput, opts ...request.Option) (*DeactivateMFADeviceOutput, error) { + req, out := c.DeactivateMFADeviceRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteAccessKey = "DeleteAccessKey" @@ -1912,8 +2350,23 @@ func (c *IAM) DeleteAccessKeyRequest(input *DeleteAccessKeyInput) (req *request. // Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DeleteAccessKey func (c *IAM) DeleteAccessKey(input *DeleteAccessKeyInput) (*DeleteAccessKeyOutput, error) { req, out := c.DeleteAccessKeyRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteAccessKeyWithContext is the same as DeleteAccessKey with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteAccessKey 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 *IAM) DeleteAccessKeyWithContext(ctx aws.Context, input *DeleteAccessKeyInput, opts ...request.Option) (*DeleteAccessKeyOutput, error) { + req, out := c.DeleteAccessKeyRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteAccountAlias = "DeleteAccountAlias" @@ -1990,8 +2443,23 @@ func (c *IAM) DeleteAccountAliasRequest(input *DeleteAccountAliasInput) (req *re // Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DeleteAccountAlias func (c *IAM) DeleteAccountAlias(input *DeleteAccountAliasInput) (*DeleteAccountAliasOutput, error) { req, out := c.DeleteAccountAliasRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteAccountAliasWithContext is the same as DeleteAccountAlias with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteAccountAlias 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 *IAM) DeleteAccountAliasWithContext(ctx aws.Context, input *DeleteAccountAliasInput, opts ...request.Option) (*DeleteAccountAliasOutput, error) { + req, out := c.DeleteAccountAliasRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteAccountPasswordPolicy = "DeleteAccountPasswordPolicy" @@ -2066,8 +2534,23 @@ func (c *IAM) DeleteAccountPasswordPolicyRequest(input *DeleteAccountPasswordPol // Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DeleteAccountPasswordPolicy func (c *IAM) DeleteAccountPasswordPolicy(input *DeleteAccountPasswordPolicyInput) (*DeleteAccountPasswordPolicyOutput, error) { req, out := c.DeleteAccountPasswordPolicyRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteAccountPasswordPolicyWithContext is the same as DeleteAccountPasswordPolicy with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteAccountPasswordPolicy 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 *IAM) DeleteAccountPasswordPolicyWithContext(ctx aws.Context, input *DeleteAccountPasswordPolicyInput, opts ...request.Option) (*DeleteAccountPasswordPolicyOutput, error) { + req, out := c.DeleteAccountPasswordPolicyRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteGroup = "DeleteGroup" @@ -2147,8 +2630,23 @@ func (c *IAM) DeleteGroupRequest(input *DeleteGroupInput) (req *request.Request, // Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DeleteGroup func (c *IAM) DeleteGroup(input *DeleteGroupInput) (*DeleteGroupOutput, error) { req, out := c.DeleteGroupRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteGroupWithContext is the same as DeleteGroup with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteGroup 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 *IAM) DeleteGroupWithContext(ctx aws.Context, input *DeleteGroupInput, opts ...request.Option) (*DeleteGroupOutput, error) { + req, out := c.DeleteGroupRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteGroupPolicy = "DeleteGroupPolicy" @@ -2229,8 +2727,23 @@ func (c *IAM) DeleteGroupPolicyRequest(input *DeleteGroupPolicyInput) (req *requ // Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DeleteGroupPolicy func (c *IAM) DeleteGroupPolicy(input *DeleteGroupPolicyInput) (*DeleteGroupPolicyOutput, error) { req, out := c.DeleteGroupPolicyRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteGroupPolicyWithContext is the same as DeleteGroupPolicy with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteGroupPolicy 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 *IAM) DeleteGroupPolicyWithContext(ctx aws.Context, input *DeleteGroupPolicyInput, opts ...request.Option) (*DeleteGroupPolicyOutput, error) { + req, out := c.DeleteGroupPolicyRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteInstanceProfile = "DeleteInstanceProfile" @@ -2318,8 +2831,23 @@ func (c *IAM) DeleteInstanceProfileRequest(input *DeleteInstanceProfileInput) (r // Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DeleteInstanceProfile func (c *IAM) DeleteInstanceProfile(input *DeleteInstanceProfileInput) (*DeleteInstanceProfileOutput, error) { req, out := c.DeleteInstanceProfileRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteInstanceProfileWithContext is the same as DeleteInstanceProfile with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteInstanceProfile 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 *IAM) DeleteInstanceProfileWithContext(ctx aws.Context, input *DeleteInstanceProfileInput, opts ...request.Option) (*DeleteInstanceProfileOutput, error) { + req, out := c.DeleteInstanceProfileRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteLoginProfile = "DeleteLoginProfile" @@ -2406,8 +2934,23 @@ func (c *IAM) DeleteLoginProfileRequest(input *DeleteLoginProfileInput) (req *re // Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DeleteLoginProfile func (c *IAM) DeleteLoginProfile(input *DeleteLoginProfileInput) (*DeleteLoginProfileOutput, error) { req, out := c.DeleteLoginProfileRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteLoginProfileWithContext is the same as DeleteLoginProfile with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteLoginProfile 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 *IAM) DeleteLoginProfileWithContext(ctx aws.Context, input *DeleteLoginProfileInput, opts ...request.Option) (*DeleteLoginProfileOutput, error) { + req, out := c.DeleteLoginProfileRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteOpenIDConnectProvider = "DeleteOpenIDConnectProvider" @@ -2489,8 +3032,23 @@ func (c *IAM) DeleteOpenIDConnectProviderRequest(input *DeleteOpenIDConnectProvi // Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DeleteOpenIDConnectProvider func (c *IAM) DeleteOpenIDConnectProvider(input *DeleteOpenIDConnectProviderInput) (*DeleteOpenIDConnectProviderOutput, error) { req, out := c.DeleteOpenIDConnectProviderRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteOpenIDConnectProviderWithContext is the same as DeleteOpenIDConnectProvider with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteOpenIDConnectProvider 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 *IAM) DeleteOpenIDConnectProviderWithContext(ctx aws.Context, input *DeleteOpenIDConnectProviderInput, opts ...request.Option) (*DeleteOpenIDConnectProviderOutput, error) { + req, out := c.DeleteOpenIDConnectProviderRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeletePolicy = "DeletePolicy" @@ -2595,8 +3153,23 @@ func (c *IAM) DeletePolicyRequest(input *DeletePolicyInput) (req *request.Reques // Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DeletePolicy func (c *IAM) DeletePolicy(input *DeletePolicyInput) (*DeletePolicyOutput, error) { req, out := c.DeletePolicyRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeletePolicyWithContext is the same as DeletePolicy with the addition of +// the ability to pass a context and additional request options. +// +// See DeletePolicy 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 *IAM) DeletePolicyWithContext(ctx aws.Context, input *DeletePolicyInput, opts ...request.Option) (*DeletePolicyOutput, error) { + req, out := c.DeletePolicyRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeletePolicyVersion = "DeletePolicyVersion" @@ -2687,8 +3260,23 @@ func (c *IAM) DeletePolicyVersionRequest(input *DeletePolicyVersionInput) (req * // Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DeletePolicyVersion func (c *IAM) DeletePolicyVersion(input *DeletePolicyVersionInput) (*DeletePolicyVersionOutput, error) { req, out := c.DeletePolicyVersionRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeletePolicyVersionWithContext is the same as DeletePolicyVersion with the addition of +// the ability to pass a context and additional request options. +// +// See DeletePolicyVersion 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 *IAM) DeletePolicyVersionWithContext(ctx aws.Context, input *DeletePolicyVersionInput, opts ...request.Option) (*DeletePolicyVersionOutput, error) { + req, out := c.DeletePolicyVersionRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteRole = "DeleteRole" @@ -2765,6 +3353,12 @@ func (c *IAM) DeleteRoleRequest(input *DeleteRoleInput) (req *request.Request, o // The request was rejected because it attempted to create resources beyond // the current AWS account limits. The error message describes the limit exceeded. // +// * ErrCodeUnmodifiableEntityException "UnmodifiableEntity" +// The request was rejected because only the service that depends on the service-linked +// role can modify or delete the role on your behalf. The error message includes +// the name of the service that depends on this service-linked role. You must +// request the change through that service. +// // * ErrCodeServiceFailureException "ServiceFailure" // The request processing has failed because of an unknown error, exception // or failure. @@ -2772,8 +3366,23 @@ func (c *IAM) DeleteRoleRequest(input *DeleteRoleInput) (req *request.Request, o // Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DeleteRole func (c *IAM) DeleteRole(input *DeleteRoleInput) (*DeleteRoleOutput, error) { req, out := c.DeleteRoleRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteRoleWithContext is the same as DeleteRole with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteRole 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 *IAM) DeleteRoleWithContext(ctx aws.Context, input *DeleteRoleInput, opts ...request.Option) (*DeleteRoleOutput, error) { + req, out := c.DeleteRoleRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteRolePolicy = "DeleteRolePolicy" @@ -2847,6 +3456,12 @@ func (c *IAM) DeleteRolePolicyRequest(input *DeleteRolePolicyInput) (req *reques // The request was rejected because it attempted to create resources beyond // the current AWS account limits. The error message describes the limit exceeded. // +// * ErrCodeUnmodifiableEntityException "UnmodifiableEntity" +// The request was rejected because only the service that depends on the service-linked +// role can modify or delete the role on your behalf. The error message includes +// the name of the service that depends on this service-linked role. You must +// request the change through that service. +// // * ErrCodeServiceFailureException "ServiceFailure" // The request processing has failed because of an unknown error, exception // or failure. @@ -2854,8 +3469,23 @@ func (c *IAM) DeleteRolePolicyRequest(input *DeleteRolePolicyInput) (req *reques // Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DeleteRolePolicy func (c *IAM) DeleteRolePolicy(input *DeleteRolePolicyInput) (*DeleteRolePolicyOutput, error) { req, out := c.DeleteRolePolicyRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteRolePolicyWithContext is the same as DeleteRolePolicy with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteRolePolicy 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 *IAM) DeleteRolePolicyWithContext(ctx aws.Context, input *DeleteRolePolicyInput, opts ...request.Option) (*DeleteRolePolicyOutput, error) { + req, out := c.DeleteRolePolicyRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteSAMLProvider = "DeleteSAMLProvider" @@ -2941,8 +3571,23 @@ func (c *IAM) DeleteSAMLProviderRequest(input *DeleteSAMLProviderInput) (req *re // Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DeleteSAMLProvider func (c *IAM) DeleteSAMLProvider(input *DeleteSAMLProviderInput) (*DeleteSAMLProviderOutput, error) { req, out := c.DeleteSAMLProviderRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteSAMLProviderWithContext is the same as DeleteSAMLProvider with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteSAMLProvider 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 *IAM) DeleteSAMLProviderWithContext(ctx aws.Context, input *DeleteSAMLProviderInput, opts ...request.Option) (*DeleteSAMLProviderOutput, error) { + req, out := c.DeleteSAMLProviderRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteSSHPublicKey = "DeleteSSHPublicKey" @@ -3015,8 +3660,23 @@ func (c *IAM) DeleteSSHPublicKeyRequest(input *DeleteSSHPublicKeyInput) (req *re // Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DeleteSSHPublicKey func (c *IAM) DeleteSSHPublicKey(input *DeleteSSHPublicKeyInput) (*DeleteSSHPublicKeyOutput, error) { req, out := c.DeleteSSHPublicKeyRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteSSHPublicKeyWithContext is the same as DeleteSSHPublicKey with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteSSHPublicKey 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 *IAM) DeleteSSHPublicKeyWithContext(ctx aws.Context, input *DeleteSSHPublicKeyInput, opts ...request.Option) (*DeleteSSHPublicKeyOutput, error) { + req, out := c.DeleteSSHPublicKeyRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteServerCertificate = "DeleteServerCertificate" @@ -3110,8 +3770,23 @@ func (c *IAM) DeleteServerCertificateRequest(input *DeleteServerCertificateInput // Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DeleteServerCertificate func (c *IAM) DeleteServerCertificate(input *DeleteServerCertificateInput) (*DeleteServerCertificateOutput, error) { req, out := c.DeleteServerCertificateRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteServerCertificateWithContext is the same as DeleteServerCertificate with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteServerCertificate 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 *IAM) DeleteServerCertificateWithContext(ctx aws.Context, input *DeleteServerCertificateInput, opts ...request.Option) (*DeleteServerCertificateOutput, error) { + req, out := c.DeleteServerCertificateRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteServiceSpecificCredential = "DeleteServiceSpecificCredential" @@ -3178,8 +3853,23 @@ func (c *IAM) DeleteServiceSpecificCredentialRequest(input *DeleteServiceSpecifi // Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DeleteServiceSpecificCredential func (c *IAM) DeleteServiceSpecificCredential(input *DeleteServiceSpecificCredentialInput) (*DeleteServiceSpecificCredentialOutput, error) { req, out := c.DeleteServiceSpecificCredentialRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteServiceSpecificCredentialWithContext is the same as DeleteServiceSpecificCredential with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteServiceSpecificCredential 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 *IAM) DeleteServiceSpecificCredentialWithContext(ctx aws.Context, input *DeleteServiceSpecificCredentialInput, opts ...request.Option) (*DeleteServiceSpecificCredentialOutput, error) { + req, out := c.DeleteServiceSpecificCredentialRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteSigningCertificate = "DeleteSigningCertificate" @@ -3259,8 +3949,23 @@ func (c *IAM) DeleteSigningCertificateRequest(input *DeleteSigningCertificateInp // Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DeleteSigningCertificate func (c *IAM) DeleteSigningCertificate(input *DeleteSigningCertificateInput) (*DeleteSigningCertificateOutput, error) { req, out := c.DeleteSigningCertificateRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteSigningCertificateWithContext is the same as DeleteSigningCertificate with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteSigningCertificate 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 *IAM) DeleteSigningCertificateWithContext(ctx aws.Context, input *DeleteSigningCertificateInput, opts ...request.Option) (*DeleteSigningCertificateOutput, error) { + req, out := c.DeleteSigningCertificateRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteUser = "DeleteUser" @@ -3340,8 +4045,23 @@ func (c *IAM) DeleteUserRequest(input *DeleteUserInput) (req *request.Request, o // Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DeleteUser func (c *IAM) DeleteUser(input *DeleteUserInput) (*DeleteUserOutput, error) { req, out := c.DeleteUserRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteUserWithContext is the same as DeleteUser with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteUser 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 *IAM) DeleteUserWithContext(ctx aws.Context, input *DeleteUserInput, opts ...request.Option) (*DeleteUserOutput, error) { + req, out := c.DeleteUserRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteUserPolicy = "DeleteUserPolicy" @@ -3422,8 +4142,23 @@ func (c *IAM) DeleteUserPolicyRequest(input *DeleteUserPolicyInput) (req *reques // Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DeleteUserPolicy func (c *IAM) DeleteUserPolicy(input *DeleteUserPolicyInput) (*DeleteUserPolicyOutput, error) { req, out := c.DeleteUserPolicyRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteUserPolicyWithContext is the same as DeleteUserPolicy with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteUserPolicy 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 *IAM) DeleteUserPolicyWithContext(ctx aws.Context, input *DeleteUserPolicyInput, opts ...request.Option) (*DeleteUserPolicyOutput, error) { + req, out := c.DeleteUserPolicyRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteVirtualMFADevice = "DeleteVirtualMFADevice" @@ -3505,8 +4240,23 @@ func (c *IAM) DeleteVirtualMFADeviceRequest(input *DeleteVirtualMFADeviceInput) // Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DeleteVirtualMFADevice func (c *IAM) DeleteVirtualMFADevice(input *DeleteVirtualMFADeviceInput) (*DeleteVirtualMFADeviceOutput, error) { req, out := c.DeleteVirtualMFADeviceRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteVirtualMFADeviceWithContext is the same as DeleteVirtualMFADevice with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteVirtualMFADevice 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 *IAM) DeleteVirtualMFADeviceWithContext(ctx aws.Context, input *DeleteVirtualMFADeviceInput, opts ...request.Option) (*DeleteVirtualMFADeviceOutput, error) { + req, out := c.DeleteVirtualMFADeviceRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDetachGroupPolicy = "DetachGroupPolicy" @@ -3590,8 +4340,23 @@ func (c *IAM) DetachGroupPolicyRequest(input *DetachGroupPolicyInput) (req *requ // Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DetachGroupPolicy func (c *IAM) DetachGroupPolicy(input *DetachGroupPolicyInput) (*DetachGroupPolicyOutput, error) { req, out := c.DetachGroupPolicyRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DetachGroupPolicyWithContext is the same as DetachGroupPolicy with the addition of +// the ability to pass a context and additional request options. +// +// See DetachGroupPolicy 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 *IAM) DetachGroupPolicyWithContext(ctx aws.Context, input *DetachGroupPolicyInput, opts ...request.Option) (*DetachGroupPolicyOutput, error) { + req, out := c.DetachGroupPolicyRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDetachRolePolicy = "DetachRolePolicy" @@ -3668,6 +4433,12 @@ func (c *IAM) DetachRolePolicyRequest(input *DetachRolePolicyInput) (req *reques // The request was rejected because an invalid or out-of-range value was supplied // for an input parameter. // +// * ErrCodeUnmodifiableEntityException "UnmodifiableEntity" +// The request was rejected because only the service that depends on the service-linked +// role can modify or delete the role on your behalf. The error message includes +// the name of the service that depends on this service-linked role. You must +// request the change through that service. +// // * ErrCodeServiceFailureException "ServiceFailure" // The request processing has failed because of an unknown error, exception // or failure. @@ -3675,8 +4446,23 @@ func (c *IAM) DetachRolePolicyRequest(input *DetachRolePolicyInput) (req *reques // Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DetachRolePolicy func (c *IAM) DetachRolePolicy(input *DetachRolePolicyInput) (*DetachRolePolicyOutput, error) { req, out := c.DetachRolePolicyRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DetachRolePolicyWithContext is the same as DetachRolePolicy with the addition of +// the ability to pass a context and additional request options. +// +// See DetachRolePolicy 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 *IAM) DetachRolePolicyWithContext(ctx aws.Context, input *DetachRolePolicyInput, opts ...request.Option) (*DetachRolePolicyOutput, error) { + req, out := c.DetachRolePolicyRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDetachUserPolicy = "DetachUserPolicy" @@ -3760,8 +4546,23 @@ func (c *IAM) DetachUserPolicyRequest(input *DetachUserPolicyInput) (req *reques // Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DetachUserPolicy func (c *IAM) DetachUserPolicy(input *DetachUserPolicyInput) (*DetachUserPolicyOutput, error) { req, out := c.DetachUserPolicyRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DetachUserPolicyWithContext is the same as DetachUserPolicy with the addition of +// the ability to pass a context and additional request options. +// +// See DetachUserPolicy 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 *IAM) DetachUserPolicyWithContext(ctx aws.Context, input *DetachUserPolicyInput, opts ...request.Option) (*DetachUserPolicyOutput, error) { + req, out := c.DetachUserPolicyRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opEnableMFADevice = "EnableMFADevice" @@ -3852,8 +4653,23 @@ func (c *IAM) EnableMFADeviceRequest(input *EnableMFADeviceInput) (req *request. // Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/EnableMFADevice func (c *IAM) EnableMFADevice(input *EnableMFADeviceInput) (*EnableMFADeviceOutput, error) { req, out := c.EnableMFADeviceRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// EnableMFADeviceWithContext is the same as EnableMFADevice with the addition of +// the ability to pass a context and additional request options. +// +// See EnableMFADevice 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 *IAM) EnableMFADeviceWithContext(ctx aws.Context, input *EnableMFADeviceInput, opts ...request.Option) (*EnableMFADeviceOutput, error) { + req, out := c.EnableMFADeviceRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGenerateCredentialReport = "GenerateCredentialReport" @@ -3924,8 +4740,23 @@ func (c *IAM) GenerateCredentialReportRequest(input *GenerateCredentialReportInp // Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GenerateCredentialReport func (c *IAM) GenerateCredentialReport(input *GenerateCredentialReportInput) (*GenerateCredentialReportOutput, error) { req, out := c.GenerateCredentialReportRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GenerateCredentialReportWithContext is the same as GenerateCredentialReport with the addition of +// the ability to pass a context and additional request options. +// +// See GenerateCredentialReport 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 *IAM) GenerateCredentialReportWithContext(ctx aws.Context, input *GenerateCredentialReportInput, opts ...request.Option) (*GenerateCredentialReportOutput, error) { + req, out := c.GenerateCredentialReportRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetAccessKeyLastUsed = "GetAccessKeyLastUsed" @@ -3993,8 +4824,23 @@ func (c *IAM) GetAccessKeyLastUsedRequest(input *GetAccessKeyLastUsedInput) (req // Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GetAccessKeyLastUsed func (c *IAM) GetAccessKeyLastUsed(input *GetAccessKeyLastUsedInput) (*GetAccessKeyLastUsedOutput, error) { req, out := c.GetAccessKeyLastUsedRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetAccessKeyLastUsedWithContext is the same as GetAccessKeyLastUsed with the addition of +// the ability to pass a context and additional request options. +// +// See GetAccessKeyLastUsed 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 *IAM) GetAccessKeyLastUsedWithContext(ctx aws.Context, input *GetAccessKeyLastUsedInput, opts ...request.Option) (*GetAccessKeyLastUsedOutput, error) { + req, out := c.GetAccessKeyLastUsedRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetAccountAuthorizationDetails = "GetAccountAuthorizationDetails" @@ -4071,8 +4917,23 @@ func (c *IAM) GetAccountAuthorizationDetailsRequest(input *GetAccountAuthorizati // Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GetAccountAuthorizationDetails func (c *IAM) GetAccountAuthorizationDetails(input *GetAccountAuthorizationDetailsInput) (*GetAccountAuthorizationDetailsOutput, error) { req, out := c.GetAccountAuthorizationDetailsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetAccountAuthorizationDetailsWithContext is the same as GetAccountAuthorizationDetails with the addition of +// the ability to pass a context and additional request options. +// +// See GetAccountAuthorizationDetails 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 *IAM) GetAccountAuthorizationDetailsWithContext(ctx aws.Context, input *GetAccountAuthorizationDetailsInput, opts ...request.Option) (*GetAccountAuthorizationDetailsOutput, error) { + req, out := c.GetAccountAuthorizationDetailsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // GetAccountAuthorizationDetailsPages iterates over the pages of a GetAccountAuthorizationDetails operation, @@ -4092,12 +4953,37 @@ func (c *IAM) GetAccountAuthorizationDetails(input *GetAccountAuthorizationDetai // return pageNum <= 3 // }) // -func (c *IAM) GetAccountAuthorizationDetailsPages(input *GetAccountAuthorizationDetailsInput, fn func(p *GetAccountAuthorizationDetailsOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.GetAccountAuthorizationDetailsRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*GetAccountAuthorizationDetailsOutput), lastPage) - }) +func (c *IAM) GetAccountAuthorizationDetailsPages(input *GetAccountAuthorizationDetailsInput, fn func(*GetAccountAuthorizationDetailsOutput, bool) bool) error { + return c.GetAccountAuthorizationDetailsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// GetAccountAuthorizationDetailsPagesWithContext same as GetAccountAuthorizationDetailsPages 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 *IAM) GetAccountAuthorizationDetailsPagesWithContext(ctx aws.Context, input *GetAccountAuthorizationDetailsInput, fn func(*GetAccountAuthorizationDetailsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *GetAccountAuthorizationDetailsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.GetAccountAuthorizationDetailsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*GetAccountAuthorizationDetailsOutput), !p.HasNextPage()) + } + return p.Err() } const opGetAccountPasswordPolicy = "GetAccountPasswordPolicy" @@ -4167,8 +5053,23 @@ func (c *IAM) GetAccountPasswordPolicyRequest(input *GetAccountPasswordPolicyInp // Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GetAccountPasswordPolicy func (c *IAM) GetAccountPasswordPolicy(input *GetAccountPasswordPolicyInput) (*GetAccountPasswordPolicyOutput, error) { req, out := c.GetAccountPasswordPolicyRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetAccountPasswordPolicyWithContext is the same as GetAccountPasswordPolicy with the addition of +// the ability to pass a context and additional request options. +// +// See GetAccountPasswordPolicy 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 *IAM) GetAccountPasswordPolicyWithContext(ctx aws.Context, input *GetAccountPasswordPolicyInput, opts ...request.Option) (*GetAccountPasswordPolicyOutput, error) { + req, out := c.GetAccountPasswordPolicyRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetAccountSummary = "GetAccountSummary" @@ -4237,8 +5138,23 @@ func (c *IAM) GetAccountSummaryRequest(input *GetAccountSummaryInput) (req *requ // Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GetAccountSummary func (c *IAM) GetAccountSummary(input *GetAccountSummaryInput) (*GetAccountSummaryOutput, error) { req, out := c.GetAccountSummaryRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetAccountSummaryWithContext is the same as GetAccountSummary with the addition of +// the ability to pass a context and additional request options. +// +// See GetAccountSummary 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 *IAM) GetAccountSummaryWithContext(ctx aws.Context, input *GetAccountSummaryInput, opts ...request.Option) (*GetAccountSummaryOutput, error) { + req, out := c.GetAccountSummaryRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetContextKeysForCustomPolicy = "GetContextKeysForCustomPolicy" @@ -4312,8 +5228,23 @@ func (c *IAM) GetContextKeysForCustomPolicyRequest(input *GetContextKeysForCusto // Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GetContextKeysForCustomPolicy func (c *IAM) GetContextKeysForCustomPolicy(input *GetContextKeysForCustomPolicyInput) (*GetContextKeysForPolicyResponse, error) { req, out := c.GetContextKeysForCustomPolicyRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetContextKeysForCustomPolicyWithContext is the same as GetContextKeysForCustomPolicy with the addition of +// the ability to pass a context and additional request options. +// +// See GetContextKeysForCustomPolicy 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 *IAM) GetContextKeysForCustomPolicyWithContext(ctx aws.Context, input *GetContextKeysForCustomPolicyInput, opts ...request.Option) (*GetContextKeysForPolicyResponse, error) { + req, out := c.GetContextKeysForCustomPolicyRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetContextKeysForPrincipalPolicy = "GetContextKeysForPrincipalPolicy" @@ -4398,8 +5329,23 @@ func (c *IAM) GetContextKeysForPrincipalPolicyRequest(input *GetContextKeysForPr // Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GetContextKeysForPrincipalPolicy func (c *IAM) GetContextKeysForPrincipalPolicy(input *GetContextKeysForPrincipalPolicyInput) (*GetContextKeysForPolicyResponse, error) { req, out := c.GetContextKeysForPrincipalPolicyRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetContextKeysForPrincipalPolicyWithContext is the same as GetContextKeysForPrincipalPolicy with the addition of +// the ability to pass a context and additional request options. +// +// See GetContextKeysForPrincipalPolicy 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 *IAM) GetContextKeysForPrincipalPolicyWithContext(ctx aws.Context, input *GetContextKeysForPrincipalPolicyInput, opts ...request.Option) (*GetContextKeysForPolicyResponse, error) { + req, out := c.GetContextKeysForPrincipalPolicyRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetCredentialReport = "GetCredentialReport" @@ -4480,8 +5426,23 @@ func (c *IAM) GetCredentialReportRequest(input *GetCredentialReportInput) (req * // Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GetCredentialReport func (c *IAM) GetCredentialReport(input *GetCredentialReportInput) (*GetCredentialReportOutput, error) { req, out := c.GetCredentialReportRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetCredentialReportWithContext is the same as GetCredentialReport with the addition of +// the ability to pass a context and additional request options. +// +// See GetCredentialReport 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 *IAM) GetCredentialReportWithContext(ctx aws.Context, input *GetCredentialReportInput, opts ...request.Option) (*GetCredentialReportOutput, error) { + req, out := c.GetCredentialReportRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetGroup = "GetGroup" @@ -4557,8 +5518,23 @@ func (c *IAM) GetGroupRequest(input *GetGroupInput) (req *request.Request, outpu // Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GetGroup func (c *IAM) GetGroup(input *GetGroupInput) (*GetGroupOutput, error) { req, out := c.GetGroupRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetGroupWithContext is the same as GetGroup with the addition of +// the ability to pass a context and additional request options. +// +// See GetGroup 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 *IAM) GetGroupWithContext(ctx aws.Context, input *GetGroupInput, opts ...request.Option) (*GetGroupOutput, error) { + req, out := c.GetGroupRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // GetGroupPages iterates over the pages of a GetGroup operation, @@ -4578,12 +5554,37 @@ func (c *IAM) GetGroup(input *GetGroupInput) (*GetGroupOutput, error) { // return pageNum <= 3 // }) // -func (c *IAM) GetGroupPages(input *GetGroupInput, fn func(p *GetGroupOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.GetGroupRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*GetGroupOutput), lastPage) - }) +func (c *IAM) GetGroupPages(input *GetGroupInput, fn func(*GetGroupOutput, bool) bool) error { + return c.GetGroupPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// GetGroupPagesWithContext same as GetGroupPages 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 *IAM) GetGroupPagesWithContext(ctx aws.Context, input *GetGroupInput, fn func(*GetGroupOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *GetGroupInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.GetGroupRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*GetGroupOutput), !p.HasNextPage()) + } + return p.Err() } const opGetGroupPolicy = "GetGroupPolicy" @@ -4668,8 +5669,23 @@ func (c *IAM) GetGroupPolicyRequest(input *GetGroupPolicyInput) (req *request.Re // Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GetGroupPolicy func (c *IAM) GetGroupPolicy(input *GetGroupPolicyInput) (*GetGroupPolicyOutput, error) { req, out := c.GetGroupPolicyRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetGroupPolicyWithContext is the same as GetGroupPolicy with the addition of +// the ability to pass a context and additional request options. +// +// See GetGroupPolicy 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 *IAM) GetGroupPolicyWithContext(ctx aws.Context, input *GetGroupPolicyInput, opts ...request.Option) (*GetGroupPolicyOutput, error) { + req, out := c.GetGroupPolicyRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetInstanceProfile = "GetInstanceProfile" @@ -4741,8 +5757,23 @@ func (c *IAM) GetInstanceProfileRequest(input *GetInstanceProfileInput) (req *re // Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GetInstanceProfile func (c *IAM) GetInstanceProfile(input *GetInstanceProfileInput) (*GetInstanceProfileOutput, error) { req, out := c.GetInstanceProfileRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetInstanceProfileWithContext is the same as GetInstanceProfile with the addition of +// the ability to pass a context and additional request options. +// +// See GetInstanceProfile 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 *IAM) GetInstanceProfileWithContext(ctx aws.Context, input *GetInstanceProfileInput, opts ...request.Option) (*GetInstanceProfileOutput, error) { + req, out := c.GetInstanceProfileRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetLoginProfile = "GetLoginProfile" @@ -4813,8 +5844,23 @@ func (c *IAM) GetLoginProfileRequest(input *GetLoginProfileInput) (req *request. // Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GetLoginProfile func (c *IAM) GetLoginProfile(input *GetLoginProfileInput) (*GetLoginProfileOutput, error) { req, out := c.GetLoginProfileRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetLoginProfileWithContext is the same as GetLoginProfile with the addition of +// the ability to pass a context and additional request options. +// +// See GetLoginProfile 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 *IAM) GetLoginProfileWithContext(ctx aws.Context, input *GetLoginProfileInput, opts ...request.Option) (*GetLoginProfileOutput, error) { + req, out := c.GetLoginProfileRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetOpenIDConnectProvider = "GetOpenIDConnectProvider" @@ -4888,8 +5934,23 @@ func (c *IAM) GetOpenIDConnectProviderRequest(input *GetOpenIDConnectProviderInp // Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GetOpenIDConnectProvider func (c *IAM) GetOpenIDConnectProvider(input *GetOpenIDConnectProviderInput) (*GetOpenIDConnectProviderOutput, error) { req, out := c.GetOpenIDConnectProviderRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetOpenIDConnectProviderWithContext is the same as GetOpenIDConnectProvider with the addition of +// the ability to pass a context and additional request options. +// +// See GetOpenIDConnectProvider 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 *IAM) GetOpenIDConnectProviderWithContext(ctx aws.Context, input *GetOpenIDConnectProviderInput, opts ...request.Option) (*GetOpenIDConnectProviderOutput, error) { + req, out := c.GetOpenIDConnectProviderRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetPolicy = "GetPolicy" @@ -4975,8 +6036,23 @@ func (c *IAM) GetPolicyRequest(input *GetPolicyInput) (req *request.Request, out // Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GetPolicy func (c *IAM) GetPolicy(input *GetPolicyInput) (*GetPolicyOutput, error) { req, out := c.GetPolicyRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetPolicyWithContext is the same as GetPolicy with the addition of +// the ability to pass a context and additional request options. +// +// See GetPolicy 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 *IAM) GetPolicyWithContext(ctx aws.Context, input *GetPolicyInput, opts ...request.Option) (*GetPolicyOutput, error) { + req, out := c.GetPolicyRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetPolicyVersion = "GetPolicyVersion" @@ -5070,8 +6146,23 @@ func (c *IAM) GetPolicyVersionRequest(input *GetPolicyVersionInput) (req *reques // Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GetPolicyVersion func (c *IAM) GetPolicyVersion(input *GetPolicyVersionInput) (*GetPolicyVersionOutput, error) { req, out := c.GetPolicyVersionRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetPolicyVersionWithContext is the same as GetPolicyVersion with the addition of +// the ability to pass a context and additional request options. +// +// See GetPolicyVersion 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 *IAM) GetPolicyVersionWithContext(ctx aws.Context, input *GetPolicyVersionInput, opts ...request.Option) (*GetPolicyVersionOutput, error) { + req, out := c.GetPolicyVersionRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetRole = "GetRole" @@ -5148,8 +6239,23 @@ func (c *IAM) GetRoleRequest(input *GetRoleInput) (req *request.Request, output // Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GetRole func (c *IAM) GetRole(input *GetRoleInput) (*GetRoleOutput, error) { req, out := c.GetRoleRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetRoleWithContext is the same as GetRole with the addition of +// the ability to pass a context and additional request options. +// +// See GetRole 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 *IAM) GetRoleWithContext(ctx aws.Context, input *GetRoleInput, opts ...request.Option) (*GetRoleOutput, error) { + req, out := c.GetRoleRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetRolePolicy = "GetRolePolicy" @@ -5237,8 +6343,23 @@ func (c *IAM) GetRolePolicyRequest(input *GetRolePolicyInput) (req *request.Requ // Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GetRolePolicy func (c *IAM) GetRolePolicy(input *GetRolePolicyInput) (*GetRolePolicyOutput, error) { req, out := c.GetRolePolicyRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetRolePolicyWithContext is the same as GetRolePolicy with the addition of +// the ability to pass a context and additional request options. +// +// See GetRolePolicy 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 *IAM) GetRolePolicyWithContext(ctx aws.Context, input *GetRolePolicyInput, opts ...request.Option) (*GetRolePolicyOutput, error) { + req, out := c.GetRolePolicyRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetSAMLProvider = "GetSAMLProvider" @@ -5314,8 +6435,23 @@ func (c *IAM) GetSAMLProviderRequest(input *GetSAMLProviderInput) (req *request. // Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GetSAMLProvider func (c *IAM) GetSAMLProvider(input *GetSAMLProviderInput) (*GetSAMLProviderOutput, error) { req, out := c.GetSAMLProviderRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetSAMLProviderWithContext is the same as GetSAMLProvider with the addition of +// the ability to pass a context and additional request options. +// +// See GetSAMLProvider 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 *IAM) GetSAMLProviderWithContext(ctx aws.Context, input *GetSAMLProviderInput, opts ...request.Option) (*GetSAMLProviderOutput, error) { + req, out := c.GetSAMLProviderRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetSSHPublicKey = "GetSSHPublicKey" @@ -5390,8 +6526,23 @@ func (c *IAM) GetSSHPublicKeyRequest(input *GetSSHPublicKeyInput) (req *request. // Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GetSSHPublicKey func (c *IAM) GetSSHPublicKey(input *GetSSHPublicKeyInput) (*GetSSHPublicKeyOutput, error) { req, out := c.GetSSHPublicKeyRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetSSHPublicKeyWithContext is the same as GetSSHPublicKey with the addition of +// the ability to pass a context and additional request options. +// +// See GetSSHPublicKey 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 *IAM) GetSSHPublicKeyWithContext(ctx aws.Context, input *GetSSHPublicKeyInput, opts ...request.Option) (*GetSSHPublicKeyOutput, error) { + req, out := c.GetSSHPublicKeyRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetServerCertificate = "GetServerCertificate" @@ -5465,8 +6616,23 @@ func (c *IAM) GetServerCertificateRequest(input *GetServerCertificateInput) (req // Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GetServerCertificate func (c *IAM) GetServerCertificate(input *GetServerCertificateInput) (*GetServerCertificateOutput, error) { req, out := c.GetServerCertificateRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetServerCertificateWithContext is the same as GetServerCertificate with the addition of +// the ability to pass a context and additional request options. +// +// See GetServerCertificate 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 *IAM) GetServerCertificateWithContext(ctx aws.Context, input *GetServerCertificateInput, opts ...request.Option) (*GetServerCertificateOutput, error) { + req, out := c.GetServerCertificateRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetUser = "GetUser" @@ -5539,8 +6705,23 @@ func (c *IAM) GetUserRequest(input *GetUserInput) (req *request.Request, output // Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GetUser func (c *IAM) GetUser(input *GetUserInput) (*GetUserOutput, error) { req, out := c.GetUserRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetUserWithContext is the same as GetUser with the addition of +// the ability to pass a context and additional request options. +// +// See GetUser 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 *IAM) GetUserWithContext(ctx aws.Context, input *GetUserInput, opts ...request.Option) (*GetUserOutput, error) { + req, out := c.GetUserRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetUserPolicy = "GetUserPolicy" @@ -5625,8 +6806,23 @@ func (c *IAM) GetUserPolicyRequest(input *GetUserPolicyInput) (req *request.Requ // Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GetUserPolicy func (c *IAM) GetUserPolicy(input *GetUserPolicyInput) (*GetUserPolicyOutput, error) { req, out := c.GetUserPolicyRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetUserPolicyWithContext is the same as GetUserPolicy with the addition of +// the ability to pass a context and additional request options. +// +// See GetUserPolicy 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 *IAM) GetUserPolicyWithContext(ctx aws.Context, input *GetUserPolicyInput, opts ...request.Option) (*GetUserPolicyOutput, error) { + req, out := c.GetUserPolicyRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opListAccessKeys = "ListAccessKeys" @@ -5713,8 +6909,23 @@ func (c *IAM) ListAccessKeysRequest(input *ListAccessKeysInput) (req *request.Re // Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListAccessKeys func (c *IAM) ListAccessKeys(input *ListAccessKeysInput) (*ListAccessKeysOutput, error) { req, out := c.ListAccessKeysRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListAccessKeysWithContext is the same as ListAccessKeys with the addition of +// the ability to pass a context and additional request options. +// +// See ListAccessKeys 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 *IAM) ListAccessKeysWithContext(ctx aws.Context, input *ListAccessKeysInput, opts ...request.Option) (*ListAccessKeysOutput, error) { + req, out := c.ListAccessKeysRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // ListAccessKeysPages iterates over the pages of a ListAccessKeys operation, @@ -5734,12 +6945,37 @@ func (c *IAM) ListAccessKeys(input *ListAccessKeysInput) (*ListAccessKeysOutput, // return pageNum <= 3 // }) // -func (c *IAM) ListAccessKeysPages(input *ListAccessKeysInput, fn func(p *ListAccessKeysOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.ListAccessKeysRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*ListAccessKeysOutput), lastPage) - }) +func (c *IAM) ListAccessKeysPages(input *ListAccessKeysInput, fn func(*ListAccessKeysOutput, bool) bool) error { + return c.ListAccessKeysPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListAccessKeysPagesWithContext same as ListAccessKeysPages 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 *IAM) ListAccessKeysPagesWithContext(ctx aws.Context, input *ListAccessKeysInput, fn func(*ListAccessKeysOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListAccessKeysInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListAccessKeysRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*ListAccessKeysOutput), !p.HasNextPage()) + } + return p.Err() } const opListAccountAliases = "ListAccountAliases" @@ -5813,8 +7049,23 @@ func (c *IAM) ListAccountAliasesRequest(input *ListAccountAliasesInput) (req *re // Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListAccountAliases func (c *IAM) ListAccountAliases(input *ListAccountAliasesInput) (*ListAccountAliasesOutput, error) { req, out := c.ListAccountAliasesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListAccountAliasesWithContext is the same as ListAccountAliases with the addition of +// the ability to pass a context and additional request options. +// +// See ListAccountAliases 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 *IAM) ListAccountAliasesWithContext(ctx aws.Context, input *ListAccountAliasesInput, opts ...request.Option) (*ListAccountAliasesOutput, error) { + req, out := c.ListAccountAliasesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // ListAccountAliasesPages iterates over the pages of a ListAccountAliases operation, @@ -5834,12 +7085,37 @@ func (c *IAM) ListAccountAliases(input *ListAccountAliasesInput) (*ListAccountAl // return pageNum <= 3 // }) // -func (c *IAM) ListAccountAliasesPages(input *ListAccountAliasesInput, fn func(p *ListAccountAliasesOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.ListAccountAliasesRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*ListAccountAliasesOutput), lastPage) - }) +func (c *IAM) ListAccountAliasesPages(input *ListAccountAliasesInput, fn func(*ListAccountAliasesOutput, bool) bool) error { + return c.ListAccountAliasesPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListAccountAliasesPagesWithContext same as ListAccountAliasesPages 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 *IAM) ListAccountAliasesPagesWithContext(ctx aws.Context, input *ListAccountAliasesInput, fn func(*ListAccountAliasesOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListAccountAliasesInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListAccountAliasesRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*ListAccountAliasesOutput), !p.HasNextPage()) + } + return p.Err() } const opListAttachedGroupPolicies = "ListAttachedGroupPolicies" @@ -5929,8 +7205,23 @@ func (c *IAM) ListAttachedGroupPoliciesRequest(input *ListAttachedGroupPoliciesI // Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListAttachedGroupPolicies func (c *IAM) ListAttachedGroupPolicies(input *ListAttachedGroupPoliciesInput) (*ListAttachedGroupPoliciesOutput, error) { req, out := c.ListAttachedGroupPoliciesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListAttachedGroupPoliciesWithContext is the same as ListAttachedGroupPolicies with the addition of +// the ability to pass a context and additional request options. +// +// See ListAttachedGroupPolicies 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 *IAM) ListAttachedGroupPoliciesWithContext(ctx aws.Context, input *ListAttachedGroupPoliciesInput, opts ...request.Option) (*ListAttachedGroupPoliciesOutput, error) { + req, out := c.ListAttachedGroupPoliciesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // ListAttachedGroupPoliciesPages iterates over the pages of a ListAttachedGroupPolicies operation, @@ -5950,12 +7241,37 @@ func (c *IAM) ListAttachedGroupPolicies(input *ListAttachedGroupPoliciesInput) ( // return pageNum <= 3 // }) // -func (c *IAM) ListAttachedGroupPoliciesPages(input *ListAttachedGroupPoliciesInput, fn func(p *ListAttachedGroupPoliciesOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.ListAttachedGroupPoliciesRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*ListAttachedGroupPoliciesOutput), lastPage) - }) +func (c *IAM) ListAttachedGroupPoliciesPages(input *ListAttachedGroupPoliciesInput, fn func(*ListAttachedGroupPoliciesOutput, bool) bool) error { + return c.ListAttachedGroupPoliciesPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListAttachedGroupPoliciesPagesWithContext same as ListAttachedGroupPoliciesPages 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 *IAM) ListAttachedGroupPoliciesPagesWithContext(ctx aws.Context, input *ListAttachedGroupPoliciesInput, fn func(*ListAttachedGroupPoliciesOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListAttachedGroupPoliciesInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListAttachedGroupPoliciesRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*ListAttachedGroupPoliciesOutput), !p.HasNextPage()) + } + return p.Err() } const opListAttachedRolePolicies = "ListAttachedRolePolicies" @@ -6045,8 +7361,23 @@ func (c *IAM) ListAttachedRolePoliciesRequest(input *ListAttachedRolePoliciesInp // Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListAttachedRolePolicies func (c *IAM) ListAttachedRolePolicies(input *ListAttachedRolePoliciesInput) (*ListAttachedRolePoliciesOutput, error) { req, out := c.ListAttachedRolePoliciesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListAttachedRolePoliciesWithContext is the same as ListAttachedRolePolicies with the addition of +// the ability to pass a context and additional request options. +// +// See ListAttachedRolePolicies 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 *IAM) ListAttachedRolePoliciesWithContext(ctx aws.Context, input *ListAttachedRolePoliciesInput, opts ...request.Option) (*ListAttachedRolePoliciesOutput, error) { + req, out := c.ListAttachedRolePoliciesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // ListAttachedRolePoliciesPages iterates over the pages of a ListAttachedRolePolicies operation, @@ -6066,12 +7397,37 @@ func (c *IAM) ListAttachedRolePolicies(input *ListAttachedRolePoliciesInput) (*L // return pageNum <= 3 // }) // -func (c *IAM) ListAttachedRolePoliciesPages(input *ListAttachedRolePoliciesInput, fn func(p *ListAttachedRolePoliciesOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.ListAttachedRolePoliciesRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*ListAttachedRolePoliciesOutput), lastPage) - }) +func (c *IAM) ListAttachedRolePoliciesPages(input *ListAttachedRolePoliciesInput, fn func(*ListAttachedRolePoliciesOutput, bool) bool) error { + return c.ListAttachedRolePoliciesPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListAttachedRolePoliciesPagesWithContext same as ListAttachedRolePoliciesPages 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 *IAM) ListAttachedRolePoliciesPagesWithContext(ctx aws.Context, input *ListAttachedRolePoliciesInput, fn func(*ListAttachedRolePoliciesOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListAttachedRolePoliciesInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListAttachedRolePoliciesRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*ListAttachedRolePoliciesOutput), !p.HasNextPage()) + } + return p.Err() } const opListAttachedUserPolicies = "ListAttachedUserPolicies" @@ -6161,8 +7517,23 @@ func (c *IAM) ListAttachedUserPoliciesRequest(input *ListAttachedUserPoliciesInp // Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListAttachedUserPolicies func (c *IAM) ListAttachedUserPolicies(input *ListAttachedUserPoliciesInput) (*ListAttachedUserPoliciesOutput, error) { req, out := c.ListAttachedUserPoliciesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListAttachedUserPoliciesWithContext is the same as ListAttachedUserPolicies with the addition of +// the ability to pass a context and additional request options. +// +// See ListAttachedUserPolicies 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 *IAM) ListAttachedUserPoliciesWithContext(ctx aws.Context, input *ListAttachedUserPoliciesInput, opts ...request.Option) (*ListAttachedUserPoliciesOutput, error) { + req, out := c.ListAttachedUserPoliciesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // ListAttachedUserPoliciesPages iterates over the pages of a ListAttachedUserPolicies operation, @@ -6182,12 +7553,37 @@ func (c *IAM) ListAttachedUserPolicies(input *ListAttachedUserPoliciesInput) (*L // return pageNum <= 3 // }) // -func (c *IAM) ListAttachedUserPoliciesPages(input *ListAttachedUserPoliciesInput, fn func(p *ListAttachedUserPoliciesOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.ListAttachedUserPoliciesRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*ListAttachedUserPoliciesOutput), lastPage) - }) +func (c *IAM) ListAttachedUserPoliciesPages(input *ListAttachedUserPoliciesInput, fn func(*ListAttachedUserPoliciesOutput, bool) bool) error { + return c.ListAttachedUserPoliciesPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListAttachedUserPoliciesPagesWithContext same as ListAttachedUserPoliciesPages 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 *IAM) ListAttachedUserPoliciesPagesWithContext(ctx aws.Context, input *ListAttachedUserPoliciesInput, fn func(*ListAttachedUserPoliciesOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListAttachedUserPoliciesInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListAttachedUserPoliciesRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*ListAttachedUserPoliciesOutput), !p.HasNextPage()) + } + return p.Err() } const opListEntitiesForPolicy = "ListEntitiesForPolicy" @@ -6274,8 +7670,23 @@ func (c *IAM) ListEntitiesForPolicyRequest(input *ListEntitiesForPolicyInput) (r // Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListEntitiesForPolicy func (c *IAM) ListEntitiesForPolicy(input *ListEntitiesForPolicyInput) (*ListEntitiesForPolicyOutput, error) { req, out := c.ListEntitiesForPolicyRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListEntitiesForPolicyWithContext is the same as ListEntitiesForPolicy with the addition of +// the ability to pass a context and additional request options. +// +// See ListEntitiesForPolicy 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 *IAM) ListEntitiesForPolicyWithContext(ctx aws.Context, input *ListEntitiesForPolicyInput, opts ...request.Option) (*ListEntitiesForPolicyOutput, error) { + req, out := c.ListEntitiesForPolicyRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // ListEntitiesForPolicyPages iterates over the pages of a ListEntitiesForPolicy operation, @@ -6295,12 +7706,37 @@ func (c *IAM) ListEntitiesForPolicy(input *ListEntitiesForPolicyInput) (*ListEnt // return pageNum <= 3 // }) // -func (c *IAM) ListEntitiesForPolicyPages(input *ListEntitiesForPolicyInput, fn func(p *ListEntitiesForPolicyOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.ListEntitiesForPolicyRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*ListEntitiesForPolicyOutput), lastPage) - }) +func (c *IAM) ListEntitiesForPolicyPages(input *ListEntitiesForPolicyInput, fn func(*ListEntitiesForPolicyOutput, bool) bool) error { + return c.ListEntitiesForPolicyPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListEntitiesForPolicyPagesWithContext same as ListEntitiesForPolicyPages 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 *IAM) ListEntitiesForPolicyPagesWithContext(ctx aws.Context, input *ListEntitiesForPolicyInput, fn func(*ListEntitiesForPolicyOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListEntitiesForPolicyInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListEntitiesForPolicyRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*ListEntitiesForPolicyOutput), !p.HasNextPage()) + } + return p.Err() } const opListGroupPolicies = "ListGroupPolicies" @@ -6386,8 +7822,23 @@ func (c *IAM) ListGroupPoliciesRequest(input *ListGroupPoliciesInput) (req *requ // Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListGroupPolicies func (c *IAM) ListGroupPolicies(input *ListGroupPoliciesInput) (*ListGroupPoliciesOutput, error) { req, out := c.ListGroupPoliciesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListGroupPoliciesWithContext is the same as ListGroupPolicies with the addition of +// the ability to pass a context and additional request options. +// +// See ListGroupPolicies 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 *IAM) ListGroupPoliciesWithContext(ctx aws.Context, input *ListGroupPoliciesInput, opts ...request.Option) (*ListGroupPoliciesOutput, error) { + req, out := c.ListGroupPoliciesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // ListGroupPoliciesPages iterates over the pages of a ListGroupPolicies operation, @@ -6407,12 +7858,37 @@ func (c *IAM) ListGroupPolicies(input *ListGroupPoliciesInput) (*ListGroupPolici // return pageNum <= 3 // }) // -func (c *IAM) ListGroupPoliciesPages(input *ListGroupPoliciesInput, fn func(p *ListGroupPoliciesOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.ListGroupPoliciesRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*ListGroupPoliciesOutput), lastPage) - }) +func (c *IAM) ListGroupPoliciesPages(input *ListGroupPoliciesInput, fn func(*ListGroupPoliciesOutput, bool) bool) error { + return c.ListGroupPoliciesPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListGroupPoliciesPagesWithContext same as ListGroupPoliciesPages 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 *IAM) ListGroupPoliciesPagesWithContext(ctx aws.Context, input *ListGroupPoliciesInput, fn func(*ListGroupPoliciesOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListGroupPoliciesInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListGroupPoliciesRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*ListGroupPoliciesOutput), !p.HasNextPage()) + } + return p.Err() } const opListGroups = "ListGroups" @@ -6485,8 +7961,23 @@ func (c *IAM) ListGroupsRequest(input *ListGroupsInput) (req *request.Request, o // Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListGroups func (c *IAM) ListGroups(input *ListGroupsInput) (*ListGroupsOutput, error) { req, out := c.ListGroupsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListGroupsWithContext is the same as ListGroups with the addition of +// the ability to pass a context and additional request options. +// +// See ListGroups 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 *IAM) ListGroupsWithContext(ctx aws.Context, input *ListGroupsInput, opts ...request.Option) (*ListGroupsOutput, error) { + req, out := c.ListGroupsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // ListGroupsPages iterates over the pages of a ListGroups operation, @@ -6506,12 +7997,37 @@ func (c *IAM) ListGroups(input *ListGroupsInput) (*ListGroupsOutput, error) { // return pageNum <= 3 // }) // -func (c *IAM) ListGroupsPages(input *ListGroupsInput, fn func(p *ListGroupsOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.ListGroupsRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*ListGroupsOutput), lastPage) - }) +func (c *IAM) ListGroupsPages(input *ListGroupsInput, fn func(*ListGroupsOutput, bool) bool) error { + return c.ListGroupsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListGroupsPagesWithContext same as ListGroupsPages 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 *IAM) ListGroupsPagesWithContext(ctx aws.Context, input *ListGroupsInput, fn func(*ListGroupsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListGroupsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListGroupsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*ListGroupsOutput), !p.HasNextPage()) + } + return p.Err() } const opListGroupsForUser = "ListGroupsForUser" @@ -6588,8 +8104,23 @@ func (c *IAM) ListGroupsForUserRequest(input *ListGroupsForUserInput) (req *requ // Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListGroupsForUser func (c *IAM) ListGroupsForUser(input *ListGroupsForUserInput) (*ListGroupsForUserOutput, error) { req, out := c.ListGroupsForUserRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListGroupsForUserWithContext is the same as ListGroupsForUser with the addition of +// the ability to pass a context and additional request options. +// +// See ListGroupsForUser 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 *IAM) ListGroupsForUserWithContext(ctx aws.Context, input *ListGroupsForUserInput, opts ...request.Option) (*ListGroupsForUserOutput, error) { + req, out := c.ListGroupsForUserRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // ListGroupsForUserPages iterates over the pages of a ListGroupsForUser operation, @@ -6609,12 +8140,37 @@ func (c *IAM) ListGroupsForUser(input *ListGroupsForUserInput) (*ListGroupsForUs // return pageNum <= 3 // }) // -func (c *IAM) ListGroupsForUserPages(input *ListGroupsForUserInput, fn func(p *ListGroupsForUserOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.ListGroupsForUserRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*ListGroupsForUserOutput), lastPage) - }) +func (c *IAM) ListGroupsForUserPages(input *ListGroupsForUserInput, fn func(*ListGroupsForUserOutput, bool) bool) error { + return c.ListGroupsForUserPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListGroupsForUserPagesWithContext same as ListGroupsForUserPages 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 *IAM) ListGroupsForUserPagesWithContext(ctx aws.Context, input *ListGroupsForUserInput, fn func(*ListGroupsForUserOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListGroupsForUserInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListGroupsForUserRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*ListGroupsForUserOutput), !p.HasNextPage()) + } + return p.Err() } const opListInstanceProfiles = "ListInstanceProfiles" @@ -6689,8 +8245,23 @@ func (c *IAM) ListInstanceProfilesRequest(input *ListInstanceProfilesInput) (req // Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListInstanceProfiles func (c *IAM) ListInstanceProfiles(input *ListInstanceProfilesInput) (*ListInstanceProfilesOutput, error) { req, out := c.ListInstanceProfilesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListInstanceProfilesWithContext is the same as ListInstanceProfiles with the addition of +// the ability to pass a context and additional request options. +// +// See ListInstanceProfiles 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 *IAM) ListInstanceProfilesWithContext(ctx aws.Context, input *ListInstanceProfilesInput, opts ...request.Option) (*ListInstanceProfilesOutput, error) { + req, out := c.ListInstanceProfilesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // ListInstanceProfilesPages iterates over the pages of a ListInstanceProfiles operation, @@ -6710,12 +8281,37 @@ func (c *IAM) ListInstanceProfiles(input *ListInstanceProfilesInput) (*ListInsta // return pageNum <= 3 // }) // -func (c *IAM) ListInstanceProfilesPages(input *ListInstanceProfilesInput, fn func(p *ListInstanceProfilesOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.ListInstanceProfilesRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*ListInstanceProfilesOutput), lastPage) - }) +func (c *IAM) ListInstanceProfilesPages(input *ListInstanceProfilesInput, fn func(*ListInstanceProfilesOutput, bool) bool) error { + return c.ListInstanceProfilesPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListInstanceProfilesPagesWithContext same as ListInstanceProfilesPages 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 *IAM) ListInstanceProfilesPagesWithContext(ctx aws.Context, input *ListInstanceProfilesInput, fn func(*ListInstanceProfilesOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListInstanceProfilesInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListInstanceProfilesRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*ListInstanceProfilesOutput), !p.HasNextPage()) + } + return p.Err() } const opListInstanceProfilesForRole = "ListInstanceProfilesForRole" @@ -6794,8 +8390,23 @@ func (c *IAM) ListInstanceProfilesForRoleRequest(input *ListInstanceProfilesForR // Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListInstanceProfilesForRole func (c *IAM) ListInstanceProfilesForRole(input *ListInstanceProfilesForRoleInput) (*ListInstanceProfilesForRoleOutput, error) { req, out := c.ListInstanceProfilesForRoleRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListInstanceProfilesForRoleWithContext is the same as ListInstanceProfilesForRole with the addition of +// the ability to pass a context and additional request options. +// +// See ListInstanceProfilesForRole 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 *IAM) ListInstanceProfilesForRoleWithContext(ctx aws.Context, input *ListInstanceProfilesForRoleInput, opts ...request.Option) (*ListInstanceProfilesForRoleOutput, error) { + req, out := c.ListInstanceProfilesForRoleRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // ListInstanceProfilesForRolePages iterates over the pages of a ListInstanceProfilesForRole operation, @@ -6815,12 +8426,37 @@ func (c *IAM) ListInstanceProfilesForRole(input *ListInstanceProfilesForRoleInpu // return pageNum <= 3 // }) // -func (c *IAM) ListInstanceProfilesForRolePages(input *ListInstanceProfilesForRoleInput, fn func(p *ListInstanceProfilesForRoleOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.ListInstanceProfilesForRoleRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*ListInstanceProfilesForRoleOutput), lastPage) - }) +func (c *IAM) ListInstanceProfilesForRolePages(input *ListInstanceProfilesForRoleInput, fn func(*ListInstanceProfilesForRoleOutput, bool) bool) error { + return c.ListInstanceProfilesForRolePagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListInstanceProfilesForRolePagesWithContext same as ListInstanceProfilesForRolePages 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 *IAM) ListInstanceProfilesForRolePagesWithContext(ctx aws.Context, input *ListInstanceProfilesForRoleInput, fn func(*ListInstanceProfilesForRoleOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListInstanceProfilesForRoleInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListInstanceProfilesForRoleRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*ListInstanceProfilesForRoleOutput), !p.HasNextPage()) + } + return p.Err() } const opListMFADevices = "ListMFADevices" @@ -6900,8 +8536,23 @@ func (c *IAM) ListMFADevicesRequest(input *ListMFADevicesInput) (req *request.Re // Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListMFADevices func (c *IAM) ListMFADevices(input *ListMFADevicesInput) (*ListMFADevicesOutput, error) { req, out := c.ListMFADevicesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListMFADevicesWithContext is the same as ListMFADevices with the addition of +// the ability to pass a context and additional request options. +// +// See ListMFADevices 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 *IAM) ListMFADevicesWithContext(ctx aws.Context, input *ListMFADevicesInput, opts ...request.Option) (*ListMFADevicesOutput, error) { + req, out := c.ListMFADevicesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // ListMFADevicesPages iterates over the pages of a ListMFADevices operation, @@ -6921,12 +8572,37 @@ func (c *IAM) ListMFADevices(input *ListMFADevicesInput) (*ListMFADevicesOutput, // return pageNum <= 3 // }) // -func (c *IAM) ListMFADevicesPages(input *ListMFADevicesInput, fn func(p *ListMFADevicesOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.ListMFADevicesRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*ListMFADevicesOutput), lastPage) - }) +func (c *IAM) ListMFADevicesPages(input *ListMFADevicesInput, fn func(*ListMFADevicesOutput, bool) bool) error { + return c.ListMFADevicesPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListMFADevicesPagesWithContext same as ListMFADevicesPages 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 *IAM) ListMFADevicesPagesWithContext(ctx aws.Context, input *ListMFADevicesInput, fn func(*ListMFADevicesOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListMFADevicesInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListMFADevicesRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*ListMFADevicesOutput), !p.HasNextPage()) + } + return p.Err() } const opListOpenIDConnectProviders = "ListOpenIDConnectProviders" @@ -6992,8 +8668,23 @@ func (c *IAM) ListOpenIDConnectProvidersRequest(input *ListOpenIDConnectProvider // Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListOpenIDConnectProviders func (c *IAM) ListOpenIDConnectProviders(input *ListOpenIDConnectProvidersInput) (*ListOpenIDConnectProvidersOutput, error) { req, out := c.ListOpenIDConnectProvidersRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListOpenIDConnectProvidersWithContext is the same as ListOpenIDConnectProviders with the addition of +// the ability to pass a context and additional request options. +// +// See ListOpenIDConnectProviders 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 *IAM) ListOpenIDConnectProvidersWithContext(ctx aws.Context, input *ListOpenIDConnectProvidersInput, opts ...request.Option) (*ListOpenIDConnectProvidersOutput, error) { + req, out := c.ListOpenIDConnectProvidersRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opListPolicies = "ListPolicies" @@ -7076,8 +8767,23 @@ func (c *IAM) ListPoliciesRequest(input *ListPoliciesInput) (req *request.Reques // Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListPolicies func (c *IAM) ListPolicies(input *ListPoliciesInput) (*ListPoliciesOutput, error) { req, out := c.ListPoliciesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListPoliciesWithContext is the same as ListPolicies with the addition of +// the ability to pass a context and additional request options. +// +// See ListPolicies 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 *IAM) ListPoliciesWithContext(ctx aws.Context, input *ListPoliciesInput, opts ...request.Option) (*ListPoliciesOutput, error) { + req, out := c.ListPoliciesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // ListPoliciesPages iterates over the pages of a ListPolicies operation, @@ -7097,12 +8803,37 @@ func (c *IAM) ListPolicies(input *ListPoliciesInput) (*ListPoliciesOutput, error // return pageNum <= 3 // }) // -func (c *IAM) ListPoliciesPages(input *ListPoliciesInput, fn func(p *ListPoliciesOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.ListPoliciesRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*ListPoliciesOutput), lastPage) - }) +func (c *IAM) ListPoliciesPages(input *ListPoliciesInput, fn func(*ListPoliciesOutput, bool) bool) error { + return c.ListPoliciesPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListPoliciesPagesWithContext same as ListPoliciesPages 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 *IAM) ListPoliciesPagesWithContext(ctx aws.Context, input *ListPoliciesInput, fn func(*ListPoliciesOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListPoliciesInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListPoliciesRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*ListPoliciesOutput), !p.HasNextPage()) + } + return p.Err() } const opListPolicyVersions = "ListPolicyVersions" @@ -7186,8 +8917,23 @@ func (c *IAM) ListPolicyVersionsRequest(input *ListPolicyVersionsInput) (req *re // Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListPolicyVersions func (c *IAM) ListPolicyVersions(input *ListPolicyVersionsInput) (*ListPolicyVersionsOutput, error) { req, out := c.ListPolicyVersionsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListPolicyVersionsWithContext is the same as ListPolicyVersions with the addition of +// the ability to pass a context and additional request options. +// +// See ListPolicyVersions 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 *IAM) ListPolicyVersionsWithContext(ctx aws.Context, input *ListPolicyVersionsInput, opts ...request.Option) (*ListPolicyVersionsOutput, error) { + req, out := c.ListPolicyVersionsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // ListPolicyVersionsPages iterates over the pages of a ListPolicyVersions operation, @@ -7207,12 +8953,37 @@ func (c *IAM) ListPolicyVersions(input *ListPolicyVersionsInput) (*ListPolicyVer // return pageNum <= 3 // }) // -func (c *IAM) ListPolicyVersionsPages(input *ListPolicyVersionsInput, fn func(p *ListPolicyVersionsOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.ListPolicyVersionsRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*ListPolicyVersionsOutput), lastPage) - }) +func (c *IAM) ListPolicyVersionsPages(input *ListPolicyVersionsInput, fn func(*ListPolicyVersionsOutput, bool) bool) error { + return c.ListPolicyVersionsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListPolicyVersionsPagesWithContext same as ListPolicyVersionsPages 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 *IAM) ListPolicyVersionsPagesWithContext(ctx aws.Context, input *ListPolicyVersionsInput, fn func(*ListPolicyVersionsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListPolicyVersionsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListPolicyVersionsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*ListPolicyVersionsOutput), !p.HasNextPage()) + } + return p.Err() } const opListRolePolicies = "ListRolePolicies" @@ -7297,8 +9068,23 @@ func (c *IAM) ListRolePoliciesRequest(input *ListRolePoliciesInput) (req *reques // Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListRolePolicies func (c *IAM) ListRolePolicies(input *ListRolePoliciesInput) (*ListRolePoliciesOutput, error) { req, out := c.ListRolePoliciesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListRolePoliciesWithContext is the same as ListRolePolicies with the addition of +// the ability to pass a context and additional request options. +// +// See ListRolePolicies 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 *IAM) ListRolePoliciesWithContext(ctx aws.Context, input *ListRolePoliciesInput, opts ...request.Option) (*ListRolePoliciesOutput, error) { + req, out := c.ListRolePoliciesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // ListRolePoliciesPages iterates over the pages of a ListRolePolicies operation, @@ -7318,12 +9104,37 @@ func (c *IAM) ListRolePolicies(input *ListRolePoliciesInput) (*ListRolePoliciesO // return pageNum <= 3 // }) // -func (c *IAM) ListRolePoliciesPages(input *ListRolePoliciesInput, fn func(p *ListRolePoliciesOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.ListRolePoliciesRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*ListRolePoliciesOutput), lastPage) - }) +func (c *IAM) ListRolePoliciesPages(input *ListRolePoliciesInput, fn func(*ListRolePoliciesOutput, bool) bool) error { + return c.ListRolePoliciesPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListRolePoliciesPagesWithContext same as ListRolePoliciesPages 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 *IAM) ListRolePoliciesPagesWithContext(ctx aws.Context, input *ListRolePoliciesInput, fn func(*ListRolePoliciesOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListRolePoliciesInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListRolePoliciesRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*ListRolePoliciesOutput), !p.HasNextPage()) + } + return p.Err() } const opListRoles = "ListRoles" @@ -7398,8 +9209,23 @@ func (c *IAM) ListRolesRequest(input *ListRolesInput) (req *request.Request, out // Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListRoles func (c *IAM) ListRoles(input *ListRolesInput) (*ListRolesOutput, error) { req, out := c.ListRolesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListRolesWithContext is the same as ListRoles with the addition of +// the ability to pass a context and additional request options. +// +// See ListRoles 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 *IAM) ListRolesWithContext(ctx aws.Context, input *ListRolesInput, opts ...request.Option) (*ListRolesOutput, error) { + req, out := c.ListRolesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // ListRolesPages iterates over the pages of a ListRoles operation, @@ -7419,12 +9245,37 @@ func (c *IAM) ListRoles(input *ListRolesInput) (*ListRolesOutput, error) { // return pageNum <= 3 // }) // -func (c *IAM) ListRolesPages(input *ListRolesInput, fn func(p *ListRolesOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.ListRolesRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*ListRolesOutput), lastPage) - }) +func (c *IAM) ListRolesPages(input *ListRolesInput, fn func(*ListRolesOutput, bool) bool) error { + return c.ListRolesPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListRolesPagesWithContext same as ListRolesPages 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 *IAM) ListRolesPagesWithContext(ctx aws.Context, input *ListRolesInput, fn func(*ListRolesOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListRolesInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListRolesRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*ListRolesOutput), !p.HasNextPage()) + } + return p.Err() } const opListSAMLProviders = "ListSAMLProviders" @@ -7491,8 +9342,23 @@ func (c *IAM) ListSAMLProvidersRequest(input *ListSAMLProvidersInput) (req *requ // Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListSAMLProviders func (c *IAM) ListSAMLProviders(input *ListSAMLProvidersInput) (*ListSAMLProvidersOutput, error) { req, out := c.ListSAMLProvidersRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListSAMLProvidersWithContext is the same as ListSAMLProviders with the addition of +// the ability to pass a context and additional request options. +// +// See ListSAMLProviders 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 *IAM) ListSAMLProvidersWithContext(ctx aws.Context, input *ListSAMLProvidersInput, opts ...request.Option) (*ListSAMLProvidersOutput, error) { + req, out := c.ListSAMLProvidersRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opListSSHPublicKeys = "ListSSHPublicKeys" @@ -7573,8 +9439,23 @@ func (c *IAM) ListSSHPublicKeysRequest(input *ListSSHPublicKeysInput) (req *requ // Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListSSHPublicKeys func (c *IAM) ListSSHPublicKeys(input *ListSSHPublicKeysInput) (*ListSSHPublicKeysOutput, error) { req, out := c.ListSSHPublicKeysRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListSSHPublicKeysWithContext is the same as ListSSHPublicKeys with the addition of +// the ability to pass a context and additional request options. +// +// See ListSSHPublicKeys 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 *IAM) ListSSHPublicKeysWithContext(ctx aws.Context, input *ListSSHPublicKeysInput, opts ...request.Option) (*ListSSHPublicKeysOutput, error) { + req, out := c.ListSSHPublicKeysRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // ListSSHPublicKeysPages iterates over the pages of a ListSSHPublicKeys operation, @@ -7594,12 +9475,37 @@ func (c *IAM) ListSSHPublicKeys(input *ListSSHPublicKeysInput) (*ListSSHPublicKe // return pageNum <= 3 // }) // -func (c *IAM) ListSSHPublicKeysPages(input *ListSSHPublicKeysInput, fn func(p *ListSSHPublicKeysOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.ListSSHPublicKeysRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*ListSSHPublicKeysOutput), lastPage) - }) +func (c *IAM) ListSSHPublicKeysPages(input *ListSSHPublicKeysInput, fn func(*ListSSHPublicKeysOutput, bool) bool) error { + return c.ListSSHPublicKeysPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListSSHPublicKeysPagesWithContext same as ListSSHPublicKeysPages 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 *IAM) ListSSHPublicKeysPagesWithContext(ctx aws.Context, input *ListSSHPublicKeysInput, fn func(*ListSSHPublicKeysOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListSSHPublicKeysInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListSSHPublicKeysRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*ListSSHPublicKeysOutput), !p.HasNextPage()) + } + return p.Err() } const opListServerCertificates = "ListServerCertificates" @@ -7678,8 +9584,23 @@ func (c *IAM) ListServerCertificatesRequest(input *ListServerCertificatesInput) // Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListServerCertificates func (c *IAM) ListServerCertificates(input *ListServerCertificatesInput) (*ListServerCertificatesOutput, error) { req, out := c.ListServerCertificatesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListServerCertificatesWithContext is the same as ListServerCertificates with the addition of +// the ability to pass a context and additional request options. +// +// See ListServerCertificates 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 *IAM) ListServerCertificatesWithContext(ctx aws.Context, input *ListServerCertificatesInput, opts ...request.Option) (*ListServerCertificatesOutput, error) { + req, out := c.ListServerCertificatesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // ListServerCertificatesPages iterates over the pages of a ListServerCertificates operation, @@ -7699,12 +9620,37 @@ func (c *IAM) ListServerCertificates(input *ListServerCertificatesInput) (*ListS // return pageNum <= 3 // }) // -func (c *IAM) ListServerCertificatesPages(input *ListServerCertificatesInput, fn func(p *ListServerCertificatesOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.ListServerCertificatesRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*ListServerCertificatesOutput), lastPage) - }) +func (c *IAM) ListServerCertificatesPages(input *ListServerCertificatesInput, fn func(*ListServerCertificatesOutput, bool) bool) error { + return c.ListServerCertificatesPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListServerCertificatesPagesWithContext same as ListServerCertificatesPages 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 *IAM) ListServerCertificatesPagesWithContext(ctx aws.Context, input *ListServerCertificatesInput, fn func(*ListServerCertificatesOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListServerCertificatesInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListServerCertificatesRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*ListServerCertificatesOutput), !p.HasNextPage()) + } + return p.Err() } const opListServiceSpecificCredentials = "ListServiceSpecificCredentials" @@ -7778,8 +9724,23 @@ func (c *IAM) ListServiceSpecificCredentialsRequest(input *ListServiceSpecificCr // Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListServiceSpecificCredentials func (c *IAM) ListServiceSpecificCredentials(input *ListServiceSpecificCredentialsInput) (*ListServiceSpecificCredentialsOutput, error) { req, out := c.ListServiceSpecificCredentialsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListServiceSpecificCredentialsWithContext is the same as ListServiceSpecificCredentials with the addition of +// the ability to pass a context and additional request options. +// +// See ListServiceSpecificCredentials 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 *IAM) ListServiceSpecificCredentialsWithContext(ctx aws.Context, input *ListServiceSpecificCredentialsInput, opts ...request.Option) (*ListServiceSpecificCredentialsOutput, error) { + req, out := c.ListServiceSpecificCredentialsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opListSigningCertificates = "ListSigningCertificates" @@ -7864,8 +9825,23 @@ func (c *IAM) ListSigningCertificatesRequest(input *ListSigningCertificatesInput // Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListSigningCertificates func (c *IAM) ListSigningCertificates(input *ListSigningCertificatesInput) (*ListSigningCertificatesOutput, error) { req, out := c.ListSigningCertificatesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListSigningCertificatesWithContext is the same as ListSigningCertificates with the addition of +// the ability to pass a context and additional request options. +// +// See ListSigningCertificates 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 *IAM) ListSigningCertificatesWithContext(ctx aws.Context, input *ListSigningCertificatesInput, opts ...request.Option) (*ListSigningCertificatesOutput, error) { + req, out := c.ListSigningCertificatesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // ListSigningCertificatesPages iterates over the pages of a ListSigningCertificates operation, @@ -7885,12 +9861,37 @@ func (c *IAM) ListSigningCertificates(input *ListSigningCertificatesInput) (*Lis // return pageNum <= 3 // }) // -func (c *IAM) ListSigningCertificatesPages(input *ListSigningCertificatesInput, fn func(p *ListSigningCertificatesOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.ListSigningCertificatesRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*ListSigningCertificatesOutput), lastPage) - }) +func (c *IAM) ListSigningCertificatesPages(input *ListSigningCertificatesInput, fn func(*ListSigningCertificatesOutput, bool) bool) error { + return c.ListSigningCertificatesPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListSigningCertificatesPagesWithContext same as ListSigningCertificatesPages 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 *IAM) ListSigningCertificatesPagesWithContext(ctx aws.Context, input *ListSigningCertificatesInput, fn func(*ListSigningCertificatesOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListSigningCertificatesInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListSigningCertificatesRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*ListSigningCertificatesOutput), !p.HasNextPage()) + } + return p.Err() } const opListUserPolicies = "ListUserPolicies" @@ -7974,8 +9975,23 @@ func (c *IAM) ListUserPoliciesRequest(input *ListUserPoliciesInput) (req *reques // Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListUserPolicies func (c *IAM) ListUserPolicies(input *ListUserPoliciesInput) (*ListUserPoliciesOutput, error) { req, out := c.ListUserPoliciesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListUserPoliciesWithContext is the same as ListUserPolicies with the addition of +// the ability to pass a context and additional request options. +// +// See ListUserPolicies 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 *IAM) ListUserPoliciesWithContext(ctx aws.Context, input *ListUserPoliciesInput, opts ...request.Option) (*ListUserPoliciesOutput, error) { + req, out := c.ListUserPoliciesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // ListUserPoliciesPages iterates over the pages of a ListUserPolicies operation, @@ -7995,12 +10011,37 @@ func (c *IAM) ListUserPolicies(input *ListUserPoliciesInput) (*ListUserPoliciesO // return pageNum <= 3 // }) // -func (c *IAM) ListUserPoliciesPages(input *ListUserPoliciesInput, fn func(p *ListUserPoliciesOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.ListUserPoliciesRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*ListUserPoliciesOutput), lastPage) - }) +func (c *IAM) ListUserPoliciesPages(input *ListUserPoliciesInput, fn func(*ListUserPoliciesOutput, bool) bool) error { + return c.ListUserPoliciesPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListUserPoliciesPagesWithContext same as ListUserPoliciesPages 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 *IAM) ListUserPoliciesPagesWithContext(ctx aws.Context, input *ListUserPoliciesInput, fn func(*ListUserPoliciesOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListUserPoliciesInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListUserPoliciesRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*ListUserPoliciesOutput), !p.HasNextPage()) + } + return p.Err() } const opListUsers = "ListUsers" @@ -8075,8 +10116,23 @@ func (c *IAM) ListUsersRequest(input *ListUsersInput) (req *request.Request, out // Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListUsers func (c *IAM) ListUsers(input *ListUsersInput) (*ListUsersOutput, error) { req, out := c.ListUsersRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListUsersWithContext is the same as ListUsers with the addition of +// the ability to pass a context and additional request options. +// +// See ListUsers 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 *IAM) ListUsersWithContext(ctx aws.Context, input *ListUsersInput, opts ...request.Option) (*ListUsersOutput, error) { + req, out := c.ListUsersRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // ListUsersPages iterates over the pages of a ListUsers operation, @@ -8096,12 +10152,37 @@ func (c *IAM) ListUsers(input *ListUsersInput) (*ListUsersOutput, error) { // return pageNum <= 3 // }) // -func (c *IAM) ListUsersPages(input *ListUsersInput, fn func(p *ListUsersOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.ListUsersRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*ListUsersOutput), lastPage) - }) +func (c *IAM) ListUsersPages(input *ListUsersInput, fn func(*ListUsersOutput, bool) bool) error { + return c.ListUsersPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListUsersPagesWithContext same as ListUsersPages 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 *IAM) ListUsersPagesWithContext(ctx aws.Context, input *ListUsersInput, fn func(*ListUsersOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListUsersInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListUsersRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*ListUsersOutput), !p.HasNextPage()) + } + return p.Err() } const opListVirtualMFADevices = "ListVirtualMFADevices" @@ -8171,8 +10252,23 @@ func (c *IAM) ListVirtualMFADevicesRequest(input *ListVirtualMFADevicesInput) (r // Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListVirtualMFADevices func (c *IAM) ListVirtualMFADevices(input *ListVirtualMFADevicesInput) (*ListVirtualMFADevicesOutput, error) { req, out := c.ListVirtualMFADevicesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListVirtualMFADevicesWithContext is the same as ListVirtualMFADevices with the addition of +// the ability to pass a context and additional request options. +// +// See ListVirtualMFADevices 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 *IAM) ListVirtualMFADevicesWithContext(ctx aws.Context, input *ListVirtualMFADevicesInput, opts ...request.Option) (*ListVirtualMFADevicesOutput, error) { + req, out := c.ListVirtualMFADevicesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // ListVirtualMFADevicesPages iterates over the pages of a ListVirtualMFADevices operation, @@ -8192,12 +10288,37 @@ func (c *IAM) ListVirtualMFADevices(input *ListVirtualMFADevicesInput) (*ListVir // return pageNum <= 3 // }) // -func (c *IAM) ListVirtualMFADevicesPages(input *ListVirtualMFADevicesInput, fn func(p *ListVirtualMFADevicesOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.ListVirtualMFADevicesRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*ListVirtualMFADevicesOutput), lastPage) - }) +func (c *IAM) ListVirtualMFADevicesPages(input *ListVirtualMFADevicesInput, fn func(*ListVirtualMFADevicesOutput, bool) bool) error { + return c.ListVirtualMFADevicesPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListVirtualMFADevicesPagesWithContext same as ListVirtualMFADevicesPages 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 *IAM) ListVirtualMFADevicesPagesWithContext(ctx aws.Context, input *ListVirtualMFADevicesInput, fn func(*ListVirtualMFADevicesOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListVirtualMFADevicesInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListVirtualMFADevicesRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*ListVirtualMFADevicesOutput), !p.HasNextPage()) + } + return p.Err() } const opPutGroupPolicy = "PutGroupPolicy" @@ -8292,8 +10413,23 @@ func (c *IAM) PutGroupPolicyRequest(input *PutGroupPolicyInput) (req *request.Re // Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/PutGroupPolicy func (c *IAM) PutGroupPolicy(input *PutGroupPolicyInput) (*PutGroupPolicyOutput, error) { req, out := c.PutGroupPolicyRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// PutGroupPolicyWithContext is the same as PutGroupPolicy with the addition of +// the ability to pass a context and additional request options. +// +// See PutGroupPolicy 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 *IAM) PutGroupPolicyWithContext(ctx aws.Context, input *PutGroupPolicyInput, opts ...request.Option) (*PutGroupPolicyOutput, error) { + req, out := c.PutGroupPolicyRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opPutRolePolicy = "PutRolePolicy" @@ -8387,6 +10523,12 @@ func (c *IAM) PutRolePolicyRequest(input *PutRolePolicyInput) (req *request.Requ // The request was rejected because it referenced an entity that does not exist. // The error message describes the entity. // +// * ErrCodeUnmodifiableEntityException "UnmodifiableEntity" +// The request was rejected because only the service that depends on the service-linked +// role can modify or delete the role on your behalf. The error message includes +// the name of the service that depends on this service-linked role. You must +// request the change through that service. +// // * ErrCodeServiceFailureException "ServiceFailure" // The request processing has failed because of an unknown error, exception // or failure. @@ -8394,8 +10536,23 @@ func (c *IAM) PutRolePolicyRequest(input *PutRolePolicyInput) (req *request.Requ // Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/PutRolePolicy func (c *IAM) PutRolePolicy(input *PutRolePolicyInput) (*PutRolePolicyOutput, error) { req, out := c.PutRolePolicyRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// PutRolePolicyWithContext is the same as PutRolePolicy with the addition of +// the ability to pass a context and additional request options. +// +// See PutRolePolicy 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 *IAM) PutRolePolicyWithContext(ctx aws.Context, input *PutRolePolicyInput, opts ...request.Option) (*PutRolePolicyOutput, error) { + req, out := c.PutRolePolicyRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opPutUserPolicy = "PutUserPolicy" @@ -8490,8 +10647,23 @@ func (c *IAM) PutUserPolicyRequest(input *PutUserPolicyInput) (req *request.Requ // Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/PutUserPolicy func (c *IAM) PutUserPolicy(input *PutUserPolicyInput) (*PutUserPolicyOutput, error) { req, out := c.PutUserPolicyRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// PutUserPolicyWithContext is the same as PutUserPolicy with the addition of +// the ability to pass a context and additional request options. +// +// See PutUserPolicy 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 *IAM) PutUserPolicyWithContext(ctx aws.Context, input *PutUserPolicyInput, opts ...request.Option) (*PutUserPolicyOutput, error) { + req, out := c.PutUserPolicyRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opRemoveClientIDFromOpenIDConnectProvider = "RemoveClientIDFromOpenIDConnectProvider" @@ -8571,8 +10743,23 @@ func (c *IAM) RemoveClientIDFromOpenIDConnectProviderRequest(input *RemoveClient // Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/RemoveClientIDFromOpenIDConnectProvider func (c *IAM) RemoveClientIDFromOpenIDConnectProvider(input *RemoveClientIDFromOpenIDConnectProviderInput) (*RemoveClientIDFromOpenIDConnectProviderOutput, error) { req, out := c.RemoveClientIDFromOpenIDConnectProviderRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// RemoveClientIDFromOpenIDConnectProviderWithContext is the same as RemoveClientIDFromOpenIDConnectProvider with the addition of +// the ability to pass a context and additional request options. +// +// See RemoveClientIDFromOpenIDConnectProvider 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 *IAM) RemoveClientIDFromOpenIDConnectProviderWithContext(ctx aws.Context, input *RemoveClientIDFromOpenIDConnectProviderInput, opts ...request.Option) (*RemoveClientIDFromOpenIDConnectProviderOutput, error) { + req, out := c.RemoveClientIDFromOpenIDConnectProviderRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opRemoveRoleFromInstanceProfile = "RemoveRoleFromInstanceProfile" @@ -8626,8 +10813,8 @@ func (c *IAM) RemoveRoleFromInstanceProfileRequest(input *RemoveRoleFromInstance // // Make sure you do not have any Amazon EC2 instances running with the role // you are about to remove from the instance profile. Removing a role from an -// instance profile that is associated with a running instance break any applications -// running on the instance. +// instance profile that is associated with a running instance might break any +// applications running on the instance. // // For more information about IAM roles, go to Working with Roles (http://docs.aws.amazon.com/IAM/latest/UserGuide/WorkingWithRoles.html). // For more information about instance profiles, go to About Instance Profiles @@ -8649,6 +10836,12 @@ func (c *IAM) RemoveRoleFromInstanceProfileRequest(input *RemoveRoleFromInstance // The request was rejected because it attempted to create resources beyond // the current AWS account limits. The error message describes the limit exceeded. // +// * ErrCodeUnmodifiableEntityException "UnmodifiableEntity" +// The request was rejected because only the service that depends on the service-linked +// role can modify or delete the role on your behalf. The error message includes +// the name of the service that depends on this service-linked role. You must +// request the change through that service. +// // * ErrCodeServiceFailureException "ServiceFailure" // The request processing has failed because of an unknown error, exception // or failure. @@ -8656,8 +10849,23 @@ func (c *IAM) RemoveRoleFromInstanceProfileRequest(input *RemoveRoleFromInstance // Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/RemoveRoleFromInstanceProfile func (c *IAM) RemoveRoleFromInstanceProfile(input *RemoveRoleFromInstanceProfileInput) (*RemoveRoleFromInstanceProfileOutput, error) { req, out := c.RemoveRoleFromInstanceProfileRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// RemoveRoleFromInstanceProfileWithContext is the same as RemoveRoleFromInstanceProfile with the addition of +// the ability to pass a context and additional request options. +// +// See RemoveRoleFromInstanceProfile 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 *IAM) RemoveRoleFromInstanceProfileWithContext(ctx aws.Context, input *RemoveRoleFromInstanceProfileInput, opts ...request.Option) (*RemoveRoleFromInstanceProfileOutput, error) { + req, out := c.RemoveRoleFromInstanceProfileRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opRemoveUserFromGroup = "RemoveUserFromGroup" @@ -8732,8 +10940,23 @@ func (c *IAM) RemoveUserFromGroupRequest(input *RemoveUserFromGroupInput) (req * // Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/RemoveUserFromGroup func (c *IAM) RemoveUserFromGroup(input *RemoveUserFromGroupInput) (*RemoveUserFromGroupOutput, error) { req, out := c.RemoveUserFromGroupRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// RemoveUserFromGroupWithContext is the same as RemoveUserFromGroup with the addition of +// the ability to pass a context and additional request options. +// +// See RemoveUserFromGroup 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 *IAM) RemoveUserFromGroupWithContext(ctx aws.Context, input *RemoveUserFromGroupInput, opts ...request.Option) (*RemoveUserFromGroupOutput, error) { + req, out := c.RemoveUserFromGroupRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opResetServiceSpecificCredential = "ResetServiceSpecificCredential" @@ -8801,8 +11024,23 @@ func (c *IAM) ResetServiceSpecificCredentialRequest(input *ResetServiceSpecificC // Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ResetServiceSpecificCredential func (c *IAM) ResetServiceSpecificCredential(input *ResetServiceSpecificCredentialInput) (*ResetServiceSpecificCredentialOutput, error) { req, out := c.ResetServiceSpecificCredentialRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ResetServiceSpecificCredentialWithContext is the same as ResetServiceSpecificCredential with the addition of +// the ability to pass a context and additional request options. +// +// See ResetServiceSpecificCredential 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 *IAM) ResetServiceSpecificCredentialWithContext(ctx aws.Context, input *ResetServiceSpecificCredentialInput, opts ...request.Option) (*ResetServiceSpecificCredentialOutput, error) { + req, out := c.ResetServiceSpecificCredentialRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opResyncMFADevice = "ResyncMFADevice" @@ -8886,8 +11124,23 @@ func (c *IAM) ResyncMFADeviceRequest(input *ResyncMFADeviceInput) (req *request. // Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ResyncMFADevice func (c *IAM) ResyncMFADevice(input *ResyncMFADeviceInput) (*ResyncMFADeviceOutput, error) { req, out := c.ResyncMFADeviceRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ResyncMFADeviceWithContext is the same as ResyncMFADevice with the addition of +// the ability to pass a context and additional request options. +// +// See ResyncMFADevice 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 *IAM) ResyncMFADeviceWithContext(ctx aws.Context, input *ResyncMFADeviceInput, opts ...request.Option) (*ResyncMFADeviceOutput, error) { + req, out := c.ResyncMFADeviceRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opSetDefaultPolicyVersion = "SetDefaultPolicyVersion" @@ -8975,8 +11228,23 @@ func (c *IAM) SetDefaultPolicyVersionRequest(input *SetDefaultPolicyVersionInput // Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/SetDefaultPolicyVersion func (c *IAM) SetDefaultPolicyVersion(input *SetDefaultPolicyVersionInput) (*SetDefaultPolicyVersionOutput, error) { req, out := c.SetDefaultPolicyVersionRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// SetDefaultPolicyVersionWithContext is the same as SetDefaultPolicyVersion with the addition of +// the ability to pass a context and additional request options. +// +// See SetDefaultPolicyVersion 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 *IAM) SetDefaultPolicyVersionWithContext(ctx aws.Context, input *SetDefaultPolicyVersionInput, opts ...request.Option) (*SetDefaultPolicyVersionOutput, error) { + req, out := c.SetDefaultPolicyVersionRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opSimulateCustomPolicy = "SimulateCustomPolicy" @@ -9067,8 +11335,23 @@ func (c *IAM) SimulateCustomPolicyRequest(input *SimulateCustomPolicyInput) (req // Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/SimulateCustomPolicy func (c *IAM) SimulateCustomPolicy(input *SimulateCustomPolicyInput) (*SimulatePolicyResponse, error) { req, out := c.SimulateCustomPolicyRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// SimulateCustomPolicyWithContext is the same as SimulateCustomPolicy with the addition of +// the ability to pass a context and additional request options. +// +// See SimulateCustomPolicy 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 *IAM) SimulateCustomPolicyWithContext(ctx aws.Context, input *SimulateCustomPolicyInput, opts ...request.Option) (*SimulatePolicyResponse, error) { + req, out := c.SimulateCustomPolicyRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // SimulateCustomPolicyPages iterates over the pages of a SimulateCustomPolicy operation, @@ -9088,12 +11371,37 @@ func (c *IAM) SimulateCustomPolicy(input *SimulateCustomPolicyInput) (*SimulateP // return pageNum <= 3 // }) // -func (c *IAM) SimulateCustomPolicyPages(input *SimulateCustomPolicyInput, fn func(p *SimulatePolicyResponse, lastPage bool) (shouldContinue bool)) error { - page, _ := c.SimulateCustomPolicyRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*SimulatePolicyResponse), lastPage) - }) +func (c *IAM) SimulateCustomPolicyPages(input *SimulateCustomPolicyInput, fn func(*SimulatePolicyResponse, bool) bool) error { + return c.SimulateCustomPolicyPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// SimulateCustomPolicyPagesWithContext same as SimulateCustomPolicyPages 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 *IAM) SimulateCustomPolicyPagesWithContext(ctx aws.Context, input *SimulateCustomPolicyInput, fn func(*SimulatePolicyResponse, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *SimulateCustomPolicyInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.SimulateCustomPolicyRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*SimulatePolicyResponse), !p.HasNextPage()) + } + return p.Err() } const opSimulatePrincipalPolicy = "SimulatePrincipalPolicy" @@ -9198,8 +11506,23 @@ func (c *IAM) SimulatePrincipalPolicyRequest(input *SimulatePrincipalPolicyInput // Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/SimulatePrincipalPolicy func (c *IAM) SimulatePrincipalPolicy(input *SimulatePrincipalPolicyInput) (*SimulatePolicyResponse, error) { req, out := c.SimulatePrincipalPolicyRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// SimulatePrincipalPolicyWithContext is the same as SimulatePrincipalPolicy with the addition of +// the ability to pass a context and additional request options. +// +// See SimulatePrincipalPolicy 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 *IAM) SimulatePrincipalPolicyWithContext(ctx aws.Context, input *SimulatePrincipalPolicyInput, opts ...request.Option) (*SimulatePolicyResponse, error) { + req, out := c.SimulatePrincipalPolicyRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // SimulatePrincipalPolicyPages iterates over the pages of a SimulatePrincipalPolicy operation, @@ -9219,12 +11542,37 @@ func (c *IAM) SimulatePrincipalPolicy(input *SimulatePrincipalPolicyInput) (*Sim // return pageNum <= 3 // }) // -func (c *IAM) SimulatePrincipalPolicyPages(input *SimulatePrincipalPolicyInput, fn func(p *SimulatePolicyResponse, lastPage bool) (shouldContinue bool)) error { - page, _ := c.SimulatePrincipalPolicyRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*SimulatePolicyResponse), lastPage) - }) +func (c *IAM) SimulatePrincipalPolicyPages(input *SimulatePrincipalPolicyInput, fn func(*SimulatePolicyResponse, bool) bool) error { + return c.SimulatePrincipalPolicyPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// SimulatePrincipalPolicyPagesWithContext same as SimulatePrincipalPolicyPages 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 *IAM) SimulatePrincipalPolicyPagesWithContext(ctx aws.Context, input *SimulatePrincipalPolicyInput, fn func(*SimulatePolicyResponse, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *SimulatePrincipalPolicyInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.SimulatePrincipalPolicyRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*SimulatePolicyResponse), !p.HasNextPage()) + } + return p.Err() } const opUpdateAccessKey = "UpdateAccessKey" @@ -9309,8 +11657,23 @@ func (c *IAM) UpdateAccessKeyRequest(input *UpdateAccessKeyInput) (req *request. // Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/UpdateAccessKey func (c *IAM) UpdateAccessKey(input *UpdateAccessKeyInput) (*UpdateAccessKeyOutput, error) { req, out := c.UpdateAccessKeyRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// UpdateAccessKeyWithContext is the same as UpdateAccessKey with the addition of +// the ability to pass a context and additional request options. +// +// See UpdateAccessKey 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 *IAM) UpdateAccessKeyWithContext(ctx aws.Context, input *UpdateAccessKeyInput, opts ...request.Option) (*UpdateAccessKeyOutput, error) { + req, out := c.UpdateAccessKeyRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opUpdateAccountPasswordPolicy = "UpdateAccountPasswordPolicy" @@ -9398,8 +11761,23 @@ func (c *IAM) UpdateAccountPasswordPolicyRequest(input *UpdateAccountPasswordPol // Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/UpdateAccountPasswordPolicy func (c *IAM) UpdateAccountPasswordPolicy(input *UpdateAccountPasswordPolicyInput) (*UpdateAccountPasswordPolicyOutput, error) { req, out := c.UpdateAccountPasswordPolicyRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// UpdateAccountPasswordPolicyWithContext is the same as UpdateAccountPasswordPolicy with the addition of +// the ability to pass a context and additional request options. +// +// See UpdateAccountPasswordPolicy 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 *IAM) UpdateAccountPasswordPolicyWithContext(ctx aws.Context, input *UpdateAccountPasswordPolicyInput, opts ...request.Option) (*UpdateAccountPasswordPolicyOutput, error) { + req, out := c.UpdateAccountPasswordPolicyRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opUpdateAssumeRolePolicy = "UpdateAssumeRolePolicy" @@ -9474,6 +11852,12 @@ func (c *IAM) UpdateAssumeRolePolicyRequest(input *UpdateAssumeRolePolicyInput) // The request was rejected because it attempted to create resources beyond // the current AWS account limits. The error message describes the limit exceeded. // +// * ErrCodeUnmodifiableEntityException "UnmodifiableEntity" +// The request was rejected because only the service that depends on the service-linked +// role can modify or delete the role on your behalf. The error message includes +// the name of the service that depends on this service-linked role. You must +// request the change through that service. +// // * ErrCodeServiceFailureException "ServiceFailure" // The request processing has failed because of an unknown error, exception // or failure. @@ -9481,8 +11865,23 @@ func (c *IAM) UpdateAssumeRolePolicyRequest(input *UpdateAssumeRolePolicyInput) // Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/UpdateAssumeRolePolicy func (c *IAM) UpdateAssumeRolePolicy(input *UpdateAssumeRolePolicyInput) (*UpdateAssumeRolePolicyOutput, error) { req, out := c.UpdateAssumeRolePolicyRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// UpdateAssumeRolePolicyWithContext is the same as UpdateAssumeRolePolicy with the addition of +// the ability to pass a context and additional request options. +// +// See UpdateAssumeRolePolicy 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 *IAM) UpdateAssumeRolePolicyWithContext(ctx aws.Context, input *UpdateAssumeRolePolicyInput, opts ...request.Option) (*UpdateAssumeRolePolicyOutput, error) { + req, out := c.UpdateAssumeRolePolicyRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opUpdateGroup = "UpdateGroup" @@ -9571,8 +11970,23 @@ func (c *IAM) UpdateGroupRequest(input *UpdateGroupInput) (req *request.Request, // Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/UpdateGroup func (c *IAM) UpdateGroup(input *UpdateGroupInput) (*UpdateGroupOutput, error) { req, out := c.UpdateGroupRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// UpdateGroupWithContext is the same as UpdateGroup with the addition of +// the ability to pass a context and additional request options. +// +// See UpdateGroup 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 *IAM) UpdateGroupWithContext(ctx aws.Context, input *UpdateGroupInput, opts ...request.Option) (*UpdateGroupOutput, error) { + req, out := c.UpdateGroupRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opUpdateLoginProfile = "UpdateLoginProfile" @@ -9661,8 +12075,23 @@ func (c *IAM) UpdateLoginProfileRequest(input *UpdateLoginProfileInput) (req *re // Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/UpdateLoginProfile func (c *IAM) UpdateLoginProfile(input *UpdateLoginProfileInput) (*UpdateLoginProfileOutput, error) { req, out := c.UpdateLoginProfileRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// UpdateLoginProfileWithContext is the same as UpdateLoginProfile with the addition of +// the ability to pass a context and additional request options. +// +// See UpdateLoginProfile 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 *IAM) UpdateLoginProfileWithContext(ctx aws.Context, input *UpdateLoginProfileInput, opts ...request.Option) (*UpdateLoginProfileOutput, error) { + req, out := c.UpdateLoginProfileRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opUpdateOpenIDConnectProviderThumbprint = "UpdateOpenIDConnectProviderThumbprint" @@ -9751,8 +12180,114 @@ func (c *IAM) UpdateOpenIDConnectProviderThumbprintRequest(input *UpdateOpenIDCo // Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/UpdateOpenIDConnectProviderThumbprint func (c *IAM) UpdateOpenIDConnectProviderThumbprint(input *UpdateOpenIDConnectProviderThumbprintInput) (*UpdateOpenIDConnectProviderThumbprintOutput, error) { req, out := c.UpdateOpenIDConnectProviderThumbprintRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// UpdateOpenIDConnectProviderThumbprintWithContext is the same as UpdateOpenIDConnectProviderThumbprint with the addition of +// the ability to pass a context and additional request options. +// +// See UpdateOpenIDConnectProviderThumbprint 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 *IAM) UpdateOpenIDConnectProviderThumbprintWithContext(ctx aws.Context, input *UpdateOpenIDConnectProviderThumbprintInput, opts ...request.Option) (*UpdateOpenIDConnectProviderThumbprintOutput, error) { + req, out := c.UpdateOpenIDConnectProviderThumbprintRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opUpdateRoleDescription = "UpdateRoleDescription" + +// UpdateRoleDescriptionRequest generates a "aws/request.Request" representing the +// client's request for the UpdateRoleDescription operation. The "output" return +// value can be used to capture response data after the request's "Send" method +// is called. +// +// See UpdateRoleDescription for usage and error information. +// +// Creating a request object using this method should be used when you want to inject +// custom logic into the request's lifecycle using a custom handler, or if you want to +// access properties on the request object before or after sending the request. If +// you just want the service response, call the UpdateRoleDescription method directly +// instead. +// +// Note: You must call the "Send" method on the returned request object in order +// to execute the request. +// +// // Example sending a request using the UpdateRoleDescriptionRequest method. +// req, resp := client.UpdateRoleDescriptionRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/UpdateRoleDescription +func (c *IAM) UpdateRoleDescriptionRequest(input *UpdateRoleDescriptionInput) (req *request.Request, output *UpdateRoleDescriptionOutput) { + op := &request.Operation{ + Name: opUpdateRoleDescription, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &UpdateRoleDescriptionInput{} + } + + output = &UpdateRoleDescriptionOutput{} + req = c.newRequest(op, input, output) + return +} + +// UpdateRoleDescription API operation for AWS Identity and Access Management. +// +// Modifies the description of a role. +// +// 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 Identity and Access Management's +// API operation UpdateRoleDescription for usage and error information. +// +// Returned Error Codes: +// * ErrCodeNoSuchEntityException "NoSuchEntity" +// The request was rejected because it referenced an entity that does not exist. +// The error message describes the entity. +// +// * ErrCodeUnmodifiableEntityException "UnmodifiableEntity" +// The request was rejected because only the service that depends on the service-linked +// role can modify or delete the role on your behalf. The error message includes +// the name of the service that depends on this service-linked role. You must +// request the change through that service. +// +// * ErrCodeServiceFailureException "ServiceFailure" +// The request processing has failed because of an unknown error, exception +// or failure. +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/UpdateRoleDescription +func (c *IAM) UpdateRoleDescription(input *UpdateRoleDescriptionInput) (*UpdateRoleDescriptionOutput, error) { + req, out := c.UpdateRoleDescriptionRequest(input) + return out, req.Send() +} + +// UpdateRoleDescriptionWithContext is the same as UpdateRoleDescription with the addition of +// the ability to pass a context and additional request options. +// +// See UpdateRoleDescription 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 *IAM) UpdateRoleDescriptionWithContext(ctx aws.Context, input *UpdateRoleDescriptionInput, opts ...request.Option) (*UpdateRoleDescriptionOutput, error) { + req, out := c.UpdateRoleDescriptionRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opUpdateSAMLProvider = "UpdateSAMLProvider" @@ -9831,8 +12366,23 @@ func (c *IAM) UpdateSAMLProviderRequest(input *UpdateSAMLProviderInput) (req *re // Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/UpdateSAMLProvider func (c *IAM) UpdateSAMLProvider(input *UpdateSAMLProviderInput) (*UpdateSAMLProviderOutput, error) { req, out := c.UpdateSAMLProviderRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// UpdateSAMLProviderWithContext is the same as UpdateSAMLProvider with the addition of +// the ability to pass a context and additional request options. +// +// See UpdateSAMLProvider 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 *IAM) UpdateSAMLProviderWithContext(ctx aws.Context, input *UpdateSAMLProviderInput, opts ...request.Option) (*UpdateSAMLProviderOutput, error) { + req, out := c.UpdateSAMLProviderRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opUpdateSSHPublicKey = "UpdateSSHPublicKey" @@ -9908,8 +12458,23 @@ func (c *IAM) UpdateSSHPublicKeyRequest(input *UpdateSSHPublicKeyInput) (req *re // Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/UpdateSSHPublicKey func (c *IAM) UpdateSSHPublicKey(input *UpdateSSHPublicKeyInput) (*UpdateSSHPublicKeyOutput, error) { req, out := c.UpdateSSHPublicKeyRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// UpdateSSHPublicKeyWithContext is the same as UpdateSSHPublicKey with the addition of +// the ability to pass a context and additional request options. +// +// See UpdateSSHPublicKey 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 *IAM) UpdateSSHPublicKeyWithContext(ctx aws.Context, input *UpdateSSHPublicKeyInput, opts ...request.Option) (*UpdateSSHPublicKeyOutput, error) { + req, out := c.UpdateSSHPublicKeyRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opUpdateServerCertificate = "UpdateServerCertificate" @@ -10006,8 +12571,23 @@ func (c *IAM) UpdateServerCertificateRequest(input *UpdateServerCertificateInput // Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/UpdateServerCertificate func (c *IAM) UpdateServerCertificate(input *UpdateServerCertificateInput) (*UpdateServerCertificateOutput, error) { req, out := c.UpdateServerCertificateRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// UpdateServerCertificateWithContext is the same as UpdateServerCertificate with the addition of +// the ability to pass a context and additional request options. +// +// See UpdateServerCertificate 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 *IAM) UpdateServerCertificateWithContext(ctx aws.Context, input *UpdateServerCertificateInput, opts ...request.Option) (*UpdateServerCertificateOutput, error) { + req, out := c.UpdateServerCertificateRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opUpdateServiceSpecificCredential = "UpdateServiceSpecificCredential" @@ -10077,8 +12657,23 @@ func (c *IAM) UpdateServiceSpecificCredentialRequest(input *UpdateServiceSpecifi // Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/UpdateServiceSpecificCredential func (c *IAM) UpdateServiceSpecificCredential(input *UpdateServiceSpecificCredentialInput) (*UpdateServiceSpecificCredentialOutput, error) { req, out := c.UpdateServiceSpecificCredentialRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// UpdateServiceSpecificCredentialWithContext is the same as UpdateServiceSpecificCredential with the addition of +// the ability to pass a context and additional request options. +// +// See UpdateServiceSpecificCredential 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 *IAM) UpdateServiceSpecificCredentialWithContext(ctx aws.Context, input *UpdateServiceSpecificCredentialInput, opts ...request.Option) (*UpdateServiceSpecificCredentialOutput, error) { + req, out := c.UpdateServiceSpecificCredentialRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opUpdateSigningCertificate = "UpdateSigningCertificate" @@ -10160,8 +12755,23 @@ func (c *IAM) UpdateSigningCertificateRequest(input *UpdateSigningCertificateInp // Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/UpdateSigningCertificate func (c *IAM) UpdateSigningCertificate(input *UpdateSigningCertificateInput) (*UpdateSigningCertificateOutput, error) { req, out := c.UpdateSigningCertificateRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// UpdateSigningCertificateWithContext is the same as UpdateSigningCertificate with the addition of +// the ability to pass a context and additional request options. +// +// See UpdateSigningCertificate 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 *IAM) UpdateSigningCertificateWithContext(ctx aws.Context, input *UpdateSigningCertificateInput, opts ...request.Option) (*UpdateSigningCertificateOutput, error) { + req, out := c.UpdateSigningCertificateRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opUpdateUser = "UpdateUser" @@ -10257,8 +12867,23 @@ func (c *IAM) UpdateUserRequest(input *UpdateUserInput) (req *request.Request, o // Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/UpdateUser func (c *IAM) UpdateUser(input *UpdateUserInput) (*UpdateUserOutput, error) { req, out := c.UpdateUserRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// UpdateUserWithContext is the same as UpdateUser with the addition of +// the ability to pass a context and additional request options. +// +// See UpdateUser 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 *IAM) UpdateUserWithContext(ctx aws.Context, input *UpdateUserInput, opts ...request.Option) (*UpdateUserOutput, error) { + req, out := c.UpdateUserRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opUploadSSHPublicKey = "UploadSSHPublicKey" @@ -10345,8 +12970,23 @@ func (c *IAM) UploadSSHPublicKeyRequest(input *UploadSSHPublicKeyInput) (req *re // Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/UploadSSHPublicKey func (c *IAM) UploadSSHPublicKey(input *UploadSSHPublicKeyInput) (*UploadSSHPublicKeyOutput, error) { req, out := c.UploadSSHPublicKeyRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// UploadSSHPublicKeyWithContext is the same as UploadSSHPublicKey with the addition of +// the ability to pass a context and additional request options. +// +// See UploadSSHPublicKey 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 *IAM) UploadSSHPublicKeyWithContext(ctx aws.Context, input *UploadSSHPublicKeyInput, opts ...request.Option) (*UploadSSHPublicKeyOutput, error) { + req, out := c.UploadSSHPublicKeyRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opUploadServerCertificate = "UploadServerCertificate" @@ -10452,8 +13092,23 @@ func (c *IAM) UploadServerCertificateRequest(input *UploadServerCertificateInput // Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/UploadServerCertificate func (c *IAM) UploadServerCertificate(input *UploadServerCertificateInput) (*UploadServerCertificateOutput, error) { req, out := c.UploadServerCertificateRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// UploadServerCertificateWithContext is the same as UploadServerCertificate with the addition of +// the ability to pass a context and additional request options. +// +// See UploadServerCertificate 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 *IAM) UploadServerCertificateWithContext(ctx aws.Context, input *UploadServerCertificateInput, opts ...request.Option) (*UploadServerCertificateOutput, error) { + req, out := c.UploadServerCertificateRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opUploadSigningCertificate = "UploadSigningCertificate" @@ -10557,8 +13212,23 @@ func (c *IAM) UploadSigningCertificateRequest(input *UploadSigningCertificateInp // Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/UploadSigningCertificate func (c *IAM) UploadSigningCertificate(input *UploadSigningCertificateInput) (*UploadSigningCertificateOutput, error) { req, out := c.UploadSigningCertificateRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// UploadSigningCertificateWithContext is the same as UploadSigningCertificate with the addition of +// the ability to pass a context and additional request options. +// +// See UploadSigningCertificate 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 *IAM) UploadSigningCertificateWithContext(ctx aws.Context, input *UploadSigningCertificateInput, opts ...request.Option) (*UploadSigningCertificateOutput, error) { + req, out := c.UploadSigningCertificateRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // Contains information about an AWS access key. @@ -10661,7 +13331,7 @@ type AccessKeyLastUsed struct { LastUsedDate *time.Time `type:"timestamp" timestampFormat:"iso8601" required:"true"` // The AWS region where this access key was most recently used. This field is - // null when: + // displays "N/A" when: // // * The user does not have an access key. // @@ -10677,7 +13347,7 @@ type AccessKeyLastUsed struct { Region *string `type:"string" required:"true"` // The name of the AWS service with which this access key was most recently - // used. This field is null when: + // used. This field displays "N/A" when: // // * The user does not have an access key. // @@ -10867,7 +13537,7 @@ type AddRoleToInstanceProfileInput struct { // // This parameter allows (per its regex pattern (http://wikipedia.org/wiki/regex)) // a string of characters consisting of upper and lowercase alphanumeric characters - // with no spaces. You can also include any of the following characters: =,.@- + // with no spaces. You can also include any of the following characters: _+=,.@- // // RoleName is a required field RoleName *string `min:"1" type:"string" required:"true"` @@ -11113,7 +13783,7 @@ type AttachRolePolicyInput struct { // // This parameter allows (per its regex pattern (http://wikipedia.org/wiki/regex)) // a string of characters consisting of upper and lowercase alphanumeric characters - // with no spaces. You can also include any of the following characters: =,.@- + // with no spaces. You can also include any of the following characters: _+=,.@- // // RoleName is a required field RoleName *string `min:"1" type:"string" required:"true"` @@ -12280,6 +14950,9 @@ type CreateRoleInput struct { // AssumeRolePolicyDocument is a required field AssumeRolePolicyDocument *string `min:"1" type:"string" required:"true"` + // A customer-provided description of the role. + Description *string `type:"string"` + // The path to the role. For more information about paths, see IAM Identifiers // (http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html) // in the IAM User Guide. @@ -12298,7 +14971,8 @@ type CreateRoleInput struct { // // This parameter allows (per its regex pattern (http://wikipedia.org/wiki/regex)) // a string of characters consisting of upper and lowercase alphanumeric characters - // with no spaces. You can also include any of the following characters: =,.@-. + // with no spaces. You can also include any of the following characters: _+=,.@- + // // Role names are not distinguished by case. For example, you cannot create // roles named both "PRODROLE" and "prodrole". // @@ -12347,6 +15021,12 @@ func (s *CreateRoleInput) SetAssumeRolePolicyDocument(v string) *CreateRoleInput return s } +// SetDescription sets the Description field's value. +func (s *CreateRoleInput) SetDescription(v string) *CreateRoleInput { + s.Description = &v + return s +} + // SetPath sets the Path field's value. func (s *CreateRoleInput) SetPath(v string) *CreateRoleInput { s.Path = &v @@ -12481,6 +15161,98 @@ func (s *CreateSAMLProviderOutput) SetSAMLProviderArn(v string) *CreateSAMLProvi return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/CreateServiceLinkedRoleRequest +type CreateServiceLinkedRoleInput struct { + _ struct{} `type:"structure"` + + // The AWS service to which this role is attached. You use a string similar + // to a URL but without the http:// in front. For example: elasticbeanstalk.amazonaws.com + // + // AWSServiceName is a required field + AWSServiceName *string `min:"1" type:"string" required:"true"` + + // A string that you provide, which is combined with the service name to form + // the complete role name. If you make multiple requests for the same service, + // then you must supply a different CustomSuffix for each request. Otherwise + // the request fails with a duplicate role name error. For example, you could + // add -1 or -debug to the suffix. + CustomSuffix *string `min:"1" type:"string"` + + // The description of the role. + Description *string `type:"string"` +} + +// String returns the string representation +func (s CreateServiceLinkedRoleInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s CreateServiceLinkedRoleInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *CreateServiceLinkedRoleInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "CreateServiceLinkedRoleInput"} + if s.AWSServiceName == nil { + invalidParams.Add(request.NewErrParamRequired("AWSServiceName")) + } + if s.AWSServiceName != nil && len(*s.AWSServiceName) < 1 { + invalidParams.Add(request.NewErrParamMinLen("AWSServiceName", 1)) + } + if s.CustomSuffix != nil && len(*s.CustomSuffix) < 1 { + invalidParams.Add(request.NewErrParamMinLen("CustomSuffix", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetAWSServiceName sets the AWSServiceName field's value. +func (s *CreateServiceLinkedRoleInput) SetAWSServiceName(v string) *CreateServiceLinkedRoleInput { + s.AWSServiceName = &v + return s +} + +// SetCustomSuffix sets the CustomSuffix field's value. +func (s *CreateServiceLinkedRoleInput) SetCustomSuffix(v string) *CreateServiceLinkedRoleInput { + s.CustomSuffix = &v + return s +} + +// SetDescription sets the Description field's value. +func (s *CreateServiceLinkedRoleInput) SetDescription(v string) *CreateServiceLinkedRoleInput { + s.Description = &v + return s +} + +// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/CreateServiceLinkedRoleResponse +type CreateServiceLinkedRoleOutput struct { + _ struct{} `type:"structure"` + + // A Role object that contains details about the newly created role. + Role *Role `type:"structure"` +} + +// String returns the string representation +func (s CreateServiceLinkedRoleOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s CreateServiceLinkedRoleOutput) GoString() string { + return s.String() +} + +// SetRole sets the Role field's value. +func (s *CreateServiceLinkedRoleOutput) SetRole(v *Role) *CreateServiceLinkedRoleOutput { + s.Role = v + return s +} + // Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/CreateServiceSpecificCredentialRequest type CreateServiceSpecificCredentialInput struct { _ struct{} `type:"structure"` @@ -12776,7 +15548,7 @@ type DeactivateMFADeviceInput struct { // // This parameter allows (per its regex pattern (http://wikipedia.org/wiki/regex)) // a string of characters consisting of upper and lowercase alphanumeric characters - // with no spaces. You can also include any of the following characters: =/:,.@- + // with no spaces. You can also include any of the following characters: =,.@:/- // // SerialNumber is a required field SerialNumber *string `min:"9" type:"string" required:"true"` @@ -13499,7 +16271,7 @@ type DeleteRoleInput struct { // // This parameter allows (per its regex pattern (http://wikipedia.org/wiki/regex)) // a string of characters consisting of upper and lowercase alphanumeric characters - // with no spaces. You can also include any of the following characters: =,.@- + // with no spaces. You can also include any of the following characters: _+=,.@- // // RoleName is a required field RoleName *string `min:"1" type:"string" required:"true"` @@ -13570,7 +16342,7 @@ type DeleteRolePolicyInput struct { // // This parameter allows (per its regex pattern (http://wikipedia.org/wiki/regex)) // a string of characters consisting of upper and lowercase alphanumeric characters - // with no spaces. You can also include any of the following characters: =,.@- + // with no spaces. You can also include any of the following characters: _+=,.@- // // RoleName is a required field RoleName *string `min:"1" type:"string" required:"true"` @@ -14145,7 +16917,7 @@ type DeleteVirtualMFADeviceInput struct { // // This parameter allows (per its regex pattern (http://wikipedia.org/wiki/regex)) // a string of characters consisting of upper and lowercase alphanumeric characters - // with no spaces. You can also include any of the following characters: =/:,.@- + // with no spaces. You can also include any of the following characters: =,.@:/- // // SerialNumber is a required field SerialNumber *string `min:"9" type:"string" required:"true"` @@ -14297,7 +17069,7 @@ type DetachRolePolicyInput struct { // // This parameter allows (per its regex pattern (http://wikipedia.org/wiki/regex)) // a string of characters consisting of upper and lowercase alphanumeric characters - // with no spaces. You can also include any of the following characters: =,.@- + // with no spaces. You can also include any of the following characters: _+=,.@- // // RoleName is a required field RoleName *string `min:"1" type:"string" required:"true"` @@ -14452,6 +17224,13 @@ type EnableMFADeviceInput struct { // // The format for this parameter is a string of 6 digits. // + // Submit your request immediately after generating the authentication codes. + // If you generate the codes and then wait too long to submit the request, the + // MFA device successfully associates with the user but the MFA device becomes + // out of sync. This happens because time-based one-time passwords (TOTP) expire + // after a short period of time. If this happens, you can resync the device + // (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_mfa_sync.html). + // // AuthenticationCode1 is a required field AuthenticationCode1 *string `min:"6" type:"string" required:"true"` @@ -14459,6 +17238,13 @@ type EnableMFADeviceInput struct { // // The format for this parameter is a string of 6 digits. // + // Submit your request immediately after generating the authentication codes. + // If you generate the codes and then wait too long to submit the request, the + // MFA device successfully associates with the user but the MFA device becomes + // out of sync. This happens because time-based one-time passwords (TOTP) expire + // after a short period of time. If this happens, you can resync the device + // (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_mfa_sync.html). + // // AuthenticationCode2 is a required field AuthenticationCode2 *string `min:"6" type:"string" required:"true"` @@ -14467,7 +17253,7 @@ type EnableMFADeviceInput struct { // // This parameter allows (per its regex pattern (http://wikipedia.org/wiki/regex)) // a string of characters consisting of upper and lowercase alphanumeric characters - // with no spaces. You can also include any of the following characters: =/:,.@- + // with no spaces. You can also include any of the following characters: =,.@:/- // // SerialNumber is a required field SerialNumber *string `min:"9" type:"string" required:"true"` @@ -14980,7 +17766,7 @@ func (s GetAccountPasswordPolicyInput) GoString() string { type GetAccountPasswordPolicyOutput struct { _ struct{} `type:"structure"` - // Contains information about the account password policy. + // A structure that contains details about the account's password policy. // // PasswordPolicy is a required field PasswordPolicy *PasswordPolicy `type:"structure" required:"true"` @@ -15927,7 +18713,7 @@ type GetRoleInput struct { // // This parameter allows (per its regex pattern (http://wikipedia.org/wiki/regex)) // a string of characters consisting of upper and lowercase alphanumeric characters - // with no spaces. You can also include any of the following characters: =,.@- + // with no spaces. You can also include any of the following characters: _+=,.@- // // RoleName is a required field RoleName *string `min:"1" type:"string" required:"true"` @@ -16009,7 +18795,7 @@ type GetRolePolicyInput struct { // // This parameter allows (per its regex pattern (http://wikipedia.org/wiki/regex)) // a string of characters consisting of upper and lowercase alphanumeric characters - // with no spaces. You can also include any of the following characters: =,.@- + // with no spaces. You can also include any of the following characters: _+=,.@- // // RoleName is a required field RoleName *string `min:"1" type:"string" required:"true"` @@ -17261,7 +20047,7 @@ type ListAttachedRolePoliciesInput struct { // // This parameter allows (per its regex pattern (http://wikipedia.org/wiki/regex)) // a string of characters consisting of upper and lowercase alphanumeric characters - // with no spaces. You can also include any of the following characters: =,.@- + // with no spaces. You can also include any of the following characters: _+=,.@- // // RoleName is a required field RoleName *string `min:"1" type:"string" required:"true"` @@ -18119,7 +20905,7 @@ type ListInstanceProfilesForRoleInput struct { // // This parameter allows (per its regex pattern (http://wikipedia.org/wiki/regex)) // a string of characters consisting of upper and lowercase alphanumeric characters - // with no spaces. You can also include any of the following characters: =,.@- + // with no spaces. You can also include any of the following characters: _+=,.@- // // RoleName is a required field RoleName *string `min:"1" type:"string" required:"true"` @@ -18836,7 +21622,7 @@ type ListRolePoliciesInput struct { // // This parameter allows (per its regex pattern (http://wikipedia.org/wiki/regex)) // a string of characters consisting of upper and lowercase alphanumeric characters - // with no spaces. You can also include any of the following characters: =,.@- + // with no spaces. You can also include any of the following characters: _+=,.@- // // RoleName is a required field RoleName *string `min:"1" type:"string" required:"true"` @@ -20922,7 +23708,7 @@ type PutRolePolicyInput struct { // // This parameter allows (per its regex pattern (http://wikipedia.org/wiki/regex)) // a string of characters consisting of upper and lowercase alphanumeric characters - // with no spaces. You can also include any of the following characters: =,.@- + // with no spaces. You can also include any of the following characters: _+=,.@- // // RoleName is a required field RoleName *string `min:"1" type:"string" required:"true"` @@ -21203,7 +23989,7 @@ type RemoveRoleFromInstanceProfileInput struct { // // This parameter allows (per its regex pattern (http://wikipedia.org/wiki/regex)) // a string of characters consisting of upper and lowercase alphanumeric characters - // with no spaces. You can also include any of the following characters: =,.@- + // with no spaces. You can also include any of the following characters: _+=,.@- // // RoleName is a required field RoleName *string `min:"1" type:"string" required:"true"` @@ -21646,22 +24432,15 @@ func (s ResyncMFADeviceOutput) GoString() string { return s.String() } -// Contains information about an IAM role. -// -// This data type is used as a response element in the following actions: -// -// * CreateRole -// -// * GetRole -// -// * ListRoles +// Contains information about an IAM role. This structure is returned as a response +// element in several APIs that interact with roles. // Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/Role type Role struct { _ struct{} `type:"structure"` // The Amazon Resource Name (ARN) specifying the role. For more information // about ARNs and how to use them in policies, see IAM Identifiers (http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html) - // in the Using IAM guide. + // in the IAM User Guide guide. // // Arn is a required field Arn *string `min:"20" type:"string" required:"true"` @@ -21675,6 +24454,9 @@ type Role struct { // CreateDate is a required field CreateDate *time.Time `type:"timestamp" timestampFormat:"iso8601" required:"true"` + // A description of the role that you provide. + Description *string `type:"string"` + // The path to the role. For more information about paths, see IAM Identifiers // (http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html) // in the Using IAM guide. @@ -21723,6 +24505,12 @@ func (s *Role) SetCreateDate(v time.Time) *Role { return s } +// SetDescription sets the Description field's value. +func (s *Role) SetDescription(v string) *Role { + s.Description = &v + return s +} + // SetPath sets the Path field's value. func (s *Role) SetPath(v string) *Role { s.Path = &v @@ -23435,7 +26223,7 @@ type UpdateAssumeRolePolicyInput struct { // // This parameter allows (per its regex pattern (http://wikipedia.org/wiki/regex)) // a string of characters consisting of upper and lowercase alphanumeric characters - // with no spaces. You can also include any of the following characters: =,.@- + // with no spaces. You can also include any of the following characters: _+=,.@- // // RoleName is a required field RoleName *string `min:"1" type:"string" required:"true"` @@ -23766,6 +26554,86 @@ func (s UpdateOpenIDConnectProviderThumbprintOutput) GoString() string { return s.String() } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/UpdateRoleDescriptionRequest +type UpdateRoleDescriptionInput struct { + _ struct{} `type:"structure"` + + // The new description that you want to apply to the specified role. + // + // Description is a required field + Description *string `type:"string" required:"true"` + + // The name of the role that you want to modify. + // + // RoleName is a required field + RoleName *string `min:"1" type:"string" required:"true"` +} + +// String returns the string representation +func (s UpdateRoleDescriptionInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s UpdateRoleDescriptionInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *UpdateRoleDescriptionInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "UpdateRoleDescriptionInput"} + if s.Description == nil { + invalidParams.Add(request.NewErrParamRequired("Description")) + } + if s.RoleName == nil { + invalidParams.Add(request.NewErrParamRequired("RoleName")) + } + if s.RoleName != nil && len(*s.RoleName) < 1 { + invalidParams.Add(request.NewErrParamMinLen("RoleName", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetDescription sets the Description field's value. +func (s *UpdateRoleDescriptionInput) SetDescription(v string) *UpdateRoleDescriptionInput { + s.Description = &v + return s +} + +// SetRoleName sets the RoleName field's value. +func (s *UpdateRoleDescriptionInput) SetRoleName(v string) *UpdateRoleDescriptionInput { + s.RoleName = &v + return s +} + +// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/UpdateRoleDescriptionResponse +type UpdateRoleDescriptionOutput struct { + _ struct{} `type:"structure"` + + // A structure that contains details about the modified role. + Role *Role `type:"structure"` +} + +// String returns the string representation +func (s UpdateRoleDescriptionOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s UpdateRoleDescriptionOutput) GoString() string { + return s.String() +} + +// SetRole sets the Role field's value. +func (s *UpdateRoleDescriptionOutput) SetRole(v *Role) *UpdateRoleDescriptionOutput { + s.Role = v + return s +} + // Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/UpdateSAMLProviderRequest type UpdateSAMLProviderInput struct { _ struct{} `type:"structure"` @@ -24931,7 +27799,7 @@ type VirtualMFADevice struct { // SerialNumber is a required field SerialNumber *string `min:"9" type:"string" required:"true"` - // The user to whom the MFA device is assigned. + // The IAM user associated with this virtual MFA device. User *User `type:"structure"` } 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 new file mode 100644 index 000000000..0f70af3b5 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/service/iam/doc.go @@ -0,0 +1,132 @@ +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. + +// 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 (http://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 (http://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 (http://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 (http://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 (http://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 (http://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. +// +// See https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08 for more information on this service. +// +// See iam package documentation for more information. +// https://docs.aws.amazon.com/sdk-for-go/api/service/iam/ +// +// Using the Client +// +// To use the client for AWS Identity and Access Management you will first need +// to create a new instance of it. +// +// When creating a client for an AWS service you'll first need to have a Session +// already created. The Session provides configuration that can be shared +// between multiple service clients. Additional configuration can be applied to +// the Session and service's client when they are constructed. The aws package's +// Config type contains several fields such as Region for the AWS Region the +// client should make API requests too. The optional Config value can be provided +// as the variadic argument for Sessions and client creation. +// +// Once the service's client is created you can use it to make API requests the +// AWS service. These clients are safe to use concurrently. +// +// // Create a session to share configuration, and load external configuration. +// sess := session.Must(session.NewSession()) +// +// // Create the service's client with the session. +// svc := iam.New(sess) +// +// See the SDK's documentation for more information on how to use service clients. +// https://docs.aws.amazon.com/sdk-for-go/api/ +// +// See aws package's Config type for more information on configuration options. +// https://docs.aws.amazon.com/sdk-for-go/api/aws/#Config +// +// See the AWS Identity and Access Management client IAM for more +// information on creating the service's client. +// https://docs.aws.amazon.com/sdk-for-go/api/service/iam/#New +// +// Once the client is created you can make an API request to the service. +// Each API method takes a input parameter, and returns the service response +// and an error. +// +// The API method will document which error codes the service can be returned +// by the operation if the service models the API operation's errors. These +// errors will also be available as const strings prefixed with "ErrCode". +// +// result, err := svc.AddClientIDToOpenIDConnectProvider(params) +// if err != nil { +// // Cast err to awserr.Error to handle specific error codes. +// aerr, ok := err.(awserr.Error) +// if ok && aerr.Code() == { +// // Specific error code handling +// } +// return err +// } +// +// fmt.Println("AddClientIDToOpenIDConnectProvider result:") +// fmt.Println(result) +// +// Using the Client with Context +// +// The service's client also provides methods to make API requests with a Context +// value. This allows you to control the timeout, and cancellation of pending +// requests. These methods also take request Option as variadic parameter to apply +// additional configuration to the API request. +// +// ctx := context.Background() +// +// result, err := svc.AddClientIDToOpenIDConnectProviderWithContext(ctx, params) +// +// See the request package documentation for more information on using Context pattern +// with the SDK. +// https://docs.aws.amazon.com/sdk-for-go/api/aws/request/ +package iam 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 26c2534bf..97ad363c8 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 @@ -1,4 +1,4 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. package iam @@ -160,6 +160,15 @@ const ( // The specified service does not support service-specific credentials. ErrCodeServiceNotSupportedException = "NotSupportedService" + // ErrCodeUnmodifiableEntityException for service response error code + // "UnmodifiableEntity". + // + // The request was rejected because only the service that depends on the service-linked + // role can modify or delete the role on your behalf. The error message includes + // the name of the service that depends on this service-linked role. You must + // request the change through that service. + ErrCodeUnmodifiableEntityException = "UnmodifiableEntity" + // ErrCodeUnrecognizedPublicKeyEncodingException for service response error code // "UnrecognizedPublicKeyEncoding". // diff --git a/vendor/github.com/aws/aws-sdk-go/service/iam/service.go b/vendor/github.com/aws/aws-sdk-go/service/iam/service.go index 1942ec03e..4f798c63d 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/iam/service.go +++ b/vendor/github.com/aws/aws-sdk-go/service/iam/service.go @@ -1,4 +1,4 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. package iam @@ -11,62 +11,12 @@ import ( "github.com/aws/aws-sdk-go/private/protocol/query" ) -// 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 (http://docs.aws.amazon.com/IAM/latest/UserGuide/). +// IAM provides the API operation methods for making requests to +// AWS Identity and Access Management. See this package's package overview docs +// for details on the service. // -// 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 (http://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 (http://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 (http://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 (http://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 (http://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. -// The service client's operations are safe to be used concurrently. -// It is not safe to mutate any of the client's properties though. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08 +// IAM methods are safe to use concurrently. It is not safe to +// modify mutate any of the struct's properties though. type IAM struct { *client.Client } diff --git a/vendor/github.com/aws/aws-sdk-go/service/iam/waiters.go b/vendor/github.com/aws/aws-sdk-go/service/iam/waiters.go index 9231bf0bd..8bf5129cb 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/iam/waiters.go +++ b/vendor/github.com/aws/aws-sdk-go/service/iam/waiters.go @@ -1,9 +1,12 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. package iam import ( - "github.com/aws/aws-sdk-go/private/waiter" + "time" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/request" ) // WaitUntilInstanceProfileExists uses the IAM API operation @@ -11,32 +14,50 @@ import ( // If the condition is not meet within the max attempt window an error will // be returned. func (c *IAM) WaitUntilInstanceProfileExists(input *GetInstanceProfileInput) error { - waiterCfg := waiter.Config{ - Operation: "GetInstanceProfile", - Delay: 1, + return c.WaitUntilInstanceProfileExistsWithContext(aws.BackgroundContext(), input) +} + +// WaitUntilInstanceProfileExistsWithContext is an extended version of WaitUntilInstanceProfileExists. +// 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 *IAM) WaitUntilInstanceProfileExistsWithContext(ctx aws.Context, input *GetInstanceProfileInput, opts ...request.WaiterOption) error { + w := request.Waiter{ + Name: "WaitUntilInstanceProfileExists", MaxAttempts: 40, - Acceptors: []waiter.WaitAcceptor{ + Delay: request.ConstantWaiterDelay(1 * time.Second), + Acceptors: []request.WaiterAcceptor{ { - State: "success", - Matcher: "status", - Argument: "", + State: request.SuccessWaiterState, + Matcher: request.StatusWaiterMatch, Expected: 200, }, { - State: "retry", - Matcher: "status", - Argument: "", + State: request.RetryWaiterState, + Matcher: request.StatusWaiterMatch, Expected: 404, }, }, + Logger: c.Config.Logger, + NewRequest: func(opts []request.Option) (*request.Request, error) { + var inCpy *GetInstanceProfileInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.GetInstanceProfileRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, } + w.ApplyOptions(opts...) - w := waiter.Waiter{ - Client: c, - Input: input, - Config: waiterCfg, - } - return w.Wait() + return w.WaitWithContext(ctx) } // WaitUntilUserExists uses the IAM API operation @@ -44,30 +65,48 @@ func (c *IAM) WaitUntilInstanceProfileExists(input *GetInstanceProfileInput) err // If the condition is not meet within the max attempt window an error will // be returned. func (c *IAM) WaitUntilUserExists(input *GetUserInput) error { - waiterCfg := waiter.Config{ - Operation: "GetUser", - Delay: 1, + return c.WaitUntilUserExistsWithContext(aws.BackgroundContext(), input) +} + +// WaitUntilUserExistsWithContext is an extended version of WaitUntilUserExists. +// 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 *IAM) WaitUntilUserExistsWithContext(ctx aws.Context, input *GetUserInput, opts ...request.WaiterOption) error { + w := request.Waiter{ + Name: "WaitUntilUserExists", MaxAttempts: 20, - Acceptors: []waiter.WaitAcceptor{ + Delay: request.ConstantWaiterDelay(1 * time.Second), + Acceptors: []request.WaiterAcceptor{ { - State: "success", - Matcher: "status", - Argument: "", + State: request.SuccessWaiterState, + Matcher: request.StatusWaiterMatch, Expected: 200, }, { - State: "retry", - Matcher: "error", - Argument: "", + State: request.RetryWaiterState, + Matcher: request.ErrorWaiterMatch, Expected: "NoSuchEntity", }, }, + Logger: c.Config.Logger, + NewRequest: func(opts []request.Option) (*request.Request, error) { + var inCpy *GetUserInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.GetUserRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, } + w.ApplyOptions(opts...) - w := waiter.Waiter{ - Client: c, - Input: input, - Config: waiterCfg, - } - return w.Wait() + return w.WaitWithContext(ctx) } diff --git a/vendor/github.com/aws/aws-sdk-go/service/inspector/api.go b/vendor/github.com/aws/aws-sdk-go/service/inspector/api.go index a81c6b062..212961fb8 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/inspector/api.go +++ b/vendor/github.com/aws/aws-sdk-go/service/inspector/api.go @@ -1,12 +1,12 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. -// Package inspector provides a client for Amazon Inspector. package inspector import ( "fmt" "time" + "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awsutil" "github.com/aws/aws-sdk-go/aws/request" "github.com/aws/aws-sdk-go/private/protocol" @@ -86,8 +86,23 @@ func (c *Inspector) AddAttributesToFindingsRequest(input *AddAttributesToFinding // Please also see https://docs.aws.amazon.com/goto/WebAPI/inspector-2016-02-16/AddAttributesToFindings func (c *Inspector) AddAttributesToFindings(input *AddAttributesToFindingsInput) (*AddAttributesToFindingsOutput, error) { req, out := c.AddAttributesToFindingsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// AddAttributesToFindingsWithContext is the same as AddAttributesToFindings with the addition of +// the ability to pass a context and additional request options. +// +// See AddAttributesToFindings 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 *Inspector) AddAttributesToFindingsWithContext(ctx aws.Context, input *AddAttributesToFindingsInput, opts ...request.Option) (*AddAttributesToFindingsOutput, error) { + req, out := c.AddAttributesToFindingsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateAssessmentTarget = "CreateAssessmentTarget" @@ -169,8 +184,23 @@ func (c *Inspector) CreateAssessmentTargetRequest(input *CreateAssessmentTargetI // Please also see https://docs.aws.amazon.com/goto/WebAPI/inspector-2016-02-16/CreateAssessmentTarget func (c *Inspector) CreateAssessmentTarget(input *CreateAssessmentTargetInput) (*CreateAssessmentTargetOutput, error) { req, out := c.CreateAssessmentTargetRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateAssessmentTargetWithContext is the same as CreateAssessmentTarget with the addition of +// the ability to pass a context and additional request options. +// +// See CreateAssessmentTarget 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 *Inspector) CreateAssessmentTargetWithContext(ctx aws.Context, input *CreateAssessmentTargetInput, opts ...request.Option) (*CreateAssessmentTargetOutput, error) { + req, out := c.CreateAssessmentTargetRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateAssessmentTemplate = "CreateAssessmentTemplate" @@ -250,8 +280,23 @@ func (c *Inspector) CreateAssessmentTemplateRequest(input *CreateAssessmentTempl // Please also see https://docs.aws.amazon.com/goto/WebAPI/inspector-2016-02-16/CreateAssessmentTemplate func (c *Inspector) CreateAssessmentTemplate(input *CreateAssessmentTemplateInput) (*CreateAssessmentTemplateOutput, error) { req, out := c.CreateAssessmentTemplateRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateAssessmentTemplateWithContext is the same as CreateAssessmentTemplate with the addition of +// the ability to pass a context and additional request options. +// +// See CreateAssessmentTemplate 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 *Inspector) CreateAssessmentTemplateWithContext(ctx aws.Context, input *CreateAssessmentTemplateInput, opts ...request.Option) (*CreateAssessmentTemplateOutput, error) { + req, out := c.CreateAssessmentTemplateRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateResourceGroup = "CreateResourceGroup" @@ -329,8 +374,23 @@ func (c *Inspector) CreateResourceGroupRequest(input *CreateResourceGroupInput) // Please also see https://docs.aws.amazon.com/goto/WebAPI/inspector-2016-02-16/CreateResourceGroup func (c *Inspector) CreateResourceGroup(input *CreateResourceGroupInput) (*CreateResourceGroupOutput, error) { req, out := c.CreateResourceGroupRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateResourceGroupWithContext is the same as CreateResourceGroup with the addition of +// the ability to pass a context and additional request options. +// +// See CreateResourceGroup 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 *Inspector) CreateResourceGroupWithContext(ctx aws.Context, input *CreateResourceGroupInput, opts ...request.Option) (*CreateResourceGroupOutput, error) { + req, out := c.CreateResourceGroupRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteAssessmentRun = "DeleteAssessmentRun" @@ -412,8 +472,23 @@ func (c *Inspector) DeleteAssessmentRunRequest(input *DeleteAssessmentRunInput) // Please also see https://docs.aws.amazon.com/goto/WebAPI/inspector-2016-02-16/DeleteAssessmentRun func (c *Inspector) DeleteAssessmentRun(input *DeleteAssessmentRunInput) (*DeleteAssessmentRunOutput, error) { req, out := c.DeleteAssessmentRunRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteAssessmentRunWithContext is the same as DeleteAssessmentRun with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteAssessmentRun 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 *Inspector) DeleteAssessmentRunWithContext(ctx aws.Context, input *DeleteAssessmentRunInput, opts ...request.Option) (*DeleteAssessmentRunOutput, error) { + req, out := c.DeleteAssessmentRunRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteAssessmentTarget = "DeleteAssessmentTarget" @@ -495,8 +570,23 @@ func (c *Inspector) DeleteAssessmentTargetRequest(input *DeleteAssessmentTargetI // Please also see https://docs.aws.amazon.com/goto/WebAPI/inspector-2016-02-16/DeleteAssessmentTarget func (c *Inspector) DeleteAssessmentTarget(input *DeleteAssessmentTargetInput) (*DeleteAssessmentTargetOutput, error) { req, out := c.DeleteAssessmentTargetRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteAssessmentTargetWithContext is the same as DeleteAssessmentTarget with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteAssessmentTarget 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 *Inspector) DeleteAssessmentTargetWithContext(ctx aws.Context, input *DeleteAssessmentTargetInput, opts ...request.Option) (*DeleteAssessmentTargetOutput, error) { + req, out := c.DeleteAssessmentTargetRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteAssessmentTemplate = "DeleteAssessmentTemplate" @@ -578,8 +668,23 @@ func (c *Inspector) DeleteAssessmentTemplateRequest(input *DeleteAssessmentTempl // Please also see https://docs.aws.amazon.com/goto/WebAPI/inspector-2016-02-16/DeleteAssessmentTemplate func (c *Inspector) DeleteAssessmentTemplate(input *DeleteAssessmentTemplateInput) (*DeleteAssessmentTemplateOutput, error) { req, out := c.DeleteAssessmentTemplateRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteAssessmentTemplateWithContext is the same as DeleteAssessmentTemplate with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteAssessmentTemplate 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 *Inspector) DeleteAssessmentTemplateWithContext(ctx aws.Context, input *DeleteAssessmentTemplateInput, opts ...request.Option) (*DeleteAssessmentTemplateOutput, error) { + req, out := c.DeleteAssessmentTemplateRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeAssessmentRuns = "DescribeAssessmentRuns" @@ -648,8 +753,23 @@ func (c *Inspector) DescribeAssessmentRunsRequest(input *DescribeAssessmentRunsI // Please also see https://docs.aws.amazon.com/goto/WebAPI/inspector-2016-02-16/DescribeAssessmentRuns func (c *Inspector) DescribeAssessmentRuns(input *DescribeAssessmentRunsInput) (*DescribeAssessmentRunsOutput, error) { req, out := c.DescribeAssessmentRunsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeAssessmentRunsWithContext is the same as DescribeAssessmentRuns with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeAssessmentRuns 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 *Inspector) DescribeAssessmentRunsWithContext(ctx aws.Context, input *DescribeAssessmentRunsInput, opts ...request.Option) (*DescribeAssessmentRunsOutput, error) { + req, out := c.DescribeAssessmentRunsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeAssessmentTargets = "DescribeAssessmentTargets" @@ -718,8 +838,23 @@ func (c *Inspector) DescribeAssessmentTargetsRequest(input *DescribeAssessmentTa // Please also see https://docs.aws.amazon.com/goto/WebAPI/inspector-2016-02-16/DescribeAssessmentTargets func (c *Inspector) DescribeAssessmentTargets(input *DescribeAssessmentTargetsInput) (*DescribeAssessmentTargetsOutput, error) { req, out := c.DescribeAssessmentTargetsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeAssessmentTargetsWithContext is the same as DescribeAssessmentTargets with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeAssessmentTargets 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 *Inspector) DescribeAssessmentTargetsWithContext(ctx aws.Context, input *DescribeAssessmentTargetsInput, opts ...request.Option) (*DescribeAssessmentTargetsOutput, error) { + req, out := c.DescribeAssessmentTargetsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeAssessmentTemplates = "DescribeAssessmentTemplates" @@ -788,8 +923,23 @@ func (c *Inspector) DescribeAssessmentTemplatesRequest(input *DescribeAssessment // Please also see https://docs.aws.amazon.com/goto/WebAPI/inspector-2016-02-16/DescribeAssessmentTemplates func (c *Inspector) DescribeAssessmentTemplates(input *DescribeAssessmentTemplatesInput) (*DescribeAssessmentTemplatesOutput, error) { req, out := c.DescribeAssessmentTemplatesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeAssessmentTemplatesWithContext is the same as DescribeAssessmentTemplates with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeAssessmentTemplates 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 *Inspector) DescribeAssessmentTemplatesWithContext(ctx aws.Context, input *DescribeAssessmentTemplatesInput, opts ...request.Option) (*DescribeAssessmentTemplatesOutput, error) { + req, out := c.DescribeAssessmentTemplatesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeCrossAccountAccessRole = "DescribeCrossAccountAccessRole" @@ -853,8 +1003,23 @@ func (c *Inspector) DescribeCrossAccountAccessRoleRequest(input *DescribeCrossAc // Please also see https://docs.aws.amazon.com/goto/WebAPI/inspector-2016-02-16/DescribeCrossAccountAccessRole func (c *Inspector) DescribeCrossAccountAccessRole(input *DescribeCrossAccountAccessRoleInput) (*DescribeCrossAccountAccessRoleOutput, error) { req, out := c.DescribeCrossAccountAccessRoleRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeCrossAccountAccessRoleWithContext is the same as DescribeCrossAccountAccessRole with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeCrossAccountAccessRole 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 *Inspector) DescribeCrossAccountAccessRoleWithContext(ctx aws.Context, input *DescribeCrossAccountAccessRoleInput, opts ...request.Option) (*DescribeCrossAccountAccessRoleOutput, error) { + req, out := c.DescribeCrossAccountAccessRoleRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeFindings = "DescribeFindings" @@ -922,8 +1087,23 @@ func (c *Inspector) DescribeFindingsRequest(input *DescribeFindingsInput) (req * // Please also see https://docs.aws.amazon.com/goto/WebAPI/inspector-2016-02-16/DescribeFindings func (c *Inspector) DescribeFindings(input *DescribeFindingsInput) (*DescribeFindingsOutput, error) { req, out := c.DescribeFindingsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeFindingsWithContext is the same as DescribeFindings with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeFindings 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 *Inspector) DescribeFindingsWithContext(ctx aws.Context, input *DescribeFindingsInput, opts ...request.Option) (*DescribeFindingsOutput, error) { + req, out := c.DescribeFindingsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeResourceGroups = "DescribeResourceGroups" @@ -992,8 +1172,23 @@ func (c *Inspector) DescribeResourceGroupsRequest(input *DescribeResourceGroupsI // Please also see https://docs.aws.amazon.com/goto/WebAPI/inspector-2016-02-16/DescribeResourceGroups func (c *Inspector) DescribeResourceGroups(input *DescribeResourceGroupsInput) (*DescribeResourceGroupsOutput, error) { req, out := c.DescribeResourceGroupsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeResourceGroupsWithContext is the same as DescribeResourceGroups with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeResourceGroups 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 *Inspector) DescribeResourceGroupsWithContext(ctx aws.Context, input *DescribeResourceGroupsInput, opts ...request.Option) (*DescribeResourceGroupsOutput, error) { + req, out := c.DescribeResourceGroupsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeRulesPackages = "DescribeRulesPackages" @@ -1062,8 +1257,23 @@ func (c *Inspector) DescribeRulesPackagesRequest(input *DescribeRulesPackagesInp // Please also see https://docs.aws.amazon.com/goto/WebAPI/inspector-2016-02-16/DescribeRulesPackages func (c *Inspector) DescribeRulesPackages(input *DescribeRulesPackagesInput) (*DescribeRulesPackagesOutput, error) { req, out := c.DescribeRulesPackagesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeRulesPackagesWithContext is the same as DescribeRulesPackages with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeRulesPackages 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 *Inspector) DescribeRulesPackagesWithContext(ctx aws.Context, input *DescribeRulesPackagesInput, opts ...request.Option) (*DescribeRulesPackagesOutput, error) { + req, out := c.DescribeRulesPackagesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetTelemetryMetadata = "GetTelemetryMetadata" @@ -1139,8 +1349,23 @@ func (c *Inspector) GetTelemetryMetadataRequest(input *GetTelemetryMetadataInput // Please also see https://docs.aws.amazon.com/goto/WebAPI/inspector-2016-02-16/GetTelemetryMetadata func (c *Inspector) GetTelemetryMetadata(input *GetTelemetryMetadataInput) (*GetTelemetryMetadataOutput, error) { req, out := c.GetTelemetryMetadataRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetTelemetryMetadataWithContext is the same as GetTelemetryMetadata with the addition of +// the ability to pass a context and additional request options. +// +// See GetTelemetryMetadata 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 *Inspector) GetTelemetryMetadataWithContext(ctx aws.Context, input *GetTelemetryMetadataInput, opts ...request.Option) (*GetTelemetryMetadataOutput, error) { + req, out := c.GetTelemetryMetadataRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opListAssessmentRunAgents = "ListAssessmentRunAgents" @@ -1216,8 +1441,23 @@ func (c *Inspector) ListAssessmentRunAgentsRequest(input *ListAssessmentRunAgent // Please also see https://docs.aws.amazon.com/goto/WebAPI/inspector-2016-02-16/ListAssessmentRunAgents func (c *Inspector) ListAssessmentRunAgents(input *ListAssessmentRunAgentsInput) (*ListAssessmentRunAgentsOutput, error) { req, out := c.ListAssessmentRunAgentsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListAssessmentRunAgentsWithContext is the same as ListAssessmentRunAgents with the addition of +// the ability to pass a context and additional request options. +// +// See ListAssessmentRunAgents 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 *Inspector) ListAssessmentRunAgentsWithContext(ctx aws.Context, input *ListAssessmentRunAgentsInput, opts ...request.Option) (*ListAssessmentRunAgentsOutput, error) { + req, out := c.ListAssessmentRunAgentsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opListAssessmentRuns = "ListAssessmentRuns" @@ -1293,8 +1533,23 @@ func (c *Inspector) ListAssessmentRunsRequest(input *ListAssessmentRunsInput) (r // Please also see https://docs.aws.amazon.com/goto/WebAPI/inspector-2016-02-16/ListAssessmentRuns func (c *Inspector) ListAssessmentRuns(input *ListAssessmentRunsInput) (*ListAssessmentRunsOutput, error) { req, out := c.ListAssessmentRunsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListAssessmentRunsWithContext is the same as ListAssessmentRuns with the addition of +// the ability to pass a context and additional request options. +// +// See ListAssessmentRuns 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 *Inspector) ListAssessmentRunsWithContext(ctx aws.Context, input *ListAssessmentRunsInput, opts ...request.Option) (*ListAssessmentRunsOutput, error) { + req, out := c.ListAssessmentRunsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opListAssessmentTargets = "ListAssessmentTargets" @@ -1367,8 +1622,23 @@ func (c *Inspector) ListAssessmentTargetsRequest(input *ListAssessmentTargetsInp // Please also see https://docs.aws.amazon.com/goto/WebAPI/inspector-2016-02-16/ListAssessmentTargets func (c *Inspector) ListAssessmentTargets(input *ListAssessmentTargetsInput) (*ListAssessmentTargetsOutput, error) { req, out := c.ListAssessmentTargetsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListAssessmentTargetsWithContext is the same as ListAssessmentTargets with the addition of +// the ability to pass a context and additional request options. +// +// See ListAssessmentTargets 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 *Inspector) ListAssessmentTargetsWithContext(ctx aws.Context, input *ListAssessmentTargetsInput, opts ...request.Option) (*ListAssessmentTargetsOutput, error) { + req, out := c.ListAssessmentTargetsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opListAssessmentTemplates = "ListAssessmentTemplates" @@ -1444,8 +1714,23 @@ func (c *Inspector) ListAssessmentTemplatesRequest(input *ListAssessmentTemplate // Please also see https://docs.aws.amazon.com/goto/WebAPI/inspector-2016-02-16/ListAssessmentTemplates func (c *Inspector) ListAssessmentTemplates(input *ListAssessmentTemplatesInput) (*ListAssessmentTemplatesOutput, error) { req, out := c.ListAssessmentTemplatesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListAssessmentTemplatesWithContext is the same as ListAssessmentTemplates with the addition of +// the ability to pass a context and additional request options. +// +// See ListAssessmentTemplates 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 *Inspector) ListAssessmentTemplatesWithContext(ctx aws.Context, input *ListAssessmentTemplatesInput, opts ...request.Option) (*ListAssessmentTemplatesOutput, error) { + req, out := c.ListAssessmentTemplatesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opListEventSubscriptions = "ListEventSubscriptions" @@ -1522,8 +1807,23 @@ func (c *Inspector) ListEventSubscriptionsRequest(input *ListEventSubscriptionsI // Please also see https://docs.aws.amazon.com/goto/WebAPI/inspector-2016-02-16/ListEventSubscriptions func (c *Inspector) ListEventSubscriptions(input *ListEventSubscriptionsInput) (*ListEventSubscriptionsOutput, error) { req, out := c.ListEventSubscriptionsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListEventSubscriptionsWithContext is the same as ListEventSubscriptions with the addition of +// the ability to pass a context and additional request options. +// +// See ListEventSubscriptions 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 *Inspector) ListEventSubscriptionsWithContext(ctx aws.Context, input *ListEventSubscriptionsInput, opts ...request.Option) (*ListEventSubscriptionsOutput, error) { + req, out := c.ListEventSubscriptionsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opListFindings = "ListFindings" @@ -1599,8 +1899,23 @@ func (c *Inspector) ListFindingsRequest(input *ListFindingsInput) (req *request. // Please also see https://docs.aws.amazon.com/goto/WebAPI/inspector-2016-02-16/ListFindings func (c *Inspector) ListFindings(input *ListFindingsInput) (*ListFindingsOutput, error) { req, out := c.ListFindingsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListFindingsWithContext is the same as ListFindings with the addition of +// the ability to pass a context and additional request options. +// +// See ListFindings 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 *Inspector) ListFindingsWithContext(ctx aws.Context, input *ListFindingsInput, opts ...request.Option) (*ListFindingsOutput, error) { + req, out := c.ListFindingsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opListRulesPackages = "ListRulesPackages" @@ -1671,8 +1986,23 @@ func (c *Inspector) ListRulesPackagesRequest(input *ListRulesPackagesInput) (req // Please also see https://docs.aws.amazon.com/goto/WebAPI/inspector-2016-02-16/ListRulesPackages func (c *Inspector) ListRulesPackages(input *ListRulesPackagesInput) (*ListRulesPackagesOutput, error) { req, out := c.ListRulesPackagesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListRulesPackagesWithContext is the same as ListRulesPackages with the addition of +// the ability to pass a context and additional request options. +// +// See ListRulesPackages 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 *Inspector) ListRulesPackagesWithContext(ctx aws.Context, input *ListRulesPackagesInput, opts ...request.Option) (*ListRulesPackagesOutput, error) { + req, out := c.ListRulesPackagesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opListTagsForResource = "ListTagsForResource" @@ -1747,8 +2077,23 @@ func (c *Inspector) ListTagsForResourceRequest(input *ListTagsForResourceInput) // Please also see https://docs.aws.amazon.com/goto/WebAPI/inspector-2016-02-16/ListTagsForResource func (c *Inspector) ListTagsForResource(input *ListTagsForResourceInput) (*ListTagsForResourceOutput, error) { req, out := c.ListTagsForResourceRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListTagsForResourceWithContext is the same as ListTagsForResource with the addition of +// the ability to pass a context and additional request options. +// +// See ListTagsForResource 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 *Inspector) ListTagsForResourceWithContext(ctx aws.Context, input *ListTagsForResourceInput, opts ...request.Option) (*ListTagsForResourceOutput, error) { + req, out := c.ListTagsForResourceRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opPreviewAgents = "PreviewAgents" @@ -1828,8 +2173,23 @@ func (c *Inspector) PreviewAgentsRequest(input *PreviewAgentsInput) (req *reques // Please also see https://docs.aws.amazon.com/goto/WebAPI/inspector-2016-02-16/PreviewAgents func (c *Inspector) PreviewAgents(input *PreviewAgentsInput) (*PreviewAgentsOutput, error) { req, out := c.PreviewAgentsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// PreviewAgentsWithContext is the same as PreviewAgents with the addition of +// the ability to pass a context and additional request options. +// +// See PreviewAgents 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 *Inspector) PreviewAgentsWithContext(ctx aws.Context, input *PreviewAgentsInput, opts ...request.Option) (*PreviewAgentsOutput, error) { + req, out := c.PreviewAgentsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opRegisterCrossAccountAccessRole = "RegisterCrossAccountAccessRole" @@ -1907,8 +2267,23 @@ func (c *Inspector) RegisterCrossAccountAccessRoleRequest(input *RegisterCrossAc // Please also see https://docs.aws.amazon.com/goto/WebAPI/inspector-2016-02-16/RegisterCrossAccountAccessRole func (c *Inspector) RegisterCrossAccountAccessRole(input *RegisterCrossAccountAccessRoleInput) (*RegisterCrossAccountAccessRoleOutput, error) { req, out := c.RegisterCrossAccountAccessRoleRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// RegisterCrossAccountAccessRoleWithContext is the same as RegisterCrossAccountAccessRole with the addition of +// the ability to pass a context and additional request options. +// +// See RegisterCrossAccountAccessRole 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 *Inspector) RegisterCrossAccountAccessRoleWithContext(ctx aws.Context, input *RegisterCrossAccountAccessRoleInput, opts ...request.Option) (*RegisterCrossAccountAccessRoleOutput, error) { + req, out := c.RegisterCrossAccountAccessRoleRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opRemoveAttributesFromFindings = "RemoveAttributesFromFindings" @@ -1985,8 +2360,23 @@ func (c *Inspector) RemoveAttributesFromFindingsRequest(input *RemoveAttributesF // Please also see https://docs.aws.amazon.com/goto/WebAPI/inspector-2016-02-16/RemoveAttributesFromFindings func (c *Inspector) RemoveAttributesFromFindings(input *RemoveAttributesFromFindingsInput) (*RemoveAttributesFromFindingsOutput, error) { req, out := c.RemoveAttributesFromFindingsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// RemoveAttributesFromFindingsWithContext is the same as RemoveAttributesFromFindings with the addition of +// the ability to pass a context and additional request options. +// +// See RemoveAttributesFromFindings 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 *Inspector) RemoveAttributesFromFindingsWithContext(ctx aws.Context, input *RemoveAttributesFromFindingsInput, opts ...request.Option) (*RemoveAttributesFromFindingsOutput, error) { + req, out := c.RemoveAttributesFromFindingsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opSetTagsForResource = "SetTagsForResource" @@ -2064,8 +2454,23 @@ func (c *Inspector) SetTagsForResourceRequest(input *SetTagsForResourceInput) (r // Please also see https://docs.aws.amazon.com/goto/WebAPI/inspector-2016-02-16/SetTagsForResource func (c *Inspector) SetTagsForResource(input *SetTagsForResourceInput) (*SetTagsForResourceOutput, error) { req, out := c.SetTagsForResourceRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// SetTagsForResourceWithContext is the same as SetTagsForResource with the addition of +// the ability to pass a context and additional request options. +// +// See SetTagsForResource 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 *Inspector) SetTagsForResourceWithContext(ctx aws.Context, input *SetTagsForResourceInput, opts ...request.Option) (*SetTagsForResourceOutput, error) { + req, out := c.SetTagsForResourceRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opStartAssessmentRun = "StartAssessmentRun" @@ -2154,8 +2559,23 @@ func (c *Inspector) StartAssessmentRunRequest(input *StartAssessmentRunInput) (r // Please also see https://docs.aws.amazon.com/goto/WebAPI/inspector-2016-02-16/StartAssessmentRun func (c *Inspector) StartAssessmentRun(input *StartAssessmentRunInput) (*StartAssessmentRunOutput, error) { req, out := c.StartAssessmentRunRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// StartAssessmentRunWithContext is the same as StartAssessmentRun with the addition of +// the ability to pass a context and additional request options. +// +// See StartAssessmentRun 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 *Inspector) StartAssessmentRunWithContext(ctx aws.Context, input *StartAssessmentRunInput, opts ...request.Option) (*StartAssessmentRunOutput, error) { + req, out := c.StartAssessmentRunRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opStopAssessmentRun = "StopAssessmentRun" @@ -2232,8 +2652,23 @@ func (c *Inspector) StopAssessmentRunRequest(input *StopAssessmentRunInput) (req // Please also see https://docs.aws.amazon.com/goto/WebAPI/inspector-2016-02-16/StopAssessmentRun func (c *Inspector) StopAssessmentRun(input *StopAssessmentRunInput) (*StopAssessmentRunOutput, error) { req, out := c.StopAssessmentRunRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// StopAssessmentRunWithContext is the same as StopAssessmentRun with the addition of +// the ability to pass a context and additional request options. +// +// See StopAssessmentRun 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 *Inspector) StopAssessmentRunWithContext(ctx aws.Context, input *StopAssessmentRunInput, opts ...request.Option) (*StopAssessmentRunOutput, error) { + req, out := c.StopAssessmentRunRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opSubscribeToEvent = "SubscribeToEvent" @@ -2315,8 +2750,23 @@ func (c *Inspector) SubscribeToEventRequest(input *SubscribeToEventInput) (req * // Please also see https://docs.aws.amazon.com/goto/WebAPI/inspector-2016-02-16/SubscribeToEvent func (c *Inspector) SubscribeToEvent(input *SubscribeToEventInput) (*SubscribeToEventOutput, error) { req, out := c.SubscribeToEventRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// SubscribeToEventWithContext is the same as SubscribeToEvent with the addition of +// the ability to pass a context and additional request options. +// +// See SubscribeToEvent 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 *Inspector) SubscribeToEventWithContext(ctx aws.Context, input *SubscribeToEventInput, opts ...request.Option) (*SubscribeToEventOutput, error) { + req, out := c.SubscribeToEventRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opUnsubscribeFromEvent = "UnsubscribeFromEvent" @@ -2394,8 +2844,23 @@ func (c *Inspector) UnsubscribeFromEventRequest(input *UnsubscribeFromEventInput // Please also see https://docs.aws.amazon.com/goto/WebAPI/inspector-2016-02-16/UnsubscribeFromEvent func (c *Inspector) UnsubscribeFromEvent(input *UnsubscribeFromEventInput) (*UnsubscribeFromEventOutput, error) { req, out := c.UnsubscribeFromEventRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// UnsubscribeFromEventWithContext is the same as UnsubscribeFromEvent with the addition of +// the ability to pass a context and additional request options. +// +// See UnsubscribeFromEvent 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 *Inspector) UnsubscribeFromEventWithContext(ctx aws.Context, input *UnsubscribeFromEventInput, opts ...request.Option) (*UnsubscribeFromEventOutput, error) { + req, out := c.UnsubscribeFromEventRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opUpdateAssessmentTarget = "UpdateAssessmentTarget" @@ -2473,8 +2938,23 @@ func (c *Inspector) UpdateAssessmentTargetRequest(input *UpdateAssessmentTargetI // Please also see https://docs.aws.amazon.com/goto/WebAPI/inspector-2016-02-16/UpdateAssessmentTarget func (c *Inspector) UpdateAssessmentTarget(input *UpdateAssessmentTargetInput) (*UpdateAssessmentTargetOutput, error) { req, out := c.UpdateAssessmentTargetRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// UpdateAssessmentTargetWithContext is the same as UpdateAssessmentTarget with the addition of +// the ability to pass a context and additional request options. +// +// See UpdateAssessmentTarget 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 *Inspector) UpdateAssessmentTargetWithContext(ctx aws.Context, input *UpdateAssessmentTargetInput, opts ...request.Option) (*UpdateAssessmentTargetOutput, error) { + req, out := c.UpdateAssessmentTargetRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // Please also see https://docs.aws.amazon.com/goto/WebAPI/inspector-2016-02-16/AddAttributesToFindingsRequest diff --git a/vendor/github.com/aws/aws-sdk-go/service/inspector/doc.go b/vendor/github.com/aws/aws-sdk-go/service/inspector/doc.go new file mode 100644 index 000000000..1d83fc5ad --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/service/inspector/doc.go @@ -0,0 +1,82 @@ +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. + +// Package inspector provides the client and types for making API +// requests to Amazon Inspector. +// +// Amazon Inspector enables you to analyze the behavior of your AWS resources +// and to identify potential security issues. For more information, see Amazon +// Inspector User Guide (http://docs.aws.amazon.com/inspector/latest/userguide/inspector_introduction.html). +// +// See https://docs.aws.amazon.com/goto/WebAPI/inspector-2016-02-16 for more information on this service. +// +// See inspector package documentation for more information. +// https://docs.aws.amazon.com/sdk-for-go/api/service/inspector/ +// +// Using the Client +// +// To use the client for Amazon Inspector you will first need +// to create a new instance of it. +// +// When creating a client for an AWS service you'll first need to have a Session +// already created. The Session provides configuration that can be shared +// between multiple service clients. Additional configuration can be applied to +// the Session and service's client when they are constructed. The aws package's +// Config type contains several fields such as Region for the AWS Region the +// client should make API requests too. The optional Config value can be provided +// as the variadic argument for Sessions and client creation. +// +// Once the service's client is created you can use it to make API requests the +// AWS service. These clients are safe to use concurrently. +// +// // Create a session to share configuration, and load external configuration. +// sess := session.Must(session.NewSession()) +// +// // Create the service's client with the session. +// svc := inspector.New(sess) +// +// See the SDK's documentation for more information on how to use service clients. +// https://docs.aws.amazon.com/sdk-for-go/api/ +// +// See aws package's Config type for more information on configuration options. +// https://docs.aws.amazon.com/sdk-for-go/api/aws/#Config +// +// See the Amazon Inspector client Inspector for more +// information on creating the service's client. +// https://docs.aws.amazon.com/sdk-for-go/api/service/inspector/#New +// +// Once the client is created you can make an API request to the service. +// Each API method takes a input parameter, and returns the service response +// and an error. +// +// The API method will document which error codes the service can be returned +// by the operation if the service models the API operation's errors. These +// errors will also be available as const strings prefixed with "ErrCode". +// +// result, err := svc.AddAttributesToFindings(params) +// if err != nil { +// // Cast err to awserr.Error to handle specific error codes. +// aerr, ok := err.(awserr.Error) +// if ok && aerr.Code() == { +// // Specific error code handling +// } +// return err +// } +// +// fmt.Println("AddAttributesToFindings result:") +// fmt.Println(result) +// +// Using the Client with Context +// +// The service's client also provides methods to make API requests with a Context +// value. This allows you to control the timeout, and cancellation of pending +// requests. These methods also take request Option as variadic parameter to apply +// additional configuration to the API request. +// +// ctx := context.Background() +// +// result, err := svc.AddAttributesToFindingsWithContext(ctx, params) +// +// See the request package documentation for more information on using Context pattern +// with the SDK. +// https://docs.aws.amazon.com/sdk-for-go/api/aws/request/ +package inspector diff --git a/vendor/github.com/aws/aws-sdk-go/service/inspector/errors.go b/vendor/github.com/aws/aws-sdk-go/service/inspector/errors.go index e39853022..2178a76b2 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/inspector/errors.go +++ b/vendor/github.com/aws/aws-sdk-go/service/inspector/errors.go @@ -1,4 +1,4 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. package inspector diff --git a/vendor/github.com/aws/aws-sdk-go/service/inspector/service.go b/vendor/github.com/aws/aws-sdk-go/service/inspector/service.go index 3401a9c40..1d65f0707 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/inspector/service.go +++ b/vendor/github.com/aws/aws-sdk-go/service/inspector/service.go @@ -1,4 +1,4 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. package inspector @@ -11,12 +11,12 @@ import ( "github.com/aws/aws-sdk-go/private/protocol/jsonrpc" ) -// Amazon Inspector enables you to analyze the behavior of your AWS resources -// and to identify potential security issues. For more information, see Amazon -// Inspector User Guide (http://docs.aws.amazon.com/inspector/latest/userguide/inspector_introduction.html). -// The service client's operations are safe to be used concurrently. -// It is not safe to mutate any of the client's properties though. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/inspector-2016-02-16 +// Inspector provides the API operation methods for making requests to +// Amazon Inspector. See this package's package overview docs +// for details on the service. +// +// Inspector methods are safe to use concurrently. It is not safe to +// modify mutate any of the struct's properties though. type Inspector struct { *client.Client } diff --git a/vendor/github.com/aws/aws-sdk-go/service/kinesis/api.go b/vendor/github.com/aws/aws-sdk-go/service/kinesis/api.go index e36f23d22..0cf5f919d 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/kinesis/api.go +++ b/vendor/github.com/aws/aws-sdk-go/service/kinesis/api.go @@ -1,12 +1,12 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. -// Package kinesis provides a client for Amazon Kinesis. package kinesis import ( "fmt" "time" + "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awsutil" "github.com/aws/aws-sdk-go/aws/request" "github.com/aws/aws-sdk-go/private/protocol" @@ -93,8 +93,23 @@ func (c *Kinesis) AddTagsToStreamRequest(input *AddTagsToStreamInput) (req *requ // Please also see https://docs.aws.amazon.com/goto/WebAPI/kinesis-2013-12-02/AddTagsToStream func (c *Kinesis) AddTagsToStream(input *AddTagsToStreamInput) (*AddTagsToStreamOutput, error) { req, out := c.AddTagsToStreamRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// AddTagsToStreamWithContext is the same as AddTagsToStream with the addition of +// the ability to pass a context and additional request options. +// +// See AddTagsToStream 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 *Kinesis) AddTagsToStreamWithContext(ctx aws.Context, input *AddTagsToStreamInput, opts ...request.Option) (*AddTagsToStreamOutput, error) { + req, out := c.AddTagsToStreamRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateStream = "CreateStream" @@ -206,8 +221,23 @@ func (c *Kinesis) CreateStreamRequest(input *CreateStreamInput) (req *request.Re // Please also see https://docs.aws.amazon.com/goto/WebAPI/kinesis-2013-12-02/CreateStream func (c *Kinesis) CreateStream(input *CreateStreamInput) (*CreateStreamOutput, error) { req, out := c.CreateStreamRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateStreamWithContext is the same as CreateStream with the addition of +// the ability to pass a context and additional request options. +// +// See CreateStream 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 *Kinesis) CreateStreamWithContext(ctx aws.Context, input *CreateStreamInput, opts ...request.Option) (*CreateStreamOutput, error) { + req, out := c.CreateStreamRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDecreaseStreamRetentionPeriod = "DecreaseStreamRetentionPeriod" @@ -288,8 +318,23 @@ func (c *Kinesis) DecreaseStreamRetentionPeriodRequest(input *DecreaseStreamRete // Please also see https://docs.aws.amazon.com/goto/WebAPI/kinesis-2013-12-02/DecreaseStreamRetentionPeriod func (c *Kinesis) DecreaseStreamRetentionPeriod(input *DecreaseStreamRetentionPeriodInput) (*DecreaseStreamRetentionPeriodOutput, error) { req, out := c.DecreaseStreamRetentionPeriodRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DecreaseStreamRetentionPeriodWithContext is the same as DecreaseStreamRetentionPeriod with the addition of +// the ability to pass a context and additional request options. +// +// See DecreaseStreamRetentionPeriod 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 *Kinesis) DecreaseStreamRetentionPeriodWithContext(ctx aws.Context, input *DecreaseStreamRetentionPeriodInput, opts ...request.Option) (*DecreaseStreamRetentionPeriodOutput, error) { + req, out := c.DecreaseStreamRetentionPeriodRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteStream = "DeleteStream" @@ -379,8 +424,23 @@ func (c *Kinesis) DeleteStreamRequest(input *DeleteStreamInput) (req *request.Re // Please also see https://docs.aws.amazon.com/goto/WebAPI/kinesis-2013-12-02/DeleteStream func (c *Kinesis) DeleteStream(input *DeleteStreamInput) (*DeleteStreamOutput, error) { req, out := c.DeleteStreamRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteStreamWithContext is the same as DeleteStream with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteStream 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 *Kinesis) DeleteStreamWithContext(ctx aws.Context, input *DeleteStreamInput, opts ...request.Option) (*DeleteStreamOutput, error) { + req, out := c.DeleteStreamRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeLimits = "DescribeLimits" @@ -450,8 +510,23 @@ func (c *Kinesis) DescribeLimitsRequest(input *DescribeLimitsInput) (req *reques // Please also see https://docs.aws.amazon.com/goto/WebAPI/kinesis-2013-12-02/DescribeLimits func (c *Kinesis) DescribeLimits(input *DescribeLimitsInput) (*DescribeLimitsOutput, error) { req, out := c.DescribeLimitsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeLimitsWithContext is the same as DescribeLimits with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeLimits for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *Kinesis) DescribeLimitsWithContext(ctx aws.Context, input *DescribeLimitsInput, opts ...request.Option) (*DescribeLimitsOutput, error) { + req, out := c.DescribeLimitsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeStream = "DescribeStream" @@ -544,8 +619,23 @@ func (c *Kinesis) DescribeStreamRequest(input *DescribeStreamInput) (req *reques // Please also see https://docs.aws.amazon.com/goto/WebAPI/kinesis-2013-12-02/DescribeStream func (c *Kinesis) DescribeStream(input *DescribeStreamInput) (*DescribeStreamOutput, error) { req, out := c.DescribeStreamRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeStreamWithContext is the same as DescribeStream with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeStream 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 *Kinesis) DescribeStreamWithContext(ctx aws.Context, input *DescribeStreamInput, opts ...request.Option) (*DescribeStreamOutput, error) { + req, out := c.DescribeStreamRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // DescribeStreamPages iterates over the pages of a DescribeStream operation, @@ -565,12 +655,37 @@ func (c *Kinesis) DescribeStream(input *DescribeStreamInput) (*DescribeStreamOut // return pageNum <= 3 // }) // -func (c *Kinesis) DescribeStreamPages(input *DescribeStreamInput, fn func(p *DescribeStreamOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.DescribeStreamRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*DescribeStreamOutput), lastPage) - }) +func (c *Kinesis) DescribeStreamPages(input *DescribeStreamInput, fn func(*DescribeStreamOutput, bool) bool) error { + return c.DescribeStreamPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// DescribeStreamPagesWithContext same as DescribeStreamPages 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 *Kinesis) DescribeStreamPagesWithContext(ctx aws.Context, input *DescribeStreamInput, fn func(*DescribeStreamOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *DescribeStreamInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeStreamRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*DescribeStreamOutput), !p.HasNextPage()) + } + return p.Err() } const opDisableEnhancedMonitoring = "DisableEnhancedMonitoring" @@ -647,8 +762,23 @@ func (c *Kinesis) DisableEnhancedMonitoringRequest(input *DisableEnhancedMonitor // Please also see https://docs.aws.amazon.com/goto/WebAPI/kinesis-2013-12-02/DisableEnhancedMonitoring func (c *Kinesis) DisableEnhancedMonitoring(input *DisableEnhancedMonitoringInput) (*EnhancedMonitoringOutput, error) { req, out := c.DisableEnhancedMonitoringRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DisableEnhancedMonitoringWithContext is the same as DisableEnhancedMonitoring with the addition of +// the ability to pass a context and additional request options. +// +// See DisableEnhancedMonitoring 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 *Kinesis) DisableEnhancedMonitoringWithContext(ctx aws.Context, input *DisableEnhancedMonitoringInput, opts ...request.Option) (*EnhancedMonitoringOutput, error) { + req, out := c.DisableEnhancedMonitoringRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opEnableEnhancedMonitoring = "EnableEnhancedMonitoring" @@ -725,8 +855,23 @@ func (c *Kinesis) EnableEnhancedMonitoringRequest(input *EnableEnhancedMonitorin // Please also see https://docs.aws.amazon.com/goto/WebAPI/kinesis-2013-12-02/EnableEnhancedMonitoring func (c *Kinesis) EnableEnhancedMonitoring(input *EnableEnhancedMonitoringInput) (*EnhancedMonitoringOutput, error) { req, out := c.EnableEnhancedMonitoringRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// EnableEnhancedMonitoringWithContext is the same as EnableEnhancedMonitoring with the addition of +// the ability to pass a context and additional request options. +// +// See EnableEnhancedMonitoring 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 *Kinesis) EnableEnhancedMonitoringWithContext(ctx aws.Context, input *EnableEnhancedMonitoringInput, opts ...request.Option) (*EnhancedMonitoringOutput, error) { + req, out := c.EnableEnhancedMonitoringRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetRecords = "GetRecords" @@ -858,8 +1003,23 @@ func (c *Kinesis) GetRecordsRequest(input *GetRecordsInput) (req *request.Reques // Please also see https://docs.aws.amazon.com/goto/WebAPI/kinesis-2013-12-02/GetRecords func (c *Kinesis) GetRecords(input *GetRecordsInput) (*GetRecordsOutput, error) { req, out := c.GetRecordsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetRecordsWithContext is the same as GetRecords with the addition of +// the ability to pass a context and additional request options. +// +// See GetRecords 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 *Kinesis) GetRecordsWithContext(ctx aws.Context, input *GetRecordsInput, opts ...request.Option) (*GetRecordsOutput, error) { + req, out := c.GetRecordsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetShardIterator = "GetShardIterator" @@ -973,8 +1133,23 @@ func (c *Kinesis) GetShardIteratorRequest(input *GetShardIteratorInput) (req *re // Please also see https://docs.aws.amazon.com/goto/WebAPI/kinesis-2013-12-02/GetShardIterator func (c *Kinesis) GetShardIterator(input *GetShardIteratorInput) (*GetShardIteratorOutput, error) { req, out := c.GetShardIteratorRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetShardIteratorWithContext is the same as GetShardIterator with the addition of +// the ability to pass a context and additional request options. +// +// See GetShardIterator 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 *Kinesis) GetShardIteratorWithContext(ctx aws.Context, input *GetShardIteratorInput, opts ...request.Option) (*GetShardIteratorOutput, error) { + req, out := c.GetShardIteratorRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opIncreaseStreamRetentionPeriod = "IncreaseStreamRetentionPeriod" @@ -1059,8 +1234,23 @@ func (c *Kinesis) IncreaseStreamRetentionPeriodRequest(input *IncreaseStreamRete // Please also see https://docs.aws.amazon.com/goto/WebAPI/kinesis-2013-12-02/IncreaseStreamRetentionPeriod func (c *Kinesis) IncreaseStreamRetentionPeriod(input *IncreaseStreamRetentionPeriodInput) (*IncreaseStreamRetentionPeriodOutput, error) { req, out := c.IncreaseStreamRetentionPeriodRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// IncreaseStreamRetentionPeriodWithContext is the same as IncreaseStreamRetentionPeriod with the addition of +// the ability to pass a context and additional request options. +// +// See IncreaseStreamRetentionPeriod 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 *Kinesis) IncreaseStreamRetentionPeriodWithContext(ctx aws.Context, input *IncreaseStreamRetentionPeriodInput, opts ...request.Option) (*IncreaseStreamRetentionPeriodOutput, error) { + req, out := c.IncreaseStreamRetentionPeriodRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opListStreams = "ListStreams" @@ -1146,8 +1336,23 @@ func (c *Kinesis) ListStreamsRequest(input *ListStreamsInput) (req *request.Requ // Please also see https://docs.aws.amazon.com/goto/WebAPI/kinesis-2013-12-02/ListStreams func (c *Kinesis) ListStreams(input *ListStreamsInput) (*ListStreamsOutput, error) { req, out := c.ListStreamsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListStreamsWithContext is the same as ListStreams with the addition of +// the ability to pass a context and additional request options. +// +// See ListStreams 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 *Kinesis) ListStreamsWithContext(ctx aws.Context, input *ListStreamsInput, opts ...request.Option) (*ListStreamsOutput, error) { + req, out := c.ListStreamsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // ListStreamsPages iterates over the pages of a ListStreams operation, @@ -1167,12 +1372,37 @@ func (c *Kinesis) ListStreams(input *ListStreamsInput) (*ListStreamsOutput, erro // return pageNum <= 3 // }) // -func (c *Kinesis) ListStreamsPages(input *ListStreamsInput, fn func(p *ListStreamsOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.ListStreamsRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*ListStreamsOutput), lastPage) - }) +func (c *Kinesis) ListStreamsPages(input *ListStreamsInput, fn func(*ListStreamsOutput, bool) bool) error { + return c.ListStreamsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListStreamsPagesWithContext same as ListStreamsPages 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 *Kinesis) ListStreamsPagesWithContext(ctx aws.Context, input *ListStreamsInput, fn func(*ListStreamsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListStreamsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListStreamsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*ListStreamsOutput), !p.HasNextPage()) + } + return p.Err() } const opListTagsForStream = "ListTagsForStream" @@ -1245,8 +1475,23 @@ func (c *Kinesis) ListTagsForStreamRequest(input *ListTagsForStreamInput) (req * // Please also see https://docs.aws.amazon.com/goto/WebAPI/kinesis-2013-12-02/ListTagsForStream func (c *Kinesis) ListTagsForStream(input *ListTagsForStreamInput) (*ListTagsForStreamOutput, error) { req, out := c.ListTagsForStreamRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListTagsForStreamWithContext is the same as ListTagsForStream with the addition of +// the ability to pass a context and additional request options. +// +// See ListTagsForStream 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 *Kinesis) ListTagsForStreamWithContext(ctx aws.Context, input *ListTagsForStreamInput, opts ...request.Option) (*ListTagsForStreamOutput, error) { + req, out := c.ListTagsForStreamRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opMergeShards = "MergeShards" @@ -1360,8 +1605,23 @@ func (c *Kinesis) MergeShardsRequest(input *MergeShardsInput) (req *request.Requ // Please also see https://docs.aws.amazon.com/goto/WebAPI/kinesis-2013-12-02/MergeShards func (c *Kinesis) MergeShards(input *MergeShardsInput) (*MergeShardsOutput, error) { req, out := c.MergeShardsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// MergeShardsWithContext is the same as MergeShards with the addition of +// the ability to pass a context and additional request options. +// +// See MergeShards 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 *Kinesis) MergeShardsWithContext(ctx aws.Context, input *MergeShardsInput, opts ...request.Option) (*MergeShardsOutput, error) { + req, out := c.MergeShardsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opPutRecord = "PutRecord" @@ -1475,8 +1735,23 @@ func (c *Kinesis) PutRecordRequest(input *PutRecordInput) (req *request.Request, // Please also see https://docs.aws.amazon.com/goto/WebAPI/kinesis-2013-12-02/PutRecord func (c *Kinesis) PutRecord(input *PutRecordInput) (*PutRecordOutput, error) { req, out := c.PutRecordRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// PutRecordWithContext is the same as PutRecord with the addition of +// the ability to pass a context and additional request options. +// +// See PutRecord 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 *Kinesis) PutRecordWithContext(ctx aws.Context, input *PutRecordInput, opts ...request.Option) (*PutRecordOutput, error) { + req, out := c.PutRecordRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opPutRecords = "PutRecords" @@ -1612,8 +1887,23 @@ func (c *Kinesis) PutRecordsRequest(input *PutRecordsInput) (req *request.Reques // Please also see https://docs.aws.amazon.com/goto/WebAPI/kinesis-2013-12-02/PutRecords func (c *Kinesis) PutRecords(input *PutRecordsInput) (*PutRecordsOutput, error) { req, out := c.PutRecordsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// PutRecordsWithContext is the same as PutRecords with the addition of +// the ability to pass a context and additional request options. +// +// See PutRecords 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 *Kinesis) PutRecordsWithContext(ctx aws.Context, input *PutRecordsInput, opts ...request.Option) (*PutRecordsOutput, error) { + req, out := c.PutRecordsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opRemoveTagsFromStream = "RemoveTagsFromStream" @@ -1695,8 +1985,23 @@ func (c *Kinesis) RemoveTagsFromStreamRequest(input *RemoveTagsFromStreamInput) // Please also see https://docs.aws.amazon.com/goto/WebAPI/kinesis-2013-12-02/RemoveTagsFromStream func (c *Kinesis) RemoveTagsFromStream(input *RemoveTagsFromStreamInput) (*RemoveTagsFromStreamOutput, error) { req, out := c.RemoveTagsFromStreamRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// RemoveTagsFromStreamWithContext is the same as RemoveTagsFromStream with the addition of +// the ability to pass a context and additional request options. +// +// See RemoveTagsFromStream 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 *Kinesis) RemoveTagsFromStreamWithContext(ctx aws.Context, input *RemoveTagsFromStreamInput, opts ...request.Option) (*RemoveTagsFromStreamOutput, error) { + req, out := c.RemoveTagsFromStreamRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opSplitShard = "SplitShard" @@ -1819,8 +2124,23 @@ func (c *Kinesis) SplitShardRequest(input *SplitShardInput) (req *request.Reques // Please also see https://docs.aws.amazon.com/goto/WebAPI/kinesis-2013-12-02/SplitShard func (c *Kinesis) SplitShard(input *SplitShardInput) (*SplitShardOutput, error) { req, out := c.SplitShardRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// SplitShardWithContext is the same as SplitShard with the addition of +// the ability to pass a context and additional request options. +// +// See SplitShard 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 *Kinesis) SplitShardWithContext(ctx aws.Context, input *SplitShardInput, opts ...request.Option) (*SplitShardOutput, error) { + req, out := c.SplitShardRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opUpdateShardCount = "UpdateShardCount" @@ -1918,8 +2238,23 @@ func (c *Kinesis) UpdateShardCountRequest(input *UpdateShardCountInput) (req *re // Please also see https://docs.aws.amazon.com/goto/WebAPI/kinesis-2013-12-02/UpdateShardCount func (c *Kinesis) UpdateShardCount(input *UpdateShardCountInput) (*UpdateShardCountOutput, error) { req, out := c.UpdateShardCountRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// UpdateShardCountWithContext is the same as UpdateShardCount with the addition of +// the ability to pass a context and additional request options. +// +// See UpdateShardCount 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 *Kinesis) UpdateShardCountWithContext(ctx aws.Context, input *UpdateShardCountInput, opts ...request.Option) (*UpdateShardCountOutput, error) { + req, out := c.UpdateShardCountRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // Represents the input for AddTagsToStream. diff --git a/vendor/github.com/aws/aws-sdk-go/service/kinesis/customizations.go b/vendor/github.com/aws/aws-sdk-go/service/kinesis/customizations.go new file mode 100644 index 000000000..f618f0da6 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/service/kinesis/customizations.go @@ -0,0 +1,22 @@ +package kinesis + +import ( + "time" + + "github.com/aws/aws-sdk-go/aws/request" +) + +var readDuration = 5 * time.Second + +func init() { + ops := []string{ + opGetRecords, + } + initRequest = func(r *request.Request) { + for _, operation := range ops { + if r.Operation.Name == operation { + r.ApplyOptions(request.WithResponseReadTimeout(readDuration)) + } + } + } +} diff --git a/vendor/github.com/aws/aws-sdk-go/service/kinesis/doc.go b/vendor/github.com/aws/aws-sdk-go/service/kinesis/doc.go new file mode 100644 index 000000000..a64d6b708 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/service/kinesis/doc.go @@ -0,0 +1,81 @@ +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. + +// Package kinesis provides the client and types for making API +// requests to Amazon Kinesis. +// +// Amazon Kinesis Streams is a managed service that scales elastically for real +// time processing of streaming big data. +// +// See https://docs.aws.amazon.com/goto/WebAPI/kinesis-2013-12-02 for more information on this service. +// +// See kinesis package documentation for more information. +// https://docs.aws.amazon.com/sdk-for-go/api/service/kinesis/ +// +// Using the Client +// +// To use the client for Amazon Kinesis you will first need +// to create a new instance of it. +// +// When creating a client for an AWS service you'll first need to have a Session +// already created. The Session provides configuration that can be shared +// between multiple service clients. Additional configuration can be applied to +// the Session and service's client when they are constructed. The aws package's +// Config type contains several fields such as Region for the AWS Region the +// client should make API requests too. The optional Config value can be provided +// as the variadic argument for Sessions and client creation. +// +// Once the service's client is created you can use it to make API requests the +// AWS service. These clients are safe to use concurrently. +// +// // Create a session to share configuration, and load external configuration. +// sess := session.Must(session.NewSession()) +// +// // Create the service's client with the session. +// svc := kinesis.New(sess) +// +// See the SDK's documentation for more information on how to use service clients. +// https://docs.aws.amazon.com/sdk-for-go/api/ +// +// See aws package's Config type for more information on configuration options. +// https://docs.aws.amazon.com/sdk-for-go/api/aws/#Config +// +// See the Amazon Kinesis client Kinesis for more +// information on creating the service's client. +// https://docs.aws.amazon.com/sdk-for-go/api/service/kinesis/#New +// +// Once the client is created you can make an API request to the service. +// Each API method takes a input parameter, and returns the service response +// and an error. +// +// The API method will document which error codes the service can be returned +// by the operation if the service models the API operation's errors. These +// errors will also be available as const strings prefixed with "ErrCode". +// +// result, err := svc.AddTagsToStream(params) +// if err != nil { +// // Cast err to awserr.Error to handle specific error codes. +// aerr, ok := err.(awserr.Error) +// if ok && aerr.Code() == { +// // Specific error code handling +// } +// return err +// } +// +// fmt.Println("AddTagsToStream result:") +// fmt.Println(result) +// +// Using the Client with Context +// +// The service's client also provides methods to make API requests with a Context +// value. This allows you to control the timeout, and cancellation of pending +// requests. These methods also take request Option as variadic parameter to apply +// additional configuration to the API request. +// +// ctx := context.Background() +// +// result, err := svc.AddTagsToStreamWithContext(ctx, params) +// +// See the request package documentation for more information on using Context pattern +// with the SDK. +// https://docs.aws.amazon.com/sdk-for-go/api/aws/request/ +package kinesis diff --git a/vendor/github.com/aws/aws-sdk-go/service/kinesis/errors.go b/vendor/github.com/aws/aws-sdk-go/service/kinesis/errors.go index 083aa5e0f..9c9beafe3 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/kinesis/errors.go +++ b/vendor/github.com/aws/aws-sdk-go/service/kinesis/errors.go @@ -1,4 +1,4 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. package kinesis diff --git a/vendor/github.com/aws/aws-sdk-go/service/kinesis/service.go b/vendor/github.com/aws/aws-sdk-go/service/kinesis/service.go index ed037fe6e..17a59119a 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/kinesis/service.go +++ b/vendor/github.com/aws/aws-sdk-go/service/kinesis/service.go @@ -1,4 +1,4 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. package kinesis @@ -11,11 +11,12 @@ import ( "github.com/aws/aws-sdk-go/private/protocol/jsonrpc" ) -// Amazon Kinesis Streams is a managed service that scales elastically for real -// time processing of streaming big data. -// The service client's operations are safe to be used concurrently. -// It is not safe to mutate any of the client's properties though. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/kinesis-2013-12-02 +// Kinesis provides the API operation methods for making requests to +// Amazon Kinesis. See this package's package overview docs +// for details on the service. +// +// Kinesis methods are safe to use concurrently. It is not safe to +// modify mutate any of the struct's properties though. type Kinesis struct { *client.Client } diff --git a/vendor/github.com/aws/aws-sdk-go/service/kinesis/waiters.go b/vendor/github.com/aws/aws-sdk-go/service/kinesis/waiters.go index c1f56d6c1..a64a77af6 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/kinesis/waiters.go +++ b/vendor/github.com/aws/aws-sdk-go/service/kinesis/waiters.go @@ -1,9 +1,12 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. package kinesis import ( - "github.com/aws/aws-sdk-go/private/waiter" + "time" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/request" ) // WaitUntilStreamExists uses the Kinesis API operation @@ -11,24 +14,89 @@ import ( // If the condition is not meet within the max attempt window an error will // be returned. func (c *Kinesis) WaitUntilStreamExists(input *DescribeStreamInput) error { - waiterCfg := waiter.Config{ - Operation: "DescribeStream", - Delay: 10, + return c.WaitUntilStreamExistsWithContext(aws.BackgroundContext(), input) +} + +// WaitUntilStreamExistsWithContext is an extended version of WaitUntilStreamExists. +// 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 *Kinesis) WaitUntilStreamExistsWithContext(ctx aws.Context, input *DescribeStreamInput, opts ...request.WaiterOption) error { + w := request.Waiter{ + Name: "WaitUntilStreamExists", MaxAttempts: 18, - Acceptors: []waiter.WaitAcceptor{ + Delay: request.ConstantWaiterDelay(10 * time.Second), + Acceptors: []request.WaiterAcceptor{ { - State: "success", - Matcher: "path", - Argument: "StreamDescription.StreamStatus", + State: request.SuccessWaiterState, + Matcher: request.PathWaiterMatch, Argument: "StreamDescription.StreamStatus", Expected: "ACTIVE", }, }, + Logger: c.Config.Logger, + NewRequest: func(opts []request.Option) (*request.Request, error) { + var inCpy *DescribeStreamInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeStreamRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, } + w.ApplyOptions(opts...) - w := waiter.Waiter{ - Client: c, - Input: input, - Config: waiterCfg, - } - return w.Wait() + return w.WaitWithContext(ctx) +} + +// WaitUntilStreamNotExists uses the Kinesis API operation +// DescribeStream to wait for a condition to be met before returning. +// If the condition is not meet within the max attempt window an error will +// be returned. +func (c *Kinesis) WaitUntilStreamNotExists(input *DescribeStreamInput) error { + return c.WaitUntilStreamNotExistsWithContext(aws.BackgroundContext(), input) +} + +// WaitUntilStreamNotExistsWithContext is an extended version of WaitUntilStreamNotExists. +// 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 *Kinesis) WaitUntilStreamNotExistsWithContext(ctx aws.Context, input *DescribeStreamInput, opts ...request.WaiterOption) error { + w := request.Waiter{ + Name: "WaitUntilStreamNotExists", + MaxAttempts: 18, + Delay: request.ConstantWaiterDelay(10 * time.Second), + Acceptors: []request.WaiterAcceptor{ + { + State: request.SuccessWaiterState, + Matcher: request.ErrorWaiterMatch, + Expected: "ResourceNotFoundException", + }, + }, + Logger: c.Config.Logger, + NewRequest: func(opts []request.Option) (*request.Request, error) { + var inCpy *DescribeStreamInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeStreamRequest(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/kms/api.go b/vendor/github.com/aws/aws-sdk-go/service/kms/api.go index afd375b1c..318cb6af1 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/kms/api.go +++ b/vendor/github.com/aws/aws-sdk-go/service/kms/api.go @@ -1,12 +1,12 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. -// Package kms provides a client for AWS Key Management Service. package kms import ( "fmt" "time" + "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awsutil" "github.com/aws/aws-sdk-go/aws/request" "github.com/aws/aws-sdk-go/private/protocol" @@ -100,8 +100,23 @@ func (c *KMS) CancelKeyDeletionRequest(input *CancelKeyDeletionInput) (req *requ // Please also see https://docs.aws.amazon.com/goto/WebAPI/kms-2014-11-01/CancelKeyDeletion func (c *KMS) CancelKeyDeletion(input *CancelKeyDeletionInput) (*CancelKeyDeletionOutput, error) { req, out := c.CancelKeyDeletionRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CancelKeyDeletionWithContext is the same as CancelKeyDeletion with the addition of +// the ability to pass a context and additional request options. +// +// See CancelKeyDeletion for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *KMS) CancelKeyDeletionWithContext(ctx aws.Context, input *CancelKeyDeletionInput, opts ...request.Option) (*CancelKeyDeletionOutput, error) { + req, out := c.CancelKeyDeletionRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateAlias = "CreateAlias" @@ -207,8 +222,23 @@ func (c *KMS) CreateAliasRequest(input *CreateAliasInput) (req *request.Request, // Please also see https://docs.aws.amazon.com/goto/WebAPI/kms-2014-11-01/CreateAlias func (c *KMS) CreateAlias(input *CreateAliasInput) (*CreateAliasOutput, error) { req, out := c.CreateAliasRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateAliasWithContext is the same as CreateAlias with the addition of +// the ability to pass a context and additional request options. +// +// See CreateAlias for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *KMS) CreateAliasWithContext(ctx aws.Context, input *CreateAliasInput, opts ...request.Option) (*CreateAliasOutput, error) { + req, out := c.CreateAliasRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateGrant = "CreateGrant" @@ -307,8 +337,23 @@ func (c *KMS) CreateGrantRequest(input *CreateGrantInput) (req *request.Request, // Please also see https://docs.aws.amazon.com/goto/WebAPI/kms-2014-11-01/CreateGrant func (c *KMS) CreateGrant(input *CreateGrantInput) (*CreateGrantOutput, error) { req, out := c.CreateGrantRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateGrantWithContext is the same as CreateGrant with the addition of +// the ability to pass a context and additional request options. +// +// See CreateGrant for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *KMS) CreateGrantWithContext(ctx aws.Context, input *CreateGrantInput, opts ...request.Option) (*CreateGrantOutput, error) { + req, out := c.CreateGrantRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateKey = "CreateKey" @@ -406,8 +451,23 @@ func (c *KMS) CreateKeyRequest(input *CreateKeyInput) (req *request.Request, out // Please also see https://docs.aws.amazon.com/goto/WebAPI/kms-2014-11-01/CreateKey func (c *KMS) CreateKey(input *CreateKeyInput) (*CreateKeyOutput, error) { req, out := c.CreateKeyRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateKeyWithContext is the same as CreateKey with the addition of +// the ability to pass a context and additional request options. +// +// See CreateKey for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *KMS) CreateKeyWithContext(ctx aws.Context, input *CreateKeyInput, opts ...request.Option) (*CreateKeyOutput, error) { + req, out := c.CreateKeyRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDecrypt = "Decrypt" @@ -518,8 +578,23 @@ func (c *KMS) DecryptRequest(input *DecryptInput) (req *request.Request, output // Please also see https://docs.aws.amazon.com/goto/WebAPI/kms-2014-11-01/Decrypt func (c *KMS) Decrypt(input *DecryptInput) (*DecryptOutput, error) { req, out := c.DecryptRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DecryptWithContext is the same as Decrypt with the addition of +// the ability to pass a context and additional request options. +// +// See Decrypt for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *KMS) DecryptWithContext(ctx aws.Context, input *DecryptInput, opts ...request.Option) (*DecryptOutput, error) { + req, out := c.DecryptRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteAlias = "DeleteAlias" @@ -602,8 +677,23 @@ func (c *KMS) DeleteAliasRequest(input *DeleteAliasInput) (req *request.Request, // Please also see https://docs.aws.amazon.com/goto/WebAPI/kms-2014-11-01/DeleteAlias func (c *KMS) DeleteAlias(input *DeleteAliasInput) (*DeleteAliasOutput, error) { req, out := c.DeleteAliasRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteAliasWithContext is the same as DeleteAlias with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteAlias for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *KMS) DeleteAliasWithContext(ctx aws.Context, input *DeleteAliasInput, opts ...request.Option) (*DeleteAliasOutput, error) { + req, out := c.DeleteAliasRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteImportedKeyMaterial = "DeleteImportedKeyMaterial" @@ -702,8 +792,23 @@ func (c *KMS) DeleteImportedKeyMaterialRequest(input *DeleteImportedKeyMaterialI // Please also see https://docs.aws.amazon.com/goto/WebAPI/kms-2014-11-01/DeleteImportedKeyMaterial func (c *KMS) DeleteImportedKeyMaterial(input *DeleteImportedKeyMaterialInput) (*DeleteImportedKeyMaterialOutput, error) { req, out := c.DeleteImportedKeyMaterialRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteImportedKeyMaterialWithContext is the same as DeleteImportedKeyMaterial with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteImportedKeyMaterial for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *KMS) DeleteImportedKeyMaterialWithContext(ctx aws.Context, input *DeleteImportedKeyMaterialInput, opts ...request.Option) (*DeleteImportedKeyMaterialOutput, error) { + req, out := c.DeleteImportedKeyMaterialRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeKey = "DescribeKey" @@ -779,8 +884,23 @@ func (c *KMS) DescribeKeyRequest(input *DescribeKeyInput) (req *request.Request, // Please also see https://docs.aws.amazon.com/goto/WebAPI/kms-2014-11-01/DescribeKey func (c *KMS) DescribeKey(input *DescribeKeyInput) (*DescribeKeyOutput, error) { req, out := c.DescribeKeyRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeKeyWithContext is the same as DescribeKey with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeKey for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *KMS) DescribeKeyWithContext(ctx aws.Context, input *DescribeKeyInput, opts ...request.Option) (*DescribeKeyOutput, error) { + req, out := c.DescribeKeyRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDisableKey = "DisableKey" @@ -870,8 +990,23 @@ func (c *KMS) DisableKeyRequest(input *DisableKeyInput) (req *request.Request, o // Please also see https://docs.aws.amazon.com/goto/WebAPI/kms-2014-11-01/DisableKey func (c *KMS) DisableKey(input *DisableKeyInput) (*DisableKeyOutput, error) { req, out := c.DisableKeyRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DisableKeyWithContext is the same as DisableKey with the addition of +// the ability to pass a context and additional request options. +// +// See DisableKey for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *KMS) DisableKeyWithContext(ctx aws.Context, input *DisableKeyInput, opts ...request.Option) (*DisableKeyOutput, error) { + req, out := c.DisableKeyRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDisableKeyRotation = "DisableKeyRotation" @@ -964,8 +1099,23 @@ func (c *KMS) DisableKeyRotationRequest(input *DisableKeyRotationInput) (req *re // Please also see https://docs.aws.amazon.com/goto/WebAPI/kms-2014-11-01/DisableKeyRotation func (c *KMS) DisableKeyRotation(input *DisableKeyRotationInput) (*DisableKeyRotationOutput, error) { req, out := c.DisableKeyRotationRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DisableKeyRotationWithContext is the same as DisableKeyRotation with the addition of +// the ability to pass a context and additional request options. +// +// See DisableKeyRotation for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *KMS) DisableKeyRotationWithContext(ctx aws.Context, input *DisableKeyRotationInput, opts ...request.Option) (*DisableKeyRotationOutput, error) { + req, out := c.DisableKeyRotationRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opEnableKey = "EnableKey" @@ -1056,8 +1206,23 @@ func (c *KMS) EnableKeyRequest(input *EnableKeyInput) (req *request.Request, out // Please also see https://docs.aws.amazon.com/goto/WebAPI/kms-2014-11-01/EnableKey func (c *KMS) EnableKey(input *EnableKeyInput) (*EnableKeyOutput, error) { req, out := c.EnableKeyRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// EnableKeyWithContext is the same as EnableKey with the addition of +// the ability to pass a context and additional request options. +// +// See EnableKey for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *KMS) EnableKeyWithContext(ctx aws.Context, input *EnableKeyInput, opts ...request.Option) (*EnableKeyOutput, error) { + req, out := c.EnableKeyRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opEnableKeyRotation = "EnableKeyRotation" @@ -1150,8 +1315,23 @@ func (c *KMS) EnableKeyRotationRequest(input *EnableKeyRotationInput) (req *requ // Please also see https://docs.aws.amazon.com/goto/WebAPI/kms-2014-11-01/EnableKeyRotation func (c *KMS) EnableKeyRotation(input *EnableKeyRotationInput) (*EnableKeyRotationOutput, error) { req, out := c.EnableKeyRotationRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// EnableKeyRotationWithContext is the same as EnableKeyRotation with the addition of +// the ability to pass a context and additional request options. +// +// See EnableKeyRotation for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *KMS) EnableKeyRotationWithContext(ctx aws.Context, input *EnableKeyRotationInput, opts ...request.Option) (*EnableKeyRotationOutput, error) { + req, out := c.EnableKeyRotationRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opEncrypt = "Encrypt" @@ -1264,8 +1444,23 @@ func (c *KMS) EncryptRequest(input *EncryptInput) (req *request.Request, output // Please also see https://docs.aws.amazon.com/goto/WebAPI/kms-2014-11-01/Encrypt func (c *KMS) Encrypt(input *EncryptInput) (*EncryptOutput, error) { req, out := c.EncryptRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// EncryptWithContext is the same as Encrypt with the addition of +// the ability to pass a context and additional request options. +// +// See Encrypt for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *KMS) EncryptWithContext(ctx aws.Context, input *EncryptInput, opts ...request.Option) (*EncryptOutput, error) { + req, out := c.EncryptRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGenerateDataKey = "GenerateDataKey" @@ -1348,7 +1543,7 @@ func (c *KMS) GenerateDataKeyRequest(input *GenerateDataKeyInput) (req *request. // data key from memory. // // To return only an encrypted copy of the data key, use GenerateDataKeyWithoutPlaintext. -// To return an arbitrary unpredictable byte string, use GenerateRandom. +// To return a random byte string that is cryptographically secure, use GenerateRandom. // // If you use the optional EncryptionContext field, you must store at least // enough information to be able to reconstruct the full encryption context @@ -1402,8 +1597,23 @@ func (c *KMS) GenerateDataKeyRequest(input *GenerateDataKeyInput) (req *request. // Please also see https://docs.aws.amazon.com/goto/WebAPI/kms-2014-11-01/GenerateDataKey func (c *KMS) GenerateDataKey(input *GenerateDataKeyInput) (*GenerateDataKeyOutput, error) { req, out := c.GenerateDataKeyRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GenerateDataKeyWithContext is the same as GenerateDataKey with the addition of +// the ability to pass a context and additional request options. +// +// See GenerateDataKey for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *KMS) GenerateDataKeyWithContext(ctx aws.Context, input *GenerateDataKeyInput, opts ...request.Option) (*GenerateDataKeyOutput, error) { + req, out := c.GenerateDataKeyRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGenerateDataKeyWithoutPlaintext = "GenerateDataKeyWithoutPlaintext" @@ -1511,8 +1721,23 @@ func (c *KMS) GenerateDataKeyWithoutPlaintextRequest(input *GenerateDataKeyWitho // Please also see https://docs.aws.amazon.com/goto/WebAPI/kms-2014-11-01/GenerateDataKeyWithoutPlaintext func (c *KMS) GenerateDataKeyWithoutPlaintext(input *GenerateDataKeyWithoutPlaintextInput) (*GenerateDataKeyWithoutPlaintextOutput, error) { req, out := c.GenerateDataKeyWithoutPlaintextRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GenerateDataKeyWithoutPlaintextWithContext is the same as GenerateDataKeyWithoutPlaintext with the addition of +// the ability to pass a context and additional request options. +// +// See GenerateDataKeyWithoutPlaintext for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *KMS) GenerateDataKeyWithoutPlaintextWithContext(ctx aws.Context, input *GenerateDataKeyWithoutPlaintextInput, opts ...request.Option) (*GenerateDataKeyWithoutPlaintextOutput, error) { + req, out := c.GenerateDataKeyWithoutPlaintextRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGenerateRandom = "GenerateRandom" @@ -1560,7 +1785,11 @@ func (c *KMS) GenerateRandomRequest(input *GenerateRandomInput) (req *request.Re // GenerateRandom API operation for AWS Key Management Service. // -// Generates an unpredictable byte string. +// Returns a random byte string that is cryptographically secure. +// +// For more information about entropy and random number generation, see the +// AWS Key Management Service Cryptographic Details (https://d0.awsstatic.com/whitepapers/KMS-Cryptographic-Details.pdf) +// whitepaper. // // 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 @@ -1581,8 +1810,23 @@ func (c *KMS) GenerateRandomRequest(input *GenerateRandomInput) (req *request.Re // Please also see https://docs.aws.amazon.com/goto/WebAPI/kms-2014-11-01/GenerateRandom func (c *KMS) GenerateRandom(input *GenerateRandomInput) (*GenerateRandomOutput, error) { req, out := c.GenerateRandomRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GenerateRandomWithContext is the same as GenerateRandom with the addition of +// the ability to pass a context and additional request options. +// +// See GenerateRandom for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *KMS) GenerateRandomWithContext(ctx aws.Context, input *GenerateRandomInput, opts ...request.Option) (*GenerateRandomOutput, error) { + req, out := c.GenerateRandomRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetKeyPolicy = "GetKeyPolicy" @@ -1666,8 +1910,23 @@ func (c *KMS) GetKeyPolicyRequest(input *GetKeyPolicyInput) (req *request.Reques // Please also see https://docs.aws.amazon.com/goto/WebAPI/kms-2014-11-01/GetKeyPolicy func (c *KMS) GetKeyPolicy(input *GetKeyPolicyInput) (*GetKeyPolicyOutput, error) { req, out := c.GetKeyPolicyRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetKeyPolicyWithContext is the same as GetKeyPolicy with the addition of +// the ability to pass a context and additional request options. +// +// See GetKeyPolicy for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *KMS) GetKeyPolicyWithContext(ctx aws.Context, input *GetKeyPolicyInput, opts ...request.Option) (*GetKeyPolicyOutput, error) { + req, out := c.GetKeyPolicyRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetKeyRotationStatus = "GetKeyRotationStatus" @@ -1756,8 +2015,23 @@ func (c *KMS) GetKeyRotationStatusRequest(input *GetKeyRotationStatusInput) (req // Please also see https://docs.aws.amazon.com/goto/WebAPI/kms-2014-11-01/GetKeyRotationStatus func (c *KMS) GetKeyRotationStatus(input *GetKeyRotationStatusInput) (*GetKeyRotationStatusOutput, error) { req, out := c.GetKeyRotationStatusRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetKeyRotationStatusWithContext is the same as GetKeyRotationStatus with the addition of +// the ability to pass a context and additional request options. +// +// See GetKeyRotationStatus for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *KMS) GetKeyRotationStatusWithContext(ctx aws.Context, input *GetKeyRotationStatusInput, opts ...request.Option) (*GetKeyRotationStatusOutput, error) { + req, out := c.GetKeyRotationStatusRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetParametersForImport = "GetParametersForImport" @@ -1860,8 +2134,23 @@ func (c *KMS) GetParametersForImportRequest(input *GetParametersForImportInput) // Please also see https://docs.aws.amazon.com/goto/WebAPI/kms-2014-11-01/GetParametersForImport func (c *KMS) GetParametersForImport(input *GetParametersForImportInput) (*GetParametersForImportOutput, error) { req, out := c.GetParametersForImportRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetParametersForImportWithContext is the same as GetParametersForImport with the addition of +// the ability to pass a context and additional request options. +// +// See GetParametersForImport for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *KMS) GetParametersForImportWithContext(ctx aws.Context, input *GetParametersForImportInput, opts ...request.Option) (*GetParametersForImportOutput, error) { + req, out := c.GetParametersForImportRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opImportKeyMaterial = "ImportKeyMaterial" @@ -1988,8 +2277,23 @@ func (c *KMS) ImportKeyMaterialRequest(input *ImportKeyMaterialInput) (req *requ // Please also see https://docs.aws.amazon.com/goto/WebAPI/kms-2014-11-01/ImportKeyMaterial func (c *KMS) ImportKeyMaterial(input *ImportKeyMaterialInput) (*ImportKeyMaterialOutput, error) { req, out := c.ImportKeyMaterialRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ImportKeyMaterialWithContext is the same as ImportKeyMaterial with the addition of +// the ability to pass a context and additional request options. +// +// See ImportKeyMaterial for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *KMS) ImportKeyMaterialWithContext(ctx aws.Context, input *ImportKeyMaterialInput, opts ...request.Option) (*ImportKeyMaterialOutput, error) { + req, out := c.ImportKeyMaterialRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opListAliases = "ListAliases" @@ -2068,8 +2372,23 @@ func (c *KMS) ListAliasesRequest(input *ListAliasesInput) (req *request.Request, // Please also see https://docs.aws.amazon.com/goto/WebAPI/kms-2014-11-01/ListAliases func (c *KMS) ListAliases(input *ListAliasesInput) (*ListAliasesOutput, error) { req, out := c.ListAliasesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListAliasesWithContext is the same as ListAliases with the addition of +// the ability to pass a context and additional request options. +// +// See ListAliases for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *KMS) ListAliasesWithContext(ctx aws.Context, input *ListAliasesInput, opts ...request.Option) (*ListAliasesOutput, error) { + req, out := c.ListAliasesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // ListAliasesPages iterates over the pages of a ListAliases operation, @@ -2089,12 +2408,37 @@ func (c *KMS) ListAliases(input *ListAliasesInput) (*ListAliasesOutput, error) { // return pageNum <= 3 // }) // -func (c *KMS) ListAliasesPages(input *ListAliasesInput, fn func(p *ListAliasesOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.ListAliasesRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*ListAliasesOutput), lastPage) - }) +func (c *KMS) ListAliasesPages(input *ListAliasesInput, fn func(*ListAliasesOutput, bool) bool) error { + return c.ListAliasesPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListAliasesPagesWithContext same as ListAliasesPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *KMS) ListAliasesPagesWithContext(ctx aws.Context, input *ListAliasesInput, fn func(*ListAliasesOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListAliasesInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListAliasesRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*ListAliasesOutput), !p.HasNextPage()) + } + return p.Err() } const opListGrants = "ListGrants" @@ -2188,8 +2532,23 @@ func (c *KMS) ListGrantsRequest(input *ListGrantsInput) (req *request.Request, o // Please also see https://docs.aws.amazon.com/goto/WebAPI/kms-2014-11-01/ListGrants func (c *KMS) ListGrants(input *ListGrantsInput) (*ListGrantsResponse, error) { req, out := c.ListGrantsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListGrantsWithContext is the same as ListGrants with the addition of +// the ability to pass a context and additional request options. +// +// See ListGrants for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *KMS) ListGrantsWithContext(ctx aws.Context, input *ListGrantsInput, opts ...request.Option) (*ListGrantsResponse, error) { + req, out := c.ListGrantsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // ListGrantsPages iterates over the pages of a ListGrants operation, @@ -2209,12 +2568,37 @@ func (c *KMS) ListGrants(input *ListGrantsInput) (*ListGrantsResponse, error) { // return pageNum <= 3 // }) // -func (c *KMS) ListGrantsPages(input *ListGrantsInput, fn func(p *ListGrantsResponse, lastPage bool) (shouldContinue bool)) error { - page, _ := c.ListGrantsRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*ListGrantsResponse), lastPage) - }) +func (c *KMS) ListGrantsPages(input *ListGrantsInput, fn func(*ListGrantsResponse, bool) bool) error { + return c.ListGrantsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListGrantsPagesWithContext same as ListGrantsPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *KMS) ListGrantsPagesWithContext(ctx aws.Context, input *ListGrantsInput, fn func(*ListGrantsResponse, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListGrantsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListGrantsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*ListGrantsResponse), !p.HasNextPage()) + } + return p.Err() } const opListKeyPolicies = "ListKeyPolicies" @@ -2304,8 +2688,23 @@ func (c *KMS) ListKeyPoliciesRequest(input *ListKeyPoliciesInput) (req *request. // Please also see https://docs.aws.amazon.com/goto/WebAPI/kms-2014-11-01/ListKeyPolicies func (c *KMS) ListKeyPolicies(input *ListKeyPoliciesInput) (*ListKeyPoliciesOutput, error) { req, out := c.ListKeyPoliciesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListKeyPoliciesWithContext is the same as ListKeyPolicies with the addition of +// the ability to pass a context and additional request options. +// +// See ListKeyPolicies for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *KMS) ListKeyPoliciesWithContext(ctx aws.Context, input *ListKeyPoliciesInput, opts ...request.Option) (*ListKeyPoliciesOutput, error) { + req, out := c.ListKeyPoliciesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // ListKeyPoliciesPages iterates over the pages of a ListKeyPolicies operation, @@ -2325,12 +2724,37 @@ func (c *KMS) ListKeyPolicies(input *ListKeyPoliciesInput) (*ListKeyPoliciesOutp // return pageNum <= 3 // }) // -func (c *KMS) ListKeyPoliciesPages(input *ListKeyPoliciesInput, fn func(p *ListKeyPoliciesOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.ListKeyPoliciesRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*ListKeyPoliciesOutput), lastPage) - }) +func (c *KMS) ListKeyPoliciesPages(input *ListKeyPoliciesInput, fn func(*ListKeyPoliciesOutput, bool) bool) error { + return c.ListKeyPoliciesPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListKeyPoliciesPagesWithContext same as ListKeyPoliciesPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *KMS) ListKeyPoliciesPagesWithContext(ctx aws.Context, input *ListKeyPoliciesInput, fn func(*ListKeyPoliciesOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListKeyPoliciesInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListKeyPoliciesRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*ListKeyPoliciesOutput), !p.HasNextPage()) + } + return p.Err() } const opListKeys = "ListKeys" @@ -2409,8 +2833,23 @@ func (c *KMS) ListKeysRequest(input *ListKeysInput) (req *request.Request, outpu // Please also see https://docs.aws.amazon.com/goto/WebAPI/kms-2014-11-01/ListKeys func (c *KMS) ListKeys(input *ListKeysInput) (*ListKeysOutput, error) { req, out := c.ListKeysRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListKeysWithContext is the same as ListKeys with the addition of +// the ability to pass a context and additional request options. +// +// See ListKeys for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *KMS) ListKeysWithContext(ctx aws.Context, input *ListKeysInput, opts ...request.Option) (*ListKeysOutput, error) { + req, out := c.ListKeysRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // ListKeysPages iterates over the pages of a ListKeys operation, @@ -2430,12 +2869,37 @@ func (c *KMS) ListKeys(input *ListKeysInput) (*ListKeysOutput, error) { // return pageNum <= 3 // }) // -func (c *KMS) ListKeysPages(input *ListKeysInput, fn func(p *ListKeysOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.ListKeysRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*ListKeysOutput), lastPage) - }) +func (c *KMS) ListKeysPages(input *ListKeysInput, fn func(*ListKeysOutput, bool) bool) error { + return c.ListKeysPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListKeysPagesWithContext same as ListKeysPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *KMS) ListKeysPagesWithContext(ctx aws.Context, input *ListKeysInput, fn func(*ListKeysOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListKeysInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListKeysRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*ListKeysOutput), !p.HasNextPage()) + } + return p.Err() } const opListResourceTags = "ListResourceTags" @@ -2511,8 +2975,23 @@ func (c *KMS) ListResourceTagsRequest(input *ListResourceTagsInput) (req *reques // Please also see https://docs.aws.amazon.com/goto/WebAPI/kms-2014-11-01/ListResourceTags func (c *KMS) ListResourceTags(input *ListResourceTagsInput) (*ListResourceTagsOutput, error) { req, out := c.ListResourceTagsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListResourceTagsWithContext is the same as ListResourceTags with the addition of +// the ability to pass a context and additional request options. +// +// See ListResourceTags for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *KMS) ListResourceTagsWithContext(ctx aws.Context, input *ListResourceTagsInput, opts ...request.Option) (*ListResourceTagsOutput, error) { + req, out := c.ListResourceTagsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opListRetirableGrants = "ListRetirableGrants" @@ -2596,8 +3075,23 @@ func (c *KMS) ListRetirableGrantsRequest(input *ListRetirableGrantsInput) (req * // Please also see https://docs.aws.amazon.com/goto/WebAPI/kms-2014-11-01/ListRetirableGrants func (c *KMS) ListRetirableGrants(input *ListRetirableGrantsInput) (*ListGrantsResponse, error) { req, out := c.ListRetirableGrantsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListRetirableGrantsWithContext is the same as ListRetirableGrants with the addition of +// the ability to pass a context and additional request options. +// +// See ListRetirableGrants for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *KMS) ListRetirableGrantsWithContext(ctx aws.Context, input *ListRetirableGrantsInput, opts ...request.Option) (*ListGrantsResponse, error) { + req, out := c.ListRetirableGrantsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opPutKeyPolicy = "PutKeyPolicy" @@ -2699,8 +3193,23 @@ func (c *KMS) PutKeyPolicyRequest(input *PutKeyPolicyInput) (req *request.Reques // Please also see https://docs.aws.amazon.com/goto/WebAPI/kms-2014-11-01/PutKeyPolicy func (c *KMS) PutKeyPolicy(input *PutKeyPolicyInput) (*PutKeyPolicyOutput, error) { req, out := c.PutKeyPolicyRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// PutKeyPolicyWithContext is the same as PutKeyPolicy with the addition of +// the ability to pass a context and additional request options. +// +// See PutKeyPolicy for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *KMS) PutKeyPolicyWithContext(ctx aws.Context, input *PutKeyPolicyInput, opts ...request.Option) (*PutKeyPolicyOutput, error) { + req, out := c.PutKeyPolicyRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opReEncrypt = "ReEncrypt" @@ -2809,8 +3318,23 @@ func (c *KMS) ReEncryptRequest(input *ReEncryptInput) (req *request.Request, out // Please also see https://docs.aws.amazon.com/goto/WebAPI/kms-2014-11-01/ReEncrypt func (c *KMS) ReEncrypt(input *ReEncryptInput) (*ReEncryptOutput, error) { req, out := c.ReEncryptRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ReEncryptWithContext is the same as ReEncrypt with the addition of +// the ability to pass a context and additional request options. +// +// See ReEncrypt for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *KMS) ReEncryptWithContext(ctx aws.Context, input *ReEncryptInput, opts ...request.Option) (*ReEncryptOutput, error) { + req, out := c.ReEncryptRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opRetireGrant = "RetireGrant" @@ -2914,8 +3438,23 @@ func (c *KMS) RetireGrantRequest(input *RetireGrantInput) (req *request.Request, // Please also see https://docs.aws.amazon.com/goto/WebAPI/kms-2014-11-01/RetireGrant func (c *KMS) RetireGrant(input *RetireGrantInput) (*RetireGrantOutput, error) { req, out := c.RetireGrantRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// RetireGrantWithContext is the same as RetireGrant with the addition of +// the ability to pass a context and additional request options. +// +// See RetireGrant for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *KMS) RetireGrantWithContext(ctx aws.Context, input *RetireGrantInput, opts ...request.Option) (*RetireGrantOutput, error) { + req, out := c.RetireGrantRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opRevokeGrant = "RevokeGrant" @@ -3005,8 +3544,23 @@ func (c *KMS) RevokeGrantRequest(input *RevokeGrantInput) (req *request.Request, // Please also see https://docs.aws.amazon.com/goto/WebAPI/kms-2014-11-01/RevokeGrant func (c *KMS) RevokeGrant(input *RevokeGrantInput) (*RevokeGrantOutput, error) { req, out := c.RevokeGrantRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// RevokeGrantWithContext is the same as RevokeGrant with the addition of +// the ability to pass a context and additional request options. +// +// See RevokeGrant for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *KMS) RevokeGrantWithContext(ctx aws.Context, input *RevokeGrantInput, opts ...request.Option) (*RevokeGrantOutput, error) { + req, out := c.RevokeGrantRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opScheduleKeyDeletion = "ScheduleKeyDeletion" @@ -3105,8 +3659,23 @@ func (c *KMS) ScheduleKeyDeletionRequest(input *ScheduleKeyDeletionInput) (req * // Please also see https://docs.aws.amazon.com/goto/WebAPI/kms-2014-11-01/ScheduleKeyDeletion func (c *KMS) ScheduleKeyDeletion(input *ScheduleKeyDeletionInput) (*ScheduleKeyDeletionOutput, error) { req, out := c.ScheduleKeyDeletionRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ScheduleKeyDeletionWithContext is the same as ScheduleKeyDeletion with the addition of +// the ability to pass a context and additional request options. +// +// See ScheduleKeyDeletion for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *KMS) ScheduleKeyDeletionWithContext(ctx aws.Context, input *ScheduleKeyDeletionInput, opts ...request.Option) (*ScheduleKeyDeletionOutput, error) { + req, out := c.ScheduleKeyDeletionRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opTagResource = "TagResource" @@ -3206,8 +3775,23 @@ func (c *KMS) TagResourceRequest(input *TagResourceInput) (req *request.Request, // Please also see https://docs.aws.amazon.com/goto/WebAPI/kms-2014-11-01/TagResource func (c *KMS) TagResource(input *TagResourceInput) (*TagResourceOutput, error) { req, out := c.TagResourceRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// TagResourceWithContext is the same as TagResource with the addition of +// the ability to pass a context and additional request options. +// +// See TagResource for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *KMS) TagResourceWithContext(ctx aws.Context, input *TagResourceInput, opts ...request.Option) (*TagResourceOutput, error) { + req, out := c.TagResourceRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opUntagResource = "UntagResource" @@ -3297,8 +3881,23 @@ func (c *KMS) UntagResourceRequest(input *UntagResourceInput) (req *request.Requ // Please also see https://docs.aws.amazon.com/goto/WebAPI/kms-2014-11-01/UntagResource func (c *KMS) UntagResource(input *UntagResourceInput) (*UntagResourceOutput, error) { req, out := c.UntagResourceRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// UntagResourceWithContext is the same as UntagResource with the addition of +// the ability to pass a context and additional request options. +// +// See UntagResource for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *KMS) UntagResourceWithContext(ctx aws.Context, input *UntagResourceInput, opts ...request.Option) (*UntagResourceOutput, error) { + req, out := c.UntagResourceRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opUpdateAlias = "UpdateAlias" @@ -3393,8 +3992,23 @@ func (c *KMS) UpdateAliasRequest(input *UpdateAliasInput) (req *request.Request, // Please also see https://docs.aws.amazon.com/goto/WebAPI/kms-2014-11-01/UpdateAlias func (c *KMS) UpdateAlias(input *UpdateAliasInput) (*UpdateAliasOutput, error) { req, out := c.UpdateAliasRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// UpdateAliasWithContext is the same as UpdateAlias with the addition of +// the ability to pass a context and additional request options. +// +// See UpdateAlias for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *KMS) UpdateAliasWithContext(ctx aws.Context, input *UpdateAliasInput, opts ...request.Option) (*UpdateAliasOutput, error) { + req, out := c.UpdateAliasRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opUpdateKeyDescription = "UpdateKeyDescription" @@ -3480,8 +4094,23 @@ func (c *KMS) UpdateKeyDescriptionRequest(input *UpdateKeyDescriptionInput) (req // Please also see https://docs.aws.amazon.com/goto/WebAPI/kms-2014-11-01/UpdateKeyDescription func (c *KMS) UpdateKeyDescription(input *UpdateKeyDescriptionInput) (*UpdateKeyDescriptionOutput, error) { req, out := c.UpdateKeyDescriptionRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// UpdateKeyDescriptionWithContext is the same as UpdateKeyDescription with the addition of +// the ability to pass a context and additional request options. +// +// See UpdateKeyDescription for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *KMS) UpdateKeyDescriptionWithContext(ctx aws.Context, input *UpdateKeyDescriptionInput, opts ...request.Option) (*UpdateKeyDescriptionOutput, error) { + req, out := c.UpdateKeyDescriptionRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // Contains information about an alias. @@ -3690,11 +4319,9 @@ func (s CreateAliasOutput) GoString() string { type CreateGrantInput struct { _ struct{} `type:"structure"` - // The conditions under which the operations permitted by the grant are allowed. - // - // You can use this value to allow the operations permitted by the grant only - // when a specified encryption context is present. For more information, see - // Encryption Context (http://docs.aws.amazon.com/kms/latest/developerguide/encryption-context.html) + // A structure that you can use to allow certain operations in the grant only + // when the desired encryption context is present. For more information about + // encryption context, see Encryption Context (http://docs.aws.amazon.com/kms/latest/developerguide/encryption-context.html) // in the AWS Key Management Service Developer Guide. Constraints *GrantConstraints `type:"structure"` @@ -5074,7 +5701,7 @@ func (s *GenerateRandomInput) SetNumberOfBytes(v int64) *GenerateRandomInput { type GenerateRandomOutput struct { _ struct{} `type:"structure"` - // The unpredictable byte string. + // The random byte string. // // Plaintext is automatically base64 encoded/decoded by the SDK. Plaintext []byte `min:"1" type:"blob"` @@ -5397,29 +6024,34 @@ func (s *GetParametersForImportOutput) SetPublicKey(v []byte) *GetParametersForI return s } -// A structure for specifying the conditions under which the operations permitted -// by the grant are allowed. -// -// You can use this structure to allow the operations permitted by the grant -// only when a specified encryption context is present. For more information -// about encryption context, see Encryption Context (http://docs.aws.amazon.com/kms/latest/developerguide/encryption-context.html) +// A structure that you can use to allow certain operations in the grant only +// when the desired encryption context is present. For more information about +// encryption context, see Encryption Context (http://docs.aws.amazon.com/kms/latest/developerguide/encryption-context.html) // in the AWS Key Management Service Developer Guide. +// +// Grant constraints apply only to operations that accept encryption context +// as input. For example, the DescribeKey operation does not accept encryption +// context as input. A grant that allows the DescribeKey operation does so regardless +// of the grant constraints. In constrast, the Encrypt operation accepts encryption +// context as input. A grant that allows the Encrypt operation does so only +// when the encryption context of the Encrypt operation satisfies the grant +// constraints. // Please also see https://docs.aws.amazon.com/goto/WebAPI/kms-2014-11-01/GrantConstraints type GrantConstraints struct { _ struct{} `type:"structure"` - // Contains a list of key-value pairs that must be present in the encryption - // context of a subsequent operation permitted by the grant. When a subsequent - // operation permitted by the grant includes an encryption context that matches - // this list, the grant allows the operation. Otherwise, the operation is not - // allowed. + // A list of key-value pairs that must be present in the encryption context + // of certain subsequent operations that the grant allows. When certain subsequent + // operations allowed by the grant include encryption context that matches this + // list, the grant allows the operation. Otherwise, the grant does not allow + // the operation. EncryptionContextEquals map[string]*string `type:"map"` - // Contains a list of key-value pairs, a subset of which must be present in - // the encryption context of a subsequent operation permitted by the grant. - // When a subsequent operation permitted by the grant includes an encryption - // context that matches this list or is a subset of this list, the grant allows - // the operation. Otherwise, the operation is not allowed. + // A list of key-value pairs, all of which must be present in the encryption + // context of certain subsequent operations that the grant allows. When certain + // subsequent operations allowed by the grant include encryption context that + // matches this list or is a superset of this list, the grant allows the operation. + // Otherwise, the grant does not allow the operation. EncryptionContextSubset map[string]*string `type:"map"` } @@ -5450,7 +6082,8 @@ func (s *GrantConstraints) SetEncryptionContextSubset(v map[string]*string) *Gra type GrantListEntry struct { _ struct{} `type:"structure"` - // The conditions under which the grant's operations are allowed. + // A list of key-value pairs that must be present in the encryption context + // of certain subsequent operations that the grant allows. Constraints *GrantConstraints `type:"structure"` // The date and time when the grant was created. diff --git a/vendor/github.com/aws/aws-sdk-go/service/kms/doc.go b/vendor/github.com/aws/aws-sdk-go/service/kms/doc.go new file mode 100644 index 000000000..6e1eb48f1 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/service/kms/doc.go @@ -0,0 +1,150 @@ +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. + +// Package kms provides the client and types for making API +// requests to AWS Key Management Service. +// +// AWS Key Management Service (AWS KMS) is an encryption and key management +// web service. This guide describes the AWS KMS operations that you can call +// programmatically. For general information about AWS KMS, see the AWS Key +// Management Service Developer Guide (http://docs.aws.amazon.com/kms/latest/developerguide/). +// +// 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 AWS KMS and other +// AWS services. For example, the SDKs take care of tasks such as signing requests +// (see below), 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/). +// +// We recommend that you use the AWS SDKs to make programmatic API calls to +// AWS KMS. +// +// Clients must support TLS (Transport Layer Security) 1.0. We recommend TLS +// 1.2. Clients must also support cipher suites with Perfect Forward Secrecy +// (PFS) such as Ephemeral Diffie-Hellman (DHE) or Elliptic Curve Ephemeral +// Diffie-Hellman (ECDHE). Most modern systems such as Java 7 and later support +// these modes. +// +// Signing Requests +// +// Requests must be signed by using an access key ID and a secret access key. +// We strongly recommend that you do not use your AWS account (root) access +// key ID and secret key for everyday work with AWS KMS. Instead, 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 that you can use +// to sign requests. +// +// All AWS KMS operations require Signature Version 4 (http://docs.aws.amazon.com/general/latest/gr/signature-version-4.html). +// +// Logging API Requests +// +// AWS KMS supports AWS CloudTrail, a service that logs AWS API calls and related +// events for your AWS account and delivers them to an Amazon S3 bucket that +// you specify. By using the information collected by CloudTrail, you can determine +// what requests were made to AWS KMS, who made the request, when it was made, +// and so on. To learn more about CloudTrail, including how to turn it on and +// find your log files, see the AWS CloudTrail User Guide (http://docs.aws.amazon.com/awscloudtrail/latest/userguide/). +// +// Additional Resources +// +// For more information about credentials and request signing, see the following: +// +// * AWS Security Credentials (http://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. +// +// * Temporary Security Credentials (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp.html) +// - This section of the IAM User Guide describes how to create and use temporary +// security credentials. +// +// * Signature Version 4 Signing Process (http://docs.aws.amazon.com/general/latest/gr/signature-version-4.html) +// - This set of topics walks you through the process of signing a request +// using an access key ID and a secret access key. +// +// Commonly Used APIs +// +// Of the APIs discussed in this guide, the following will prove the most useful +// for most applications. You will likely perform actions other than these, +// such as creating keys and assigning policies, by using the console. +// +// * Encrypt +// +// * Decrypt +// +// * GenerateDataKey +// +// * GenerateDataKeyWithoutPlaintext +// +// See https://docs.aws.amazon.com/goto/WebAPI/kms-2014-11-01 for more information on this service. +// +// See kms package documentation for more information. +// https://docs.aws.amazon.com/sdk-for-go/api/service/kms/ +// +// Using the Client +// +// To use the client for AWS Key Management Service you will first need +// to create a new instance of it. +// +// When creating a client for an AWS service you'll first need to have a Session +// already created. The Session provides configuration that can be shared +// between multiple service clients. Additional configuration can be applied to +// the Session and service's client when they are constructed. The aws package's +// Config type contains several fields such as Region for the AWS Region the +// client should make API requests too. The optional Config value can be provided +// as the variadic argument for Sessions and client creation. +// +// Once the service's client is created you can use it to make API requests the +// AWS service. These clients are safe to use concurrently. +// +// // Create a session to share configuration, and load external configuration. +// sess := session.Must(session.NewSession()) +// +// // Create the service's client with the session. +// svc := kms.New(sess) +// +// See the SDK's documentation for more information on how to use service clients. +// https://docs.aws.amazon.com/sdk-for-go/api/ +// +// See aws package's Config type for more information on configuration options. +// https://docs.aws.amazon.com/sdk-for-go/api/aws/#Config +// +// See the AWS Key Management Service client KMS for more +// information on creating the service's client. +// https://docs.aws.amazon.com/sdk-for-go/api/service/kms/#New +// +// Once the client is created you can make an API request to the service. +// Each API method takes a input parameter, and returns the service response +// and an error. +// +// The API method will document which error codes the service can be returned +// by the operation if the service models the API operation's errors. These +// errors will also be available as const strings prefixed with "ErrCode". +// +// result, err := svc.CancelKeyDeletion(params) +// if err != nil { +// // Cast err to awserr.Error to handle specific error codes. +// aerr, ok := err.(awserr.Error) +// if ok && aerr.Code() == { +// // Specific error code handling +// } +// return err +// } +// +// fmt.Println("CancelKeyDeletion result:") +// fmt.Println(result) +// +// Using the Client with Context +// +// The service's client also provides methods to make API requests with a Context +// value. This allows you to control the timeout, and cancellation of pending +// requests. These methods also take request Option as variadic parameter to apply +// additional configuration to the API request. +// +// ctx := context.Background() +// +// result, err := svc.CancelKeyDeletionWithContext(ctx, params) +// +// See the request package documentation for more information on using Context pattern +// with the SDK. +// https://docs.aws.amazon.com/sdk-for-go/api/aws/request/ +package kms diff --git a/vendor/github.com/aws/aws-sdk-go/service/kms/errors.go b/vendor/github.com/aws/aws-sdk-go/service/kms/errors.go index 474ae6baf..0358c9443 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/kms/errors.go +++ b/vendor/github.com/aws/aws-sdk-go/service/kms/errors.go @@ -1,4 +1,4 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. package kms diff --git a/vendor/github.com/aws/aws-sdk-go/service/kms/service.go b/vendor/github.com/aws/aws-sdk-go/service/kms/service.go index b4688cad3..3ff65de5e 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/kms/service.go +++ b/vendor/github.com/aws/aws-sdk-go/service/kms/service.go @@ -1,4 +1,4 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. package kms @@ -11,80 +11,12 @@ import ( "github.com/aws/aws-sdk-go/private/protocol/jsonrpc" ) -// AWS Key Management Service (AWS KMS) is an encryption and key management -// web service. This guide describes the AWS KMS operations that you can call -// programmatically. For general information about AWS KMS, see the AWS Key -// Management Service Developer Guide (http://docs.aws.amazon.com/kms/latest/developerguide/). +// KMS provides the API operation methods for making requests to +// AWS Key Management Service. See this package's package overview docs +// for details on the service. // -// 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 AWS KMS and other -// AWS services. For example, the SDKs take care of tasks such as signing requests -// (see below), 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/). -// -// We recommend that you use the AWS SDKs to make programmatic API calls to -// AWS KMS. -// -// Clients must support TLS (Transport Layer Security) 1.0. We recommend TLS -// 1.2. Clients must also support cipher suites with Perfect Forward Secrecy -// (PFS) such as Ephemeral Diffie-Hellman (DHE) or Elliptic Curve Ephemeral -// Diffie-Hellman (ECDHE). Most modern systems such as Java 7 and later support -// these modes. -// -// Signing Requests -// -// Requests must be signed by using an access key ID and a secret access key. -// We strongly recommend that you do not use your AWS account (root) access -// key ID and secret key for everyday work with AWS KMS. Instead, 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 that you can use -// to sign requests. -// -// All AWS KMS operations require Signature Version 4 (http://docs.aws.amazon.com/general/latest/gr/signature-version-4.html). -// -// Logging API Requests -// -// AWS KMS supports AWS CloudTrail, a service that logs AWS API calls and related -// events for your AWS account and delivers them to an Amazon S3 bucket that -// you specify. By using the information collected by CloudTrail, you can determine -// what requests were made to AWS KMS, who made the request, when it was made, -// and so on. To learn more about CloudTrail, including how to turn it on and -// find your log files, see the AWS CloudTrail User Guide (http://docs.aws.amazon.com/awscloudtrail/latest/userguide/). -// -// Additional Resources -// -// For more information about credentials and request signing, see the following: -// -// * AWS Security Credentials (http://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. -// -// * Temporary Security Credentials (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp.html) -// - This section of the IAM User Guide describes how to create and use temporary -// security credentials. -// -// * Signature Version 4 Signing Process (http://docs.aws.amazon.com/general/latest/gr/signature-version-4.html) -// - This set of topics walks you through the process of signing a request -// using an access key ID and a secret access key. -// -// Commonly Used APIs -// -// Of the APIs discussed in this guide, the following will prove the most useful -// for most applications. You will likely perform actions other than these, -// such as creating keys and assigning policies, by using the console. -// -// * Encrypt -// -// * Decrypt -// -// * GenerateDataKey -// -// * GenerateDataKeyWithoutPlaintext -// The service client's operations are safe to be used concurrently. -// It is not safe to mutate any of the client's properties though. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/kms-2014-11-01 +// KMS methods are safe to use concurrently. It is not safe to +// modify mutate any of the struct's properties though. type KMS struct { *client.Client } diff --git a/vendor/github.com/aws/aws-sdk-go/service/lambda/api.go b/vendor/github.com/aws/aws-sdk-go/service/lambda/api.go index 4a215f4eb..019cf5102 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/lambda/api.go +++ b/vendor/github.com/aws/aws-sdk-go/service/lambda/api.go @@ -1,12 +1,12 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. -// Package lambda provides a client for AWS Lambda. package lambda import ( "io" "time" + "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awsutil" "github.com/aws/aws-sdk-go/aws/request" "github.com/aws/aws-sdk-go/private/protocol" @@ -102,8 +102,23 @@ func (c *Lambda) AddPermissionRequest(input *AddPermissionInput) (req *request.R // func (c *Lambda) AddPermission(input *AddPermissionInput) (*AddPermissionOutput, error) { req, out := c.AddPermissionRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// AddPermissionWithContext is the same as AddPermission with the addition of +// the ability to pass a context and additional request options. +// +// See AddPermission 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 *Lambda) AddPermissionWithContext(ctx aws.Context, input *AddPermissionInput, opts ...request.Option) (*AddPermissionOutput, error) { + req, out := c.AddPermissionRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateAlias = "CreateAlias" @@ -182,8 +197,23 @@ func (c *Lambda) CreateAliasRequest(input *CreateAliasInput) (req *request.Reque // func (c *Lambda) CreateAlias(input *CreateAliasInput) (*AliasConfiguration, error) { req, out := c.CreateAliasRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateAliasWithContext is the same as CreateAlias with the addition of +// the ability to pass a context and additional request options. +// +// See CreateAlias for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *Lambda) CreateAliasWithContext(ctx aws.Context, input *CreateAliasInput, opts ...request.Option) (*AliasConfiguration, error) { + req, out := c.CreateAliasRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateEventSourceMapping = "CreateEventSourceMapping" @@ -282,8 +312,23 @@ func (c *Lambda) CreateEventSourceMappingRequest(input *CreateEventSourceMapping // func (c *Lambda) CreateEventSourceMapping(input *CreateEventSourceMappingInput) (*EventSourceMappingConfiguration, error) { req, out := c.CreateEventSourceMappingRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateEventSourceMappingWithContext is the same as CreateEventSourceMapping with the addition of +// the ability to pass a context and additional request options. +// +// See CreateEventSourceMapping 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 *Lambda) CreateEventSourceMappingWithContext(ctx aws.Context, input *CreateEventSourceMappingInput, opts ...request.Option) (*EventSourceMappingConfiguration, error) { + req, out := c.CreateEventSourceMappingRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateFunction = "CreateFunction" @@ -370,8 +415,23 @@ func (c *Lambda) CreateFunctionRequest(input *CreateFunctionInput) (req *request // func (c *Lambda) CreateFunction(input *CreateFunctionInput) (*FunctionConfiguration, error) { req, out := c.CreateFunctionRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateFunctionWithContext is the same as CreateFunction with the addition of +// the ability to pass a context and additional request options. +// +// See CreateFunction 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 *Lambda) CreateFunctionWithContext(ctx aws.Context, input *CreateFunctionInput, opts ...request.Option) (*FunctionConfiguration, error) { + req, out := c.CreateFunctionRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteAlias = "DeleteAlias" @@ -444,8 +504,23 @@ func (c *Lambda) DeleteAliasRequest(input *DeleteAliasInput) (req *request.Reque // func (c *Lambda) DeleteAlias(input *DeleteAliasInput) (*DeleteAliasOutput, error) { req, out := c.DeleteAliasRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteAliasWithContext is the same as DeleteAlias with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteAlias for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *Lambda) DeleteAliasWithContext(ctx aws.Context, input *DeleteAliasInput, opts ...request.Option) (*DeleteAliasOutput, error) { + req, out := c.DeleteAliasRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteEventSourceMapping = "DeleteEventSourceMapping" @@ -521,8 +596,23 @@ func (c *Lambda) DeleteEventSourceMappingRequest(input *DeleteEventSourceMapping // func (c *Lambda) DeleteEventSourceMapping(input *DeleteEventSourceMappingInput) (*EventSourceMappingConfiguration, error) { req, out := c.DeleteEventSourceMappingRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteEventSourceMappingWithContext is the same as DeleteEventSourceMapping with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteEventSourceMapping 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 *Lambda) DeleteEventSourceMappingWithContext(ctx aws.Context, input *DeleteEventSourceMappingInput, opts ...request.Option) (*EventSourceMappingConfiguration, error) { + req, out := c.DeleteEventSourceMappingRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteFunction = "DeleteFunction" @@ -611,8 +701,23 @@ func (c *Lambda) DeleteFunctionRequest(input *DeleteFunctionInput) (req *request // func (c *Lambda) DeleteFunction(input *DeleteFunctionInput) (*DeleteFunctionOutput, error) { req, out := c.DeleteFunctionRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteFunctionWithContext is the same as DeleteFunction with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteFunction 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 *Lambda) DeleteFunctionWithContext(ctx aws.Context, input *DeleteFunctionInput, opts ...request.Option) (*DeleteFunctionOutput, error) { + req, out := c.DeleteFunctionRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetAccountSettings = "GetAccountSettings" @@ -681,8 +786,23 @@ func (c *Lambda) GetAccountSettingsRequest(input *GetAccountSettingsInput) (req // func (c *Lambda) GetAccountSettings(input *GetAccountSettingsInput) (*GetAccountSettingsOutput, error) { req, out := c.GetAccountSettingsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetAccountSettingsWithContext is the same as GetAccountSettings with the addition of +// the ability to pass a context and additional request options. +// +// See GetAccountSettings 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 *Lambda) GetAccountSettingsWithContext(ctx aws.Context, input *GetAccountSettingsInput, opts ...request.Option) (*GetAccountSettingsOutput, error) { + req, out := c.GetAccountSettingsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetAlias = "GetAlias" @@ -758,8 +878,23 @@ func (c *Lambda) GetAliasRequest(input *GetAliasInput) (req *request.Request, ou // func (c *Lambda) GetAlias(input *GetAliasInput) (*AliasConfiguration, error) { req, out := c.GetAliasRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetAliasWithContext is the same as GetAlias with the addition of +// the ability to pass a context and additional request options. +// +// See GetAlias 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 *Lambda) GetAliasWithContext(ctx aws.Context, input *GetAliasInput, opts ...request.Option) (*AliasConfiguration, error) { + req, out := c.GetAliasRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetEventSourceMapping = "GetEventSourceMapping" @@ -834,8 +969,23 @@ func (c *Lambda) GetEventSourceMappingRequest(input *GetEventSourceMappingInput) // func (c *Lambda) GetEventSourceMapping(input *GetEventSourceMappingInput) (*EventSourceMappingConfiguration, error) { req, out := c.GetEventSourceMappingRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetEventSourceMappingWithContext is the same as GetEventSourceMapping with the addition of +// the ability to pass a context and additional request options. +// +// See GetEventSourceMapping 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 *Lambda) GetEventSourceMappingWithContext(ctx aws.Context, input *GetEventSourceMappingInput, opts ...request.Option) (*EventSourceMappingConfiguration, error) { + req, out := c.GetEventSourceMappingRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetFunction = "GetFunction" @@ -919,8 +1069,23 @@ func (c *Lambda) GetFunctionRequest(input *GetFunctionInput) (req *request.Reque // func (c *Lambda) GetFunction(input *GetFunctionInput) (*GetFunctionOutput, error) { req, out := c.GetFunctionRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetFunctionWithContext is the same as GetFunction with the addition of +// the ability to pass a context and additional request options. +// +// See GetFunction 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 *Lambda) GetFunctionWithContext(ctx aws.Context, input *GetFunctionInput, opts ...request.Option) (*GetFunctionOutput, error) { + req, out := c.GetFunctionRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetFunctionConfiguration = "GetFunctionConfiguration" @@ -1004,8 +1169,23 @@ func (c *Lambda) GetFunctionConfigurationRequest(input *GetFunctionConfiguration // func (c *Lambda) GetFunctionConfiguration(input *GetFunctionConfigurationInput) (*FunctionConfiguration, error) { req, out := c.GetFunctionConfigurationRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetFunctionConfigurationWithContext is the same as GetFunctionConfiguration with the addition of +// the ability to pass a context and additional request options. +// +// See GetFunctionConfiguration 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 *Lambda) GetFunctionConfigurationWithContext(ctx aws.Context, input *GetFunctionConfigurationInput, opts ...request.Option) (*FunctionConfiguration, error) { + req, out := c.GetFunctionConfigurationRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetPolicy = "GetPolicy" @@ -1058,8 +1238,6 @@ func (c *Lambda) GetPolicyRequest(input *GetPolicyInput) (req *request.Request, // the version or alias name using the Qualifier parameter. For more information // about versioning, see AWS Lambda Function Versioning and Aliases (http://docs.aws.amazon.com/lambda/latest/dg/versioning-aliases.html). // -// For information about adding permissions, see AddPermission. -// // You need permission for the lambda:GetPolicy action. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions @@ -1086,8 +1264,23 @@ func (c *Lambda) GetPolicyRequest(input *GetPolicyInput) (req *request.Request, // func (c *Lambda) GetPolicy(input *GetPolicyInput) (*GetPolicyOutput, error) { req, out := c.GetPolicyRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetPolicyWithContext is the same as GetPolicy with the addition of +// the ability to pass a context and additional request options. +// +// See GetPolicy 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 *Lambda) GetPolicyWithContext(ctx aws.Context, input *GetPolicyInput, opts ...request.Option) (*GetPolicyOutput, error) { + req, out := c.GetPolicyRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opInvoke = "Invoke" @@ -1225,8 +1418,23 @@ func (c *Lambda) InvokeRequest(input *InvokeInput) (req *request.Request, output // func (c *Lambda) Invoke(input *InvokeInput) (*InvokeOutput, error) { req, out := c.InvokeRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// InvokeWithContext is the same as Invoke with the addition of +// the ability to pass a context and additional request options. +// +// See Invoke 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 *Lambda) InvokeWithContext(ctx aws.Context, input *InvokeInput, opts ...request.Option) (*InvokeOutput, error) { + req, out := c.InvokeRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opInvokeAsync = "InvokeAsync" @@ -1303,8 +1511,23 @@ func (c *Lambda) InvokeAsyncRequest(input *InvokeAsyncInput) (req *request.Reque // func (c *Lambda) InvokeAsync(input *InvokeAsyncInput) (*InvokeAsyncOutput, error) { req, out := c.InvokeAsyncRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// InvokeAsyncWithContext is the same as InvokeAsync with the addition of +// the ability to pass a context and additional request options. +// +// See InvokeAsync 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 *Lambda) InvokeAsyncWithContext(ctx aws.Context, input *InvokeAsyncInput, opts ...request.Option) (*InvokeAsyncOutput, error) { + req, out := c.InvokeAsyncRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opListAliases = "ListAliases" @@ -1381,8 +1604,23 @@ func (c *Lambda) ListAliasesRequest(input *ListAliasesInput) (req *request.Reque // func (c *Lambda) ListAliases(input *ListAliasesInput) (*ListAliasesOutput, error) { req, out := c.ListAliasesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListAliasesWithContext is the same as ListAliases with the addition of +// the ability to pass a context and additional request options. +// +// See ListAliases for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *Lambda) ListAliasesWithContext(ctx aws.Context, input *ListAliasesInput, opts ...request.Option) (*ListAliasesOutput, error) { + req, out := c.ListAliasesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opListEventSourceMappings = "ListEventSourceMappings" @@ -1472,8 +1710,23 @@ func (c *Lambda) ListEventSourceMappingsRequest(input *ListEventSourceMappingsIn // func (c *Lambda) ListEventSourceMappings(input *ListEventSourceMappingsInput) (*ListEventSourceMappingsOutput, error) { req, out := c.ListEventSourceMappingsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListEventSourceMappingsWithContext is the same as ListEventSourceMappings with the addition of +// the ability to pass a context and additional request options. +// +// See ListEventSourceMappings 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 *Lambda) ListEventSourceMappingsWithContext(ctx aws.Context, input *ListEventSourceMappingsInput, opts ...request.Option) (*ListEventSourceMappingsOutput, error) { + req, out := c.ListEventSourceMappingsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // ListEventSourceMappingsPages iterates over the pages of a ListEventSourceMappings operation, @@ -1493,12 +1746,37 @@ func (c *Lambda) ListEventSourceMappings(input *ListEventSourceMappingsInput) (* // return pageNum <= 3 // }) // -func (c *Lambda) ListEventSourceMappingsPages(input *ListEventSourceMappingsInput, fn func(p *ListEventSourceMappingsOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.ListEventSourceMappingsRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*ListEventSourceMappingsOutput), lastPage) - }) +func (c *Lambda) ListEventSourceMappingsPages(input *ListEventSourceMappingsInput, fn func(*ListEventSourceMappingsOutput, bool) bool) error { + return c.ListEventSourceMappingsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListEventSourceMappingsPagesWithContext same as ListEventSourceMappingsPages 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 *Lambda) ListEventSourceMappingsPagesWithContext(ctx aws.Context, input *ListEventSourceMappingsInput, fn func(*ListEventSourceMappingsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListEventSourceMappingsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListEventSourceMappingsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*ListEventSourceMappingsOutput), !p.HasNextPage()) + } + return p.Err() } const opListFunctions = "ListFunctions" @@ -1575,8 +1853,23 @@ func (c *Lambda) ListFunctionsRequest(input *ListFunctionsInput) (req *request.R // func (c *Lambda) ListFunctions(input *ListFunctionsInput) (*ListFunctionsOutput, error) { req, out := c.ListFunctionsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListFunctionsWithContext is the same as ListFunctions with the addition of +// the ability to pass a context and additional request options. +// +// See ListFunctions 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 *Lambda) ListFunctionsWithContext(ctx aws.Context, input *ListFunctionsInput, opts ...request.Option) (*ListFunctionsOutput, error) { + req, out := c.ListFunctionsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // ListFunctionsPages iterates over the pages of a ListFunctions operation, @@ -1596,12 +1889,126 @@ func (c *Lambda) ListFunctions(input *ListFunctionsInput) (*ListFunctionsOutput, // return pageNum <= 3 // }) // -func (c *Lambda) ListFunctionsPages(input *ListFunctionsInput, fn func(p *ListFunctionsOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.ListFunctionsRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*ListFunctionsOutput), lastPage) - }) +func (c *Lambda) ListFunctionsPages(input *ListFunctionsInput, fn func(*ListFunctionsOutput, bool) bool) error { + return c.ListFunctionsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListFunctionsPagesWithContext same as ListFunctionsPages 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 *Lambda) ListFunctionsPagesWithContext(ctx aws.Context, input *ListFunctionsInput, fn func(*ListFunctionsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListFunctionsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListFunctionsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*ListFunctionsOutput), !p.HasNextPage()) + } + return p.Err() +} + +const opListTags = "ListTags" + +// ListTagsRequest generates a "aws/request.Request" representing the +// client's request for the ListTags operation. The "output" return +// value can be used to capture response data after the request's "Send" method +// is called. +// +// See ListTags for usage and error information. +// +// Creating a request object using this method should be used when you want to inject +// custom logic into the request's lifecycle using a custom handler, or if you want to +// access properties on the request object before or after sending the request. If +// you just want the service response, call the ListTags method directly +// instead. +// +// Note: You must call the "Send" method on the returned request object in order +// to execute the request. +// +// // Example sending a request using the ListTagsRequest method. +// req, resp := client.ListTagsRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +func (c *Lambda) ListTagsRequest(input *ListTagsInput) (req *request.Request, output *ListTagsOutput) { + op := &request.Operation{ + Name: opListTags, + HTTPMethod: "GET", + HTTPPath: "/2017-03-31/tags/{ARN}", + } + + if input == nil { + input = &ListTagsInput{} + } + + output = &ListTagsOutput{} + req = c.newRequest(op, input, output) + return +} + +// ListTags API operation for AWS Lambda. +// +// Returns a list of tags assigned to a function when supplied the function +// ARN (Amazon Resource Name). +// +// 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 Lambda's +// API operation ListTags for usage and error information. +// +// Returned Error Codes: +// * ErrCodeServiceException "ServiceException" +// The AWS Lambda service encountered an internal error. +// +// * ErrCodeResourceNotFoundException "ResourceNotFoundException" +// The resource (for example, a Lambda function or access policy statement) +// specified in the request does not exist. +// +// * ErrCodeInvalidParameterValueException "InvalidParameterValueException" +// One of the parameters in the request is invalid. For example, if you provided +// an IAM role for AWS Lambda to assume in the CreateFunction or the UpdateFunctionConfiguration +// API, that AWS Lambda is unable to assume you will get this exception. +// +// * ErrCodeTooManyRequestsException "TooManyRequestsException" +// +func (c *Lambda) ListTags(input *ListTagsInput) (*ListTagsOutput, error) { + req, out := c.ListTagsRequest(input) + return out, req.Send() +} + +// ListTagsWithContext is the same as ListTags with the addition of +// the ability to pass a context and additional request options. +// +// See ListTags 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 *Lambda) ListTagsWithContext(ctx aws.Context, input *ListTagsInput, opts ...request.Option) (*ListTagsOutput, error) { + req, out := c.ListTagsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opListVersionsByFunction = "ListVersionsByFunction" @@ -1674,8 +2081,23 @@ func (c *Lambda) ListVersionsByFunctionRequest(input *ListVersionsByFunctionInpu // func (c *Lambda) ListVersionsByFunction(input *ListVersionsByFunctionInput) (*ListVersionsByFunctionOutput, error) { req, out := c.ListVersionsByFunctionRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListVersionsByFunctionWithContext is the same as ListVersionsByFunction with the addition of +// the ability to pass a context and additional request options. +// +// See ListVersionsByFunction 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 *Lambda) ListVersionsByFunctionWithContext(ctx aws.Context, input *ListVersionsByFunctionInput, opts ...request.Option) (*ListVersionsByFunctionOutput, error) { + req, out := c.ListVersionsByFunctionRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opPublishVersion = "PublishVersion" @@ -1754,8 +2176,23 @@ func (c *Lambda) PublishVersionRequest(input *PublishVersionInput) (req *request // func (c *Lambda) PublishVersion(input *PublishVersionInput) (*FunctionConfiguration, error) { req, out := c.PublishVersionRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// PublishVersionWithContext is the same as PublishVersion with the addition of +// the ability to pass a context and additional request options. +// +// See PublishVersion 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 *Lambda) PublishVersionWithContext(ctx aws.Context, input *PublishVersionInput, opts ...request.Option) (*FunctionConfiguration, error) { + req, out := c.PublishVersionRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opRemovePermission = "RemovePermission" @@ -1841,8 +2278,206 @@ func (c *Lambda) RemovePermissionRequest(input *RemovePermissionInput) (req *req // func (c *Lambda) RemovePermission(input *RemovePermissionInput) (*RemovePermissionOutput, error) { req, out := c.RemovePermissionRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// RemovePermissionWithContext is the same as RemovePermission with the addition of +// the ability to pass a context and additional request options. +// +// See RemovePermission 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 *Lambda) RemovePermissionWithContext(ctx aws.Context, input *RemovePermissionInput, opts ...request.Option) (*RemovePermissionOutput, error) { + req, out := c.RemovePermissionRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opTagResource = "TagResource" + +// TagResourceRequest generates a "aws/request.Request" representing the +// client's request for the TagResource operation. The "output" return +// value can be used to capture response data after the request's "Send" method +// is called. +// +// See TagResource for usage and error information. +// +// Creating a request object using this method should be used when you want to inject +// custom logic into the request's lifecycle using a custom handler, or if you want to +// access properties on the request object before or after sending the request. If +// you just want the service response, call the TagResource method directly +// instead. +// +// Note: You must call the "Send" method on the returned request object in order +// to execute the request. +// +// // Example sending a request using the TagResourceRequest method. +// req, resp := client.TagResourceRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +func (c *Lambda) TagResourceRequest(input *TagResourceInput) (req *request.Request, output *TagResourceOutput) { + op := &request.Operation{ + Name: opTagResource, + HTTPMethod: "POST", + HTTPPath: "/2017-03-31/tags/{ARN}", + } + + if input == nil { + input = &TagResourceInput{} + } + + output = &TagResourceOutput{} + req = c.newRequest(op, input, output) + req.Handlers.Unmarshal.Remove(restjson.UnmarshalHandler) + req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) + return +} + +// TagResource API operation for AWS Lambda. +// +// Creates a list of tags (key-value pairs) on the Lambda function. Requires +// the Lambda function ARN (Amazon Resource Name). If a key is specified without +// a value, Lambda creates a tag with the specified key and a value of null. +// +// 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 Lambda's +// API operation TagResource for usage and error information. +// +// Returned Error Codes: +// * ErrCodeServiceException "ServiceException" +// The AWS Lambda service encountered an internal error. +// +// * ErrCodeResourceNotFoundException "ResourceNotFoundException" +// The resource (for example, a Lambda function or access policy statement) +// specified in the request does not exist. +// +// * ErrCodeInvalidParameterValueException "InvalidParameterValueException" +// One of the parameters in the request is invalid. For example, if you provided +// an IAM role for AWS Lambda to assume in the CreateFunction or the UpdateFunctionConfiguration +// API, that AWS Lambda is unable to assume you will get this exception. +// +// * ErrCodeTooManyRequestsException "TooManyRequestsException" +// +func (c *Lambda) TagResource(input *TagResourceInput) (*TagResourceOutput, error) { + req, out := c.TagResourceRequest(input) + return out, req.Send() +} + +// TagResourceWithContext is the same as TagResource with the addition of +// the ability to pass a context and additional request options. +// +// See TagResource for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *Lambda) TagResourceWithContext(ctx aws.Context, input *TagResourceInput, opts ...request.Option) (*TagResourceOutput, error) { + req, out := c.TagResourceRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opUntagResource = "UntagResource" + +// UntagResourceRequest generates a "aws/request.Request" representing the +// client's request for the UntagResource operation. The "output" return +// value can be used to capture response data after the request's "Send" method +// is called. +// +// See UntagResource for usage and error information. +// +// Creating a request object using this method should be used when you want to inject +// custom logic into the request's lifecycle using a custom handler, or if you want to +// access properties on the request object before or after sending the request. If +// you just want the service response, call the UntagResource method directly +// instead. +// +// Note: You must call the "Send" method on the returned request object in order +// to execute the request. +// +// // Example sending a request using the UntagResourceRequest method. +// req, resp := client.UntagResourceRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +func (c *Lambda) UntagResourceRequest(input *UntagResourceInput) (req *request.Request, output *UntagResourceOutput) { + op := &request.Operation{ + Name: opUntagResource, + HTTPMethod: "DELETE", + HTTPPath: "/2017-03-31/tags/{ARN}", + } + + if input == nil { + input = &UntagResourceInput{} + } + + output = &UntagResourceOutput{} + req = c.newRequest(op, input, output) + req.Handlers.Unmarshal.Remove(restjson.UnmarshalHandler) + req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) + return +} + +// UntagResource API operation for AWS Lambda. +// +// Removes tags from a Lambda function. Requires the function ARN (Amazon Resource +// Name). +// +// 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 Lambda's +// API operation UntagResource for usage and error information. +// +// Returned Error Codes: +// * ErrCodeServiceException "ServiceException" +// The AWS Lambda service encountered an internal error. +// +// * ErrCodeResourceNotFoundException "ResourceNotFoundException" +// The resource (for example, a Lambda function or access policy statement) +// specified in the request does not exist. +// +// * ErrCodeInvalidParameterValueException "InvalidParameterValueException" +// One of the parameters in the request is invalid. For example, if you provided +// an IAM role for AWS Lambda to assume in the CreateFunction or the UpdateFunctionConfiguration +// API, that AWS Lambda is unable to assume you will get this exception. +// +// * ErrCodeTooManyRequestsException "TooManyRequestsException" +// +func (c *Lambda) UntagResource(input *UntagResourceInput) (*UntagResourceOutput, error) { + req, out := c.UntagResourceRequest(input) + return out, req.Send() +} + +// UntagResourceWithContext is the same as UntagResource with the addition of +// the ability to pass a context and additional request options. +// +// See UntagResource for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *Lambda) UntagResourceWithContext(ctx aws.Context, input *UntagResourceInput, opts ...request.Option) (*UntagResourceOutput, error) { + req, out := c.UntagResourceRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opUpdateAlias = "UpdateAlias" @@ -1918,8 +2553,23 @@ func (c *Lambda) UpdateAliasRequest(input *UpdateAliasInput) (req *request.Reque // func (c *Lambda) UpdateAlias(input *UpdateAliasInput) (*AliasConfiguration, error) { req, out := c.UpdateAliasRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// UpdateAliasWithContext is the same as UpdateAlias with the addition of +// the ability to pass a context and additional request options. +// +// See UpdateAlias for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *Lambda) UpdateAliasWithContext(ctx aws.Context, input *UpdateAliasInput, opts ...request.Option) (*AliasConfiguration, error) { + req, out := c.UpdateAliasRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opUpdateEventSourceMapping = "UpdateEventSourceMapping" @@ -2010,8 +2660,23 @@ func (c *Lambda) UpdateEventSourceMappingRequest(input *UpdateEventSourceMapping // func (c *Lambda) UpdateEventSourceMapping(input *UpdateEventSourceMappingInput) (*EventSourceMappingConfiguration, error) { req, out := c.UpdateEventSourceMappingRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// UpdateEventSourceMappingWithContext is the same as UpdateEventSourceMapping with the addition of +// the ability to pass a context and additional request options. +// +// See UpdateEventSourceMapping 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 *Lambda) UpdateEventSourceMappingWithContext(ctx aws.Context, input *UpdateEventSourceMappingInput, opts ...request.Option) (*EventSourceMappingConfiguration, error) { + req, out := c.UpdateEventSourceMappingRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opUpdateFunctionCode = "UpdateFunctionCode" @@ -2094,8 +2759,23 @@ func (c *Lambda) UpdateFunctionCodeRequest(input *UpdateFunctionCodeInput) (req // func (c *Lambda) UpdateFunctionCode(input *UpdateFunctionCodeInput) (*FunctionConfiguration, error) { req, out := c.UpdateFunctionCodeRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// UpdateFunctionCodeWithContext is the same as UpdateFunctionCode with the addition of +// the ability to pass a context and additional request options. +// +// See UpdateFunctionCode 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 *Lambda) UpdateFunctionCodeWithContext(ctx aws.Context, input *UpdateFunctionCodeInput, opts ...request.Option) (*FunctionConfiguration, error) { + req, out := c.UpdateFunctionCodeRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opUpdateFunctionConfiguration = "UpdateFunctionConfiguration" @@ -2177,8 +2857,23 @@ func (c *Lambda) UpdateFunctionConfigurationRequest(input *UpdateFunctionConfigu // func (c *Lambda) UpdateFunctionConfiguration(input *UpdateFunctionConfigurationInput) (*FunctionConfiguration, error) { req, out := c.UpdateFunctionConfigurationRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// UpdateFunctionConfigurationWithContext is the same as UpdateFunctionConfiguration with the addition of +// the ability to pass a context and additional request options. +// +// See UpdateFunctionConfiguration 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 *Lambda) UpdateFunctionConfigurationWithContext(ctx aws.Context, input *UpdateFunctionConfigurationInput, opts ...request.Option) (*FunctionConfiguration, error) { + req, out := c.UpdateFunctionConfigurationRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // Provides limits of code size and concurrency associated with the current @@ -2201,8 +2896,8 @@ type AccountLimit struct { // The default limit is 100. ConcurrentExecutions *int64 `type:"integer"` - // Maximum size, in megabytes, of a code package you can upload per region. - // The default size is 75 GB. + // Maximum size, in bytes, of a code package you can upload per region. The + // default size is 75 GB. TotalCodeSize *int64 `type:"long"` } @@ -2296,7 +2991,7 @@ type AddPermissionInput struct { // Amazon Resource Name (ARN) of the function (for example, arn:aws:lambda:us-west-2:account-id:function:ThumbNail). // AWS Lambda also allows you to specify partial ARN (for example, account-id:Thumbnail). // Note that the length constraint applies only to the ARN. If you specify only - // the function name, it is limited to 64 character in length. + // the function name, it is limited to 64 characters in length. // // FunctionName is a required field FunctionName *string `location:"uri" locationName:"FunctionName" min:"1" type:"string" required:"true"` @@ -2330,24 +3025,23 @@ type AddPermissionInput struct { // arn:aws:lambda:aws-region:acct-id:function:function-name Qualifier *string `location:"querystring" locationName:"Qualifier" min:"1" type:"string"` - // This parameter is used for S3, SES, CloudWatch Logs and CloudWatch Rules - // only. The AWS account ID (without a hyphen) of the source owner. For example, - // if the SourceArn identifies a bucket, then this is the bucket owner's account - // ID. You can use this additional condition to ensure the bucket you specify - // is owned by a specific account (it is possible the bucket owner deleted the - // bucket and some other AWS account created the bucket). You can also use this - // condition to specify all sources (that is, you don't specify the SourceArn) - // owned by a specific account. + // This parameter is used for S3 and SES. The AWS account ID (without a hyphen) + // of the source owner. For example, if the SourceArn identifies a bucket, then + // this is the bucket owner's account ID. You can use this additional condition + // to ensure the bucket you specify is owned by a specific account (it is possible + // the bucket owner deleted the bucket and some other AWS account created the + // bucket). You can also use this condition to specify all sources (that is, + // you don't specify the SourceArn) owned by a specific account. SourceAccount *string `type:"string"` - // This is optional; however, when granting Amazon S3 permission to invoke your - // function, you should specify this field with the Amazon Resource Name (ARN) - // as its value. This ensures that only events generated from the specified - // source can invoke the function. + // This is optional; however, when granting permission to invoke your function, + // you should specify this field with the Amazon Resource Name (ARN) as its + // value. This ensures that only events generated from the specified source + // can invoke the function. // - // If you add a permission for the Amazon S3 principal without providing the - // source ARN, any AWS account that creates a mapping to your function ARN can - // send events to invoke your Lambda function from Amazon S3. + // If you add a permission without providing the source ARN, any AWS account + // that creates a mapping to your function ARN can send events to invoke your + // Lambda function. SourceArn *string `type:"string"` // A unique statement identifier. @@ -2529,7 +3223,9 @@ type CreateAliasInput struct { // Description of the alias. Description *string `type:"string"` - // Name of the Lambda function for which you want to create an alias. + // Name of the Lambda function for which you want to create an alias. Note that + // the length constraint applies only to the ARN. If you specify only the function + // name, it is limited to 64 characters in length. // // FunctionName is a required field FunctionName *string `location:"uri" locationName:"FunctionName" min:"1" type:"string" required:"true"` @@ -2642,7 +3338,7 @@ type CreateEventSourceMappingInput struct { // ID qualifier (for example, account-id:Thumbnail). // // Note that the length constraint applies only to the ARN. If you specify only - // the function name, it is limited to 64 character in length. + // the function name, it is limited to 64 characters in length. // // FunctionName is a required field FunctionName *string `min:"1" type:"string" required:"true"` @@ -2742,7 +3438,7 @@ type CreateFunctionInput struct { // Code is a required field Code *FunctionCode `type:"structure" required:"true"` - // The parent object that contains the target Amazon Resource Name (ARN) of + // The parent object that contains the target ARN (Amazon Resource Name) of // an Amazon SQS queue or Amazon SNS topic. DeadLetterConfig *DeadLetterConfig `type:"structure"` @@ -2756,7 +3452,8 @@ type CreateFunctionInput struct { // The name you want to assign to the function you are uploading. The function // names appear in the console and are returned in the ListFunctions API. Function // names are used to specify functions to other AWS Lambda API operations, such - // as Invoke. + // as Invoke. Note that the length constraint applies only to the ARN. If you + // specify only the function name, it is limited to 64 characters in length. // // FunctionName is a required field FunctionName *string `min:"1" type:"string" required:"true"` @@ -2795,22 +3492,30 @@ type CreateFunctionInput struct { // The runtime environment for the Lambda function you are uploading. // - // To use the Node.js runtime v4.3, set the value to "nodejs4.3". To use earlier - // runtime (v0.10.42), set the value to "nodejs". + // To use the Python runtime v3.6, set the value to "python3.6". To use the + // Python runtime v2.7, set the value to "python2.7". To use the Node.js runtime + // v6.10, set the value to "nodejs6.10". To use the Node.js runtime v4.3, set + // the value to "nodejs4.3". // // You can no longer create functions using the v0.10.42 runtime version as // of November, 2016. Existing functions will be supported until early 2017, - // but we recommend you migrate them to nodejs4.3 runtime version as soon as - // possible. + // but we recommend you migrate them to either nodejs6.10 or nodejs4.3 runtime + // version as soon as possible. // // Runtime is a required field Runtime *string `type:"string" required:"true" enum:"Runtime"` + // The list of tags (key-value pairs) assigned to the new function. + Tags map[string]*string `type:"map"` + // The function execution time at which Lambda should terminate the function. // Because the execution time has cost implications, we recommend you set this // value based on your expected execution time. The default is 3 seconds. Timeout *int64 `min:"1" type:"integer"` + // The parent object that contains your function's tracing settings. + TracingConfig *TracingConfig `type:"structure"` + // If your Lambda function accesses resources in a VPC, you provide this parameter // identifying the list of security group IDs and subnet IDs. These must belong // to the same VPC. You must provide at least one security group and one subnet @@ -2933,19 +3638,31 @@ func (s *CreateFunctionInput) SetRuntime(v string) *CreateFunctionInput { return s } +// SetTags sets the Tags field's value. +func (s *CreateFunctionInput) SetTags(v map[string]*string) *CreateFunctionInput { + s.Tags = v + return s +} + // SetTimeout sets the Timeout field's value. func (s *CreateFunctionInput) SetTimeout(v int64) *CreateFunctionInput { s.Timeout = &v return s } +// SetTracingConfig sets the TracingConfig field's value. +func (s *CreateFunctionInput) SetTracingConfig(v *TracingConfig) *CreateFunctionInput { + s.TracingConfig = v + return s +} + // SetVpcConfig sets the VpcConfig field's value. func (s *CreateFunctionInput) SetVpcConfig(v *VpcConfig) *CreateFunctionInput { s.VpcConfig = v return s } -// The parent object that contains the target Amazon Resource Name (ARN) of +// The parent object that contains the target ARN (Amazon Resource Name) of // an Amazon SQS queue or Amazon SNS topic. type DeadLetterConfig struct { _ struct{} `type:"structure"` @@ -2975,7 +3692,9 @@ type DeleteAliasInput struct { _ struct{} `type:"structure"` // The Lambda function name for which the alias is created. Deleting an alias - // does not delete the function version to which it is pointing. + // does not delete the function version to which it is pointing. Note that the + // length constraint applies only to the ARN. If you specify only the function + // name, it is limited to 64 characters in length. // // FunctionName is a required field FunctionName *string `location:"uri" locationName:"FunctionName" min:"1" type:"string" required:"true"` @@ -3094,7 +3813,7 @@ type DeleteFunctionInput struct { // Lambda also allows you to specify only the function name with the account // ID qualifier (for example, account-id:Thumbnail). Note that the length constraint // applies only to the ARN. If you specify only the function name, it is limited - // to 64 character in length. + // to 64 characters in length. // // FunctionName is a required field FunctionName *string `location:"uri" locationName:"FunctionName" min:"1" type:"string" required:"true"` @@ -3175,7 +3894,6 @@ type Environment struct { _ struct{} `type:"structure"` // The key-value pairs that represent your environment's configuration settings. - // The value you specify cannot contain a ",". Variables map[string]*string `type:"map"` } @@ -3480,7 +4198,7 @@ type FunctionConfiguration struct { // The size, in bytes, of the function .zip file you uploaded. CodeSize *int64 `type:"long"` - // The parent object that contains the target Amazon Resource Name (ARN) of + // The parent object that contains the target ARN (Amazon Resource Name) of // an Amazon SQS queue or Amazon SNS topic. DeadLetterConfig *DeadLetterConfig `type:"structure"` @@ -3493,7 +4211,9 @@ type FunctionConfiguration struct { // The Amazon Resource Name (ARN) assigned to the function. FunctionArn *string `type:"string"` - // The name of the function. + // The name of the function. Note that the length constraint applies only to + // the ARN. If you specify only the function name, it is limited to 64 characters + // in length. FunctionName *string `min:"1" type:"string"` // The function Lambda calls to begin executing your function. @@ -3516,9 +4236,6 @@ type FunctionConfiguration struct { Role *string `type:"string"` // The runtime environment for the Lambda function. - // - // To use the Node.js runtime v4.3, set the value to "nodejs4.3". To use earlier - // runtime (v0.10.42), set the value to "nodejs". Runtime *string `type:"string" enum:"Runtime"` // The function execution time at which Lambda should terminate the function. @@ -3526,6 +4243,9 @@ type FunctionConfiguration struct { // value based on your expected execution time. The default is 3 seconds. Timeout *int64 `min:"1" type:"integer"` + // The parent object that contains your function's tracing settings. + TracingConfig *TracingConfigResponse `type:"structure"` + // The version of the Lambda function. Version *string `min:"1" type:"string"` @@ -3627,6 +4347,12 @@ func (s *FunctionConfiguration) SetTimeout(v int64) *FunctionConfiguration { return s } +// SetTracingConfig sets the TracingConfig field's value. +func (s *FunctionConfiguration) SetTracingConfig(v *TracingConfigResponse) *FunctionConfiguration { + s.TracingConfig = v + return s +} + // SetVersion sets the Version field's value. func (s *FunctionConfiguration) SetVersion(v string) *FunctionConfiguration { s.Version = &v @@ -3692,7 +4418,9 @@ type GetAliasInput struct { // Function name for which the alias is created. An alias is a subresource that // exists only in the context of an existing Lambda function so you must specify - // the function name. + // the function name. Note that the length constraint applies only to the ARN. + // If you specify only the function name, it is limited to 64 characters in + // length. // // FunctionName is a required field FunctionName *string `location:"uri" locationName:"FunctionName" min:"1" type:"string" required:"true"` @@ -3795,7 +4523,7 @@ type GetFunctionConfigurationInput struct { // Amazon Resource Name (ARN) of the function (for example, arn:aws:lambda:us-west-2:account-id:function:ThumbNail). // AWS Lambda also allows you to specify a partial ARN (for example, account-id:Thumbnail). // Note that the length constraint applies only to the ARN. If you specify only - // the function name, it is limited to 64 character in length. + // the function name, it is limited to 64 characters in length. // // FunctionName is a required field FunctionName *string `location:"uri" locationName:"FunctionName" min:"1" type:"string" required:"true"` @@ -3861,7 +4589,7 @@ type GetFunctionInput struct { // Amazon Resource Name (ARN) of the function (for example, arn:aws:lambda:us-west-2:account-id:function:ThumbNail). // AWS Lambda also allows you to specify a partial ARN (for example, account-id:Thumbnail). // Note that the length constraint applies only to the ARN. If you specify only - // the function name, it is limited to 64 character in length. + // the function name, it is limited to 64 characters in length. // // FunctionName is a required field FunctionName *string `location:"uri" locationName:"FunctionName" min:"1" type:"string" required:"true"` @@ -3926,6 +4654,9 @@ type GetFunctionOutput struct { // A complex type that describes function metadata. Configuration *FunctionConfiguration `type:"structure"` + + // Returns the list of tags associated with the function. + Tags map[string]*string `type:"map"` } // String returns the string representation @@ -3950,6 +4681,12 @@ func (s *GetFunctionOutput) SetConfiguration(v *FunctionConfiguration) *GetFunct return s } +// SetTags sets the Tags field's value. +func (s *GetFunctionOutput) SetTags(v map[string]*string) *GetFunctionOutput { + s.Tags = v + return s +} + type GetPolicyInput struct { _ struct{} `type:"structure"` @@ -3962,7 +4699,7 @@ type GetPolicyInput struct { // Lambda also allows you to specify only the function name with the account // ID qualifier (for example, account-id:Thumbnail). Note that the length constraint // applies only to the ARN. If you specify only the function name, it is limited - // to 64 character in length. + // to 64 characters in length. // // FunctionName is a required field FunctionName *string `location:"uri" locationName:"FunctionName" min:"1" type:"string" required:"true"` @@ -4043,7 +4780,9 @@ func (s *GetPolicyOutput) SetPolicy(v string) *GetPolicyOutput { type InvokeAsyncInput struct { _ struct{} `deprecated:"true" type:"structure" payload:"InvokeArgs"` - // The Lambda function name. + // The Lambda function name. Note that the length constraint applies only to + // the ARN. If you specify only the function name, it is limited to 64 characters + // in length. // // FunctionName is a required field FunctionName *string `location:"uri" locationName:"FunctionName" min:"1" type:"string" required:"true"` @@ -4137,7 +4876,7 @@ type InvokeInput struct { // Amazon Resource Name (ARN) of the function (for example, arn:aws:lambda:us-west-2:account-id:function:ThumbNail). // AWS Lambda also allows you to specify a partial ARN (for example, account-id:Thumbnail). // Note that the length constraint applies only to the ARN. If you specify only - // the function name, it is limited to 64 character in length. + // the function name, it is limited to 64 characters in length. // // FunctionName is a required field FunctionName *string `location:"uri" locationName:"FunctionName" min:"1" type:"string" required:"true"` @@ -4305,7 +5044,9 @@ func (s *InvokeOutput) SetStatusCode(v int64) *InvokeOutput { type ListAliasesInput struct { _ struct{} `type:"structure"` - // Lambda function name for which the alias is created. + // Lambda function name for which the alias is created. Note that the length + // constraint applies only to the ARN. If you specify only the function name, + // it is limited to 64 characters in length. // // FunctionName is a required field FunctionName *string `location:"uri" locationName:"FunctionName" min:"1" type:"string" required:"true"` @@ -4428,7 +5169,7 @@ type ListEventSourceMappingsInput struct { // Lambda also allows you to specify only the function name with the account // ID qualifier (for example, account-id:Thumbnail). Note that the length constraint // applies only to the ARN. If you specify only the function name, it is limited - // to 64 character in length. + // to 64 characters in length. FunctionName *string `location:"querystring" locationName:"FunctionName" min:"1" type:"string"` // Optional string. An opaque pagination token returned from a previous ListEventSourceMappings @@ -4604,6 +5345,67 @@ func (s *ListFunctionsOutput) SetNextMarker(v string) *ListFunctionsOutput { return s } +type ListTagsInput struct { + _ struct{} `type:"structure"` + + // The ARN (Amazon Resource Name) of the function. + // + // Resource is a required field + Resource *string `location:"uri" locationName:"ARN" type:"string" required:"true"` +} + +// String returns the string representation +func (s ListTagsInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ListTagsInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *ListTagsInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "ListTagsInput"} + if s.Resource == nil { + invalidParams.Add(request.NewErrParamRequired("Resource")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetResource sets the Resource field's value. +func (s *ListTagsInput) SetResource(v string) *ListTagsInput { + s.Resource = &v + return s +} + +type ListTagsOutput struct { + _ struct{} `type:"structure"` + + // The list of tags assigned to the function. + Tags map[string]*string `type:"map"` +} + +// String returns the string representation +func (s ListTagsOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ListTagsOutput) GoString() string { + return s.String() +} + +// SetTags sets the Tags field's value. +func (s *ListTagsOutput) SetTags(v map[string]*string) *ListTagsOutput { + s.Tags = v + return s +} + type ListVersionsByFunctionInput struct { _ struct{} `type:"structure"` @@ -4612,7 +5414,7 @@ type ListVersionsByFunctionInput struct { // function (for example, arn:aws:lambda:us-west-2:account-id:function:ThumbNail). // AWS Lambda also allows you to specify a partial ARN (for example, account-id:Thumbnail). // Note that the length constraint applies only to the ARN. If you specify only - // the function name, it is limited to 64 character in length. + // the function name, it is limited to 64 characters in length. // // FunctionName is a required field FunctionName *string `location:"uri" locationName:"FunctionName" min:"1" type:"string" required:"true"` @@ -4723,7 +5525,7 @@ type PublishVersionInput struct { // arn:aws:lambda:us-west-2:account-id:function:ThumbNail). AWS Lambda also // allows you to specify a partial ARN (for example, account-id:Thumbnail). // Note that the length constraint applies only to the ARN. If you specify only - // the function name, it is limited to 64 character in length. + // the function name, it is limited to 64 characters in length. // // FunctionName is a required field FunctionName *string `location:"uri" locationName:"FunctionName" min:"1" type:"string" required:"true"` @@ -4782,7 +5584,7 @@ type RemovePermissionInput struct { // Amazon Resource Name (ARN) of the function (for example, arn:aws:lambda:us-west-2:account-id:function:ThumbNail). // AWS Lambda also allows you to specify a partial ARN (for example, account-id:Thumbnail). // Note that the length constraint applies only to the ARN. If you specify only - // the function name, it is limited to 64 character in length. + // the function name, it is limited to 64 characters in length. // // FunctionName is a required field FunctionName *string `location:"uri" locationName:"FunctionName" min:"1" type:"string" required:"true"` @@ -4866,13 +5668,199 @@ func (s RemovePermissionOutput) GoString() string { return s.String() } +type TagResourceInput struct { + _ struct{} `type:"structure"` + + // The ARN (Amazon Resource Name) of the Lambda function. + // + // Resource is a required field + Resource *string `location:"uri" locationName:"ARN" type:"string" required:"true"` + + // The list of tags (key-value pairs) you are assigning to the Lambda function. + // + // Tags is a required field + Tags map[string]*string `type:"map" required:"true"` +} + +// String returns the string representation +func (s TagResourceInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s TagResourceInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *TagResourceInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "TagResourceInput"} + if s.Resource == nil { + invalidParams.Add(request.NewErrParamRequired("Resource")) + } + if s.Tags == nil { + invalidParams.Add(request.NewErrParamRequired("Tags")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetResource sets the Resource field's value. +func (s *TagResourceInput) SetResource(v string) *TagResourceInput { + s.Resource = &v + return s +} + +// SetTags sets the Tags field's value. +func (s *TagResourceInput) SetTags(v map[string]*string) *TagResourceInput { + s.Tags = v + return s +} + +type TagResourceOutput struct { + _ struct{} `type:"structure"` +} + +// String returns the string representation +func (s TagResourceOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s TagResourceOutput) GoString() string { + return s.String() +} + +// The parent object that contains your function's tracing settings. +type TracingConfig struct { + _ struct{} `type:"structure"` + + // Can be either PassThrough or Active. If PassThrough, Lambda will only trace + // the request from an upstream service if it contains a tracing header with + // "sampled=1". If Active, Lambda will respect any tracing header it receives + // from an upstream service. If no tracing header is received, Lambda will call + // X-Ray for a tracing decision. + Mode *string `type:"string" enum:"TracingMode"` +} + +// String returns the string representation +func (s TracingConfig) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s TracingConfig) GoString() string { + return s.String() +} + +// SetMode sets the Mode field's value. +func (s *TracingConfig) SetMode(v string) *TracingConfig { + s.Mode = &v + return s +} + +// Parent object of the tracing information associated with your Lambda function. +type TracingConfigResponse struct { + _ struct{} `type:"structure"` + + // The tracing mode associated with your Lambda function. + Mode *string `type:"string" enum:"TracingMode"` +} + +// String returns the string representation +func (s TracingConfigResponse) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s TracingConfigResponse) GoString() string { + return s.String() +} + +// SetMode sets the Mode field's value. +func (s *TracingConfigResponse) SetMode(v string) *TracingConfigResponse { + s.Mode = &v + return s +} + +type UntagResourceInput struct { + _ struct{} `type:"structure"` + + // The ARN (Amazon Resource Name) of the function. + // + // Resource is a required field + Resource *string `location:"uri" locationName:"ARN" type:"string" required:"true"` + + // The list of tag keys to be deleted from the function. + // + // TagKeys is a required field + TagKeys []*string `location:"querystring" locationName:"tagKeys" type:"list" required:"true"` +} + +// String returns the string representation +func (s UntagResourceInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s UntagResourceInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *UntagResourceInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "UntagResourceInput"} + if s.Resource == nil { + invalidParams.Add(request.NewErrParamRequired("Resource")) + } + if s.TagKeys == nil { + invalidParams.Add(request.NewErrParamRequired("TagKeys")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetResource sets the Resource field's value. +func (s *UntagResourceInput) SetResource(v string) *UntagResourceInput { + s.Resource = &v + return s +} + +// SetTagKeys sets the TagKeys field's value. +func (s *UntagResourceInput) SetTagKeys(v []*string) *UntagResourceInput { + s.TagKeys = v + return s +} + +type UntagResourceOutput struct { + _ struct{} `type:"structure"` +} + +// String returns the string representation +func (s UntagResourceOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s UntagResourceOutput) GoString() string { + return s.String() +} + type UpdateAliasInput struct { _ struct{} `type:"structure"` // You can change the description of the alias using this parameter. Description *string `type:"string"` - // The function name for which the alias is created. + // The function name for which the alias is created. Note that the length constraint + // applies only to the ARN. If you specify only the function name, it is limited + // to 64 characters in length. // // FunctionName is a required field FunctionName *string `location:"uri" locationName:"FunctionName" min:"1" type:"string" required:"true"` @@ -4962,6 +5950,8 @@ type UpdateEventSourceMappingInput struct { // You can specify a function name (for example, Thumbnail) or you can specify // Amazon Resource Name (ARN) of the function (for example, arn:aws:lambda:us-west-2:account-id:function:ThumbNail). // AWS Lambda also allows you to specify a partial ARN (for example, account-id:Thumbnail). + // Note that the length constraint applies only to the ARN. If you specify only + // the function name, it is limited to 64 characters in length. // // If you are using versioning, you can also provide a qualified function ARN // (ARN that is qualified with function version or alias name as suffix). For @@ -5034,13 +6024,21 @@ func (s *UpdateEventSourceMappingInput) SetUUID(v string) *UpdateEventSourceMapp type UpdateFunctionCodeInput struct { _ struct{} `type:"structure"` + // This boolean parameter can be used to test your request to AWS Lambda to + // update the Lambda function and publish a version as an atomic operation. + // It will do all necessary computation and validation of your code but will + // not upload it or a publish a version. Each time this operation is invoked, + // the CodeSha256 hash value the provided code will also be computed and returned + // in the response. + DryRun *bool `type:"boolean"` + // The existing Lambda function name whose code you want to replace. // // You can specify a function name (for example, Thumbnail) or you can specify // Amazon Resource Name (ARN) of the function (for example, arn:aws:lambda:us-west-2:account-id:function:ThumbNail). // AWS Lambda also allows you to specify a partial ARN (for example, account-id:Thumbnail). // Note that the length constraint applies only to the ARN. If you specify only - // the function name, it is limited to 64 character in length. + // the function name, it is limited to 64 characters in length. // // FunctionName is a required field FunctionName *string `location:"uri" locationName:"FunctionName" min:"1" type:"string" required:"true"` @@ -5106,6 +6104,12 @@ func (s *UpdateFunctionCodeInput) Validate() error { return nil } +// SetDryRun sets the DryRun field's value. +func (s *UpdateFunctionCodeInput) SetDryRun(v bool) *UpdateFunctionCodeInput { + s.DryRun = &v + return s +} + // SetFunctionName sets the FunctionName field's value. func (s *UpdateFunctionCodeInput) SetFunctionName(v string) *UpdateFunctionCodeInput { s.FunctionName = &v @@ -5145,7 +6149,7 @@ func (s *UpdateFunctionCodeInput) SetZipFile(v []byte) *UpdateFunctionCodeInput type UpdateFunctionConfigurationInput struct { _ struct{} `type:"structure"` - // The parent object that contains the target Amazon Resource Name (ARN) of + // The parent object that contains the target ARN (Amazon Resource Name) of // an Amazon SQS queue or Amazon SNS topic. DeadLetterConfig *DeadLetterConfig `type:"structure"` @@ -5190,8 +6194,11 @@ type UpdateFunctionConfigurationInput struct { // The runtime environment for the Lambda function. // - // To use the Node.js runtime v4.3, set the value to "nodejs4.3". To use earlier - // runtime (v0.10.42), set the value to "nodejs". + // To use the Python runtime v3.6, set the value to "python3.6". To use the + // Python runtime v2.7, set the value to "python2.7". To use the Node.js runtime + // v6.10, set the value to "nodejs6.10". To use the Node.js runtime v4.3, set + // the value to "nodejs4.3". To use the Python runtime v3.6, set the value to + // "python3.6". To use the Python runtime v2.7, set the value to "python2.7". // // You can no longer downgrade to the v0.10.42 runtime version. This version // will no longer be supported as of early 2017. @@ -5202,6 +6209,9 @@ type UpdateFunctionConfigurationInput struct { // value based on your expected execution time. The default is 3 seconds. Timeout *int64 `min:"1" type:"integer"` + // The parent object that contains your function's tracing settings. + TracingConfig *TracingConfig `type:"structure"` + // If your Lambda function accesses resources in a VPC, you provide this parameter // identifying the list of security group IDs and subnet IDs. These must belong // to the same VPC. You must provide at least one security group and one subnet @@ -5301,6 +6311,12 @@ func (s *UpdateFunctionConfigurationInput) SetTimeout(v int64) *UpdateFunctionCo return s } +// SetTracingConfig sets the TracingConfig field's value. +func (s *UpdateFunctionConfigurationInput) SetTracingConfig(v *TracingConfig) *UpdateFunctionConfigurationInput { + s.TracingConfig = v + return s +} + // SetVpcConfig sets the VpcConfig field's value. func (s *UpdateFunctionConfigurationInput) SetVpcConfig(v *VpcConfig) *UpdateFunctionConfigurationInput { s.VpcConfig = v @@ -5422,12 +6438,18 @@ const ( // RuntimeNodejs43 is a Runtime enum value RuntimeNodejs43 = "nodejs4.3" + // RuntimeNodejs610 is a Runtime enum value + RuntimeNodejs610 = "nodejs6.10" + // RuntimeJava8 is a Runtime enum value RuntimeJava8 = "java8" // RuntimePython27 is a Runtime enum value RuntimePython27 = "python2.7" + // RuntimePython36 is a Runtime enum value + RuntimePython36 = "python3.6" + // RuntimeDotnetcore10 is a Runtime enum value RuntimeDotnetcore10 = "dotnetcore1.0" @@ -5445,3 +6467,11 @@ const ( // ThrottleReasonCallerRateLimitExceeded is a ThrottleReason enum value ThrottleReasonCallerRateLimitExceeded = "CallerRateLimitExceeded" ) + +const ( + // TracingModeActive is a TracingMode enum value + TracingModeActive = "Active" + + // TracingModePassThrough is a TracingMode enum value + TracingModePassThrough = "PassThrough" +) diff --git a/vendor/github.com/aws/aws-sdk-go/service/lambda/doc.go b/vendor/github.com/aws/aws-sdk-go/service/lambda/doc.go new file mode 100644 index 000000000..b51b2a41a --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/service/lambda/doc.go @@ -0,0 +1,84 @@ +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. + +// Package lambda provides the client and types for making API +// requests to AWS Lambda. +// +// Overview +// +// This is the AWS Lambda API Reference. The AWS Lambda Developer Guide provides +// additional information. For the service overview, see What is AWS Lambda +// (http://docs.aws.amazon.com/lambda/latest/dg/welcome.html), and for information +// about how the service works, see AWS Lambda: How it Works (http://docs.aws.amazon.com/lambda/latest/dg/lambda-introduction.html) +// in the AWS Lambda Developer Guide. +// +// See lambda package documentation for more information. +// https://docs.aws.amazon.com/sdk-for-go/api/service/lambda/ +// +// Using the Client +// +// To use the client for AWS Lambda you will first need +// to create a new instance of it. +// +// When creating a client for an AWS service you'll first need to have a Session +// already created. The Session provides configuration that can be shared +// between multiple service clients. Additional configuration can be applied to +// the Session and service's client when they are constructed. The aws package's +// Config type contains several fields such as Region for the AWS Region the +// client should make API requests too. The optional Config value can be provided +// as the variadic argument for Sessions and client creation. +// +// Once the service's client is created you can use it to make API requests the +// AWS service. These clients are safe to use concurrently. +// +// // Create a session to share configuration, and load external configuration. +// sess := session.Must(session.NewSession()) +// +// // Create the service's client with the session. +// svc := lambda.New(sess) +// +// See the SDK's documentation for more information on how to use service clients. +// https://docs.aws.amazon.com/sdk-for-go/api/ +// +// See aws package's Config type for more information on configuration options. +// https://docs.aws.amazon.com/sdk-for-go/api/aws/#Config +// +// See the AWS Lambda client Lambda for more +// information on creating the service's client. +// https://docs.aws.amazon.com/sdk-for-go/api/service/lambda/#New +// +// Once the client is created you can make an API request to the service. +// Each API method takes a input parameter, and returns the service response +// and an error. +// +// The API method will document which error codes the service can be returned +// by the operation if the service models the API operation's errors. These +// errors will also be available as const strings prefixed with "ErrCode". +// +// result, err := svc.AddPermission(params) +// if err != nil { +// // Cast err to awserr.Error to handle specific error codes. +// aerr, ok := err.(awserr.Error) +// if ok && aerr.Code() == { +// // Specific error code handling +// } +// return err +// } +// +// fmt.Println("AddPermission result:") +// fmt.Println(result) +// +// Using the Client with Context +// +// The service's client also provides methods to make API requests with a Context +// value. This allows you to control the timeout, and cancellation of pending +// requests. These methods also take request Option as variadic parameter to apply +// additional configuration to the API request. +// +// ctx := context.Background() +// +// result, err := svc.AddPermissionWithContext(ctx, params) +// +// See the request package documentation for more information on using Context pattern +// with the SDK. +// https://docs.aws.amazon.com/sdk-for-go/api/aws/request/ +package lambda diff --git a/vendor/github.com/aws/aws-sdk-go/service/lambda/errors.go b/vendor/github.com/aws/aws-sdk-go/service/lambda/errors.go index 1f9a11b6b..7ff426888 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/lambda/errors.go +++ b/vendor/github.com/aws/aws-sdk-go/service/lambda/errors.go @@ -1,4 +1,4 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. package lambda diff --git a/vendor/github.com/aws/aws-sdk-go/service/lambda/service.go b/vendor/github.com/aws/aws-sdk-go/service/lambda/service.go index abb46faa3..83c5e3094 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/lambda/service.go +++ b/vendor/github.com/aws/aws-sdk-go/service/lambda/service.go @@ -1,4 +1,4 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. package lambda @@ -11,15 +11,12 @@ import ( "github.com/aws/aws-sdk-go/private/protocol/restjson" ) -// Overview +// Lambda provides the API operation methods for making requests to +// AWS Lambda. See this package's package overview docs +// for details on the service. // -// This is the AWS Lambda API Reference. The AWS Lambda Developer Guide provides -// additional information. For the service overview, see What is AWS Lambda -// (http://docs.aws.amazon.com/lambda/latest/dg/welcome.html), and for information -// about how the service works, see AWS Lambda: How it Works (http://docs.aws.amazon.com/lambda/latest/dg/lambda-introduction.html) -// in the AWS Lambda Developer Guide. -// The service client's operations are safe to be used concurrently. -// It is not safe to mutate any of the client's properties though. +// Lambda methods are safe to use concurrently. It is not safe to +// modify mutate any of the struct's properties though. type Lambda struct { *client.Client } diff --git a/vendor/github.com/aws/aws-sdk-go/service/lightsail/api.go b/vendor/github.com/aws/aws-sdk-go/service/lightsail/api.go index 06a44736e..13bfbb577 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/lightsail/api.go +++ b/vendor/github.com/aws/aws-sdk-go/service/lightsail/api.go @@ -1,11 +1,11 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. -// Package lightsail provides a client for Amazon Lightsail. package lightsail import ( "time" + "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awsutil" "github.com/aws/aws-sdk-go/aws/request" ) @@ -92,8 +92,23 @@ func (c *Lightsail) AllocateStaticIpRequest(input *AllocateStaticIpInput) (req * // Please also see https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/AllocateStaticIp func (c *Lightsail) AllocateStaticIp(input *AllocateStaticIpInput) (*AllocateStaticIpOutput, error) { req, out := c.AllocateStaticIpRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// AllocateStaticIpWithContext is the same as AllocateStaticIp with the addition of +// the ability to pass a context and additional request options. +// +// See AllocateStaticIp 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 *Lightsail) AllocateStaticIpWithContext(ctx aws.Context, input *AllocateStaticIpInput, opts ...request.Option) (*AllocateStaticIpOutput, error) { + req, out := c.AllocateStaticIpRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opAttachStaticIp = "AttachStaticIp" @@ -178,8 +193,23 @@ func (c *Lightsail) AttachStaticIpRequest(input *AttachStaticIpInput) (req *requ // Please also see https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/AttachStaticIp func (c *Lightsail) AttachStaticIp(input *AttachStaticIpInput) (*AttachStaticIpOutput, error) { req, out := c.AttachStaticIpRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// AttachStaticIpWithContext is the same as AttachStaticIp with the addition of +// the ability to pass a context and additional request options. +// +// See AttachStaticIp 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 *Lightsail) AttachStaticIpWithContext(ctx aws.Context, input *AttachStaticIpInput, opts ...request.Option) (*AttachStaticIpOutput, error) { + req, out := c.AttachStaticIpRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCloseInstancePublicPorts = "CloseInstancePublicPorts" @@ -264,8 +294,23 @@ func (c *Lightsail) CloseInstancePublicPortsRequest(input *CloseInstancePublicPo // Please also see https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/CloseInstancePublicPorts func (c *Lightsail) CloseInstancePublicPorts(input *CloseInstancePublicPortsInput) (*CloseInstancePublicPortsOutput, error) { req, out := c.CloseInstancePublicPortsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CloseInstancePublicPortsWithContext is the same as CloseInstancePublicPorts with the addition of +// the ability to pass a context and additional request options. +// +// See CloseInstancePublicPorts 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 *Lightsail) CloseInstancePublicPortsWithContext(ctx aws.Context, input *CloseInstancePublicPortsInput, opts ...request.Option) (*CloseInstancePublicPortsOutput, error) { + req, out := c.CloseInstancePublicPortsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateDomain = "CreateDomain" @@ -350,8 +395,23 @@ func (c *Lightsail) CreateDomainRequest(input *CreateDomainInput) (req *request. // Please also see https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/CreateDomain func (c *Lightsail) CreateDomain(input *CreateDomainInput) (*CreateDomainOutput, error) { req, out := c.CreateDomainRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateDomainWithContext is the same as CreateDomain with the addition of +// the ability to pass a context and additional request options. +// +// See CreateDomain 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 *Lightsail) CreateDomainWithContext(ctx aws.Context, input *CreateDomainInput, opts ...request.Option) (*CreateDomainOutput, error) { + req, out := c.CreateDomainRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateDomainEntry = "CreateDomainEntry" @@ -437,8 +497,23 @@ func (c *Lightsail) CreateDomainEntryRequest(input *CreateDomainEntryInput) (req // Please also see https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/CreateDomainEntry func (c *Lightsail) CreateDomainEntry(input *CreateDomainEntryInput) (*CreateDomainEntryOutput, error) { req, out := c.CreateDomainEntryRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateDomainEntryWithContext is the same as CreateDomainEntry with the addition of +// the ability to pass a context and additional request options. +// +// See CreateDomainEntry 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 *Lightsail) CreateDomainEntryWithContext(ctx aws.Context, input *CreateDomainEntryInput, opts ...request.Option) (*CreateDomainEntryOutput, error) { + req, out := c.CreateDomainEntryRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateInstanceSnapshot = "CreateInstanceSnapshot" @@ -524,8 +599,23 @@ func (c *Lightsail) CreateInstanceSnapshotRequest(input *CreateInstanceSnapshotI // Please also see https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/CreateInstanceSnapshot func (c *Lightsail) CreateInstanceSnapshot(input *CreateInstanceSnapshotInput) (*CreateInstanceSnapshotOutput, error) { req, out := c.CreateInstanceSnapshotRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateInstanceSnapshotWithContext is the same as CreateInstanceSnapshot with the addition of +// the ability to pass a context and additional request options. +// +// See CreateInstanceSnapshot 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 *Lightsail) CreateInstanceSnapshotWithContext(ctx aws.Context, input *CreateInstanceSnapshotInput, opts ...request.Option) (*CreateInstanceSnapshotOutput, error) { + req, out := c.CreateInstanceSnapshotRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateInstances = "CreateInstances" @@ -610,8 +700,23 @@ func (c *Lightsail) CreateInstancesRequest(input *CreateInstancesInput) (req *re // Please also see https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/CreateInstances func (c *Lightsail) CreateInstances(input *CreateInstancesInput) (*CreateInstancesOutput, error) { req, out := c.CreateInstancesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateInstancesWithContext is the same as CreateInstances with the addition of +// the ability to pass a context and additional request options. +// +// See CreateInstances 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 *Lightsail) CreateInstancesWithContext(ctx aws.Context, input *CreateInstancesInput, opts ...request.Option) (*CreateInstancesOutput, error) { + req, out := c.CreateInstancesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateInstancesFromSnapshot = "CreateInstancesFromSnapshot" @@ -697,8 +802,23 @@ func (c *Lightsail) CreateInstancesFromSnapshotRequest(input *CreateInstancesFro // Please also see https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/CreateInstancesFromSnapshot func (c *Lightsail) CreateInstancesFromSnapshot(input *CreateInstancesFromSnapshotInput) (*CreateInstancesFromSnapshotOutput, error) { req, out := c.CreateInstancesFromSnapshotRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateInstancesFromSnapshotWithContext is the same as CreateInstancesFromSnapshot with the addition of +// the ability to pass a context and additional request options. +// +// See CreateInstancesFromSnapshot 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 *Lightsail) CreateInstancesFromSnapshotWithContext(ctx aws.Context, input *CreateInstancesFromSnapshotInput, opts ...request.Option) (*CreateInstancesFromSnapshotOutput, error) { + req, out := c.CreateInstancesFromSnapshotRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateKeyPair = "CreateKeyPair" @@ -783,8 +903,23 @@ func (c *Lightsail) CreateKeyPairRequest(input *CreateKeyPairInput) (req *reques // Please also see https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/CreateKeyPair func (c *Lightsail) CreateKeyPair(input *CreateKeyPairInput) (*CreateKeyPairOutput, error) { req, out := c.CreateKeyPairRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateKeyPairWithContext is the same as CreateKeyPair with the addition of +// the ability to pass a context and additional request options. +// +// See CreateKeyPair 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 *Lightsail) CreateKeyPairWithContext(ctx aws.Context, input *CreateKeyPairInput, opts ...request.Option) (*CreateKeyPairOutput, error) { + req, out := c.CreateKeyPairRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteDomain = "DeleteDomain" @@ -869,8 +1004,23 @@ func (c *Lightsail) DeleteDomainRequest(input *DeleteDomainInput) (req *request. // Please also see https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/DeleteDomain func (c *Lightsail) DeleteDomain(input *DeleteDomainInput) (*DeleteDomainOutput, error) { req, out := c.DeleteDomainRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteDomainWithContext is the same as DeleteDomain with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteDomain 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 *Lightsail) DeleteDomainWithContext(ctx aws.Context, input *DeleteDomainInput, opts ...request.Option) (*DeleteDomainOutput, error) { + req, out := c.DeleteDomainRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteDomainEntry = "DeleteDomainEntry" @@ -955,8 +1105,23 @@ func (c *Lightsail) DeleteDomainEntryRequest(input *DeleteDomainEntryInput) (req // Please also see https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/DeleteDomainEntry func (c *Lightsail) DeleteDomainEntry(input *DeleteDomainEntryInput) (*DeleteDomainEntryOutput, error) { req, out := c.DeleteDomainEntryRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteDomainEntryWithContext is the same as DeleteDomainEntry with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteDomainEntry 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 *Lightsail) DeleteDomainEntryWithContext(ctx aws.Context, input *DeleteDomainEntryInput, opts ...request.Option) (*DeleteDomainEntryOutput, error) { + req, out := c.DeleteDomainEntryRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteInstance = "DeleteInstance" @@ -1041,8 +1206,23 @@ func (c *Lightsail) DeleteInstanceRequest(input *DeleteInstanceInput) (req *requ // Please also see https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/DeleteInstance func (c *Lightsail) DeleteInstance(input *DeleteInstanceInput) (*DeleteInstanceOutput, error) { req, out := c.DeleteInstanceRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteInstanceWithContext is the same as DeleteInstance with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteInstance 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 *Lightsail) DeleteInstanceWithContext(ctx aws.Context, input *DeleteInstanceInput, opts ...request.Option) (*DeleteInstanceOutput, error) { + req, out := c.DeleteInstanceRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteInstanceSnapshot = "DeleteInstanceSnapshot" @@ -1127,8 +1307,23 @@ func (c *Lightsail) DeleteInstanceSnapshotRequest(input *DeleteInstanceSnapshotI // Please also see https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/DeleteInstanceSnapshot func (c *Lightsail) DeleteInstanceSnapshot(input *DeleteInstanceSnapshotInput) (*DeleteInstanceSnapshotOutput, error) { req, out := c.DeleteInstanceSnapshotRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteInstanceSnapshotWithContext is the same as DeleteInstanceSnapshot with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteInstanceSnapshot 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 *Lightsail) DeleteInstanceSnapshotWithContext(ctx aws.Context, input *DeleteInstanceSnapshotInput, opts ...request.Option) (*DeleteInstanceSnapshotOutput, error) { + req, out := c.DeleteInstanceSnapshotRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteKeyPair = "DeleteKeyPair" @@ -1213,8 +1408,23 @@ func (c *Lightsail) DeleteKeyPairRequest(input *DeleteKeyPairInput) (req *reques // Please also see https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/DeleteKeyPair func (c *Lightsail) DeleteKeyPair(input *DeleteKeyPairInput) (*DeleteKeyPairOutput, error) { req, out := c.DeleteKeyPairRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteKeyPairWithContext is the same as DeleteKeyPair with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteKeyPair 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 *Lightsail) DeleteKeyPairWithContext(ctx aws.Context, input *DeleteKeyPairInput, opts ...request.Option) (*DeleteKeyPairOutput, error) { + req, out := c.DeleteKeyPairRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDetachStaticIp = "DetachStaticIp" @@ -1299,8 +1509,23 @@ func (c *Lightsail) DetachStaticIpRequest(input *DetachStaticIpInput) (req *requ // Please also see https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/DetachStaticIp func (c *Lightsail) DetachStaticIp(input *DetachStaticIpInput) (*DetachStaticIpOutput, error) { req, out := c.DetachStaticIpRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DetachStaticIpWithContext is the same as DetachStaticIp with the addition of +// the ability to pass a context and additional request options. +// +// See DetachStaticIp 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 *Lightsail) DetachStaticIpWithContext(ctx aws.Context, input *DetachStaticIpInput, opts ...request.Option) (*DetachStaticIpOutput, error) { + req, out := c.DetachStaticIpRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDownloadDefaultKeyPair = "DownloadDefaultKeyPair" @@ -1385,8 +1610,23 @@ func (c *Lightsail) DownloadDefaultKeyPairRequest(input *DownloadDefaultKeyPairI // Please also see https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/DownloadDefaultKeyPair func (c *Lightsail) DownloadDefaultKeyPair(input *DownloadDefaultKeyPairInput) (*DownloadDefaultKeyPairOutput, error) { req, out := c.DownloadDefaultKeyPairRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DownloadDefaultKeyPairWithContext is the same as DownloadDefaultKeyPair with the addition of +// the ability to pass a context and additional request options. +// +// See DownloadDefaultKeyPair 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 *Lightsail) DownloadDefaultKeyPairWithContext(ctx aws.Context, input *DownloadDefaultKeyPairInput, opts ...request.Option) (*DownloadDefaultKeyPairOutput, error) { + req, out := c.DownloadDefaultKeyPairRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetActiveNames = "GetActiveNames" @@ -1471,8 +1711,23 @@ func (c *Lightsail) GetActiveNamesRequest(input *GetActiveNamesInput) (req *requ // Please also see https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetActiveNames func (c *Lightsail) GetActiveNames(input *GetActiveNamesInput) (*GetActiveNamesOutput, error) { req, out := c.GetActiveNamesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetActiveNamesWithContext is the same as GetActiveNames with the addition of +// the ability to pass a context and additional request options. +// +// See GetActiveNames 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 *Lightsail) GetActiveNamesWithContext(ctx aws.Context, input *GetActiveNamesInput, opts ...request.Option) (*GetActiveNamesOutput, error) { + req, out := c.GetActiveNamesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetBlueprints = "GetBlueprints" @@ -1560,8 +1815,23 @@ func (c *Lightsail) GetBlueprintsRequest(input *GetBlueprintsInput) (req *reques // Please also see https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetBlueprints func (c *Lightsail) GetBlueprints(input *GetBlueprintsInput) (*GetBlueprintsOutput, error) { req, out := c.GetBlueprintsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetBlueprintsWithContext is the same as GetBlueprints with the addition of +// the ability to pass a context and additional request options. +// +// See GetBlueprints 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 *Lightsail) GetBlueprintsWithContext(ctx aws.Context, input *GetBlueprintsInput, opts ...request.Option) (*GetBlueprintsOutput, error) { + req, out := c.GetBlueprintsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetBundles = "GetBundles" @@ -1647,8 +1917,23 @@ func (c *Lightsail) GetBundlesRequest(input *GetBundlesInput) (req *request.Requ // Please also see https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetBundles func (c *Lightsail) GetBundles(input *GetBundlesInput) (*GetBundlesOutput, error) { req, out := c.GetBundlesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetBundlesWithContext is the same as GetBundles with the addition of +// the ability to pass a context and additional request options. +// +// See GetBundles 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 *Lightsail) GetBundlesWithContext(ctx aws.Context, input *GetBundlesInput, opts ...request.Option) (*GetBundlesOutput, error) { + req, out := c.GetBundlesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetDomain = "GetDomain" @@ -1733,8 +2018,23 @@ func (c *Lightsail) GetDomainRequest(input *GetDomainInput) (req *request.Reques // Please also see https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetDomain func (c *Lightsail) GetDomain(input *GetDomainInput) (*GetDomainOutput, error) { req, out := c.GetDomainRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetDomainWithContext is the same as GetDomain with the addition of +// the ability to pass a context and additional request options. +// +// See GetDomain 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 *Lightsail) GetDomainWithContext(ctx aws.Context, input *GetDomainInput, opts ...request.Option) (*GetDomainOutput, error) { + req, out := c.GetDomainRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetDomains = "GetDomains" @@ -1819,8 +2119,23 @@ func (c *Lightsail) GetDomainsRequest(input *GetDomainsInput) (req *request.Requ // Please also see https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetDomains func (c *Lightsail) GetDomains(input *GetDomainsInput) (*GetDomainsOutput, error) { req, out := c.GetDomainsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetDomainsWithContext is the same as GetDomains with the addition of +// the ability to pass a context and additional request options. +// +// See GetDomains 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 *Lightsail) GetDomainsWithContext(ctx aws.Context, input *GetDomainsInput, opts ...request.Option) (*GetDomainsOutput, error) { + req, out := c.GetDomainsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetInstance = "GetInstance" @@ -1906,8 +2221,23 @@ func (c *Lightsail) GetInstanceRequest(input *GetInstanceInput) (req *request.Re // Please also see https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetInstance func (c *Lightsail) GetInstance(input *GetInstanceInput) (*GetInstanceOutput, error) { req, out := c.GetInstanceRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetInstanceWithContext is the same as GetInstance with the addition of +// the ability to pass a context and additional request options. +// +// See GetInstance 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 *Lightsail) GetInstanceWithContext(ctx aws.Context, input *GetInstanceInput, opts ...request.Option) (*GetInstanceOutput, error) { + req, out := c.GetInstanceRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetInstanceAccessDetails = "GetInstanceAccessDetails" @@ -1993,8 +2323,23 @@ func (c *Lightsail) GetInstanceAccessDetailsRequest(input *GetInstanceAccessDeta // Please also see https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetInstanceAccessDetails func (c *Lightsail) GetInstanceAccessDetails(input *GetInstanceAccessDetailsInput) (*GetInstanceAccessDetailsOutput, error) { req, out := c.GetInstanceAccessDetailsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetInstanceAccessDetailsWithContext is the same as GetInstanceAccessDetails with the addition of +// the ability to pass a context and additional request options. +// +// See GetInstanceAccessDetails 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 *Lightsail) GetInstanceAccessDetailsWithContext(ctx aws.Context, input *GetInstanceAccessDetailsInput, opts ...request.Option) (*GetInstanceAccessDetailsOutput, error) { + req, out := c.GetInstanceAccessDetailsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetInstanceMetricData = "GetInstanceMetricData" @@ -2080,8 +2425,23 @@ func (c *Lightsail) GetInstanceMetricDataRequest(input *GetInstanceMetricDataInp // Please also see https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetInstanceMetricData func (c *Lightsail) GetInstanceMetricData(input *GetInstanceMetricDataInput) (*GetInstanceMetricDataOutput, error) { req, out := c.GetInstanceMetricDataRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetInstanceMetricDataWithContext is the same as GetInstanceMetricData with the addition of +// the ability to pass a context and additional request options. +// +// See GetInstanceMetricData 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 *Lightsail) GetInstanceMetricDataWithContext(ctx aws.Context, input *GetInstanceMetricDataInput, opts ...request.Option) (*GetInstanceMetricDataOutput, error) { + req, out := c.GetInstanceMetricDataRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetInstancePortStates = "GetInstancePortStates" @@ -2166,8 +2526,23 @@ func (c *Lightsail) GetInstancePortStatesRequest(input *GetInstancePortStatesInp // Please also see https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetInstancePortStates func (c *Lightsail) GetInstancePortStates(input *GetInstancePortStatesInput) (*GetInstancePortStatesOutput, error) { req, out := c.GetInstancePortStatesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetInstancePortStatesWithContext is the same as GetInstancePortStates with the addition of +// the ability to pass a context and additional request options. +// +// See GetInstancePortStates 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 *Lightsail) GetInstancePortStatesWithContext(ctx aws.Context, input *GetInstancePortStatesInput, opts ...request.Option) (*GetInstancePortStatesOutput, error) { + req, out := c.GetInstancePortStatesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetInstanceSnapshot = "GetInstanceSnapshot" @@ -2252,8 +2627,23 @@ func (c *Lightsail) GetInstanceSnapshotRequest(input *GetInstanceSnapshotInput) // Please also see https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetInstanceSnapshot func (c *Lightsail) GetInstanceSnapshot(input *GetInstanceSnapshotInput) (*GetInstanceSnapshotOutput, error) { req, out := c.GetInstanceSnapshotRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetInstanceSnapshotWithContext is the same as GetInstanceSnapshot with the addition of +// the ability to pass a context and additional request options. +// +// See GetInstanceSnapshot 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 *Lightsail) GetInstanceSnapshotWithContext(ctx aws.Context, input *GetInstanceSnapshotInput, opts ...request.Option) (*GetInstanceSnapshotOutput, error) { + req, out := c.GetInstanceSnapshotRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetInstanceSnapshots = "GetInstanceSnapshots" @@ -2338,8 +2728,23 @@ func (c *Lightsail) GetInstanceSnapshotsRequest(input *GetInstanceSnapshotsInput // Please also see https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetInstanceSnapshots func (c *Lightsail) GetInstanceSnapshots(input *GetInstanceSnapshotsInput) (*GetInstanceSnapshotsOutput, error) { req, out := c.GetInstanceSnapshotsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetInstanceSnapshotsWithContext is the same as GetInstanceSnapshots with the addition of +// the ability to pass a context and additional request options. +// +// See GetInstanceSnapshots 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 *Lightsail) GetInstanceSnapshotsWithContext(ctx aws.Context, input *GetInstanceSnapshotsInput, opts ...request.Option) (*GetInstanceSnapshotsOutput, error) { + req, out := c.GetInstanceSnapshotsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetInstanceState = "GetInstanceState" @@ -2424,8 +2829,23 @@ func (c *Lightsail) GetInstanceStateRequest(input *GetInstanceStateInput) (req * // Please also see https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetInstanceState func (c *Lightsail) GetInstanceState(input *GetInstanceStateInput) (*GetInstanceStateOutput, error) { req, out := c.GetInstanceStateRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetInstanceStateWithContext is the same as GetInstanceState with the addition of +// the ability to pass a context and additional request options. +// +// See GetInstanceState 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 *Lightsail) GetInstanceStateWithContext(ctx aws.Context, input *GetInstanceStateInput, opts ...request.Option) (*GetInstanceStateOutput, error) { + req, out := c.GetInstanceStateRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetInstances = "GetInstances" @@ -2511,8 +2931,23 @@ func (c *Lightsail) GetInstancesRequest(input *GetInstancesInput) (req *request. // Please also see https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetInstances func (c *Lightsail) GetInstances(input *GetInstancesInput) (*GetInstancesOutput, error) { req, out := c.GetInstancesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetInstancesWithContext is the same as GetInstances with the addition of +// the ability to pass a context and additional request options. +// +// See GetInstances 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 *Lightsail) GetInstancesWithContext(ctx aws.Context, input *GetInstancesInput, opts ...request.Option) (*GetInstancesOutput, error) { + req, out := c.GetInstancesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetKeyPair = "GetKeyPair" @@ -2597,8 +3032,23 @@ func (c *Lightsail) GetKeyPairRequest(input *GetKeyPairInput) (req *request.Requ // Please also see https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetKeyPair func (c *Lightsail) GetKeyPair(input *GetKeyPairInput) (*GetKeyPairOutput, error) { req, out := c.GetKeyPairRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetKeyPairWithContext is the same as GetKeyPair with the addition of +// the ability to pass a context and additional request options. +// +// See GetKeyPair 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 *Lightsail) GetKeyPairWithContext(ctx aws.Context, input *GetKeyPairInput, opts ...request.Option) (*GetKeyPairOutput, error) { + req, out := c.GetKeyPairRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetKeyPairs = "GetKeyPairs" @@ -2683,8 +3133,23 @@ func (c *Lightsail) GetKeyPairsRequest(input *GetKeyPairsInput) (req *request.Re // Please also see https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetKeyPairs func (c *Lightsail) GetKeyPairs(input *GetKeyPairsInput) (*GetKeyPairsOutput, error) { req, out := c.GetKeyPairsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetKeyPairsWithContext is the same as GetKeyPairs with the addition of +// the ability to pass a context and additional request options. +// +// See GetKeyPairs 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 *Lightsail) GetKeyPairsWithContext(ctx aws.Context, input *GetKeyPairsInput, opts ...request.Option) (*GetKeyPairsOutput, error) { + req, out := c.GetKeyPairsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetOperation = "GetOperation" @@ -2771,8 +3236,23 @@ func (c *Lightsail) GetOperationRequest(input *GetOperationInput) (req *request. // Please also see https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetOperation func (c *Lightsail) GetOperation(input *GetOperationInput) (*GetOperationOutput, error) { req, out := c.GetOperationRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetOperationWithContext is the same as GetOperation with the addition of +// the ability to pass a context and additional request options. +// +// See GetOperation 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 *Lightsail) GetOperationWithContext(ctx aws.Context, input *GetOperationInput, opts ...request.Option) (*GetOperationOutput, error) { + req, out := c.GetOperationRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetOperations = "GetOperations" @@ -2861,8 +3341,23 @@ func (c *Lightsail) GetOperationsRequest(input *GetOperationsInput) (req *reques // Please also see https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetOperations func (c *Lightsail) GetOperations(input *GetOperationsInput) (*GetOperationsOutput, error) { req, out := c.GetOperationsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetOperationsWithContext is the same as GetOperations with the addition of +// the ability to pass a context and additional request options. +// +// See GetOperations 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 *Lightsail) GetOperationsWithContext(ctx aws.Context, input *GetOperationsInput, opts ...request.Option) (*GetOperationsOutput, error) { + req, out := c.GetOperationsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetOperationsForResource = "GetOperationsForResource" @@ -2947,8 +3442,23 @@ func (c *Lightsail) GetOperationsForResourceRequest(input *GetOperationsForResou // Please also see https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetOperationsForResource func (c *Lightsail) GetOperationsForResource(input *GetOperationsForResourceInput) (*GetOperationsForResourceOutput, error) { req, out := c.GetOperationsForResourceRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetOperationsForResourceWithContext is the same as GetOperationsForResource with the addition of +// the ability to pass a context and additional request options. +// +// See GetOperationsForResource 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 *Lightsail) GetOperationsForResourceWithContext(ctx aws.Context, input *GetOperationsForResourceInput, opts ...request.Option) (*GetOperationsForResourceOutput, error) { + req, out := c.GetOperationsForResourceRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetRegions = "GetRegions" @@ -3033,8 +3543,23 @@ func (c *Lightsail) GetRegionsRequest(input *GetRegionsInput) (req *request.Requ // Please also see https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetRegions func (c *Lightsail) GetRegions(input *GetRegionsInput) (*GetRegionsOutput, error) { req, out := c.GetRegionsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetRegionsWithContext is the same as GetRegions with the addition of +// the ability to pass a context and additional request options. +// +// See GetRegions 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 *Lightsail) GetRegionsWithContext(ctx aws.Context, input *GetRegionsInput, opts ...request.Option) (*GetRegionsOutput, error) { + req, out := c.GetRegionsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetStaticIp = "GetStaticIp" @@ -3119,8 +3644,23 @@ func (c *Lightsail) GetStaticIpRequest(input *GetStaticIpInput) (req *request.Re // Please also see https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetStaticIp func (c *Lightsail) GetStaticIp(input *GetStaticIpInput) (*GetStaticIpOutput, error) { req, out := c.GetStaticIpRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetStaticIpWithContext is the same as GetStaticIp with the addition of +// the ability to pass a context and additional request options. +// +// See GetStaticIp 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 *Lightsail) GetStaticIpWithContext(ctx aws.Context, input *GetStaticIpInput, opts ...request.Option) (*GetStaticIpOutput, error) { + req, out := c.GetStaticIpRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetStaticIps = "GetStaticIps" @@ -3205,8 +3745,23 @@ func (c *Lightsail) GetStaticIpsRequest(input *GetStaticIpsInput) (req *request. // Please also see https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetStaticIps func (c *Lightsail) GetStaticIps(input *GetStaticIpsInput) (*GetStaticIpsOutput, error) { req, out := c.GetStaticIpsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetStaticIpsWithContext is the same as GetStaticIps with the addition of +// the ability to pass a context and additional request options. +// +// See GetStaticIps 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 *Lightsail) GetStaticIpsWithContext(ctx aws.Context, input *GetStaticIpsInput, opts ...request.Option) (*GetStaticIpsOutput, error) { + req, out := c.GetStaticIpsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opImportKeyPair = "ImportKeyPair" @@ -3291,8 +3846,23 @@ func (c *Lightsail) ImportKeyPairRequest(input *ImportKeyPairInput) (req *reques // Please also see https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/ImportKeyPair func (c *Lightsail) ImportKeyPair(input *ImportKeyPairInput) (*ImportKeyPairOutput, error) { req, out := c.ImportKeyPairRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ImportKeyPairWithContext is the same as ImportKeyPair with the addition of +// the ability to pass a context and additional request options. +// +// See ImportKeyPair 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 *Lightsail) ImportKeyPairWithContext(ctx aws.Context, input *ImportKeyPairInput, opts ...request.Option) (*ImportKeyPairOutput, error) { + req, out := c.ImportKeyPairRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opIsVpcPeered = "IsVpcPeered" @@ -3377,8 +3947,23 @@ func (c *Lightsail) IsVpcPeeredRequest(input *IsVpcPeeredInput) (req *request.Re // Please also see https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/IsVpcPeered func (c *Lightsail) IsVpcPeered(input *IsVpcPeeredInput) (*IsVpcPeeredOutput, error) { req, out := c.IsVpcPeeredRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// IsVpcPeeredWithContext is the same as IsVpcPeered with the addition of +// the ability to pass a context and additional request options. +// +// See IsVpcPeered 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 *Lightsail) IsVpcPeeredWithContext(ctx aws.Context, input *IsVpcPeeredInput, opts ...request.Option) (*IsVpcPeeredOutput, error) { + req, out := c.IsVpcPeeredRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opOpenInstancePublicPorts = "OpenInstancePublicPorts" @@ -3463,8 +4048,23 @@ func (c *Lightsail) OpenInstancePublicPortsRequest(input *OpenInstancePublicPort // Please also see https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/OpenInstancePublicPorts func (c *Lightsail) OpenInstancePublicPorts(input *OpenInstancePublicPortsInput) (*OpenInstancePublicPortsOutput, error) { req, out := c.OpenInstancePublicPortsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// OpenInstancePublicPortsWithContext is the same as OpenInstancePublicPorts with the addition of +// the ability to pass a context and additional request options. +// +// See OpenInstancePublicPorts 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 *Lightsail) OpenInstancePublicPortsWithContext(ctx aws.Context, input *OpenInstancePublicPortsInput, opts ...request.Option) (*OpenInstancePublicPortsOutput, error) { + req, out := c.OpenInstancePublicPortsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opPeerVpc = "PeerVpc" @@ -3549,8 +4149,23 @@ func (c *Lightsail) PeerVpcRequest(input *PeerVpcInput) (req *request.Request, o // Please also see https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/PeerVpc func (c *Lightsail) PeerVpc(input *PeerVpcInput) (*PeerVpcOutput, error) { req, out := c.PeerVpcRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// PeerVpcWithContext is the same as PeerVpc with the addition of +// the ability to pass a context and additional request options. +// +// See PeerVpc 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 *Lightsail) PeerVpcWithContext(ctx aws.Context, input *PeerVpcInput, opts ...request.Option) (*PeerVpcOutput, error) { + req, out := c.PeerVpcRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opRebootInstance = "RebootInstance" @@ -3638,8 +4253,23 @@ func (c *Lightsail) RebootInstanceRequest(input *RebootInstanceInput) (req *requ // Please also see https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/RebootInstance func (c *Lightsail) RebootInstance(input *RebootInstanceInput) (*RebootInstanceOutput, error) { req, out := c.RebootInstanceRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// RebootInstanceWithContext is the same as RebootInstance with the addition of +// the ability to pass a context and additional request options. +// +// See RebootInstance 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 *Lightsail) RebootInstanceWithContext(ctx aws.Context, input *RebootInstanceInput, opts ...request.Option) (*RebootInstanceOutput, error) { + req, out := c.RebootInstanceRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opReleaseStaticIp = "ReleaseStaticIp" @@ -3724,8 +4354,23 @@ func (c *Lightsail) ReleaseStaticIpRequest(input *ReleaseStaticIpInput) (req *re // Please also see https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/ReleaseStaticIp func (c *Lightsail) ReleaseStaticIp(input *ReleaseStaticIpInput) (*ReleaseStaticIpOutput, error) { req, out := c.ReleaseStaticIpRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ReleaseStaticIpWithContext is the same as ReleaseStaticIp with the addition of +// the ability to pass a context and additional request options. +// +// See ReleaseStaticIp 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 *Lightsail) ReleaseStaticIpWithContext(ctx aws.Context, input *ReleaseStaticIpInput, opts ...request.Option) (*ReleaseStaticIpOutput, error) { + req, out := c.ReleaseStaticIpRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opStartInstance = "StartInstance" @@ -3811,8 +4456,23 @@ func (c *Lightsail) StartInstanceRequest(input *StartInstanceInput) (req *reques // Please also see https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/StartInstance func (c *Lightsail) StartInstance(input *StartInstanceInput) (*StartInstanceOutput, error) { req, out := c.StartInstanceRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// StartInstanceWithContext is the same as StartInstance with the addition of +// the ability to pass a context and additional request options. +// +// See StartInstance 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 *Lightsail) StartInstanceWithContext(ctx aws.Context, input *StartInstanceInput, opts ...request.Option) (*StartInstanceOutput, error) { + req, out := c.StartInstanceRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opStopInstance = "StopInstance" @@ -3897,8 +4557,23 @@ func (c *Lightsail) StopInstanceRequest(input *StopInstanceInput) (req *request. // Please also see https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/StopInstance func (c *Lightsail) StopInstance(input *StopInstanceInput) (*StopInstanceOutput, error) { req, out := c.StopInstanceRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// StopInstanceWithContext is the same as StopInstance with the addition of +// the ability to pass a context and additional request options. +// +// See StopInstance 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 *Lightsail) StopInstanceWithContext(ctx aws.Context, input *StopInstanceInput, opts ...request.Option) (*StopInstanceOutput, error) { + req, out := c.StopInstanceRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opUnpeerVpc = "UnpeerVpc" @@ -3983,8 +4658,23 @@ func (c *Lightsail) UnpeerVpcRequest(input *UnpeerVpcInput) (req *request.Reques // Please also see https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/UnpeerVpc func (c *Lightsail) UnpeerVpc(input *UnpeerVpcInput) (*UnpeerVpcOutput, error) { req, out := c.UnpeerVpcRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// UnpeerVpcWithContext is the same as UnpeerVpc with the addition of +// the ability to pass a context and additional request options. +// +// See UnpeerVpc 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 *Lightsail) UnpeerVpcWithContext(ctx aws.Context, input *UnpeerVpcInput, opts ...request.Option) (*UnpeerVpcOutput, error) { + req, out := c.UnpeerVpcRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opUpdateDomainEntry = "UpdateDomainEntry" @@ -4069,8 +4759,23 @@ func (c *Lightsail) UpdateDomainEntryRequest(input *UpdateDomainEntryInput) (req // Please also see https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/UpdateDomainEntry func (c *Lightsail) UpdateDomainEntry(input *UpdateDomainEntryInput) (*UpdateDomainEntryOutput, error) { req, out := c.UpdateDomainEntryRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// UpdateDomainEntryWithContext is the same as UpdateDomainEntry with the addition of +// the ability to pass a context and additional request options. +// +// See UpdateDomainEntry 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 *Lightsail) UpdateDomainEntryWithContext(ctx aws.Context, input *UpdateDomainEntryInput, opts ...request.Option) (*UpdateDomainEntryOutput, error) { + req, out := c.UpdateDomainEntryRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // Please also see https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/AllocateStaticIpRequest diff --git a/vendor/github.com/aws/aws-sdk-go/service/lightsail/doc.go b/vendor/github.com/aws/aws-sdk-go/service/lightsail/doc.go new file mode 100644 index 000000000..171892107 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/service/lightsail/doc.go @@ -0,0 +1,92 @@ +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. + +// Package lightsail provides the client and types for making API +// requests to Amazon Lightsail. +// +// Amazon Lightsail is the easiest way to get started with AWS for developers +// who just need virtual private servers. Lightsail includes everything you +// need to launch your project quickly - a virtual machine, SSD-based storage, +// data transfer, DNS management, and a static IP - for a low, predictable price. +// You manage those Lightsail servers through the Lightsail console or by using +// the API or command-line interface (CLI). +// +// For more information about Lightsail concepts and tasks, see the Lightsail +// Dev Guide (http://lightsail.aws.amazon.com/ls/docs). +// +// To use the Lightsail API or the CLI, you will need to use AWS Identity and +// Access Management (IAM) to generate access keys. For details about how to +// set this up, see the Lightsail Dev Guide (http://lightsail.aws.amazon.com/ls/docs/how-to/articles/lightsail-how-to-set-up-access-keys-to-use-sdk-api-cli). +// +// See https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28 for more information on this service. +// +// See lightsail package documentation for more information. +// https://docs.aws.amazon.com/sdk-for-go/api/service/lightsail/ +// +// Using the Client +// +// To use the client for Amazon Lightsail you will first need +// to create a new instance of it. +// +// When creating a client for an AWS service you'll first need to have a Session +// already created. The Session provides configuration that can be shared +// between multiple service clients. Additional configuration can be applied to +// the Session and service's client when they are constructed. The aws package's +// Config type contains several fields such as Region for the AWS Region the +// client should make API requests too. The optional Config value can be provided +// as the variadic argument for Sessions and client creation. +// +// Once the service's client is created you can use it to make API requests the +// AWS service. These clients are safe to use concurrently. +// +// // Create a session to share configuration, and load external configuration. +// sess := session.Must(session.NewSession()) +// +// // Create the service's client with the session. +// svc := lightsail.New(sess) +// +// See the SDK's documentation for more information on how to use service clients. +// https://docs.aws.amazon.com/sdk-for-go/api/ +// +// See aws package's Config type for more information on configuration options. +// https://docs.aws.amazon.com/sdk-for-go/api/aws/#Config +// +// See the Amazon Lightsail client Lightsail for more +// information on creating the service's client. +// https://docs.aws.amazon.com/sdk-for-go/api/service/lightsail/#New +// +// Once the client is created you can make an API request to the service. +// Each API method takes a input parameter, and returns the service response +// and an error. +// +// The API method will document which error codes the service can be returned +// by the operation if the service models the API operation's errors. These +// errors will also be available as const strings prefixed with "ErrCode". +// +// result, err := svc.AllocateStaticIp(params) +// if err != nil { +// // Cast err to awserr.Error to handle specific error codes. +// aerr, ok := err.(awserr.Error) +// if ok && aerr.Code() == { +// // Specific error code handling +// } +// return err +// } +// +// fmt.Println("AllocateStaticIp result:") +// fmt.Println(result) +// +// Using the Client with Context +// +// The service's client also provides methods to make API requests with a Context +// value. This allows you to control the timeout, and cancellation of pending +// requests. These methods also take request Option as variadic parameter to apply +// additional configuration to the API request. +// +// ctx := context.Background() +// +// result, err := svc.AllocateStaticIpWithContext(ctx, params) +// +// See the request package documentation for more information on using Context pattern +// with the SDK. +// https://docs.aws.amazon.com/sdk-for-go/api/aws/request/ +package lightsail diff --git a/vendor/github.com/aws/aws-sdk-go/service/lightsail/errors.go b/vendor/github.com/aws/aws-sdk-go/service/lightsail/errors.go index 309a86b9c..a42a1393b 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/lightsail/errors.go +++ b/vendor/github.com/aws/aws-sdk-go/service/lightsail/errors.go @@ -1,4 +1,4 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. package lightsail diff --git a/vendor/github.com/aws/aws-sdk-go/service/lightsail/service.go b/vendor/github.com/aws/aws-sdk-go/service/lightsail/service.go index c3e15def0..a76cf79e0 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/lightsail/service.go +++ b/vendor/github.com/aws/aws-sdk-go/service/lightsail/service.go @@ -1,4 +1,4 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. package lightsail @@ -11,22 +11,12 @@ import ( "github.com/aws/aws-sdk-go/private/protocol/jsonrpc" ) -// Amazon Lightsail is the easiest way to get started with AWS for developers -// who just need virtual private servers. Lightsail includes everything you -// need to launch your project quickly - a virtual machine, SSD-based storage, -// data transfer, DNS management, and a static IP - for a low, predictable price. -// You manage those Lightsail servers through the Lightsail console or by using -// the API or command-line interface (CLI). +// Lightsail provides the API operation methods for making requests to +// Amazon Lightsail. See this package's package overview docs +// for details on the service. // -// For more information about Lightsail concepts and tasks, see the Lightsail -// Dev Guide (http://lightsail.aws.amazon.com/ls/docs). -// -// To use the Lightsail API or the CLI, you will need to use AWS Identity and -// Access Management (IAM) to generate access keys. For details about how to -// set this up, see the Lightsail Dev Guide (http://lightsail.aws.amazon.com/ls/docs/how-to/articles/lightsail-how-to-set-up-access-keys-to-use-sdk-api-cli). -// The service client's operations are safe to be used concurrently. -// It is not safe to mutate any of the client's properties though. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28 +// Lightsail methods are safe to use concurrently. It is not safe to +// modify mutate any of the struct's properties though. type Lightsail struct { *client.Client } diff --git a/vendor/github.com/aws/aws-sdk-go/service/opsworks/api.go b/vendor/github.com/aws/aws-sdk-go/service/opsworks/api.go index d0c09d284..3f725f6bd 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/opsworks/api.go +++ b/vendor/github.com/aws/aws-sdk-go/service/opsworks/api.go @@ -1,11 +1,11 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. -// Package opsworks provides a client for AWS OpsWorks. package opsworks import ( "fmt" + "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awsutil" "github.com/aws/aws-sdk-go/aws/request" "github.com/aws/aws-sdk-go/private/protocol" @@ -66,7 +66,7 @@ func (c *OpsWorks) AssignInstanceRequest(input *AssignInstanceInput) (req *reque // * You can assign registered Amazon EC2 instances only to custom layers. // // * You cannot use this action with instances that were created with AWS -// OpsWorks. +// OpsWorks Stacks. // // Required Permissions: To use this action, an AWS Identity and Access Management // (IAM) user must have a Manage permissions level for the stack or an attached @@ -90,8 +90,23 @@ func (c *OpsWorks) AssignInstanceRequest(input *AssignInstanceInput) (req *reque // Please also see https://docs.aws.amazon.com/goto/WebAPI/opsworks-2013-02-18/AssignInstance func (c *OpsWorks) AssignInstance(input *AssignInstanceInput) (*AssignInstanceOutput, error) { req, out := c.AssignInstanceRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// AssignInstanceWithContext is the same as AssignInstance with the addition of +// the ability to pass a context and additional request options. +// +// See AssignInstance 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 *OpsWorks) AssignInstanceWithContext(ctx aws.Context, input *AssignInstanceInput, opts ...request.Option) (*AssignInstanceOutput, error) { + req, out := c.AssignInstanceRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opAssignVolume = "AssignVolume" @@ -169,8 +184,23 @@ func (c *OpsWorks) AssignVolumeRequest(input *AssignVolumeInput) (req *request.R // Please also see https://docs.aws.amazon.com/goto/WebAPI/opsworks-2013-02-18/AssignVolume func (c *OpsWorks) AssignVolume(input *AssignVolumeInput) (*AssignVolumeOutput, error) { req, out := c.AssignVolumeRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// AssignVolumeWithContext is the same as AssignVolume with the addition of +// the ability to pass a context and additional request options. +// +// See AssignVolume 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 *OpsWorks) AssignVolumeWithContext(ctx aws.Context, input *AssignVolumeInput, opts ...request.Option) (*AssignVolumeOutput, error) { + req, out := c.AssignVolumeRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opAssociateElasticIp = "AssociateElasticIp" @@ -246,8 +276,23 @@ func (c *OpsWorks) AssociateElasticIpRequest(input *AssociateElasticIpInput) (re // Please also see https://docs.aws.amazon.com/goto/WebAPI/opsworks-2013-02-18/AssociateElasticIp func (c *OpsWorks) AssociateElasticIp(input *AssociateElasticIpInput) (*AssociateElasticIpOutput, error) { req, out := c.AssociateElasticIpRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// AssociateElasticIpWithContext is the same as AssociateElasticIp with the addition of +// the ability to pass a context and additional request options. +// +// See AssociateElasticIp 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 *OpsWorks) AssociateElasticIpWithContext(ctx aws.Context, input *AssociateElasticIpInput, opts ...request.Option) (*AssociateElasticIpOutput, error) { + req, out := c.AssociateElasticIpRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opAttachElasticLoadBalancer = "AttachElasticLoadBalancer" @@ -326,8 +371,23 @@ func (c *OpsWorks) AttachElasticLoadBalancerRequest(input *AttachElasticLoadBala // Please also see https://docs.aws.amazon.com/goto/WebAPI/opsworks-2013-02-18/AttachElasticLoadBalancer func (c *OpsWorks) AttachElasticLoadBalancer(input *AttachElasticLoadBalancerInput) (*AttachElasticLoadBalancerOutput, error) { req, out := c.AttachElasticLoadBalancerRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// AttachElasticLoadBalancerWithContext is the same as AttachElasticLoadBalancer with the addition of +// the ability to pass a context and additional request options. +// +// See AttachElasticLoadBalancer 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 *OpsWorks) AttachElasticLoadBalancerWithContext(ctx aws.Context, input *AttachElasticLoadBalancerInput, opts ...request.Option) (*AttachElasticLoadBalancerOutput, error) { + req, out := c.AttachElasticLoadBalancerRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCloneStack = "CloneStack" @@ -400,8 +460,23 @@ func (c *OpsWorks) CloneStackRequest(input *CloneStackInput) (req *request.Reque // Please also see https://docs.aws.amazon.com/goto/WebAPI/opsworks-2013-02-18/CloneStack func (c *OpsWorks) CloneStack(input *CloneStackInput) (*CloneStackOutput, error) { req, out := c.CloneStackRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CloneStackWithContext is the same as CloneStack with the addition of +// the ability to pass a context and additional request options. +// +// See CloneStack 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 *OpsWorks) CloneStackWithContext(ctx aws.Context, input *CloneStackInput, opts ...request.Option) (*CloneStackOutput, error) { + req, out := c.CloneStackRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateApp = "CreateApp" @@ -474,8 +549,23 @@ func (c *OpsWorks) CreateAppRequest(input *CreateAppInput) (req *request.Request // Please also see https://docs.aws.amazon.com/goto/WebAPI/opsworks-2013-02-18/CreateApp func (c *OpsWorks) CreateApp(input *CreateAppInput) (*CreateAppOutput, error) { req, out := c.CreateAppRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateAppWithContext is the same as CreateApp with the addition of +// the ability to pass a context and additional request options. +// +// See CreateApp 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 *OpsWorks) CreateAppWithContext(ctx aws.Context, input *CreateAppInput, opts ...request.Option) (*CreateAppOutput, error) { + req, out := c.CreateAppRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateDeployment = "CreateDeployment" @@ -549,8 +639,23 @@ func (c *OpsWorks) CreateDeploymentRequest(input *CreateDeploymentInput) (req *r // Please also see https://docs.aws.amazon.com/goto/WebAPI/opsworks-2013-02-18/CreateDeployment func (c *OpsWorks) CreateDeployment(input *CreateDeploymentInput) (*CreateDeploymentOutput, error) { req, out := c.CreateDeploymentRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateDeploymentWithContext is the same as CreateDeployment with the addition of +// the ability to pass a context and additional request options. +// +// See CreateDeployment 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 *OpsWorks) CreateDeploymentWithContext(ctx aws.Context, input *CreateDeploymentInput, opts ...request.Option) (*CreateDeploymentOutput, error) { + req, out := c.CreateDeploymentRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateInstance = "CreateInstance" @@ -623,8 +728,23 @@ func (c *OpsWorks) CreateInstanceRequest(input *CreateInstanceInput) (req *reque // Please also see https://docs.aws.amazon.com/goto/WebAPI/opsworks-2013-02-18/CreateInstance func (c *OpsWorks) CreateInstance(input *CreateInstanceInput) (*CreateInstanceOutput, error) { req, out := c.CreateInstanceRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateInstanceWithContext is the same as CreateInstance with the addition of +// the ability to pass a context and additional request options. +// +// See CreateInstance 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 *OpsWorks) CreateInstanceWithContext(ctx aws.Context, input *CreateInstanceInput, opts ...request.Option) (*CreateInstanceOutput, error) { + req, out := c.CreateInstanceRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateLayer = "CreateLayer" @@ -703,8 +823,23 @@ func (c *OpsWorks) CreateLayerRequest(input *CreateLayerInput) (req *request.Req // Please also see https://docs.aws.amazon.com/goto/WebAPI/opsworks-2013-02-18/CreateLayer func (c *OpsWorks) CreateLayer(input *CreateLayerInput) (*CreateLayerOutput, error) { req, out := c.CreateLayerRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateLayerWithContext is the same as CreateLayer with the addition of +// the ability to pass a context and additional request options. +// +// See CreateLayer 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 *OpsWorks) CreateLayerWithContext(ctx aws.Context, input *CreateLayerInput, opts ...request.Option) (*CreateLayerOutput, error) { + req, out := c.CreateLayerRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateStack = "CreateStack" @@ -772,8 +907,23 @@ func (c *OpsWorks) CreateStackRequest(input *CreateStackInput) (req *request.Req // Please also see https://docs.aws.amazon.com/goto/WebAPI/opsworks-2013-02-18/CreateStack func (c *OpsWorks) CreateStack(input *CreateStackInput) (*CreateStackOutput, error) { req, out := c.CreateStackRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateStackWithContext is the same as CreateStack with the addition of +// the ability to pass a context and additional request options. +// +// See CreateStack 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 *OpsWorks) CreateStackWithContext(ctx aws.Context, input *CreateStackInput, opts ...request.Option) (*CreateStackOutput, error) { + req, out := c.CreateStackRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateUserProfile = "CreateUserProfile" @@ -841,8 +991,23 @@ func (c *OpsWorks) CreateUserProfileRequest(input *CreateUserProfileInput) (req // Please also see https://docs.aws.amazon.com/goto/WebAPI/opsworks-2013-02-18/CreateUserProfile func (c *OpsWorks) CreateUserProfile(input *CreateUserProfileInput) (*CreateUserProfileOutput, error) { req, out := c.CreateUserProfileRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateUserProfileWithContext is the same as CreateUserProfile with the addition of +// the ability to pass a context and additional request options. +// +// See CreateUserProfile 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 *OpsWorks) CreateUserProfileWithContext(ctx aws.Context, input *CreateUserProfileInput, opts ...request.Option) (*CreateUserProfileOutput, error) { + req, out := c.CreateUserProfileRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteApp = "DeleteApp" @@ -916,8 +1081,23 @@ func (c *OpsWorks) DeleteAppRequest(input *DeleteAppInput) (req *request.Request // Please also see https://docs.aws.amazon.com/goto/WebAPI/opsworks-2013-02-18/DeleteApp func (c *OpsWorks) DeleteApp(input *DeleteAppInput) (*DeleteAppOutput, error) { req, out := c.DeleteAppRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteAppWithContext is the same as DeleteApp with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteApp 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 *OpsWorks) DeleteAppWithContext(ctx aws.Context, input *DeleteAppInput, opts ...request.Option) (*DeleteAppOutput, error) { + req, out := c.DeleteAppRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteInstance = "DeleteInstance" @@ -994,8 +1174,23 @@ func (c *OpsWorks) DeleteInstanceRequest(input *DeleteInstanceInput) (req *reque // Please also see https://docs.aws.amazon.com/goto/WebAPI/opsworks-2013-02-18/DeleteInstance func (c *OpsWorks) DeleteInstance(input *DeleteInstanceInput) (*DeleteInstanceOutput, error) { req, out := c.DeleteInstanceRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteInstanceWithContext is the same as DeleteInstance with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteInstance 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 *OpsWorks) DeleteInstanceWithContext(ctx aws.Context, input *DeleteInstanceInput, opts ...request.Option) (*DeleteInstanceOutput, error) { + req, out := c.DeleteInstanceRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteLayer = "DeleteLayer" @@ -1071,8 +1266,23 @@ func (c *OpsWorks) DeleteLayerRequest(input *DeleteLayerInput) (req *request.Req // Please also see https://docs.aws.amazon.com/goto/WebAPI/opsworks-2013-02-18/DeleteLayer func (c *OpsWorks) DeleteLayer(input *DeleteLayerInput) (*DeleteLayerOutput, error) { req, out := c.DeleteLayerRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteLayerWithContext is the same as DeleteLayer with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteLayer 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 *OpsWorks) DeleteLayerWithContext(ctx aws.Context, input *DeleteLayerInput, opts ...request.Option) (*DeleteLayerOutput, error) { + req, out := c.DeleteLayerRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteStack = "DeleteStack" @@ -1148,8 +1358,23 @@ func (c *OpsWorks) DeleteStackRequest(input *DeleteStackInput) (req *request.Req // Please also see https://docs.aws.amazon.com/goto/WebAPI/opsworks-2013-02-18/DeleteStack func (c *OpsWorks) DeleteStack(input *DeleteStackInput) (*DeleteStackOutput, error) { req, out := c.DeleteStackRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteStackWithContext is the same as DeleteStack with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteStack 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 *OpsWorks) DeleteStackWithContext(ctx aws.Context, input *DeleteStackInput, opts ...request.Option) (*DeleteStackOutput, error) { + req, out := c.DeleteStackRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteUserProfile = "DeleteUserProfile" @@ -1222,8 +1447,23 @@ func (c *OpsWorks) DeleteUserProfileRequest(input *DeleteUserProfileInput) (req // Please also see https://docs.aws.amazon.com/goto/WebAPI/opsworks-2013-02-18/DeleteUserProfile func (c *OpsWorks) DeleteUserProfile(input *DeleteUserProfileInput) (*DeleteUserProfileOutput, error) { req, out := c.DeleteUserProfileRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteUserProfileWithContext is the same as DeleteUserProfile with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteUserProfile 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 *OpsWorks) DeleteUserProfileWithContext(ctx aws.Context, input *DeleteUserProfileInput, opts ...request.Option) (*DeleteUserProfileOutput, error) { + req, out := c.DeleteUserProfileRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeregisterEcsCluster = "DeregisterEcsCluster" @@ -1298,8 +1538,23 @@ func (c *OpsWorks) DeregisterEcsClusterRequest(input *DeregisterEcsClusterInput) // Please also see https://docs.aws.amazon.com/goto/WebAPI/opsworks-2013-02-18/DeregisterEcsCluster func (c *OpsWorks) DeregisterEcsCluster(input *DeregisterEcsClusterInput) (*DeregisterEcsClusterOutput, error) { req, out := c.DeregisterEcsClusterRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeregisterEcsClusterWithContext is the same as DeregisterEcsCluster with the addition of +// the ability to pass a context and additional request options. +// +// See DeregisterEcsCluster 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 *OpsWorks) DeregisterEcsClusterWithContext(ctx aws.Context, input *DeregisterEcsClusterInput, opts ...request.Option) (*DeregisterEcsClusterOutput, error) { + req, out := c.DeregisterEcsClusterRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeregisterElasticIp = "DeregisterElasticIp" @@ -1374,8 +1629,23 @@ func (c *OpsWorks) DeregisterElasticIpRequest(input *DeregisterElasticIpInput) ( // Please also see https://docs.aws.amazon.com/goto/WebAPI/opsworks-2013-02-18/DeregisterElasticIp func (c *OpsWorks) DeregisterElasticIp(input *DeregisterElasticIpInput) (*DeregisterElasticIpOutput, error) { req, out := c.DeregisterElasticIpRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeregisterElasticIpWithContext is the same as DeregisterElasticIp with the addition of +// the ability to pass a context and additional request options. +// +// See DeregisterElasticIp 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 *OpsWorks) DeregisterElasticIpWithContext(ctx aws.Context, input *DeregisterElasticIpInput, opts ...request.Option) (*DeregisterElasticIpOutput, error) { + req, out := c.DeregisterElasticIpRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeregisterInstance = "DeregisterInstance" @@ -1427,7 +1697,7 @@ func (c *OpsWorks) DeregisterInstanceRequest(input *DeregisterInstanceInput) (re // // Deregister a registered Amazon EC2 or on-premises instance. This action removes // the instance from the stack and returns it to your control. This action can -// not be used with instances that were created with AWS OpsWorks. +// not be used with instances that were created with AWS OpsWorks Stacks. // // Required Permissions: To use this action, an IAM user must have a Manage // permissions level for the stack or an attached policy that explicitly grants @@ -1451,8 +1721,23 @@ func (c *OpsWorks) DeregisterInstanceRequest(input *DeregisterInstanceInput) (re // Please also see https://docs.aws.amazon.com/goto/WebAPI/opsworks-2013-02-18/DeregisterInstance func (c *OpsWorks) DeregisterInstance(input *DeregisterInstanceInput) (*DeregisterInstanceOutput, error) { req, out := c.DeregisterInstanceRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeregisterInstanceWithContext is the same as DeregisterInstance with the addition of +// the ability to pass a context and additional request options. +// +// See DeregisterInstance 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 *OpsWorks) DeregisterInstanceWithContext(ctx aws.Context, input *DeregisterInstanceInput, opts ...request.Option) (*DeregisterInstanceOutput, error) { + req, out := c.DeregisterInstanceRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeregisterRdsDbInstance = "DeregisterRdsDbInstance" @@ -1526,8 +1811,23 @@ func (c *OpsWorks) DeregisterRdsDbInstanceRequest(input *DeregisterRdsDbInstance // Please also see https://docs.aws.amazon.com/goto/WebAPI/opsworks-2013-02-18/DeregisterRdsDbInstance func (c *OpsWorks) DeregisterRdsDbInstance(input *DeregisterRdsDbInstanceInput) (*DeregisterRdsDbInstanceOutput, error) { req, out := c.DeregisterRdsDbInstanceRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeregisterRdsDbInstanceWithContext is the same as DeregisterRdsDbInstance with the addition of +// the ability to pass a context and additional request options. +// +// See DeregisterRdsDbInstance 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 *OpsWorks) DeregisterRdsDbInstanceWithContext(ctx aws.Context, input *DeregisterRdsDbInstanceInput, opts ...request.Option) (*DeregisterRdsDbInstanceOutput, error) { + req, out := c.DeregisterRdsDbInstanceRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeregisterVolume = "DeregisterVolume" @@ -1602,8 +1902,23 @@ func (c *OpsWorks) DeregisterVolumeRequest(input *DeregisterVolumeInput) (req *r // Please also see https://docs.aws.amazon.com/goto/WebAPI/opsworks-2013-02-18/DeregisterVolume func (c *OpsWorks) DeregisterVolume(input *DeregisterVolumeInput) (*DeregisterVolumeOutput, error) { req, out := c.DeregisterVolumeRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeregisterVolumeWithContext is the same as DeregisterVolume with the addition of +// the ability to pass a context and additional request options. +// +// See DeregisterVolume 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 *OpsWorks) DeregisterVolumeWithContext(ctx aws.Context, input *DeregisterVolumeInput, opts ...request.Option) (*DeregisterVolumeOutput, error) { + req, out := c.DeregisterVolumeRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeAgentVersions = "DescribeAgentVersions" @@ -1651,9 +1966,9 @@ func (c *OpsWorks) DescribeAgentVersionsRequest(input *DescribeAgentVersionsInpu // DescribeAgentVersions API operation for AWS OpsWorks. // -// Describes the available AWS OpsWorks agent versions. You must specify a stack -// ID or a configuration manager. DescribeAgentVersions returns a list of available -// agent versions for the specified stack or configuration manager. +// Describes the available AWS OpsWorks Stacks agent versions. You must specify +// a stack ID or a configuration manager. DescribeAgentVersions returns a list +// of available agent versions for the specified stack or configuration manager. // // 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 @@ -1672,8 +1987,23 @@ func (c *OpsWorks) DescribeAgentVersionsRequest(input *DescribeAgentVersionsInpu // Please also see https://docs.aws.amazon.com/goto/WebAPI/opsworks-2013-02-18/DescribeAgentVersions func (c *OpsWorks) DescribeAgentVersions(input *DescribeAgentVersionsInput) (*DescribeAgentVersionsOutput, error) { req, out := c.DescribeAgentVersionsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeAgentVersionsWithContext is the same as DescribeAgentVersions with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeAgentVersions 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 *OpsWorks) DescribeAgentVersionsWithContext(ctx aws.Context, input *DescribeAgentVersionsInput, opts ...request.Option) (*DescribeAgentVersionsOutput, error) { + req, out := c.DescribeAgentVersionsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeApps = "DescribeApps" @@ -1723,7 +2053,7 @@ func (c *OpsWorks) DescribeAppsRequest(input *DescribeAppsInput) (req *request.R // // Requests a description of a specified set of apps. // -// You must specify at least one of the parameters. +// This call accepts only one resource-identifying parameter. // // Required Permissions: To use this action, an IAM user must have a Show, Deploy, // or Manage permissions level for the stack, or an attached policy that explicitly @@ -1747,8 +2077,23 @@ func (c *OpsWorks) DescribeAppsRequest(input *DescribeAppsInput) (req *request.R // Please also see https://docs.aws.amazon.com/goto/WebAPI/opsworks-2013-02-18/DescribeApps func (c *OpsWorks) DescribeApps(input *DescribeAppsInput) (*DescribeAppsOutput, error) { req, out := c.DescribeAppsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeAppsWithContext is the same as DescribeApps with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeApps 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 *OpsWorks) DescribeAppsWithContext(ctx aws.Context, input *DescribeAppsInput, opts ...request.Option) (*DescribeAppsOutput, error) { + req, out := c.DescribeAppsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeCommands = "DescribeCommands" @@ -1798,7 +2143,7 @@ func (c *OpsWorks) DescribeCommandsRequest(input *DescribeCommandsInput) (req *r // // Describes the results of specified commands. // -// You must specify at least one of the parameters. +// This call accepts only one resource-identifying parameter. // // Required Permissions: To use this action, an IAM user must have a Show, Deploy, // or Manage permissions level for the stack, or an attached policy that explicitly @@ -1822,8 +2167,23 @@ func (c *OpsWorks) DescribeCommandsRequest(input *DescribeCommandsInput) (req *r // Please also see https://docs.aws.amazon.com/goto/WebAPI/opsworks-2013-02-18/DescribeCommands func (c *OpsWorks) DescribeCommands(input *DescribeCommandsInput) (*DescribeCommandsOutput, error) { req, out := c.DescribeCommandsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeCommandsWithContext is the same as DescribeCommands with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeCommands 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 *OpsWorks) DescribeCommandsWithContext(ctx aws.Context, input *DescribeCommandsInput, opts ...request.Option) (*DescribeCommandsOutput, error) { + req, out := c.DescribeCommandsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeDeployments = "DescribeDeployments" @@ -1873,7 +2233,7 @@ func (c *OpsWorks) DescribeDeploymentsRequest(input *DescribeDeploymentsInput) ( // // Requests a description of a specified set of deployments. // -// You must specify at least one of the parameters. +// This call accepts only one resource-identifying parameter. // // Required Permissions: To use this action, an IAM user must have a Show, Deploy, // or Manage permissions level for the stack, or an attached policy that explicitly @@ -1897,8 +2257,23 @@ func (c *OpsWorks) DescribeDeploymentsRequest(input *DescribeDeploymentsInput) ( // Please also see https://docs.aws.amazon.com/goto/WebAPI/opsworks-2013-02-18/DescribeDeployments func (c *OpsWorks) DescribeDeployments(input *DescribeDeploymentsInput) (*DescribeDeploymentsOutput, error) { req, out := c.DescribeDeploymentsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeDeploymentsWithContext is the same as DescribeDeployments with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeDeployments 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 *OpsWorks) DescribeDeploymentsWithContext(ctx aws.Context, input *DescribeDeploymentsInput, opts ...request.Option) (*DescribeDeploymentsOutput, error) { + req, out := c.DescribeDeploymentsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeEcsClusters = "DescribeEcsClusters" @@ -1954,14 +2329,16 @@ func (c *OpsWorks) DescribeEcsClustersRequest(input *DescribeEcsClustersInput) ( // // Describes Amazon ECS clusters that are registered with a stack. If you specify // only a stack ID, you can use the MaxResults and NextToken parameters to paginate -// the response. However, AWS OpsWorks currently supports only one cluster per -// layer, so the result set has a maximum of one element. +// the response. However, AWS OpsWorks Stacks currently supports only one cluster +// per layer, so the result set has a maximum of one element. // // Required Permissions: To use this action, an IAM user must have a Show, Deploy, // or Manage permissions level for the stack or an attached policy that explicitly // grants permission. For more information on user permissions, see Managing // User Permissions (http://docs.aws.amazon.com/opsworks/latest/userguide/opsworks-security-users.html). // +// This call accepts only one resource-identifying parameter. +// // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about // the error. @@ -1979,8 +2356,23 @@ func (c *OpsWorks) DescribeEcsClustersRequest(input *DescribeEcsClustersInput) ( // Please also see https://docs.aws.amazon.com/goto/WebAPI/opsworks-2013-02-18/DescribeEcsClusters func (c *OpsWorks) DescribeEcsClusters(input *DescribeEcsClustersInput) (*DescribeEcsClustersOutput, error) { req, out := c.DescribeEcsClustersRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeEcsClustersWithContext is the same as DescribeEcsClusters with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeEcsClusters 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 *OpsWorks) DescribeEcsClustersWithContext(ctx aws.Context, input *DescribeEcsClustersInput, opts ...request.Option) (*DescribeEcsClustersOutput, error) { + req, out := c.DescribeEcsClustersRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // DescribeEcsClustersPages iterates over the pages of a DescribeEcsClusters operation, @@ -2000,12 +2392,37 @@ func (c *OpsWorks) DescribeEcsClusters(input *DescribeEcsClustersInput) (*Descri // return pageNum <= 3 // }) // -func (c *OpsWorks) DescribeEcsClustersPages(input *DescribeEcsClustersInput, fn func(p *DescribeEcsClustersOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.DescribeEcsClustersRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*DescribeEcsClustersOutput), lastPage) - }) +func (c *OpsWorks) DescribeEcsClustersPages(input *DescribeEcsClustersInput, fn func(*DescribeEcsClustersOutput, bool) bool) error { + return c.DescribeEcsClustersPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// DescribeEcsClustersPagesWithContext same as DescribeEcsClustersPages 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 *OpsWorks) DescribeEcsClustersPagesWithContext(ctx aws.Context, input *DescribeEcsClustersInput, fn func(*DescribeEcsClustersOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *DescribeEcsClustersInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeEcsClustersRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*DescribeEcsClustersOutput), !p.HasNextPage()) + } + return p.Err() } const opDescribeElasticIps = "DescribeElasticIps" @@ -2055,7 +2472,7 @@ func (c *OpsWorks) DescribeElasticIpsRequest(input *DescribeElasticIpsInput) (re // // Describes Elastic IP addresses (http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/elastic-ip-addresses-eip.html). // -// You must specify at least one of the parameters. +// This call accepts only one resource-identifying parameter. // // Required Permissions: To use this action, an IAM user must have a Show, Deploy, // or Manage permissions level for the stack, or an attached policy that explicitly @@ -2079,8 +2496,23 @@ func (c *OpsWorks) DescribeElasticIpsRequest(input *DescribeElasticIpsInput) (re // Please also see https://docs.aws.amazon.com/goto/WebAPI/opsworks-2013-02-18/DescribeElasticIps func (c *OpsWorks) DescribeElasticIps(input *DescribeElasticIpsInput) (*DescribeElasticIpsOutput, error) { req, out := c.DescribeElasticIpsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeElasticIpsWithContext is the same as DescribeElasticIps with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeElasticIps 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 *OpsWorks) DescribeElasticIpsWithContext(ctx aws.Context, input *DescribeElasticIpsInput, opts ...request.Option) (*DescribeElasticIpsOutput, error) { + req, out := c.DescribeElasticIpsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeElasticLoadBalancers = "DescribeElasticLoadBalancers" @@ -2130,7 +2562,7 @@ func (c *OpsWorks) DescribeElasticLoadBalancersRequest(input *DescribeElasticLoa // // Describes a stack's Elastic Load Balancing instances. // -// You must specify at least one of the parameters. +// This call accepts only one resource-identifying parameter. // // Required Permissions: To use this action, an IAM user must have a Show, Deploy, // or Manage permissions level for the stack, or an attached policy that explicitly @@ -2154,8 +2586,23 @@ func (c *OpsWorks) DescribeElasticLoadBalancersRequest(input *DescribeElasticLoa // Please also see https://docs.aws.amazon.com/goto/WebAPI/opsworks-2013-02-18/DescribeElasticLoadBalancers func (c *OpsWorks) DescribeElasticLoadBalancers(input *DescribeElasticLoadBalancersInput) (*DescribeElasticLoadBalancersOutput, error) { req, out := c.DescribeElasticLoadBalancersRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeElasticLoadBalancersWithContext is the same as DescribeElasticLoadBalancers with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeElasticLoadBalancers 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 *OpsWorks) DescribeElasticLoadBalancersWithContext(ctx aws.Context, input *DescribeElasticLoadBalancersInput, opts ...request.Option) (*DescribeElasticLoadBalancersOutput, error) { + req, out := c.DescribeElasticLoadBalancersRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeInstances = "DescribeInstances" @@ -2205,7 +2652,7 @@ func (c *OpsWorks) DescribeInstancesRequest(input *DescribeInstancesInput) (req // // Requests a description of a set of instances. // -// You must specify at least one of the parameters. +// This call accepts only one resource-identifying parameter. // // Required Permissions: To use this action, an IAM user must have a Show, Deploy, // or Manage permissions level for the stack, or an attached policy that explicitly @@ -2229,8 +2676,23 @@ func (c *OpsWorks) DescribeInstancesRequest(input *DescribeInstancesInput) (req // Please also see https://docs.aws.amazon.com/goto/WebAPI/opsworks-2013-02-18/DescribeInstances func (c *OpsWorks) DescribeInstances(input *DescribeInstancesInput) (*DescribeInstancesOutput, error) { req, out := c.DescribeInstancesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeInstancesWithContext is the same as DescribeInstances with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeInstances 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 *OpsWorks) DescribeInstancesWithContext(ctx aws.Context, input *DescribeInstancesInput, opts ...request.Option) (*DescribeInstancesOutput, error) { + req, out := c.DescribeInstancesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeLayers = "DescribeLayers" @@ -2280,7 +2742,7 @@ func (c *OpsWorks) DescribeLayersRequest(input *DescribeLayersInput) (req *reque // // Requests a description of one or more layers in a specified stack. // -// You must specify at least one of the parameters. +// This call accepts only one resource-identifying parameter. // // Required Permissions: To use this action, an IAM user must have a Show, Deploy, // or Manage permissions level for the stack, or an attached policy that explicitly @@ -2304,8 +2766,23 @@ func (c *OpsWorks) DescribeLayersRequest(input *DescribeLayersInput) (req *reque // Please also see https://docs.aws.amazon.com/goto/WebAPI/opsworks-2013-02-18/DescribeLayers func (c *OpsWorks) DescribeLayers(input *DescribeLayersInput) (*DescribeLayersOutput, error) { req, out := c.DescribeLayersRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeLayersWithContext is the same as DescribeLayers with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeLayers 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 *OpsWorks) DescribeLayersWithContext(ctx aws.Context, input *DescribeLayersInput, opts ...request.Option) (*DescribeLayersOutput, error) { + req, out := c.DescribeLayersRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeLoadBasedAutoScaling = "DescribeLoadBasedAutoScaling" @@ -2379,8 +2856,23 @@ func (c *OpsWorks) DescribeLoadBasedAutoScalingRequest(input *DescribeLoadBasedA // Please also see https://docs.aws.amazon.com/goto/WebAPI/opsworks-2013-02-18/DescribeLoadBasedAutoScaling func (c *OpsWorks) DescribeLoadBasedAutoScaling(input *DescribeLoadBasedAutoScalingInput) (*DescribeLoadBasedAutoScalingOutput, error) { req, out := c.DescribeLoadBasedAutoScalingRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeLoadBasedAutoScalingWithContext is the same as DescribeLoadBasedAutoScaling with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeLoadBasedAutoScaling 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 *OpsWorks) DescribeLoadBasedAutoScalingWithContext(ctx aws.Context, input *DescribeLoadBasedAutoScalingInput, opts ...request.Option) (*DescribeLoadBasedAutoScalingOutput, error) { + req, out := c.DescribeLoadBasedAutoScalingRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeMyUserProfile = "DescribeMyUserProfile" @@ -2443,8 +2935,23 @@ func (c *OpsWorks) DescribeMyUserProfileRequest(input *DescribeMyUserProfileInpu // Please also see https://docs.aws.amazon.com/goto/WebAPI/opsworks-2013-02-18/DescribeMyUserProfile func (c *OpsWorks) DescribeMyUserProfile(input *DescribeMyUserProfileInput) (*DescribeMyUserProfileOutput, error) { req, out := c.DescribeMyUserProfileRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeMyUserProfileWithContext is the same as DescribeMyUserProfile with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeMyUserProfile 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 *OpsWorks) DescribeMyUserProfileWithContext(ctx aws.Context, input *DescribeMyUserProfileInput, opts ...request.Option) (*DescribeMyUserProfileOutput, error) { + req, out := c.DescribeMyUserProfileRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribePermissions = "DescribePermissions" @@ -2516,8 +3023,23 @@ func (c *OpsWorks) DescribePermissionsRequest(input *DescribePermissionsInput) ( // Please also see https://docs.aws.amazon.com/goto/WebAPI/opsworks-2013-02-18/DescribePermissions func (c *OpsWorks) DescribePermissions(input *DescribePermissionsInput) (*DescribePermissionsOutput, error) { req, out := c.DescribePermissionsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribePermissionsWithContext is the same as DescribePermissions with the addition of +// the ability to pass a context and additional request options. +// +// See DescribePermissions 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 *OpsWorks) DescribePermissionsWithContext(ctx aws.Context, input *DescribePermissionsInput, opts ...request.Option) (*DescribePermissionsOutput, error) { + req, out := c.DescribePermissionsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeRaidArrays = "DescribeRaidArrays" @@ -2567,7 +3089,7 @@ func (c *OpsWorks) DescribeRaidArraysRequest(input *DescribeRaidArraysInput) (re // // Describe an instance's RAID arrays. // -// You must specify at least one of the parameters. +// This call accepts only one resource-identifying parameter. // // Required Permissions: To use this action, an IAM user must have a Show, Deploy, // or Manage permissions level for the stack, or an attached policy that explicitly @@ -2591,8 +3113,23 @@ func (c *OpsWorks) DescribeRaidArraysRequest(input *DescribeRaidArraysInput) (re // Please also see https://docs.aws.amazon.com/goto/WebAPI/opsworks-2013-02-18/DescribeRaidArrays func (c *OpsWorks) DescribeRaidArrays(input *DescribeRaidArraysInput) (*DescribeRaidArraysOutput, error) { req, out := c.DescribeRaidArraysRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeRaidArraysWithContext is the same as DescribeRaidArrays with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeRaidArrays 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 *OpsWorks) DescribeRaidArraysWithContext(ctx aws.Context, input *DescribeRaidArraysInput, opts ...request.Option) (*DescribeRaidArraysOutput, error) { + req, out := c.DescribeRaidArraysRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeRdsDbInstances = "DescribeRdsDbInstances" @@ -2647,6 +3184,8 @@ func (c *OpsWorks) DescribeRdsDbInstancesRequest(input *DescribeRdsDbInstancesIn // grants permissions. For more information on user permissions, see Managing // User Permissions (http://docs.aws.amazon.com/opsworks/latest/userguide/opsworks-security-users.html). // +// This call accepts only one resource-identifying parameter. +// // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about // the error. @@ -2664,8 +3203,23 @@ func (c *OpsWorks) DescribeRdsDbInstancesRequest(input *DescribeRdsDbInstancesIn // Please also see https://docs.aws.amazon.com/goto/WebAPI/opsworks-2013-02-18/DescribeRdsDbInstances func (c *OpsWorks) DescribeRdsDbInstances(input *DescribeRdsDbInstancesInput) (*DescribeRdsDbInstancesOutput, error) { req, out := c.DescribeRdsDbInstancesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeRdsDbInstancesWithContext is the same as DescribeRdsDbInstances with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeRdsDbInstances 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 *OpsWorks) DescribeRdsDbInstancesWithContext(ctx aws.Context, input *DescribeRdsDbInstancesInput, opts ...request.Option) (*DescribeRdsDbInstancesOutput, error) { + req, out := c.DescribeRdsDbInstancesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeServiceErrors = "DescribeServiceErrors" @@ -2713,13 +3267,15 @@ func (c *OpsWorks) DescribeServiceErrorsRequest(input *DescribeServiceErrorsInpu // DescribeServiceErrors API operation for AWS OpsWorks. // -// Describes AWS OpsWorks service errors. +// Describes AWS OpsWorks Stacks service errors. // // Required Permissions: To use this action, an IAM user must have a Show, Deploy, // or Manage permissions level for the stack, or an attached policy that explicitly // grants permissions. For more information on user permissions, see Managing // User Permissions (http://docs.aws.amazon.com/opsworks/latest/userguide/opsworks-security-users.html). // +// This call accepts only one resource-identifying parameter. +// // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about // the error. @@ -2737,8 +3293,23 @@ func (c *OpsWorks) DescribeServiceErrorsRequest(input *DescribeServiceErrorsInpu // Please also see https://docs.aws.amazon.com/goto/WebAPI/opsworks-2013-02-18/DescribeServiceErrors func (c *OpsWorks) DescribeServiceErrors(input *DescribeServiceErrorsInput) (*DescribeServiceErrorsOutput, error) { req, out := c.DescribeServiceErrorsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeServiceErrorsWithContext is the same as DescribeServiceErrors with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeServiceErrors 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 *OpsWorks) DescribeServiceErrorsWithContext(ctx aws.Context, input *DescribeServiceErrorsInput, opts ...request.Option) (*DescribeServiceErrorsOutput, error) { + req, out := c.DescribeServiceErrorsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeStackProvisioningParameters = "DescribeStackProvisioningParameters" @@ -2810,8 +3381,23 @@ func (c *OpsWorks) DescribeStackProvisioningParametersRequest(input *DescribeSta // Please also see https://docs.aws.amazon.com/goto/WebAPI/opsworks-2013-02-18/DescribeStackProvisioningParameters func (c *OpsWorks) DescribeStackProvisioningParameters(input *DescribeStackProvisioningParametersInput) (*DescribeStackProvisioningParametersOutput, error) { req, out := c.DescribeStackProvisioningParametersRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeStackProvisioningParametersWithContext is the same as DescribeStackProvisioningParameters with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeStackProvisioningParameters 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 *OpsWorks) DescribeStackProvisioningParametersWithContext(ctx aws.Context, input *DescribeStackProvisioningParametersInput, opts ...request.Option) (*DescribeStackProvisioningParametersOutput, error) { + req, out := c.DescribeStackProvisioningParametersRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeStackSummary = "DescribeStackSummary" @@ -2884,8 +3470,23 @@ func (c *OpsWorks) DescribeStackSummaryRequest(input *DescribeStackSummaryInput) // Please also see https://docs.aws.amazon.com/goto/WebAPI/opsworks-2013-02-18/DescribeStackSummary func (c *OpsWorks) DescribeStackSummary(input *DescribeStackSummaryInput) (*DescribeStackSummaryOutput, error) { req, out := c.DescribeStackSummaryRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeStackSummaryWithContext is the same as DescribeStackSummary with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeStackSummary 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 *OpsWorks) DescribeStackSummaryWithContext(ctx aws.Context, input *DescribeStackSummaryInput, opts ...request.Option) (*DescribeStackSummaryOutput, error) { + req, out := c.DescribeStackSummaryRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeStacks = "DescribeStacks" @@ -2957,8 +3558,23 @@ func (c *OpsWorks) DescribeStacksRequest(input *DescribeStacksInput) (req *reque // Please also see https://docs.aws.amazon.com/goto/WebAPI/opsworks-2013-02-18/DescribeStacks func (c *OpsWorks) DescribeStacks(input *DescribeStacksInput) (*DescribeStacksOutput, error) { req, out := c.DescribeStacksRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeStacksWithContext is the same as DescribeStacks with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeStacks 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 *OpsWorks) DescribeStacksWithContext(ctx aws.Context, input *DescribeStacksInput, opts ...request.Option) (*DescribeStacksOutput, error) { + req, out := c.DescribeStacksRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeTimeBasedAutoScaling = "DescribeTimeBasedAutoScaling" @@ -3032,8 +3648,23 @@ func (c *OpsWorks) DescribeTimeBasedAutoScalingRequest(input *DescribeTimeBasedA // Please also see https://docs.aws.amazon.com/goto/WebAPI/opsworks-2013-02-18/DescribeTimeBasedAutoScaling func (c *OpsWorks) DescribeTimeBasedAutoScaling(input *DescribeTimeBasedAutoScalingInput) (*DescribeTimeBasedAutoScalingOutput, error) { req, out := c.DescribeTimeBasedAutoScalingRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeTimeBasedAutoScalingWithContext is the same as DescribeTimeBasedAutoScaling with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeTimeBasedAutoScaling 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 *OpsWorks) DescribeTimeBasedAutoScalingWithContext(ctx aws.Context, input *DescribeTimeBasedAutoScalingInput, opts ...request.Option) (*DescribeTimeBasedAutoScalingOutput, error) { + req, out := c.DescribeTimeBasedAutoScalingRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeUserProfiles = "DescribeUserProfiles" @@ -3104,8 +3735,23 @@ func (c *OpsWorks) DescribeUserProfilesRequest(input *DescribeUserProfilesInput) // Please also see https://docs.aws.amazon.com/goto/WebAPI/opsworks-2013-02-18/DescribeUserProfiles func (c *OpsWorks) DescribeUserProfiles(input *DescribeUserProfilesInput) (*DescribeUserProfilesOutput, error) { req, out := c.DescribeUserProfilesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeUserProfilesWithContext is the same as DescribeUserProfiles with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeUserProfiles 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 *OpsWorks) DescribeUserProfilesWithContext(ctx aws.Context, input *DescribeUserProfilesInput, opts ...request.Option) (*DescribeUserProfilesOutput, error) { + req, out := c.DescribeUserProfilesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeVolumes = "DescribeVolumes" @@ -3155,7 +3801,7 @@ func (c *OpsWorks) DescribeVolumesRequest(input *DescribeVolumesInput) (req *req // // Describes an instance's Amazon EBS volumes. // -// You must specify at least one of the parameters. +// This call accepts only one resource-identifying parameter. // // Required Permissions: To use this action, an IAM user must have a Show, Deploy, // or Manage permissions level for the stack, or an attached policy that explicitly @@ -3179,8 +3825,23 @@ func (c *OpsWorks) DescribeVolumesRequest(input *DescribeVolumesInput) (req *req // Please also see https://docs.aws.amazon.com/goto/WebAPI/opsworks-2013-02-18/DescribeVolumes func (c *OpsWorks) DescribeVolumes(input *DescribeVolumesInput) (*DescribeVolumesOutput, error) { req, out := c.DescribeVolumesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeVolumesWithContext is the same as DescribeVolumes with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeVolumes 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 *OpsWorks) DescribeVolumesWithContext(ctx aws.Context, input *DescribeVolumesInput, opts ...request.Option) (*DescribeVolumesOutput, error) { + req, out := c.DescribeVolumesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDetachElasticLoadBalancer = "DetachElasticLoadBalancer" @@ -3251,8 +3912,23 @@ func (c *OpsWorks) DetachElasticLoadBalancerRequest(input *DetachElasticLoadBala // Please also see https://docs.aws.amazon.com/goto/WebAPI/opsworks-2013-02-18/DetachElasticLoadBalancer func (c *OpsWorks) DetachElasticLoadBalancer(input *DetachElasticLoadBalancerInput) (*DetachElasticLoadBalancerOutput, error) { req, out := c.DetachElasticLoadBalancerRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DetachElasticLoadBalancerWithContext is the same as DetachElasticLoadBalancer with the addition of +// the ability to pass a context and additional request options. +// +// See DetachElasticLoadBalancer 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 *OpsWorks) DetachElasticLoadBalancerWithContext(ctx aws.Context, input *DetachElasticLoadBalancerInput, opts ...request.Option) (*DetachElasticLoadBalancerOutput, error) { + req, out := c.DetachElasticLoadBalancerRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDisassociateElasticIp = "DisassociateElasticIp" @@ -3328,8 +4004,23 @@ func (c *OpsWorks) DisassociateElasticIpRequest(input *DisassociateElasticIpInpu // Please also see https://docs.aws.amazon.com/goto/WebAPI/opsworks-2013-02-18/DisassociateElasticIp func (c *OpsWorks) DisassociateElasticIp(input *DisassociateElasticIpInput) (*DisassociateElasticIpOutput, error) { req, out := c.DisassociateElasticIpRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DisassociateElasticIpWithContext is the same as DisassociateElasticIp with the addition of +// the ability to pass a context and additional request options. +// +// See DisassociateElasticIp 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 *OpsWorks) DisassociateElasticIpWithContext(ctx aws.Context, input *DisassociateElasticIpInput, opts ...request.Option) (*DisassociateElasticIpOutput, error) { + req, out := c.DisassociateElasticIpRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetHostnameSuggestion = "GetHostnameSuggestion" @@ -3402,8 +4093,23 @@ func (c *OpsWorks) GetHostnameSuggestionRequest(input *GetHostnameSuggestionInpu // Please also see https://docs.aws.amazon.com/goto/WebAPI/opsworks-2013-02-18/GetHostnameSuggestion func (c *OpsWorks) GetHostnameSuggestion(input *GetHostnameSuggestionInput) (*GetHostnameSuggestionOutput, error) { req, out := c.GetHostnameSuggestionRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetHostnameSuggestionWithContext is the same as GetHostnameSuggestion with the addition of +// the ability to pass a context and additional request options. +// +// See GetHostnameSuggestion 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 *OpsWorks) GetHostnameSuggestionWithContext(ctx aws.Context, input *GetHostnameSuggestionInput, opts ...request.Option) (*GetHostnameSuggestionOutput, error) { + req, out := c.GetHostnameSuggestionRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGrantAccess = "GrantAccess" @@ -3472,8 +4178,23 @@ func (c *OpsWorks) GrantAccessRequest(input *GrantAccessInput) (req *request.Req // Please also see https://docs.aws.amazon.com/goto/WebAPI/opsworks-2013-02-18/GrantAccess func (c *OpsWorks) GrantAccess(input *GrantAccessInput) (*GrantAccessOutput, error) { req, out := c.GrantAccessRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GrantAccessWithContext is the same as GrantAccess with the addition of +// the ability to pass a context and additional request options. +// +// See GrantAccess 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 *OpsWorks) GrantAccessWithContext(ctx aws.Context, input *GrantAccessInput, opts ...request.Option) (*GrantAccessOutput, error) { + req, out := c.GrantAccessRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opRebootInstance = "RebootInstance" @@ -3548,8 +4269,23 @@ func (c *OpsWorks) RebootInstanceRequest(input *RebootInstanceInput) (req *reque // Please also see https://docs.aws.amazon.com/goto/WebAPI/opsworks-2013-02-18/RebootInstance func (c *OpsWorks) RebootInstance(input *RebootInstanceInput) (*RebootInstanceOutput, error) { req, out := c.RebootInstanceRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// RebootInstanceWithContext is the same as RebootInstance with the addition of +// the ability to pass a context and additional request options. +// +// See RebootInstance 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 *OpsWorks) RebootInstanceWithContext(ctx aws.Context, input *RebootInstanceInput, opts ...request.Option) (*RebootInstanceOutput, error) { + req, out := c.RebootInstanceRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opRegisterEcsCluster = "RegisterEcsCluster" @@ -3623,8 +4359,23 @@ func (c *OpsWorks) RegisterEcsClusterRequest(input *RegisterEcsClusterInput) (re // Please also see https://docs.aws.amazon.com/goto/WebAPI/opsworks-2013-02-18/RegisterEcsCluster func (c *OpsWorks) RegisterEcsCluster(input *RegisterEcsClusterInput) (*RegisterEcsClusterOutput, error) { req, out := c.RegisterEcsClusterRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// RegisterEcsClusterWithContext is the same as RegisterEcsCluster with the addition of +// the ability to pass a context and additional request options. +// +// See RegisterEcsCluster 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 *OpsWorks) RegisterEcsClusterWithContext(ctx aws.Context, input *RegisterEcsClusterInput, opts ...request.Option) (*RegisterEcsClusterOutput, error) { + req, out := c.RegisterEcsClusterRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opRegisterElasticIp = "RegisterElasticIp" @@ -3699,8 +4450,23 @@ func (c *OpsWorks) RegisterElasticIpRequest(input *RegisterElasticIpInput) (req // Please also see https://docs.aws.amazon.com/goto/WebAPI/opsworks-2013-02-18/RegisterElasticIp func (c *OpsWorks) RegisterElasticIp(input *RegisterElasticIpInput) (*RegisterElasticIpOutput, error) { req, out := c.RegisterElasticIpRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// RegisterElasticIpWithContext is the same as RegisterElasticIp with the addition of +// the ability to pass a context and additional request options. +// +// See RegisterElasticIp 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 *OpsWorks) RegisterElasticIpWithContext(ctx aws.Context, input *RegisterElasticIpInput, opts ...request.Option) (*RegisterElasticIpOutput, error) { + req, out := c.RegisterElasticIpRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opRegisterInstance = "RegisterInstance" @@ -3748,15 +4514,21 @@ func (c *OpsWorks) RegisterInstanceRequest(input *RegisterInstanceInput) (req *r // RegisterInstance API operation for AWS OpsWorks. // -// Registers instances with a specified stack that were created outside of AWS -// OpsWorks. +// Registers instances that were created outside of AWS OpsWorks Stacks with +// a specified stack. // // We do not recommend using this action to register instances. The complete -// registration operation has two primary steps, installing the AWS OpsWorks -// agent on the instance and registering the instance with the stack. RegisterInstance +// registration operation includes two tasks: installing the AWS OpsWorks Stacks +// agent on the instance, and registering the instance with the stack. RegisterInstance // handles only the second step. You should instead use the AWS CLI register // command, which performs the entire registration operation. For more information, -// see Registering an Instance with an AWS OpsWorks Stack (http://docs.aws.amazon.com/opsworks/latest/userguide/registered-instances-register.html). +// see Registering an Instance with an AWS OpsWorks Stacks Stack (http://docs.aws.amazon.com/opsworks/latest/userguide/registered-instances-register.html). +// +// Registered instances have the same requirements as instances that are created +// by using the CreateInstance API. For example, registered instances must be +// running a supported Linux-based operating system, and they must have a supported +// instance type. For more information about requirements for instances that +// you want to register, see Preparing the Instance (http://docs.aws.amazon.com/opsworks/latest/userguide/registered-instances-register-registering-preparer.html). // // Required Permissions: To use this action, an IAM user must have a Manage // permissions level for the stack or an attached policy that explicitly grants @@ -3780,8 +4552,23 @@ func (c *OpsWorks) RegisterInstanceRequest(input *RegisterInstanceInput) (req *r // Please also see https://docs.aws.amazon.com/goto/WebAPI/opsworks-2013-02-18/RegisterInstance func (c *OpsWorks) RegisterInstance(input *RegisterInstanceInput) (*RegisterInstanceOutput, error) { req, out := c.RegisterInstanceRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// RegisterInstanceWithContext is the same as RegisterInstance with the addition of +// the ability to pass a context and additional request options. +// +// See RegisterInstance 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 *OpsWorks) RegisterInstanceWithContext(ctx aws.Context, input *RegisterInstanceInput, opts ...request.Option) (*RegisterInstanceOutput, error) { + req, out := c.RegisterInstanceRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opRegisterRdsDbInstance = "RegisterRdsDbInstance" @@ -3855,8 +4642,23 @@ func (c *OpsWorks) RegisterRdsDbInstanceRequest(input *RegisterRdsDbInstanceInpu // Please also see https://docs.aws.amazon.com/goto/WebAPI/opsworks-2013-02-18/RegisterRdsDbInstance func (c *OpsWorks) RegisterRdsDbInstance(input *RegisterRdsDbInstanceInput) (*RegisterRdsDbInstanceOutput, error) { req, out := c.RegisterRdsDbInstanceRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// RegisterRdsDbInstanceWithContext is the same as RegisterRdsDbInstance with the addition of +// the ability to pass a context and additional request options. +// +// See RegisterRdsDbInstance 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 *OpsWorks) RegisterRdsDbInstanceWithContext(ctx aws.Context, input *RegisterRdsDbInstanceInput, opts ...request.Option) (*RegisterRdsDbInstanceOutput, error) { + req, out := c.RegisterRdsDbInstanceRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opRegisterVolume = "RegisterVolume" @@ -3931,8 +4733,23 @@ func (c *OpsWorks) RegisterVolumeRequest(input *RegisterVolumeInput) (req *reque // Please also see https://docs.aws.amazon.com/goto/WebAPI/opsworks-2013-02-18/RegisterVolume func (c *OpsWorks) RegisterVolume(input *RegisterVolumeInput) (*RegisterVolumeOutput, error) { req, out := c.RegisterVolumeRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// RegisterVolumeWithContext is the same as RegisterVolume with the addition of +// the ability to pass a context and additional request options. +// +// See RegisterVolume 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 *OpsWorks) RegisterVolumeWithContext(ctx aws.Context, input *RegisterVolumeInput, opts ...request.Option) (*RegisterVolumeOutput, error) { + req, out := c.RegisterVolumeRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opSetLoadBasedAutoScaling = "SetLoadBasedAutoScaling" @@ -4013,8 +4830,23 @@ func (c *OpsWorks) SetLoadBasedAutoScalingRequest(input *SetLoadBasedAutoScaling // Please also see https://docs.aws.amazon.com/goto/WebAPI/opsworks-2013-02-18/SetLoadBasedAutoScaling func (c *OpsWorks) SetLoadBasedAutoScaling(input *SetLoadBasedAutoScalingInput) (*SetLoadBasedAutoScalingOutput, error) { req, out := c.SetLoadBasedAutoScalingRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// SetLoadBasedAutoScalingWithContext is the same as SetLoadBasedAutoScaling with the addition of +// the ability to pass a context and additional request options. +// +// See SetLoadBasedAutoScaling 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 *OpsWorks) SetLoadBasedAutoScalingWithContext(ctx aws.Context, input *SetLoadBasedAutoScalingInput, opts ...request.Option) (*SetLoadBasedAutoScalingOutput, error) { + req, out := c.SetLoadBasedAutoScalingRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opSetPermission = "SetPermission" @@ -4089,8 +4921,23 @@ func (c *OpsWorks) SetPermissionRequest(input *SetPermissionInput) (req *request // Please also see https://docs.aws.amazon.com/goto/WebAPI/opsworks-2013-02-18/SetPermission func (c *OpsWorks) SetPermission(input *SetPermissionInput) (*SetPermissionOutput, error) { req, out := c.SetPermissionRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// SetPermissionWithContext is the same as SetPermission with the addition of +// the ability to pass a context and additional request options. +// +// See SetPermission 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 *OpsWorks) SetPermissionWithContext(ctx aws.Context, input *SetPermissionInput, opts ...request.Option) (*SetPermissionOutput, error) { + req, out := c.SetPermissionRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opSetTimeBasedAutoScaling = "SetTimeBasedAutoScaling" @@ -4166,8 +5013,23 @@ func (c *OpsWorks) SetTimeBasedAutoScalingRequest(input *SetTimeBasedAutoScaling // Please also see https://docs.aws.amazon.com/goto/WebAPI/opsworks-2013-02-18/SetTimeBasedAutoScaling func (c *OpsWorks) SetTimeBasedAutoScaling(input *SetTimeBasedAutoScalingInput) (*SetTimeBasedAutoScalingOutput, error) { req, out := c.SetTimeBasedAutoScalingRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// SetTimeBasedAutoScalingWithContext is the same as SetTimeBasedAutoScaling with the addition of +// the ability to pass a context and additional request options. +// +// See SetTimeBasedAutoScaling 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 *OpsWorks) SetTimeBasedAutoScalingWithContext(ctx aws.Context, input *SetTimeBasedAutoScalingInput, opts ...request.Option) (*SetTimeBasedAutoScalingOutput, error) { + req, out := c.SetTimeBasedAutoScalingRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opStartInstance = "StartInstance" @@ -4242,8 +5104,23 @@ func (c *OpsWorks) StartInstanceRequest(input *StartInstanceInput) (req *request // Please also see https://docs.aws.amazon.com/goto/WebAPI/opsworks-2013-02-18/StartInstance func (c *OpsWorks) StartInstance(input *StartInstanceInput) (*StartInstanceOutput, error) { req, out := c.StartInstanceRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// StartInstanceWithContext is the same as StartInstance with the addition of +// the ability to pass a context and additional request options. +// +// See StartInstance 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 *OpsWorks) StartInstanceWithContext(ctx aws.Context, input *StartInstanceInput, opts ...request.Option) (*StartInstanceOutput, error) { + req, out := c.StartInstanceRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opStartStack = "StartStack" @@ -4317,8 +5194,23 @@ func (c *OpsWorks) StartStackRequest(input *StartStackInput) (req *request.Reque // Please also see https://docs.aws.amazon.com/goto/WebAPI/opsworks-2013-02-18/StartStack func (c *OpsWorks) StartStack(input *StartStackInput) (*StartStackOutput, error) { req, out := c.StartStackRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// StartStackWithContext is the same as StartStack with the addition of +// the ability to pass a context and additional request options. +// +// See StartStack 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 *OpsWorks) StartStackWithContext(ctx aws.Context, input *StartStackInput, opts ...request.Option) (*StartStackOutput, error) { + req, out := c.StartStackRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opStopInstance = "StopInstance" @@ -4395,8 +5287,23 @@ func (c *OpsWorks) StopInstanceRequest(input *StopInstanceInput) (req *request.R // Please also see https://docs.aws.amazon.com/goto/WebAPI/opsworks-2013-02-18/StopInstance func (c *OpsWorks) StopInstance(input *StopInstanceInput) (*StopInstanceOutput, error) { req, out := c.StopInstanceRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// StopInstanceWithContext is the same as StopInstance with the addition of +// the ability to pass a context and additional request options. +// +// See StopInstance 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 *OpsWorks) StopInstanceWithContext(ctx aws.Context, input *StopInstanceInput, opts ...request.Option) (*StopInstanceOutput, error) { + req, out := c.StopInstanceRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opStopStack = "StopStack" @@ -4470,8 +5377,23 @@ func (c *OpsWorks) StopStackRequest(input *StopStackInput) (req *request.Request // Please also see https://docs.aws.amazon.com/goto/WebAPI/opsworks-2013-02-18/StopStack func (c *OpsWorks) StopStack(input *StopStackInput) (*StopStackOutput, error) { req, out := c.StopStackRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// StopStackWithContext is the same as StopStack with the addition of +// the ability to pass a context and additional request options. +// +// See StopStack 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 *OpsWorks) StopStackWithContext(ctx aws.Context, input *StopStackInput, opts ...request.Option) (*StopStackOutput, error) { + req, out := c.StopStackRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opUnassignInstance = "UnassignInstance" @@ -4524,7 +5446,7 @@ func (c *OpsWorks) UnassignInstanceRequest(input *UnassignInstanceInput) (req *r // Unassigns a registered instance from all of it's layers. The instance remains // in the stack as an unassigned instance and can be assigned to another layer, // as needed. You cannot use this action with instances that were created with -// AWS OpsWorks. +// AWS OpsWorks Stacks. // // Required Permissions: To use this action, an IAM user must have a Manage // permissions level for the stack or an attached policy that explicitly grants @@ -4548,8 +5470,23 @@ func (c *OpsWorks) UnassignInstanceRequest(input *UnassignInstanceInput) (req *r // Please also see https://docs.aws.amazon.com/goto/WebAPI/opsworks-2013-02-18/UnassignInstance func (c *OpsWorks) UnassignInstance(input *UnassignInstanceInput) (*UnassignInstanceOutput, error) { req, out := c.UnassignInstanceRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// UnassignInstanceWithContext is the same as UnassignInstance with the addition of +// the ability to pass a context and additional request options. +// +// See UnassignInstance 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 *OpsWorks) UnassignInstanceWithContext(ctx aws.Context, input *UnassignInstanceInput, opts ...request.Option) (*UnassignInstanceOutput, error) { + req, out := c.UnassignInstanceRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opUnassignVolume = "UnassignVolume" @@ -4624,8 +5561,23 @@ func (c *OpsWorks) UnassignVolumeRequest(input *UnassignVolumeInput) (req *reque // Please also see https://docs.aws.amazon.com/goto/WebAPI/opsworks-2013-02-18/UnassignVolume func (c *OpsWorks) UnassignVolume(input *UnassignVolumeInput) (*UnassignVolumeOutput, error) { req, out := c.UnassignVolumeRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// UnassignVolumeWithContext is the same as UnassignVolume with the addition of +// the ability to pass a context and additional request options. +// +// See UnassignVolume 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 *OpsWorks) UnassignVolumeWithContext(ctx aws.Context, input *UnassignVolumeInput, opts ...request.Option) (*UnassignVolumeOutput, error) { + req, out := c.UnassignVolumeRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opUpdateApp = "UpdateApp" @@ -4699,8 +5651,23 @@ func (c *OpsWorks) UpdateAppRequest(input *UpdateAppInput) (req *request.Request // Please also see https://docs.aws.amazon.com/goto/WebAPI/opsworks-2013-02-18/UpdateApp func (c *OpsWorks) UpdateApp(input *UpdateAppInput) (*UpdateAppOutput, error) { req, out := c.UpdateAppRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// UpdateAppWithContext is the same as UpdateApp with the addition of +// the ability to pass a context and additional request options. +// +// See UpdateApp 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 *OpsWorks) UpdateAppWithContext(ctx aws.Context, input *UpdateAppInput, opts ...request.Option) (*UpdateAppOutput, error) { + req, out := c.UpdateAppRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opUpdateElasticIp = "UpdateElasticIp" @@ -4775,8 +5742,23 @@ func (c *OpsWorks) UpdateElasticIpRequest(input *UpdateElasticIpInput) (req *req // Please also see https://docs.aws.amazon.com/goto/WebAPI/opsworks-2013-02-18/UpdateElasticIp func (c *OpsWorks) UpdateElasticIp(input *UpdateElasticIpInput) (*UpdateElasticIpOutput, error) { req, out := c.UpdateElasticIpRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// UpdateElasticIpWithContext is the same as UpdateElasticIp with the addition of +// the ability to pass a context and additional request options. +// +// See UpdateElasticIp 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 *OpsWorks) UpdateElasticIpWithContext(ctx aws.Context, input *UpdateElasticIpInput, opts ...request.Option) (*UpdateElasticIpOutput, error) { + req, out := c.UpdateElasticIpRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opUpdateInstance = "UpdateInstance" @@ -4850,8 +5832,23 @@ func (c *OpsWorks) UpdateInstanceRequest(input *UpdateInstanceInput) (req *reque // Please also see https://docs.aws.amazon.com/goto/WebAPI/opsworks-2013-02-18/UpdateInstance func (c *OpsWorks) UpdateInstance(input *UpdateInstanceInput) (*UpdateInstanceOutput, error) { req, out := c.UpdateInstanceRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// UpdateInstanceWithContext is the same as UpdateInstance with the addition of +// the ability to pass a context and additional request options. +// +// See UpdateInstance 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 *OpsWorks) UpdateInstanceWithContext(ctx aws.Context, input *UpdateInstanceInput, opts ...request.Option) (*UpdateInstanceOutput, error) { + req, out := c.UpdateInstanceRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opUpdateLayer = "UpdateLayer" @@ -4925,8 +5922,23 @@ func (c *OpsWorks) UpdateLayerRequest(input *UpdateLayerInput) (req *request.Req // Please also see https://docs.aws.amazon.com/goto/WebAPI/opsworks-2013-02-18/UpdateLayer func (c *OpsWorks) UpdateLayer(input *UpdateLayerInput) (*UpdateLayerOutput, error) { req, out := c.UpdateLayerRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// UpdateLayerWithContext is the same as UpdateLayer with the addition of +// the ability to pass a context and additional request options. +// +// See UpdateLayer 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 *OpsWorks) UpdateLayerWithContext(ctx aws.Context, input *UpdateLayerInput, opts ...request.Option) (*UpdateLayerOutput, error) { + req, out := c.UpdateLayerRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opUpdateMyUserProfile = "UpdateMyUserProfile" @@ -4996,8 +6008,23 @@ func (c *OpsWorks) UpdateMyUserProfileRequest(input *UpdateMyUserProfileInput) ( // Please also see https://docs.aws.amazon.com/goto/WebAPI/opsworks-2013-02-18/UpdateMyUserProfile func (c *OpsWorks) UpdateMyUserProfile(input *UpdateMyUserProfileInput) (*UpdateMyUserProfileOutput, error) { req, out := c.UpdateMyUserProfileRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// UpdateMyUserProfileWithContext is the same as UpdateMyUserProfile with the addition of +// the ability to pass a context and additional request options. +// +// See UpdateMyUserProfile 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 *OpsWorks) UpdateMyUserProfileWithContext(ctx aws.Context, input *UpdateMyUserProfileInput, opts ...request.Option) (*UpdateMyUserProfileOutput, error) { + req, out := c.UpdateMyUserProfileRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opUpdateRdsDbInstance = "UpdateRdsDbInstance" @@ -5071,8 +6098,23 @@ func (c *OpsWorks) UpdateRdsDbInstanceRequest(input *UpdateRdsDbInstanceInput) ( // Please also see https://docs.aws.amazon.com/goto/WebAPI/opsworks-2013-02-18/UpdateRdsDbInstance func (c *OpsWorks) UpdateRdsDbInstance(input *UpdateRdsDbInstanceInput) (*UpdateRdsDbInstanceOutput, error) { req, out := c.UpdateRdsDbInstanceRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// UpdateRdsDbInstanceWithContext is the same as UpdateRdsDbInstance with the addition of +// the ability to pass a context and additional request options. +// +// See UpdateRdsDbInstance 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 *OpsWorks) UpdateRdsDbInstanceWithContext(ctx aws.Context, input *UpdateRdsDbInstanceInput, opts ...request.Option) (*UpdateRdsDbInstanceOutput, error) { + req, out := c.UpdateRdsDbInstanceRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opUpdateStack = "UpdateStack" @@ -5146,8 +6188,23 @@ func (c *OpsWorks) UpdateStackRequest(input *UpdateStackInput) (req *request.Req // Please also see https://docs.aws.amazon.com/goto/WebAPI/opsworks-2013-02-18/UpdateStack func (c *OpsWorks) UpdateStack(input *UpdateStackInput) (*UpdateStackOutput, error) { req, out := c.UpdateStackRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// UpdateStackWithContext is the same as UpdateStack with the addition of +// the ability to pass a context and additional request options. +// +// See UpdateStack 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 *OpsWorks) UpdateStackWithContext(ctx aws.Context, input *UpdateStackInput, opts ...request.Option) (*UpdateStackOutput, error) { + req, out := c.UpdateStackRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opUpdateUserProfile = "UpdateUserProfile" @@ -5220,8 +6277,23 @@ func (c *OpsWorks) UpdateUserProfileRequest(input *UpdateUserProfileInput) (req // Please also see https://docs.aws.amazon.com/goto/WebAPI/opsworks-2013-02-18/UpdateUserProfile func (c *OpsWorks) UpdateUserProfile(input *UpdateUserProfileInput) (*UpdateUserProfileOutput, error) { req, out := c.UpdateUserProfileRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// UpdateUserProfileWithContext is the same as UpdateUserProfile with the addition of +// the ability to pass a context and additional request options. +// +// See UpdateUserProfile 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 *OpsWorks) UpdateUserProfileWithContext(ctx aws.Context, input *UpdateUserProfileInput, opts ...request.Option) (*UpdateUserProfileOutput, error) { + req, out := c.UpdateUserProfileRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opUpdateVolume = "UpdateVolume" @@ -5296,8 +6368,23 @@ func (c *OpsWorks) UpdateVolumeRequest(input *UpdateVolumeInput) (req *request.R // Please also see https://docs.aws.amazon.com/goto/WebAPI/opsworks-2013-02-18/UpdateVolume func (c *OpsWorks) UpdateVolume(input *UpdateVolumeInput) (*UpdateVolumeOutput, error) { req, out := c.UpdateVolumeRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// UpdateVolumeWithContext is the same as UpdateVolume with the addition of +// the ability to pass a context and additional request options. +// +// See UpdateVolume 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 *OpsWorks) UpdateVolumeWithContext(ctx aws.Context, input *UpdateVolumeInput, opts ...request.Option) (*UpdateVolumeOutput, error) { + req, out := c.UpdateVolumeRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // Describes an agent version. @@ -5752,7 +6839,7 @@ func (s AttachElasticLoadBalancerOutput) GoString() string { } // Describes a load-based auto scaling upscaling or downscaling threshold configuration, -// which specifies when AWS OpsWorks starts or stops load-based instances. +// which specifies when AWS OpsWorks Stacks starts or stops load-based instances. // Please also see https://docs.aws.amazon.com/goto/WebAPI/opsworks-2013-02-18/AutoScalingThresholds type AutoScalingThresholds struct { _ struct{} `type:"structure"` @@ -5762,9 +6849,9 @@ type AutoScalingThresholds struct { // be in the same region as the stack. // // To use custom alarms, you must update your service role to allow cloudwatch:DescribeAlarms. - // You can either have AWS OpsWorks update the role for you when you first use - // this feature or you can edit the role manually. For more information, see - // Allowing AWS OpsWorks to Act on Your Behalf (http://docs.aws.amazon.com/opsworks/latest/userguide/opsworks-security-servicerole.html). + // You can either have AWS OpsWorks Stacks update the role for you when you + // first use this feature or you can edit the role manually. For more information, + // see Allowing AWS OpsWorks Stacks to Act on Your Behalf (http://docs.aws.amazon.com/opsworks/latest/userguide/opsworks-security-servicerole.html). Alarms []*string `type:"list"` // The CPU utilization threshold, as a percent of the available CPU. A value @@ -5772,13 +6859,13 @@ type AutoScalingThresholds struct { CpuThreshold *float64 `type:"double"` // The amount of time (in minutes) after a scaling event occurs that AWS OpsWorks - // should ignore metrics and suppress additional scaling events. For example, - // AWS OpsWorks adds new instances following an upscaling event but the instances - // won't start reducing the load until they have been booted and configured. - // There is no point in raising additional scaling events during that operation, - // which typically takes several minutes. IgnoreMetricsTime allows you to direct - // AWS OpsWorks to suppress scaling events long enough to get the new instances - // online. + // Stacks should ignore metrics and suppress additional scaling events. For + // example, AWS OpsWorks Stacks adds new instances following an upscaling event + // but the instances won't start reducing the load until they have been booted + // and configured. There is no point in raising additional scaling events during + // that operation, which typically takes several minutes. IgnoreMetricsTime + // allows you to direct AWS OpsWorks Stacks to suppress scaling events long + // enough to get the new instances online. IgnoreMetricsTime *int64 `min:"1" type:"integer"` // The number of instances to add or remove when the load exceeds a threshold. @@ -5874,7 +6961,7 @@ type BlockDeviceMapping struct { // The device name that is exposed to the instance, such as /dev/sdh. For the // root device, you can use the explicit device name or you can set this parameter - // to ROOT_DEVICE and AWS OpsWorks will provide the correct device name. + // to ROOT_DEVICE and AWS OpsWorks Stacks will provide the correct device name. DeviceName *string `type:"string"` // An EBSBlockDevice that defines how to configure an Amazon EBS volume when @@ -5960,20 +7047,21 @@ func (s *ChefConfiguration) SetManageBerkshelf(v bool) *ChefConfiguration { type CloneStackInput struct { _ struct{} `type:"structure"` - // The default AWS OpsWorks agent version. You have the following options: + // The default AWS OpsWorks Stacks agent version. You have the following options: // - // * Auto-update - Set this parameter to LATEST. AWS OpsWorks automatically + // * Auto-update - Set this parameter to LATEST. AWS OpsWorks Stacks automatically // installs new agent versions on the stack's instances as soon as they are // available. // // * Fixed version - Set this parameter to your preferred agent version. // To update the agent version, you must edit the stack configuration and - // specify a new version. AWS OpsWorks then automatically installs that version - // on the stack's instances. + // specify a new version. AWS OpsWorks Stacks then automatically installs + // that version on the stack's instances. // // The default setting is LATEST. To specify an agent version, you must use // the complete version number, not the abbreviated number shown on the console. // For a list of available agent version numbers, call DescribeAgentVersions. + // AgentVersion cannot be set to Chef 12.2. // // You can also specify an agent version when you create or update an instance, // which overrides the stack's default setting. @@ -6029,12 +7117,13 @@ type CloneStackInput struct { // The stack's operating system, which must be set to one of the following. // // * A supported Linux operating system: An Amazon Linux version, such as - // Amazon Linux 2016.03, Amazon Linux 2015.09, or Amazon Linux 2015.03. + // Amazon Linux 2016.09, Amazon Linux 2016.03, Amazon Linux 2015.09, or Amazon + // Linux 2015.03. // // * A supported Ubuntu operating system, such as Ubuntu 16.04 LTS, Ubuntu // 14.04 LTS, or Ubuntu 12.04 LTS. // - // * CentOS 7 + // * CentOS Linux 7 // // * Red Hat Enterprise Linux 7 // @@ -6047,7 +7136,8 @@ type CloneStackInput struct { // OpsWorks, see Using Custom AMIs (http://docs.aws.amazon.com/opsworks/latest/userguide/workinginstances-custom-ami.html). // // The default option is the parent stack's operating system. For more information - // on the supported operating systems, see AWS OpsWorks Operating Systems (http://docs.aws.amazon.com/opsworks/latest/userguide/workinginstances-os.html). + // on the supported operating systems, see AWS OpsWorks Stacks Operating Systems + // (http://docs.aws.amazon.com/opsworks/latest/userguide/workinginstances-os.html). // // You can specify a different Linux operating system for the cloned stack, // but you cannot change from Linux to Windows or Windows to Linux. @@ -6114,11 +7204,12 @@ type CloneStackInput struct { Region *string `type:"string"` // The stack AWS Identity and Access Management (IAM) role, which allows AWS - // OpsWorks to work with AWS resources on your behalf. You must set this parameter - // to the Amazon Resource Name (ARN) for an existing IAM role. If you create - // a stack by using the AWS OpsWorks console, it creates the role for you. You - // can obtain an existing stack's IAM ARN programmatically by calling DescribePermissions. - // For more information about IAM ARNs, see Using Identifiers (http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html). + // OpsWorks Stacks to work with AWS resources on your behalf. You must set this + // parameter to the Amazon Resource Name (ARN) for an existing IAM role. If + // you create a stack by using the AWS OpsWorks Stacks console, it creates the + // role for you. You can obtain an existing stack's IAM ARN programmatically + // by calling DescribePermissions. For more information about IAM ARNs, see + // Using Identifiers (http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html). // // You must set this parameter to a valid service role ARN or the action will // fail; there is no default value. You can specify the source stack's service @@ -6135,25 +7226,25 @@ type CloneStackInput struct { // Whether to use custom cookbooks. UseCustomCookbooks *bool `type:"boolean"` - // Whether to associate the AWS OpsWorks built-in security groups with the stack's - // layers. + // Whether to associate the AWS OpsWorks Stacks built-in security groups with + // the stack's layers. // - // AWS OpsWorks provides a standard set of built-in security groups, one for - // each layer, which are associated with layers by default. With UseOpsworksSecurityGroups + // AWS OpsWorks Stacks provides a standard set of built-in security groups, + // one for each layer, which are associated with layers by default. With UseOpsworksSecurityGroups // you can instead provide your own custom security groups. UseOpsworksSecurityGroups // has the following settings: // - // * True - AWS OpsWorks automatically associates the appropriate built-in - // security group with each layer (default setting). You can associate additional - // security groups with a layer after you create it but you cannot delete - // the built-in security group. + // * True - AWS OpsWorks Stacks automatically associates the appropriate + // built-in security group with each layer (default setting). You can associate + // additional security groups with a layer after you create it but you cannot + // delete the built-in security group. // - // * False - AWS OpsWorks does not associate built-in security groups with - // layers. You must create appropriate Amazon Elastic Compute Cloud (Amazon - // EC2) security groups and associate a security group with each layer that - // you create. However, you can still manually associate a built-in security - // group with a layer on creation; custom security groups are required only - // for those layers that need custom settings. + // * False - AWS OpsWorks Stacks does not associate built-in security groups + // with layers. You must create appropriate Amazon Elastic Compute Cloud + // (Amazon EC2) security groups and associate a security group with each + // layer that you create. However, you can still manually associate a built-in + // security group with a layer on creation; custom security groups are required + // only for those layers that need custom settings. // // For more information, see Create a New Stack (http://docs.aws.amazon.com/opsworks/latest/userguide/workingstacks-creating.html). UseOpsworksSecurityGroups *bool `type:"boolean"` @@ -6169,9 +7260,10 @@ type CloneStackInput struct { // // If the VPC ID corresponds to a default VPC and you have specified either // the DefaultAvailabilityZone or the DefaultSubnetId parameter only, AWS OpsWorks - // infers the value of the other parameter. If you specify neither parameter, - // AWS OpsWorks sets these parameters to the first valid Availability Zone for - // the specified region and the corresponding default VPC subnet ID, respectively. + // Stacks infers the value of the other parameter. If you specify neither parameter, + // AWS OpsWorks Stacks sets these parameters to the first valid Availability + // Zone for the specified region and the corresponding default VPC subnet ID, + // respectively. // // If you specify a nondefault VPC ID, note the following: // @@ -6179,8 +7271,8 @@ type CloneStackInput struct { // // * You must specify a value for DefaultSubnetId. // - // For more information on how to use AWS OpsWorks with a VPC, see Running a - // Stack in a VPC (http://docs.aws.amazon.com/opsworks/latest/userguide/workingstacks-vpc.html). + // For more information on how to use AWS OpsWorks Stacks with a VPC, see Running + // a Stack in a VPC (http://docs.aws.amazon.com/opsworks/latest/userguide/workingstacks-vpc.html). // For more information on default VPC and EC2 Classic, see Supported Platforms // (http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-supported-platforms.html). VpcId *string `type:"string"` @@ -6369,6 +7461,185 @@ func (s *CloneStackOutput) SetStackId(v string) *CloneStackOutput { return s } +// Describes the Amazon CloudWatch logs configuration for a layer. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/opsworks-2013-02-18/CloudWatchLogsConfiguration +type CloudWatchLogsConfiguration struct { + _ struct{} `type:"structure"` + + // Whether CloudWatch Logs is enabled for a layer. + Enabled *bool `type:"boolean"` + + // A list of configuration options for CloudWatch Logs. + LogStreams []*CloudWatchLogsLogStream `type:"list"` +} + +// String returns the string representation +func (s CloudWatchLogsConfiguration) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s CloudWatchLogsConfiguration) GoString() string { + return s.String() +} + +// SetEnabled sets the Enabled field's value. +func (s *CloudWatchLogsConfiguration) SetEnabled(v bool) *CloudWatchLogsConfiguration { + s.Enabled = &v + return s +} + +// SetLogStreams sets the LogStreams field's value. +func (s *CloudWatchLogsConfiguration) SetLogStreams(v []*CloudWatchLogsLogStream) *CloudWatchLogsConfiguration { + s.LogStreams = v + return s +} + +// Describes the Amazon CloudWatch logs configuration for a layer. For detailed +// information about members of this data type, see the CloudWatch Logs Agent +// Reference (http://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/AgentReference.html). +// Please also see https://docs.aws.amazon.com/goto/WebAPI/opsworks-2013-02-18/CloudWatchLogsLogStream +type CloudWatchLogsLogStream struct { + _ struct{} `type:"structure"` + + // Specifies the max number of log events in a batch, up to 10000. The default + // value is 1000. + BatchCount *int64 `type:"integer"` + + // Specifies the maximum size of log events in a batch, in bytes, up to 1048576 + // bytes. The default value is 32768 bytes. This size is calculated as the sum + // of all event messages in UTF-8, plus 26 bytes for each log event. + BatchSize *int64 `type:"integer"` + + // Specifies the time duration for the batching of log events. The minimum value + // is 5000ms and default value is 5000ms. + BufferDuration *int64 `type:"integer"` + + // Specifies how the time stamp is extracted from logs. For more information, + // see the CloudWatch Logs Agent Reference (http://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/AgentReference.html). + DatetimeFormat *string `type:"string"` + + // Specifies the encoding of the log file so that the file can be read correctly. + // The default is utf_8. Encodings supported by Python codecs.decode() can be + // used here. + Encoding *string `type:"string" enum:"CloudWatchLogsEncoding"` + + // Specifies log files that you want to push to CloudWatch Logs. + // + // File can point to a specific file or multiple files (by using wild card characters + // such as /var/log/system.log*). Only the latest file is pushed to CloudWatch + // Logs, based on file modification time. We recommend that you use wild card + // characters to specify a series of files of the same type, such as access_log.2014-06-01-01, + // access_log.2014-06-01-02, and so on by using a pattern like access_log.*. + // Don't use a wildcard to match multiple file types, such as access_log_80 + // and access_log_443. To specify multiple, different file types, add another + // log stream entry to the configuration file, so that each log file type is + // stored in a different log group. + // + // Zipped files are not supported. + File *string `type:"string"` + + // Specifies the range of lines for identifying a file. The valid values are + // one number, or two dash-delimited numbers, such as '1', '2-5'. The default + // value is '1', meaning the first line is used to calculate the fingerprint. + // Fingerprint lines are not sent to CloudWatch Logs unless all specified lines + // are available. + FileFingerprintLines *string `type:"string"` + + // Specifies where to start to read data (start_of_file or end_of_file). The + // default is start_of_file. This setting is only used if there is no state + // persisted for that log stream. + InitialPosition *string `type:"string" enum:"CloudWatchLogsInitialPosition"` + + // Specifies the destination log group. A log group is created automatically + // if it doesn't already exist. Log group names can be between 1 and 512 characters + // long. Allowed characters include a-z, A-Z, 0-9, '_' (underscore), '-' (hyphen), + // '/' (forward slash), and '.' (period). + LogGroupName *string `type:"string"` + + // Specifies the pattern for identifying the start of a log message. + MultiLineStartPattern *string `type:"string"` + + // Specifies the time zone of log event time stamps. + TimeZone *string `type:"string" enum:"CloudWatchLogsTimeZone"` +} + +// String returns the string representation +func (s CloudWatchLogsLogStream) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s CloudWatchLogsLogStream) GoString() string { + return s.String() +} + +// SetBatchCount sets the BatchCount field's value. +func (s *CloudWatchLogsLogStream) SetBatchCount(v int64) *CloudWatchLogsLogStream { + s.BatchCount = &v + return s +} + +// SetBatchSize sets the BatchSize field's value. +func (s *CloudWatchLogsLogStream) SetBatchSize(v int64) *CloudWatchLogsLogStream { + s.BatchSize = &v + return s +} + +// SetBufferDuration sets the BufferDuration field's value. +func (s *CloudWatchLogsLogStream) SetBufferDuration(v int64) *CloudWatchLogsLogStream { + s.BufferDuration = &v + return s +} + +// SetDatetimeFormat sets the DatetimeFormat field's value. +func (s *CloudWatchLogsLogStream) SetDatetimeFormat(v string) *CloudWatchLogsLogStream { + s.DatetimeFormat = &v + return s +} + +// SetEncoding sets the Encoding field's value. +func (s *CloudWatchLogsLogStream) SetEncoding(v string) *CloudWatchLogsLogStream { + s.Encoding = &v + return s +} + +// SetFile sets the File field's value. +func (s *CloudWatchLogsLogStream) SetFile(v string) *CloudWatchLogsLogStream { + s.File = &v + return s +} + +// SetFileFingerprintLines sets the FileFingerprintLines field's value. +func (s *CloudWatchLogsLogStream) SetFileFingerprintLines(v string) *CloudWatchLogsLogStream { + s.FileFingerprintLines = &v + return s +} + +// SetInitialPosition sets the InitialPosition field's value. +func (s *CloudWatchLogsLogStream) SetInitialPosition(v string) *CloudWatchLogsLogStream { + s.InitialPosition = &v + return s +} + +// SetLogGroupName sets the LogGroupName field's value. +func (s *CloudWatchLogsLogStream) SetLogGroupName(v string) *CloudWatchLogsLogStream { + s.LogGroupName = &v + return s +} + +// SetMultiLineStartPattern sets the MultiLineStartPattern field's value. +func (s *CloudWatchLogsLogStream) SetMultiLineStartPattern(v string) *CloudWatchLogsLogStream { + s.MultiLineStartPattern = &v + return s +} + +// SetTimeZone sets the TimeZone field's value. +func (s *CloudWatchLogsLogStream) SetTimeZone(v string) *CloudWatchLogsLogStream { + s.TimeZone = &v + return s +} + // Describes a command. // Please also see https://docs.aws.amazon.com/goto/WebAPI/opsworks-2013-02-18/Command type Command struct { @@ -6560,9 +7831,9 @@ type CreateAppInput struct { // The app type. Each supported type is associated with a particular layer. // For example, PHP applications are associated with a PHP layer. AWS OpsWorks - // deploys an application to those instances that are members of the corresponding - // layer. If your app isn't one of the standard types, or you prefer to implement - // your own Deploy recipes, specify other. + // Stacks deploys an application to those instances that are members of the + // corresponding layer. If your app isn't one of the standard types, or you + // prefer to implement your own Deploy recipes, specify other. // // Type is a required field Type *string `type:"string" required:"true" enum:"AppType"` @@ -6851,18 +8122,19 @@ func (s *CreateDeploymentOutput) SetDeploymentId(v string) *CreateDeploymentOutp type CreateInstanceInput struct { _ struct{} `type:"structure"` - // The default AWS OpsWorks agent version. You have the following options: + // The default AWS OpsWorks Stacks agent version. You have the following options: // // * INHERIT - Use the stack's default agent version setting. // // * version_number - Use the specified agent version. This value overrides // the stack's default setting. To update the agent version, edit the instance - // configuration and specify a new version. AWS OpsWorks then automatically + // configuration and specify a new version. AWS OpsWorks Stacks then automatically // installs that version on the instance. // // The default setting is INHERIT. To specify an agent version, you must use // the complete version number, not the abbreviated number shown on the console. // For a list of available agent version numbers, call DescribeAgentVersions. + // AgentVersion cannot be set to Chef 12.2. AgentVersion *string `type:"string"` // A custom AMI ID to be used to create the instance. The AMI should be based @@ -6925,12 +8197,13 @@ type CreateInstanceInput struct { // The instance's operating system, which must be set to one of the following. // // * A supported Linux operating system: An Amazon Linux version, such as - // Amazon Linux 2016.03, Amazon Linux 2015.09, or Amazon Linux 2015.03. + // Amazon Linux 2016.09, Amazon Linux 2016.03, Amazon Linux 2015.09, or Amazon + // Linux 2015.03. // // * A supported Ubuntu operating system, such as Ubuntu 16.04 LTS, Ubuntu // 14.04 LTS, or Ubuntu 12.04 LTS. // - // * CentOS 7 + // * CentOS Linux 7 // // * Red Hat Enterprise Linux 7 // @@ -6942,15 +8215,15 @@ type CreateInstanceInput struct { // * A custom AMI: Custom. // // For more information on the supported operating systems, see AWS OpsWorks - // Operating Systems (http://docs.aws.amazon.com/opsworks/latest/userguide/workinginstances-os.html). + // Stacks Operating Systems (http://docs.aws.amazon.com/opsworks/latest/userguide/workinginstances-os.html). // // The default option is the current Amazon Linux version. If you set this parameter // to Custom, you must use the CreateInstance action's AmiId parameter to specify // the custom AMI that you want to use. Block device mappings are not supported // if the value is Custom. For more information on the supported operating systems, // see Operating Systems (http://docs.aws.amazon.com/opsworks/latest/userguide/workinginstances-os.html)For - // more information on how to use custom AMIs with AWS OpsWorks, see Using Custom - // AMIs (http://docs.aws.amazon.com/opsworks/latest/userguide/workinginstances-custom-ami.html). + // more information on how to use custom AMIs with AWS OpsWorks Stacks, see + // Using Custom AMIs (http://docs.aws.amazon.com/opsworks/latest/userguide/workinginstances-custom-ami.html). Os *string `type:"string"` // The instance root device type. For more information, see Storage for the @@ -6967,7 +8240,7 @@ type CreateInstanceInput struct { // The ID of the instance's subnet. If the stack is running in a VPC, you can // use this parameter to override the stack's default subnet ID value and direct - // AWS OpsWorks to launch the instance in a different subnet. + // AWS OpsWorks Stacks to launch the instance in a different subnet. SubnetId *string `type:"string"` // The instance's tenancy option. The default option is no tenancy, or if the @@ -7167,6 +8440,10 @@ type CreateLayerInput struct { // a Layer (http://docs.aws.amazon.com/opsworks/latest/userguide/workinglayers-basics-edit.html). AutoAssignPublicIps *bool `type:"boolean"` + // Specifies CloudWatch Logs configuration options for the layer. For more information, + // see CloudWatchLogsLogStream. + CloudWatchLogsConfiguration *CloudWatchLogsConfiguration `type:"structure"` + // The ARN of an IAM profile to be used for the layer's EC2 instances. For more // information about IAM ARNs, see Using Identifiers (http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html). CustomInstanceProfileArn *string `type:"string"` @@ -7210,13 +8487,13 @@ type CreateLayerInput struct { Packages []*string `type:"list"` // For custom layers only, use this parameter to specify the layer's short name, - // which is used internally by AWS OpsWorks and by Chef recipes. The short name - // is also used as the name for the directory where your app files are installed. - // It can have a maximum of 200 characters, which are limited to the alphanumeric - // characters, '-', '_', and '.'. + // which is used internally by AWS OpsWorks Stacks and by Chef recipes. The + // short name is also used as the name for the directory where your app files + // are installed. It can have a maximum of 200 characters, which are limited + // to the alphanumeric characters, '-', '_', and '.'. // - // The built-in layers' short names are defined by AWS OpsWorks. For more information, - // see the Layer Reference (http://docs.aws.amazon.com/opsworks/latest/userguide/layers.html). + // The built-in layers' short names are defined by AWS OpsWorks Stacks. For + // more information, see the Layer Reference (http://docs.aws.amazon.com/opsworks/latest/userguide/layers.html). // // Shortname is a required field Shortname *string `type:"string" required:"true"` @@ -7300,6 +8577,12 @@ func (s *CreateLayerInput) SetAutoAssignPublicIps(v bool) *CreateLayerInput { return s } +// SetCloudWatchLogsConfiguration sets the CloudWatchLogsConfiguration field's value. +func (s *CreateLayerInput) SetCloudWatchLogsConfiguration(v *CloudWatchLogsConfiguration) *CreateLayerInput { + s.CloudWatchLogsConfiguration = v + return s +} + // SetCustomInstanceProfileArn sets the CustomInstanceProfileArn field's value. func (s *CreateLayerInput) SetCustomInstanceProfileArn(v string) *CreateLayerInput { s.CustomInstanceProfileArn = &v @@ -7413,21 +8696,21 @@ func (s *CreateLayerOutput) SetLayerId(v string) *CreateLayerOutput { type CreateStackInput struct { _ struct{} `type:"structure"` - // The default AWS OpsWorks agent version. You have the following options: + // The default AWS OpsWorks Stacks agent version. You have the following options: // - // * Auto-update - Set this parameter to LATEST. AWS OpsWorks automatically + // * Auto-update - Set this parameter to LATEST. AWS OpsWorks Stacks automatically // installs new agent versions on the stack's instances as soon as they are // available. // // * Fixed version - Set this parameter to your preferred agent version. // To update the agent version, you must edit the stack configuration and - // specify a new version. AWS OpsWorks then automatically installs that version - // on the stack's instances. + // specify a new version. AWS OpsWorks Stacks then automatically installs + // that version on the stack's instances. // // The default setting is the most recent release of the agent. To specify an // agent version, you must use the complete version number, not the abbreviated // number shown on the console. For a list of available agent version numbers, - // call DescribeAgentVersions. + // call DescribeAgentVersions. AgentVersion cannot be set to Chef 12.2. // // You can also specify an agent version when you create or update an instance, // which overrides the stack's default setting. @@ -7480,12 +8763,13 @@ type CreateStackInput struct { // You can specify one of the following. // // * A supported Linux operating system: An Amazon Linux version, such as - // Amazon Linux 2016.03, Amazon Linux 2015.09, or Amazon Linux 2015.03. + // Amazon Linux 2016.09, Amazon Linux 2016.03, Amazon Linux 2015.09, or Amazon + // Linux 2015.03. // // * A supported Ubuntu operating system, such as Ubuntu 16.04 LTS, Ubuntu // 14.04 LTS, or Ubuntu 12.04 LTS. // - // * CentOS 7 + // * CentOS Linux 7 // // * Red Hat Enterprise Linux 7 // @@ -7498,7 +8782,8 @@ type CreateStackInput struct { // you create instances. For more information, see Using Custom AMIs (http://docs.aws.amazon.com/opsworks/latest/userguide/workinginstances-custom-ami.html). // // The default option is the current Amazon Linux version. For more information - // on the supported operating systems, see AWS OpsWorks Operating Systems (http://docs.aws.amazon.com/opsworks/latest/userguide/workinginstances-os.html). + // on the supported operating systems, see AWS OpsWorks Stacks Operating Systems + // (http://docs.aws.amazon.com/opsworks/latest/userguide/workinginstances-os.html). DefaultOs *string `type:"string"` // The default root device type. This value is the default for all instances @@ -7567,9 +8852,9 @@ type CreateStackInput struct { Region *string `type:"string" required:"true"` // The stack's AWS Identity and Access Management (IAM) role, which allows AWS - // OpsWorks to work with AWS resources on your behalf. You must set this parameter - // to the Amazon Resource Name (ARN) for an existing IAM role. For more information - // about IAM ARNs, see Using Identifiers (http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html). + // OpsWorks Stacks to work with AWS resources on your behalf. You must set this + // parameter to the Amazon Resource Name (ARN) for an existing IAM role. For + // more information about IAM ARNs, see Using Identifiers (http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html). // // ServiceRoleArn is a required field ServiceRoleArn *string `type:"string" required:"true"` @@ -7577,21 +8862,21 @@ type CreateStackInput struct { // Whether the stack uses custom cookbooks. UseCustomCookbooks *bool `type:"boolean"` - // Whether to associate the AWS OpsWorks built-in security groups with the stack's - // layers. + // Whether to associate the AWS OpsWorks Stacks built-in security groups with + // the stack's layers. // - // AWS OpsWorks provides a standard set of built-in security groups, one for - // each layer, which are associated with layers by default. With UseOpsworksSecurityGroups + // AWS OpsWorks Stacks provides a standard set of built-in security groups, + // one for each layer, which are associated with layers by default. With UseOpsworksSecurityGroups // you can instead provide your own custom security groups. UseOpsworksSecurityGroups // has the following settings: // - // * True - AWS OpsWorks automatically associates the appropriate built-in - // security group with each layer (default setting). You can associate additional - // security groups with a layer after you create it, but you cannot delete - // the built-in security group. + // * True - AWS OpsWorks Stacks automatically associates the appropriate + // built-in security group with each layer (default setting). You can associate + // additional security groups with a layer after you create it, but you cannot + // delete the built-in security group. // - // * False - AWS OpsWorks does not associate built-in security groups with - // layers. You must create appropriate EC2 security groups and associate + // * False - AWS OpsWorks Stacks does not associate built-in security groups + // with layers. You must create appropriate EC2 security groups and associate // a security group with each layer that you create. However, you can still // manually associate a built-in security group with a layer on creation; // custom security groups are required only for those layers that need custom @@ -7611,9 +8896,10 @@ type CreateStackInput struct { // // If the VPC ID corresponds to a default VPC and you have specified either // the DefaultAvailabilityZone or the DefaultSubnetId parameter only, AWS OpsWorks - // infers the value of the other parameter. If you specify neither parameter, - // AWS OpsWorks sets these parameters to the first valid Availability Zone for - // the specified region and the corresponding default VPC subnet ID, respectively. + // Stacks infers the value of the other parameter. If you specify neither parameter, + // AWS OpsWorks Stacks sets these parameters to the first valid Availability + // Zone for the specified region and the corresponding default VPC subnet ID, + // respectively. // // If you specify a nondefault VPC ID, note the following: // @@ -7621,8 +8907,8 @@ type CreateStackInput struct { // // * You must specify a value for DefaultSubnetId. // - // For more information on how to use AWS OpsWorks with a VPC, see Running a - // Stack in a VPC (http://docs.aws.amazon.com/opsworks/latest/userguide/workingstacks-vpc.html). + // For more information on how to use AWS OpsWorks Stacks with a VPC, see Running + // a Stack in a VPC (http://docs.aws.amazon.com/opsworks/latest/userguide/workingstacks-vpc.html). // For more information on default VPC and EC2-Classic, see Supported Platforms // (http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-supported-platforms.html). VpcId *string `type:"string"` @@ -7818,9 +9104,9 @@ type CreateUserProfileInput struct { // The user's SSH user name. The allowable characters are [a-z], [A-Z], [0-9], // '-', and '_'. If the specified name includes other punctuation marks, AWS - // OpsWorks removes them. For example, my.name will be changed to myname. If - // you do not specify an SSH user name, AWS OpsWorks generates one from the - // IAM user name. + // OpsWorks Stacks removes them. For example, my.name will be changed to myname. + // If you do not specify an SSH user name, AWS OpsWorks Stacks generates one + // from the IAM user name. SshUsername *string `type:"string"` } @@ -8382,9 +9668,9 @@ type DeploymentCommand struct { // whose OS you want to upgrade, such as Amazon Linux 2014.09. You must also // set the allow_reboot argument to true. // - // * allow_reboot - Specifies whether to allow AWS OpsWorks to reboot the - // instances if necessary, after installing the updates. This argument can - // be set to either true or false. The default value is false. + // * allow_reboot - Specifies whether to allow AWS OpsWorks Stacks to reboot + // the instances if necessary, after installing the updates. This argument + // can be set to either true or false. The default value is false. // // For example, to upgrade an instance to Amazon Linux 2014.09, set Args to // the following. @@ -8417,9 +9703,9 @@ type DeploymentCommand struct { // The default setting is {"migrate":["false"]}. // // * rollback Roll the app back to the previous version. When you update - // an app, AWS OpsWorks stores the previous version, up to a maximum of five - // versions. You can use this command to roll an app back as many as four - // versions. + // an app, AWS OpsWorks Stacks stores the previous version, up to a maximum + // of five versions. You can use this command to roll an app back as many + // as four versions. // // * start: Start the app's web or application server. // @@ -8688,9 +9974,9 @@ func (s DeregisterRdsDbInstanceOutput) GoString() string { type DeregisterVolumeInput struct { _ struct{} `type:"structure"` - // The AWS OpsWorks volume ID, which is the GUID that AWS OpsWorks assigned - // to the instance when you registered the volume with the stack, not the Amazon - // EC2 volume ID. + // The AWS OpsWorks Stacks volume ID, which is the GUID that AWS OpsWorks Stacks + // assigned to the instance when you registered the volume with the stack, not + // the Amazon EC2 volume ID. // // VolumeId is a required field VolumeId *string `type:"string" required:"true"` @@ -9795,7 +11081,7 @@ func (s *DescribeStackProvisioningParametersInput) SetStackId(v string) *Describ type DescribeStackProvisioningParametersOutput struct { _ struct{} `type:"structure"` - // The AWS OpsWorks agent installer's URL. + // The AWS OpsWorks Stacks agent installer's URL. AgentInstallerUrl *string `type:"string"` // An embedded object that contains the provisioning parameters. @@ -10679,7 +11965,7 @@ func (s *GetHostnameSuggestionOutput) SetLayerId(v string) *GetHostnameSuggestio type GrantAccessInput struct { _ struct{} `type:"structure"` - // The instance's AWS OpsWorks ID. + // The instance's AWS OpsWorks Stacks ID. // // InstanceId is a required field InstanceId *string `type:"string" required:"true"` @@ -10853,7 +12139,7 @@ type Instance struct { // For registered instances, who performed the registration. RegisteredBy *string `type:"string"` - // The instance's reported AWS OpsWorks agent version. + // The instance's reported AWS OpsWorks Stacks agent version. ReportedAgentVersion *string `type:"string"` // For registered instances, the reported operating system. @@ -11404,10 +12690,10 @@ type Layer struct { // The layer attributes. // // For the HaproxyStatsPassword, MysqlRootPassword, and GangliaPassword attributes, - // AWS OpsWorks returns *****FILTERED***** instead of the actual value + // AWS OpsWorks Stacks returns *****FILTERED***** instead of the actual value // - // For an ECS Cluster layer, AWS OpsWorks the EcsClusterArn attribute is set - // to the cluster's ARN. + // For an ECS Cluster layer, AWS OpsWorks Stacks the EcsClusterArn attribute + // is set to the cluster's ARN. Attributes map[string]*string `type:"map"` // Whether to automatically assign an Elastic IP address (http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/elastic-ip-addresses-eip.html) @@ -11419,6 +12705,9 @@ type Layer struct { // a Layer (http://docs.aws.amazon.com/opsworks/latest/userguide/workinglayers-basics-edit.html). AutoAssignPublicIps *bool `type:"boolean"` + // The Amazon CloudWatch Logs configuration settings for the layer. + CloudWatchLogsConfiguration *CloudWatchLogsConfiguration `type:"structure"` + // Date when the layer was created. CreatedAt *string `type:"string"` @@ -11436,12 +12725,13 @@ type Layer struct { // An array containing the layer's custom security group IDs. CustomSecurityGroupIds []*string `type:"list"` - // AWS OpsWorks supports five lifecycle events: setup, configuration, deploy, - // undeploy, and shutdown. For each layer, AWS OpsWorks runs a set of standard - // recipes for each event. In addition, you can provide custom recipes for any - // or all layers and events. AWS OpsWorks runs custom event recipes after the - // standard recipes. LayerCustomRecipes specifies the custom recipes for a particular - // layer to be run in response to each of the five events. + // AWS OpsWorks Stacks supports five lifecycle events: setup, configuration, + // deploy, undeploy, and shutdown. For each layer, AWS OpsWorks Stacks runs + // a set of standard recipes for each event. In addition, you can provide custom + // recipes for any or all layers and events. AWS OpsWorks Stacks runs custom + // event recipes after the standard recipes. LayerCustomRecipes specifies the + // custom recipes for a particular layer to be run in response to each of the + // five events. // // To specify a recipe, use the cookbook's directory name in the repository // followed by two colons and the recipe name, which is the recipe's file name @@ -11521,6 +12811,12 @@ func (s *Layer) SetAutoAssignPublicIps(v bool) *Layer { return s } +// SetCloudWatchLogsConfiguration sets the CloudWatchLogsConfiguration field's value. +func (s *Layer) SetCloudWatchLogsConfiguration(v *CloudWatchLogsConfiguration) *Layer { + s.CloudWatchLogsConfiguration = v + return s +} + // SetCreatedAt sets the CreatedAt field's value. func (s *Layer) SetCreatedAt(v string) *Layer { s.CreatedAt = &v @@ -11660,7 +12956,7 @@ type LoadBasedAutoScalingConfiguration struct { _ struct{} `type:"structure"` // An AutoScalingThresholds object that describes the downscaling configuration, - // which defines how and when AWS OpsWorks reduces the number of instances. + // which defines how and when AWS OpsWorks Stacks reduces the number of instances. DownScaling *AutoScalingThresholds `type:"structure"` // Whether load-based auto scaling is enabled for the layer. @@ -11670,7 +12966,7 @@ type LoadBasedAutoScalingConfiguration struct { LayerId *string `type:"string"` // An AutoScalingThresholds object that describes the upscaling configuration, - // which defines how and when AWS OpsWorks increases the number of instances. + // which defines how and when AWS OpsWorks Stacks increases the number of instances. UpScaling *AutoScalingThresholds `type:"structure"` } @@ -11928,7 +13224,7 @@ type RdsDbInstance struct { // The DB instance identifier. DbInstanceIdentifier *string `type:"string"` - // AWS OpsWorks returns *****FILTERED***** instead of the actual value. + // AWS OpsWorks Stacks returns *****FILTERED***** instead of the actual value. DbPassword *string `type:"string"` // The master user name. @@ -11937,9 +13233,10 @@ type RdsDbInstance struct { // The instance's database engine. Engine *string `type:"string"` - // Set to true if AWS OpsWorks was unable to discover the Amazon RDS instance. - // AWS OpsWorks attempts to discover the instance only once. If this value is - // set to true, you must deregister the instance and then register it again. + // Set to true if AWS OpsWorks Stacks is unable to discover the Amazon RDS instance. + // AWS OpsWorks Stacks attempts to discover the instance only once. If this + // value is set to true, you must deregister the instance, and then register + // it again. MissingOnRds *bool `type:"boolean"` // The instance's ARN. @@ -11948,7 +13245,7 @@ type RdsDbInstance struct { // The instance's AWS region. Region *string `type:"string"` - // The ID of the stack that the instance is registered with. + // The ID of the stack with which the instance is registered. StackId *string `type:"string"` } @@ -12070,12 +13367,13 @@ func (s RebootInstanceOutput) GoString() string { return s.String() } -// AWS OpsWorks supports five lifecycle events: setup, configuration, deploy, -// undeploy, and shutdown. For each layer, AWS OpsWorks runs a set of standard -// recipes for each event. In addition, you can provide custom recipes for any -// or all layers and events. AWS OpsWorks runs custom event recipes after the -// standard recipes. LayerCustomRecipes specifies the custom recipes for a particular -// layer to be run in response to each of the five events. +// AWS OpsWorks Stacks supports five lifecycle events: setup, configuration, +// deploy, undeploy, and shutdown. For each layer, AWS OpsWorks Stacks runs +// a set of standard recipes for each event. In addition, you can provide custom +// recipes for any or all layers and events. AWS OpsWorks Stacks runs custom +// event recipes after the standard recipes. LayerCustomRecipes specifies the +// custom recipes for a particular layer to be run in response to each of the +// five events. // // To specify a recipe, use the cookbook's directory name in the repository // followed by two colons and the recipe name, which is the recipe's file name @@ -12396,7 +13694,7 @@ func (s *RegisterInstanceInput) SetStackId(v string) *RegisterInstanceInput { type RegisterInstanceOutput struct { _ struct{} `type:"structure"` - // The registered instance's AWS OpsWorks ID. + // The registered instance's AWS OpsWorks Stacks ID. InstanceId *string `type:"string"` } @@ -12680,7 +13978,7 @@ func (s *SelfUserProfile) SetSshUsername(v string) *SelfUserProfile { return s } -// Describes an AWS OpsWorks service error. +// Describes an AWS OpsWorks Stacks service error. // Please also see https://docs.aws.amazon.com/goto/WebAPI/opsworks-2013-02-18/ServiceError type ServiceError struct { _ struct{} `type:"structure"` @@ -12756,7 +14054,7 @@ type SetLoadBasedAutoScalingInput struct { // An AutoScalingThresholds object with the downscaling threshold configuration. // If the load falls below these thresholds for a specified amount of time, - // AWS OpsWorks stops a specified number of instances. + // AWS OpsWorks Stacks stops a specified number of instances. DownScaling *AutoScalingThresholds `type:"structure"` // Enables load-based auto scaling for the layer. @@ -12769,7 +14067,7 @@ type SetLoadBasedAutoScalingInput struct { // An AutoScalingThresholds object with the upscaling threshold configuration. // If the load exceeds these thresholds for a specified amount of time, AWS - // OpsWorks starts a specified number of instances. + // OpsWorks Stacks starts a specified number of instances. UpScaling *AutoScalingThresholds `type:"structure"` } @@ -13026,8 +14324,8 @@ type ShutdownEventConfiguration struct { // see Connection Draining (http://docs.aws.amazon.com/ElasticLoadBalancing/latest/DeveloperGuide/TerminologyandKeyConcepts.html#conn-drain) DelayUntilElbConnectionsDrained *bool `type:"boolean"` - // The time, in seconds, that AWS OpsWorks will wait after triggering a Shutdown - // event before shutting down an instance. + // The time, in seconds, that AWS OpsWorks Stacks will wait after triggering + // a Shutdown event before shutting down an instance. ExecutionTimeout *int64 `type:"integer"` } @@ -13070,20 +14368,20 @@ type Source struct { // For more information on how to safely handle IAM credentials, see http://docs.aws.amazon.com/general/latest/gr/aws-access-keys-best-practices.html // (http://docs.aws.amazon.com/general/latest/gr/aws-access-keys-best-practices.html). // - // In responses, AWS OpsWorks returns *****FILTERED***** instead of the actual - // value. + // In responses, AWS OpsWorks Stacks returns *****FILTERED***** instead of the + // actual value. Password *string `type:"string"` - // The application's version. AWS OpsWorks enables you to easily deploy new - // versions of an application. One of the simplest approaches is to have branches - // or revisions in your repository that represent different versions that can - // potentially be deployed. + // The application's version. AWS OpsWorks Stacks enables you to easily deploy + // new versions of an application. One of the simplest approaches is to have + // branches or revisions in your repository that represent different versions + // that can potentially be deployed. Revision *string `type:"string"` // In requests, the repository's SSH key. // - // In responses, AWS OpsWorks returns *****FILTERED***** instead of the actual - // value. + // In responses, AWS OpsWorks Stacks returns *****FILTERED***** instead of the + // actual value. SshKey *string `type:"string"` // The repository type. @@ -13296,8 +14594,8 @@ type Stack struct { // Whether the stack uses custom cookbooks. UseCustomCookbooks *bool `type:"boolean"` - // Whether the stack automatically associates the AWS OpsWorks built-in security - // groups with the stack's layers. + // Whether the stack automatically associates the AWS OpsWorks Stacks built-in + // security groups with the stack's layers. UseOpsworksSecurityGroups *bool `type:"boolean"` // The VPC ID; applicable only if the stack is running in a VPC. @@ -13774,7 +15072,7 @@ func (s StopStackOutput) GoString() string { type TemporaryCredential struct { _ struct{} `type:"structure"` - // The instance's AWS OpsWorks ID. + // The instance's AWS OpsWorks Stacks ID. InstanceId *string `type:"string"` // The password. @@ -14206,18 +15504,20 @@ func (s UpdateElasticIpOutput) GoString() string { type UpdateInstanceInput struct { _ struct{} `type:"structure"` - // The default AWS OpsWorks agent version. You have the following options: + // The default AWS OpsWorks Stacks agent version. You have the following options: // // * INHERIT - Use the stack's default agent version setting. // // * version_number - Use the specified agent version. This value overrides // the stack's default setting. To update the agent version, you must edit - // the instance configuration and specify a new version. AWS OpsWorks then - // automatically installs that version on the instance. + // the instance configuration and specify a new version. AWS OpsWorks Stacks + // then automatically installs that version on the instance. // // The default setting is INHERIT. To specify an agent version, you must use // the complete version number, not the abbreviated number shown on the console. // For a list of available agent version numbers, call DescribeAgentVersions. + // + // AgentVersion cannot be set to Chef 12.2. AgentVersion *string `type:"string"` // The ID of the AMI that was used to create the instance. The value of this @@ -14271,12 +15571,13 @@ type UpdateInstanceInput struct { // You cannot update an instance that is using a custom AMI. // // * A supported Linux operating system: An Amazon Linux version, such as - // Amazon Linux 2016.03, Amazon Linux 2015.09, or Amazon Linux 2015.03. + // Amazon Linux 2016.09, Amazon Linux 2016.03, Amazon Linux 2015.09, or Amazon + // Linux 2015.03. // // * A supported Ubuntu operating system, such as Ubuntu 16.04 LTS, Ubuntu // 14.04 LTS, or Ubuntu 12.04 LTS. // - // * CentOS 7 + // * CentOS Linux 7 // // * Red Hat Enterprise Linux 7 // @@ -14286,7 +15587,7 @@ type UpdateInstanceInput struct { // Windows Server 2012 R2 with SQL Server Web. // // For more information on the supported operating systems, see AWS OpsWorks - // Operating Systems (http://docs.aws.amazon.com/opsworks/latest/userguide/workinginstances-os.html). + // Stacks Operating Systems (http://docs.aws.amazon.com/opsworks/latest/userguide/workinginstances-os.html). // // The default option is the current Amazon Linux version. If you set this parameter // to Custom, you must use the AmiId parameter to specify the custom AMI that @@ -14429,6 +15730,10 @@ type UpdateLayerInput struct { // a Layer (http://docs.aws.amazon.com/opsworks/latest/userguide/workinglayers-basics-edit.html). AutoAssignPublicIps *bool `type:"boolean"` + // Specifies CloudWatch Logs configuration options for the layer. For more information, + // see CloudWatchLogsLogStream. + CloudWatchLogsConfiguration *CloudWatchLogsConfiguration `type:"structure"` + // The ARN of an IAM profile to be used for all of the layer's EC2 instances. // For more information about IAM ARNs, see Using Identifiers (http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html). CustomInstanceProfileArn *string `type:"string"` @@ -14462,6 +15767,7 @@ type UpdateLayerInput struct { // LayerId is a required field LayerId *string `type:"string" required:"true"` + // Specifies the lifecycle event configuration LifecycleEventConfiguration *LifecycleEventConfiguration `type:"structure"` // The layer name, which is used by the console. @@ -14471,13 +15777,13 @@ type UpdateLayerInput struct { Packages []*string `type:"list"` // For custom layers only, use this parameter to specify the layer's short name, - // which is used internally by AWS OpsWorksand by Chef. The short name is also - // used as the name for the directory where your app files are installed. It - // can have a maximum of 200 characters and must be in the following format: + // which is used internally by AWS OpsWorks Stacks and by Chef. The short name + // is also used as the name for the directory where your app files are installed. + // It can have a maximum of 200 characters and must be in the following format: // /\A[a-z0-9\-\_\.]+\Z/. // - // The built-in layers' short names are defined by AWS OpsWorks. For more information, - // see the Layer Reference (http://docs.aws.amazon.com/opsworks/latest/userguide/layers.html) + // The built-in layers' short names are defined by AWS OpsWorks Stacks. For + // more information, see the Layer Reference (http://docs.aws.amazon.com/opsworks/latest/userguide/layers.html) Shortname *string `type:"string"` // Whether to use Amazon EBS-optimized instances. @@ -14538,6 +15844,12 @@ func (s *UpdateLayerInput) SetAutoAssignPublicIps(v bool) *UpdateLayerInput { return s } +// SetCloudWatchLogsConfiguration sets the CloudWatchLogsConfiguration field's value. +func (s *UpdateLayerInput) SetCloudWatchLogsConfiguration(v *CloudWatchLogsConfiguration) *UpdateLayerInput { + s.CloudWatchLogsConfiguration = v + return s +} + // SetCustomInstanceProfileArn sets the CustomInstanceProfileArn field's value. func (s *UpdateLayerInput) SetCustomInstanceProfileArn(v string) *UpdateLayerInput { s.CustomInstanceProfileArn = &v @@ -14746,20 +16058,21 @@ func (s UpdateRdsDbInstanceOutput) GoString() string { type UpdateStackInput struct { _ struct{} `type:"structure"` - // The default AWS OpsWorks agent version. You have the following options: + // The default AWS OpsWorks Stacks agent version. You have the following options: // - // * Auto-update - Set this parameter to LATEST. AWS OpsWorks automatically + // * Auto-update - Set this parameter to LATEST. AWS OpsWorks Stacks automatically // installs new agent versions on the stack's instances as soon as they are // available. // // * Fixed version - Set this parameter to your preferred agent version. // To update the agent version, you must edit the stack configuration and - // specify a new version. AWS OpsWorks then automatically installs that version - // on the stack's instances. + // specify a new version. AWS OpsWorks Stacks then automatically installs + // that version on the stack's instances. // // The default setting is LATEST. To specify an agent version, you must use // the complete version number, not the abbreviated number shown on the console. // For a list of available agent version numbers, call DescribeAgentVersions. + // AgentVersion cannot be set to Chef 12.2. // // You can also specify an agent version when you create or update an instance, // which overrides the stack's default setting. @@ -14808,12 +16121,13 @@ type UpdateStackInput struct { // The stack's operating system, which must be set to one of the following: // // * A supported Linux operating system: An Amazon Linux version, such as - // Amazon Linux 2016.03, Amazon Linux 2015.09, or Amazon Linux 2015.03. + // Amazon Linux 2016.09, Amazon Linux 2016.03, Amazon Linux 2015.09, or Amazon + // Linux 2015.03. // // * A supported Ubuntu operating system, such as Ubuntu 16.04 LTS, Ubuntu // 14.04 LTS, or Ubuntu 12.04 LTS. // - // * CentOS 7 + // * CentOS Linux 7 // // * Red Hat Enterprise Linux 7 // @@ -14827,7 +16141,8 @@ type UpdateStackInput struct { // OpsWorks, see Using Custom AMIs (http://docs.aws.amazon.com/opsworks/latest/userguide/workinginstances-custom-ami.html). // // The default option is the stack's current operating system. For more information - // on the supported operating systems, see AWS OpsWorks Operating Systems (http://docs.aws.amazon.com/opsworks/latest/userguide/workinginstances-os.html). + // on the supported operating systems, see AWS OpsWorks Stacks Operating Systems + // (http://docs.aws.amazon.com/opsworks/latest/userguide/workinginstances-os.html). DefaultOs *string `type:"string"` // The default root device type. This value is used by default for all instances @@ -14836,8 +16151,8 @@ type UpdateStackInput struct { DefaultRootDeviceType *string `type:"string" enum:"RootDeviceType"` // A default Amazon EC2 key-pair name. The default value is none. If you specify - // a key-pair name, AWS OpsWorks installs the public key on the instance and - // you can use the private key with an SSH client to log in to the instance. + // a key-pair name, AWS OpsWorks Stacks installs the public key on the instance + // and you can use the private key with an SSH client to log in to the instance. // For more information, see Using SSH to Communicate with an Instance (http://docs.aws.amazon.com/opsworks/latest/userguide/workinginstances-ssh.html) // and Managing SSH Access (http://docs.aws.amazon.com/opsworks/latest/userguide/security-ssh-access.html). // You can override this setting by specifying a different key pair, or no key @@ -14897,21 +16212,21 @@ type UpdateStackInput struct { // Whether the stack uses custom cookbooks. UseCustomCookbooks *bool `type:"boolean"` - // Whether to associate the AWS OpsWorks built-in security groups with the stack's - // layers. + // Whether to associate the AWS OpsWorks Stacks built-in security groups with + // the stack's layers. // - // AWS OpsWorks provides a standard set of built-in security groups, one for - // each layer, which are associated with layers by default. UseOpsworksSecurityGroups + // AWS OpsWorks Stacks provides a standard set of built-in security groups, + // one for each layer, which are associated with layers by default. UseOpsworksSecurityGroups // allows you to provide your own custom security groups instead of using the // built-in groups. UseOpsworksSecurityGroups has the following settings: // - // * True - AWS OpsWorks automatically associates the appropriate built-in - // security group with each layer (default setting). You can associate additional - // security groups with a layer after you create it, but you cannot delete - // the built-in security group. + // * True - AWS OpsWorks Stacks automatically associates the appropriate + // built-in security group with each layer (default setting). You can associate + // additional security groups with a layer after you create it, but you cannot + // delete the built-in security group. // - // * False - AWS OpsWorks does not associate built-in security groups with - // layers. You must create appropriate EC2 security groups and associate + // * False - AWS OpsWorks Stacks does not associate built-in security groups + // with layers. You must create appropriate EC2 security groups and associate // a security group with each layer that you create. However, you can still // manually associate a built-in security group with a layer on. Custom security // groups are required only for those layers that need custom settings. @@ -15084,9 +16399,9 @@ type UpdateUserProfileInput struct { // The user's SSH user name. The allowable characters are [a-z], [A-Z], [0-9], // '-', and '_'. If the specified name includes other punctuation marks, AWS - // OpsWorks removes them. For example, my.name will be changed to myname. If - // you do not specify an SSH user name, AWS OpsWorks generates one from the - // IAM user name. + // OpsWorks Stacks removes them. For example, my.name will be changed to myname. + // If you do not specify an SSH user name, AWS OpsWorks Stacks generates one + // from the IAM user name. SshUsername *string `type:"string"` } @@ -15671,6 +16986,308 @@ const ( AutoScalingTypeTimer = "timer" ) +// Specifies the encoding of the log file so that the file can be read correctly. +// The default is utf_8. Encodings supported by Python codecs.decode() can be +// used here. +const ( + // CloudWatchLogsEncodingAscii is a CloudWatchLogsEncoding enum value + CloudWatchLogsEncodingAscii = "ascii" + + // CloudWatchLogsEncodingBig5 is a CloudWatchLogsEncoding enum value + CloudWatchLogsEncodingBig5 = "big5" + + // CloudWatchLogsEncodingBig5hkscs is a CloudWatchLogsEncoding enum value + CloudWatchLogsEncodingBig5hkscs = "big5hkscs" + + // CloudWatchLogsEncodingCp037 is a CloudWatchLogsEncoding enum value + CloudWatchLogsEncodingCp037 = "cp037" + + // CloudWatchLogsEncodingCp424 is a CloudWatchLogsEncoding enum value + CloudWatchLogsEncodingCp424 = "cp424" + + // CloudWatchLogsEncodingCp437 is a CloudWatchLogsEncoding enum value + CloudWatchLogsEncodingCp437 = "cp437" + + // CloudWatchLogsEncodingCp500 is a CloudWatchLogsEncoding enum value + CloudWatchLogsEncodingCp500 = "cp500" + + // CloudWatchLogsEncodingCp720 is a CloudWatchLogsEncoding enum value + CloudWatchLogsEncodingCp720 = "cp720" + + // CloudWatchLogsEncodingCp737 is a CloudWatchLogsEncoding enum value + CloudWatchLogsEncodingCp737 = "cp737" + + // CloudWatchLogsEncodingCp775 is a CloudWatchLogsEncoding enum value + CloudWatchLogsEncodingCp775 = "cp775" + + // CloudWatchLogsEncodingCp850 is a CloudWatchLogsEncoding enum value + CloudWatchLogsEncodingCp850 = "cp850" + + // CloudWatchLogsEncodingCp852 is a CloudWatchLogsEncoding enum value + CloudWatchLogsEncodingCp852 = "cp852" + + // CloudWatchLogsEncodingCp855 is a CloudWatchLogsEncoding enum value + CloudWatchLogsEncodingCp855 = "cp855" + + // CloudWatchLogsEncodingCp856 is a CloudWatchLogsEncoding enum value + CloudWatchLogsEncodingCp856 = "cp856" + + // CloudWatchLogsEncodingCp857 is a CloudWatchLogsEncoding enum value + CloudWatchLogsEncodingCp857 = "cp857" + + // CloudWatchLogsEncodingCp858 is a CloudWatchLogsEncoding enum value + CloudWatchLogsEncodingCp858 = "cp858" + + // CloudWatchLogsEncodingCp860 is a CloudWatchLogsEncoding enum value + CloudWatchLogsEncodingCp860 = "cp860" + + // CloudWatchLogsEncodingCp861 is a CloudWatchLogsEncoding enum value + CloudWatchLogsEncodingCp861 = "cp861" + + // CloudWatchLogsEncodingCp862 is a CloudWatchLogsEncoding enum value + CloudWatchLogsEncodingCp862 = "cp862" + + // CloudWatchLogsEncodingCp863 is a CloudWatchLogsEncoding enum value + CloudWatchLogsEncodingCp863 = "cp863" + + // CloudWatchLogsEncodingCp864 is a CloudWatchLogsEncoding enum value + CloudWatchLogsEncodingCp864 = "cp864" + + // CloudWatchLogsEncodingCp865 is a CloudWatchLogsEncoding enum value + CloudWatchLogsEncodingCp865 = "cp865" + + // CloudWatchLogsEncodingCp866 is a CloudWatchLogsEncoding enum value + CloudWatchLogsEncodingCp866 = "cp866" + + // CloudWatchLogsEncodingCp869 is a CloudWatchLogsEncoding enum value + CloudWatchLogsEncodingCp869 = "cp869" + + // CloudWatchLogsEncodingCp874 is a CloudWatchLogsEncoding enum value + CloudWatchLogsEncodingCp874 = "cp874" + + // CloudWatchLogsEncodingCp875 is a CloudWatchLogsEncoding enum value + CloudWatchLogsEncodingCp875 = "cp875" + + // CloudWatchLogsEncodingCp932 is a CloudWatchLogsEncoding enum value + CloudWatchLogsEncodingCp932 = "cp932" + + // CloudWatchLogsEncodingCp949 is a CloudWatchLogsEncoding enum value + CloudWatchLogsEncodingCp949 = "cp949" + + // CloudWatchLogsEncodingCp950 is a CloudWatchLogsEncoding enum value + CloudWatchLogsEncodingCp950 = "cp950" + + // CloudWatchLogsEncodingCp1006 is a CloudWatchLogsEncoding enum value + CloudWatchLogsEncodingCp1006 = "cp1006" + + // CloudWatchLogsEncodingCp1026 is a CloudWatchLogsEncoding enum value + CloudWatchLogsEncodingCp1026 = "cp1026" + + // CloudWatchLogsEncodingCp1140 is a CloudWatchLogsEncoding enum value + CloudWatchLogsEncodingCp1140 = "cp1140" + + // CloudWatchLogsEncodingCp1250 is a CloudWatchLogsEncoding enum value + CloudWatchLogsEncodingCp1250 = "cp1250" + + // CloudWatchLogsEncodingCp1251 is a CloudWatchLogsEncoding enum value + CloudWatchLogsEncodingCp1251 = "cp1251" + + // CloudWatchLogsEncodingCp1252 is a CloudWatchLogsEncoding enum value + CloudWatchLogsEncodingCp1252 = "cp1252" + + // CloudWatchLogsEncodingCp1253 is a CloudWatchLogsEncoding enum value + CloudWatchLogsEncodingCp1253 = "cp1253" + + // CloudWatchLogsEncodingCp1254 is a CloudWatchLogsEncoding enum value + CloudWatchLogsEncodingCp1254 = "cp1254" + + // CloudWatchLogsEncodingCp1255 is a CloudWatchLogsEncoding enum value + CloudWatchLogsEncodingCp1255 = "cp1255" + + // CloudWatchLogsEncodingCp1256 is a CloudWatchLogsEncoding enum value + CloudWatchLogsEncodingCp1256 = "cp1256" + + // CloudWatchLogsEncodingCp1257 is a CloudWatchLogsEncoding enum value + CloudWatchLogsEncodingCp1257 = "cp1257" + + // CloudWatchLogsEncodingCp1258 is a CloudWatchLogsEncoding enum value + CloudWatchLogsEncodingCp1258 = "cp1258" + + // CloudWatchLogsEncodingEucJp is a CloudWatchLogsEncoding enum value + CloudWatchLogsEncodingEucJp = "euc_jp" + + // CloudWatchLogsEncodingEucJis2004 is a CloudWatchLogsEncoding enum value + CloudWatchLogsEncodingEucJis2004 = "euc_jis_2004" + + // CloudWatchLogsEncodingEucJisx0213 is a CloudWatchLogsEncoding enum value + CloudWatchLogsEncodingEucJisx0213 = "euc_jisx0213" + + // CloudWatchLogsEncodingEucKr is a CloudWatchLogsEncoding enum value + CloudWatchLogsEncodingEucKr = "euc_kr" + + // CloudWatchLogsEncodingGb2312 is a CloudWatchLogsEncoding enum value + CloudWatchLogsEncodingGb2312 = "gb2312" + + // CloudWatchLogsEncodingGbk is a CloudWatchLogsEncoding enum value + CloudWatchLogsEncodingGbk = "gbk" + + // CloudWatchLogsEncodingGb18030 is a CloudWatchLogsEncoding enum value + CloudWatchLogsEncodingGb18030 = "gb18030" + + // CloudWatchLogsEncodingHz is a CloudWatchLogsEncoding enum value + CloudWatchLogsEncodingHz = "hz" + + // CloudWatchLogsEncodingIso2022Jp is a CloudWatchLogsEncoding enum value + CloudWatchLogsEncodingIso2022Jp = "iso2022_jp" + + // CloudWatchLogsEncodingIso2022Jp1 is a CloudWatchLogsEncoding enum value + CloudWatchLogsEncodingIso2022Jp1 = "iso2022_jp_1" + + // CloudWatchLogsEncodingIso2022Jp2 is a CloudWatchLogsEncoding enum value + CloudWatchLogsEncodingIso2022Jp2 = "iso2022_jp_2" + + // CloudWatchLogsEncodingIso2022Jp2004 is a CloudWatchLogsEncoding enum value + CloudWatchLogsEncodingIso2022Jp2004 = "iso2022_jp_2004" + + // CloudWatchLogsEncodingIso2022Jp3 is a CloudWatchLogsEncoding enum value + CloudWatchLogsEncodingIso2022Jp3 = "iso2022_jp_3" + + // CloudWatchLogsEncodingIso2022JpExt is a CloudWatchLogsEncoding enum value + CloudWatchLogsEncodingIso2022JpExt = "iso2022_jp_ext" + + // CloudWatchLogsEncodingIso2022Kr is a CloudWatchLogsEncoding enum value + CloudWatchLogsEncodingIso2022Kr = "iso2022_kr" + + // CloudWatchLogsEncodingLatin1 is a CloudWatchLogsEncoding enum value + CloudWatchLogsEncodingLatin1 = "latin_1" + + // CloudWatchLogsEncodingIso88592 is a CloudWatchLogsEncoding enum value + CloudWatchLogsEncodingIso88592 = "iso8859_2" + + // CloudWatchLogsEncodingIso88593 is a CloudWatchLogsEncoding enum value + CloudWatchLogsEncodingIso88593 = "iso8859_3" + + // CloudWatchLogsEncodingIso88594 is a CloudWatchLogsEncoding enum value + CloudWatchLogsEncodingIso88594 = "iso8859_4" + + // CloudWatchLogsEncodingIso88595 is a CloudWatchLogsEncoding enum value + CloudWatchLogsEncodingIso88595 = "iso8859_5" + + // CloudWatchLogsEncodingIso88596 is a CloudWatchLogsEncoding enum value + CloudWatchLogsEncodingIso88596 = "iso8859_6" + + // CloudWatchLogsEncodingIso88597 is a CloudWatchLogsEncoding enum value + CloudWatchLogsEncodingIso88597 = "iso8859_7" + + // CloudWatchLogsEncodingIso88598 is a CloudWatchLogsEncoding enum value + CloudWatchLogsEncodingIso88598 = "iso8859_8" + + // CloudWatchLogsEncodingIso88599 is a CloudWatchLogsEncoding enum value + CloudWatchLogsEncodingIso88599 = "iso8859_9" + + // CloudWatchLogsEncodingIso885910 is a CloudWatchLogsEncoding enum value + CloudWatchLogsEncodingIso885910 = "iso8859_10" + + // CloudWatchLogsEncodingIso885913 is a CloudWatchLogsEncoding enum value + CloudWatchLogsEncodingIso885913 = "iso8859_13" + + // CloudWatchLogsEncodingIso885914 is a CloudWatchLogsEncoding enum value + CloudWatchLogsEncodingIso885914 = "iso8859_14" + + // CloudWatchLogsEncodingIso885915 is a CloudWatchLogsEncoding enum value + CloudWatchLogsEncodingIso885915 = "iso8859_15" + + // CloudWatchLogsEncodingIso885916 is a CloudWatchLogsEncoding enum value + CloudWatchLogsEncodingIso885916 = "iso8859_16" + + // CloudWatchLogsEncodingJohab is a CloudWatchLogsEncoding enum value + CloudWatchLogsEncodingJohab = "johab" + + // CloudWatchLogsEncodingKoi8R is a CloudWatchLogsEncoding enum value + CloudWatchLogsEncodingKoi8R = "koi8_r" + + // CloudWatchLogsEncodingKoi8U is a CloudWatchLogsEncoding enum value + CloudWatchLogsEncodingKoi8U = "koi8_u" + + // CloudWatchLogsEncodingMacCyrillic is a CloudWatchLogsEncoding enum value + CloudWatchLogsEncodingMacCyrillic = "mac_cyrillic" + + // CloudWatchLogsEncodingMacGreek is a CloudWatchLogsEncoding enum value + CloudWatchLogsEncodingMacGreek = "mac_greek" + + // CloudWatchLogsEncodingMacIceland is a CloudWatchLogsEncoding enum value + CloudWatchLogsEncodingMacIceland = "mac_iceland" + + // CloudWatchLogsEncodingMacLatin2 is a CloudWatchLogsEncoding enum value + CloudWatchLogsEncodingMacLatin2 = "mac_latin2" + + // CloudWatchLogsEncodingMacRoman is a CloudWatchLogsEncoding enum value + CloudWatchLogsEncodingMacRoman = "mac_roman" + + // CloudWatchLogsEncodingMacTurkish is a CloudWatchLogsEncoding enum value + CloudWatchLogsEncodingMacTurkish = "mac_turkish" + + // CloudWatchLogsEncodingPtcp154 is a CloudWatchLogsEncoding enum value + CloudWatchLogsEncodingPtcp154 = "ptcp154" + + // CloudWatchLogsEncodingShiftJis is a CloudWatchLogsEncoding enum value + CloudWatchLogsEncodingShiftJis = "shift_jis" + + // CloudWatchLogsEncodingShiftJis2004 is a CloudWatchLogsEncoding enum value + CloudWatchLogsEncodingShiftJis2004 = "shift_jis_2004" + + // CloudWatchLogsEncodingShiftJisx0213 is a CloudWatchLogsEncoding enum value + CloudWatchLogsEncodingShiftJisx0213 = "shift_jisx0213" + + // CloudWatchLogsEncodingUtf32 is a CloudWatchLogsEncoding enum value + CloudWatchLogsEncodingUtf32 = "utf_32" + + // CloudWatchLogsEncodingUtf32Be is a CloudWatchLogsEncoding enum value + CloudWatchLogsEncodingUtf32Be = "utf_32_be" + + // CloudWatchLogsEncodingUtf32Le is a CloudWatchLogsEncoding enum value + CloudWatchLogsEncodingUtf32Le = "utf_32_le" + + // CloudWatchLogsEncodingUtf16 is a CloudWatchLogsEncoding enum value + CloudWatchLogsEncodingUtf16 = "utf_16" + + // CloudWatchLogsEncodingUtf16Be is a CloudWatchLogsEncoding enum value + CloudWatchLogsEncodingUtf16Be = "utf_16_be" + + // CloudWatchLogsEncodingUtf16Le is a CloudWatchLogsEncoding enum value + CloudWatchLogsEncodingUtf16Le = "utf_16_le" + + // CloudWatchLogsEncodingUtf7 is a CloudWatchLogsEncoding enum value + CloudWatchLogsEncodingUtf7 = "utf_7" + + // CloudWatchLogsEncodingUtf8 is a CloudWatchLogsEncoding enum value + CloudWatchLogsEncodingUtf8 = "utf_8" + + // CloudWatchLogsEncodingUtf8Sig is a CloudWatchLogsEncoding enum value + CloudWatchLogsEncodingUtf8Sig = "utf_8_sig" +) + +// Specifies where to start to read data (start_of_file or end_of_file). The +// default is start_of_file. It's only used if there is no state persisted for +// that log stream. +const ( + // CloudWatchLogsInitialPositionStartOfFile is a CloudWatchLogsInitialPosition enum value + CloudWatchLogsInitialPositionStartOfFile = "start_of_file" + + // CloudWatchLogsInitialPositionEndOfFile is a CloudWatchLogsInitialPosition enum value + CloudWatchLogsInitialPositionEndOfFile = "end_of_file" +) + +// The preferred time zone for logs streamed to CloudWatch Logs. Valid values +// are LOCAL and UTC, for Coordinated Universal Time. +const ( + // CloudWatchLogsTimeZoneLocal is a CloudWatchLogsTimeZone enum value + CloudWatchLogsTimeZoneLocal = "LOCAL" + + // CloudWatchLogsTimeZoneUtc is a CloudWatchLogsTimeZone enum value + CloudWatchLogsTimeZoneUtc = "UTC" +) + const ( // DeploymentCommandNameInstallDependencies is a DeploymentCommandName enum value DeploymentCommandNameInstallDependencies = "install_dependencies" diff --git a/vendor/github.com/aws/aws-sdk-go/service/opsworks/doc.go b/vendor/github.com/aws/aws-sdk-go/service/opsworks/doc.go new file mode 100644 index 000000000..91746b4f9 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/service/opsworks/doc.go @@ -0,0 +1,149 @@ +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. + +// Package opsworks provides the client and types for making API +// requests to AWS OpsWorks. +// +// Welcome to the AWS OpsWorks Stacks API Reference. This guide provides descriptions, +// syntax, and usage examples for AWS OpsWorks Stacks actions and data types, +// including common parameters and error codes. +// +// AWS OpsWorks Stacks is an application management service that provides an +// integrated experience for overseeing the complete application lifecycle. +// For information about this product, go to the AWS OpsWorks (http://aws.amazon.com/opsworks/) +// details page. +// +// SDKs and CLI +// +// The most common way to use the AWS OpsWorks Stacks API is by using the AWS +// Command Line Interface (CLI) or by using one of the AWS SDKs to implement +// applications in your preferred language. For more information, see: +// +// * AWS CLI (http://docs.aws.amazon.com/cli/latest/userguide/cli-chap-welcome.html) +// +// * AWS SDK for Java (http://docs.aws.amazon.com/AWSJavaSDK/latest/javadoc/com/amazonaws/services/opsworks/AWSOpsWorksClient.html) +// +// * AWS SDK for .NET (http://docs.aws.amazon.com/sdkfornet/latest/apidocs/html/N_Amazon_OpsWorks.htm) +// +// * AWS SDK for PHP 2 (http://docs.aws.amazon.com/aws-sdk-php-2/latest/class-Aws.OpsWorks.OpsWorksClient.html) +// +// * AWS SDK for Ruby (http://docs.aws.amazon.com/sdkforruby/api/) +// +// * AWS SDK for Node.js (http://aws.amazon.com/documentation/sdkforjavascript/) +// +// * AWS SDK for Python(Boto) (http://docs.pythonboto.org/en/latest/ref/opsworks.html) +// +// Endpoints +// +// AWS OpsWorks Stacks supports the following endpoints, all HTTPS. You must +// connect to one of the following endpoints. Stacks can only be accessed or +// managed within the endpoint in which they are created. +// +// * opsworks.us-east-1.amazonaws.com +// +// * opsworks.us-east-2.amazonaws.com +// +// * opsworks.us-west-1.amazonaws.com +// +// * opsworks.us-west-2.amazonaws.com +// +// * opsworks.eu-west-1.amazonaws.com +// +// * opsworks.eu-west-2.amazonaws.com +// +// * opsworks.eu-central-1.amazonaws.com +// +// * opsworks.ap-northeast-1.amazonaws.com +// +// * opsworks.ap-northeast-2.amazonaws.com +// +// * opsworks.ap-south-1.amazonaws.com +// +// * opsworks.ap-southeast-1.amazonaws.com +// +// * opsworks.ap-southeast-2.amazonaws.com +// +// * opsworks.sa-east-1.amazonaws.com +// +// Chef Versions +// +// When you call CreateStack, CloneStack, or UpdateStack we recommend you use +// the ConfigurationManager parameter to specify the Chef version. The recommended +// and default value for Linux stacks is currently 12. Windows stacks use Chef +// 12.2. For more information, see Chef Versions (http://docs.aws.amazon.com/opsworks/latest/userguide/workingcookbook-chef11.html). +// +// You can specify Chef 12, 11.10, or 11.4 for your Linux stack. We recommend +// migrating your existing Linux stacks to Chef 12 as soon as possible. +// +// See https://docs.aws.amazon.com/goto/WebAPI/opsworks-2013-02-18 for more information on this service. +// +// See opsworks package documentation for more information. +// https://docs.aws.amazon.com/sdk-for-go/api/service/opsworks/ +// +// Using the Client +// +// To use the client for AWS OpsWorks you will first need +// to create a new instance of it. +// +// When creating a client for an AWS service you'll first need to have a Session +// already created. The Session provides configuration that can be shared +// between multiple service clients. Additional configuration can be applied to +// the Session and service's client when they are constructed. The aws package's +// Config type contains several fields such as Region for the AWS Region the +// client should make API requests too. The optional Config value can be provided +// as the variadic argument for Sessions and client creation. +// +// Once the service's client is created you can use it to make API requests the +// AWS service. These clients are safe to use concurrently. +// +// // Create a session to share configuration, and load external configuration. +// sess := session.Must(session.NewSession()) +// +// // Create the service's client with the session. +// svc := opsworks.New(sess) +// +// See the SDK's documentation for more information on how to use service clients. +// https://docs.aws.amazon.com/sdk-for-go/api/ +// +// See aws package's Config type for more information on configuration options. +// https://docs.aws.amazon.com/sdk-for-go/api/aws/#Config +// +// See the AWS OpsWorks client OpsWorks for more +// information on creating the service's client. +// https://docs.aws.amazon.com/sdk-for-go/api/service/opsworks/#New +// +// Once the client is created you can make an API request to the service. +// Each API method takes a input parameter, and returns the service response +// and an error. +// +// The API method will document which error codes the service can be returned +// by the operation if the service models the API operation's errors. These +// errors will also be available as const strings prefixed with "ErrCode". +// +// result, err := svc.AssignInstance(params) +// if err != nil { +// // Cast err to awserr.Error to handle specific error codes. +// aerr, ok := err.(awserr.Error) +// if ok && aerr.Code() == { +// // Specific error code handling +// } +// return err +// } +// +// fmt.Println("AssignInstance result:") +// fmt.Println(result) +// +// Using the Client with Context +// +// The service's client also provides methods to make API requests with a Context +// value. This allows you to control the timeout, and cancellation of pending +// requests. These methods also take request Option as variadic parameter to apply +// additional configuration to the API request. +// +// ctx := context.Background() +// +// result, err := svc.AssignInstanceWithContext(ctx, params) +// +// See the request package documentation for more information on using Context pattern +// with the SDK. +// https://docs.aws.amazon.com/sdk-for-go/api/aws/request/ +package opsworks diff --git a/vendor/github.com/aws/aws-sdk-go/service/opsworks/errors.go b/vendor/github.com/aws/aws-sdk-go/service/opsworks/errors.go index d3e09499d..fc849646c 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/opsworks/errors.go +++ b/vendor/github.com/aws/aws-sdk-go/service/opsworks/errors.go @@ -1,4 +1,4 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. package opsworks diff --git a/vendor/github.com/aws/aws-sdk-go/service/opsworks/service.go b/vendor/github.com/aws/aws-sdk-go/service/opsworks/service.go index fa799d9ff..3e94bb43d 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/opsworks/service.go +++ b/vendor/github.com/aws/aws-sdk-go/service/opsworks/service.go @@ -1,4 +1,4 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. package opsworks @@ -11,75 +11,12 @@ import ( "github.com/aws/aws-sdk-go/private/protocol/jsonrpc" ) -// Welcome to the AWS OpsWorks API Reference. This guide provides descriptions, -// syntax, and usage examples for AWS OpsWorks actions and data types, including -// common parameters and error codes. +// OpsWorks provides the API operation methods for making requests to +// AWS OpsWorks. See this package's package overview docs +// for details on the service. // -// AWS OpsWorks is an application management service that provides an integrated -// experience for overseeing the complete application lifecycle. For information -// about this product, go to the AWS OpsWorks (http://aws.amazon.com/opsworks/) -// details page. -// -// SDKs and CLI -// -// The most common way to use the AWS OpsWorks API is by using the AWS Command -// Line Interface (CLI) or by using one of the AWS SDKs to implement applications -// in your preferred language. For more information, see: -// -// * AWS CLI (http://docs.aws.amazon.com/cli/latest/userguide/cli-chap-welcome.html) -// -// * AWS SDK for Java (http://docs.aws.amazon.com/AWSJavaSDK/latest/javadoc/com/amazonaws/services/opsworks/AWSOpsWorksClient.html) -// -// * AWS SDK for .NET (http://docs.aws.amazon.com/sdkfornet/latest/apidocs/html/N_Amazon_OpsWorks.htm) -// -// * AWS SDK for PHP 2 (http://docs.aws.amazon.com/aws-sdk-php-2/latest/class-Aws.OpsWorks.OpsWorksClient.html) -// -// * AWS SDK for Ruby (http://docs.aws.amazon.com/sdkforruby/api/) -// -// * AWS SDK for Node.js (http://aws.amazon.com/documentation/sdkforjavascript/) -// -// * AWS SDK for Python(Boto) (http://docs.pythonboto.org/en/latest/ref/opsworks.html) -// -// Endpoints -// -// AWS OpsWorks supports the following endpoints, all HTTPS. You must connect -// to one of the following endpoints. Stacks can only be accessed or managed -// within the endpoint in which they are created. -// -// * opsworks.us-east-1.amazonaws.com -// -// * opsworks.us-west-1.amazonaws.com -// -// * opsworks.us-west-2.amazonaws.com -// -// * opsworks.eu-west-1.amazonaws.com -// -// * opsworks.eu-central-1.amazonaws.com -// -// * opsworks.ap-northeast-1.amazonaws.com -// -// * opsworks.ap-northeast-2.amazonaws.com -// -// * opsworks.ap-south-1.amazonaws.com -// -// * opsworks.ap-southeast-1.amazonaws.com -// -// * opsworks.ap-southeast-2.amazonaws.com -// -// * opsworks.sa-east-1.amazonaws.com -// -// Chef Versions -// -// When you call CreateStack, CloneStack, or UpdateStack we recommend you use -// the ConfigurationManager parameter to specify the Chef version. The recommended -// and default value for Linux stacks is currently 12. Windows stacks use Chef -// 12.2. For more information, see Chef Versions (http://docs.aws.amazon.com/opsworks/latest/userguide/workingcookbook-chef11.html). -// -// You can specify Chef 12, 11.10, or 11.4 for your Linux stack. We recommend -// migrating your existing Linux stacks to Chef 12 as soon as possible. -// The service client's operations are safe to be used concurrently. -// It is not safe to mutate any of the client's properties though. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/opsworks-2013-02-18 +// OpsWorks methods are safe to use concurrently. It is not safe to +// modify mutate any of the struct's properties though. type OpsWorks struct { *client.Client } diff --git a/vendor/github.com/aws/aws-sdk-go/service/opsworks/waiters.go b/vendor/github.com/aws/aws-sdk-go/service/opsworks/waiters.go index dc4fa42ae..99a800a60 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/opsworks/waiters.go +++ b/vendor/github.com/aws/aws-sdk-go/service/opsworks/waiters.go @@ -1,9 +1,12 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. package opsworks import ( - "github.com/aws/aws-sdk-go/private/waiter" + "time" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/request" ) // WaitUntilAppExists uses the AWS OpsWorks API operation @@ -11,32 +14,50 @@ import ( // If the condition is not meet within the max attempt window an error will // be returned. func (c *OpsWorks) WaitUntilAppExists(input *DescribeAppsInput) error { - waiterCfg := waiter.Config{ - Operation: "DescribeApps", - Delay: 1, + return c.WaitUntilAppExistsWithContext(aws.BackgroundContext(), input) +} + +// WaitUntilAppExistsWithContext is an extended version of WaitUntilAppExists. +// 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 *OpsWorks) WaitUntilAppExistsWithContext(ctx aws.Context, input *DescribeAppsInput, opts ...request.WaiterOption) error { + w := request.Waiter{ + Name: "WaitUntilAppExists", MaxAttempts: 40, - Acceptors: []waiter.WaitAcceptor{ + Delay: request.ConstantWaiterDelay(1 * time.Second), + Acceptors: []request.WaiterAcceptor{ { - State: "success", - Matcher: "status", - Argument: "", + State: request.SuccessWaiterState, + Matcher: request.StatusWaiterMatch, Expected: 200, }, { - State: "failure", - Matcher: "status", - Argument: "", + State: request.FailureWaiterState, + Matcher: request.StatusWaiterMatch, Expected: 400, }, }, + Logger: c.Config.Logger, + NewRequest: func(opts []request.Option) (*request.Request, error) { + var inCpy *DescribeAppsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeAppsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, } + w.ApplyOptions(opts...) - w := waiter.Waiter{ - Client: c, - Input: input, - Config: waiterCfg, - } - return w.Wait() + return w.WaitWithContext(ctx) } // WaitUntilDeploymentSuccessful uses the AWS OpsWorks API operation @@ -44,32 +65,50 @@ func (c *OpsWorks) WaitUntilAppExists(input *DescribeAppsInput) error { // If the condition is not meet within the max attempt window an error will // be returned. func (c *OpsWorks) WaitUntilDeploymentSuccessful(input *DescribeDeploymentsInput) error { - waiterCfg := waiter.Config{ - Operation: "DescribeDeployments", - Delay: 15, + return c.WaitUntilDeploymentSuccessfulWithContext(aws.BackgroundContext(), input) +} + +// WaitUntilDeploymentSuccessfulWithContext is an extended version of WaitUntilDeploymentSuccessful. +// 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 *OpsWorks) WaitUntilDeploymentSuccessfulWithContext(ctx aws.Context, input *DescribeDeploymentsInput, opts ...request.WaiterOption) error { + w := request.Waiter{ + Name: "WaitUntilDeploymentSuccessful", MaxAttempts: 40, - Acceptors: []waiter.WaitAcceptor{ + Delay: request.ConstantWaiterDelay(15 * time.Second), + Acceptors: []request.WaiterAcceptor{ { - State: "success", - Matcher: "pathAll", - Argument: "Deployments[].Status", + State: request.SuccessWaiterState, + Matcher: request.PathAllWaiterMatch, Argument: "Deployments[].Status", Expected: "successful", }, { - State: "failure", - Matcher: "pathAny", - Argument: "Deployments[].Status", + State: request.FailureWaiterState, + Matcher: request.PathAnyWaiterMatch, Argument: "Deployments[].Status", Expected: "failed", }, }, + Logger: c.Config.Logger, + NewRequest: func(opts []request.Option) (*request.Request, error) { + var inCpy *DescribeDeploymentsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeDeploymentsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, } + w.ApplyOptions(opts...) - w := waiter.Waiter{ - Client: c, - Input: input, - Config: waiterCfg, - } - return w.Wait() + return w.WaitWithContext(ctx) } // WaitUntilInstanceOnline uses the AWS OpsWorks API operation @@ -77,74 +116,85 @@ func (c *OpsWorks) WaitUntilDeploymentSuccessful(input *DescribeDeploymentsInput // If the condition is not meet within the max attempt window an error will // be returned. func (c *OpsWorks) WaitUntilInstanceOnline(input *DescribeInstancesInput) error { - waiterCfg := waiter.Config{ - Operation: "DescribeInstances", - Delay: 15, + return c.WaitUntilInstanceOnlineWithContext(aws.BackgroundContext(), input) +} + +// WaitUntilInstanceOnlineWithContext is an extended version of WaitUntilInstanceOnline. +// 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 *OpsWorks) WaitUntilInstanceOnlineWithContext(ctx aws.Context, input *DescribeInstancesInput, opts ...request.WaiterOption) error { + w := request.Waiter{ + Name: "WaitUntilInstanceOnline", MaxAttempts: 40, - Acceptors: []waiter.WaitAcceptor{ + Delay: request.ConstantWaiterDelay(15 * time.Second), + Acceptors: []request.WaiterAcceptor{ { - State: "success", - Matcher: "pathAll", - Argument: "Instances[].Status", + State: request.SuccessWaiterState, + Matcher: request.PathAllWaiterMatch, Argument: "Instances[].Status", Expected: "online", }, { - State: "failure", - Matcher: "pathAny", - Argument: "Instances[].Status", + State: request.FailureWaiterState, + Matcher: request.PathAnyWaiterMatch, Argument: "Instances[].Status", Expected: "setup_failed", }, { - State: "failure", - Matcher: "pathAny", - Argument: "Instances[].Status", + State: request.FailureWaiterState, + Matcher: request.PathAnyWaiterMatch, Argument: "Instances[].Status", Expected: "shutting_down", }, { - State: "failure", - Matcher: "pathAny", - Argument: "Instances[].Status", + State: request.FailureWaiterState, + Matcher: request.PathAnyWaiterMatch, Argument: "Instances[].Status", Expected: "start_failed", }, { - State: "failure", - Matcher: "pathAny", - Argument: "Instances[].Status", + State: request.FailureWaiterState, + Matcher: request.PathAnyWaiterMatch, Argument: "Instances[].Status", Expected: "stopped", }, { - State: "failure", - Matcher: "pathAny", - Argument: "Instances[].Status", + State: request.FailureWaiterState, + Matcher: request.PathAnyWaiterMatch, Argument: "Instances[].Status", Expected: "stopping", }, { - State: "failure", - Matcher: "pathAny", - Argument: "Instances[].Status", + State: request.FailureWaiterState, + Matcher: request.PathAnyWaiterMatch, Argument: "Instances[].Status", Expected: "terminating", }, { - State: "failure", - Matcher: "pathAny", - Argument: "Instances[].Status", + State: request.FailureWaiterState, + Matcher: request.PathAnyWaiterMatch, Argument: "Instances[].Status", Expected: "terminated", }, { - State: "failure", - Matcher: "pathAny", - Argument: "Instances[].Status", + State: request.FailureWaiterState, + Matcher: request.PathAnyWaiterMatch, Argument: "Instances[].Status", Expected: "stop_failed", }, }, + Logger: c.Config.Logger, + NewRequest: func(opts []request.Option) (*request.Request, error) { + var inCpy *DescribeInstancesInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeInstancesRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, } + w.ApplyOptions(opts...) - w := waiter.Waiter{ - Client: c, - Input: input, - Config: waiterCfg, - } - return w.Wait() + return w.WaitWithContext(ctx) } // WaitUntilInstanceRegistered uses the AWS OpsWorks API operation @@ -152,68 +202,80 @@ func (c *OpsWorks) WaitUntilInstanceOnline(input *DescribeInstancesInput) error // If the condition is not meet within the max attempt window an error will // be returned. func (c *OpsWorks) WaitUntilInstanceRegistered(input *DescribeInstancesInput) error { - waiterCfg := waiter.Config{ - Operation: "DescribeInstances", - Delay: 15, + return c.WaitUntilInstanceRegisteredWithContext(aws.BackgroundContext(), input) +} + +// WaitUntilInstanceRegisteredWithContext is an extended version of WaitUntilInstanceRegistered. +// 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 *OpsWorks) WaitUntilInstanceRegisteredWithContext(ctx aws.Context, input *DescribeInstancesInput, opts ...request.WaiterOption) error { + w := request.Waiter{ + Name: "WaitUntilInstanceRegistered", MaxAttempts: 40, - Acceptors: []waiter.WaitAcceptor{ + Delay: request.ConstantWaiterDelay(15 * time.Second), + Acceptors: []request.WaiterAcceptor{ { - State: "success", - Matcher: "pathAll", - Argument: "Instances[].Status", + State: request.SuccessWaiterState, + Matcher: request.PathAllWaiterMatch, Argument: "Instances[].Status", Expected: "registered", }, { - State: "failure", - Matcher: "pathAny", - Argument: "Instances[].Status", + State: request.FailureWaiterState, + Matcher: request.PathAnyWaiterMatch, Argument: "Instances[].Status", Expected: "setup_failed", }, { - State: "failure", - Matcher: "pathAny", - Argument: "Instances[].Status", + State: request.FailureWaiterState, + Matcher: request.PathAnyWaiterMatch, Argument: "Instances[].Status", Expected: "shutting_down", }, { - State: "failure", - Matcher: "pathAny", - Argument: "Instances[].Status", + State: request.FailureWaiterState, + Matcher: request.PathAnyWaiterMatch, Argument: "Instances[].Status", Expected: "stopped", }, { - State: "failure", - Matcher: "pathAny", - Argument: "Instances[].Status", + State: request.FailureWaiterState, + Matcher: request.PathAnyWaiterMatch, Argument: "Instances[].Status", Expected: "stopping", }, { - State: "failure", - Matcher: "pathAny", - Argument: "Instances[].Status", + State: request.FailureWaiterState, + Matcher: request.PathAnyWaiterMatch, Argument: "Instances[].Status", Expected: "terminating", }, { - State: "failure", - Matcher: "pathAny", - Argument: "Instances[].Status", + State: request.FailureWaiterState, + Matcher: request.PathAnyWaiterMatch, Argument: "Instances[].Status", Expected: "terminated", }, { - State: "failure", - Matcher: "pathAny", - Argument: "Instances[].Status", + State: request.FailureWaiterState, + Matcher: request.PathAnyWaiterMatch, Argument: "Instances[].Status", Expected: "stop_failed", }, }, + Logger: c.Config.Logger, + NewRequest: func(opts []request.Option) (*request.Request, error) { + var inCpy *DescribeInstancesInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeInstancesRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, } + w.ApplyOptions(opts...) - w := waiter.Waiter{ - Client: c, - Input: input, - Config: waiterCfg, - } - return w.Wait() + return w.WaitWithContext(ctx) } // WaitUntilInstanceStopped uses the AWS OpsWorks API operation @@ -221,80 +283,90 @@ func (c *OpsWorks) WaitUntilInstanceRegistered(input *DescribeInstancesInput) er // If the condition is not meet within the max attempt window an error will // be returned. func (c *OpsWorks) WaitUntilInstanceStopped(input *DescribeInstancesInput) error { - waiterCfg := waiter.Config{ - Operation: "DescribeInstances", - Delay: 15, + return c.WaitUntilInstanceStoppedWithContext(aws.BackgroundContext(), input) +} + +// WaitUntilInstanceStoppedWithContext is an extended version of WaitUntilInstanceStopped. +// 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 *OpsWorks) WaitUntilInstanceStoppedWithContext(ctx aws.Context, input *DescribeInstancesInput, opts ...request.WaiterOption) error { + w := request.Waiter{ + Name: "WaitUntilInstanceStopped", MaxAttempts: 40, - Acceptors: []waiter.WaitAcceptor{ + Delay: request.ConstantWaiterDelay(15 * time.Second), + Acceptors: []request.WaiterAcceptor{ { - State: "success", - Matcher: "pathAll", - Argument: "Instances[].Status", + State: request.SuccessWaiterState, + Matcher: request.PathAllWaiterMatch, Argument: "Instances[].Status", Expected: "stopped", }, { - State: "failure", - Matcher: "pathAny", - Argument: "Instances[].Status", + State: request.FailureWaiterState, + Matcher: request.PathAnyWaiterMatch, Argument: "Instances[].Status", Expected: "booting", }, { - State: "failure", - Matcher: "pathAny", - Argument: "Instances[].Status", + State: request.FailureWaiterState, + Matcher: request.PathAnyWaiterMatch, Argument: "Instances[].Status", Expected: "online", }, { - State: "failure", - Matcher: "pathAny", - Argument: "Instances[].Status", + State: request.FailureWaiterState, + Matcher: request.PathAnyWaiterMatch, Argument: "Instances[].Status", Expected: "pending", }, { - State: "failure", - Matcher: "pathAny", - Argument: "Instances[].Status", + State: request.FailureWaiterState, + Matcher: request.PathAnyWaiterMatch, Argument: "Instances[].Status", Expected: "rebooting", }, { - State: "failure", - Matcher: "pathAny", - Argument: "Instances[].Status", + State: request.FailureWaiterState, + Matcher: request.PathAnyWaiterMatch, Argument: "Instances[].Status", Expected: "requested", }, { - State: "failure", - Matcher: "pathAny", - Argument: "Instances[].Status", + State: request.FailureWaiterState, + Matcher: request.PathAnyWaiterMatch, Argument: "Instances[].Status", Expected: "running_setup", }, { - State: "failure", - Matcher: "pathAny", - Argument: "Instances[].Status", + State: request.FailureWaiterState, + Matcher: request.PathAnyWaiterMatch, Argument: "Instances[].Status", Expected: "setup_failed", }, { - State: "failure", - Matcher: "pathAny", - Argument: "Instances[].Status", + State: request.FailureWaiterState, + Matcher: request.PathAnyWaiterMatch, Argument: "Instances[].Status", Expected: "start_failed", }, { - State: "failure", - Matcher: "pathAny", - Argument: "Instances[].Status", + State: request.FailureWaiterState, + Matcher: request.PathAnyWaiterMatch, Argument: "Instances[].Status", Expected: "stop_failed", }, }, + Logger: c.Config.Logger, + NewRequest: func(opts []request.Option) (*request.Request, error) { + var inCpy *DescribeInstancesInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeInstancesRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, } + w.ApplyOptions(opts...) - w := waiter.Waiter{ - Client: c, - Input: input, - Config: waiterCfg, - } - return w.Wait() + return w.WaitWithContext(ctx) } // WaitUntilInstanceTerminated uses the AWS OpsWorks API operation @@ -302,78 +374,88 @@ func (c *OpsWorks) WaitUntilInstanceStopped(input *DescribeInstancesInput) error // If the condition is not meet within the max attempt window an error will // be returned. func (c *OpsWorks) WaitUntilInstanceTerminated(input *DescribeInstancesInput) error { - waiterCfg := waiter.Config{ - Operation: "DescribeInstances", - Delay: 15, + return c.WaitUntilInstanceTerminatedWithContext(aws.BackgroundContext(), input) +} + +// WaitUntilInstanceTerminatedWithContext is an extended version of WaitUntilInstanceTerminated. +// 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 *OpsWorks) WaitUntilInstanceTerminatedWithContext(ctx aws.Context, input *DescribeInstancesInput, opts ...request.WaiterOption) error { + w := request.Waiter{ + Name: "WaitUntilInstanceTerminated", MaxAttempts: 40, - Acceptors: []waiter.WaitAcceptor{ + Delay: request.ConstantWaiterDelay(15 * time.Second), + Acceptors: []request.WaiterAcceptor{ { - State: "success", - Matcher: "pathAll", - Argument: "Instances[].Status", + State: request.SuccessWaiterState, + Matcher: request.PathAllWaiterMatch, Argument: "Instances[].Status", Expected: "terminated", }, { - State: "success", - Matcher: "error", - Argument: "", + State: request.SuccessWaiterState, + Matcher: request.ErrorWaiterMatch, Expected: "ResourceNotFoundException", }, { - State: "failure", - Matcher: "pathAny", - Argument: "Instances[].Status", + State: request.FailureWaiterState, + Matcher: request.PathAnyWaiterMatch, Argument: "Instances[].Status", Expected: "booting", }, { - State: "failure", - Matcher: "pathAny", - Argument: "Instances[].Status", + State: request.FailureWaiterState, + Matcher: request.PathAnyWaiterMatch, Argument: "Instances[].Status", Expected: "online", }, { - State: "failure", - Matcher: "pathAny", - Argument: "Instances[].Status", + State: request.FailureWaiterState, + Matcher: request.PathAnyWaiterMatch, Argument: "Instances[].Status", Expected: "pending", }, { - State: "failure", - Matcher: "pathAny", - Argument: "Instances[].Status", + State: request.FailureWaiterState, + Matcher: request.PathAnyWaiterMatch, Argument: "Instances[].Status", Expected: "rebooting", }, { - State: "failure", - Matcher: "pathAny", - Argument: "Instances[].Status", + State: request.FailureWaiterState, + Matcher: request.PathAnyWaiterMatch, Argument: "Instances[].Status", Expected: "requested", }, { - State: "failure", - Matcher: "pathAny", - Argument: "Instances[].Status", + State: request.FailureWaiterState, + Matcher: request.PathAnyWaiterMatch, Argument: "Instances[].Status", Expected: "running_setup", }, { - State: "failure", - Matcher: "pathAny", - Argument: "Instances[].Status", + State: request.FailureWaiterState, + Matcher: request.PathAnyWaiterMatch, Argument: "Instances[].Status", Expected: "setup_failed", }, { - State: "failure", - Matcher: "pathAny", - Argument: "Instances[].Status", + State: request.FailureWaiterState, + Matcher: request.PathAnyWaiterMatch, Argument: "Instances[].Status", Expected: "start_failed", }, }, + Logger: c.Config.Logger, + NewRequest: func(opts []request.Option) (*request.Request, error) { + var inCpy *DescribeInstancesInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeInstancesRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, } + w.ApplyOptions(opts...) - w := waiter.Waiter{ - Client: c, - Input: input, - Config: waiterCfg, - } - return w.Wait() + return w.WaitWithContext(ctx) } diff --git a/vendor/github.com/aws/aws-sdk-go/service/rds/api.go b/vendor/github.com/aws/aws-sdk-go/service/rds/api.go index 48b6d2c8b..786172c72 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/rds/api.go +++ b/vendor/github.com/aws/aws-sdk-go/service/rds/api.go @@ -1,12 +1,12 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. -// Package rds provides a client for Amazon Relational Database Service. package rds import ( "fmt" "time" + "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awsutil" "github.com/aws/aws-sdk-go/aws/request" "github.com/aws/aws-sdk-go/private/protocol" @@ -89,8 +89,23 @@ func (c *RDS) AddRoleToDBClusterRequest(input *AddRoleToDBClusterInput) (req *re // Please also see https://docs.aws.amazon.com/goto/WebAPI/rds-2014-10-31/AddRoleToDBCluster func (c *RDS) AddRoleToDBCluster(input *AddRoleToDBClusterInput) (*AddRoleToDBClusterOutput, error) { req, out := c.AddRoleToDBClusterRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// AddRoleToDBClusterWithContext is the same as AddRoleToDBCluster with the addition of +// the ability to pass a context and additional request options. +// +// See AddRoleToDBCluster 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 *RDS) AddRoleToDBClusterWithContext(ctx aws.Context, input *AddRoleToDBClusterInput, opts ...request.Option) (*AddRoleToDBClusterOutput, error) { + req, out := c.AddRoleToDBClusterRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opAddSourceIdentifierToSubscription = "AddSourceIdentifierToSubscription" @@ -157,8 +172,23 @@ func (c *RDS) AddSourceIdentifierToSubscriptionRequest(input *AddSourceIdentifie // Please also see https://docs.aws.amazon.com/goto/WebAPI/rds-2014-10-31/AddSourceIdentifierToSubscription func (c *RDS) AddSourceIdentifierToSubscription(input *AddSourceIdentifierToSubscriptionInput) (*AddSourceIdentifierToSubscriptionOutput, error) { req, out := c.AddSourceIdentifierToSubscriptionRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// AddSourceIdentifierToSubscriptionWithContext is the same as AddSourceIdentifierToSubscription with the addition of +// the ability to pass a context and additional request options. +// +// See AddSourceIdentifierToSubscription 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 *RDS) AddSourceIdentifierToSubscriptionWithContext(ctx aws.Context, input *AddSourceIdentifierToSubscriptionInput, opts ...request.Option) (*AddSourceIdentifierToSubscriptionOutput, error) { + req, out := c.AddSourceIdentifierToSubscriptionRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opAddTagsToResource = "AddTagsToResource" @@ -235,8 +265,23 @@ func (c *RDS) AddTagsToResourceRequest(input *AddTagsToResourceInput) (req *requ // Please also see https://docs.aws.amazon.com/goto/WebAPI/rds-2014-10-31/AddTagsToResource func (c *RDS) AddTagsToResource(input *AddTagsToResourceInput) (*AddTagsToResourceOutput, error) { req, out := c.AddTagsToResourceRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// AddTagsToResourceWithContext is the same as AddTagsToResource with the addition of +// the ability to pass a context and additional request options. +// +// See AddTagsToResource 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 *RDS) AddTagsToResourceWithContext(ctx aws.Context, input *AddTagsToResourceInput, opts ...request.Option) (*AddTagsToResourceOutput, error) { + req, out := c.AddTagsToResourceRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opApplyPendingMaintenanceAction = "ApplyPendingMaintenanceAction" @@ -301,8 +346,23 @@ func (c *RDS) ApplyPendingMaintenanceActionRequest(input *ApplyPendingMaintenanc // Please also see https://docs.aws.amazon.com/goto/WebAPI/rds-2014-10-31/ApplyPendingMaintenanceAction func (c *RDS) ApplyPendingMaintenanceAction(input *ApplyPendingMaintenanceActionInput) (*ApplyPendingMaintenanceActionOutput, error) { req, out := c.ApplyPendingMaintenanceActionRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ApplyPendingMaintenanceActionWithContext is the same as ApplyPendingMaintenanceAction with the addition of +// the ability to pass a context and additional request options. +// +// See ApplyPendingMaintenanceAction 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 *RDS) ApplyPendingMaintenanceActionWithContext(ctx aws.Context, input *ApplyPendingMaintenanceActionInput, opts ...request.Option) (*ApplyPendingMaintenanceActionOutput, error) { + req, out := c.ApplyPendingMaintenanceActionRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opAuthorizeDBSecurityGroupIngress = "AuthorizeDBSecurityGroupIngress" @@ -388,8 +448,23 @@ func (c *RDS) AuthorizeDBSecurityGroupIngressRequest(input *AuthorizeDBSecurityG // Please also see https://docs.aws.amazon.com/goto/WebAPI/rds-2014-10-31/AuthorizeDBSecurityGroupIngress func (c *RDS) AuthorizeDBSecurityGroupIngress(input *AuthorizeDBSecurityGroupIngressInput) (*AuthorizeDBSecurityGroupIngressOutput, error) { req, out := c.AuthorizeDBSecurityGroupIngressRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// AuthorizeDBSecurityGroupIngressWithContext is the same as AuthorizeDBSecurityGroupIngress with the addition of +// the ability to pass a context and additional request options. +// +// See AuthorizeDBSecurityGroupIngress 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 *RDS) AuthorizeDBSecurityGroupIngressWithContext(ctx aws.Context, input *AuthorizeDBSecurityGroupIngressInput, opts ...request.Option) (*AuthorizeDBSecurityGroupIngressOutput, error) { + req, out := c.AuthorizeDBSecurityGroupIngressRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCopyDBClusterParameterGroup = "CopyDBClusterParameterGroup" @@ -460,8 +535,23 @@ func (c *RDS) CopyDBClusterParameterGroupRequest(input *CopyDBClusterParameterGr // Please also see https://docs.aws.amazon.com/goto/WebAPI/rds-2014-10-31/CopyDBClusterParameterGroup func (c *RDS) CopyDBClusterParameterGroup(input *CopyDBClusterParameterGroupInput) (*CopyDBClusterParameterGroupOutput, error) { req, out := c.CopyDBClusterParameterGroupRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CopyDBClusterParameterGroupWithContext is the same as CopyDBClusterParameterGroup with the addition of +// the ability to pass a context and additional request options. +// +// See CopyDBClusterParameterGroup 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 *RDS) CopyDBClusterParameterGroupWithContext(ctx aws.Context, input *CopyDBClusterParameterGroupInput, opts ...request.Option) (*CopyDBClusterParameterGroupOutput, error) { + req, out := c.CopyDBClusterParameterGroupRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCopyDBClusterSnapshot = "CopyDBClusterSnapshot" @@ -601,8 +691,23 @@ func (c *RDS) CopyDBClusterSnapshotRequest(input *CopyDBClusterSnapshotInput) (r // Please also see https://docs.aws.amazon.com/goto/WebAPI/rds-2014-10-31/CopyDBClusterSnapshot func (c *RDS) CopyDBClusterSnapshot(input *CopyDBClusterSnapshotInput) (*CopyDBClusterSnapshotOutput, error) { req, out := c.CopyDBClusterSnapshotRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CopyDBClusterSnapshotWithContext is the same as CopyDBClusterSnapshot with the addition of +// the ability to pass a context and additional request options. +// +// See CopyDBClusterSnapshot 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 *RDS) CopyDBClusterSnapshotWithContext(ctx aws.Context, input *CopyDBClusterSnapshotInput, opts ...request.Option) (*CopyDBClusterSnapshotOutput, error) { + req, out := c.CopyDBClusterSnapshotRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCopyDBParameterGroup = "CopyDBParameterGroup" @@ -673,8 +778,23 @@ func (c *RDS) CopyDBParameterGroupRequest(input *CopyDBParameterGroupInput) (req // Please also see https://docs.aws.amazon.com/goto/WebAPI/rds-2014-10-31/CopyDBParameterGroup func (c *RDS) CopyDBParameterGroup(input *CopyDBParameterGroupInput) (*CopyDBParameterGroupOutput, error) { req, out := c.CopyDBParameterGroupRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CopyDBParameterGroupWithContext is the same as CopyDBParameterGroup with the addition of +// the ability to pass a context and additional request options. +// +// See CopyDBParameterGroup 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 *RDS) CopyDBParameterGroupWithContext(ctx aws.Context, input *CopyDBParameterGroupInput, opts ...request.Option) (*CopyDBParameterGroupOutput, error) { + req, out := c.CopyDBParameterGroupRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCopyDBSnapshot = "CopyDBSnapshot" @@ -728,7 +848,7 @@ func (c *RDS) CopyDBSnapshotRequest(input *CopyDBSnapshotInput) (req *request.Re // To copy a DB snapshot from a shared manual DB snapshot, SourceDBSnapshotIdentifier // must be the Amazon Resource Name (ARN) of the shared DB snapshot. // -// You can copy an encrypted DB snapshot from another AWS Region. In that case, +// You can copy an encrypted DB snapshot from another AWS region. In that case, // the region where you call the CopyDBSnapshot action is the destination region // for the encrypted DB snapshot to be copied to. To copy an encrypted DB snapshot // from another region, you must provide the following values: @@ -779,7 +899,7 @@ func (c *RDS) CopyDBSnapshotRequest(input *CopyDBSnapshotInput) (req *request.Re // in the presigned URL. // // For more information on copying encrypted snapshots from one region to another, -// see Copying an Encrypted DB Snapshot to Another Region (http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_CopySnapshot.html#USER_CopySnapshot.Encrypted.CrossRegion) +// see Copying a DB Snapshot (http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_CopySnapshot.html#USER_CopyDBSnapshot) // in the Amazon RDS User Guide. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions @@ -808,8 +928,23 @@ func (c *RDS) CopyDBSnapshotRequest(input *CopyDBSnapshotInput) (req *request.Re // Please also see https://docs.aws.amazon.com/goto/WebAPI/rds-2014-10-31/CopyDBSnapshot func (c *RDS) CopyDBSnapshot(input *CopyDBSnapshotInput) (*CopyDBSnapshotOutput, error) { req, out := c.CopyDBSnapshotRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CopyDBSnapshotWithContext is the same as CopyDBSnapshot with the addition of +// the ability to pass a context and additional request options. +// +// See CopyDBSnapshot 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 *RDS) CopyDBSnapshotWithContext(ctx aws.Context, input *CopyDBSnapshotInput, opts ...request.Option) (*CopyDBSnapshotOutput, error) { + req, out := c.CopyDBSnapshotRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCopyOptionGroup = "CopyOptionGroup" @@ -879,8 +1014,23 @@ func (c *RDS) CopyOptionGroupRequest(input *CopyOptionGroupInput) (req *request. // Please also see https://docs.aws.amazon.com/goto/WebAPI/rds-2014-10-31/CopyOptionGroup func (c *RDS) CopyOptionGroup(input *CopyOptionGroupInput) (*CopyOptionGroupOutput, error) { req, out := c.CopyOptionGroupRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CopyOptionGroupWithContext is the same as CopyOptionGroup with the addition of +// the ability to pass a context and additional request options. +// +// See CopyOptionGroup 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 *RDS) CopyOptionGroupWithContext(ctx aws.Context, input *CopyOptionGroupInput, opts ...request.Option) (*CopyOptionGroupOutput, error) { + req, out := c.CopyOptionGroupRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateDBCluster = "CreateDBCluster" @@ -1002,8 +1152,23 @@ func (c *RDS) CreateDBClusterRequest(input *CreateDBClusterInput) (req *request. // Please also see https://docs.aws.amazon.com/goto/WebAPI/rds-2014-10-31/CreateDBCluster func (c *RDS) CreateDBCluster(input *CreateDBClusterInput) (*CreateDBClusterOutput, error) { req, out := c.CreateDBClusterRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateDBClusterWithContext is the same as CreateDBCluster with the addition of +// the ability to pass a context and additional request options. +// +// See CreateDBCluster 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 *RDS) CreateDBClusterWithContext(ctx aws.Context, input *CreateDBClusterInput, opts ...request.Option) (*CreateDBClusterOutput, error) { + req, out := c.CreateDBClusterRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateDBClusterParameterGroup = "CreateDBClusterParameterGroup" @@ -1098,8 +1263,23 @@ func (c *RDS) CreateDBClusterParameterGroupRequest(input *CreateDBClusterParamet // Please also see https://docs.aws.amazon.com/goto/WebAPI/rds-2014-10-31/CreateDBClusterParameterGroup func (c *RDS) CreateDBClusterParameterGroup(input *CreateDBClusterParameterGroupInput) (*CreateDBClusterParameterGroupOutput, error) { req, out := c.CreateDBClusterParameterGroupRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateDBClusterParameterGroupWithContext is the same as CreateDBClusterParameterGroup with the addition of +// the ability to pass a context and additional request options. +// +// See CreateDBClusterParameterGroup 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 *RDS) CreateDBClusterParameterGroupWithContext(ctx aws.Context, input *CreateDBClusterParameterGroupInput, opts ...request.Option) (*CreateDBClusterParameterGroupOutput, error) { + req, out := c.CreateDBClusterParameterGroupRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateDBClusterSnapshot = "CreateDBClusterSnapshot" @@ -1177,8 +1357,23 @@ func (c *RDS) CreateDBClusterSnapshotRequest(input *CreateDBClusterSnapshotInput // Please also see https://docs.aws.amazon.com/goto/WebAPI/rds-2014-10-31/CreateDBClusterSnapshot func (c *RDS) CreateDBClusterSnapshot(input *CreateDBClusterSnapshotInput) (*CreateDBClusterSnapshotOutput, error) { req, out := c.CreateDBClusterSnapshotRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateDBClusterSnapshotWithContext is the same as CreateDBClusterSnapshot with the addition of +// the ability to pass a context and additional request options. +// +// See CreateDBClusterSnapshot 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 *RDS) CreateDBClusterSnapshotWithContext(ctx aws.Context, input *CreateDBClusterSnapshotInput, opts ...request.Option) (*CreateDBClusterSnapshotOutput, error) { + req, out := c.CreateDBClusterSnapshotRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateDBInstance = "CreateDBInstance" @@ -1302,8 +1497,23 @@ func (c *RDS) CreateDBInstanceRequest(input *CreateDBInstanceInput) (req *reques // Please also see https://docs.aws.amazon.com/goto/WebAPI/rds-2014-10-31/CreateDBInstance func (c *RDS) CreateDBInstance(input *CreateDBInstanceInput) (*CreateDBInstanceOutput, error) { req, out := c.CreateDBInstanceRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateDBInstanceWithContext is the same as CreateDBInstance with the addition of +// the ability to pass a context and additional request options. +// +// See CreateDBInstance 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 *RDS) CreateDBInstanceWithContext(ctx aws.Context, input *CreateDBInstanceInput, opts ...request.Option) (*CreateDBInstanceOutput, error) { + req, out := c.CreateDBInstanceRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateDBInstanceReadReplica = "CreateDBInstanceReadReplica" @@ -1354,6 +1564,9 @@ func (c *RDS) CreateDBInstanceReadReplicaRequest(input *CreateDBInstanceReadRepl // Creates a DB instance for a DB instance running MySQL, MariaDB, or PostgreSQL // that acts as a Read Replica of a source DB instance. // +// Amazon Aurora does not support this action. You must call the CreateDBInstance +// action to create a DB instance for an Aurora DB cluster. +// // All Read Replica DB instances are created as Single-AZ deployments with backups // disabled. All other DB instance attributes (including DB security groups // and DB parameter groups) are inherited from the source DB instance, except @@ -1488,8 +1701,23 @@ func (c *RDS) CreateDBInstanceReadReplicaRequest(input *CreateDBInstanceReadRepl // Please also see https://docs.aws.amazon.com/goto/WebAPI/rds-2014-10-31/CreateDBInstanceReadReplica func (c *RDS) CreateDBInstanceReadReplica(input *CreateDBInstanceReadReplicaInput) (*CreateDBInstanceReadReplicaOutput, error) { req, out := c.CreateDBInstanceReadReplicaRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateDBInstanceReadReplicaWithContext is the same as CreateDBInstanceReadReplica with the addition of +// the ability to pass a context and additional request options. +// +// See CreateDBInstanceReadReplica 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 *RDS) CreateDBInstanceReadReplicaWithContext(ctx aws.Context, input *CreateDBInstanceReadReplicaInput, opts ...request.Option) (*CreateDBInstanceReadReplicaOutput, error) { + req, out := c.CreateDBInstanceReadReplicaRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateDBParameterGroup = "CreateDBParameterGroup" @@ -1577,8 +1805,23 @@ func (c *RDS) CreateDBParameterGroupRequest(input *CreateDBParameterGroupInput) // Please also see https://docs.aws.amazon.com/goto/WebAPI/rds-2014-10-31/CreateDBParameterGroup func (c *RDS) CreateDBParameterGroup(input *CreateDBParameterGroupInput) (*CreateDBParameterGroupOutput, error) { req, out := c.CreateDBParameterGroupRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateDBParameterGroupWithContext is the same as CreateDBParameterGroup with the addition of +// the ability to pass a context and additional request options. +// +// See CreateDBParameterGroup 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 *RDS) CreateDBParameterGroupWithContext(ctx aws.Context, input *CreateDBParameterGroupInput, opts ...request.Option) (*CreateDBParameterGroupOutput, error) { + req, out := c.CreateDBParameterGroupRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateDBSecurityGroup = "CreateDBSecurityGroup" @@ -1651,8 +1894,23 @@ func (c *RDS) CreateDBSecurityGroupRequest(input *CreateDBSecurityGroupInput) (r // Please also see https://docs.aws.amazon.com/goto/WebAPI/rds-2014-10-31/CreateDBSecurityGroup func (c *RDS) CreateDBSecurityGroup(input *CreateDBSecurityGroupInput) (*CreateDBSecurityGroupOutput, error) { req, out := c.CreateDBSecurityGroupRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateDBSecurityGroupWithContext is the same as CreateDBSecurityGroup with the addition of +// the ability to pass a context and additional request options. +// +// See CreateDBSecurityGroup 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 *RDS) CreateDBSecurityGroupWithContext(ctx aws.Context, input *CreateDBSecurityGroupInput, opts ...request.Option) (*CreateDBSecurityGroupOutput, error) { + req, out := c.CreateDBSecurityGroupRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateDBSnapshot = "CreateDBSnapshot" @@ -1725,8 +1983,23 @@ func (c *RDS) CreateDBSnapshotRequest(input *CreateDBSnapshotInput) (req *reques // Please also see https://docs.aws.amazon.com/goto/WebAPI/rds-2014-10-31/CreateDBSnapshot func (c *RDS) CreateDBSnapshot(input *CreateDBSnapshotInput) (*CreateDBSnapshotOutput, error) { req, out := c.CreateDBSnapshotRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateDBSnapshotWithContext is the same as CreateDBSnapshot with the addition of +// the ability to pass a context and additional request options. +// +// See CreateDBSnapshot 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 *RDS) CreateDBSnapshotWithContext(ctx aws.Context, input *CreateDBSnapshotInput, opts ...request.Option) (*CreateDBSnapshotOutput, error) { + req, out := c.CreateDBSnapshotRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateDBSubnetGroup = "CreateDBSubnetGroup" @@ -1806,8 +2079,23 @@ func (c *RDS) CreateDBSubnetGroupRequest(input *CreateDBSubnetGroupInput) (req * // Please also see https://docs.aws.amazon.com/goto/WebAPI/rds-2014-10-31/CreateDBSubnetGroup func (c *RDS) CreateDBSubnetGroup(input *CreateDBSubnetGroupInput) (*CreateDBSubnetGroupOutput, error) { req, out := c.CreateDBSubnetGroupRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateDBSubnetGroupWithContext is the same as CreateDBSubnetGroup with the addition of +// the ability to pass a context and additional request options. +// +// See CreateDBSubnetGroup 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 *RDS) CreateDBSubnetGroupWithContext(ctx aws.Context, input *CreateDBSubnetGroupInput, opts ...request.Option) (*CreateDBSubnetGroupOutput, error) { + req, out := c.CreateDBSubnetGroupRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateEventSubscription = "CreateEventSubscription" @@ -1906,8 +2194,23 @@ func (c *RDS) CreateEventSubscriptionRequest(input *CreateEventSubscriptionInput // Please also see https://docs.aws.amazon.com/goto/WebAPI/rds-2014-10-31/CreateEventSubscription func (c *RDS) CreateEventSubscription(input *CreateEventSubscriptionInput) (*CreateEventSubscriptionOutput, error) { req, out := c.CreateEventSubscriptionRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateEventSubscriptionWithContext is the same as CreateEventSubscription with the addition of +// the ability to pass a context and additional request options. +// +// See CreateEventSubscription 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 *RDS) CreateEventSubscriptionWithContext(ctx aws.Context, input *CreateEventSubscriptionInput, opts ...request.Option) (*CreateEventSubscriptionOutput, error) { + req, out := c.CreateEventSubscriptionRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateOptionGroup = "CreateOptionGroup" @@ -1974,8 +2277,23 @@ func (c *RDS) CreateOptionGroupRequest(input *CreateOptionGroupInput) (req *requ // Please also see https://docs.aws.amazon.com/goto/WebAPI/rds-2014-10-31/CreateOptionGroup func (c *RDS) CreateOptionGroup(input *CreateOptionGroupInput) (*CreateOptionGroupOutput, error) { req, out := c.CreateOptionGroupRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateOptionGroupWithContext is the same as CreateOptionGroup with the addition of +// the ability to pass a context and additional request options. +// +// See CreateOptionGroup 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 *RDS) CreateOptionGroupWithContext(ctx aws.Context, input *CreateOptionGroupInput, opts ...request.Option) (*CreateOptionGroupOutput, error) { + req, out := c.CreateOptionGroupRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteDBCluster = "DeleteDBCluster" @@ -2056,8 +2374,23 @@ func (c *RDS) DeleteDBClusterRequest(input *DeleteDBClusterInput) (req *request. // Please also see https://docs.aws.amazon.com/goto/WebAPI/rds-2014-10-31/DeleteDBCluster func (c *RDS) DeleteDBCluster(input *DeleteDBClusterInput) (*DeleteDBClusterOutput, error) { req, out := c.DeleteDBClusterRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteDBClusterWithContext is the same as DeleteDBCluster with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteDBCluster 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 *RDS) DeleteDBClusterWithContext(ctx aws.Context, input *DeleteDBClusterInput, opts ...request.Option) (*DeleteDBClusterOutput, error) { + req, out := c.DeleteDBClusterRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteDBClusterParameterGroup = "DeleteDBClusterParameterGroup" @@ -2122,7 +2455,9 @@ func (c *RDS) DeleteDBClusterParameterGroupRequest(input *DeleteDBClusterParamet // // Returned Error Codes: // * ErrCodeInvalidDBParameterGroupStateFault "InvalidDBParameterGroupState" -// The DB parameter group cannot be deleted because it is in use. +// The DB parameter group is in use or is in an invalid state. If you are attempting +// to delete the parameter group, you cannot delete it when the parameter group +// is in this state. // // * ErrCodeDBParameterGroupNotFoundFault "DBParameterGroupNotFound" // DBParameterGroupName does not refer to an existing DB parameter group. @@ -2130,8 +2465,23 @@ func (c *RDS) DeleteDBClusterParameterGroupRequest(input *DeleteDBClusterParamet // Please also see https://docs.aws.amazon.com/goto/WebAPI/rds-2014-10-31/DeleteDBClusterParameterGroup func (c *RDS) DeleteDBClusterParameterGroup(input *DeleteDBClusterParameterGroupInput) (*DeleteDBClusterParameterGroupOutput, error) { req, out := c.DeleteDBClusterParameterGroupRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteDBClusterParameterGroupWithContext is the same as DeleteDBClusterParameterGroup with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteDBClusterParameterGroup 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 *RDS) DeleteDBClusterParameterGroupWithContext(ctx aws.Context, input *DeleteDBClusterParameterGroupInput, opts ...request.Option) (*DeleteDBClusterParameterGroupOutput, error) { + req, out := c.DeleteDBClusterParameterGroupRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteDBClusterSnapshot = "DeleteDBClusterSnapshot" @@ -2204,8 +2554,23 @@ func (c *RDS) DeleteDBClusterSnapshotRequest(input *DeleteDBClusterSnapshotInput // Please also see https://docs.aws.amazon.com/goto/WebAPI/rds-2014-10-31/DeleteDBClusterSnapshot func (c *RDS) DeleteDBClusterSnapshot(input *DeleteDBClusterSnapshotInput) (*DeleteDBClusterSnapshotOutput, error) { req, out := c.DeleteDBClusterSnapshotRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteDBClusterSnapshotWithContext is the same as DeleteDBClusterSnapshot with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteDBClusterSnapshot 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 *RDS) DeleteDBClusterSnapshotWithContext(ctx aws.Context, input *DeleteDBClusterSnapshotInput, opts ...request.Option) (*DeleteDBClusterSnapshotOutput, error) { + req, out := c.DeleteDBClusterSnapshotRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteDBInstance = "DeleteDBInstance" @@ -2305,8 +2670,23 @@ func (c *RDS) DeleteDBInstanceRequest(input *DeleteDBInstanceInput) (req *reques // Please also see https://docs.aws.amazon.com/goto/WebAPI/rds-2014-10-31/DeleteDBInstance func (c *RDS) DeleteDBInstance(input *DeleteDBInstanceInput) (*DeleteDBInstanceOutput, error) { req, out := c.DeleteDBInstanceRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteDBInstanceWithContext is the same as DeleteDBInstance with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteDBInstance 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 *RDS) DeleteDBInstanceWithContext(ctx aws.Context, input *DeleteDBInstanceInput, opts ...request.Option) (*DeleteDBInstanceOutput, error) { + req, out := c.DeleteDBInstanceRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteDBParameterGroup = "DeleteDBParameterGroup" @@ -2368,7 +2748,9 @@ func (c *RDS) DeleteDBParameterGroupRequest(input *DeleteDBParameterGroupInput) // // Returned Error Codes: // * ErrCodeInvalidDBParameterGroupStateFault "InvalidDBParameterGroupState" -// The DB parameter group cannot be deleted because it is in use. +// The DB parameter group is in use or is in an invalid state. If you are attempting +// to delete the parameter group, you cannot delete it when the parameter group +// is in this state. // // * ErrCodeDBParameterGroupNotFoundFault "DBParameterGroupNotFound" // DBParameterGroupName does not refer to an existing DB parameter group. @@ -2376,8 +2758,23 @@ func (c *RDS) DeleteDBParameterGroupRequest(input *DeleteDBParameterGroupInput) // Please also see https://docs.aws.amazon.com/goto/WebAPI/rds-2014-10-31/DeleteDBParameterGroup func (c *RDS) DeleteDBParameterGroup(input *DeleteDBParameterGroupInput) (*DeleteDBParameterGroupOutput, error) { req, out := c.DeleteDBParameterGroupRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteDBParameterGroupWithContext is the same as DeleteDBParameterGroup with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteDBParameterGroup 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 *RDS) DeleteDBParameterGroupWithContext(ctx aws.Context, input *DeleteDBParameterGroupInput, opts ...request.Option) (*DeleteDBParameterGroupOutput, error) { + req, out := c.DeleteDBParameterGroupRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteDBSecurityGroup = "DeleteDBSecurityGroup" @@ -2448,8 +2845,23 @@ func (c *RDS) DeleteDBSecurityGroupRequest(input *DeleteDBSecurityGroupInput) (r // Please also see https://docs.aws.amazon.com/goto/WebAPI/rds-2014-10-31/DeleteDBSecurityGroup func (c *RDS) DeleteDBSecurityGroup(input *DeleteDBSecurityGroupInput) (*DeleteDBSecurityGroupOutput, error) { req, out := c.DeleteDBSecurityGroupRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteDBSecurityGroupWithContext is the same as DeleteDBSecurityGroup with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteDBSecurityGroup 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 *RDS) DeleteDBSecurityGroupWithContext(ctx aws.Context, input *DeleteDBSecurityGroupInput, opts ...request.Option) (*DeleteDBSecurityGroupOutput, error) { + req, out := c.DeleteDBSecurityGroupRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteDBSnapshot = "DeleteDBSnapshot" @@ -2519,8 +2931,23 @@ func (c *RDS) DeleteDBSnapshotRequest(input *DeleteDBSnapshotInput) (req *reques // Please also see https://docs.aws.amazon.com/goto/WebAPI/rds-2014-10-31/DeleteDBSnapshot func (c *RDS) DeleteDBSnapshot(input *DeleteDBSnapshotInput) (*DeleteDBSnapshotOutput, error) { req, out := c.DeleteDBSnapshotRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteDBSnapshotWithContext is the same as DeleteDBSnapshot with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteDBSnapshot 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 *RDS) DeleteDBSnapshotWithContext(ctx aws.Context, input *DeleteDBSnapshotInput, opts ...request.Option) (*DeleteDBSnapshotOutput, error) { + req, out := c.DeleteDBSnapshotRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteDBSubnetGroup = "DeleteDBSubnetGroup" @@ -2594,8 +3021,23 @@ func (c *RDS) DeleteDBSubnetGroupRequest(input *DeleteDBSubnetGroupInput) (req * // Please also see https://docs.aws.amazon.com/goto/WebAPI/rds-2014-10-31/DeleteDBSubnetGroup func (c *RDS) DeleteDBSubnetGroup(input *DeleteDBSubnetGroupInput) (*DeleteDBSubnetGroupOutput, error) { req, out := c.DeleteDBSubnetGroupRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteDBSubnetGroupWithContext is the same as DeleteDBSubnetGroup with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteDBSubnetGroup 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 *RDS) DeleteDBSubnetGroupWithContext(ctx aws.Context, input *DeleteDBSubnetGroupInput, opts ...request.Option) (*DeleteDBSubnetGroupOutput, error) { + req, out := c.DeleteDBSubnetGroupRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteEventSubscription = "DeleteEventSubscription" @@ -2663,8 +3105,23 @@ func (c *RDS) DeleteEventSubscriptionRequest(input *DeleteEventSubscriptionInput // Please also see https://docs.aws.amazon.com/goto/WebAPI/rds-2014-10-31/DeleteEventSubscription func (c *RDS) DeleteEventSubscription(input *DeleteEventSubscriptionInput) (*DeleteEventSubscriptionOutput, error) { req, out := c.DeleteEventSubscriptionRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteEventSubscriptionWithContext is the same as DeleteEventSubscription with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteEventSubscription 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 *RDS) DeleteEventSubscriptionWithContext(ctx aws.Context, input *DeleteEventSubscriptionInput, opts ...request.Option) (*DeleteEventSubscriptionOutput, error) { + req, out := c.DeleteEventSubscriptionRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteOptionGroup = "DeleteOptionGroup" @@ -2733,8 +3190,23 @@ func (c *RDS) DeleteOptionGroupRequest(input *DeleteOptionGroupInput) (req *requ // Please also see https://docs.aws.amazon.com/goto/WebAPI/rds-2014-10-31/DeleteOptionGroup func (c *RDS) DeleteOptionGroup(input *DeleteOptionGroupInput) (*DeleteOptionGroupOutput, error) { req, out := c.DeleteOptionGroupRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteOptionGroupWithContext is the same as DeleteOptionGroup with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteOptionGroup 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 *RDS) DeleteOptionGroupWithContext(ctx aws.Context, input *DeleteOptionGroupInput, opts ...request.Option) (*DeleteOptionGroupOutput, error) { + req, out := c.DeleteOptionGroupRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeAccountAttributes = "DescribeAccountAttributes" @@ -2798,8 +3270,23 @@ func (c *RDS) DescribeAccountAttributesRequest(input *DescribeAccountAttributesI // Please also see https://docs.aws.amazon.com/goto/WebAPI/rds-2014-10-31/DescribeAccountAttributes func (c *RDS) DescribeAccountAttributes(input *DescribeAccountAttributesInput) (*DescribeAccountAttributesOutput, error) { req, out := c.DescribeAccountAttributesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeAccountAttributesWithContext is the same as DescribeAccountAttributes with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeAccountAttributes 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 *RDS) DescribeAccountAttributesWithContext(ctx aws.Context, input *DescribeAccountAttributesInput, opts ...request.Option) (*DescribeAccountAttributesOutput, error) { + req, out := c.DescribeAccountAttributesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeCertificates = "DescribeCertificates" @@ -2863,8 +3350,23 @@ func (c *RDS) DescribeCertificatesRequest(input *DescribeCertificatesInput) (req // Please also see https://docs.aws.amazon.com/goto/WebAPI/rds-2014-10-31/DescribeCertificates func (c *RDS) DescribeCertificates(input *DescribeCertificatesInput) (*DescribeCertificatesOutput, error) { req, out := c.DescribeCertificatesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeCertificatesWithContext is the same as DescribeCertificates with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeCertificates 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 *RDS) DescribeCertificatesWithContext(ctx aws.Context, input *DescribeCertificatesInput, opts ...request.Option) (*DescribeCertificatesOutput, error) { + req, out := c.DescribeCertificatesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeDBClusterParameterGroups = "DescribeDBClusterParameterGroups" @@ -2933,8 +3435,23 @@ func (c *RDS) DescribeDBClusterParameterGroupsRequest(input *DescribeDBClusterPa // Please also see https://docs.aws.amazon.com/goto/WebAPI/rds-2014-10-31/DescribeDBClusterParameterGroups func (c *RDS) DescribeDBClusterParameterGroups(input *DescribeDBClusterParameterGroupsInput) (*DescribeDBClusterParameterGroupsOutput, error) { req, out := c.DescribeDBClusterParameterGroupsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeDBClusterParameterGroupsWithContext is the same as DescribeDBClusterParameterGroups with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeDBClusterParameterGroups 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 *RDS) DescribeDBClusterParameterGroupsWithContext(ctx aws.Context, input *DescribeDBClusterParameterGroupsInput, opts ...request.Option) (*DescribeDBClusterParameterGroupsOutput, error) { + req, out := c.DescribeDBClusterParameterGroupsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeDBClusterParameters = "DescribeDBClusterParameters" @@ -3002,8 +3519,23 @@ func (c *RDS) DescribeDBClusterParametersRequest(input *DescribeDBClusterParamet // Please also see https://docs.aws.amazon.com/goto/WebAPI/rds-2014-10-31/DescribeDBClusterParameters func (c *RDS) DescribeDBClusterParameters(input *DescribeDBClusterParametersInput) (*DescribeDBClusterParametersOutput, error) { req, out := c.DescribeDBClusterParametersRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeDBClusterParametersWithContext is the same as DescribeDBClusterParameters with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeDBClusterParameters 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 *RDS) DescribeDBClusterParametersWithContext(ctx aws.Context, input *DescribeDBClusterParametersInput, opts ...request.Option) (*DescribeDBClusterParametersOutput, error) { + req, out := c.DescribeDBClusterParametersRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeDBClusterSnapshotAttributes = "DescribeDBClusterSnapshotAttributes" @@ -3078,8 +3610,23 @@ func (c *RDS) DescribeDBClusterSnapshotAttributesRequest(input *DescribeDBCluste // Please also see https://docs.aws.amazon.com/goto/WebAPI/rds-2014-10-31/DescribeDBClusterSnapshotAttributes func (c *RDS) DescribeDBClusterSnapshotAttributes(input *DescribeDBClusterSnapshotAttributesInput) (*DescribeDBClusterSnapshotAttributesOutput, error) { req, out := c.DescribeDBClusterSnapshotAttributesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeDBClusterSnapshotAttributesWithContext is the same as DescribeDBClusterSnapshotAttributes with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeDBClusterSnapshotAttributes 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 *RDS) DescribeDBClusterSnapshotAttributesWithContext(ctx aws.Context, input *DescribeDBClusterSnapshotAttributesInput, opts ...request.Option) (*DescribeDBClusterSnapshotAttributesOutput, error) { + req, out := c.DescribeDBClusterSnapshotAttributesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeDBClusterSnapshots = "DescribeDBClusterSnapshots" @@ -3147,8 +3694,23 @@ func (c *RDS) DescribeDBClusterSnapshotsRequest(input *DescribeDBClusterSnapshot // Please also see https://docs.aws.amazon.com/goto/WebAPI/rds-2014-10-31/DescribeDBClusterSnapshots func (c *RDS) DescribeDBClusterSnapshots(input *DescribeDBClusterSnapshotsInput) (*DescribeDBClusterSnapshotsOutput, error) { req, out := c.DescribeDBClusterSnapshotsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeDBClusterSnapshotsWithContext is the same as DescribeDBClusterSnapshots with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeDBClusterSnapshots 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 *RDS) DescribeDBClusterSnapshotsWithContext(ctx aws.Context, input *DescribeDBClusterSnapshotsInput, opts ...request.Option) (*DescribeDBClusterSnapshotsOutput, error) { + req, out := c.DescribeDBClusterSnapshotsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeDBClusters = "DescribeDBClusters" @@ -3216,8 +3778,23 @@ func (c *RDS) DescribeDBClustersRequest(input *DescribeDBClustersInput) (req *re // Please also see https://docs.aws.amazon.com/goto/WebAPI/rds-2014-10-31/DescribeDBClusters func (c *RDS) DescribeDBClusters(input *DescribeDBClustersInput) (*DescribeDBClustersOutput, error) { req, out := c.DescribeDBClustersRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeDBClustersWithContext is the same as DescribeDBClusters with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeDBClusters 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 *RDS) DescribeDBClustersWithContext(ctx aws.Context, input *DescribeDBClustersInput, opts ...request.Option) (*DescribeDBClustersOutput, error) { + req, out := c.DescribeDBClustersRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeDBEngineVersions = "DescribeDBEngineVersions" @@ -3282,8 +3859,23 @@ func (c *RDS) DescribeDBEngineVersionsRequest(input *DescribeDBEngineVersionsInp // Please also see https://docs.aws.amazon.com/goto/WebAPI/rds-2014-10-31/DescribeDBEngineVersions func (c *RDS) DescribeDBEngineVersions(input *DescribeDBEngineVersionsInput) (*DescribeDBEngineVersionsOutput, error) { req, out := c.DescribeDBEngineVersionsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeDBEngineVersionsWithContext is the same as DescribeDBEngineVersions with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeDBEngineVersions 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 *RDS) DescribeDBEngineVersionsWithContext(ctx aws.Context, input *DescribeDBEngineVersionsInput, opts ...request.Option) (*DescribeDBEngineVersionsOutput, error) { + req, out := c.DescribeDBEngineVersionsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // DescribeDBEngineVersionsPages iterates over the pages of a DescribeDBEngineVersions operation, @@ -3303,12 +3895,37 @@ func (c *RDS) DescribeDBEngineVersions(input *DescribeDBEngineVersionsInput) (*D // return pageNum <= 3 // }) // -func (c *RDS) DescribeDBEngineVersionsPages(input *DescribeDBEngineVersionsInput, fn func(p *DescribeDBEngineVersionsOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.DescribeDBEngineVersionsRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*DescribeDBEngineVersionsOutput), lastPage) - }) +func (c *RDS) DescribeDBEngineVersionsPages(input *DescribeDBEngineVersionsInput, fn func(*DescribeDBEngineVersionsOutput, bool) bool) error { + return c.DescribeDBEngineVersionsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// DescribeDBEngineVersionsPagesWithContext same as DescribeDBEngineVersionsPages 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 *RDS) DescribeDBEngineVersionsPagesWithContext(ctx aws.Context, input *DescribeDBEngineVersionsInput, fn func(*DescribeDBEngineVersionsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *DescribeDBEngineVersionsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeDBEngineVersionsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*DescribeDBEngineVersionsOutput), !p.HasNextPage()) + } + return p.Err() } const opDescribeDBInstances = "DescribeDBInstances" @@ -3378,8 +3995,23 @@ func (c *RDS) DescribeDBInstancesRequest(input *DescribeDBInstancesInput) (req * // Please also see https://docs.aws.amazon.com/goto/WebAPI/rds-2014-10-31/DescribeDBInstances func (c *RDS) DescribeDBInstances(input *DescribeDBInstancesInput) (*DescribeDBInstancesOutput, error) { req, out := c.DescribeDBInstancesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeDBInstancesWithContext is the same as DescribeDBInstances with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeDBInstances 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 *RDS) DescribeDBInstancesWithContext(ctx aws.Context, input *DescribeDBInstancesInput, opts ...request.Option) (*DescribeDBInstancesOutput, error) { + req, out := c.DescribeDBInstancesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // DescribeDBInstancesPages iterates over the pages of a DescribeDBInstances operation, @@ -3399,12 +4031,37 @@ func (c *RDS) DescribeDBInstances(input *DescribeDBInstancesInput) (*DescribeDBI // return pageNum <= 3 // }) // -func (c *RDS) DescribeDBInstancesPages(input *DescribeDBInstancesInput, fn func(p *DescribeDBInstancesOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.DescribeDBInstancesRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*DescribeDBInstancesOutput), lastPage) - }) +func (c *RDS) DescribeDBInstancesPages(input *DescribeDBInstancesInput, fn func(*DescribeDBInstancesOutput, bool) bool) error { + return c.DescribeDBInstancesPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// DescribeDBInstancesPagesWithContext same as DescribeDBInstancesPages 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 *RDS) DescribeDBInstancesPagesWithContext(ctx aws.Context, input *DescribeDBInstancesInput, fn func(*DescribeDBInstancesOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *DescribeDBInstancesInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeDBInstancesRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*DescribeDBInstancesOutput), !p.HasNextPage()) + } + return p.Err() } const opDescribeDBLogFiles = "DescribeDBLogFiles" @@ -3474,8 +4131,23 @@ func (c *RDS) DescribeDBLogFilesRequest(input *DescribeDBLogFilesInput) (req *re // Please also see https://docs.aws.amazon.com/goto/WebAPI/rds-2014-10-31/DescribeDBLogFiles func (c *RDS) DescribeDBLogFiles(input *DescribeDBLogFilesInput) (*DescribeDBLogFilesOutput, error) { req, out := c.DescribeDBLogFilesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeDBLogFilesWithContext is the same as DescribeDBLogFiles with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeDBLogFiles 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 *RDS) DescribeDBLogFilesWithContext(ctx aws.Context, input *DescribeDBLogFilesInput, opts ...request.Option) (*DescribeDBLogFilesOutput, error) { + req, out := c.DescribeDBLogFilesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // DescribeDBLogFilesPages iterates over the pages of a DescribeDBLogFiles operation, @@ -3495,12 +4167,37 @@ func (c *RDS) DescribeDBLogFiles(input *DescribeDBLogFilesInput) (*DescribeDBLog // return pageNum <= 3 // }) // -func (c *RDS) DescribeDBLogFilesPages(input *DescribeDBLogFilesInput, fn func(p *DescribeDBLogFilesOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.DescribeDBLogFilesRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*DescribeDBLogFilesOutput), lastPage) - }) +func (c *RDS) DescribeDBLogFilesPages(input *DescribeDBLogFilesInput, fn func(*DescribeDBLogFilesOutput, bool) bool) error { + return c.DescribeDBLogFilesPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// DescribeDBLogFilesPagesWithContext same as DescribeDBLogFilesPages 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 *RDS) DescribeDBLogFilesPagesWithContext(ctx aws.Context, input *DescribeDBLogFilesInput, fn func(*DescribeDBLogFilesOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *DescribeDBLogFilesInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeDBLogFilesRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*DescribeDBLogFilesOutput), !p.HasNextPage()) + } + return p.Err() } const opDescribeDBParameterGroups = "DescribeDBParameterGroups" @@ -3572,8 +4269,23 @@ func (c *RDS) DescribeDBParameterGroupsRequest(input *DescribeDBParameterGroupsI // Please also see https://docs.aws.amazon.com/goto/WebAPI/rds-2014-10-31/DescribeDBParameterGroups func (c *RDS) DescribeDBParameterGroups(input *DescribeDBParameterGroupsInput) (*DescribeDBParameterGroupsOutput, error) { req, out := c.DescribeDBParameterGroupsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeDBParameterGroupsWithContext is the same as DescribeDBParameterGroups with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeDBParameterGroups 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 *RDS) DescribeDBParameterGroupsWithContext(ctx aws.Context, input *DescribeDBParameterGroupsInput, opts ...request.Option) (*DescribeDBParameterGroupsOutput, error) { + req, out := c.DescribeDBParameterGroupsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // DescribeDBParameterGroupsPages iterates over the pages of a DescribeDBParameterGroups operation, @@ -3593,12 +4305,37 @@ func (c *RDS) DescribeDBParameterGroups(input *DescribeDBParameterGroupsInput) ( // return pageNum <= 3 // }) // -func (c *RDS) DescribeDBParameterGroupsPages(input *DescribeDBParameterGroupsInput, fn func(p *DescribeDBParameterGroupsOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.DescribeDBParameterGroupsRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*DescribeDBParameterGroupsOutput), lastPage) - }) +func (c *RDS) DescribeDBParameterGroupsPages(input *DescribeDBParameterGroupsInput, fn func(*DescribeDBParameterGroupsOutput, bool) bool) error { + return c.DescribeDBParameterGroupsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// DescribeDBParameterGroupsPagesWithContext same as DescribeDBParameterGroupsPages 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 *RDS) DescribeDBParameterGroupsPagesWithContext(ctx aws.Context, input *DescribeDBParameterGroupsInput, fn func(*DescribeDBParameterGroupsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *DescribeDBParameterGroupsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeDBParameterGroupsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*DescribeDBParameterGroupsOutput), !p.HasNextPage()) + } + return p.Err() } const opDescribeDBParameters = "DescribeDBParameters" @@ -3668,8 +4405,23 @@ func (c *RDS) DescribeDBParametersRequest(input *DescribeDBParametersInput) (req // Please also see https://docs.aws.amazon.com/goto/WebAPI/rds-2014-10-31/DescribeDBParameters func (c *RDS) DescribeDBParameters(input *DescribeDBParametersInput) (*DescribeDBParametersOutput, error) { req, out := c.DescribeDBParametersRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeDBParametersWithContext is the same as DescribeDBParameters with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeDBParameters 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 *RDS) DescribeDBParametersWithContext(ctx aws.Context, input *DescribeDBParametersInput, opts ...request.Option) (*DescribeDBParametersOutput, error) { + req, out := c.DescribeDBParametersRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // DescribeDBParametersPages iterates over the pages of a DescribeDBParameters operation, @@ -3689,12 +4441,37 @@ func (c *RDS) DescribeDBParameters(input *DescribeDBParametersInput) (*DescribeD // return pageNum <= 3 // }) // -func (c *RDS) DescribeDBParametersPages(input *DescribeDBParametersInput, fn func(p *DescribeDBParametersOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.DescribeDBParametersRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*DescribeDBParametersOutput), lastPage) - }) +func (c *RDS) DescribeDBParametersPages(input *DescribeDBParametersInput, fn func(*DescribeDBParametersOutput, bool) bool) error { + return c.DescribeDBParametersPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// DescribeDBParametersPagesWithContext same as DescribeDBParametersPages 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 *RDS) DescribeDBParametersPagesWithContext(ctx aws.Context, input *DescribeDBParametersInput, fn func(*DescribeDBParametersOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *DescribeDBParametersInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeDBParametersRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*DescribeDBParametersOutput), !p.HasNextPage()) + } + return p.Err() } const opDescribeDBSecurityGroups = "DescribeDBSecurityGroups" @@ -3766,8 +4543,23 @@ func (c *RDS) DescribeDBSecurityGroupsRequest(input *DescribeDBSecurityGroupsInp // Please also see https://docs.aws.amazon.com/goto/WebAPI/rds-2014-10-31/DescribeDBSecurityGroups func (c *RDS) DescribeDBSecurityGroups(input *DescribeDBSecurityGroupsInput) (*DescribeDBSecurityGroupsOutput, error) { req, out := c.DescribeDBSecurityGroupsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeDBSecurityGroupsWithContext is the same as DescribeDBSecurityGroups with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeDBSecurityGroups 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 *RDS) DescribeDBSecurityGroupsWithContext(ctx aws.Context, input *DescribeDBSecurityGroupsInput, opts ...request.Option) (*DescribeDBSecurityGroupsOutput, error) { + req, out := c.DescribeDBSecurityGroupsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // DescribeDBSecurityGroupsPages iterates over the pages of a DescribeDBSecurityGroups operation, @@ -3787,12 +4579,37 @@ func (c *RDS) DescribeDBSecurityGroups(input *DescribeDBSecurityGroupsInput) (*D // return pageNum <= 3 // }) // -func (c *RDS) DescribeDBSecurityGroupsPages(input *DescribeDBSecurityGroupsInput, fn func(p *DescribeDBSecurityGroupsOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.DescribeDBSecurityGroupsRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*DescribeDBSecurityGroupsOutput), lastPage) - }) +func (c *RDS) DescribeDBSecurityGroupsPages(input *DescribeDBSecurityGroupsInput, fn func(*DescribeDBSecurityGroupsOutput, bool) bool) error { + return c.DescribeDBSecurityGroupsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// DescribeDBSecurityGroupsPagesWithContext same as DescribeDBSecurityGroupsPages 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 *RDS) DescribeDBSecurityGroupsPagesWithContext(ctx aws.Context, input *DescribeDBSecurityGroupsInput, fn func(*DescribeDBSecurityGroupsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *DescribeDBSecurityGroupsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeDBSecurityGroupsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*DescribeDBSecurityGroupsOutput), !p.HasNextPage()) + } + return p.Err() } const opDescribeDBSnapshotAttributes = "DescribeDBSnapshotAttributes" @@ -3867,8 +4684,23 @@ func (c *RDS) DescribeDBSnapshotAttributesRequest(input *DescribeDBSnapshotAttri // Please also see https://docs.aws.amazon.com/goto/WebAPI/rds-2014-10-31/DescribeDBSnapshotAttributes func (c *RDS) DescribeDBSnapshotAttributes(input *DescribeDBSnapshotAttributesInput) (*DescribeDBSnapshotAttributesOutput, error) { req, out := c.DescribeDBSnapshotAttributesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeDBSnapshotAttributesWithContext is the same as DescribeDBSnapshotAttributes with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeDBSnapshotAttributes 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 *RDS) DescribeDBSnapshotAttributesWithContext(ctx aws.Context, input *DescribeDBSnapshotAttributesInput, opts ...request.Option) (*DescribeDBSnapshotAttributesOutput, error) { + req, out := c.DescribeDBSnapshotAttributesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeDBSnapshots = "DescribeDBSnapshots" @@ -3938,8 +4770,23 @@ func (c *RDS) DescribeDBSnapshotsRequest(input *DescribeDBSnapshotsInput) (req * // Please also see https://docs.aws.amazon.com/goto/WebAPI/rds-2014-10-31/DescribeDBSnapshots func (c *RDS) DescribeDBSnapshots(input *DescribeDBSnapshotsInput) (*DescribeDBSnapshotsOutput, error) { req, out := c.DescribeDBSnapshotsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeDBSnapshotsWithContext is the same as DescribeDBSnapshots with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeDBSnapshots 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 *RDS) DescribeDBSnapshotsWithContext(ctx aws.Context, input *DescribeDBSnapshotsInput, opts ...request.Option) (*DescribeDBSnapshotsOutput, error) { + req, out := c.DescribeDBSnapshotsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // DescribeDBSnapshotsPages iterates over the pages of a DescribeDBSnapshots operation, @@ -3959,12 +4806,37 @@ func (c *RDS) DescribeDBSnapshots(input *DescribeDBSnapshotsInput) (*DescribeDBS // return pageNum <= 3 // }) // -func (c *RDS) DescribeDBSnapshotsPages(input *DescribeDBSnapshotsInput, fn func(p *DescribeDBSnapshotsOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.DescribeDBSnapshotsRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*DescribeDBSnapshotsOutput), lastPage) - }) +func (c *RDS) DescribeDBSnapshotsPages(input *DescribeDBSnapshotsInput, fn func(*DescribeDBSnapshotsOutput, bool) bool) error { + return c.DescribeDBSnapshotsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// DescribeDBSnapshotsPagesWithContext same as DescribeDBSnapshotsPages 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 *RDS) DescribeDBSnapshotsPagesWithContext(ctx aws.Context, input *DescribeDBSnapshotsInput, fn func(*DescribeDBSnapshotsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *DescribeDBSnapshotsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeDBSnapshotsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*DescribeDBSnapshotsOutput), !p.HasNextPage()) + } + return p.Err() } const opDescribeDBSubnetGroups = "DescribeDBSubnetGroups" @@ -4037,8 +4909,23 @@ func (c *RDS) DescribeDBSubnetGroupsRequest(input *DescribeDBSubnetGroupsInput) // Please also see https://docs.aws.amazon.com/goto/WebAPI/rds-2014-10-31/DescribeDBSubnetGroups func (c *RDS) DescribeDBSubnetGroups(input *DescribeDBSubnetGroupsInput) (*DescribeDBSubnetGroupsOutput, error) { req, out := c.DescribeDBSubnetGroupsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeDBSubnetGroupsWithContext is the same as DescribeDBSubnetGroups with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeDBSubnetGroups 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 *RDS) DescribeDBSubnetGroupsWithContext(ctx aws.Context, input *DescribeDBSubnetGroupsInput, opts ...request.Option) (*DescribeDBSubnetGroupsOutput, error) { + req, out := c.DescribeDBSubnetGroupsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // DescribeDBSubnetGroupsPages iterates over the pages of a DescribeDBSubnetGroups operation, @@ -4058,12 +4945,37 @@ func (c *RDS) DescribeDBSubnetGroups(input *DescribeDBSubnetGroupsInput) (*Descr // return pageNum <= 3 // }) // -func (c *RDS) DescribeDBSubnetGroupsPages(input *DescribeDBSubnetGroupsInput, fn func(p *DescribeDBSubnetGroupsOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.DescribeDBSubnetGroupsRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*DescribeDBSubnetGroupsOutput), lastPage) - }) +func (c *RDS) DescribeDBSubnetGroupsPages(input *DescribeDBSubnetGroupsInput, fn func(*DescribeDBSubnetGroupsOutput, bool) bool) error { + return c.DescribeDBSubnetGroupsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// DescribeDBSubnetGroupsPagesWithContext same as DescribeDBSubnetGroupsPages 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 *RDS) DescribeDBSubnetGroupsPagesWithContext(ctx aws.Context, input *DescribeDBSubnetGroupsInput, fn func(*DescribeDBSubnetGroupsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *DescribeDBSubnetGroupsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeDBSubnetGroupsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*DescribeDBSubnetGroupsOutput), !p.HasNextPage()) + } + return p.Err() } const opDescribeEngineDefaultClusterParameters = "DescribeEngineDefaultClusterParameters" @@ -4126,8 +5038,23 @@ func (c *RDS) DescribeEngineDefaultClusterParametersRequest(input *DescribeEngin // Please also see https://docs.aws.amazon.com/goto/WebAPI/rds-2014-10-31/DescribeEngineDefaultClusterParameters func (c *RDS) DescribeEngineDefaultClusterParameters(input *DescribeEngineDefaultClusterParametersInput) (*DescribeEngineDefaultClusterParametersOutput, error) { req, out := c.DescribeEngineDefaultClusterParametersRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeEngineDefaultClusterParametersWithContext is the same as DescribeEngineDefaultClusterParameters with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeEngineDefaultClusterParameters 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 *RDS) DescribeEngineDefaultClusterParametersWithContext(ctx aws.Context, input *DescribeEngineDefaultClusterParametersInput, opts ...request.Option) (*DescribeEngineDefaultClusterParametersOutput, error) { + req, out := c.DescribeEngineDefaultClusterParametersRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeEngineDefaultParameters = "DescribeEngineDefaultParameters" @@ -4193,8 +5120,23 @@ func (c *RDS) DescribeEngineDefaultParametersRequest(input *DescribeEngineDefaul // Please also see https://docs.aws.amazon.com/goto/WebAPI/rds-2014-10-31/DescribeEngineDefaultParameters func (c *RDS) DescribeEngineDefaultParameters(input *DescribeEngineDefaultParametersInput) (*DescribeEngineDefaultParametersOutput, error) { req, out := c.DescribeEngineDefaultParametersRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeEngineDefaultParametersWithContext is the same as DescribeEngineDefaultParameters with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeEngineDefaultParameters 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 *RDS) DescribeEngineDefaultParametersWithContext(ctx aws.Context, input *DescribeEngineDefaultParametersInput, opts ...request.Option) (*DescribeEngineDefaultParametersOutput, error) { + req, out := c.DescribeEngineDefaultParametersRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // DescribeEngineDefaultParametersPages iterates over the pages of a DescribeEngineDefaultParameters operation, @@ -4214,12 +5156,37 @@ func (c *RDS) DescribeEngineDefaultParameters(input *DescribeEngineDefaultParame // return pageNum <= 3 // }) // -func (c *RDS) DescribeEngineDefaultParametersPages(input *DescribeEngineDefaultParametersInput, fn func(p *DescribeEngineDefaultParametersOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.DescribeEngineDefaultParametersRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*DescribeEngineDefaultParametersOutput), lastPage) - }) +func (c *RDS) DescribeEngineDefaultParametersPages(input *DescribeEngineDefaultParametersInput, fn func(*DescribeEngineDefaultParametersOutput, bool) bool) error { + return c.DescribeEngineDefaultParametersPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// DescribeEngineDefaultParametersPagesWithContext same as DescribeEngineDefaultParametersPages 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 *RDS) DescribeEngineDefaultParametersPagesWithContext(ctx aws.Context, input *DescribeEngineDefaultParametersInput, fn func(*DescribeEngineDefaultParametersOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *DescribeEngineDefaultParametersInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeEngineDefaultParametersRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*DescribeEngineDefaultParametersOutput), !p.HasNextPage()) + } + return p.Err() } const opDescribeEventCategories = "DescribeEventCategories" @@ -4281,8 +5248,23 @@ func (c *RDS) DescribeEventCategoriesRequest(input *DescribeEventCategoriesInput // Please also see https://docs.aws.amazon.com/goto/WebAPI/rds-2014-10-31/DescribeEventCategories func (c *RDS) DescribeEventCategories(input *DescribeEventCategoriesInput) (*DescribeEventCategoriesOutput, error) { req, out := c.DescribeEventCategoriesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeEventCategoriesWithContext is the same as DescribeEventCategories with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeEventCategories 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 *RDS) DescribeEventCategoriesWithContext(ctx aws.Context, input *DescribeEventCategoriesInput, opts ...request.Option) (*DescribeEventCategoriesOutput, error) { + req, out := c.DescribeEventCategoriesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeEventSubscriptions = "DescribeEventSubscriptions" @@ -4356,8 +5338,23 @@ func (c *RDS) DescribeEventSubscriptionsRequest(input *DescribeEventSubscription // Please also see https://docs.aws.amazon.com/goto/WebAPI/rds-2014-10-31/DescribeEventSubscriptions func (c *RDS) DescribeEventSubscriptions(input *DescribeEventSubscriptionsInput) (*DescribeEventSubscriptionsOutput, error) { req, out := c.DescribeEventSubscriptionsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeEventSubscriptionsWithContext is the same as DescribeEventSubscriptions with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeEventSubscriptions 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 *RDS) DescribeEventSubscriptionsWithContext(ctx aws.Context, input *DescribeEventSubscriptionsInput, opts ...request.Option) (*DescribeEventSubscriptionsOutput, error) { + req, out := c.DescribeEventSubscriptionsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // DescribeEventSubscriptionsPages iterates over the pages of a DescribeEventSubscriptions operation, @@ -4377,12 +5374,37 @@ func (c *RDS) DescribeEventSubscriptions(input *DescribeEventSubscriptionsInput) // return pageNum <= 3 // }) // -func (c *RDS) DescribeEventSubscriptionsPages(input *DescribeEventSubscriptionsInput, fn func(p *DescribeEventSubscriptionsOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.DescribeEventSubscriptionsRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*DescribeEventSubscriptionsOutput), lastPage) - }) +func (c *RDS) DescribeEventSubscriptionsPages(input *DescribeEventSubscriptionsInput, fn func(*DescribeEventSubscriptionsOutput, bool) bool) error { + return c.DescribeEventSubscriptionsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// DescribeEventSubscriptionsPagesWithContext same as DescribeEventSubscriptionsPages 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 *RDS) DescribeEventSubscriptionsPagesWithContext(ctx aws.Context, input *DescribeEventSubscriptionsInput, fn func(*DescribeEventSubscriptionsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *DescribeEventSubscriptionsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeEventSubscriptionsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*DescribeEventSubscriptionsOutput), !p.HasNextPage()) + } + return p.Err() } const opDescribeEvents = "DescribeEvents" @@ -4451,8 +5473,23 @@ func (c *RDS) DescribeEventsRequest(input *DescribeEventsInput) (req *request.Re // Please also see https://docs.aws.amazon.com/goto/WebAPI/rds-2014-10-31/DescribeEvents func (c *RDS) DescribeEvents(input *DescribeEventsInput) (*DescribeEventsOutput, error) { req, out := c.DescribeEventsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeEventsWithContext is the same as DescribeEvents with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeEvents 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 *RDS) DescribeEventsWithContext(ctx aws.Context, input *DescribeEventsInput, opts ...request.Option) (*DescribeEventsOutput, error) { + req, out := c.DescribeEventsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // DescribeEventsPages iterates over the pages of a DescribeEvents operation, @@ -4472,12 +5509,37 @@ func (c *RDS) DescribeEvents(input *DescribeEventsInput) (*DescribeEventsOutput, // return pageNum <= 3 // }) // -func (c *RDS) DescribeEventsPages(input *DescribeEventsInput, fn func(p *DescribeEventsOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.DescribeEventsRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*DescribeEventsOutput), lastPage) - }) +func (c *RDS) DescribeEventsPages(input *DescribeEventsInput, fn func(*DescribeEventsOutput, bool) bool) error { + return c.DescribeEventsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// DescribeEventsPagesWithContext same as DescribeEventsPages 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 *RDS) DescribeEventsPagesWithContext(ctx aws.Context, input *DescribeEventsInput, fn func(*DescribeEventsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *DescribeEventsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeEventsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*DescribeEventsOutput), !p.HasNextPage()) + } + return p.Err() } const opDescribeOptionGroupOptions = "DescribeOptionGroupOptions" @@ -4542,8 +5604,23 @@ func (c *RDS) DescribeOptionGroupOptionsRequest(input *DescribeOptionGroupOption // Please also see https://docs.aws.amazon.com/goto/WebAPI/rds-2014-10-31/DescribeOptionGroupOptions func (c *RDS) DescribeOptionGroupOptions(input *DescribeOptionGroupOptionsInput) (*DescribeOptionGroupOptionsOutput, error) { req, out := c.DescribeOptionGroupOptionsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeOptionGroupOptionsWithContext is the same as DescribeOptionGroupOptions with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeOptionGroupOptions 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 *RDS) DescribeOptionGroupOptionsWithContext(ctx aws.Context, input *DescribeOptionGroupOptionsInput, opts ...request.Option) (*DescribeOptionGroupOptionsOutput, error) { + req, out := c.DescribeOptionGroupOptionsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // DescribeOptionGroupOptionsPages iterates over the pages of a DescribeOptionGroupOptions operation, @@ -4563,12 +5640,37 @@ func (c *RDS) DescribeOptionGroupOptions(input *DescribeOptionGroupOptionsInput) // return pageNum <= 3 // }) // -func (c *RDS) DescribeOptionGroupOptionsPages(input *DescribeOptionGroupOptionsInput, fn func(p *DescribeOptionGroupOptionsOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.DescribeOptionGroupOptionsRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*DescribeOptionGroupOptionsOutput), lastPage) - }) +func (c *RDS) DescribeOptionGroupOptionsPages(input *DescribeOptionGroupOptionsInput, fn func(*DescribeOptionGroupOptionsOutput, bool) bool) error { + return c.DescribeOptionGroupOptionsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// DescribeOptionGroupOptionsPagesWithContext same as DescribeOptionGroupOptionsPages 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 *RDS) DescribeOptionGroupOptionsPagesWithContext(ctx aws.Context, input *DescribeOptionGroupOptionsInput, fn func(*DescribeOptionGroupOptionsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *DescribeOptionGroupOptionsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeOptionGroupOptionsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*DescribeOptionGroupOptionsOutput), !p.HasNextPage()) + } + return p.Err() } const opDescribeOptionGroups = "DescribeOptionGroups" @@ -4638,8 +5740,23 @@ func (c *RDS) DescribeOptionGroupsRequest(input *DescribeOptionGroupsInput) (req // Please also see https://docs.aws.amazon.com/goto/WebAPI/rds-2014-10-31/DescribeOptionGroups func (c *RDS) DescribeOptionGroups(input *DescribeOptionGroupsInput) (*DescribeOptionGroupsOutput, error) { req, out := c.DescribeOptionGroupsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeOptionGroupsWithContext is the same as DescribeOptionGroups with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeOptionGroups 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 *RDS) DescribeOptionGroupsWithContext(ctx aws.Context, input *DescribeOptionGroupsInput, opts ...request.Option) (*DescribeOptionGroupsOutput, error) { + req, out := c.DescribeOptionGroupsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // DescribeOptionGroupsPages iterates over the pages of a DescribeOptionGroups operation, @@ -4659,12 +5776,37 @@ func (c *RDS) DescribeOptionGroups(input *DescribeOptionGroupsInput) (*DescribeO // return pageNum <= 3 // }) // -func (c *RDS) DescribeOptionGroupsPages(input *DescribeOptionGroupsInput, fn func(p *DescribeOptionGroupsOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.DescribeOptionGroupsRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*DescribeOptionGroupsOutput), lastPage) - }) +func (c *RDS) DescribeOptionGroupsPages(input *DescribeOptionGroupsInput, fn func(*DescribeOptionGroupsOutput, bool) bool) error { + return c.DescribeOptionGroupsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// DescribeOptionGroupsPagesWithContext same as DescribeOptionGroupsPages 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 *RDS) DescribeOptionGroupsPagesWithContext(ctx aws.Context, input *DescribeOptionGroupsInput, fn func(*DescribeOptionGroupsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *DescribeOptionGroupsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeOptionGroupsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*DescribeOptionGroupsOutput), !p.HasNextPage()) + } + return p.Err() } const opDescribeOrderableDBInstanceOptions = "DescribeOrderableDBInstanceOptions" @@ -4729,8 +5871,23 @@ func (c *RDS) DescribeOrderableDBInstanceOptionsRequest(input *DescribeOrderable // Please also see https://docs.aws.amazon.com/goto/WebAPI/rds-2014-10-31/DescribeOrderableDBInstanceOptions func (c *RDS) DescribeOrderableDBInstanceOptions(input *DescribeOrderableDBInstanceOptionsInput) (*DescribeOrderableDBInstanceOptionsOutput, error) { req, out := c.DescribeOrderableDBInstanceOptionsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeOrderableDBInstanceOptionsWithContext is the same as DescribeOrderableDBInstanceOptions with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeOrderableDBInstanceOptions 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 *RDS) DescribeOrderableDBInstanceOptionsWithContext(ctx aws.Context, input *DescribeOrderableDBInstanceOptionsInput, opts ...request.Option) (*DescribeOrderableDBInstanceOptionsOutput, error) { + req, out := c.DescribeOrderableDBInstanceOptionsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // DescribeOrderableDBInstanceOptionsPages iterates over the pages of a DescribeOrderableDBInstanceOptions operation, @@ -4750,12 +5907,37 @@ func (c *RDS) DescribeOrderableDBInstanceOptions(input *DescribeOrderableDBInsta // return pageNum <= 3 // }) // -func (c *RDS) DescribeOrderableDBInstanceOptionsPages(input *DescribeOrderableDBInstanceOptionsInput, fn func(p *DescribeOrderableDBInstanceOptionsOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.DescribeOrderableDBInstanceOptionsRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*DescribeOrderableDBInstanceOptionsOutput), lastPage) - }) +func (c *RDS) DescribeOrderableDBInstanceOptionsPages(input *DescribeOrderableDBInstanceOptionsInput, fn func(*DescribeOrderableDBInstanceOptionsOutput, bool) bool) error { + return c.DescribeOrderableDBInstanceOptionsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// DescribeOrderableDBInstanceOptionsPagesWithContext same as DescribeOrderableDBInstanceOptionsPages 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 *RDS) DescribeOrderableDBInstanceOptionsPagesWithContext(ctx aws.Context, input *DescribeOrderableDBInstanceOptionsInput, fn func(*DescribeOrderableDBInstanceOptionsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *DescribeOrderableDBInstanceOptionsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeOrderableDBInstanceOptionsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*DescribeOrderableDBInstanceOptionsOutput), !p.HasNextPage()) + } + return p.Err() } const opDescribePendingMaintenanceActions = "DescribePendingMaintenanceActions" @@ -4820,8 +6002,23 @@ func (c *RDS) DescribePendingMaintenanceActionsRequest(input *DescribePendingMai // Please also see https://docs.aws.amazon.com/goto/WebAPI/rds-2014-10-31/DescribePendingMaintenanceActions func (c *RDS) DescribePendingMaintenanceActions(input *DescribePendingMaintenanceActionsInput) (*DescribePendingMaintenanceActionsOutput, error) { req, out := c.DescribePendingMaintenanceActionsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribePendingMaintenanceActionsWithContext is the same as DescribePendingMaintenanceActions with the addition of +// the ability to pass a context and additional request options. +// +// See DescribePendingMaintenanceActions 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 *RDS) DescribePendingMaintenanceActionsWithContext(ctx aws.Context, input *DescribePendingMaintenanceActionsInput, opts ...request.Option) (*DescribePendingMaintenanceActionsOutput, error) { + req, out := c.DescribePendingMaintenanceActionsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeReservedDBInstances = "DescribeReservedDBInstances" @@ -4892,8 +6089,23 @@ func (c *RDS) DescribeReservedDBInstancesRequest(input *DescribeReservedDBInstan // Please also see https://docs.aws.amazon.com/goto/WebAPI/rds-2014-10-31/DescribeReservedDBInstances func (c *RDS) DescribeReservedDBInstances(input *DescribeReservedDBInstancesInput) (*DescribeReservedDBInstancesOutput, error) { req, out := c.DescribeReservedDBInstancesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeReservedDBInstancesWithContext is the same as DescribeReservedDBInstances with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeReservedDBInstances 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 *RDS) DescribeReservedDBInstancesWithContext(ctx aws.Context, input *DescribeReservedDBInstancesInput, opts ...request.Option) (*DescribeReservedDBInstancesOutput, error) { + req, out := c.DescribeReservedDBInstancesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // DescribeReservedDBInstancesPages iterates over the pages of a DescribeReservedDBInstances operation, @@ -4913,12 +6125,37 @@ func (c *RDS) DescribeReservedDBInstances(input *DescribeReservedDBInstancesInpu // return pageNum <= 3 // }) // -func (c *RDS) DescribeReservedDBInstancesPages(input *DescribeReservedDBInstancesInput, fn func(p *DescribeReservedDBInstancesOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.DescribeReservedDBInstancesRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*DescribeReservedDBInstancesOutput), lastPage) - }) +func (c *RDS) DescribeReservedDBInstancesPages(input *DescribeReservedDBInstancesInput, fn func(*DescribeReservedDBInstancesOutput, bool) bool) error { + return c.DescribeReservedDBInstancesPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// DescribeReservedDBInstancesPagesWithContext same as DescribeReservedDBInstancesPages 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 *RDS) DescribeReservedDBInstancesPagesWithContext(ctx aws.Context, input *DescribeReservedDBInstancesInput, fn func(*DescribeReservedDBInstancesOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *DescribeReservedDBInstancesInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeReservedDBInstancesRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*DescribeReservedDBInstancesOutput), !p.HasNextPage()) + } + return p.Err() } const opDescribeReservedDBInstancesOfferings = "DescribeReservedDBInstancesOfferings" @@ -4988,8 +6225,23 @@ func (c *RDS) DescribeReservedDBInstancesOfferingsRequest(input *DescribeReserve // Please also see https://docs.aws.amazon.com/goto/WebAPI/rds-2014-10-31/DescribeReservedDBInstancesOfferings func (c *RDS) DescribeReservedDBInstancesOfferings(input *DescribeReservedDBInstancesOfferingsInput) (*DescribeReservedDBInstancesOfferingsOutput, error) { req, out := c.DescribeReservedDBInstancesOfferingsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeReservedDBInstancesOfferingsWithContext is the same as DescribeReservedDBInstancesOfferings with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeReservedDBInstancesOfferings 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 *RDS) DescribeReservedDBInstancesOfferingsWithContext(ctx aws.Context, input *DescribeReservedDBInstancesOfferingsInput, opts ...request.Option) (*DescribeReservedDBInstancesOfferingsOutput, error) { + req, out := c.DescribeReservedDBInstancesOfferingsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // DescribeReservedDBInstancesOfferingsPages iterates over the pages of a DescribeReservedDBInstancesOfferings operation, @@ -5009,12 +6261,37 @@ func (c *RDS) DescribeReservedDBInstancesOfferings(input *DescribeReservedDBInst // return pageNum <= 3 // }) // -func (c *RDS) DescribeReservedDBInstancesOfferingsPages(input *DescribeReservedDBInstancesOfferingsInput, fn func(p *DescribeReservedDBInstancesOfferingsOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.DescribeReservedDBInstancesOfferingsRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*DescribeReservedDBInstancesOfferingsOutput), lastPage) - }) +func (c *RDS) DescribeReservedDBInstancesOfferingsPages(input *DescribeReservedDBInstancesOfferingsInput, fn func(*DescribeReservedDBInstancesOfferingsOutput, bool) bool) error { + return c.DescribeReservedDBInstancesOfferingsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// DescribeReservedDBInstancesOfferingsPagesWithContext same as DescribeReservedDBInstancesOfferingsPages 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 *RDS) DescribeReservedDBInstancesOfferingsPagesWithContext(ctx aws.Context, input *DescribeReservedDBInstancesOfferingsInput, fn func(*DescribeReservedDBInstancesOfferingsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *DescribeReservedDBInstancesOfferingsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeReservedDBInstancesOfferingsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*DescribeReservedDBInstancesOfferingsOutput), !p.HasNextPage()) + } + return p.Err() } const opDescribeSourceRegions = "DescribeSourceRegions" @@ -5075,8 +6352,23 @@ func (c *RDS) DescribeSourceRegionsRequest(input *DescribeSourceRegionsInput) (r // Please also see https://docs.aws.amazon.com/goto/WebAPI/rds-2014-10-31/DescribeSourceRegions func (c *RDS) DescribeSourceRegions(input *DescribeSourceRegionsInput) (*DescribeSourceRegionsOutput, error) { req, out := c.DescribeSourceRegionsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeSourceRegionsWithContext is the same as DescribeSourceRegions with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeSourceRegions 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 *RDS) DescribeSourceRegionsWithContext(ctx aws.Context, input *DescribeSourceRegionsInput, opts ...request.Option) (*DescribeSourceRegionsOutput, error) { + req, out := c.DescribeSourceRegionsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDownloadDBLogFilePortion = "DownloadDBLogFilePortion" @@ -5149,8 +6441,23 @@ func (c *RDS) DownloadDBLogFilePortionRequest(input *DownloadDBLogFilePortionInp // Please also see https://docs.aws.amazon.com/goto/WebAPI/rds-2014-10-31/DownloadDBLogFilePortion func (c *RDS) DownloadDBLogFilePortion(input *DownloadDBLogFilePortionInput) (*DownloadDBLogFilePortionOutput, error) { req, out := c.DownloadDBLogFilePortionRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DownloadDBLogFilePortionWithContext is the same as DownloadDBLogFilePortion with the addition of +// the ability to pass a context and additional request options. +// +// See DownloadDBLogFilePortion 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 *RDS) DownloadDBLogFilePortionWithContext(ctx aws.Context, input *DownloadDBLogFilePortionInput, opts ...request.Option) (*DownloadDBLogFilePortionOutput, error) { + req, out := c.DownloadDBLogFilePortionRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // DownloadDBLogFilePortionPages iterates over the pages of a DownloadDBLogFilePortion operation, @@ -5170,12 +6477,37 @@ func (c *RDS) DownloadDBLogFilePortion(input *DownloadDBLogFilePortionInput) (*D // return pageNum <= 3 // }) // -func (c *RDS) DownloadDBLogFilePortionPages(input *DownloadDBLogFilePortionInput, fn func(p *DownloadDBLogFilePortionOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.DownloadDBLogFilePortionRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*DownloadDBLogFilePortionOutput), lastPage) - }) +func (c *RDS) DownloadDBLogFilePortionPages(input *DownloadDBLogFilePortionInput, fn func(*DownloadDBLogFilePortionOutput, bool) bool) error { + return c.DownloadDBLogFilePortionPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// DownloadDBLogFilePortionPagesWithContext same as DownloadDBLogFilePortionPages 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 *RDS) DownloadDBLogFilePortionPagesWithContext(ctx aws.Context, input *DownloadDBLogFilePortionInput, fn func(*DownloadDBLogFilePortionOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *DownloadDBLogFilePortionInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DownloadDBLogFilePortionRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*DownloadDBLogFilePortionOutput), !p.HasNextPage()) + } + return p.Err() } const opFailoverDBCluster = "FailoverDBCluster" @@ -5258,8 +6590,23 @@ func (c *RDS) FailoverDBClusterRequest(input *FailoverDBClusterInput) (req *requ // Please also see https://docs.aws.amazon.com/goto/WebAPI/rds-2014-10-31/FailoverDBCluster func (c *RDS) FailoverDBCluster(input *FailoverDBClusterInput) (*FailoverDBClusterOutput, error) { req, out := c.FailoverDBClusterRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// FailoverDBClusterWithContext is the same as FailoverDBCluster with the addition of +// the ability to pass a context and additional request options. +// +// See FailoverDBCluster 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 *RDS) FailoverDBClusterWithContext(ctx aws.Context, input *FailoverDBClusterInput, opts ...request.Option) (*FailoverDBClusterOutput, error) { + req, out := c.FailoverDBClusterRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opListTagsForResource = "ListTagsForResource" @@ -5332,8 +6679,23 @@ func (c *RDS) ListTagsForResourceRequest(input *ListTagsForResourceInput) (req * // Please also see https://docs.aws.amazon.com/goto/WebAPI/rds-2014-10-31/ListTagsForResource func (c *RDS) ListTagsForResource(input *ListTagsForResourceInput) (*ListTagsForResourceOutput, error) { req, out := c.ListTagsForResourceRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListTagsForResourceWithContext is the same as ListTagsForResource with the addition of +// the ability to pass a context and additional request options. +// +// See ListTagsForResource 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 *RDS) ListTagsForResourceWithContext(ctx aws.Context, input *ListTagsForResourceInput, opts ...request.Option) (*ListTagsForResourceOutput, error) { + req, out := c.ListTagsForResourceRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opModifyDBCluster = "ModifyDBCluster" @@ -5435,8 +6797,23 @@ func (c *RDS) ModifyDBClusterRequest(input *ModifyDBClusterInput) (req *request. // Please also see https://docs.aws.amazon.com/goto/WebAPI/rds-2014-10-31/ModifyDBCluster func (c *RDS) ModifyDBCluster(input *ModifyDBClusterInput) (*ModifyDBClusterOutput, error) { req, out := c.ModifyDBClusterRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ModifyDBClusterWithContext is the same as ModifyDBCluster with the addition of +// the ability to pass a context and additional request options. +// +// See ModifyDBCluster 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 *RDS) ModifyDBClusterWithContext(ctx aws.Context, input *ModifyDBClusterInput, opts ...request.Option) (*ModifyDBClusterOutput, error) { + req, out := c.ModifyDBClusterRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opModifyDBClusterParameterGroup = "ModifyDBClusterParameterGroup" @@ -5518,13 +6895,30 @@ func (c *RDS) ModifyDBClusterParameterGroupRequest(input *ModifyDBClusterParamet // DBParameterGroupName does not refer to an existing DB parameter group. // // * ErrCodeInvalidDBParameterGroupStateFault "InvalidDBParameterGroupState" -// The DB parameter group cannot be deleted because it is in use. +// The DB parameter group is in use or is in an invalid state. If you are attempting +// to delete the parameter group, you cannot delete it when the parameter group +// is in this state. // // Please also see https://docs.aws.amazon.com/goto/WebAPI/rds-2014-10-31/ModifyDBClusterParameterGroup func (c *RDS) ModifyDBClusterParameterGroup(input *ModifyDBClusterParameterGroupInput) (*DBClusterParameterGroupNameMessage, error) { req, out := c.ModifyDBClusterParameterGroupRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ModifyDBClusterParameterGroupWithContext is the same as ModifyDBClusterParameterGroup with the addition of +// the ability to pass a context and additional request options. +// +// See ModifyDBClusterParameterGroup 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 *RDS) ModifyDBClusterParameterGroupWithContext(ctx aws.Context, input *ModifyDBClusterParameterGroupInput, opts ...request.Option) (*DBClusterParameterGroupNameMessage, error) { + req, out := c.ModifyDBClusterParameterGroupRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opModifyDBClusterSnapshotAttribute = "ModifyDBClusterSnapshotAttribute" @@ -5581,14 +6975,15 @@ func (c *RDS) ModifyDBClusterSnapshotAttributeRequest(input *ModifyDBClusterSnap // snapshot. Use the value all to make the manual DB cluster snapshot public, // which means that it can be copied or restored by all AWS accounts. Do not // add the all value for any manual DB cluster snapshots that contain private -// information that you don't want available to all AWS accounts. +// information that you don't want available to all AWS accounts. If a manual +// DB cluster snapshot is encrypted, it can be shared, but only by specifying +// a list of authorized AWS account IDs for the ValuesToAdd parameter. You can't +// use all as a value for that parameter in this case. // // To view which AWS accounts have access to copy or restore a manual DB cluster // snapshot, or whether a manual DB cluster snapshot public or private, use // the DescribeDBClusterSnapshotAttributes API action. // -// If a manual DB cluster snapshot is encrypted, it cannot be shared. -// // 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. @@ -5610,8 +7005,23 @@ func (c *RDS) ModifyDBClusterSnapshotAttributeRequest(input *ModifyDBClusterSnap // Please also see https://docs.aws.amazon.com/goto/WebAPI/rds-2014-10-31/ModifyDBClusterSnapshotAttribute func (c *RDS) ModifyDBClusterSnapshotAttribute(input *ModifyDBClusterSnapshotAttributeInput) (*ModifyDBClusterSnapshotAttributeOutput, error) { req, out := c.ModifyDBClusterSnapshotAttributeRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ModifyDBClusterSnapshotAttributeWithContext is the same as ModifyDBClusterSnapshotAttribute with the addition of +// the ability to pass a context and additional request options. +// +// See ModifyDBClusterSnapshotAttribute 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 *RDS) ModifyDBClusterSnapshotAttributeWithContext(ctx aws.Context, input *ModifyDBClusterSnapshotAttributeInput, opts ...request.Option) (*ModifyDBClusterSnapshotAttributeOutput, error) { + req, out := c.ModifyDBClusterSnapshotAttributeRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opModifyDBInstance = "ModifyDBInstance" @@ -5729,8 +7139,23 @@ func (c *RDS) ModifyDBInstanceRequest(input *ModifyDBInstanceInput) (req *reques // Please also see https://docs.aws.amazon.com/goto/WebAPI/rds-2014-10-31/ModifyDBInstance func (c *RDS) ModifyDBInstance(input *ModifyDBInstanceInput) (*ModifyDBInstanceOutput, error) { req, out := c.ModifyDBInstanceRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ModifyDBInstanceWithContext is the same as ModifyDBInstance with the addition of +// the ability to pass a context and additional request options. +// +// See ModifyDBInstance 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 *RDS) ModifyDBInstanceWithContext(ctx aws.Context, input *ModifyDBInstanceInput, opts ...request.Option) (*ModifyDBInstanceOutput, error) { + req, out := c.ModifyDBInstanceRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opModifyDBParameterGroup = "ModifyDBParameterGroup" @@ -5809,13 +7234,30 @@ func (c *RDS) ModifyDBParameterGroupRequest(input *ModifyDBParameterGroupInput) // DBParameterGroupName does not refer to an existing DB parameter group. // // * ErrCodeInvalidDBParameterGroupStateFault "InvalidDBParameterGroupState" -// The DB parameter group cannot be deleted because it is in use. +// The DB parameter group is in use or is in an invalid state. If you are attempting +// to delete the parameter group, you cannot delete it when the parameter group +// is in this state. // // Please also see https://docs.aws.amazon.com/goto/WebAPI/rds-2014-10-31/ModifyDBParameterGroup func (c *RDS) ModifyDBParameterGroup(input *ModifyDBParameterGroupInput) (*DBParameterGroupNameMessage, error) { req, out := c.ModifyDBParameterGroupRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ModifyDBParameterGroupWithContext is the same as ModifyDBParameterGroup with the addition of +// the ability to pass a context and additional request options. +// +// See ModifyDBParameterGroup 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 *RDS) ModifyDBParameterGroupWithContext(ctx aws.Context, input *ModifyDBParameterGroupInput, opts ...request.Option) (*DBParameterGroupNameMessage, error) { + req, out := c.ModifyDBParameterGroupRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opModifyDBSnapshot = "ModifyDBSnapshot" @@ -5884,8 +7326,23 @@ func (c *RDS) ModifyDBSnapshotRequest(input *ModifyDBSnapshotInput) (req *reques // Please also see https://docs.aws.amazon.com/goto/WebAPI/rds-2014-10-31/ModifyDBSnapshot func (c *RDS) ModifyDBSnapshot(input *ModifyDBSnapshotInput) (*ModifyDBSnapshotOutput, error) { req, out := c.ModifyDBSnapshotRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ModifyDBSnapshotWithContext is the same as ModifyDBSnapshot with the addition of +// the ability to pass a context and additional request options. +// +// See ModifyDBSnapshot 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 *RDS) ModifyDBSnapshotWithContext(ctx aws.Context, input *ModifyDBSnapshotInput, opts ...request.Option) (*ModifyDBSnapshotOutput, error) { + req, out := c.ModifyDBSnapshotRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opModifyDBSnapshotAttribute = "ModifyDBSnapshotAttribute" @@ -5942,14 +7399,15 @@ func (c *RDS) ModifyDBSnapshotAttributeRequest(input *ModifyDBSnapshotAttributeI // Uses the value all to make the manual DB snapshot public, which means it // can be copied or restored by all AWS accounts. Do not add the all value for // any manual DB snapshots that contain private information that you don't want -// available to all AWS accounts. +// available to all AWS accounts. If the manual DB snapshot is encrypted, it +// can be shared, but only by specifying a list of authorized AWS account IDs +// for the ValuesToAdd parameter. You can't use all as a value for that parameter +// in this case. // // To view which AWS accounts have access to copy or restore a manual DB snapshot, // or whether a manual DB snapshot public or private, use the DescribeDBSnapshotAttributes // API action. // -// If the manual DB snapshot is encrypted, it cannot be shared. -// // 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. @@ -5971,8 +7429,23 @@ func (c *RDS) ModifyDBSnapshotAttributeRequest(input *ModifyDBSnapshotAttributeI // Please also see https://docs.aws.amazon.com/goto/WebAPI/rds-2014-10-31/ModifyDBSnapshotAttribute func (c *RDS) ModifyDBSnapshotAttribute(input *ModifyDBSnapshotAttributeInput) (*ModifyDBSnapshotAttributeOutput, error) { req, out := c.ModifyDBSnapshotAttributeRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ModifyDBSnapshotAttributeWithContext is the same as ModifyDBSnapshotAttribute with the addition of +// the ability to pass a context and additional request options. +// +// See ModifyDBSnapshotAttribute 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 *RDS) ModifyDBSnapshotAttributeWithContext(ctx aws.Context, input *ModifyDBSnapshotAttributeInput, opts ...request.Option) (*ModifyDBSnapshotAttributeOutput, error) { + req, out := c.ModifyDBSnapshotAttributeRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opModifyDBSubnetGroup = "ModifyDBSubnetGroup" @@ -6052,8 +7525,23 @@ func (c *RDS) ModifyDBSubnetGroupRequest(input *ModifyDBSubnetGroupInput) (req * // Please also see https://docs.aws.amazon.com/goto/WebAPI/rds-2014-10-31/ModifyDBSubnetGroup func (c *RDS) ModifyDBSubnetGroup(input *ModifyDBSubnetGroupInput) (*ModifyDBSubnetGroupOutput, error) { req, out := c.ModifyDBSubnetGroupRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ModifyDBSubnetGroupWithContext is the same as ModifyDBSubnetGroup with the addition of +// the ability to pass a context and additional request options. +// +// See ModifyDBSubnetGroup 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 *RDS) ModifyDBSubnetGroupWithContext(ctx aws.Context, input *ModifyDBSubnetGroupInput, opts ...request.Option) (*ModifyDBSubnetGroupOutput, error) { + req, out := c.ModifyDBSubnetGroupRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opModifyEventSubscription = "ModifyEventSubscription" @@ -6140,8 +7628,23 @@ func (c *RDS) ModifyEventSubscriptionRequest(input *ModifyEventSubscriptionInput // Please also see https://docs.aws.amazon.com/goto/WebAPI/rds-2014-10-31/ModifyEventSubscription func (c *RDS) ModifyEventSubscription(input *ModifyEventSubscriptionInput) (*ModifyEventSubscriptionOutput, error) { req, out := c.ModifyEventSubscriptionRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ModifyEventSubscriptionWithContext is the same as ModifyEventSubscription with the addition of +// the ability to pass a context and additional request options. +// +// See ModifyEventSubscription 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 *RDS) ModifyEventSubscriptionWithContext(ctx aws.Context, input *ModifyEventSubscriptionInput, opts ...request.Option) (*ModifyEventSubscriptionOutput, error) { + req, out := c.ModifyEventSubscriptionRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opModifyOptionGroup = "ModifyOptionGroup" @@ -6208,8 +7711,23 @@ func (c *RDS) ModifyOptionGroupRequest(input *ModifyOptionGroupInput) (req *requ // Please also see https://docs.aws.amazon.com/goto/WebAPI/rds-2014-10-31/ModifyOptionGroup func (c *RDS) ModifyOptionGroup(input *ModifyOptionGroupInput) (*ModifyOptionGroupOutput, error) { req, out := c.ModifyOptionGroupRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ModifyOptionGroupWithContext is the same as ModifyOptionGroup with the addition of +// the ability to pass a context and additional request options. +// +// See ModifyOptionGroup 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 *RDS) ModifyOptionGroupWithContext(ctx aws.Context, input *ModifyOptionGroupInput, opts ...request.Option) (*ModifyOptionGroupOutput, error) { + req, out := c.ModifyOptionGroupRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opPromoteReadReplica = "PromoteReadReplica" @@ -6281,8 +7799,23 @@ func (c *RDS) PromoteReadReplicaRequest(input *PromoteReadReplicaInput) (req *re // Please also see https://docs.aws.amazon.com/goto/WebAPI/rds-2014-10-31/PromoteReadReplica func (c *RDS) PromoteReadReplica(input *PromoteReadReplicaInput) (*PromoteReadReplicaOutput, error) { req, out := c.PromoteReadReplicaRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// PromoteReadReplicaWithContext is the same as PromoteReadReplica with the addition of +// the ability to pass a context and additional request options. +// +// See PromoteReadReplica 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 *RDS) PromoteReadReplicaWithContext(ctx aws.Context, input *PromoteReadReplicaInput, opts ...request.Option) (*PromoteReadReplicaOutput, error) { + req, out := c.PromoteReadReplicaRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opPromoteReadReplicaDBCluster = "PromoteReadReplicaDBCluster" @@ -6349,8 +7882,23 @@ func (c *RDS) PromoteReadReplicaDBClusterRequest(input *PromoteReadReplicaDBClus // Please also see https://docs.aws.amazon.com/goto/WebAPI/rds-2014-10-31/PromoteReadReplicaDBCluster func (c *RDS) PromoteReadReplicaDBCluster(input *PromoteReadReplicaDBClusterInput) (*PromoteReadReplicaDBClusterOutput, error) { req, out := c.PromoteReadReplicaDBClusterRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// PromoteReadReplicaDBClusterWithContext is the same as PromoteReadReplicaDBCluster with the addition of +// the ability to pass a context and additional request options. +// +// See PromoteReadReplicaDBCluster 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 *RDS) PromoteReadReplicaDBClusterWithContext(ctx aws.Context, input *PromoteReadReplicaDBClusterInput, opts ...request.Option) (*PromoteReadReplicaDBClusterOutput, error) { + req, out := c.PromoteReadReplicaDBClusterRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opPurchaseReservedDBInstancesOffering = "PurchaseReservedDBInstancesOffering" @@ -6420,8 +7968,23 @@ func (c *RDS) PurchaseReservedDBInstancesOfferingRequest(input *PurchaseReserved // Please also see https://docs.aws.amazon.com/goto/WebAPI/rds-2014-10-31/PurchaseReservedDBInstancesOffering func (c *RDS) PurchaseReservedDBInstancesOffering(input *PurchaseReservedDBInstancesOfferingInput) (*PurchaseReservedDBInstancesOfferingOutput, error) { req, out := c.PurchaseReservedDBInstancesOfferingRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// PurchaseReservedDBInstancesOfferingWithContext is the same as PurchaseReservedDBInstancesOffering with the addition of +// the ability to pass a context and additional request options. +// +// See PurchaseReservedDBInstancesOffering 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 *RDS) PurchaseReservedDBInstancesOfferingWithContext(ctx aws.Context, input *PurchaseReservedDBInstancesOfferingInput, opts ...request.Option) (*PurchaseReservedDBInstancesOfferingOutput, error) { + req, out := c.PurchaseReservedDBInstancesOfferingRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opRebootDBInstance = "RebootDBInstance" @@ -6504,8 +8067,23 @@ func (c *RDS) RebootDBInstanceRequest(input *RebootDBInstanceInput) (req *reques // Please also see https://docs.aws.amazon.com/goto/WebAPI/rds-2014-10-31/RebootDBInstance func (c *RDS) RebootDBInstance(input *RebootDBInstanceInput) (*RebootDBInstanceOutput, error) { req, out := c.RebootDBInstanceRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// RebootDBInstanceWithContext is the same as RebootDBInstance with the addition of +// the ability to pass a context and additional request options. +// +// See RebootDBInstance 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 *RDS) RebootDBInstanceWithContext(ctx aws.Context, input *RebootDBInstanceInput, opts ...request.Option) (*RebootDBInstanceOutput, error) { + req, out := c.RebootDBInstanceRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opRemoveRoleFromDBCluster = "RemoveRoleFromDBCluster" @@ -6580,8 +8158,23 @@ func (c *RDS) RemoveRoleFromDBClusterRequest(input *RemoveRoleFromDBClusterInput // Please also see https://docs.aws.amazon.com/goto/WebAPI/rds-2014-10-31/RemoveRoleFromDBCluster func (c *RDS) RemoveRoleFromDBCluster(input *RemoveRoleFromDBClusterInput) (*RemoveRoleFromDBClusterOutput, error) { req, out := c.RemoveRoleFromDBClusterRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// RemoveRoleFromDBClusterWithContext is the same as RemoveRoleFromDBCluster with the addition of +// the ability to pass a context and additional request options. +// +// See RemoveRoleFromDBCluster 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 *RDS) RemoveRoleFromDBClusterWithContext(ctx aws.Context, input *RemoveRoleFromDBClusterInput, opts ...request.Option) (*RemoveRoleFromDBClusterOutput, error) { + req, out := c.RemoveRoleFromDBClusterRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opRemoveSourceIdentifierFromSubscription = "RemoveSourceIdentifierFromSubscription" @@ -6648,8 +8241,23 @@ func (c *RDS) RemoveSourceIdentifierFromSubscriptionRequest(input *RemoveSourceI // Please also see https://docs.aws.amazon.com/goto/WebAPI/rds-2014-10-31/RemoveSourceIdentifierFromSubscription func (c *RDS) RemoveSourceIdentifierFromSubscription(input *RemoveSourceIdentifierFromSubscriptionInput) (*RemoveSourceIdentifierFromSubscriptionOutput, error) { req, out := c.RemoveSourceIdentifierFromSubscriptionRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// RemoveSourceIdentifierFromSubscriptionWithContext is the same as RemoveSourceIdentifierFromSubscription with the addition of +// the ability to pass a context and additional request options. +// +// See RemoveSourceIdentifierFromSubscription 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 *RDS) RemoveSourceIdentifierFromSubscriptionWithContext(ctx aws.Context, input *RemoveSourceIdentifierFromSubscriptionInput, opts ...request.Option) (*RemoveSourceIdentifierFromSubscriptionOutput, error) { + req, out := c.RemoveSourceIdentifierFromSubscriptionRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opRemoveTagsFromResource = "RemoveTagsFromResource" @@ -6724,8 +8332,23 @@ func (c *RDS) RemoveTagsFromResourceRequest(input *RemoveTagsFromResourceInput) // Please also see https://docs.aws.amazon.com/goto/WebAPI/rds-2014-10-31/RemoveTagsFromResource func (c *RDS) RemoveTagsFromResource(input *RemoveTagsFromResourceInput) (*RemoveTagsFromResourceOutput, error) { req, out := c.RemoveTagsFromResourceRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// RemoveTagsFromResourceWithContext is the same as RemoveTagsFromResource with the addition of +// the ability to pass a context and additional request options. +// +// See RemoveTagsFromResource 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 *RDS) RemoveTagsFromResourceWithContext(ctx aws.Context, input *RemoveTagsFromResourceInput, opts ...request.Option) (*RemoveTagsFromResourceOutput, error) { + req, out := c.RemoveTagsFromResourceRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opResetDBClusterParameterGroup = "ResetDBClusterParameterGroup" @@ -6796,7 +8419,9 @@ func (c *RDS) ResetDBClusterParameterGroupRequest(input *ResetDBClusterParameter // // Returned Error Codes: // * ErrCodeInvalidDBParameterGroupStateFault "InvalidDBParameterGroupState" -// The DB parameter group cannot be deleted because it is in use. +// The DB parameter group is in use or is in an invalid state. If you are attempting +// to delete the parameter group, you cannot delete it when the parameter group +// is in this state. // // * ErrCodeDBParameterGroupNotFoundFault "DBParameterGroupNotFound" // DBParameterGroupName does not refer to an existing DB parameter group. @@ -6804,8 +8429,23 @@ func (c *RDS) ResetDBClusterParameterGroupRequest(input *ResetDBClusterParameter // Please also see https://docs.aws.amazon.com/goto/WebAPI/rds-2014-10-31/ResetDBClusterParameterGroup func (c *RDS) ResetDBClusterParameterGroup(input *ResetDBClusterParameterGroupInput) (*DBClusterParameterGroupNameMessage, error) { req, out := c.ResetDBClusterParameterGroupRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ResetDBClusterParameterGroupWithContext is the same as ResetDBClusterParameterGroup with the addition of +// the ability to pass a context and additional request options. +// +// See ResetDBClusterParameterGroup 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 *RDS) ResetDBClusterParameterGroupWithContext(ctx aws.Context, input *ResetDBClusterParameterGroupInput, opts ...request.Option) (*DBClusterParameterGroupNameMessage, error) { + req, out := c.ResetDBClusterParameterGroupRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opResetDBParameterGroup = "ResetDBParameterGroup" @@ -6854,7 +8494,7 @@ func (c *RDS) ResetDBParameterGroupRequest(input *ResetDBParameterGroupInput) (r // ResetDBParameterGroup API operation for Amazon Relational Database Service. // // Modifies the parameters of a DB parameter group to the engine/system default -// value. To reset specific parameters submit a list of the following: ParameterName +// value. To reset specific parameters, provide a list of the following: ParameterName // and ApplyMethod. To reset the entire DB parameter group, specify the DBParameterGroup // name and ResetAllParameters parameters. When resetting the entire group, // dynamic parameters are updated immediately and static parameters are set @@ -6870,7 +8510,9 @@ func (c *RDS) ResetDBParameterGroupRequest(input *ResetDBParameterGroupInput) (r // // Returned Error Codes: // * ErrCodeInvalidDBParameterGroupStateFault "InvalidDBParameterGroupState" -// The DB parameter group cannot be deleted because it is in use. +// The DB parameter group is in use or is in an invalid state. If you are attempting +// to delete the parameter group, you cannot delete it when the parameter group +// is in this state. // // * ErrCodeDBParameterGroupNotFoundFault "DBParameterGroupNotFound" // DBParameterGroupName does not refer to an existing DB parameter group. @@ -6878,8 +8520,23 @@ func (c *RDS) ResetDBParameterGroupRequest(input *ResetDBParameterGroupInput) (r // Please also see https://docs.aws.amazon.com/goto/WebAPI/rds-2014-10-31/ResetDBParameterGroup func (c *RDS) ResetDBParameterGroup(input *ResetDBParameterGroupInput) (*DBParameterGroupNameMessage, error) { req, out := c.ResetDBParameterGroupRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ResetDBParameterGroupWithContext is the same as ResetDBParameterGroup with the addition of +// the ability to pass a context and additional request options. +// +// See ResetDBParameterGroup 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 *RDS) ResetDBParameterGroupWithContext(ctx aws.Context, input *ResetDBParameterGroupInput, opts ...request.Option) (*DBParameterGroupNameMessage, error) { + req, out := c.ResetDBParameterGroupRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opRestoreDBClusterFromS3 = "RestoreDBClusterFromS3" @@ -6930,7 +8587,7 @@ func (c *RDS) RestoreDBClusterFromS3Request(input *RestoreDBClusterFromS3Input) // Creates an Amazon Aurora DB cluster from data stored in an Amazon S3 bucket. // Amazon RDS must be authorized to access the Amazon S3 bucket and the data // must be created using the Percona XtraBackup utility as described in Migrating -// Data from MySQL by Using an Amazon S3 Bucket (AmazonRDS/latest/UserGuide/Aurora.Migrate.MySQL.html#Aurora.Migrate.MySQL.S3). +// Data from MySQL by Using an Amazon S3 Bucket (http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/Aurora.Migrate.MySQL.html#Aurora.Migrate.MySQL.S3). // // 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 @@ -6991,8 +8648,23 @@ func (c *RDS) RestoreDBClusterFromS3Request(input *RestoreDBClusterFromS3Input) // Please also see https://docs.aws.amazon.com/goto/WebAPI/rds-2014-10-31/RestoreDBClusterFromS3 func (c *RDS) RestoreDBClusterFromS3(input *RestoreDBClusterFromS3Input) (*RestoreDBClusterFromS3Output, error) { req, out := c.RestoreDBClusterFromS3Request(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// RestoreDBClusterFromS3WithContext is the same as RestoreDBClusterFromS3 with the addition of +// the ability to pass a context and additional request options. +// +// See RestoreDBClusterFromS3 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 *RDS) RestoreDBClusterFromS3WithContext(ctx aws.Context, input *RestoreDBClusterFromS3Input, opts ...request.Option) (*RestoreDBClusterFromS3Output, error) { + req, out := c.RestoreDBClusterFromS3Request(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opRestoreDBClusterFromSnapshot = "RestoreDBClusterFromSnapshot" @@ -7117,8 +8789,23 @@ func (c *RDS) RestoreDBClusterFromSnapshotRequest(input *RestoreDBClusterFromSna // Please also see https://docs.aws.amazon.com/goto/WebAPI/rds-2014-10-31/RestoreDBClusterFromSnapshot func (c *RDS) RestoreDBClusterFromSnapshot(input *RestoreDBClusterFromSnapshotInput) (*RestoreDBClusterFromSnapshotOutput, error) { req, out := c.RestoreDBClusterFromSnapshotRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// RestoreDBClusterFromSnapshotWithContext is the same as RestoreDBClusterFromSnapshot with the addition of +// the ability to pass a context and additional request options. +// +// See RestoreDBClusterFromSnapshot 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 *RDS) RestoreDBClusterFromSnapshotWithContext(ctx aws.Context, input *RestoreDBClusterFromSnapshotInput, opts ...request.Option) (*RestoreDBClusterFromSnapshotOutput, error) { + req, out := c.RestoreDBClusterFromSnapshotRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opRestoreDBClusterToPointInTime = "RestoreDBClusterToPointInTime" @@ -7186,23 +8873,19 @@ func (c *RDS) RestoreDBClusterToPointInTimeRequest(input *RestoreDBClusterToPoin // * ErrCodeDBClusterAlreadyExistsFault "DBClusterAlreadyExistsFault" // User already has a DB cluster with the given identifier. // +// * ErrCodeDBClusterNotFoundFault "DBClusterNotFoundFault" +// DBClusterIdentifier does not refer to an existing DB cluster. +// // * ErrCodeDBClusterQuotaExceededFault "DBClusterQuotaExceededFault" // User attempted to create a new DB cluster and the user has already reached // the maximum allowed DB cluster quota. // -// * ErrCodeStorageQuotaExceededFault "StorageQuotaExceeded" -// Request would result in user exceeding the allowed amount of storage available -// across all DB instances. +// * ErrCodeDBClusterSnapshotNotFoundFault "DBClusterSnapshotNotFoundFault" +// DBClusterSnapshotIdentifier does not refer to an existing DB cluster snapshot. // // * ErrCodeDBSubnetGroupNotFoundFault "DBSubnetGroupNotFoundFault" // DBSubnetGroupName does not refer to an existing DB subnet group. // -// * ErrCodeDBClusterNotFoundFault "DBClusterNotFoundFault" -// DBClusterIdentifier does not refer to an existing DB cluster. -// -// * ErrCodeDBClusterSnapshotNotFoundFault "DBClusterSnapshotNotFoundFault" -// DBClusterSnapshotIdentifier does not refer to an existing DB cluster snapshot. -// // * ErrCodeInsufficientDBClusterCapacityFault "InsufficientDBClusterCapacityFault" // The DB cluster does not have enough capacity for the current operation. // @@ -7211,41 +8894,56 @@ func (c *RDS) RestoreDBClusterToPointInTimeRequest(input *RestoreDBClusterToPoin // able to resolve this error by updating your subnet group to use different // Availability Zones that have more storage available. // -// * ErrCodeInvalidDBSnapshotStateFault "InvalidDBSnapshotState" -// The state of the DB snapshot does not allow deletion. -// // * ErrCodeInvalidDBClusterSnapshotStateFault "InvalidDBClusterSnapshotStateFault" // The supplied value is not a valid DB cluster snapshot state. // -// * ErrCodeStorageQuotaExceededFault "StorageQuotaExceeded" -// Request would result in user exceeding the allowed amount of storage available -// across all DB instances. +// * ErrCodeInvalidDBClusterStateFault "InvalidDBClusterStateFault" +// The DB cluster is not in a valid state. // -// * ErrCodeInvalidVPCNetworkStateFault "InvalidVPCNetworkStateFault" -// DB subnet group does not cover all Availability Zones after it is created -// because users' change. +// * ErrCodeInvalidDBSnapshotStateFault "InvalidDBSnapshotState" +// The state of the DB snapshot does not allow deletion. // // * ErrCodeInvalidRestoreFault "InvalidRestoreFault" // Cannot restore from vpc backup to non-vpc DB instance. // -// * ErrCodeDBSubnetGroupNotFoundFault "DBSubnetGroupNotFoundFault" -// DBSubnetGroupName does not refer to an existing DB subnet group. -// // * ErrCodeInvalidSubnet "InvalidSubnet" // The requested subnet is invalid, or multiple subnets were requested that // are not all in a common VPC. // -// * ErrCodeOptionGroupNotFoundFault "OptionGroupNotFoundFault" -// The specified option group could not be found. +// * ErrCodeInvalidVPCNetworkStateFault "InvalidVPCNetworkStateFault" +// DB subnet group does not cover all Availability Zones after it is created +// because users' change. // // * ErrCodeKMSKeyNotAccessibleFault "KMSKeyNotAccessibleFault" // Error accessing KMS key. // +// * ErrCodeOptionGroupNotFoundFault "OptionGroupNotFoundFault" +// The specified option group could not be found. +// +// * ErrCodeStorageQuotaExceededFault "StorageQuotaExceeded" +// Request would result in user exceeding the allowed amount of storage available +// across all DB instances. +// // Please also see https://docs.aws.amazon.com/goto/WebAPI/rds-2014-10-31/RestoreDBClusterToPointInTime func (c *RDS) RestoreDBClusterToPointInTime(input *RestoreDBClusterToPointInTimeInput) (*RestoreDBClusterToPointInTimeOutput, error) { req, out := c.RestoreDBClusterToPointInTimeRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// RestoreDBClusterToPointInTimeWithContext is the same as RestoreDBClusterToPointInTime with the addition of +// the ability to pass a context and additional request options. +// +// See RestoreDBClusterToPointInTime 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 *RDS) RestoreDBClusterToPointInTimeWithContext(ctx aws.Context, input *RestoreDBClusterToPointInTimeInput, opts ...request.Option) (*RestoreDBClusterToPointInTimeOutput, error) { + req, out := c.RestoreDBClusterToPointInTimeRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opRestoreDBInstanceFromDBSnapshot = "RestoreDBInstanceFromDBSnapshot" @@ -7387,8 +9085,23 @@ func (c *RDS) RestoreDBInstanceFromDBSnapshotRequest(input *RestoreDBInstanceFro // Please also see https://docs.aws.amazon.com/goto/WebAPI/rds-2014-10-31/RestoreDBInstanceFromDBSnapshot func (c *RDS) RestoreDBInstanceFromDBSnapshot(input *RestoreDBInstanceFromDBSnapshotInput) (*RestoreDBInstanceFromDBSnapshotOutput, error) { req, out := c.RestoreDBInstanceFromDBSnapshotRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// RestoreDBInstanceFromDBSnapshotWithContext is the same as RestoreDBInstanceFromDBSnapshot with the addition of +// the ability to pass a context and additional request options. +// +// See RestoreDBInstanceFromDBSnapshot 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 *RDS) RestoreDBInstanceFromDBSnapshotWithContext(ctx aws.Context, input *RestoreDBInstanceFromDBSnapshotInput, opts ...request.Option) (*RestoreDBInstanceFromDBSnapshotOutput, error) { + req, out := c.RestoreDBInstanceFromDBSnapshotRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opRestoreDBInstanceToPointInTime = "RestoreDBInstanceToPointInTime" @@ -7527,8 +9240,23 @@ func (c *RDS) RestoreDBInstanceToPointInTimeRequest(input *RestoreDBInstanceToPo // Please also see https://docs.aws.amazon.com/goto/WebAPI/rds-2014-10-31/RestoreDBInstanceToPointInTime func (c *RDS) RestoreDBInstanceToPointInTime(input *RestoreDBInstanceToPointInTimeInput) (*RestoreDBInstanceToPointInTimeOutput, error) { req, out := c.RestoreDBInstanceToPointInTimeRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// RestoreDBInstanceToPointInTimeWithContext is the same as RestoreDBInstanceToPointInTime with the addition of +// the ability to pass a context and additional request options. +// +// See RestoreDBInstanceToPointInTime 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 *RDS) RestoreDBInstanceToPointInTimeWithContext(ctx aws.Context, input *RestoreDBInstanceToPointInTimeInput, opts ...request.Option) (*RestoreDBInstanceToPointInTimeOutput, error) { + req, out := c.RestoreDBInstanceToPointInTimeRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opRevokeDBSecurityGroupIngress = "RevokeDBSecurityGroupIngress" @@ -7605,8 +9333,23 @@ func (c *RDS) RevokeDBSecurityGroupIngressRequest(input *RevokeDBSecurityGroupIn // Please also see https://docs.aws.amazon.com/goto/WebAPI/rds-2014-10-31/RevokeDBSecurityGroupIngress func (c *RDS) RevokeDBSecurityGroupIngress(input *RevokeDBSecurityGroupIngressInput) (*RevokeDBSecurityGroupIngressOutput, error) { req, out := c.RevokeDBSecurityGroupIngressRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// RevokeDBSecurityGroupIngressWithContext is the same as RevokeDBSecurityGroupIngress with the addition of +// the ability to pass a context and additional request options. +// +// See RevokeDBSecurityGroupIngress 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 *RDS) RevokeDBSecurityGroupIngressWithContext(ctx aws.Context, input *RevokeDBSecurityGroupIngressInput, opts ...request.Option) (*RevokeDBSecurityGroupIngressOutput, error) { + req, out := c.RevokeDBSecurityGroupIngressRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // Describes a quota for an AWS account, for example, the number of DB instances @@ -8377,6 +10120,8 @@ func (s *CopyDBClusterParameterGroupOutput) SetDBClusterParameterGroup(v *DBClus type CopyDBClusterSnapshotInput struct { _ struct{} `type:"structure"` + // True to copy all tags from the source DB cluster snapshot to the target DB + // cluster snapshot; otherwise false. The default is false. CopyTags *bool `type:"boolean"` // DestinationRegion is used for presigning the request to a given region. @@ -8439,6 +10184,9 @@ type CopyDBClusterSnapshotInput struct { // The identifier of the DB cluster snapshot to copy. This parameter is not // case-sensitive. // + // You cannot copy an encrypted, shared DB cluster snapshot from one AWS region + // to another. + // // Constraints: // // * Must contain from 1 to 63 alphanumeric characters or hyphens. @@ -8447,6 +10195,15 @@ type CopyDBClusterSnapshotInput struct { // // * Cannot end with a hyphen or contain two consecutive hyphens. // + // * Must specify a valid system snapshot in the "available" state. + // + // * If the source snapshot is in the same region as the copy, specify a + // valid DB snapshot identifier. + // + // * If the source snapshot is in a different region than the copy, specify + // a valid DB cluster snapshot ARN. For more information, go to Copying + // a DB Snapshot or DB Cluster Snapshot (http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_CopySnapshot.html). + // // Example: my-cluster-snapshot1 // // SourceDBClusterSnapshotIdentifier is a required field @@ -8773,7 +10530,7 @@ type CopyDBSnapshotInput struct { // snapshot to be copied. This identifier must be in the Amazon Resource // Name (ARN) format for the source region. For example, if you are copying // an encrypted DB snapshot from the us-west-2 region, then your SourceDBSnapshotIdentifier - // would look like Example: arn:aws:rds:us-west-2:123456789012:snapshot:mysql-instance1-snapshot-20161115. + // looks like the following example: arn:aws:rds:us-west-2:123456789012:snapshot:mysql-instance1-snapshot-20161115. // // To learn how to generate a Signature Version 4 signed request, see Authenticating // Requests: Using Query Parameters (AWS Signature Version 4) (http://docs.aws.amazon.com/AmazonS3/latest/API/sigv4-query-string-auth.html) @@ -8796,7 +10553,7 @@ type CopyDBSnapshotInput struct { // // * If the source snapshot is in a different region than the copy, specify // a valid DB snapshot ARN. For more information, go to Copying a DB Snapshot - // (http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_CopySnapshot.html). + // or DB Cluster Snapshot (http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_CopySnapshot.html). // // Example: rds:mydb-2012-04-02-00-01 // @@ -9124,6 +10881,12 @@ type CreateDBClusterInput struct { // DestinationRegion is used for presigning the request to a given region. DestinationRegion *string `type:"string"` + // A Boolean value that is true to enable mapping of AWS Identity and Access + // Management (IAM) accounts to database accounts, and otherwise false. + // + // Default: false + EnableIAMDatabaseAuthentication *bool `type:"boolean"` + // The name of the database engine to be used for this DB cluster. // // Valid Values: aurora @@ -9341,6 +11104,12 @@ func (s *CreateDBClusterInput) SetDestinationRegion(v string) *CreateDBClusterIn return s } +// SetEnableIAMDatabaseAuthentication sets the EnableIAMDatabaseAuthentication field's value. +func (s *CreateDBClusterInput) SetEnableIAMDatabaseAuthentication(v bool) *CreateDBClusterInput { + s.EnableIAMDatabaseAuthentication = &v + return s +} + // SetEngine sets the Engine field's value. func (s *CreateDBClusterInput) SetEngine(v string) *CreateDBClusterInput { s.Engine = &v @@ -9711,6 +11480,12 @@ type CreateDBInstanceInput struct { // // Type: Integer // + // Amazon Aurora + // + // Not applicable. Aurora cluster volumes automatically grow as the amount of + // data in your database increases, though you are only charged for the space + // that you use in an Aurora cluster volume. + // // MySQL // // Constraints: Must be an integer from 5 to 6144. @@ -9908,6 +11683,18 @@ type CreateDBInstanceInput struct { // Directory Service. DomainIAMRoleName *string `type:"string"` + // True to enable mapping of AWS Identity and Access Management (IAM) accounts + // to database accounts; otherwise false. + // + // You can enable IAM database authentication for the following database engines + // + // * For MySQL 5.6, minor version 5.6.34 or higher + // + // * For MySQL 5.7, minor version 5.7.16 or higher + // + // Default: false + EnableIAMDatabaseAuthentication *bool `type:"boolean"` + // The name of the database engine to be used for this instance. // // Valid Values: mysql | mariadb | oracle-se1 | oracle-se2 | oracle-se | oracle-ee @@ -10006,109 +11793,13 @@ type CreateDBInstanceInput struct { // ap-southeast-2, eu-west-1, sa-east-1, us-east-1, us-gov-west-1, us-west-1, // us-west-2): 5.1.73a | 5.1.73b // - // Oracle Database Enterprise Edition (oracle-ee) - // - // * Version 12.1 (available in all AWS regions except ap-south-1, ap-northeast-2): - // 12.1.0.1.v1 | 12.1.0.1.v2 - // - // * Version 12.1 (only available in AWS regions ap-northeast-1, ap-southeast-1, - // ap-southeast-2, eu-central-1, eu-west-1, sa-east-1, us-east-1, us-west-1, - // us-west-2): 12.1.0.1.v3 | 12.1.0.1.v4 | 12.1.0.1.v5 - // - // * Version 12.1 (available in all AWS regions): 12.1.0.2.v1 - // - // * Version 12.1 (available in all AWS regions except us-gov-west-1): 12.1.0.2.v2 - // | 12.1.0.2.v3 | 12.1.0.2.v4 - // - // * Version 11.2 (only available in AWS regions ap-northeast-1, ap-southeast-1, - // ap-southeast-2, eu-west-1, sa-east-1, us-east-1, us-gov-west-1, us-west-1, - // us-west-2): 11.2.0.2.v3 | 11.2.0.2.v4 | 11.2.0.2.v5 | 11.2.0.2.v6 | 11.2.0.2.v7 - // - // * Version 11.2 (available in all AWS regions except ap-south-1, ap-northeast-2): - // 11.2.0.3.v1 | 11.2.0.3.v2 | 11.2.0.3.v3 - // - // * Version 11.2 (only available in AWS regions ap-northeast-1, ap-southeast-1, - // ap-southeast-2, eu-central-1, eu-west-1, sa-east-1, us-east-1, us-west-1, - // us-west-2): 11.2.0.3.v4 - // - // * Version 11.2 (available in all AWS regions): 11.2.0.4.v1 | 11.2.0.4.v3 - // | 11.2.0.4.v4 - // - // * Version 11.2 (available in all AWS regions except us-gov-west-1): 11.2.0.4.v5 - // | 11.2.0.4.v6 | 11.2.0.4.v7 | 11.2.0.4.v8 - // - // Oracle Database Standard Edition (oracle-se) - // - // * Version 12.1 (available in all AWS regions except ap-south-1, ap-northeast-2): - // 12.1.0.1.v1 | 12.1.0.1.v2 - // - // * Version 12.1 (only available in AWS regions ap-northeast-1, ap-southeast-1, - // ap-southeast-2, eu-central-1, eu-west-1, sa-east-1, us-east-1, us-west-1, - // us-west-2): 12.1.0.1.v3 | 12.1.0.1.v4 | 12.1.0.1.v5 - // - // * Version 11.2 (only available in AWS regions ap-northeast-1, ap-southeast-1, - // ap-southeast-2, eu-west-1, sa-east-1, us-east-1, us-gov-west-1, us-west-1, - // us-west-2): 11.2.0.2.v3 | 11.2.0.2.v4 | 11.2.0.2.v5 | 11.2.0.2.v6 | 11.2.0.2.v7 - // - // * Version 11.2 (available in all AWS regions except ap-south-1, ap-northeast-2): - // 11.2.0.3.v1 | 11.2.0.3.v2 | 11.2.0.3.v3 - // - // * Version 11.2 (only available in AWS regions ap-northeast-1, ap-southeast-1, - // ap-southeast-2, eu-central-1, eu-west-1, sa-east-1, us-east-1, us-west-1, - // us-west-2): 11.2.0.3.v4 - // - // * Version 11.2 (available in all AWS regions): 11.2.0.4.v1 | 11.2.0.4.v3 - // | 11.2.0.4.v4 - // - // * Version 11.2 (available in all AWS regions except us-gov-west-1): 11.2.0.4.v5 - // | 11.2.0.4.v6 | 11.2.0.4.v7 | 11.2.0.4.v8 - // - // Oracle Database Standard Edition One (oracle-se1) - // - // * Version 12.1 (available in all AWS regions except ap-south-1, ap-northeast-2): - // 12.1.0.1.v1 | 12.1.0.1.v2 - // - // * Version 12.1 (only available in AWS regions ap-northeast-1, ap-southeast-1, - // ap-southeast-2, eu-central-1, eu-west-1, sa-east-1, us-east-1, us-west-1, - // us-west-2): 12.1.0.1.v3 | 12.1.0.1.v4 | 12.1.0.1.v5 - // - // * Version 11.2 (only available in AWS regions ap-northeast-1, ap-southeast-1, - // ap-southeast-2, eu-west-1, sa-east-1, us-east-1, us-gov-west-1, us-west-1, - // us-west-2): 11.2.0.2.v3 | 11.2.0.2.v4 | 11.2.0.2.v5 | 11.2.0.2.v6 | 11.2.0.2.v7 - // - // * Version 11.2 (available in all AWS regions except ap-south-1, ap-northeast-2): - // 11.2.0.3.v1 | 11.2.0.3.v2 | 11.2.0.3.v3 - // - // * Version 11.2 (only available in AWS regions ap-northeast-1, ap-southeast-1, - // ap-southeast-2, eu-central-1, eu-west-1, sa-east-1, us-east-1, us-west-1, - // us-west-2): 11.2.0.3.v4 - // - // * Version 11.2 (available in all AWS regions): 11.2.0.4.v1 | 11.2.0.4.v3 - // | 11.2.0.4.v4 - // - // * Version 11.2 (available in all AWS regions except us-gov-west-1): 11.2.0.4.v5 - // | 11.2.0.4.v6 | 11.2.0.4.v7 | 11.2.0.4.v8 - // - // Oracle Database Standard Edition Two (oracle-se2) - // - // * Version 12.1 (available in all AWS regions except us-gov-west-1): 12.1.0.2.v2 - // | 12.1.0.2.v3 | 12.1.0.2.v4 - // - // PostgreSQL - // - // * Version 9.6: 9.6.1 - // - // * Version 9.5:9.5.4 | 9.5.2 - // - // * Version 9.4: 9.4.9 | 9.4.7 | 9.4.5 | 9.4.4 | 9.4.1 - // - // * Version 9.3: 9.3.14 | 9.3.12 | 9.3.10 | 9.3.9 | 9.3.6 | 9.3.5 | 9.3.3 - // | 9.3.2 | 9.3.1 - // // Oracle 12c // - // 12.1.0.2.v6 (supported for EE in all AWS regions, and SE2 in all AWS regions - // except us-gov-west-1) + // * 12.1.0.2.v7 (supported for EE in all AWS regions, and SE2 in all AWS + // regions except us-gov-west-1) + // + // * 12.1.0.2.v6 (supported for EE in all AWS regions, and SE2 in all AWS + // regions except us-gov-west-1) // // * 12.1.0.2.v5 (supported for EE in all AWS regions, and SE2 in all AWS // regions except us-gov-west-1) @@ -10125,26 +11816,10 @@ type CreateDBInstanceInput struct { // * 12.1.0.2.v1 (supported for EE in all AWS regions, and SE2 in all AWS // regions except us-gov-west-1) // - // * 12.1.0.1.v6 (supported for EE, SE1, and SE, in all AWS regions except - // ap-south-1, ap-northeast-2) - // - // * 12.1.0.1.v5 (supported for EE, SE1, and SE, in all AWS regions except - // ap-south-1, ap-northeast-2) - // - // * 12.1.0.1.v4 (supported for EE, SE1, and SE, in all AWS regions except - // ap-south-1, ap-northeast-2) - // - // * 12.1.0.1.v3 (supported for EE, SE1, and SE, in all AWS regions except - // ap-south-1, ap-northeast-2) - // - // * 12.1.0.1.v2 (supported for EE, SE1, and SE, in all AWS regions except - // ap-south-1, ap-northeast-2) - // - // * 12.1.0.1.v1 (supported for EE, SE1, and SE, in all AWS regions except - // ap-south-1, ap-northeast-2) - // // Oracle 11g // + // * 11.2.0.4.v11 (supported for EE, SE1, and SE, in all AWS regions) + // // * 11.2.0.4.v10 (supported for EE, SE1, and SE, in all AWS regions) // // * 11.2.0.4.v9 (supported for EE, SE1, and SE, in all AWS regions) @@ -10165,43 +11840,14 @@ type CreateDBInstanceInput struct { // // PostgreSQL // - // * Version 9.5 (available in these AWS regions: ap-northeast-1, ap-northeast-2, - // ap-south-1, ap-southeast-1, ap-southeast-2, eu-central-1, eu-west-1, sa-east-1, - // us-east-1, us-west-1, us-west-2): * 9.5.4 + // * Version 9.6: 9.6.1 // - // * Version 9.5 (available in these AWS regions: ap-northeast-1, ap-northeast-2, - // ap-south-1, ap-southeast-1, ap-southeast-2, eu-central-1, eu-west-1, sa-east-1, - // us-east-1, us-east-2, us-west-1, us-west-2): * 9.5.2 + // * Version 9.5:9.5.4 | 9.5.2 // - // * Version 9.4 (available in these AWS regions: ap-northeast-1, ap-northeast-2, - // ap-south-1, ap-southeast-1, ap-southeast-2, eu-central-1, eu-west-1, sa-east-1, - // us-east-1, us-west-1, us-west-2): * 9.4.9 + // * Version 9.4: 9.4.9 | 9.4.7 | 9.4.5 | 9.4.4 | 9.4.1 // - // * Version 9.4 (available in these AWS regions: ap-northeast-1, ap-northeast-2, - // ap-south-1, ap-southeast-1, ap-southeast-2, eu-central-1, eu-west-1, sa-east-1, - // us-east-1, us-east-2, us-west-1, us-west-2): * 9.4.7 - // - // * Version 9.4 (available in all AWS regions): * 9.4.5 - // - // * Version 9.4 (available in these AWS regions: ap-northeast-1, ap-northeast-2, - // ap-southeast-1, ap-southeast-2, eu-central-1, eu-west-1, sa-east-1, us-east-1, - // us-gov-west-1, us-west-1, us-west-2): * 9.4.4 - // - // * Version 9.4 (available in these AWS regions: ap-northeast-1, ap-northeast-2, - // ap-southeast-1, ap-southeast-2, eu-central-1, eu-west-1, sa-east-1, us-east-1, - // us-east-2, us-gov-west-1, us-west-1, us-west-2): * 9.4.1 - // - // * Version 9.3 (available in these AWS regions: ap-northeast-1, ap-southeast-1, - // ap-southeast-2, eu-central-1, eu-west-1, sa-east-1, us-east-1, us-gov-west-1, - // us-west-1, us-west-2): * 9.3.10 | 9.3.3 | 9.3.5 | 9.3.6 | 9.3.9 - // - // * Version 9.3 (available in these AWS regions: ap-northeast-1, ap-southeast-1, - // ap-southeast-2, eu-west-1, sa-east-1, us-east-1, us-gov-west-1, us-west-1, - // us-west-2): * 9.3.1 | 9.3.2 - // - // * Version 9.3 (available in these AWS regions: ap-northeast-1, ap-southeast-1, - // ap-southeast-2, eu-central-1, eu-west-1, sa-east-1, us-east-1, us-west-1, - // us-west-2): * 9.3.12 | 9.3.14 + // * Version 9.3: 9.3.14 | 9.3.12 | 9.3.10 | 9.3.9 | 9.3.6 | 9.3.5 | 9.3.3 + // | 9.3.2 | 9.3.1 EngineVersion *string `type:"string"` // The amount of Provisioned IOPS (input/output operations per second) to be @@ -10234,13 +11880,20 @@ type CreateDBInstanceInput struct { // The password for the master database user. Can be any printable ASCII character // except "/", """, or "@". // - // Type: String + // Amazon Aurora // - // MySQL + // Not applicable. You specify the password for the master database user when + // you create your DB cluster. + // + // MariaDB // // Constraints: Must contain from 8 to 41 characters. // - // MariaDB + // Microsoft SQL Server + // + // Constraints: Must contain from 8 to 128 characters. + // + // MySQL // // Constraints: Must contain from 8 to 41 characters. // @@ -10248,20 +11901,35 @@ type CreateDBInstanceInput struct { // // Constraints: Must contain from 8 to 30 characters. // - // SQL Server - // - // Constraints: Must contain from 8 to 128 characters. - // // PostgreSQL // // Constraints: Must contain from 8 to 128 characters. + MasterUserPassword *string `type:"string"` + + // The name for the master database user. // // Amazon Aurora // - // Constraints: Must contain from 8 to 41 characters. - MasterUserPassword *string `type:"string"` - - // The name of master user for the client DB instance. + // Not applicable. You specify the name for the master database user when you + // create your DB cluster. + // + // MariaDB + // + // Constraints: + // + // * Must be 1 to 16 alphanumeric characters. + // + // * Cannot be a reserved word for the chosen database engine. + // + // Microsoft SQL Server + // + // Constraints: + // + // * Must be 1 to 128 alphanumeric characters. + // + // * First character must be a letter. + // + // * Cannot be a reserved word for the chosen database engine. // // MySQL // @@ -10273,16 +11941,6 @@ type CreateDBInstanceInput struct { // // * Cannot be a reserved word for the chosen database engine. // - // MariaDB - // - // Constraints: - // - // * Must be 1 to 16 alphanumeric characters. - // - // * Cannot be a reserved word for the chosen database engine. - // - // Type: String - // // Oracle // // Constraints: @@ -10293,16 +11951,6 @@ type CreateDBInstanceInput struct { // // * Cannot be a reserved word for the chosen database engine. // - // SQL Server - // - // Constraints: - // - // * Must be 1 to 128 alphanumeric characters. - // - // * First character must be a letter. - // - // * Cannot be a reserved word for the chosen database engine. - // // PostgreSQL // // Constraints: @@ -10326,8 +11974,8 @@ type CreateDBInstanceInput struct { // The ARN for the IAM role that permits RDS to send enhanced monitoring metrics // to CloudWatch Logs. For example, arn:aws:iam:123456789012:role/emaccess. - // For information on creating a monitoring role, go to To create an IAM role - // for Amazon RDS Enhanced Monitoring (http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_Monitoring.html#USER_Monitoring.OS.IAMRole). + // For information on creating a monitoring role, go to Setting Up and Enabling + // Enhanced Monitoring (http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_Monitoring.OS.html#USER_Monitoring.OS.Enabling). // // If MonitoringInterval is set to a value other than 0, then you must supply // a MonitoringRoleArn value. @@ -10399,8 +12047,7 @@ type CreateDBInstanceInput struct { // // Default: A 30-minute window selected at random from an 8-hour block of time // per region. To see the time blocks available, see Adjusting the Preferred - // Maintenance Window (http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/AdjustingTheMaintenanceWindow.html) - // in the Amazon RDS User Guide. + // DB Instance Maintenance Window (http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_UpgradeDBInstance.Maintenance.html#AdjustingTheMaintenanceWindow). // // Constraints: // @@ -10609,6 +12256,12 @@ func (s *CreateDBInstanceInput) SetDomainIAMRoleName(v string) *CreateDBInstance return s } +// SetEnableIAMDatabaseAuthentication sets the EnableIAMDatabaseAuthentication field's value. +func (s *CreateDBInstanceInput) SetEnableIAMDatabaseAuthentication(v bool) *CreateDBInstanceInput { + s.EnableIAMDatabaseAuthentication = &v + return s +} + // SetEngine sets the Engine field's value. func (s *CreateDBInstanceInput) SetEngine(v string) *CreateDBInstanceInput { s.Engine = &v @@ -10849,6 +12502,20 @@ type CreateDBInstanceReadReplicaInput struct { // DestinationRegion is used for presigning the request to a given region. DestinationRegion *string `type:"string"` + // True to enable mapping of AWS Identity and Access Management (IAM) accounts + // to database accounts; otherwise false. + // + // You can enable IAM database authentication for the following database engines + // + // * For MySQL 5.6, minor version 5.6.34 or higher + // + // * For MySQL 5.7, minor version 5.7.16 or higher + // + // * Aurora 5.6 or higher. + // + // Default: false + EnableIAMDatabaseAuthentication *bool `type:"boolean"` + // The amount of Provisioned IOPS (input/output operations per second) to be // initially allocated for the DB instance. Iops *int64 `type:"integer"` @@ -11069,6 +12736,12 @@ func (s *CreateDBInstanceReadReplicaInput) SetDestinationRegion(v string) *Creat return s } +// SetEnableIAMDatabaseAuthentication sets the EnableIAMDatabaseAuthentication field's value. +func (s *CreateDBInstanceReadReplicaInput) SetEnableIAMDatabaseAuthentication(v bool) *CreateDBInstanceReadReplicaInput { + s.EnableIAMDatabaseAuthentication = &v + return s +} + // SetIops sets the Iops field's value. func (s *CreateDBInstanceReadReplicaInput) SetIops(v int64) *CreateDBInstanceReadReplicaInput { s.Iops = &v @@ -11928,7 +13601,10 @@ func (s *CreateOptionGroupOutput) SetOptionGroup(v *OptionGroup) *CreateOptionGr type DBCluster struct { _ struct{} `type:"structure"` - // Specifies the allocated storage size in gigabytes (GB). + // For all database engines except Amazon Aurora, AllocatedStorage specifies + // the allocated storage size in gigabytes (GB). For Aurora, AllocatedStorage + // always returns 1, because Aurora DB cluster storage size is not fixed, but + // instead automatically adjusts as needed. AllocatedStorage *int64 `type:"integer"` // Provides a list of the AWS Identity and Access Management (IAM) roles that @@ -11998,6 +13674,10 @@ type DBCluster struct { // Specifies the ID that Amazon Route 53 assigns when you create a hosted zone. HostedZoneId *string `type:"string"` + // True if mapping of AWS Identity and Access Management (IAM) accounts to database + // accounts is enabled; otherwise false. + IAMDatabaseAuthenticationEnabled *bool `type:"boolean"` + // If StorageEncrypted is true, the KMS key identifier for the encrypted DB // cluster. KmsKeyId *string `type:"string"` @@ -12040,7 +13720,7 @@ type DBCluster struct { // If a failover occurs, and the Aurora Replica that you are connected to is // promoted to be the primary instance, your connection will be dropped. To // continue sending your read workload to other Aurora Replicas in the cluster, - // you can then recoonect to the reader endpoint. + // you can then reconnect to the reader endpoint. ReaderEndpoint *string `type:"string"` // Contains the identifier of the source DB cluster if this DB cluster is a @@ -12181,6 +13861,12 @@ func (s *DBCluster) SetHostedZoneId(v string) *DBCluster { return s } +// SetIAMDatabaseAuthenticationEnabled sets the IAMDatabaseAuthenticationEnabled field's value. +func (s *DBCluster) SetIAMDatabaseAuthenticationEnabled(v bool) *DBCluster { + s.IAMDatabaseAuthenticationEnabled = &v + return s +} + // SetKmsKeyId sets the KmsKeyId field's value. func (s *DBCluster) SetKmsKeyId(v string) *DBCluster { s.KmsKeyId = &v @@ -12533,6 +14219,10 @@ type DBClusterSnapshot struct { // Provides the version of the database engine for this DB cluster snapshot. EngineVersion *string `type:"string"` + // True if mapping of AWS Identity and Access Management (IAM) accounts to database + // accounts is enabled; otherwise false. + IAMDatabaseAuthenticationEnabled *bool `type:"boolean"` + // If StorageEncrypted is true, the KMS key identifier for the encrypted DB // cluster snapshot. KmsKeyId *string `type:"string"` @@ -12557,6 +14247,11 @@ type DBClusterSnapshot struct { // Provides the type of the DB cluster snapshot. SnapshotType *string `type:"string"` + // If the DB cluster snapshot was copied from a source DB cluster snapshot, + // the Amazon Resource Name (ARN) for the source DB cluster snapshot; otherwise, + // a null value. + SourceDBClusterSnapshotArn *string `type:"string"` + // Specifies the status of this DB cluster snapshot. Status *string `type:"string"` @@ -12625,6 +14320,12 @@ func (s *DBClusterSnapshot) SetEngineVersion(v string) *DBClusterSnapshot { return s } +// SetIAMDatabaseAuthenticationEnabled sets the IAMDatabaseAuthenticationEnabled field's value. +func (s *DBClusterSnapshot) SetIAMDatabaseAuthenticationEnabled(v bool) *DBClusterSnapshot { + s.IAMDatabaseAuthenticationEnabled = &v + return s +} + // SetKmsKeyId sets the KmsKeyId field's value. func (s *DBClusterSnapshot) SetKmsKeyId(v string) *DBClusterSnapshot { s.KmsKeyId = &v @@ -12667,6 +14368,12 @@ func (s *DBClusterSnapshot) SetSnapshotType(v string) *DBClusterSnapshot { return s } +// SetSourceDBClusterSnapshotArn sets the SourceDBClusterSnapshotArn field's value. +func (s *DBClusterSnapshot) SetSourceDBClusterSnapshotArn(v string) *DBClusterSnapshot { + s.SourceDBClusterSnapshotArn = &v + return s +} + // SetStatus sets the Status field's value. func (s *DBClusterSnapshot) SetStatus(v string) *DBClusterSnapshot { s.Status = &v @@ -12932,7 +14639,7 @@ type DBInstance struct { // when returning values from CreateDBInstanceReadReplica since Read Replicas // are only supported for these engines. // - // MySQL, MariaDB, SQL Server, PostgreSQL, Amazon Aurora + // MySQL, MariaDB, SQL Server, PostgreSQL // // Contains the name of the initial database of this instance that was provided // at create time, if one was specified when the DB instance was created. This @@ -12982,6 +14689,19 @@ type DBInstance struct { // receives the Enhanced Monitoring metrics data for the DB instance. EnhancedMonitoringResourceArn *string `type:"string"` + // True if mapping of AWS Identity and Access Management (IAM) accounts to database + // accounts is enabled; otherwise false. + // + // IAM database authentication can be enabled for the following database engines + // + // * For MySQL 5.6, minor version 5.6.34 or higher + // + // * For MySQL 5.7, minor version 5.7.16 or higher + // + // * Aurora 5.6 or higher. To enable IAM database authentication for Aurora, + // see DBCluster Type. + IAMDatabaseAuthenticationEnabled *bool `type:"boolean"` + // Provides the date and time the DB instance was created. InstanceCreateTime *time.Time `type:"timestamp" timestampFormat:"iso8601"` @@ -13239,6 +14959,12 @@ func (s *DBInstance) SetEnhancedMonitoringResourceArn(v string) *DBInstance { return s } +// SetIAMDatabaseAuthenticationEnabled sets the IAMDatabaseAuthenticationEnabled field's value. +func (s *DBInstance) SetIAMDatabaseAuthenticationEnabled(v bool) *DBInstance { + s.IAMDatabaseAuthenticationEnabled = &v + return s +} + // SetInstanceCreateTime sets the InstanceCreateTime field's value. func (s *DBInstance) SetInstanceCreateTime(v time.Time) *DBInstance { s.InstanceCreateTime = &v @@ -13744,6 +15470,10 @@ type DBSnapshot struct { // Specifies the version of the database engine. EngineVersion *string `type:"string"` + // True if mapping of AWS Identity and Access Management (IAM) accounts to database + // accounts is enabled; otherwise false. + IAMDatabaseAuthenticationEnabled *bool `type:"boolean"` + // Specifies the time when the snapshot was taken, in Universal Coordinated // Time (UTC). InstanceCreateTime *time.Time `type:"timestamp" timestampFormat:"iso8601"` @@ -13861,6 +15591,12 @@ func (s *DBSnapshot) SetEngineVersion(v string) *DBSnapshot { return s } +// SetIAMDatabaseAuthenticationEnabled sets the IAMDatabaseAuthenticationEnabled field's value. +func (s *DBSnapshot) SetIAMDatabaseAuthenticationEnabled(v bool) *DBSnapshot { + s.IAMDatabaseAuthenticationEnabled = &v + return s +} + // SetInstanceCreateTime sets the InstanceCreateTime field's value. func (s *DBSnapshot) SetInstanceCreateTime(v time.Time) *DBSnapshot { s.InstanceCreateTime = &v @@ -19528,6 +21264,12 @@ type ModifyDBClusterInput struct { // The name of the DB cluster parameter group to use for the DB cluster. DBClusterParameterGroupName *string `type:"string"` + // A Boolean value that is true to enable mapping of AWS Identity and Access + // Management (IAM) accounts to database accounts, and otherwise false. + // + // Default: false + EnableIAMDatabaseAuthentication *bool `type:"boolean"` + // The new password for the master database user. This password can contain // any printable ASCII character except "/", """, or "@". // @@ -19601,7 +21343,7 @@ type ModifyDBClusterInput struct { // Constraints: Minimum 30-minute window. PreferredMaintenanceWindow *string `type:"string"` - // A lst of VPC security groups that the DB cluster will belong to. + // A list of VPC security groups that the DB cluster will belong to. VpcSecurityGroupIds []*string `locationNameList:"VpcSecurityGroupId" type:"list"` } @@ -19652,6 +21394,12 @@ func (s *ModifyDBClusterInput) SetDBClusterParameterGroupName(v string) *ModifyD return s } +// SetEnableIAMDatabaseAuthentication sets the EnableIAMDatabaseAuthentication field's value. +func (s *ModifyDBClusterInput) SetEnableIAMDatabaseAuthentication(v bool) *ModifyDBClusterInput { + s.EnableIAMDatabaseAuthentication = &v + return s +} + // SetMasterUserPassword sets the MasterUserPassword field's value. func (s *ModifyDBClusterInput) SetMasterUserPassword(v string) *ModifyDBClusterInput { s.MasterUserPassword = &v @@ -20173,6 +21921,18 @@ type ModifyDBInstanceInput struct { // The name of the IAM role to use when making API calls to the Directory Service. DomainIAMRoleName *string `type:"string"` + // True to enable mapping of AWS Identity and Access Management (IAM) accounts + // to database accounts; otherwise false. + // + // You can enable IAM database authentication for the following database engines + // + // * For MySQL 5.6, minor version 5.6.34 or higher + // + // * For MySQL 5.7, minor version 5.7.16 or higher + // + // Default: false + EnableIAMDatabaseAuthentication *bool `type:"boolean"` + // The version number of the database engine to upgrade to. Changing this parameter // results in an outage and the change is applied during the next maintenance // window unless the ApplyImmediately parameter is set to true for this request. @@ -20499,6 +22259,12 @@ func (s *ModifyDBInstanceInput) SetDomainIAMRoleName(v string) *ModifyDBInstance return s } +// SetEnableIAMDatabaseAuthentication sets the EnableIAMDatabaseAuthentication field's value. +func (s *ModifyDBInstanceInput) SetEnableIAMDatabaseAuthentication(v bool) *ModifyDBInstanceInput { + s.EnableIAMDatabaseAuthentication = &v + return s +} + // SetEngineVersion sets the EngineVersion field's value. func (s *ModifyDBInstanceInput) SetEngineVersion(v string) *ModifyDBInstanceInput { s.EngineVersion = &v @@ -21913,6 +23679,9 @@ type OrderableDBInstanceOption struct { // from 1 to 60 seconds. SupportsEnhancedMonitoring *bool `type:"boolean"` + // Indicates whether this orderable DB instance supports IAM database authentication. + SupportsIAMDatabaseAuthentication *bool `type:"boolean"` + // Indicates whether this orderable DB instance supports provisioned IOPS. SupportsIops *bool `type:"boolean"` @@ -21987,6 +23756,12 @@ func (s *OrderableDBInstanceOption) SetSupportsEnhancedMonitoring(v bool) *Order return s } +// SetSupportsIAMDatabaseAuthentication sets the SupportsIAMDatabaseAuthentication field's value. +func (s *OrderableDBInstanceOption) SetSupportsIAMDatabaseAuthentication(v bool) *OrderableDBInstanceOption { + s.SupportsIAMDatabaseAuthentication = &v + return s +} + // SetSupportsIops sets the SupportsIops field's value. func (s *OrderableDBInstanceOption) SetSupportsIops(v bool) *OrderableDBInstanceOption { s.SupportsIops = &v @@ -22777,7 +24552,7 @@ func (s *RecurringCharge) SetRecurringChargeFrequency(v string) *RecurringCharge type RemoveRoleFromDBClusterInput struct { _ struct{} `type:"structure"` - // The name of the DB cluster to disassociate the IAM role rom. + // The name of the DB cluster to disassociate the IAM role from. // // DBClusterIdentifier is a required field DBClusterIdentifier *string `type:"string" required:"true"` @@ -23329,10 +25104,10 @@ type ResetDBParameterGroupInput struct { // DBParameterGroupName is a required field DBParameterGroupName *string `type:"string" required:"true"` - // An array of parameter names, values, and the apply method for the parameter - // update. At least one parameter name, value, and apply method must be supplied; - // subsequent arguments are optional. A maximum of 20 parameters can be modified - // in a single request. + // To reset the entire DB parameter group, specify the DBParameterGroup name + // and ResetAllParameters parameters. To reset specific parameters, provide + // a list of the following: ParameterName and ApplyMethod. A maximum of 20 parameters + // can be modified in a single request. // // MySQL // @@ -23499,6 +25274,12 @@ type RestoreDBClusterFromS3Input struct { // The database name for the restored DB cluster. DatabaseName *string `type:"string"` + // A Boolean value that is true to enable mapping of AWS Identity and Access + // Management (IAM) accounts to database accounts, and otherwise false. + // + // Default: false + EnableIAMDatabaseAuthentication *bool `type:"boolean"` + // The name of the database engine to be used for the restored DB cluster. // // Valid Values: aurora @@ -23726,6 +25507,12 @@ func (s *RestoreDBClusterFromS3Input) SetDatabaseName(v string) *RestoreDBCluste return s } +// SetEnableIAMDatabaseAuthentication sets the EnableIAMDatabaseAuthentication field's value. +func (s *RestoreDBClusterFromS3Input) SetEnableIAMDatabaseAuthentication(v bool) *RestoreDBClusterFromS3Input { + s.EnableIAMDatabaseAuthentication = &v + return s +} + // SetEngine sets the Engine field's value. func (s *RestoreDBClusterFromS3Input) SetEngine(v string) *RestoreDBClusterFromS3Input { s.Engine = &v @@ -23901,6 +25688,12 @@ type RestoreDBClusterFromSnapshotInput struct { // The database name for the restored DB cluster. DatabaseName *string `type:"string"` + // A Boolean value that is true to enable mapping of AWS Identity and Access + // Management (IAM) accounts to database accounts, and otherwise false. + // + // Default: false + EnableIAMDatabaseAuthentication *bool `type:"boolean"` + // The database engine to use for the new DB cluster. // // Default: The same as source @@ -24015,6 +25808,12 @@ func (s *RestoreDBClusterFromSnapshotInput) SetDatabaseName(v string) *RestoreDB return s } +// SetEnableIAMDatabaseAuthentication sets the EnableIAMDatabaseAuthentication field's value. +func (s *RestoreDBClusterFromSnapshotInput) SetEnableIAMDatabaseAuthentication(v bool) *RestoreDBClusterFromSnapshotInput { + s.EnableIAMDatabaseAuthentication = &v + return s +} + // SetEngine sets the Engine field's value. func (s *RestoreDBClusterFromSnapshotInput) SetEngine(v string) *RestoreDBClusterFromSnapshotInput { s.Engine = &v @@ -24126,6 +25925,12 @@ type RestoreDBClusterToPointInTimeInput struct { // Example: mySubnetgroup DBSubnetGroupName *string `type:"string"` + // A Boolean value that is true to enable mapping of AWS Identity and Access + // Management (IAM) accounts to database accounts, and otherwise false. + // + // Default: false + EnableIAMDatabaseAuthentication *bool `type:"boolean"` + // The KMS key identifier to use when restoring an encrypted DB cluster from // an encrypted DB cluster. // @@ -24243,6 +26048,12 @@ func (s *RestoreDBClusterToPointInTimeInput) SetDBSubnetGroupName(v string) *Res return s } +// SetEnableIAMDatabaseAuthentication sets the EnableIAMDatabaseAuthentication field's value. +func (s *RestoreDBClusterToPointInTimeInput) SetEnableIAMDatabaseAuthentication(v bool) *RestoreDBClusterToPointInTimeInput { + s.EnableIAMDatabaseAuthentication = &v + return s +} + // SetKmsKeyId sets the KmsKeyId field's value. func (s *RestoreDBClusterToPointInTimeInput) SetKmsKeyId(v string) *RestoreDBClusterToPointInTimeInput { s.KmsKeyId = &v @@ -24413,6 +26224,20 @@ type RestoreDBInstanceFromDBSnapshotInput struct { // Directory Service. DomainIAMRoleName *string `type:"string"` + // True to enable mapping of AWS Identity and Access Management (IAM) accounts + // to database accounts; otherwise false. + // + // You can enable IAM database authentication for the following database engines + // + // * For MySQL 5.6, minor version 5.6.34 or higher + // + // * For MySQL 5.7, minor version 5.7.16 or higher + // + // * Aurora 5.6 or higher. + // + // Default: false + EnableIAMDatabaseAuthentication *bool `type:"boolean"` + // The database engine to use for the new instance. // // Default: The same as source @@ -24589,6 +26414,12 @@ func (s *RestoreDBInstanceFromDBSnapshotInput) SetDomainIAMRoleName(v string) *R return s } +// SetEnableIAMDatabaseAuthentication sets the EnableIAMDatabaseAuthentication field's value. +func (s *RestoreDBInstanceFromDBSnapshotInput) SetEnableIAMDatabaseAuthentication(v bool) *RestoreDBInstanceFromDBSnapshotInput { + s.EnableIAMDatabaseAuthentication = &v + return s +} + // SetEngine sets the Engine field's value. func (s *RestoreDBInstanceFromDBSnapshotInput) SetEngine(v string) *RestoreDBInstanceFromDBSnapshotInput { s.Engine = &v @@ -24740,6 +26571,20 @@ type RestoreDBInstanceToPointInTimeInput struct { // Directory Service. DomainIAMRoleName *string `type:"string"` + // True to enable mapping of AWS Identity and Access Management (IAM) accounts + // to database accounts; otherwise false. + // + // You can enable IAM database authentication for the following database engines + // + // * For MySQL 5.6, minor version 5.6.34 or higher + // + // * For MySQL 5.7, minor version 5.7.16 or higher + // + // * Aurora 5.6 or higher. + // + // Default: false + EnableIAMDatabaseAuthentication *bool `type:"boolean"` + // The database engine to use for the new instance. // // Default: The same as source @@ -24948,6 +26793,12 @@ func (s *RestoreDBInstanceToPointInTimeInput) SetDomainIAMRoleName(v string) *Re return s } +// SetEnableIAMDatabaseAuthentication sets the EnableIAMDatabaseAuthentication field's value. +func (s *RestoreDBInstanceToPointInTimeInput) SetEnableIAMDatabaseAuthentication(v bool) *RestoreDBInstanceToPointInTimeInput { + s.EnableIAMDatabaseAuthentication = &v + return s +} + // SetEngine sets the Engine field's value. func (s *RestoreDBInstanceToPointInTimeInput) SetEngine(v string) *RestoreDBInstanceToPointInTimeInput { s.Engine = &v diff --git a/vendor/github.com/aws/aws-sdk-go/service/rds/doc.go b/vendor/github.com/aws/aws-sdk-go/service/rds/doc.go new file mode 100644 index 000000000..c3365d9f3 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/service/rds/doc.go @@ -0,0 +1,121 @@ +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. + +// Package rds provides the client and types for making API +// requests to Amazon Relational Database Service. +// +// Amazon Relational Database Service (Amazon RDS) is a web service that makes +// it easier to set up, operate, and scale a relational database in the cloud. +// It provides cost-efficient, resizable capacity for an industry-standard relational +// database and manages common database administration tasks, freeing up developers +// to focus on what makes their applications and businesses unique. +// +// Amazon RDS gives you access to the capabilities of a MySQL, MariaDB, PostgreSQL, +// Microsoft SQL Server, Oracle, or Amazon Aurora database server. These capabilities +// mean that the code, applications, and tools you already use today with your +// existing databases work with Amazon RDS without modification. Amazon RDS +// automatically backs up your database and maintains the database software +// that powers your DB instance. Amazon RDS is flexible: you can scale your +// database instance's compute resources and storage capacity to meet your application's +// demand. As with all Amazon Web Services, there are no up-front investments, +// and you pay only for the resources you use. +// +// This interface reference for Amazon RDS contains documentation for a programming +// or command line interface you can use to manage Amazon RDS. Note that Amazon +// RDS is asynchronous, which means that some interfaces might require techniques +// such as polling or callback functions to determine when a command has been +// applied. In this reference, the parameter descriptions indicate whether a +// command is applied immediately, on the next instance reboot, or during the +// maintenance window. The reference structure is as follows, and we list following +// some related topics from the user guide. +// +// Amazon RDS API Reference +// +// * For the alphabetical list of API actions, see API Actions (http://docs.aws.amazon.com/AmazonRDS/latest/APIReference/API_Operations.html). +// +// * For the alphabetical list of data types, see Data Types (http://docs.aws.amazon.com/AmazonRDS/latest/APIReference/API_Types.html). +// +// * For a list of common query parameters, see Common Parameters (http://docs.aws.amazon.com/AmazonRDS/latest/APIReference/CommonParameters.html). +// +// * For descriptions of the error codes, see Common Errors (http://docs.aws.amazon.com/AmazonRDS/latest/APIReference/CommonErrors.html). +// +// Amazon RDS User Guide +// +// * For a summary of the Amazon RDS interfaces, see Available RDS Interfaces +// (http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/Welcome.html#Welcome.Interfaces). +// +// * For more information about how to use the Query API, see Using the Query +// API (http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/Using_the_Query_API.html). +// +// See https://docs.aws.amazon.com/goto/WebAPI/rds-2014-10-31 for more information on this service. +// +// See rds package documentation for more information. +// https://docs.aws.amazon.com/sdk-for-go/api/service/rds/ +// +// Using the Client +// +// To use the client for Amazon Relational Database Service you will first need +// to create a new instance of it. +// +// When creating a client for an AWS service you'll first need to have a Session +// already created. The Session provides configuration that can be shared +// between multiple service clients. Additional configuration can be applied to +// the Session and service's client when they are constructed. The aws package's +// Config type contains several fields such as Region for the AWS Region the +// client should make API requests too. The optional Config value can be provided +// as the variadic argument for Sessions and client creation. +// +// Once the service's client is created you can use it to make API requests the +// AWS service. These clients are safe to use concurrently. +// +// // Create a session to share configuration, and load external configuration. +// sess := session.Must(session.NewSession()) +// +// // Create the service's client with the session. +// svc := rds.New(sess) +// +// See the SDK's documentation for more information on how to use service clients. +// https://docs.aws.amazon.com/sdk-for-go/api/ +// +// See aws package's Config type for more information on configuration options. +// https://docs.aws.amazon.com/sdk-for-go/api/aws/#Config +// +// See the Amazon Relational Database Service client RDS for more +// information on creating the service's client. +// https://docs.aws.amazon.com/sdk-for-go/api/service/rds/#New +// +// Once the client is created you can make an API request to the service. +// Each API method takes a input parameter, and returns the service response +// and an error. +// +// The API method will document which error codes the service can be returned +// by the operation if the service models the API operation's errors. These +// errors will also be available as const strings prefixed with "ErrCode". +// +// result, err := svc.AddRoleToDBCluster(params) +// if err != nil { +// // Cast err to awserr.Error to handle specific error codes. +// aerr, ok := err.(awserr.Error) +// if ok && aerr.Code() == { +// // Specific error code handling +// } +// return err +// } +// +// fmt.Println("AddRoleToDBCluster result:") +// fmt.Println(result) +// +// Using the Client with Context +// +// The service's client also provides methods to make API requests with a Context +// value. This allows you to control the timeout, and cancellation of pending +// requests. These methods also take request Option as variadic parameter to apply +// additional configuration to the API request. +// +// ctx := context.Background() +// +// result, err := svc.AddRoleToDBClusterWithContext(ctx, params) +// +// See the request package documentation for more information on using Context pattern +// with the SDK. +// https://docs.aws.amazon.com/sdk-for-go/api/aws/request/ +package rds diff --git a/vendor/github.com/aws/aws-sdk-go/service/rds/doc_custom.go b/vendor/github.com/aws/aws-sdk-go/service/rds/doc_custom.go new file mode 100644 index 000000000..3a4b87905 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/service/rds/doc_custom.go @@ -0,0 +1,25 @@ +// IAM User or Role Database Authentication +// +// The rdsutil package's BuildAuthToken function provides a connection +// authentication token builder. Given an endpoint of the RDS database, +// AWS region, DB user, and AWS credentials the function will create an +// presigned URL to use as the authentication token for the database's +// connection. +// +// The following example shows how to use BuildAuthToken to create an authentication +// token for connecting to a MySQL database in RDS. +// +// authToken, err := rdsutils.BuildAuthToken(dbEndpoint, awsRegion, dbUser, awsCreds) +// +// // Create the MySQL DNS string for the DB connection +// // user:password@protocol(endpoint)/dbname? +// dnsStr = fmt.Sprintf("%s:%s@tcp(%s)/%s?tls=true", +// dbUser, authToken, dbEndpoint, dbName, +// ) +// +// // Use db to perform SQL operations on database +// db, err := sql.Open("mysql", dnsStr) +// +// See rdsutil package for more information. +// http://docs.aws.amazon.com/sdk-for-go/api/service/rds/rdsutils/ +package rds diff --git a/vendor/github.com/aws/aws-sdk-go/service/rds/errors.go b/vendor/github.com/aws/aws-sdk-go/service/rds/errors.go index 1ffd1a0fb..4cb1983df 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/rds/errors.go +++ b/vendor/github.com/aws/aws-sdk-go/service/rds/errors.go @@ -1,4 +1,4 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. package rds @@ -272,7 +272,9 @@ const ( // ErrCodeInvalidDBParameterGroupStateFault for service response error code // "InvalidDBParameterGroupState". // - // The DB parameter group cannot be deleted because it is in use. + // The DB parameter group is in use or is in an invalid state. If you are attempting + // to delete the parameter group, you cannot delete it when the parameter group + // is in this state. ErrCodeInvalidDBParameterGroupStateFault = "InvalidDBParameterGroupState" // ErrCodeInvalidDBSecurityGroupStateFault for service response error code diff --git a/vendor/github.com/aws/aws-sdk-go/service/rds/service.go b/vendor/github.com/aws/aws-sdk-go/service/rds/service.go index e81de9182..2e2ec2e97 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/rds/service.go +++ b/vendor/github.com/aws/aws-sdk-go/service/rds/service.go @@ -1,4 +1,4 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. package rds @@ -11,52 +11,12 @@ import ( "github.com/aws/aws-sdk-go/private/protocol/query" ) +// RDS provides the API operation methods for making requests to +// Amazon Relational Database Service. See this package's package overview docs +// for details on the service. // -// Amazon Relational Database Service (Amazon RDS) is a web service that makes -// it easier to set up, operate, and scale a relational database in the cloud. -// It provides cost-efficient, resizeable capacity for an industry-standard -// relational database and manages common database administration tasks, freeing -// up developers to focus on what makes their applications and businesses unique. -// -// Amazon RDS gives you access to the capabilities of a MySQL, MariaDB, PostgreSQL, -// Microsoft SQL Server, Oracle, or Amazon Aurora database server. These capabilities -// mean that the code, applications, and tools you already use today with your -// existing databases work with Amazon RDS without modification. Amazon RDS -// automatically backs up your database and maintains the database software -// that powers your DB instance. Amazon RDS is flexible: you can scale your -// database instance's compute resources and storage capacity to meet your application's -// demand. As with all Amazon Web Services, there are no up-front investments, -// and you pay only for the resources you use. -// -// This interface reference for Amazon RDS contains documentation for a programming -// or command line interface you can use to manage Amazon RDS. Note that Amazon -// RDS is asynchronous, which means that some interfaces might require techniques -// such as polling or callback functions to determine when a command has been -// applied. In this reference, the parameter descriptions indicate whether a -// command is applied immediately, on the next instance reboot, or during the -// maintenance window. The reference structure is as follows, and we list following -// some related topics from the user guide. -// -// Amazon RDS API Reference -// -// * For the alphabetical list of API actions, see API Actions (http://docs.aws.amazon.com/AmazonRDS/latest/APIReference/API_Operations.html). -// -// * For the alphabetical list of data types, see Data Types (http://docs.aws.amazon.com/AmazonRDS/latest/APIReference/API_Types.html). -// -// * For a list of common query parameters, see Common Parameters (http://docs.aws.amazon.com/AmazonRDS/latest/APIReference/CommonParameters.html). -// -// * For descriptions of the error codes, see Common Errors (http://docs.aws.amazon.com/AmazonRDS/latest/APIReference/CommonErrors.html). -// -// Amazon RDS User Guide -// -// * For a summary of the Amazon RDS interfaces, see Available RDS Interfaces -// (http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/Welcome.html#Welcome.Interfaces). -// -// * For more information about how to use the Query API, see Using the Query -// API (http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/Using_the_Query_API.html). -// The service client's operations are safe to be used concurrently. -// It is not safe to mutate any of the client's properties though. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/rds-2014-10-31 +// RDS methods are safe to use concurrently. It is not safe to +// modify mutate any of the struct's properties though. type RDS struct { *client.Client } diff --git a/vendor/github.com/aws/aws-sdk-go/service/rds/waiters.go b/vendor/github.com/aws/aws-sdk-go/service/rds/waiters.go index 00f532a75..3ea78a9ba 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/rds/waiters.go +++ b/vendor/github.com/aws/aws-sdk-go/service/rds/waiters.go @@ -1,9 +1,12 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. package rds import ( - "github.com/aws/aws-sdk-go/private/waiter" + "time" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/request" ) // WaitUntilDBInstanceAvailable uses the Amazon RDS API operation @@ -11,56 +14,70 @@ import ( // If the condition is not meet within the max attempt window an error will // be returned. func (c *RDS) WaitUntilDBInstanceAvailable(input *DescribeDBInstancesInput) error { - waiterCfg := waiter.Config{ - Operation: "DescribeDBInstances", - Delay: 30, + return c.WaitUntilDBInstanceAvailableWithContext(aws.BackgroundContext(), input) +} + +// WaitUntilDBInstanceAvailableWithContext is an extended version of WaitUntilDBInstanceAvailable. +// 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 *RDS) WaitUntilDBInstanceAvailableWithContext(ctx aws.Context, input *DescribeDBInstancesInput, opts ...request.WaiterOption) error { + w := request.Waiter{ + Name: "WaitUntilDBInstanceAvailable", MaxAttempts: 60, - Acceptors: []waiter.WaitAcceptor{ + Delay: request.ConstantWaiterDelay(30 * time.Second), + Acceptors: []request.WaiterAcceptor{ { - State: "success", - Matcher: "pathAll", - Argument: "DBInstances[].DBInstanceStatus", + State: request.SuccessWaiterState, + Matcher: request.PathAllWaiterMatch, Argument: "DBInstances[].DBInstanceStatus", Expected: "available", }, { - State: "failure", - Matcher: "pathAny", - Argument: "DBInstances[].DBInstanceStatus", + State: request.FailureWaiterState, + Matcher: request.PathAnyWaiterMatch, Argument: "DBInstances[].DBInstanceStatus", Expected: "deleted", }, { - State: "failure", - Matcher: "pathAny", - Argument: "DBInstances[].DBInstanceStatus", + State: request.FailureWaiterState, + Matcher: request.PathAnyWaiterMatch, Argument: "DBInstances[].DBInstanceStatus", Expected: "deleting", }, { - State: "failure", - Matcher: "pathAny", - Argument: "DBInstances[].DBInstanceStatus", + State: request.FailureWaiterState, + Matcher: request.PathAnyWaiterMatch, Argument: "DBInstances[].DBInstanceStatus", Expected: "failed", }, { - State: "failure", - Matcher: "pathAny", - Argument: "DBInstances[].DBInstanceStatus", + State: request.FailureWaiterState, + Matcher: request.PathAnyWaiterMatch, Argument: "DBInstances[].DBInstanceStatus", Expected: "incompatible-restore", }, { - State: "failure", - Matcher: "pathAny", - Argument: "DBInstances[].DBInstanceStatus", + State: request.FailureWaiterState, + Matcher: request.PathAnyWaiterMatch, Argument: "DBInstances[].DBInstanceStatus", Expected: "incompatible-parameters", }, }, + Logger: c.Config.Logger, + NewRequest: func(opts []request.Option) (*request.Request, error) { + var inCpy *DescribeDBInstancesInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeDBInstancesRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, } + w.ApplyOptions(opts...) - w := waiter.Waiter{ - Client: c, - Input: input, - Config: waiterCfg, - } - return w.Wait() + return w.WaitWithContext(ctx) } // WaitUntilDBInstanceDeleted uses the Amazon RDS API operation @@ -68,54 +85,68 @@ func (c *RDS) WaitUntilDBInstanceAvailable(input *DescribeDBInstancesInput) erro // If the condition is not meet within the max attempt window an error will // be returned. func (c *RDS) WaitUntilDBInstanceDeleted(input *DescribeDBInstancesInput) error { - waiterCfg := waiter.Config{ - Operation: "DescribeDBInstances", - Delay: 30, + return c.WaitUntilDBInstanceDeletedWithContext(aws.BackgroundContext(), input) +} + +// WaitUntilDBInstanceDeletedWithContext is an extended version of WaitUntilDBInstanceDeleted. +// 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 *RDS) WaitUntilDBInstanceDeletedWithContext(ctx aws.Context, input *DescribeDBInstancesInput, opts ...request.WaiterOption) error { + w := request.Waiter{ + Name: "WaitUntilDBInstanceDeleted", MaxAttempts: 60, - Acceptors: []waiter.WaitAcceptor{ + Delay: request.ConstantWaiterDelay(30 * time.Second), + Acceptors: []request.WaiterAcceptor{ { - State: "success", - Matcher: "pathAll", - Argument: "DBInstances[].DBInstanceStatus", + State: request.SuccessWaiterState, + Matcher: request.PathAllWaiterMatch, Argument: "DBInstances[].DBInstanceStatus", Expected: "deleted", }, { - State: "success", - Matcher: "error", - Argument: "", + State: request.SuccessWaiterState, + Matcher: request.ErrorWaiterMatch, Expected: "DBInstanceNotFound", }, { - State: "failure", - Matcher: "pathAny", - Argument: "DBInstances[].DBInstanceStatus", + State: request.FailureWaiterState, + Matcher: request.PathAnyWaiterMatch, Argument: "DBInstances[].DBInstanceStatus", Expected: "creating", }, { - State: "failure", - Matcher: "pathAny", - Argument: "DBInstances[].DBInstanceStatus", + State: request.FailureWaiterState, + Matcher: request.PathAnyWaiterMatch, Argument: "DBInstances[].DBInstanceStatus", Expected: "modifying", }, { - State: "failure", - Matcher: "pathAny", - Argument: "DBInstances[].DBInstanceStatus", + State: request.FailureWaiterState, + Matcher: request.PathAnyWaiterMatch, Argument: "DBInstances[].DBInstanceStatus", Expected: "rebooting", }, { - State: "failure", - Matcher: "pathAny", - Argument: "DBInstances[].DBInstanceStatus", + State: request.FailureWaiterState, + Matcher: request.PathAnyWaiterMatch, Argument: "DBInstances[].DBInstanceStatus", Expected: "resetting-master-credentials", }, }, + Logger: c.Config.Logger, + NewRequest: func(opts []request.Option) (*request.Request, error) { + var inCpy *DescribeDBInstancesInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeDBInstancesRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, } + w.ApplyOptions(opts...) - w := waiter.Waiter{ - Client: c, - Input: input, - Config: waiterCfg, - } - return w.Wait() + return w.WaitWithContext(ctx) } diff --git a/vendor/github.com/aws/aws-sdk-go/service/redshift/api.go b/vendor/github.com/aws/aws-sdk-go/service/redshift/api.go index 7a9a7cf2c..6fab8fc65 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/redshift/api.go +++ b/vendor/github.com/aws/aws-sdk-go/service/redshift/api.go @@ -1,11 +1,11 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. -// Package redshift provides a client for Amazon Redshift. package redshift import ( "time" + "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awsutil" "github.com/aws/aws-sdk-go/aws/request" "github.com/aws/aws-sdk-go/private/protocol" @@ -103,8 +103,23 @@ func (c *Redshift) AuthorizeClusterSecurityGroupIngressRequest(input *AuthorizeC // Please also see https://docs.aws.amazon.com/goto/WebAPI/redshift-2012-12-01/AuthorizeClusterSecurityGroupIngress func (c *Redshift) AuthorizeClusterSecurityGroupIngress(input *AuthorizeClusterSecurityGroupIngressInput) (*AuthorizeClusterSecurityGroupIngressOutput, error) { req, out := c.AuthorizeClusterSecurityGroupIngressRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// AuthorizeClusterSecurityGroupIngressWithContext is the same as AuthorizeClusterSecurityGroupIngress with the addition of +// the ability to pass a context and additional request options. +// +// See AuthorizeClusterSecurityGroupIngress 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 *Redshift) AuthorizeClusterSecurityGroupIngressWithContext(ctx aws.Context, input *AuthorizeClusterSecurityGroupIngressInput, opts ...request.Option) (*AuthorizeClusterSecurityGroupIngressOutput, error) { + req, out := c.AuthorizeClusterSecurityGroupIngressRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opAuthorizeSnapshotAccess = "AuthorizeSnapshotAccess" @@ -190,8 +205,23 @@ func (c *Redshift) AuthorizeSnapshotAccessRequest(input *AuthorizeSnapshotAccess // Please also see https://docs.aws.amazon.com/goto/WebAPI/redshift-2012-12-01/AuthorizeSnapshotAccess func (c *Redshift) AuthorizeSnapshotAccess(input *AuthorizeSnapshotAccessInput) (*AuthorizeSnapshotAccessOutput, error) { req, out := c.AuthorizeSnapshotAccessRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// AuthorizeSnapshotAccessWithContext is the same as AuthorizeSnapshotAccess with the addition of +// the ability to pass a context and additional request options. +// +// See AuthorizeSnapshotAccess 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 *Redshift) AuthorizeSnapshotAccessWithContext(ctx aws.Context, input *AuthorizeSnapshotAccessInput, opts ...request.Option) (*AuthorizeSnapshotAccessOutput, error) { + req, out := c.AuthorizeSnapshotAccessRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCopyClusterSnapshot = "CopyClusterSnapshot" @@ -279,8 +309,23 @@ func (c *Redshift) CopyClusterSnapshotRequest(input *CopyClusterSnapshotInput) ( // Please also see https://docs.aws.amazon.com/goto/WebAPI/redshift-2012-12-01/CopyClusterSnapshot func (c *Redshift) CopyClusterSnapshot(input *CopyClusterSnapshotInput) (*CopyClusterSnapshotOutput, error) { req, out := c.CopyClusterSnapshotRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CopyClusterSnapshotWithContext is the same as CopyClusterSnapshot with the addition of +// the ability to pass a context and additional request options. +// +// See CopyClusterSnapshot 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 *Redshift) CopyClusterSnapshotWithContext(ctx aws.Context, input *CopyClusterSnapshotInput, opts ...request.Option) (*CopyClusterSnapshotOutput, error) { + req, out := c.CopyClusterSnapshotRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateCluster = "CreateCluster" @@ -414,8 +459,23 @@ func (c *Redshift) CreateClusterRequest(input *CreateClusterInput) (req *request // Please also see https://docs.aws.amazon.com/goto/WebAPI/redshift-2012-12-01/CreateCluster func (c *Redshift) CreateCluster(input *CreateClusterInput) (*CreateClusterOutput, error) { req, out := c.CreateClusterRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateClusterWithContext is the same as CreateCluster with the addition of +// the ability to pass a context and additional request options. +// +// See CreateCluster 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 *Redshift) CreateClusterWithContext(ctx aws.Context, input *CreateClusterInput, opts ...request.Option) (*CreateClusterOutput, error) { + req, out := c.CreateClusterRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateClusterParameterGroup = "CreateClusterParameterGroup" @@ -501,8 +561,23 @@ func (c *Redshift) CreateClusterParameterGroupRequest(input *CreateClusterParame // Please also see https://docs.aws.amazon.com/goto/WebAPI/redshift-2012-12-01/CreateClusterParameterGroup func (c *Redshift) CreateClusterParameterGroup(input *CreateClusterParameterGroupInput) (*CreateClusterParameterGroupOutput, error) { req, out := c.CreateClusterParameterGroupRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateClusterParameterGroupWithContext is the same as CreateClusterParameterGroup with the addition of +// the ability to pass a context and additional request options. +// +// See CreateClusterParameterGroup 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 *Redshift) CreateClusterParameterGroupWithContext(ctx aws.Context, input *CreateClusterParameterGroupInput, opts ...request.Option) (*CreateClusterParameterGroupOutput, error) { + req, out := c.CreateClusterParameterGroupRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateClusterSecurityGroup = "CreateClusterSecurityGroup" @@ -583,8 +658,23 @@ func (c *Redshift) CreateClusterSecurityGroupRequest(input *CreateClusterSecurit // Please also see https://docs.aws.amazon.com/goto/WebAPI/redshift-2012-12-01/CreateClusterSecurityGroup func (c *Redshift) CreateClusterSecurityGroup(input *CreateClusterSecurityGroupInput) (*CreateClusterSecurityGroupOutput, error) { req, out := c.CreateClusterSecurityGroupRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateClusterSecurityGroupWithContext is the same as CreateClusterSecurityGroup with the addition of +// the ability to pass a context and additional request options. +// +// See CreateClusterSecurityGroup 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 *Redshift) CreateClusterSecurityGroupWithContext(ctx aws.Context, input *CreateClusterSecurityGroupInput, opts ...request.Option) (*CreateClusterSecurityGroupOutput, error) { + req, out := c.CreateClusterSecurityGroupRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateClusterSnapshot = "CreateClusterSnapshot" @@ -670,8 +760,23 @@ func (c *Redshift) CreateClusterSnapshotRequest(input *CreateClusterSnapshotInpu // Please also see https://docs.aws.amazon.com/goto/WebAPI/redshift-2012-12-01/CreateClusterSnapshot func (c *Redshift) CreateClusterSnapshot(input *CreateClusterSnapshotInput) (*CreateClusterSnapshotOutput, error) { req, out := c.CreateClusterSnapshotRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateClusterSnapshotWithContext is the same as CreateClusterSnapshot with the addition of +// the ability to pass a context and additional request options. +// +// See CreateClusterSnapshot 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 *Redshift) CreateClusterSnapshotWithContext(ctx aws.Context, input *CreateClusterSnapshotInput, opts ...request.Option) (*CreateClusterSnapshotOutput, error) { + req, out := c.CreateClusterSnapshotRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateClusterSubnetGroup = "CreateClusterSubnetGroup" @@ -770,8 +875,23 @@ func (c *Redshift) CreateClusterSubnetGroupRequest(input *CreateClusterSubnetGro // Please also see https://docs.aws.amazon.com/goto/WebAPI/redshift-2012-12-01/CreateClusterSubnetGroup func (c *Redshift) CreateClusterSubnetGroup(input *CreateClusterSubnetGroupInput) (*CreateClusterSubnetGroupOutput, error) { req, out := c.CreateClusterSubnetGroupRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateClusterSubnetGroupWithContext is the same as CreateClusterSubnetGroup with the addition of +// the ability to pass a context and additional request options. +// +// See CreateClusterSubnetGroup 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 *Redshift) CreateClusterSubnetGroupWithContext(ctx aws.Context, input *CreateClusterSubnetGroupInput, opts ...request.Option) (*CreateClusterSubnetGroupOutput, error) { + req, out := c.CreateClusterSubnetGroupRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateEventSubscription = "CreateEventSubscription" @@ -896,8 +1016,23 @@ func (c *Redshift) CreateEventSubscriptionRequest(input *CreateEventSubscription // Please also see https://docs.aws.amazon.com/goto/WebAPI/redshift-2012-12-01/CreateEventSubscription func (c *Redshift) CreateEventSubscription(input *CreateEventSubscriptionInput) (*CreateEventSubscriptionOutput, error) { req, out := c.CreateEventSubscriptionRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateEventSubscriptionWithContext is the same as CreateEventSubscription with the addition of +// the ability to pass a context and additional request options. +// +// See CreateEventSubscription 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 *Redshift) CreateEventSubscriptionWithContext(ctx aws.Context, input *CreateEventSubscriptionInput, opts ...request.Option) (*CreateEventSubscriptionOutput, error) { + req, out := c.CreateEventSubscriptionRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateHsmClientCertificate = "CreateHsmClientCertificate" @@ -981,8 +1116,23 @@ func (c *Redshift) CreateHsmClientCertificateRequest(input *CreateHsmClientCerti // Please also see https://docs.aws.amazon.com/goto/WebAPI/redshift-2012-12-01/CreateHsmClientCertificate func (c *Redshift) CreateHsmClientCertificate(input *CreateHsmClientCertificateInput) (*CreateHsmClientCertificateOutput, error) { req, out := c.CreateHsmClientCertificateRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateHsmClientCertificateWithContext is the same as CreateHsmClientCertificate with the addition of +// the ability to pass a context and additional request options. +// +// See CreateHsmClientCertificate 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 *Redshift) CreateHsmClientCertificateWithContext(ctx aws.Context, input *CreateHsmClientCertificateInput, opts ...request.Option) (*CreateHsmClientCertificateOutput, error) { + req, out := c.CreateHsmClientCertificateRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateHsmConfiguration = "CreateHsmConfiguration" @@ -1067,8 +1217,23 @@ func (c *Redshift) CreateHsmConfigurationRequest(input *CreateHsmConfigurationIn // Please also see https://docs.aws.amazon.com/goto/WebAPI/redshift-2012-12-01/CreateHsmConfiguration func (c *Redshift) CreateHsmConfiguration(input *CreateHsmConfigurationInput) (*CreateHsmConfigurationOutput, error) { req, out := c.CreateHsmConfigurationRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateHsmConfigurationWithContext is the same as CreateHsmConfiguration with the addition of +// the ability to pass a context and additional request options. +// +// See CreateHsmConfiguration 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 *Redshift) CreateHsmConfigurationWithContext(ctx aws.Context, input *CreateHsmConfigurationInput, opts ...request.Option) (*CreateHsmConfigurationOutput, error) { + req, out := c.CreateHsmConfigurationRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateSnapshotCopyGrant = "CreateSnapshotCopyGrant" @@ -1156,8 +1321,23 @@ func (c *Redshift) CreateSnapshotCopyGrantRequest(input *CreateSnapshotCopyGrant // Please also see https://docs.aws.amazon.com/goto/WebAPI/redshift-2012-12-01/CreateSnapshotCopyGrant func (c *Redshift) CreateSnapshotCopyGrant(input *CreateSnapshotCopyGrantInput) (*CreateSnapshotCopyGrantOutput, error) { req, out := c.CreateSnapshotCopyGrantRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateSnapshotCopyGrantWithContext is the same as CreateSnapshotCopyGrant with the addition of +// the ability to pass a context and additional request options. +// +// See CreateSnapshotCopyGrant 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 *Redshift) CreateSnapshotCopyGrantWithContext(ctx aws.Context, input *CreateSnapshotCopyGrantInput, opts ...request.Option) (*CreateSnapshotCopyGrantOutput, error) { + req, out := c.CreateSnapshotCopyGrantRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateTags = "CreateTags" @@ -1235,8 +1415,23 @@ func (c *Redshift) CreateTagsRequest(input *CreateTagsInput) (req *request.Reque // Please also see https://docs.aws.amazon.com/goto/WebAPI/redshift-2012-12-01/CreateTags func (c *Redshift) CreateTags(input *CreateTagsInput) (*CreateTagsOutput, error) { req, out := c.CreateTagsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateTagsWithContext is the same as CreateTags with the addition of +// the ability to pass a context and additional request options. +// +// See CreateTags 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 *Redshift) CreateTagsWithContext(ctx aws.Context, input *CreateTagsInput, opts ...request.Option) (*CreateTagsOutput, error) { + req, out := c.CreateTagsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteCluster = "DeleteCluster" @@ -1327,8 +1522,23 @@ func (c *Redshift) DeleteClusterRequest(input *DeleteClusterInput) (req *request // Please also see https://docs.aws.amazon.com/goto/WebAPI/redshift-2012-12-01/DeleteCluster func (c *Redshift) DeleteCluster(input *DeleteClusterInput) (*DeleteClusterOutput, error) { req, out := c.DeleteClusterRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteClusterWithContext is the same as DeleteCluster with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteCluster 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 *Redshift) DeleteClusterWithContext(ctx aws.Context, input *DeleteClusterInput, opts ...request.Option) (*DeleteClusterOutput, error) { + req, out := c.DeleteClusterRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteClusterParameterGroup = "DeleteClusterParameterGroup" @@ -1401,8 +1611,23 @@ func (c *Redshift) DeleteClusterParameterGroupRequest(input *DeleteClusterParame // Please also see https://docs.aws.amazon.com/goto/WebAPI/redshift-2012-12-01/DeleteClusterParameterGroup func (c *Redshift) DeleteClusterParameterGroup(input *DeleteClusterParameterGroupInput) (*DeleteClusterParameterGroupOutput, error) { req, out := c.DeleteClusterParameterGroupRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteClusterParameterGroupWithContext is the same as DeleteClusterParameterGroup with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteClusterParameterGroup 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 *Redshift) DeleteClusterParameterGroupWithContext(ctx aws.Context, input *DeleteClusterParameterGroupInput, opts ...request.Option) (*DeleteClusterParameterGroupOutput, error) { + req, out := c.DeleteClusterParameterGroupRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteClusterSecurityGroup = "DeleteClusterSecurityGroup" @@ -1479,8 +1704,23 @@ func (c *Redshift) DeleteClusterSecurityGroupRequest(input *DeleteClusterSecurit // Please also see https://docs.aws.amazon.com/goto/WebAPI/redshift-2012-12-01/DeleteClusterSecurityGroup func (c *Redshift) DeleteClusterSecurityGroup(input *DeleteClusterSecurityGroupInput) (*DeleteClusterSecurityGroupOutput, error) { req, out := c.DeleteClusterSecurityGroupRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteClusterSecurityGroupWithContext is the same as DeleteClusterSecurityGroup with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteClusterSecurityGroup 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 *Redshift) DeleteClusterSecurityGroupWithContext(ctx aws.Context, input *DeleteClusterSecurityGroupInput, opts ...request.Option) (*DeleteClusterSecurityGroupOutput, error) { + req, out := c.DeleteClusterSecurityGroupRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteClusterSnapshot = "DeleteClusterSnapshot" @@ -1555,8 +1795,23 @@ func (c *Redshift) DeleteClusterSnapshotRequest(input *DeleteClusterSnapshotInpu // Please also see https://docs.aws.amazon.com/goto/WebAPI/redshift-2012-12-01/DeleteClusterSnapshot func (c *Redshift) DeleteClusterSnapshot(input *DeleteClusterSnapshotInput) (*DeleteClusterSnapshotOutput, error) { req, out := c.DeleteClusterSnapshotRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteClusterSnapshotWithContext is the same as DeleteClusterSnapshot with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteClusterSnapshot 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 *Redshift) DeleteClusterSnapshotWithContext(ctx aws.Context, input *DeleteClusterSnapshotInput, opts ...request.Option) (*DeleteClusterSnapshotOutput, error) { + req, out := c.DeleteClusterSnapshotRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteClusterSubnetGroup = "DeleteClusterSubnetGroup" @@ -1629,8 +1884,23 @@ func (c *Redshift) DeleteClusterSubnetGroupRequest(input *DeleteClusterSubnetGro // Please also see https://docs.aws.amazon.com/goto/WebAPI/redshift-2012-12-01/DeleteClusterSubnetGroup func (c *Redshift) DeleteClusterSubnetGroup(input *DeleteClusterSubnetGroupInput) (*DeleteClusterSubnetGroupOutput, error) { req, out := c.DeleteClusterSubnetGroupRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteClusterSubnetGroupWithContext is the same as DeleteClusterSubnetGroup with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteClusterSubnetGroup 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 *Redshift) DeleteClusterSubnetGroupWithContext(ctx aws.Context, input *DeleteClusterSubnetGroupInput, opts ...request.Option) (*DeleteClusterSubnetGroupOutput, error) { + req, out := c.DeleteClusterSubnetGroupRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteEventSubscription = "DeleteEventSubscription" @@ -1701,8 +1971,23 @@ func (c *Redshift) DeleteEventSubscriptionRequest(input *DeleteEventSubscription // Please also see https://docs.aws.amazon.com/goto/WebAPI/redshift-2012-12-01/DeleteEventSubscription func (c *Redshift) DeleteEventSubscription(input *DeleteEventSubscriptionInput) (*DeleteEventSubscriptionOutput, error) { req, out := c.DeleteEventSubscriptionRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteEventSubscriptionWithContext is the same as DeleteEventSubscription with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteEventSubscription 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 *Redshift) DeleteEventSubscriptionWithContext(ctx aws.Context, input *DeleteEventSubscriptionInput, opts ...request.Option) (*DeleteEventSubscriptionOutput, error) { + req, out := c.DeleteEventSubscriptionRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteHsmClientCertificate = "DeleteHsmClientCertificate" @@ -1772,8 +2057,23 @@ func (c *Redshift) DeleteHsmClientCertificateRequest(input *DeleteHsmClientCerti // Please also see https://docs.aws.amazon.com/goto/WebAPI/redshift-2012-12-01/DeleteHsmClientCertificate func (c *Redshift) DeleteHsmClientCertificate(input *DeleteHsmClientCertificateInput) (*DeleteHsmClientCertificateOutput, error) { req, out := c.DeleteHsmClientCertificateRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteHsmClientCertificateWithContext is the same as DeleteHsmClientCertificate with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteHsmClientCertificate 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 *Redshift) DeleteHsmClientCertificateWithContext(ctx aws.Context, input *DeleteHsmClientCertificateInput, opts ...request.Option) (*DeleteHsmClientCertificateOutput, error) { + req, out := c.DeleteHsmClientCertificateRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteHsmConfiguration = "DeleteHsmConfiguration" @@ -1843,8 +2143,23 @@ func (c *Redshift) DeleteHsmConfigurationRequest(input *DeleteHsmConfigurationIn // Please also see https://docs.aws.amazon.com/goto/WebAPI/redshift-2012-12-01/DeleteHsmConfiguration func (c *Redshift) DeleteHsmConfiguration(input *DeleteHsmConfigurationInput) (*DeleteHsmConfigurationOutput, error) { req, out := c.DeleteHsmConfigurationRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteHsmConfigurationWithContext is the same as DeleteHsmConfiguration with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteHsmConfiguration 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 *Redshift) DeleteHsmConfigurationWithContext(ctx aws.Context, input *DeleteHsmConfigurationInput, opts ...request.Option) (*DeleteHsmConfigurationOutput, error) { + req, out := c.DeleteHsmConfigurationRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteSnapshotCopyGrant = "DeleteSnapshotCopyGrant" @@ -1915,8 +2230,23 @@ func (c *Redshift) DeleteSnapshotCopyGrantRequest(input *DeleteSnapshotCopyGrant // Please also see https://docs.aws.amazon.com/goto/WebAPI/redshift-2012-12-01/DeleteSnapshotCopyGrant func (c *Redshift) DeleteSnapshotCopyGrant(input *DeleteSnapshotCopyGrantInput) (*DeleteSnapshotCopyGrantOutput, error) { req, out := c.DeleteSnapshotCopyGrantRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteSnapshotCopyGrantWithContext is the same as DeleteSnapshotCopyGrant with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteSnapshotCopyGrant 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 *Redshift) DeleteSnapshotCopyGrantWithContext(ctx aws.Context, input *DeleteSnapshotCopyGrantInput, opts ...request.Option) (*DeleteSnapshotCopyGrantOutput, error) { + req, out := c.DeleteSnapshotCopyGrantRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteTags = "DeleteTags" @@ -1986,8 +2316,23 @@ func (c *Redshift) DeleteTagsRequest(input *DeleteTagsInput) (req *request.Reque // Please also see https://docs.aws.amazon.com/goto/WebAPI/redshift-2012-12-01/DeleteTags func (c *Redshift) DeleteTags(input *DeleteTagsInput) (*DeleteTagsOutput, error) { req, out := c.DeleteTagsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteTagsWithContext is the same as DeleteTags with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteTags 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 *Redshift) DeleteTagsWithContext(ctx aws.Context, input *DeleteTagsInput, opts ...request.Option) (*DeleteTagsOutput, error) { + req, out := c.DeleteTagsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeClusterParameterGroups = "DescribeClusterParameterGroups" @@ -2078,8 +2423,23 @@ func (c *Redshift) DescribeClusterParameterGroupsRequest(input *DescribeClusterP // Please also see https://docs.aws.amazon.com/goto/WebAPI/redshift-2012-12-01/DescribeClusterParameterGroups func (c *Redshift) DescribeClusterParameterGroups(input *DescribeClusterParameterGroupsInput) (*DescribeClusterParameterGroupsOutput, error) { req, out := c.DescribeClusterParameterGroupsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeClusterParameterGroupsWithContext is the same as DescribeClusterParameterGroups with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeClusterParameterGroups 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 *Redshift) DescribeClusterParameterGroupsWithContext(ctx aws.Context, input *DescribeClusterParameterGroupsInput, opts ...request.Option) (*DescribeClusterParameterGroupsOutput, error) { + req, out := c.DescribeClusterParameterGroupsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // DescribeClusterParameterGroupsPages iterates over the pages of a DescribeClusterParameterGroups operation, @@ -2099,12 +2459,37 @@ func (c *Redshift) DescribeClusterParameterGroups(input *DescribeClusterParamete // return pageNum <= 3 // }) // -func (c *Redshift) DescribeClusterParameterGroupsPages(input *DescribeClusterParameterGroupsInput, fn func(p *DescribeClusterParameterGroupsOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.DescribeClusterParameterGroupsRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*DescribeClusterParameterGroupsOutput), lastPage) - }) +func (c *Redshift) DescribeClusterParameterGroupsPages(input *DescribeClusterParameterGroupsInput, fn func(*DescribeClusterParameterGroupsOutput, bool) bool) error { + return c.DescribeClusterParameterGroupsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// DescribeClusterParameterGroupsPagesWithContext same as DescribeClusterParameterGroupsPages 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 *Redshift) DescribeClusterParameterGroupsPagesWithContext(ctx aws.Context, input *DescribeClusterParameterGroupsInput, fn func(*DescribeClusterParameterGroupsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *DescribeClusterParameterGroupsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeClusterParameterGroupsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*DescribeClusterParameterGroupsOutput), !p.HasNextPage()) + } + return p.Err() } const opDescribeClusterParameters = "DescribeClusterParameters" @@ -2185,8 +2570,23 @@ func (c *Redshift) DescribeClusterParametersRequest(input *DescribeClusterParame // Please also see https://docs.aws.amazon.com/goto/WebAPI/redshift-2012-12-01/DescribeClusterParameters func (c *Redshift) DescribeClusterParameters(input *DescribeClusterParametersInput) (*DescribeClusterParametersOutput, error) { req, out := c.DescribeClusterParametersRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeClusterParametersWithContext is the same as DescribeClusterParameters with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeClusterParameters 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 *Redshift) DescribeClusterParametersWithContext(ctx aws.Context, input *DescribeClusterParametersInput, opts ...request.Option) (*DescribeClusterParametersOutput, error) { + req, out := c.DescribeClusterParametersRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // DescribeClusterParametersPages iterates over the pages of a DescribeClusterParameters operation, @@ -2206,12 +2606,37 @@ func (c *Redshift) DescribeClusterParameters(input *DescribeClusterParametersInp // return pageNum <= 3 // }) // -func (c *Redshift) DescribeClusterParametersPages(input *DescribeClusterParametersInput, fn func(p *DescribeClusterParametersOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.DescribeClusterParametersRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*DescribeClusterParametersOutput), lastPage) - }) +func (c *Redshift) DescribeClusterParametersPages(input *DescribeClusterParametersInput, fn func(*DescribeClusterParametersOutput, bool) bool) error { + return c.DescribeClusterParametersPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// DescribeClusterParametersPagesWithContext same as DescribeClusterParametersPages 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 *Redshift) DescribeClusterParametersPagesWithContext(ctx aws.Context, input *DescribeClusterParametersInput, fn func(*DescribeClusterParametersOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *DescribeClusterParametersInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeClusterParametersRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*DescribeClusterParametersOutput), !p.HasNextPage()) + } + return p.Err() } const opDescribeClusterSecurityGroups = "DescribeClusterSecurityGroups" @@ -2301,8 +2726,23 @@ func (c *Redshift) DescribeClusterSecurityGroupsRequest(input *DescribeClusterSe // Please also see https://docs.aws.amazon.com/goto/WebAPI/redshift-2012-12-01/DescribeClusterSecurityGroups func (c *Redshift) DescribeClusterSecurityGroups(input *DescribeClusterSecurityGroupsInput) (*DescribeClusterSecurityGroupsOutput, error) { req, out := c.DescribeClusterSecurityGroupsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeClusterSecurityGroupsWithContext is the same as DescribeClusterSecurityGroups with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeClusterSecurityGroups 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 *Redshift) DescribeClusterSecurityGroupsWithContext(ctx aws.Context, input *DescribeClusterSecurityGroupsInput, opts ...request.Option) (*DescribeClusterSecurityGroupsOutput, error) { + req, out := c.DescribeClusterSecurityGroupsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // DescribeClusterSecurityGroupsPages iterates over the pages of a DescribeClusterSecurityGroups operation, @@ -2322,12 +2762,37 @@ func (c *Redshift) DescribeClusterSecurityGroups(input *DescribeClusterSecurityG // return pageNum <= 3 // }) // -func (c *Redshift) DescribeClusterSecurityGroupsPages(input *DescribeClusterSecurityGroupsInput, fn func(p *DescribeClusterSecurityGroupsOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.DescribeClusterSecurityGroupsRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*DescribeClusterSecurityGroupsOutput), lastPage) - }) +func (c *Redshift) DescribeClusterSecurityGroupsPages(input *DescribeClusterSecurityGroupsInput, fn func(*DescribeClusterSecurityGroupsOutput, bool) bool) error { + return c.DescribeClusterSecurityGroupsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// DescribeClusterSecurityGroupsPagesWithContext same as DescribeClusterSecurityGroupsPages 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 *Redshift) DescribeClusterSecurityGroupsPagesWithContext(ctx aws.Context, input *DescribeClusterSecurityGroupsInput, fn func(*DescribeClusterSecurityGroupsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *DescribeClusterSecurityGroupsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeClusterSecurityGroupsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*DescribeClusterSecurityGroupsOutput), !p.HasNextPage()) + } + return p.Err() } const opDescribeClusterSnapshots = "DescribeClusterSnapshots" @@ -2414,8 +2879,23 @@ func (c *Redshift) DescribeClusterSnapshotsRequest(input *DescribeClusterSnapsho // Please also see https://docs.aws.amazon.com/goto/WebAPI/redshift-2012-12-01/DescribeClusterSnapshots func (c *Redshift) DescribeClusterSnapshots(input *DescribeClusterSnapshotsInput) (*DescribeClusterSnapshotsOutput, error) { req, out := c.DescribeClusterSnapshotsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeClusterSnapshotsWithContext is the same as DescribeClusterSnapshots with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeClusterSnapshots 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 *Redshift) DescribeClusterSnapshotsWithContext(ctx aws.Context, input *DescribeClusterSnapshotsInput, opts ...request.Option) (*DescribeClusterSnapshotsOutput, error) { + req, out := c.DescribeClusterSnapshotsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // DescribeClusterSnapshotsPages iterates over the pages of a DescribeClusterSnapshots operation, @@ -2435,12 +2915,37 @@ func (c *Redshift) DescribeClusterSnapshots(input *DescribeClusterSnapshotsInput // return pageNum <= 3 // }) // -func (c *Redshift) DescribeClusterSnapshotsPages(input *DescribeClusterSnapshotsInput, fn func(p *DescribeClusterSnapshotsOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.DescribeClusterSnapshotsRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*DescribeClusterSnapshotsOutput), lastPage) - }) +func (c *Redshift) DescribeClusterSnapshotsPages(input *DescribeClusterSnapshotsInput, fn func(*DescribeClusterSnapshotsOutput, bool) bool) error { + return c.DescribeClusterSnapshotsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// DescribeClusterSnapshotsPagesWithContext same as DescribeClusterSnapshotsPages 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 *Redshift) DescribeClusterSnapshotsPagesWithContext(ctx aws.Context, input *DescribeClusterSnapshotsInput, fn func(*DescribeClusterSnapshotsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *DescribeClusterSnapshotsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeClusterSnapshotsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*DescribeClusterSnapshotsOutput), !p.HasNextPage()) + } + return p.Err() } const opDescribeClusterSubnetGroups = "DescribeClusterSubnetGroups" @@ -2526,8 +3031,23 @@ func (c *Redshift) DescribeClusterSubnetGroupsRequest(input *DescribeClusterSubn // Please also see https://docs.aws.amazon.com/goto/WebAPI/redshift-2012-12-01/DescribeClusterSubnetGroups func (c *Redshift) DescribeClusterSubnetGroups(input *DescribeClusterSubnetGroupsInput) (*DescribeClusterSubnetGroupsOutput, error) { req, out := c.DescribeClusterSubnetGroupsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeClusterSubnetGroupsWithContext is the same as DescribeClusterSubnetGroups with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeClusterSubnetGroups 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 *Redshift) DescribeClusterSubnetGroupsWithContext(ctx aws.Context, input *DescribeClusterSubnetGroupsInput, opts ...request.Option) (*DescribeClusterSubnetGroupsOutput, error) { + req, out := c.DescribeClusterSubnetGroupsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // DescribeClusterSubnetGroupsPages iterates over the pages of a DescribeClusterSubnetGroups operation, @@ -2547,12 +3067,37 @@ func (c *Redshift) DescribeClusterSubnetGroups(input *DescribeClusterSubnetGroup // return pageNum <= 3 // }) // -func (c *Redshift) DescribeClusterSubnetGroupsPages(input *DescribeClusterSubnetGroupsInput, fn func(p *DescribeClusterSubnetGroupsOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.DescribeClusterSubnetGroupsRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*DescribeClusterSubnetGroupsOutput), lastPage) - }) +func (c *Redshift) DescribeClusterSubnetGroupsPages(input *DescribeClusterSubnetGroupsInput, fn func(*DescribeClusterSubnetGroupsOutput, bool) bool) error { + return c.DescribeClusterSubnetGroupsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// DescribeClusterSubnetGroupsPagesWithContext same as DescribeClusterSubnetGroupsPages 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 *Redshift) DescribeClusterSubnetGroupsPagesWithContext(ctx aws.Context, input *DescribeClusterSubnetGroupsInput, fn func(*DescribeClusterSubnetGroupsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *DescribeClusterSubnetGroupsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeClusterSubnetGroupsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*DescribeClusterSubnetGroupsOutput), !p.HasNextPage()) + } + return p.Err() } const opDescribeClusterVersions = "DescribeClusterVersions" @@ -2621,8 +3166,23 @@ func (c *Redshift) DescribeClusterVersionsRequest(input *DescribeClusterVersions // Please also see https://docs.aws.amazon.com/goto/WebAPI/redshift-2012-12-01/DescribeClusterVersions func (c *Redshift) DescribeClusterVersions(input *DescribeClusterVersionsInput) (*DescribeClusterVersionsOutput, error) { req, out := c.DescribeClusterVersionsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeClusterVersionsWithContext is the same as DescribeClusterVersions with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeClusterVersions 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 *Redshift) DescribeClusterVersionsWithContext(ctx aws.Context, input *DescribeClusterVersionsInput, opts ...request.Option) (*DescribeClusterVersionsOutput, error) { + req, out := c.DescribeClusterVersionsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // DescribeClusterVersionsPages iterates over the pages of a DescribeClusterVersions operation, @@ -2642,12 +3202,37 @@ func (c *Redshift) DescribeClusterVersions(input *DescribeClusterVersionsInput) // return pageNum <= 3 // }) // -func (c *Redshift) DescribeClusterVersionsPages(input *DescribeClusterVersionsInput, fn func(p *DescribeClusterVersionsOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.DescribeClusterVersionsRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*DescribeClusterVersionsOutput), lastPage) - }) +func (c *Redshift) DescribeClusterVersionsPages(input *DescribeClusterVersionsInput, fn func(*DescribeClusterVersionsOutput, bool) bool) error { + return c.DescribeClusterVersionsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// DescribeClusterVersionsPagesWithContext same as DescribeClusterVersionsPages 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 *Redshift) DescribeClusterVersionsPagesWithContext(ctx aws.Context, input *DescribeClusterVersionsInput, fn func(*DescribeClusterVersionsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *DescribeClusterVersionsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeClusterVersionsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*DescribeClusterVersionsOutput), !p.HasNextPage()) + } + return p.Err() } const opDescribeClusters = "DescribeClusters" @@ -2733,8 +3318,23 @@ func (c *Redshift) DescribeClustersRequest(input *DescribeClustersInput) (req *r // Please also see https://docs.aws.amazon.com/goto/WebAPI/redshift-2012-12-01/DescribeClusters func (c *Redshift) DescribeClusters(input *DescribeClustersInput) (*DescribeClustersOutput, error) { req, out := c.DescribeClustersRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeClustersWithContext is the same as DescribeClusters with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeClusters 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 *Redshift) DescribeClustersWithContext(ctx aws.Context, input *DescribeClustersInput, opts ...request.Option) (*DescribeClustersOutput, error) { + req, out := c.DescribeClustersRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // DescribeClustersPages iterates over the pages of a DescribeClusters operation, @@ -2754,12 +3354,37 @@ func (c *Redshift) DescribeClusters(input *DescribeClustersInput) (*DescribeClus // return pageNum <= 3 // }) // -func (c *Redshift) DescribeClustersPages(input *DescribeClustersInput, fn func(p *DescribeClustersOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.DescribeClustersRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*DescribeClustersOutput), lastPage) - }) +func (c *Redshift) DescribeClustersPages(input *DescribeClustersInput, fn func(*DescribeClustersOutput, bool) bool) error { + return c.DescribeClustersPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// DescribeClustersPagesWithContext same as DescribeClustersPages 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 *Redshift) DescribeClustersPagesWithContext(ctx aws.Context, input *DescribeClustersInput, fn func(*DescribeClustersOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *DescribeClustersInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeClustersRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*DescribeClustersOutput), !p.HasNextPage()) + } + return p.Err() } const opDescribeDefaultClusterParameters = "DescribeDefaultClusterParameters" @@ -2828,8 +3453,23 @@ func (c *Redshift) DescribeDefaultClusterParametersRequest(input *DescribeDefaul // Please also see https://docs.aws.amazon.com/goto/WebAPI/redshift-2012-12-01/DescribeDefaultClusterParameters func (c *Redshift) DescribeDefaultClusterParameters(input *DescribeDefaultClusterParametersInput) (*DescribeDefaultClusterParametersOutput, error) { req, out := c.DescribeDefaultClusterParametersRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeDefaultClusterParametersWithContext is the same as DescribeDefaultClusterParameters with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeDefaultClusterParameters 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 *Redshift) DescribeDefaultClusterParametersWithContext(ctx aws.Context, input *DescribeDefaultClusterParametersInput, opts ...request.Option) (*DescribeDefaultClusterParametersOutput, error) { + req, out := c.DescribeDefaultClusterParametersRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // DescribeDefaultClusterParametersPages iterates over the pages of a DescribeDefaultClusterParameters operation, @@ -2849,12 +3489,37 @@ func (c *Redshift) DescribeDefaultClusterParameters(input *DescribeDefaultCluste // return pageNum <= 3 // }) // -func (c *Redshift) DescribeDefaultClusterParametersPages(input *DescribeDefaultClusterParametersInput, fn func(p *DescribeDefaultClusterParametersOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.DescribeDefaultClusterParametersRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*DescribeDefaultClusterParametersOutput), lastPage) - }) +func (c *Redshift) DescribeDefaultClusterParametersPages(input *DescribeDefaultClusterParametersInput, fn func(*DescribeDefaultClusterParametersOutput, bool) bool) error { + return c.DescribeDefaultClusterParametersPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// DescribeDefaultClusterParametersPagesWithContext same as DescribeDefaultClusterParametersPages 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 *Redshift) DescribeDefaultClusterParametersPagesWithContext(ctx aws.Context, input *DescribeDefaultClusterParametersInput, fn func(*DescribeDefaultClusterParametersOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *DescribeDefaultClusterParametersInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeDefaultClusterParametersRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*DescribeDefaultClusterParametersOutput), !p.HasNextPage()) + } + return p.Err() } const opDescribeEventCategories = "DescribeEventCategories" @@ -2915,8 +3580,23 @@ func (c *Redshift) DescribeEventCategoriesRequest(input *DescribeEventCategories // Please also see https://docs.aws.amazon.com/goto/WebAPI/redshift-2012-12-01/DescribeEventCategories func (c *Redshift) DescribeEventCategories(input *DescribeEventCategoriesInput) (*DescribeEventCategoriesOutput, error) { req, out := c.DescribeEventCategoriesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeEventCategoriesWithContext is the same as DescribeEventCategories with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeEventCategories 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 *Redshift) DescribeEventCategoriesWithContext(ctx aws.Context, input *DescribeEventCategoriesInput, opts ...request.Option) (*DescribeEventCategoriesOutput, error) { + req, out := c.DescribeEventCategoriesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeEventSubscriptions = "DescribeEventSubscriptions" @@ -2989,8 +3669,23 @@ func (c *Redshift) DescribeEventSubscriptionsRequest(input *DescribeEventSubscri // Please also see https://docs.aws.amazon.com/goto/WebAPI/redshift-2012-12-01/DescribeEventSubscriptions func (c *Redshift) DescribeEventSubscriptions(input *DescribeEventSubscriptionsInput) (*DescribeEventSubscriptionsOutput, error) { req, out := c.DescribeEventSubscriptionsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeEventSubscriptionsWithContext is the same as DescribeEventSubscriptions with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeEventSubscriptions 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 *Redshift) DescribeEventSubscriptionsWithContext(ctx aws.Context, input *DescribeEventSubscriptionsInput, opts ...request.Option) (*DescribeEventSubscriptionsOutput, error) { + req, out := c.DescribeEventSubscriptionsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // DescribeEventSubscriptionsPages iterates over the pages of a DescribeEventSubscriptions operation, @@ -3010,12 +3705,37 @@ func (c *Redshift) DescribeEventSubscriptions(input *DescribeEventSubscriptionsI // return pageNum <= 3 // }) // -func (c *Redshift) DescribeEventSubscriptionsPages(input *DescribeEventSubscriptionsInput, fn func(p *DescribeEventSubscriptionsOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.DescribeEventSubscriptionsRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*DescribeEventSubscriptionsOutput), lastPage) - }) +func (c *Redshift) DescribeEventSubscriptionsPages(input *DescribeEventSubscriptionsInput, fn func(*DescribeEventSubscriptionsOutput, bool) bool) error { + return c.DescribeEventSubscriptionsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// DescribeEventSubscriptionsPagesWithContext same as DescribeEventSubscriptionsPages 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 *Redshift) DescribeEventSubscriptionsPagesWithContext(ctx aws.Context, input *DescribeEventSubscriptionsInput, fn func(*DescribeEventSubscriptionsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *DescribeEventSubscriptionsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeEventSubscriptionsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*DescribeEventSubscriptionsOutput), !p.HasNextPage()) + } + return p.Err() } const opDescribeEvents = "DescribeEvents" @@ -3083,8 +3803,23 @@ func (c *Redshift) DescribeEventsRequest(input *DescribeEventsInput) (req *reque // Please also see https://docs.aws.amazon.com/goto/WebAPI/redshift-2012-12-01/DescribeEvents func (c *Redshift) DescribeEvents(input *DescribeEventsInput) (*DescribeEventsOutput, error) { req, out := c.DescribeEventsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeEventsWithContext is the same as DescribeEvents with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeEvents 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 *Redshift) DescribeEventsWithContext(ctx aws.Context, input *DescribeEventsInput, opts ...request.Option) (*DescribeEventsOutput, error) { + req, out := c.DescribeEventsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // DescribeEventsPages iterates over the pages of a DescribeEvents operation, @@ -3104,12 +3839,37 @@ func (c *Redshift) DescribeEvents(input *DescribeEventsInput) (*DescribeEventsOu // return pageNum <= 3 // }) // -func (c *Redshift) DescribeEventsPages(input *DescribeEventsInput, fn func(p *DescribeEventsOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.DescribeEventsRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*DescribeEventsOutput), lastPage) - }) +func (c *Redshift) DescribeEventsPages(input *DescribeEventsInput, fn func(*DescribeEventsOutput, bool) bool) error { + return c.DescribeEventsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// DescribeEventsPagesWithContext same as DescribeEventsPages 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 *Redshift) DescribeEventsPagesWithContext(ctx aws.Context, input *DescribeEventsInput, fn func(*DescribeEventsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *DescribeEventsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeEventsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*DescribeEventsOutput), !p.HasNextPage()) + } + return p.Err() } const opDescribeHsmClientCertificates = "DescribeHsmClientCertificates" @@ -3194,8 +3954,23 @@ func (c *Redshift) DescribeHsmClientCertificatesRequest(input *DescribeHsmClient // Please also see https://docs.aws.amazon.com/goto/WebAPI/redshift-2012-12-01/DescribeHsmClientCertificates func (c *Redshift) DescribeHsmClientCertificates(input *DescribeHsmClientCertificatesInput) (*DescribeHsmClientCertificatesOutput, error) { req, out := c.DescribeHsmClientCertificatesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeHsmClientCertificatesWithContext is the same as DescribeHsmClientCertificates with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeHsmClientCertificates 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 *Redshift) DescribeHsmClientCertificatesWithContext(ctx aws.Context, input *DescribeHsmClientCertificatesInput, opts ...request.Option) (*DescribeHsmClientCertificatesOutput, error) { + req, out := c.DescribeHsmClientCertificatesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // DescribeHsmClientCertificatesPages iterates over the pages of a DescribeHsmClientCertificates operation, @@ -3215,12 +3990,37 @@ func (c *Redshift) DescribeHsmClientCertificates(input *DescribeHsmClientCertifi // return pageNum <= 3 // }) // -func (c *Redshift) DescribeHsmClientCertificatesPages(input *DescribeHsmClientCertificatesInput, fn func(p *DescribeHsmClientCertificatesOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.DescribeHsmClientCertificatesRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*DescribeHsmClientCertificatesOutput), lastPage) - }) +func (c *Redshift) DescribeHsmClientCertificatesPages(input *DescribeHsmClientCertificatesInput, fn func(*DescribeHsmClientCertificatesOutput, bool) bool) error { + return c.DescribeHsmClientCertificatesPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// DescribeHsmClientCertificatesPagesWithContext same as DescribeHsmClientCertificatesPages 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 *Redshift) DescribeHsmClientCertificatesPagesWithContext(ctx aws.Context, input *DescribeHsmClientCertificatesInput, fn func(*DescribeHsmClientCertificatesOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *DescribeHsmClientCertificatesInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeHsmClientCertificatesRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*DescribeHsmClientCertificatesOutput), !p.HasNextPage()) + } + return p.Err() } const opDescribeHsmConfigurations = "DescribeHsmConfigurations" @@ -3305,8 +4105,23 @@ func (c *Redshift) DescribeHsmConfigurationsRequest(input *DescribeHsmConfigurat // Please also see https://docs.aws.amazon.com/goto/WebAPI/redshift-2012-12-01/DescribeHsmConfigurations func (c *Redshift) DescribeHsmConfigurations(input *DescribeHsmConfigurationsInput) (*DescribeHsmConfigurationsOutput, error) { req, out := c.DescribeHsmConfigurationsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeHsmConfigurationsWithContext is the same as DescribeHsmConfigurations with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeHsmConfigurations 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 *Redshift) DescribeHsmConfigurationsWithContext(ctx aws.Context, input *DescribeHsmConfigurationsInput, opts ...request.Option) (*DescribeHsmConfigurationsOutput, error) { + req, out := c.DescribeHsmConfigurationsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // DescribeHsmConfigurationsPages iterates over the pages of a DescribeHsmConfigurations operation, @@ -3326,12 +4141,37 @@ func (c *Redshift) DescribeHsmConfigurations(input *DescribeHsmConfigurationsInp // return pageNum <= 3 // }) // -func (c *Redshift) DescribeHsmConfigurationsPages(input *DescribeHsmConfigurationsInput, fn func(p *DescribeHsmConfigurationsOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.DescribeHsmConfigurationsRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*DescribeHsmConfigurationsOutput), lastPage) - }) +func (c *Redshift) DescribeHsmConfigurationsPages(input *DescribeHsmConfigurationsInput, fn func(*DescribeHsmConfigurationsOutput, bool) bool) error { + return c.DescribeHsmConfigurationsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// DescribeHsmConfigurationsPagesWithContext same as DescribeHsmConfigurationsPages 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 *Redshift) DescribeHsmConfigurationsPagesWithContext(ctx aws.Context, input *DescribeHsmConfigurationsInput, fn func(*DescribeHsmConfigurationsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *DescribeHsmConfigurationsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeHsmConfigurationsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*DescribeHsmConfigurationsOutput), !p.HasNextPage()) + } + return p.Err() } const opDescribeLoggingStatus = "DescribeLoggingStatus" @@ -3396,8 +4236,23 @@ func (c *Redshift) DescribeLoggingStatusRequest(input *DescribeLoggingStatusInpu // Please also see https://docs.aws.amazon.com/goto/WebAPI/redshift-2012-12-01/DescribeLoggingStatus func (c *Redshift) DescribeLoggingStatus(input *DescribeLoggingStatusInput) (*LoggingStatus, error) { req, out := c.DescribeLoggingStatusRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeLoggingStatusWithContext is the same as DescribeLoggingStatus with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeLoggingStatus 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 *Redshift) DescribeLoggingStatusWithContext(ctx aws.Context, input *DescribeLoggingStatusInput, opts ...request.Option) (*LoggingStatus, error) { + req, out := c.DescribeLoggingStatusRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeOrderableClusterOptions = "DescribeOrderableClusterOptions" @@ -3470,8 +4325,23 @@ func (c *Redshift) DescribeOrderableClusterOptionsRequest(input *DescribeOrderab // Please also see https://docs.aws.amazon.com/goto/WebAPI/redshift-2012-12-01/DescribeOrderableClusterOptions func (c *Redshift) DescribeOrderableClusterOptions(input *DescribeOrderableClusterOptionsInput) (*DescribeOrderableClusterOptionsOutput, error) { req, out := c.DescribeOrderableClusterOptionsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeOrderableClusterOptionsWithContext is the same as DescribeOrderableClusterOptions with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeOrderableClusterOptions 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 *Redshift) DescribeOrderableClusterOptionsWithContext(ctx aws.Context, input *DescribeOrderableClusterOptionsInput, opts ...request.Option) (*DescribeOrderableClusterOptionsOutput, error) { + req, out := c.DescribeOrderableClusterOptionsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // DescribeOrderableClusterOptionsPages iterates over the pages of a DescribeOrderableClusterOptions operation, @@ -3491,12 +4361,37 @@ func (c *Redshift) DescribeOrderableClusterOptions(input *DescribeOrderableClust // return pageNum <= 3 // }) // -func (c *Redshift) DescribeOrderableClusterOptionsPages(input *DescribeOrderableClusterOptionsInput, fn func(p *DescribeOrderableClusterOptionsOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.DescribeOrderableClusterOptionsRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*DescribeOrderableClusterOptionsOutput), lastPage) - }) +func (c *Redshift) DescribeOrderableClusterOptionsPages(input *DescribeOrderableClusterOptionsInput, fn func(*DescribeOrderableClusterOptionsOutput, bool) bool) error { + return c.DescribeOrderableClusterOptionsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// DescribeOrderableClusterOptionsPagesWithContext same as DescribeOrderableClusterOptionsPages 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 *Redshift) DescribeOrderableClusterOptionsPagesWithContext(ctx aws.Context, input *DescribeOrderableClusterOptionsInput, fn func(*DescribeOrderableClusterOptionsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *DescribeOrderableClusterOptionsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeOrderableClusterOptionsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*DescribeOrderableClusterOptionsOutput), !p.HasNextPage()) + } + return p.Err() } const opDescribeReservedNodeOfferings = "DescribeReservedNodeOfferings" @@ -3575,11 +4470,30 @@ func (c *Redshift) DescribeReservedNodeOfferingsRequest(input *DescribeReservedN // * ErrCodeUnsupportedOperationFault "UnsupportedOperation" // The requested operation isn't supported. // +// * ErrCodeDependentServiceUnavailableFault "DependentServiceUnavailableFault" +// Your request cannot be completed because a dependent internal service is +// temporarily unavailable. Wait 30 to 60 seconds and try again. +// // Please also see https://docs.aws.amazon.com/goto/WebAPI/redshift-2012-12-01/DescribeReservedNodeOfferings func (c *Redshift) DescribeReservedNodeOfferings(input *DescribeReservedNodeOfferingsInput) (*DescribeReservedNodeOfferingsOutput, error) { req, out := c.DescribeReservedNodeOfferingsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeReservedNodeOfferingsWithContext is the same as DescribeReservedNodeOfferings with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeReservedNodeOfferings 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 *Redshift) DescribeReservedNodeOfferingsWithContext(ctx aws.Context, input *DescribeReservedNodeOfferingsInput, opts ...request.Option) (*DescribeReservedNodeOfferingsOutput, error) { + req, out := c.DescribeReservedNodeOfferingsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // DescribeReservedNodeOfferingsPages iterates over the pages of a DescribeReservedNodeOfferings operation, @@ -3599,12 +4513,37 @@ func (c *Redshift) DescribeReservedNodeOfferings(input *DescribeReservedNodeOffe // return pageNum <= 3 // }) // -func (c *Redshift) DescribeReservedNodeOfferingsPages(input *DescribeReservedNodeOfferingsInput, fn func(p *DescribeReservedNodeOfferingsOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.DescribeReservedNodeOfferingsRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*DescribeReservedNodeOfferingsOutput), lastPage) - }) +func (c *Redshift) DescribeReservedNodeOfferingsPages(input *DescribeReservedNodeOfferingsInput, fn func(*DescribeReservedNodeOfferingsOutput, bool) bool) error { + return c.DescribeReservedNodeOfferingsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// DescribeReservedNodeOfferingsPagesWithContext same as DescribeReservedNodeOfferingsPages 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 *Redshift) DescribeReservedNodeOfferingsPagesWithContext(ctx aws.Context, input *DescribeReservedNodeOfferingsInput, fn func(*DescribeReservedNodeOfferingsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *DescribeReservedNodeOfferingsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeReservedNodeOfferingsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*DescribeReservedNodeOfferingsOutput), !p.HasNextPage()) + } + return p.Err() } const opDescribeReservedNodes = "DescribeReservedNodes" @@ -3671,11 +4610,30 @@ func (c *Redshift) DescribeReservedNodesRequest(input *DescribeReservedNodesInpu // * ErrCodeReservedNodeNotFoundFault "ReservedNodeNotFound" // The specified reserved compute node not found. // +// * ErrCodeDependentServiceUnavailableFault "DependentServiceUnavailableFault" +// Your request cannot be completed because a dependent internal service is +// temporarily unavailable. Wait 30 to 60 seconds and try again. +// // Please also see https://docs.aws.amazon.com/goto/WebAPI/redshift-2012-12-01/DescribeReservedNodes func (c *Redshift) DescribeReservedNodes(input *DescribeReservedNodesInput) (*DescribeReservedNodesOutput, error) { req, out := c.DescribeReservedNodesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeReservedNodesWithContext is the same as DescribeReservedNodes with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeReservedNodes 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 *Redshift) DescribeReservedNodesWithContext(ctx aws.Context, input *DescribeReservedNodesInput, opts ...request.Option) (*DescribeReservedNodesOutput, error) { + req, out := c.DescribeReservedNodesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // DescribeReservedNodesPages iterates over the pages of a DescribeReservedNodes operation, @@ -3695,12 +4653,37 @@ func (c *Redshift) DescribeReservedNodes(input *DescribeReservedNodesInput) (*De // return pageNum <= 3 // }) // -func (c *Redshift) DescribeReservedNodesPages(input *DescribeReservedNodesInput, fn func(p *DescribeReservedNodesOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.DescribeReservedNodesRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*DescribeReservedNodesOutput), lastPage) - }) +func (c *Redshift) DescribeReservedNodesPages(input *DescribeReservedNodesInput, fn func(*DescribeReservedNodesOutput, bool) bool) error { + return c.DescribeReservedNodesPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// DescribeReservedNodesPagesWithContext same as DescribeReservedNodesPages 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 *Redshift) DescribeReservedNodesPagesWithContext(ctx aws.Context, input *DescribeReservedNodesInput, fn func(*DescribeReservedNodesOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *DescribeReservedNodesInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeReservedNodesRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*DescribeReservedNodesOutput), !p.HasNextPage()) + } + return p.Err() } const opDescribeResize = "DescribeResize" @@ -3773,8 +4756,23 @@ func (c *Redshift) DescribeResizeRequest(input *DescribeResizeInput) (req *reque // Please also see https://docs.aws.amazon.com/goto/WebAPI/redshift-2012-12-01/DescribeResize func (c *Redshift) DescribeResize(input *DescribeResizeInput) (*DescribeResizeOutput, error) { req, out := c.DescribeResizeRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeResizeWithContext is the same as DescribeResize with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeResize 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 *Redshift) DescribeResizeWithContext(ctx aws.Context, input *DescribeResizeInput, opts ...request.Option) (*DescribeResizeOutput, error) { + req, out := c.DescribeResizeRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeSnapshotCopyGrants = "DescribeSnapshotCopyGrants" @@ -3847,8 +4845,23 @@ func (c *Redshift) DescribeSnapshotCopyGrantsRequest(input *DescribeSnapshotCopy // Please also see https://docs.aws.amazon.com/goto/WebAPI/redshift-2012-12-01/DescribeSnapshotCopyGrants func (c *Redshift) DescribeSnapshotCopyGrants(input *DescribeSnapshotCopyGrantsInput) (*DescribeSnapshotCopyGrantsOutput, error) { req, out := c.DescribeSnapshotCopyGrantsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeSnapshotCopyGrantsWithContext is the same as DescribeSnapshotCopyGrants with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeSnapshotCopyGrants 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 *Redshift) DescribeSnapshotCopyGrantsWithContext(ctx aws.Context, input *DescribeSnapshotCopyGrantsInput, opts ...request.Option) (*DescribeSnapshotCopyGrantsOutput, error) { + req, out := c.DescribeSnapshotCopyGrantsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeTableRestoreStatus = "DescribeTableRestoreStatus" @@ -3919,8 +4932,23 @@ func (c *Redshift) DescribeTableRestoreStatusRequest(input *DescribeTableRestore // Please also see https://docs.aws.amazon.com/goto/WebAPI/redshift-2012-12-01/DescribeTableRestoreStatus func (c *Redshift) DescribeTableRestoreStatus(input *DescribeTableRestoreStatusInput) (*DescribeTableRestoreStatusOutput, error) { req, out := c.DescribeTableRestoreStatusRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeTableRestoreStatusWithContext is the same as DescribeTableRestoreStatus with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeTableRestoreStatus 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 *Redshift) DescribeTableRestoreStatusWithContext(ctx aws.Context, input *DescribeTableRestoreStatusInput, opts ...request.Option) (*DescribeTableRestoreStatusOutput, error) { + req, out := c.DescribeTableRestoreStatusRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeTags = "DescribeTags" @@ -4009,8 +5037,23 @@ func (c *Redshift) DescribeTagsRequest(input *DescribeTagsInput) (req *request.R // Please also see https://docs.aws.amazon.com/goto/WebAPI/redshift-2012-12-01/DescribeTags func (c *Redshift) DescribeTags(input *DescribeTagsInput) (*DescribeTagsOutput, error) { req, out := c.DescribeTagsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeTagsWithContext is the same as DescribeTags with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeTags 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 *Redshift) DescribeTagsWithContext(ctx aws.Context, input *DescribeTagsInput, opts ...request.Option) (*DescribeTagsOutput, error) { + req, out := c.DescribeTagsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDisableLogging = "DisableLogging" @@ -4075,8 +5118,23 @@ func (c *Redshift) DisableLoggingRequest(input *DisableLoggingInput) (req *reque // Please also see https://docs.aws.amazon.com/goto/WebAPI/redshift-2012-12-01/DisableLogging func (c *Redshift) DisableLogging(input *DisableLoggingInput) (*LoggingStatus, error) { req, out := c.DisableLoggingRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DisableLoggingWithContext is the same as DisableLogging with the addition of +// the ability to pass a context and additional request options. +// +// See DisableLogging 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 *Redshift) DisableLoggingWithContext(ctx aws.Context, input *DisableLoggingInput, opts ...request.Option) (*LoggingStatus, error) { + req, out := c.DisableLoggingRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDisableSnapshotCopy = "DisableSnapshotCopy" @@ -4154,8 +5212,23 @@ func (c *Redshift) DisableSnapshotCopyRequest(input *DisableSnapshotCopyInput) ( // Please also see https://docs.aws.amazon.com/goto/WebAPI/redshift-2012-12-01/DisableSnapshotCopy func (c *Redshift) DisableSnapshotCopy(input *DisableSnapshotCopyInput) (*DisableSnapshotCopyOutput, error) { req, out := c.DisableSnapshotCopyRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DisableSnapshotCopyWithContext is the same as DisableSnapshotCopy with the addition of +// the ability to pass a context and additional request options. +// +// See DisableSnapshotCopy 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 *Redshift) DisableSnapshotCopyWithContext(ctx aws.Context, input *DisableSnapshotCopyInput, opts ...request.Option) (*DisableSnapshotCopyOutput, error) { + req, out := c.DisableSnapshotCopyRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opEnableLogging = "EnableLogging" @@ -4236,8 +5309,23 @@ func (c *Redshift) EnableLoggingRequest(input *EnableLoggingInput) (req *request // Please also see https://docs.aws.amazon.com/goto/WebAPI/redshift-2012-12-01/EnableLogging func (c *Redshift) EnableLogging(input *EnableLoggingInput) (*LoggingStatus, error) { req, out := c.EnableLoggingRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// EnableLoggingWithContext is the same as EnableLogging with the addition of +// the ability to pass a context and additional request options. +// +// See EnableLogging 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 *Redshift) EnableLoggingWithContext(ctx aws.Context, input *EnableLoggingInput, opts ...request.Option) (*LoggingStatus, error) { + req, out := c.EnableLoggingRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opEnableSnapshotCopy = "EnableSnapshotCopy" @@ -4331,8 +5419,128 @@ func (c *Redshift) EnableSnapshotCopyRequest(input *EnableSnapshotCopyInput) (re // Please also see https://docs.aws.amazon.com/goto/WebAPI/redshift-2012-12-01/EnableSnapshotCopy func (c *Redshift) EnableSnapshotCopy(input *EnableSnapshotCopyInput) (*EnableSnapshotCopyOutput, error) { req, out := c.EnableSnapshotCopyRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// EnableSnapshotCopyWithContext is the same as EnableSnapshotCopy with the addition of +// the ability to pass a context and additional request options. +// +// See EnableSnapshotCopy 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 *Redshift) EnableSnapshotCopyWithContext(ctx aws.Context, input *EnableSnapshotCopyInput, opts ...request.Option) (*EnableSnapshotCopyOutput, error) { + req, out := c.EnableSnapshotCopyRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opGetClusterCredentials = "GetClusterCredentials" + +// GetClusterCredentialsRequest generates a "aws/request.Request" representing the +// client's request for the GetClusterCredentials operation. The "output" return +// value can be used to capture response data after the request's "Send" method +// is called. +// +// See GetClusterCredentials for usage and error information. +// +// Creating a request object using this method should be used when you want to inject +// custom logic into the request's lifecycle using a custom handler, or if you want to +// access properties on the request object before or after sending the request. If +// you just want the service response, call the GetClusterCredentials method directly +// instead. +// +// Note: You must call the "Send" method on the returned request object in order +// to execute the request. +// +// // Example sending a request using the GetClusterCredentialsRequest method. +// req, resp := client.GetClusterCredentialsRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/redshift-2012-12-01/GetClusterCredentials +func (c *Redshift) GetClusterCredentialsRequest(input *GetClusterCredentialsInput) (req *request.Request, output *GetClusterCredentialsOutput) { + op := &request.Operation{ + Name: opGetClusterCredentials, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &GetClusterCredentialsInput{} + } + + output = &GetClusterCredentialsOutput{} + req = c.newRequest(op, input, output) + return +} + +// GetClusterCredentials API operation for Amazon Redshift. +// +// Returns a database user name and temporary password with temporary authorization +// to log in to an Amazon Redshift database. The action returns the database +// user name prefixed with IAM: if AutoCreate is False or IAMA: if AutoCreate +// is True. You can optionally specify one or more database user groups that +// the user will join at log in. By default, the temporary credentials expire +// in 900 seconds. You can optionally specify a duration between 900 seconds +// (15 minutes) and 3600 seconds (60 minutes). For more information, see Generating +// IAM Database User Credentials in the Amazon Redshift Cluster Management Guide. +// +// The IAM user or role that executes GetClusterCredentials must have an IAM +// policy attached that allows the redshift:GetClusterCredentials action with +// access to the dbuser resource on the cluster. The user name specified for +// dbuser in the IAM policy and the user name specified for the DbUser parameter +// must match. +// +// If the DbGroups parameter is specified, the IAM policy must allow the redshift:JoinGroup +// action with access to the listed dbgroups. +// +// In addition, if the AutoCreate parameter is set to True, then the policy +// must include the redshift:CreateClusterUser privilege. +// +// If the DbName parameter is specified, the IAM policy must allow access to +// the resource dbname for the specified database name. +// +// 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 Redshift's +// API operation GetClusterCredentials for usage and error information. +// +// Returned Error Codes: +// * ErrCodeClusterNotFoundFault "ClusterNotFound" +// The ClusterIdentifier parameter does not refer to an existing cluster. +// +// * ErrCodeUnsupportedOperationFault "UnsupportedOperation" +// The requested operation isn't supported. +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/redshift-2012-12-01/GetClusterCredentials +func (c *Redshift) GetClusterCredentials(input *GetClusterCredentialsInput) (*GetClusterCredentialsOutput, error) { + req, out := c.GetClusterCredentialsRequest(input) + return out, req.Send() +} + +// GetClusterCredentialsWithContext is the same as GetClusterCredentials with the addition of +// the ability to pass a context and additional request options. +// +// See GetClusterCredentials 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 *Redshift) GetClusterCredentialsWithContext(ctx aws.Context, input *GetClusterCredentialsInput, opts ...request.Option) (*GetClusterCredentialsOutput, error) { + req, out := c.GetClusterCredentialsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opModifyCluster = "ModifyCluster" @@ -4415,6 +5623,9 @@ func (c *Redshift) ModifyClusterRequest(input *ModifyClusterInput) (req *request // (http://docs.aws.amazon.com/redshift/latest/mgmt/amazon-redshift-limits.html) // in the Amazon Redshift Cluster Management Guide. // +// * ErrCodeNumberOfNodesPerClusterLimitExceededFault "NumberOfNodesPerClusterLimitExceeded" +// The operation would exceed the number of nodes allowed for a cluster. +// // * ErrCodeClusterSecurityGroupNotFoundFault "ClusterSecurityGroupNotFound" // The cluster security group name does not refer to an existing cluster security // group. @@ -4453,8 +5664,23 @@ func (c *Redshift) ModifyClusterRequest(input *ModifyClusterInput) (req *request // Please also see https://docs.aws.amazon.com/goto/WebAPI/redshift-2012-12-01/ModifyCluster func (c *Redshift) ModifyCluster(input *ModifyClusterInput) (*ModifyClusterOutput, error) { req, out := c.ModifyClusterRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ModifyClusterWithContext is the same as ModifyCluster with the addition of +// the ability to pass a context and additional request options. +// +// See ModifyCluster 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 *Redshift) ModifyClusterWithContext(ctx aws.Context, input *ModifyClusterInput, opts ...request.Option) (*ModifyClusterOutput, error) { + req, out := c.ModifyClusterRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opModifyClusterIamRoles = "ModifyClusterIamRoles" @@ -4524,8 +5750,23 @@ func (c *Redshift) ModifyClusterIamRolesRequest(input *ModifyClusterIamRolesInpu // Please also see https://docs.aws.amazon.com/goto/WebAPI/redshift-2012-12-01/ModifyClusterIamRoles func (c *Redshift) ModifyClusterIamRoles(input *ModifyClusterIamRolesInput) (*ModifyClusterIamRolesOutput, error) { req, out := c.ModifyClusterIamRolesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ModifyClusterIamRolesWithContext is the same as ModifyClusterIamRoles with the addition of +// the ability to pass a context and additional request options. +// +// See ModifyClusterIamRoles 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 *Redshift) ModifyClusterIamRolesWithContext(ctx aws.Context, input *ModifyClusterIamRolesInput, opts ...request.Option) (*ModifyClusterIamRolesOutput, error) { + req, out := c.ModifyClusterIamRolesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opModifyClusterParameterGroup = "ModifyClusterParameterGroup" @@ -4598,8 +5839,23 @@ func (c *Redshift) ModifyClusterParameterGroupRequest(input *ModifyClusterParame // Please also see https://docs.aws.amazon.com/goto/WebAPI/redshift-2012-12-01/ModifyClusterParameterGroup func (c *Redshift) ModifyClusterParameterGroup(input *ModifyClusterParameterGroupInput) (*ClusterParameterGroupNameMessage, error) { req, out := c.ModifyClusterParameterGroupRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ModifyClusterParameterGroupWithContext is the same as ModifyClusterParameterGroup with the addition of +// the ability to pass a context and additional request options. +// +// See ModifyClusterParameterGroup 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 *Redshift) ModifyClusterParameterGroupWithContext(ctx aws.Context, input *ModifyClusterParameterGroupInput, opts ...request.Option) (*ClusterParameterGroupNameMessage, error) { + req, out := c.ModifyClusterParameterGroupRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opModifyClusterSubnetGroup = "ModifyClusterSubnetGroup" @@ -4686,8 +5942,23 @@ func (c *Redshift) ModifyClusterSubnetGroupRequest(input *ModifyClusterSubnetGro // Please also see https://docs.aws.amazon.com/goto/WebAPI/redshift-2012-12-01/ModifyClusterSubnetGroup func (c *Redshift) ModifyClusterSubnetGroup(input *ModifyClusterSubnetGroupInput) (*ModifyClusterSubnetGroupOutput, error) { req, out := c.ModifyClusterSubnetGroupRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ModifyClusterSubnetGroupWithContext is the same as ModifyClusterSubnetGroup with the addition of +// the ability to pass a context and additional request options. +// +// See ModifyClusterSubnetGroup 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 *Redshift) ModifyClusterSubnetGroupWithContext(ctx aws.Context, input *ModifyClusterSubnetGroupInput, opts ...request.Option) (*ModifyClusterSubnetGroupOutput, error) { + req, out := c.ModifyClusterSubnetGroupRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opModifyEventSubscription = "ModifyEventSubscription" @@ -4783,8 +6054,23 @@ func (c *Redshift) ModifyEventSubscriptionRequest(input *ModifyEventSubscription // Please also see https://docs.aws.amazon.com/goto/WebAPI/redshift-2012-12-01/ModifyEventSubscription func (c *Redshift) ModifyEventSubscription(input *ModifyEventSubscriptionInput) (*ModifyEventSubscriptionOutput, error) { req, out := c.ModifyEventSubscriptionRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ModifyEventSubscriptionWithContext is the same as ModifyEventSubscription with the addition of +// the ability to pass a context and additional request options. +// +// See ModifyEventSubscription 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 *Redshift) ModifyEventSubscriptionWithContext(ctx aws.Context, input *ModifyEventSubscriptionInput, opts ...request.Option) (*ModifyEventSubscriptionOutput, error) { + req, out := c.ModifyEventSubscriptionRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opModifySnapshotCopyRetentionPeriod = "ModifySnapshotCopyRetentionPeriod" @@ -4858,8 +6144,23 @@ func (c *Redshift) ModifySnapshotCopyRetentionPeriodRequest(input *ModifySnapsho // Please also see https://docs.aws.amazon.com/goto/WebAPI/redshift-2012-12-01/ModifySnapshotCopyRetentionPeriod func (c *Redshift) ModifySnapshotCopyRetentionPeriod(input *ModifySnapshotCopyRetentionPeriodInput) (*ModifySnapshotCopyRetentionPeriodOutput, error) { req, out := c.ModifySnapshotCopyRetentionPeriodRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ModifySnapshotCopyRetentionPeriodWithContext is the same as ModifySnapshotCopyRetentionPeriod with the addition of +// the ability to pass a context and additional request options. +// +// See ModifySnapshotCopyRetentionPeriod 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 *Redshift) ModifySnapshotCopyRetentionPeriodWithContext(ctx aws.Context, input *ModifySnapshotCopyRetentionPeriodInput, opts ...request.Option) (*ModifySnapshotCopyRetentionPeriodOutput, error) { + req, out := c.ModifySnapshotCopyRetentionPeriodRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opPurchaseReservedNodeOffering = "PurchaseReservedNodeOffering" @@ -4942,8 +6243,23 @@ func (c *Redshift) PurchaseReservedNodeOfferingRequest(input *PurchaseReservedNo // Please also see https://docs.aws.amazon.com/goto/WebAPI/redshift-2012-12-01/PurchaseReservedNodeOffering func (c *Redshift) PurchaseReservedNodeOffering(input *PurchaseReservedNodeOfferingInput) (*PurchaseReservedNodeOfferingOutput, error) { req, out := c.PurchaseReservedNodeOfferingRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// PurchaseReservedNodeOfferingWithContext is the same as PurchaseReservedNodeOffering with the addition of +// the ability to pass a context and additional request options. +// +// See PurchaseReservedNodeOffering 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 *Redshift) PurchaseReservedNodeOfferingWithContext(ctx aws.Context, input *PurchaseReservedNodeOfferingInput, opts ...request.Option) (*PurchaseReservedNodeOfferingOutput, error) { + req, out := c.PurchaseReservedNodeOfferingRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opRebootCluster = "RebootCluster" @@ -5016,8 +6332,23 @@ func (c *Redshift) RebootClusterRequest(input *RebootClusterInput) (req *request // Please also see https://docs.aws.amazon.com/goto/WebAPI/redshift-2012-12-01/RebootCluster func (c *Redshift) RebootCluster(input *RebootClusterInput) (*RebootClusterOutput, error) { req, out := c.RebootClusterRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// RebootClusterWithContext is the same as RebootCluster with the addition of +// the ability to pass a context and additional request options. +// +// See RebootCluster 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 *Redshift) RebootClusterWithContext(ctx aws.Context, input *RebootClusterInput, opts ...request.Option) (*RebootClusterOutput, error) { + req, out := c.RebootClusterRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opResetClusterParameterGroup = "ResetClusterParameterGroup" @@ -5089,8 +6420,23 @@ func (c *Redshift) ResetClusterParameterGroupRequest(input *ResetClusterParamete // Please also see https://docs.aws.amazon.com/goto/WebAPI/redshift-2012-12-01/ResetClusterParameterGroup func (c *Redshift) ResetClusterParameterGroup(input *ResetClusterParameterGroupInput) (*ClusterParameterGroupNameMessage, error) { req, out := c.ResetClusterParameterGroupRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ResetClusterParameterGroupWithContext is the same as ResetClusterParameterGroup with the addition of +// the ability to pass a context and additional request options. +// +// See ResetClusterParameterGroup 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 *Redshift) ResetClusterParameterGroupWithContext(ctx aws.Context, input *ResetClusterParameterGroupInput, opts ...request.Option) (*ClusterParameterGroupNameMessage, error) { + req, out := c.ResetClusterParameterGroupRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opRestoreFromClusterSnapshot = "RestoreFromClusterSnapshot" @@ -5240,8 +6586,23 @@ func (c *Redshift) RestoreFromClusterSnapshotRequest(input *RestoreFromClusterSn // Please also see https://docs.aws.amazon.com/goto/WebAPI/redshift-2012-12-01/RestoreFromClusterSnapshot func (c *Redshift) RestoreFromClusterSnapshot(input *RestoreFromClusterSnapshotInput) (*RestoreFromClusterSnapshotOutput, error) { req, out := c.RestoreFromClusterSnapshotRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// RestoreFromClusterSnapshotWithContext is the same as RestoreFromClusterSnapshot with the addition of +// the ability to pass a context and additional request options. +// +// See RestoreFromClusterSnapshot 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 *Redshift) RestoreFromClusterSnapshotWithContext(ctx aws.Context, input *RestoreFromClusterSnapshotInput, opts ...request.Option) (*RestoreFromClusterSnapshotOutput, error) { + req, out := c.RestoreFromClusterSnapshotRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opRestoreTableFromClusterSnapshot = "RestoreTableFromClusterSnapshot" @@ -5338,8 +6699,23 @@ func (c *Redshift) RestoreTableFromClusterSnapshotRequest(input *RestoreTableFro // Please also see https://docs.aws.amazon.com/goto/WebAPI/redshift-2012-12-01/RestoreTableFromClusterSnapshot func (c *Redshift) RestoreTableFromClusterSnapshot(input *RestoreTableFromClusterSnapshotInput) (*RestoreTableFromClusterSnapshotOutput, error) { req, out := c.RestoreTableFromClusterSnapshotRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// RestoreTableFromClusterSnapshotWithContext is the same as RestoreTableFromClusterSnapshot with the addition of +// the ability to pass a context and additional request options. +// +// See RestoreTableFromClusterSnapshot 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 *Redshift) RestoreTableFromClusterSnapshotWithContext(ctx aws.Context, input *RestoreTableFromClusterSnapshotInput, opts ...request.Option) (*RestoreTableFromClusterSnapshotOutput, error) { + req, out := c.RestoreTableFromClusterSnapshotRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opRevokeClusterSecurityGroupIngress = "RevokeClusterSecurityGroupIngress" @@ -5415,8 +6791,23 @@ func (c *Redshift) RevokeClusterSecurityGroupIngressRequest(input *RevokeCluster // Please also see https://docs.aws.amazon.com/goto/WebAPI/redshift-2012-12-01/RevokeClusterSecurityGroupIngress func (c *Redshift) RevokeClusterSecurityGroupIngress(input *RevokeClusterSecurityGroupIngressInput) (*RevokeClusterSecurityGroupIngressOutput, error) { req, out := c.RevokeClusterSecurityGroupIngressRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// RevokeClusterSecurityGroupIngressWithContext is the same as RevokeClusterSecurityGroupIngress with the addition of +// the ability to pass a context and additional request options. +// +// See RevokeClusterSecurityGroupIngress 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 *Redshift) RevokeClusterSecurityGroupIngressWithContext(ctx aws.Context, input *RevokeClusterSecurityGroupIngressInput, opts ...request.Option) (*RevokeClusterSecurityGroupIngressOutput, error) { + req, out := c.RevokeClusterSecurityGroupIngressRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opRevokeSnapshotAccess = "RevokeSnapshotAccess" @@ -5494,8 +6885,23 @@ func (c *Redshift) RevokeSnapshotAccessRequest(input *RevokeSnapshotAccessInput) // Please also see https://docs.aws.amazon.com/goto/WebAPI/redshift-2012-12-01/RevokeSnapshotAccess func (c *Redshift) RevokeSnapshotAccess(input *RevokeSnapshotAccessInput) (*RevokeSnapshotAccessOutput, error) { req, out := c.RevokeSnapshotAccessRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// RevokeSnapshotAccessWithContext is the same as RevokeSnapshotAccess with the addition of +// the ability to pass a context and additional request options. +// +// See RevokeSnapshotAccess 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 *Redshift) RevokeSnapshotAccessWithContext(ctx aws.Context, input *RevokeSnapshotAccessInput, opts ...request.Option) (*RevokeSnapshotAccessOutput, error) { + req, out := c.RevokeSnapshotAccessRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opRotateEncryptionKey = "RotateEncryptionKey" @@ -5566,8 +6972,23 @@ func (c *Redshift) RotateEncryptionKeyRequest(input *RotateEncryptionKeyInput) ( // Please also see https://docs.aws.amazon.com/goto/WebAPI/redshift-2012-12-01/RotateEncryptionKey func (c *Redshift) RotateEncryptionKey(input *RotateEncryptionKeyInput) (*RotateEncryptionKeyOutput, error) { req, out := c.RotateEncryptionKeyRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// RotateEncryptionKeyWithContext is the same as RotateEncryptionKey with the addition of +// the ability to pass a context and additional request options. +// +// See RotateEncryptionKey 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 *Redshift) RotateEncryptionKeyWithContext(ctx aws.Context, input *RotateEncryptionKeyInput, opts ...request.Option) (*RotateEncryptionKeyOutput, error) { + req, out := c.RotateEncryptionKeyRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // Describes an AWS customer account authorized to restore a snapshot. @@ -5575,6 +6996,10 @@ func (c *Redshift) RotateEncryptionKey(input *RotateEncryptionKeyInput) (*Rotate type AccountWithRestoreAccess struct { _ struct{} `type:"structure"` + // The identifier of an AWS support account authorized to restore a snapshot. + // For AWS support, the identifier is amazon-redshift-support. + AccountAlias *string `type:"string"` + // The identifier of an AWS customer account authorized to restore a snapshot. AccountId *string `type:"string"` } @@ -5589,6 +7014,12 @@ func (s AccountWithRestoreAccess) GoString() string { return s.String() } +// SetAccountAlias sets the AccountAlias field's value. +func (s *AccountWithRestoreAccess) SetAccountAlias(v string) *AccountWithRestoreAccess { + s.AccountAlias = &v + return s +} + // SetAccountId sets the AccountId field's value. func (s *AccountWithRestoreAccess) SetAccountId(v string) *AccountWithRestoreAccess { s.AccountId = &v @@ -5696,6 +7127,8 @@ type AuthorizeSnapshotAccessInput struct { // The identifier of the AWS customer account authorized to restore the specified // snapshot. // + // To share a snapshot with AWS support, specify amazon-redshift-support. + // // AccountWithRestoreAccess is a required field AccountWithRestoreAccess *string `type:"string" required:"true"` @@ -12178,6 +13611,185 @@ func (s *EventSubscription) SetTags(v []*Tag) *EventSubscription { return s } +// The request parameters to get cluster credentials. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/redshift-2012-12-01/GetClusterCredentialsMessage +type GetClusterCredentialsInput struct { + _ struct{} `type:"structure"` + + // Create a database user with the name specified for DbUser if one does not + // exist. + AutoCreate *bool `type:"boolean"` + + // The unique identifier of the cluster that contains the database for which + // your are requesting credentials. This parameter is case sensitive. + // + // ClusterIdentifier is a required field + ClusterIdentifier *string `type:"string" required:"true"` + + // A list of the names of existing database groups that DbUser will join for + // the current session. If not specified, the new user is added only to PUBLIC. + DbGroups []*string `locationNameList:"DbGroup" type:"list"` + + // The name of a database that DbUser is authorized to log on to. If DbName + // is not specified, DbUser can log in to any existing database. + // + // Constraints: + // + // * Must be 1 to 64 alphanumeric characters or hyphens + // + // * Must contain only lowercase letters. + // + // * Cannot be a reserved word. A list of reserved words can be found in + // Reserved Words (http://docs.aws.amazon.com/redshift/latest/dg/r_pg_keywords.html) + // in the Amazon Redshift Database Developer Guide. + DbName *string `type:"string"` + + // The name of a database user. If a user name matching DbUser exists in the + // database, the temporary user credentials have the same permissions as the + // existing user. If DbUser doesn't exist in the database and Autocreate is + // True, a new user is created using the value for DbUser with PUBLIC permissions. + // If a database user matching the value for DbUser doesn't exist and Autocreate + // is False, then the command succeeds but the connection attempt will fail + // because the user doesn't exist in the database. + // + // For more information, see CREATE USER (http://docs.aws.amazon.com/http:/docs.aws.amazon.com/redshift/latest/dg/r_CREATE_USER.html) + // in the Amazon Redshift Database Developer Guide. + // + // Constraints: + // + // * Must be 1 to 128 alphanumeric characters or hyphens + // + // * Must contain only lowercase letters. + // + // * First character must be a letter. + // + // * Must not contain a colon ( : ) or slash ( / ). + // + // * Cannot be a reserved word. A list of reserved words can be found in + // Reserved Words (http://docs.aws.amazon.com/redshift/latest/dg/r_pg_keywords.html) + // in the Amazon Redshift Database Developer Guide. + // + // DbUser is a required field + DbUser *string `type:"string" required:"true"` + + // The number of seconds until the returned temporary password expires. + // + // Constraint: minimum 900, maximum 3600. + // + // Default: 900 + DurationSeconds *int64 `type:"integer"` +} + +// String returns the string representation +func (s GetClusterCredentialsInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s GetClusterCredentialsInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *GetClusterCredentialsInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "GetClusterCredentialsInput"} + if s.ClusterIdentifier == nil { + invalidParams.Add(request.NewErrParamRequired("ClusterIdentifier")) + } + if s.DbUser == nil { + invalidParams.Add(request.NewErrParamRequired("DbUser")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetAutoCreate sets the AutoCreate field's value. +func (s *GetClusterCredentialsInput) SetAutoCreate(v bool) *GetClusterCredentialsInput { + s.AutoCreate = &v + return s +} + +// SetClusterIdentifier sets the ClusterIdentifier field's value. +func (s *GetClusterCredentialsInput) SetClusterIdentifier(v string) *GetClusterCredentialsInput { + s.ClusterIdentifier = &v + return s +} + +// SetDbGroups sets the DbGroups field's value. +func (s *GetClusterCredentialsInput) SetDbGroups(v []*string) *GetClusterCredentialsInput { + s.DbGroups = v + return s +} + +// SetDbName sets the DbName field's value. +func (s *GetClusterCredentialsInput) SetDbName(v string) *GetClusterCredentialsInput { + s.DbName = &v + return s +} + +// SetDbUser sets the DbUser field's value. +func (s *GetClusterCredentialsInput) SetDbUser(v string) *GetClusterCredentialsInput { + s.DbUser = &v + return s +} + +// SetDurationSeconds sets the DurationSeconds field's value. +func (s *GetClusterCredentialsInput) SetDurationSeconds(v int64) *GetClusterCredentialsInput { + s.DurationSeconds = &v + return s +} + +// Temporary credentials with authorization to log in to an Amazon Redshift +// database. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/redshift-2012-12-01/ClusterCredentials +type GetClusterCredentialsOutput struct { + _ struct{} `type:"structure"` + + // A temporary password that authorizes the user name returned by DbUser to + // log on to the database DbName. + DbPassword *string `type:"string"` + + // A database user name that is authorized to log on to the database DbName + // using the password DbPassword. If the DbGroups parameter is specifed, DbUser + // is added to the listed groups for the current session. The user name is prefixed + // with IAM: for an existing user name or IAMA: if the user was auto-created. + DbUser *string `type:"string"` + + // The date and time DbPassword expires. + Expiration *time.Time `type:"timestamp" timestampFormat:"iso8601"` +} + +// String returns the string representation +func (s GetClusterCredentialsOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s GetClusterCredentialsOutput) GoString() string { + return s.String() +} + +// SetDbPassword sets the DbPassword field's value. +func (s *GetClusterCredentialsOutput) SetDbPassword(v string) *GetClusterCredentialsOutput { + s.DbPassword = &v + return s +} + +// SetDbUser sets the DbUser field's value. +func (s *GetClusterCredentialsOutput) SetDbUser(v string) *GetClusterCredentialsOutput { + s.DbUser = &v + return s +} + +// SetExpiration sets the Expiration field's value. +func (s *GetClusterCredentialsOutput) SetExpiration(v time.Time) *GetClusterCredentialsOutput { + s.Expiration = &v + return s +} + // Returns information about an HSM client certificate. The certificate is stored // in a secure Hardware Storage Module (HSM), and used by the Amazon Redshift // cluster to encrypt data files. diff --git a/vendor/github.com/aws/aws-sdk-go/service/redshift/doc.go b/vendor/github.com/aws/aws-sdk-go/service/redshift/doc.go new file mode 100644 index 000000000..3a3fb7d1e --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/service/redshift/doc.go @@ -0,0 +1,103 @@ +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. + +// Package redshift provides the client and types for making API +// requests to Amazon Redshift. +// +// Overview +// +// This is an interface reference for Amazon Redshift. It contains documentation +// for one of the programming or command line interfaces you can use to manage +// Amazon Redshift clusters. Note that Amazon Redshift is asynchronous, which +// means that some interfaces may require techniques, such as polling or asynchronous +// callback handlers, to determine when a command has been applied. In this +// reference, the parameter descriptions indicate whether a change is applied +// immediately, on the next instance reboot, or during the next maintenance +// window. For a summary of the Amazon Redshift cluster management interfaces, +// go to Using the Amazon Redshift Management Interfaces (http://docs.aws.amazon.com/redshift/latest/mgmt/using-aws-sdk.html). +// +// Amazon Redshift manages all the work of setting up, operating, and scaling +// a data warehouse: provisioning capacity, monitoring and backing up the cluster, +// and applying patches and upgrades to the Amazon Redshift engine. You can +// focus on using your data to acquire new insights for your business and customers. +// +// If you are a first-time user of Amazon Redshift, we recommend that you begin +// by reading the Amazon Redshift Getting Started Guide (http://docs.aws.amazon.com/redshift/latest/gsg/getting-started.html). +// +// If you are a database developer, the Amazon Redshift Database Developer Guide +// (http://docs.aws.amazon.com/redshift/latest/dg/welcome.html) explains how +// to design, build, query, and maintain the databases that make up your data +// warehouse. +// +// See https://docs.aws.amazon.com/goto/WebAPI/redshift-2012-12-01 for more information on this service. +// +// See redshift package documentation for more information. +// https://docs.aws.amazon.com/sdk-for-go/api/service/redshift/ +// +// Using the Client +// +// To use the client for Amazon Redshift you will first need +// to create a new instance of it. +// +// When creating a client for an AWS service you'll first need to have a Session +// already created. The Session provides configuration that can be shared +// between multiple service clients. Additional configuration can be applied to +// the Session and service's client when they are constructed. The aws package's +// Config type contains several fields such as Region for the AWS Region the +// client should make API requests too. The optional Config value can be provided +// as the variadic argument for Sessions and client creation. +// +// Once the service's client is created you can use it to make API requests the +// AWS service. These clients are safe to use concurrently. +// +// // Create a session to share configuration, and load external configuration. +// sess := session.Must(session.NewSession()) +// +// // Create the service's client with the session. +// svc := redshift.New(sess) +// +// See the SDK's documentation for more information on how to use service clients. +// https://docs.aws.amazon.com/sdk-for-go/api/ +// +// See aws package's Config type for more information on configuration options. +// https://docs.aws.amazon.com/sdk-for-go/api/aws/#Config +// +// See the Amazon Redshift client Redshift for more +// information on creating the service's client. +// https://docs.aws.amazon.com/sdk-for-go/api/service/redshift/#New +// +// Once the client is created you can make an API request to the service. +// Each API method takes a input parameter, and returns the service response +// and an error. +// +// The API method will document which error codes the service can be returned +// by the operation if the service models the API operation's errors. These +// errors will also be available as const strings prefixed with "ErrCode". +// +// result, err := svc.AuthorizeClusterSecurityGroupIngress(params) +// if err != nil { +// // Cast err to awserr.Error to handle specific error codes. +// aerr, ok := err.(awserr.Error) +// if ok && aerr.Code() == { +// // Specific error code handling +// } +// return err +// } +// +// fmt.Println("AuthorizeClusterSecurityGroupIngress result:") +// fmt.Println(result) +// +// Using the Client with Context +// +// The service's client also provides methods to make API requests with a Context +// value. This allows you to control the timeout, and cancellation of pending +// requests. These methods also take request Option as variadic parameter to apply +// additional configuration to the API request. +// +// ctx := context.Background() +// +// result, err := svc.AuthorizeClusterSecurityGroupIngressWithContext(ctx, params) +// +// See the request package documentation for more information on using Context pattern +// with the SDK. +// https://docs.aws.amazon.com/sdk-for-go/api/aws/request/ +package redshift diff --git a/vendor/github.com/aws/aws-sdk-go/service/redshift/errors.go b/vendor/github.com/aws/aws-sdk-go/service/redshift/errors.go index b59f68d88..8b0570fe3 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/redshift/errors.go +++ b/vendor/github.com/aws/aws-sdk-go/service/redshift/errors.go @@ -1,4 +1,4 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. package redshift @@ -165,6 +165,13 @@ const ( // requests made by Amazon Redshift on your behalf. Wait and retry the request. ErrCodeDependentServiceRequestThrottlingFault = "DependentServiceRequestThrottlingFault" + // ErrCodeDependentServiceUnavailableFault for service response error code + // "DependentServiceUnavailableFault". + // + // Your request cannot be completed because a dependent internal service is + // temporarily unavailable. Wait 30 to 60 seconds and try again. + ErrCodeDependentServiceUnavailableFault = "DependentServiceUnavailableFault" + // ErrCodeEventSubscriptionQuotaExceededFault for service response error code // "EventSubscriptionQuotaExceeded". // diff --git a/vendor/github.com/aws/aws-sdk-go/service/redshift/service.go b/vendor/github.com/aws/aws-sdk-go/service/redshift/service.go index 904e408df..b859170a4 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/redshift/service.go +++ b/vendor/github.com/aws/aws-sdk-go/service/redshift/service.go @@ -1,4 +1,4 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. package redshift @@ -11,33 +11,12 @@ import ( "github.com/aws/aws-sdk-go/private/protocol/query" ) -// Overview +// Redshift provides the API operation methods for making requests to +// Amazon Redshift. See this package's package overview docs +// for details on the service. // -// This is an interface reference for Amazon Redshift. It contains documentation -// for one of the programming or command line interfaces you can use to manage -// Amazon Redshift clusters. Note that Amazon Redshift is asynchronous, which -// means that some interfaces may require techniques, such as polling or asynchronous -// callback handlers, to determine when a command has been applied. In this -// reference, the parameter descriptions indicate whether a change is applied -// immediately, on the next instance reboot, or during the next maintenance -// window. For a summary of the Amazon Redshift cluster management interfaces, -// go to Using the Amazon Redshift Management Interfaces (http://docs.aws.amazon.com/redshift/latest/mgmt/using-aws-sdk.html). -// -// Amazon Redshift manages all the work of setting up, operating, and scaling -// a data warehouse: provisioning capacity, monitoring and backing up the cluster, -// and applying patches and upgrades to the Amazon Redshift engine. You can -// focus on using your data to acquire new insights for your business and customers. -// -// If you are a first-time user of Amazon Redshift, we recommend that you begin -// by reading the Amazon Redshift Getting Started Guide (http://docs.aws.amazon.com/redshift/latest/gsg/getting-started.html). -// -// If you are a database developer, the Amazon Redshift Database Developer Guide -// (http://docs.aws.amazon.com/redshift/latest/dg/welcome.html) explains how -// to design, build, query, and maintain the databases that make up your data -// warehouse. -// The service client's operations are safe to be used concurrently. -// It is not safe to mutate any of the client's properties though. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/redshift-2012-12-01 +// Redshift methods are safe to use concurrently. It is not safe to +// modify mutate any of the struct's properties though. type Redshift struct { *client.Client } diff --git a/vendor/github.com/aws/aws-sdk-go/service/redshift/waiters.go b/vendor/github.com/aws/aws-sdk-go/service/redshift/waiters.go index 59e26ed59..21ce4ee92 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/redshift/waiters.go +++ b/vendor/github.com/aws/aws-sdk-go/service/redshift/waiters.go @@ -1,9 +1,12 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. package redshift import ( - "github.com/aws/aws-sdk-go/private/waiter" + "time" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/request" ) // WaitUntilClusterAvailable uses the Amazon Redshift API operation @@ -11,38 +14,55 @@ import ( // If the condition is not meet within the max attempt window an error will // be returned. func (c *Redshift) WaitUntilClusterAvailable(input *DescribeClustersInput) error { - waiterCfg := waiter.Config{ - Operation: "DescribeClusters", - Delay: 60, + return c.WaitUntilClusterAvailableWithContext(aws.BackgroundContext(), input) +} + +// WaitUntilClusterAvailableWithContext is an extended version of WaitUntilClusterAvailable. +// 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 *Redshift) WaitUntilClusterAvailableWithContext(ctx aws.Context, input *DescribeClustersInput, opts ...request.WaiterOption) error { + w := request.Waiter{ + Name: "WaitUntilClusterAvailable", MaxAttempts: 30, - Acceptors: []waiter.WaitAcceptor{ + Delay: request.ConstantWaiterDelay(60 * time.Second), + Acceptors: []request.WaiterAcceptor{ { - State: "success", - Matcher: "pathAll", - Argument: "Clusters[].ClusterStatus", + State: request.SuccessWaiterState, + Matcher: request.PathAllWaiterMatch, Argument: "Clusters[].ClusterStatus", Expected: "available", }, { - State: "failure", - Matcher: "pathAny", - Argument: "Clusters[].ClusterStatus", + State: request.FailureWaiterState, + Matcher: request.PathAnyWaiterMatch, Argument: "Clusters[].ClusterStatus", Expected: "deleting", }, { - State: "retry", - Matcher: "error", - Argument: "", + State: request.RetryWaiterState, + Matcher: request.ErrorWaiterMatch, Expected: "ClusterNotFound", }, }, + Logger: c.Config.Logger, + NewRequest: func(opts []request.Option) (*request.Request, error) { + var inCpy *DescribeClustersInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeClustersRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, } + w.ApplyOptions(opts...) - w := waiter.Waiter{ - Client: c, - Input: input, - Config: waiterCfg, - } - return w.Wait() + return w.WaitWithContext(ctx) } // WaitUntilClusterDeleted uses the Amazon Redshift API operation @@ -50,38 +70,55 @@ func (c *Redshift) WaitUntilClusterAvailable(input *DescribeClustersInput) error // If the condition is not meet within the max attempt window an error will // be returned. func (c *Redshift) WaitUntilClusterDeleted(input *DescribeClustersInput) error { - waiterCfg := waiter.Config{ - Operation: "DescribeClusters", - Delay: 60, + return c.WaitUntilClusterDeletedWithContext(aws.BackgroundContext(), input) +} + +// WaitUntilClusterDeletedWithContext is an extended version of WaitUntilClusterDeleted. +// 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 *Redshift) WaitUntilClusterDeletedWithContext(ctx aws.Context, input *DescribeClustersInput, opts ...request.WaiterOption) error { + w := request.Waiter{ + Name: "WaitUntilClusterDeleted", MaxAttempts: 30, - Acceptors: []waiter.WaitAcceptor{ + Delay: request.ConstantWaiterDelay(60 * time.Second), + Acceptors: []request.WaiterAcceptor{ { - State: "success", - Matcher: "error", - Argument: "", + State: request.SuccessWaiterState, + Matcher: request.ErrorWaiterMatch, Expected: "ClusterNotFound", }, { - State: "failure", - Matcher: "pathAny", - Argument: "Clusters[].ClusterStatus", + State: request.FailureWaiterState, + Matcher: request.PathAnyWaiterMatch, Argument: "Clusters[].ClusterStatus", Expected: "creating", }, { - State: "failure", - Matcher: "pathAny", - Argument: "Clusters[].ClusterStatus", + State: request.FailureWaiterState, + Matcher: request.PathAnyWaiterMatch, Argument: "Clusters[].ClusterStatus", Expected: "modifying", }, }, + Logger: c.Config.Logger, + NewRequest: func(opts []request.Option) (*request.Request, error) { + var inCpy *DescribeClustersInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeClustersRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, } + w.ApplyOptions(opts...) - w := waiter.Waiter{ - Client: c, - Input: input, - Config: waiterCfg, - } - return w.Wait() + return w.WaitWithContext(ctx) } // WaitUntilClusterRestored uses the Amazon Redshift API operation @@ -89,32 +126,50 @@ func (c *Redshift) WaitUntilClusterDeleted(input *DescribeClustersInput) error { // If the condition is not meet within the max attempt window an error will // be returned. func (c *Redshift) WaitUntilClusterRestored(input *DescribeClustersInput) error { - waiterCfg := waiter.Config{ - Operation: "DescribeClusters", - Delay: 60, + return c.WaitUntilClusterRestoredWithContext(aws.BackgroundContext(), input) +} + +// WaitUntilClusterRestoredWithContext is an extended version of WaitUntilClusterRestored. +// 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 *Redshift) WaitUntilClusterRestoredWithContext(ctx aws.Context, input *DescribeClustersInput, opts ...request.WaiterOption) error { + w := request.Waiter{ + Name: "WaitUntilClusterRestored", MaxAttempts: 30, - Acceptors: []waiter.WaitAcceptor{ + Delay: request.ConstantWaiterDelay(60 * time.Second), + Acceptors: []request.WaiterAcceptor{ { - State: "success", - Matcher: "pathAll", - Argument: "Clusters[].RestoreStatus.Status", + State: request.SuccessWaiterState, + Matcher: request.PathAllWaiterMatch, Argument: "Clusters[].RestoreStatus.Status", Expected: "completed", }, { - State: "failure", - Matcher: "pathAny", - Argument: "Clusters[].ClusterStatus", + State: request.FailureWaiterState, + Matcher: request.PathAnyWaiterMatch, Argument: "Clusters[].ClusterStatus", Expected: "deleting", }, }, + Logger: c.Config.Logger, + NewRequest: func(opts []request.Option) (*request.Request, error) { + var inCpy *DescribeClustersInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeClustersRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, } + w.ApplyOptions(opts...) - w := waiter.Waiter{ - Client: c, - Input: input, - Config: waiterCfg, - } - return w.Wait() + return w.WaitWithContext(ctx) } // WaitUntilSnapshotAvailable uses the Amazon Redshift API operation @@ -122,36 +177,53 @@ func (c *Redshift) WaitUntilClusterRestored(input *DescribeClustersInput) error // If the condition is not meet within the max attempt window an error will // be returned. func (c *Redshift) WaitUntilSnapshotAvailable(input *DescribeClusterSnapshotsInput) error { - waiterCfg := waiter.Config{ - Operation: "DescribeClusterSnapshots", - Delay: 15, + return c.WaitUntilSnapshotAvailableWithContext(aws.BackgroundContext(), input) +} + +// WaitUntilSnapshotAvailableWithContext is an extended version of WaitUntilSnapshotAvailable. +// 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 *Redshift) WaitUntilSnapshotAvailableWithContext(ctx aws.Context, input *DescribeClusterSnapshotsInput, opts ...request.WaiterOption) error { + w := request.Waiter{ + Name: "WaitUntilSnapshotAvailable", MaxAttempts: 20, - Acceptors: []waiter.WaitAcceptor{ + Delay: request.ConstantWaiterDelay(15 * time.Second), + Acceptors: []request.WaiterAcceptor{ { - State: "success", - Matcher: "pathAll", - Argument: "Snapshots[].Status", + State: request.SuccessWaiterState, + Matcher: request.PathAllWaiterMatch, Argument: "Snapshots[].Status", Expected: "available", }, { - State: "failure", - Matcher: "pathAny", - Argument: "Snapshots[].Status", + State: request.FailureWaiterState, + Matcher: request.PathAnyWaiterMatch, Argument: "Snapshots[].Status", Expected: "failed", }, { - State: "failure", - Matcher: "pathAny", - Argument: "Snapshots[].Status", + State: request.FailureWaiterState, + Matcher: request.PathAnyWaiterMatch, Argument: "Snapshots[].Status", Expected: "deleted", }, }, + Logger: c.Config.Logger, + NewRequest: func(opts []request.Option) (*request.Request, error) { + var inCpy *DescribeClusterSnapshotsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeClusterSnapshotsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, } + w.ApplyOptions(opts...) - w := waiter.Waiter{ - Client: c, - Input: input, - Config: waiterCfg, - } - return w.Wait() + return w.WaitWithContext(ctx) } diff --git a/vendor/github.com/aws/aws-sdk-go/service/route53/api.go b/vendor/github.com/aws/aws-sdk-go/service/route53/api.go index acbc1eaab..df9f44ffa 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/route53/api.go +++ b/vendor/github.com/aws/aws-sdk-go/service/route53/api.go @@ -1,12 +1,12 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. -// Package route53 provides a client for Amazon Route 53. package route53 import ( "fmt" "time" + "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awsutil" "github.com/aws/aws-sdk-go/aws/request" ) @@ -61,11 +61,6 @@ func (c *Route53) AssociateVPCWithHostedZoneRequest(input *AssociateVPCWithHoste // To perform the association, the VPC and the private hosted zone must already // exist. You can't convert a public hosted zone into a private hosted zone. // -// Send a POST request to the /2013-04-01/hostedzone/hosted zone ID/associatevpc -// resource. The request body must include a document with an AssociateVPCWithHostedZoneRequest -// element. The response contains a ChangeInfo data type that you can use to -// track the progress of the request. -// // If you want to associate a VPC that was created by using one AWS account // with a private hosted zone that was created by using a different account, // the AWS account that created the private hosted zone must first submit a @@ -111,8 +106,23 @@ func (c *Route53) AssociateVPCWithHostedZoneRequest(input *AssociateVPCWithHoste // Please also see https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/AssociateVPCWithHostedZone func (c *Route53) AssociateVPCWithHostedZone(input *AssociateVPCWithHostedZoneInput) (*AssociateVPCWithHostedZoneOutput, error) { req, out := c.AssociateVPCWithHostedZoneRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// AssociateVPCWithHostedZoneWithContext is the same as AssociateVPCWithHostedZone with the addition of +// the ability to pass a context and additional request options. +// +// See AssociateVPCWithHostedZone 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 *Route53) AssociateVPCWithHostedZoneWithContext(ctx aws.Context, input *AssociateVPCWithHostedZoneInput, opts ...request.Option) (*AssociateVPCWithHostedZoneOutput, error) { + req, out := c.AssociateVPCWithHostedZoneRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opChangeResourceRecordSets = "ChangeResourceRecordSets" @@ -160,10 +170,11 @@ func (c *Route53) ChangeResourceRecordSetsRequest(input *ChangeResourceRecordSet // ChangeResourceRecordSets API operation for Amazon Route 53. // -// Create, change, update, or delete authoritative DNS information on all Amazon -// Route 53 servers. Send a POST request to: -// -// /2013-04-01/hostedzone/Amazon Route 53 hosted Zone ID/rrset resource. +// Creates, changes, or deletes a resource record set, which contains authoritative +// DNS information for a specified domain name or subdomain name. For example, +// you can use ChangeResourceRecordSets to create a resource record set that +// routes traffic for test.example.com to a web server that has an IP address +// of 192.0.2.44. // // Change Batches and Transactional Changes // @@ -271,8 +282,23 @@ func (c *Route53) ChangeResourceRecordSetsRequest(input *ChangeResourceRecordSet // Please also see https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/ChangeResourceRecordSets func (c *Route53) ChangeResourceRecordSets(input *ChangeResourceRecordSetsInput) (*ChangeResourceRecordSetsOutput, error) { req, out := c.ChangeResourceRecordSetsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ChangeResourceRecordSetsWithContext is the same as ChangeResourceRecordSets with the addition of +// the ability to pass a context and additional request options. +// +// See ChangeResourceRecordSets 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 *Route53) ChangeResourceRecordSetsWithContext(ctx aws.Context, input *ChangeResourceRecordSetsInput, opts ...request.Option) (*ChangeResourceRecordSetsOutput, error) { + req, out := c.ChangeResourceRecordSetsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opChangeTagsForResource = "ChangeTagsForResource" @@ -357,8 +383,23 @@ func (c *Route53) ChangeTagsForResourceRequest(input *ChangeTagsForResourceInput // Please also see https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/ChangeTagsForResource func (c *Route53) ChangeTagsForResource(input *ChangeTagsForResourceInput) (*ChangeTagsForResourceOutput, error) { req, out := c.ChangeTagsForResourceRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ChangeTagsForResourceWithContext is the same as ChangeTagsForResource with the addition of +// the ability to pass a context and additional request options. +// +// See ChangeTagsForResource 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 *Route53) ChangeTagsForResourceWithContext(ctx aws.Context, input *ChangeTagsForResourceInput, opts ...request.Option) (*ChangeTagsForResourceOutput, error) { + req, out := c.ChangeTagsForResourceRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateHealthCheck = "CreateHealthCheck" @@ -408,12 +449,10 @@ func (c *Route53) CreateHealthCheckRequest(input *CreateHealthCheckInput) (req * // // Creates a new health check. // -// To create a new health check, send a POST request to the /2013-04-01/healthcheck -// resource. The request body must include a document with a CreateHealthCheckRequest -// element. The response returns the CreateHealthCheckResponse element, containing -// the health check ID specified when adding health check to a resource record -// set. For information about adding health checks to resource record sets, -// see ResourceRecordSet$HealthCheckId in ChangeResourceRecordSets. +// For information about adding health checks to resource record sets, see ResourceRecordSet$HealthCheckId +// in ChangeResourceRecordSets. +// +// ELB Load Balancers // // If you're registering EC2 instances with an Elastic Load Balancing (ELB) // load balancer, do not create Amazon Route 53 health checks for the EC2 instances. @@ -421,6 +460,8 @@ func (c *Route53) CreateHealthCheckRequest(input *CreateHealthCheckInput) (req * // for an ELB health check, which performs a similar function to an Amazon Route // 53 health check. // +// Private Hosted Zones +// // You can associate health checks with failover resource record sets in a private // hosted zone. Note the following: // @@ -454,8 +495,14 @@ func (c *Route53) CreateHealthCheckRequest(input *CreateHealthCheckInput) (req * // // * ErrCodeHealthCheckAlreadyExists "HealthCheckAlreadyExists" // The health check you're attempting to create already exists. Amazon Route -// 53 returns this error when a health check has already been created with the -// specified value for CallerReference. +// 53 returns this error when you submit a request that has the following values: +// +// * The same value for CallerReference as an existing health check, and +// one or more values that differ from the existing health check that has +// the same caller reference. +// +// * The same value for CallerReference as a health check that you created +// and later deleted, regardless of the other settings in the request. // // * ErrCodeInvalidInput "InvalidInput" // The input is not valid. @@ -463,8 +510,23 @@ func (c *Route53) CreateHealthCheckRequest(input *CreateHealthCheckInput) (req * // Please also see https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/CreateHealthCheck func (c *Route53) CreateHealthCheck(input *CreateHealthCheckInput) (*CreateHealthCheckOutput, error) { req, out := c.CreateHealthCheckRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateHealthCheckWithContext is the same as CreateHealthCheck with the addition of +// the ability to pass a context and additional request options. +// +// See CreateHealthCheck 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 *Route53) CreateHealthCheckWithContext(ctx aws.Context, input *CreateHealthCheckInput, opts ...request.Option) (*CreateHealthCheckOutput, error) { + req, out := c.CreateHealthCheckRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateHostedZone = "CreateHostedZone" @@ -512,20 +574,15 @@ func (c *Route53) CreateHostedZoneRequest(input *CreateHostedZoneInput) (req *re // CreateHostedZone API operation for Amazon Route 53. // -// Creates a new public hosted zone, used to specify how the Domain Name System -// (DNS) routes traffic on the Internet for a domain, such as example.com, and -// its subdomains. +// Creates a new public hosted zone, which you use to specify how the Domain +// Name System (DNS) routes traffic on the Internet for a domain, such as example.com, +// and its subdomains. // -// Public hosted zones can't be converted to a private hosted zone or vice versa. -// Instead, create a new hosted zone with the same name and create new resource -// record sets. +// You can't convert a public hosted zones to a private hosted zone or vice +// versa. Instead, you must create a new hosted zone with the same name and +// create new resource record sets. // -// Send a POST request to the /2013-04-01/hostedzone resource. The request body -// must include a document with a CreateHostedZoneRequest element. The response -// returns the CreateHostedZoneResponse element containing metadata about the -// hosted zone. -// -// Fore more information about charges for hosted zones, see Amazon Route 53 +// For more information about charges for hosted zones, see Amazon Route 53 // Pricing (http://aws.amazon.com/route53/pricing/). // // Note the following: @@ -538,20 +595,20 @@ func (c *Route53) CreateHostedZoneRequest(input *CreateHostedZoneInput) (req *re // (http://docs.aws.amazon.com/Route53/latest/DeveloperGuide/SOA-NSrecords.html) // in the Amazon Route 53 Developer Guide. // +// If you want to use the same name servers for multiple hosted zones, you can +// optionally associate a reusable delegation set with the hosted zone. See +// the DelegationSetId element. +// // * If your domain is registered with a registrar other than Amazon Route // 53, you must update the name servers with your registrar to make Amazon // Route 53 your DNS service. For more information, see Configuring Amazon // Route 53 as your DNS Service (http://docs.aws.amazon.com/Route53/latest/DeveloperGuide/creating-migrating.html) -// in the Amazon Route 53 Developer's Guide. +// in the Amazon Route 53 Developer Guide. // -// After creating a zone, its initial status is PENDING. This means that it -// is not yet available on all DNS servers. The status of the zone changes to -// INSYNC when the NS and SOA records are available on all Amazon Route 53 DNS -// servers. -// -// When trying to create a hosted zone using a reusable delegation set, specify -// an optional DelegationSetId, and Amazon Route 53 would assign those 4 NS -// records for the zone, instead of allotting a new one. +// When you submit a CreateHostedZone request, the initial status of the hosted +// zone is PENDING. This means that the NS and SOA records are not yet available +// on all Amazon Route 53 DNS servers. When the NS and SOA records are available, +// the status of the zone changes to INSYNC. // // 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 @@ -604,8 +661,23 @@ func (c *Route53) CreateHostedZoneRequest(input *CreateHostedZoneInput) (req *re // Please also see https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/CreateHostedZone func (c *Route53) CreateHostedZone(input *CreateHostedZoneInput) (*CreateHostedZoneOutput, error) { req, out := c.CreateHostedZoneRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateHostedZoneWithContext is the same as CreateHostedZone with the addition of +// the ability to pass a context and additional request options. +// +// See CreateHostedZone 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 *Route53) CreateHostedZoneWithContext(ctx aws.Context, input *CreateHostedZoneInput, opts ...request.Option) (*CreateHostedZoneOutput, error) { + req, out := c.CreateHostedZoneRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateReusableDelegationSet = "CreateReusableDelegationSet" @@ -657,14 +729,10 @@ func (c *Route53) CreateReusableDelegationSetRequest(input *CreateReusableDelega // by multiple hosted zones. If a hosted zoned ID is specified, CreateReusableDelegationSet // marks the delegation set associated with that zone as reusable // -// Send a POST request to the /2013-04-01/delegationset resource. The request -// body must include a document with a CreateReusableDelegationSetRequest element. +// A reusable delegation set can't be associated with a private hosted zone. // -// A reusable delegation set can't be associated with a private hosted zone/ -// -// For more information, including a procedure on how to create and configure -// a reusable delegation set (also known as white label name servers), see Configuring -// White Label Name Servers (http://docs.aws.amazon.com/Route53/latest/DeveloperGuide/white-label-name-servers.html). +// For information on how to use a reusable delegation set to configure white +// label name servers, see Configuring White Label Name Servers (http://docs.aws.amazon.com/Route53/latest/DeveloperGuide/white-label-name-servers.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 @@ -703,8 +771,23 @@ func (c *Route53) CreateReusableDelegationSetRequest(input *CreateReusableDelega // Please also see https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/CreateReusableDelegationSet func (c *Route53) CreateReusableDelegationSet(input *CreateReusableDelegationSetInput) (*CreateReusableDelegationSetOutput, error) { req, out := c.CreateReusableDelegationSetRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateReusableDelegationSetWithContext is the same as CreateReusableDelegationSet with the addition of +// the ability to pass a context and additional request options. +// +// See CreateReusableDelegationSet 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 *Route53) CreateReusableDelegationSetWithContext(ctx aws.Context, input *CreateReusableDelegationSetInput, opts ...request.Option) (*CreateReusableDelegationSetOutput, error) { + req, out := c.CreateReusableDelegationSetRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateTrafficPolicy = "CreateTrafficPolicy" @@ -756,11 +839,6 @@ func (c *Route53) CreateTrafficPolicyRequest(input *CreateTrafficPolicyInput) (r // sets for one domain name (such as example.com) or one subdomain name (such // as www.example.com). // -// Send a POST request to the /2013-04-01/trafficpolicy resource. The request -// body must include a document with a CreateTrafficPolicyRequest element. The -// response includes the CreateTrafficPolicyResponse element, which contains -// information about the new traffic policy. -// // 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. @@ -787,8 +865,23 @@ func (c *Route53) CreateTrafficPolicyRequest(input *CreateTrafficPolicyInput) (r // Please also see https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/CreateTrafficPolicy func (c *Route53) CreateTrafficPolicy(input *CreateTrafficPolicyInput) (*CreateTrafficPolicyOutput, error) { req, out := c.CreateTrafficPolicyRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateTrafficPolicyWithContext is the same as CreateTrafficPolicy with the addition of +// the ability to pass a context and additional request options. +// +// See CreateTrafficPolicy 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 *Route53) CreateTrafficPolicyWithContext(ctx aws.Context, input *CreateTrafficPolicyInput, opts ...request.Option) (*CreateTrafficPolicyOutput, error) { + req, out := c.CreateTrafficPolicyRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateTrafficPolicyInstance = "CreateTrafficPolicyInstance" @@ -843,11 +936,6 @@ func (c *Route53) CreateTrafficPolicyInstanceRequest(input *CreateTrafficPolicyI // responds to DNS queries for the domain or subdomain name by using the resource // record sets that CreateTrafficPolicyInstance created. // -// Send a POST request to the /2013-04-01/trafficpolicyinstance resource. The -// request body must include a document with a CreateTrafficPolicyRequest element. -// The response returns the CreateTrafficPolicyInstanceResponse element, which -// contains information about the traffic policy 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. @@ -876,8 +964,23 @@ func (c *Route53) CreateTrafficPolicyInstanceRequest(input *CreateTrafficPolicyI // Please also see https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/CreateTrafficPolicyInstance func (c *Route53) CreateTrafficPolicyInstance(input *CreateTrafficPolicyInstanceInput) (*CreateTrafficPolicyInstanceOutput, error) { req, out := c.CreateTrafficPolicyInstanceRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateTrafficPolicyInstanceWithContext is the same as CreateTrafficPolicyInstance with the addition of +// the ability to pass a context and additional request options. +// +// See CreateTrafficPolicyInstance 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 *Route53) CreateTrafficPolicyInstanceWithContext(ctx aws.Context, input *CreateTrafficPolicyInstanceInput, opts ...request.Option) (*CreateTrafficPolicyInstanceOutput, error) { + req, out := c.CreateTrafficPolicyInstanceRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateTrafficPolicyVersion = "CreateTrafficPolicyVersion" @@ -934,11 +1037,6 @@ func (c *Route53) CreateTrafficPolicyVersionRequest(input *CreateTrafficPolicyVe // the limit and need to create another version, you'll need to start a new // traffic policy. // -// Send a POST request to the /2013-04-01/trafficpolicy/ resource. The request -// body includes a document with a CreateTrafficPolicyVersionRequest element. -// The response returns the CreateTrafficPolicyVersionResponse element, which -// contains information about the new version of the traffic policy. -// // 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. @@ -964,8 +1062,23 @@ func (c *Route53) CreateTrafficPolicyVersionRequest(input *CreateTrafficPolicyVe // Please also see https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/CreateTrafficPolicyVersion func (c *Route53) CreateTrafficPolicyVersion(input *CreateTrafficPolicyVersionInput) (*CreateTrafficPolicyVersionOutput, error) { req, out := c.CreateTrafficPolicyVersionRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateTrafficPolicyVersionWithContext is the same as CreateTrafficPolicyVersion with the addition of +// the ability to pass a context and additional request options. +// +// See CreateTrafficPolicyVersion 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 *Route53) CreateTrafficPolicyVersionWithContext(ctx aws.Context, input *CreateTrafficPolicyVersionInput, opts ...request.Option) (*CreateTrafficPolicyVersionOutput, error) { + req, out := c.CreateTrafficPolicyVersionRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateVPCAssociationAuthorization = "CreateVPCAssociationAuthorization" @@ -1024,10 +1137,6 @@ func (c *Route53) CreateVPCAssociationAuthorizationRequest(input *CreateVPCAssoc // with a hosted zone that you created by using a different account, you must // submit one authorization request for each VPC. // -// Send a POST request to the /2013-04-01/hostedzone/hosted zone ID/authorizevpcassociation -// resource. The request body must include a document with a CreateVPCAssociationAuthorizationRequest -// element. The response contains information about the authorization. -// // 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. @@ -1060,8 +1169,23 @@ func (c *Route53) CreateVPCAssociationAuthorizationRequest(input *CreateVPCAssoc // Please also see https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/CreateVPCAssociationAuthorization func (c *Route53) CreateVPCAssociationAuthorization(input *CreateVPCAssociationAuthorizationInput) (*CreateVPCAssociationAuthorizationOutput, error) { req, out := c.CreateVPCAssociationAuthorizationRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateVPCAssociationAuthorizationWithContext is the same as CreateVPCAssociationAuthorization with the addition of +// the ability to pass a context and additional request options. +// +// See CreateVPCAssociationAuthorization 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 *Route53) CreateVPCAssociationAuthorizationWithContext(ctx aws.Context, input *CreateVPCAssociationAuthorizationInput, opts ...request.Option) (*CreateVPCAssociationAuthorizationOutput, error) { + req, out := c.CreateVPCAssociationAuthorizationRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteHealthCheck = "DeleteHealthCheck" @@ -1109,8 +1233,7 @@ func (c *Route53) DeleteHealthCheckRequest(input *DeleteHealthCheckInput) (req * // DeleteHealthCheck API operation for Amazon Route 53. // -// Deletes a health check. Send a DELETE request to the /2013-04-01/healthcheck/health -// check ID resource. +// Deletes a health check. // // Amazon Route 53 does not prevent you from deleting a health check even if // the health check is associated with one or more resource record sets. If @@ -1143,8 +1266,23 @@ func (c *Route53) DeleteHealthCheckRequest(input *DeleteHealthCheckInput) (req * // Please also see https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/DeleteHealthCheck func (c *Route53) DeleteHealthCheck(input *DeleteHealthCheckInput) (*DeleteHealthCheckOutput, error) { req, out := c.DeleteHealthCheckRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteHealthCheckWithContext is the same as DeleteHealthCheck with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteHealthCheck 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 *Route53) DeleteHealthCheckWithContext(ctx aws.Context, input *DeleteHealthCheckInput, opts ...request.Option) (*DeleteHealthCheckOutput, error) { + req, out := c.DeleteHealthCheckRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteHostedZone = "DeleteHostedZone" @@ -1192,16 +1330,37 @@ func (c *Route53) DeleteHostedZoneRequest(input *DeleteHostedZoneInput) (req *re // DeleteHostedZone API operation for Amazon Route 53. // -// Deletes a hosted zone. Send a DELETE request to the /Amazon Route 53 API -// version/hostedzone/hosted zone ID resource. +// Deletes a hosted zone. // -// Delete a hosted zone only if there are no resource record sets other than -// the default SOA record and NS resource record sets. If the hosted zone contains -// other resource record sets, delete them before deleting the hosted zone. -// If you try to delete a hosted zone that contains other resource record sets, -// Amazon Route 53 denies your request with a HostedZoneNotEmpty error. For +// If the name servers for the hosted zone are associated with a domain and +// if you want to make the domain unavailable on the Internet, we recommend +// that you delete the name servers from the domain to prevent future DNS queries +// from possibly being misrouted. If the domain is registered with Amazon Route +// 53, see UpdateDomainNameservers. If the domain is registered with another +// registrar, use the method provided by the registrar to delete name servers +// for the domain. +// +// Some domain registries don't allow you to remove all of the name servers +// for a domain. If the registry for your domain requires one or more name servers, +// we recommend that you delete the hosted zone only if you transfer DNS service +// to another service provider, and you replace the name servers for the domain +// with name servers from the new provider. +// +// You can delete a hosted zone only if it contains only the default SOA record +// and NS resource record sets. If the hosted zone contains other resource record +// sets, you must delete them before you can delete the hosted zone. If you +// try to delete a hosted zone that contains other resource record sets, the +// request fails, and Amazon Route 53 returns a HostedZoneNotEmpty error. For // information about deleting records from your hosted zone, see ChangeResourceRecordSets. // +// To verify that the hosted zone has been deleted, do one of the following: +// +// * Use the GetHostedZone action to request information about the hosted +// zone. +// +// * Use the ListHostedZones action to get a list of the hosted zones associated +// with the current AWS 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 // the error. @@ -1232,8 +1391,23 @@ func (c *Route53) DeleteHostedZoneRequest(input *DeleteHostedZoneInput) (req *re // Please also see https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/DeleteHostedZone func (c *Route53) DeleteHostedZone(input *DeleteHostedZoneInput) (*DeleteHostedZoneOutput, error) { req, out := c.DeleteHostedZoneRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteHostedZoneWithContext is the same as DeleteHostedZone with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteHostedZone 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 *Route53) DeleteHostedZoneWithContext(ctx aws.Context, input *DeleteHostedZoneInput, opts ...request.Option) (*DeleteHostedZoneOutput, error) { + req, out := c.DeleteHostedZoneRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteReusableDelegationSet = "DeleteReusableDelegationSet" @@ -1281,14 +1455,13 @@ func (c *Route53) DeleteReusableDelegationSetRequest(input *DeleteReusableDelega // DeleteReusableDelegationSet API operation for Amazon Route 53. // -// Deletes a reusable delegation set. Send a DELETE request to the /2013-04-01/delegationset/delegation -// set ID resource. +// Deletes a reusable delegation set. // -// You can delete a reusable delegation set only if there are no associated -// hosted zones. +// You can delete a reusable delegation set only if it isn't associated with +// any hosted zones. // // To verify that the reusable delegation set is not associated with any hosted -// zones, run the GetReusableDelegationSet action and specify the ID of the +// zones, submit a GetReusableDelegationSet request and specify the ID of the // reusable delegation set that you want to delete. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions @@ -1315,8 +1488,23 @@ func (c *Route53) DeleteReusableDelegationSetRequest(input *DeleteReusableDelega // Please also see https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/DeleteReusableDelegationSet func (c *Route53) DeleteReusableDelegationSet(input *DeleteReusableDelegationSetInput) (*DeleteReusableDelegationSetOutput, error) { req, out := c.DeleteReusableDelegationSetRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteReusableDelegationSetWithContext is the same as DeleteReusableDelegationSet with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteReusableDelegationSet 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 *Route53) DeleteReusableDelegationSetWithContext(ctx aws.Context, input *DeleteReusableDelegationSetInput, opts ...request.Option) (*DeleteReusableDelegationSetOutput, error) { + req, out := c.DeleteReusableDelegationSetRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteTrafficPolicy = "DeleteTrafficPolicy" @@ -1366,8 +1554,6 @@ func (c *Route53) DeleteTrafficPolicyRequest(input *DeleteTrafficPolicyInput) (r // // Deletes a traffic policy. // -// Send a DELETE request to the /Amazon Route 53 API version/trafficpolicy resource. -// // 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. @@ -1393,8 +1579,23 @@ func (c *Route53) DeleteTrafficPolicyRequest(input *DeleteTrafficPolicyInput) (r // Please also see https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/DeleteTrafficPolicy func (c *Route53) DeleteTrafficPolicy(input *DeleteTrafficPolicyInput) (*DeleteTrafficPolicyOutput, error) { req, out := c.DeleteTrafficPolicyRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteTrafficPolicyWithContext is the same as DeleteTrafficPolicy with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteTrafficPolicy 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 *Route53) DeleteTrafficPolicyWithContext(ctx aws.Context, input *DeleteTrafficPolicyInput, opts ...request.Option) (*DeleteTrafficPolicyOutput, error) { + req, out := c.DeleteTrafficPolicyRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteTrafficPolicyInstance = "DeleteTrafficPolicyInstance" @@ -1445,9 +1646,6 @@ func (c *Route53) DeleteTrafficPolicyInstanceRequest(input *DeleteTrafficPolicyI // Deletes a traffic policy instance and all of the resource record sets that // Amazon Route 53 created when you created the instance. // -// Send a DELETE request to the /Amazon Route 53 API version/trafficpolicy/traffic -// policy instance ID resource. -// // In the Amazon Route 53 console, traffic policy instances are known as policy // records. // @@ -1475,8 +1673,23 @@ func (c *Route53) DeleteTrafficPolicyInstanceRequest(input *DeleteTrafficPolicyI // Please also see https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/DeleteTrafficPolicyInstance func (c *Route53) DeleteTrafficPolicyInstance(input *DeleteTrafficPolicyInstanceInput) (*DeleteTrafficPolicyInstanceOutput, error) { req, out := c.DeleteTrafficPolicyInstanceRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteTrafficPolicyInstanceWithContext is the same as DeleteTrafficPolicyInstance with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteTrafficPolicyInstance 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 *Route53) DeleteTrafficPolicyInstanceWithContext(ctx aws.Context, input *DeleteTrafficPolicyInstanceInput, opts ...request.Option) (*DeleteTrafficPolicyInstanceOutput, error) { + req, out := c.DeleteTrafficPolicyInstanceRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteVPCAssociationAuthorization = "DeleteVPCAssociationAuthorization" @@ -1535,10 +1748,6 @@ func (c *Route53) DeleteVPCAssociationAuthorizationRequest(input *DeleteVPCAssoc // won't disassociate the VPC from the hosted zone. If you want to delete an // existing association, use DisassociateVPCFromHostedZone. // -// Send a DELETE request to the /2013-04-01/hostedzone/hosted zone ID/deauthorizevpcassociation -// resource. The request body must include a document with a DeleteVPCAssociationAuthorizationRequest -// element. -// // 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. @@ -1568,8 +1777,23 @@ func (c *Route53) DeleteVPCAssociationAuthorizationRequest(input *DeleteVPCAssoc // Please also see https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/DeleteVPCAssociationAuthorization func (c *Route53) DeleteVPCAssociationAuthorization(input *DeleteVPCAssociationAuthorizationInput) (*DeleteVPCAssociationAuthorizationOutput, error) { req, out := c.DeleteVPCAssociationAuthorizationRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteVPCAssociationAuthorizationWithContext is the same as DeleteVPCAssociationAuthorization with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteVPCAssociationAuthorization 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 *Route53) DeleteVPCAssociationAuthorizationWithContext(ctx aws.Context, input *DeleteVPCAssociationAuthorizationInput, opts ...request.Option) (*DeleteVPCAssociationAuthorizationOutput, error) { + req, out := c.DeleteVPCAssociationAuthorizationRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDisassociateVPCFromHostedZone = "DisassociateVPCFromHostedZone" @@ -1621,10 +1845,6 @@ func (c *Route53) DisassociateVPCFromHostedZoneRequest(input *DisassociateVPCFro // // You can't disassociate the last VPC from a private hosted zone. // -// Send a POST request to the /2013-04-01/hostedzone/hosted zone ID/disassociatevpc -// resource. The request body must include a document with a DisassociateVPCFromHostedZoneRequest -// element. The response includes a DisassociateVPCFromHostedZoneResponse element. -// // You can't disassociate a VPC from a private hosted zone when only one VPC // is associated with the hosted zone. You also can't convert a private hosted // zone into a public hosted zone. @@ -1658,8 +1878,23 @@ func (c *Route53) DisassociateVPCFromHostedZoneRequest(input *DisassociateVPCFro // Please also see https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/DisassociateVPCFromHostedZone func (c *Route53) DisassociateVPCFromHostedZone(input *DisassociateVPCFromHostedZoneInput) (*DisassociateVPCFromHostedZoneOutput, error) { req, out := c.DisassociateVPCFromHostedZoneRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DisassociateVPCFromHostedZoneWithContext is the same as DisassociateVPCFromHostedZone with the addition of +// the ability to pass a context and additional request options. +// +// See DisassociateVPCFromHostedZone 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 *Route53) DisassociateVPCFromHostedZoneWithContext(ctx aws.Context, input *DisassociateVPCFromHostedZoneInput, opts ...request.Option) (*DisassociateVPCFromHostedZoneOutput, error) { + req, out := c.DisassociateVPCFromHostedZoneRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetChange = "GetChange" @@ -1710,11 +1945,11 @@ func (c *Route53) GetChangeRequest(input *GetChangeInput) (req *request.Request, // Returns the current status of a change batch request. The status is one of // the following values: // -// * PENDING indicates that the changes in this request have not replicated +// * PENDING indicates that the changes in this request have not propagated // to all Amazon Route 53 DNS servers. This is the initial status of all // change batch requests. // -// * INSYNC indicates that the changes have replicated to all Amazon Route +// * INSYNC indicates that the changes have propagated to all Amazon Route // 53 DNS servers. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions @@ -1734,8 +1969,23 @@ func (c *Route53) GetChangeRequest(input *GetChangeInput) (req *request.Request, // Please also see https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/GetChange func (c *Route53) GetChange(input *GetChangeInput) (*GetChangeOutput, error) { req, out := c.GetChangeRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetChangeWithContext is the same as GetChange with the addition of +// the ability to pass a context and additional request options. +// +// See GetChange 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 *Route53) GetChangeWithContext(ctx aws.Context, input *GetChangeInput, opts ...request.Option) (*GetChangeOutput, error) { + req, out := c.GetChangeRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetCheckerIpRanges = "GetCheckerIpRanges" @@ -1797,8 +2047,23 @@ func (c *Route53) GetCheckerIpRangesRequest(input *GetCheckerIpRangesInput) (req // Please also see https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/GetCheckerIpRanges func (c *Route53) GetCheckerIpRanges(input *GetCheckerIpRangesInput) (*GetCheckerIpRangesOutput, error) { req, out := c.GetCheckerIpRangesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetCheckerIpRangesWithContext is the same as GetCheckerIpRanges with the addition of +// the ability to pass a context and additional request options. +// +// See GetCheckerIpRanges 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 *Route53) GetCheckerIpRangesWithContext(ctx aws.Context, input *GetCheckerIpRangesInput, opts ...request.Option) (*GetCheckerIpRangesOutput, error) { + req, out := c.GetCheckerIpRangesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetGeoLocation = "GetGeoLocation" @@ -1846,9 +2111,24 @@ func (c *Route53) GetGeoLocationRequest(input *GetGeoLocationInput) (req *reques // GetGeoLocation API operation for Amazon Route 53. // -// Retrieves a single geo location. Send a GET request to the /2013-04-01/geolocation -// resource with one of these options: continentcode | countrycode | countrycode -// and subdivisioncode. +// Gets information about whether a specified geographic location is supported +// for Amazon Route 53 geolocation resource record sets. +// +// Use the following syntax to determine whether a continent is supported for +// geolocation: +// +// GET /2013-04-01/geolocation?ContinentCode=two-letter abbreviation for a continent +// +// Use the following syntax to determine whether a country is supported for +// geolocation: +// +// GET /2013-04-01/geolocation?CountryCode=two-character country code +// +// Use the following syntax to determine whether a subdivision of a country +// is supported for geolocation: +// +// GET /2013-04-01/geolocation?CountryCode=two-character country code&SubdivisionCode=subdivision +// code // // 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 @@ -1867,8 +2147,23 @@ func (c *Route53) GetGeoLocationRequest(input *GetGeoLocationInput) (req *reques // Please also see https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/GetGeoLocation func (c *Route53) GetGeoLocation(input *GetGeoLocationInput) (*GetGeoLocationOutput, error) { req, out := c.GetGeoLocationRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetGeoLocationWithContext is the same as GetGeoLocation with the addition of +// the ability to pass a context and additional request options. +// +// See GetGeoLocation 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 *Route53) GetGeoLocationWithContext(ctx aws.Context, input *GetGeoLocationInput, opts ...request.Option) (*GetGeoLocationOutput, error) { + req, out := c.GetGeoLocationRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetHealthCheck = "GetHealthCheck" @@ -1916,11 +2211,7 @@ func (c *Route53) GetHealthCheckRequest(input *GetHealthCheckInput) (req *reques // GetHealthCheck API operation for Amazon Route 53. // -// Gets information about a specified health check. Send a GET request to the -// /2013-04-01/healthcheck/health check ID resource. For more information about -// using the console to perform this operation, see Amazon Route 53 Health Checks -// and DNS Failover (http://docs.aws.amazon.com/Route53/latest/DeveloperGuide/dns-failover.html) -// in the Amazon Route 53 Developer Guide. +// Gets information about a specified health check. // // 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 @@ -1944,8 +2235,23 @@ func (c *Route53) GetHealthCheckRequest(input *GetHealthCheckInput) (req *reques // Please also see https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/GetHealthCheck func (c *Route53) GetHealthCheck(input *GetHealthCheckInput) (*GetHealthCheckOutput, error) { req, out := c.GetHealthCheckRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetHealthCheckWithContext is the same as GetHealthCheck with the addition of +// the ability to pass a context and additional request options. +// +// See GetHealthCheck 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 *Route53) GetHealthCheckWithContext(ctx aws.Context, input *GetHealthCheckInput, opts ...request.Option) (*GetHealthCheckOutput, error) { + req, out := c.GetHealthCheckRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetHealthCheckCount = "GetHealthCheckCount" @@ -1993,8 +2299,8 @@ func (c *Route53) GetHealthCheckCountRequest(input *GetHealthCheckCountInput) (r // GetHealthCheckCount API operation for Amazon Route 53. // -// To retrieve a count of all your health checks, send a GET request to the -// /2013-04-01/healthcheckcount resource. +// Retrieves the number of health checks that are associated with the current +// AWS 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 @@ -2005,8 +2311,23 @@ func (c *Route53) GetHealthCheckCountRequest(input *GetHealthCheckCountInput) (r // Please also see https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/GetHealthCheckCount func (c *Route53) GetHealthCheckCount(input *GetHealthCheckCountInput) (*GetHealthCheckCountOutput, error) { req, out := c.GetHealthCheckCountRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetHealthCheckCountWithContext is the same as GetHealthCheckCount with the addition of +// the ability to pass a context and additional request options. +// +// See GetHealthCheckCount 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 *Route53) GetHealthCheckCountWithContext(ctx aws.Context, input *GetHealthCheckCountInput, opts ...request.Option) (*GetHealthCheckCountOutput, error) { + req, out := c.GetHealthCheckCountRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetHealthCheckLastFailureReason = "GetHealthCheckLastFailureReason" @@ -2054,10 +2375,7 @@ func (c *Route53) GetHealthCheckLastFailureReasonRequest(input *GetHealthCheckLa // GetHealthCheckLastFailureReason API operation for Amazon Route 53. // -// If you want to learn why a health check is currently failing or why it failed -// most recently (if at all), you can get the failure reason for the most recent -// failure. Send a GET request to the /Amazon Route 53 API version/healthcheck/health -// check ID/lastfailurereason resource. +// Gets the reason that a specified health check failed most recently. // // 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 @@ -2077,8 +2395,23 @@ func (c *Route53) GetHealthCheckLastFailureReasonRequest(input *GetHealthCheckLa // Please also see https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/GetHealthCheckLastFailureReason func (c *Route53) GetHealthCheckLastFailureReason(input *GetHealthCheckLastFailureReasonInput) (*GetHealthCheckLastFailureReasonOutput, error) { req, out := c.GetHealthCheckLastFailureReasonRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetHealthCheckLastFailureReasonWithContext is the same as GetHealthCheckLastFailureReason with the addition of +// the ability to pass a context and additional request options. +// +// See GetHealthCheckLastFailureReason 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 *Route53) GetHealthCheckLastFailureReasonWithContext(ctx aws.Context, input *GetHealthCheckLastFailureReasonInput, opts ...request.Option) (*GetHealthCheckLastFailureReasonOutput, error) { + req, out := c.GetHealthCheckLastFailureReasonRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetHealthCheckStatus = "GetHealthCheckStatus" @@ -2126,9 +2459,7 @@ func (c *Route53) GetHealthCheckStatusRequest(input *GetHealthCheckStatusInput) // GetHealthCheckStatus API operation for Amazon Route 53. // -// Gets status of a specified health check. Send a GET request to the /2013-04-01/healthcheck/health -// check ID/status resource. You can use this call to get a health check's current -// status. +// Gets status of a specified health check. // // 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 @@ -2148,8 +2479,23 @@ func (c *Route53) GetHealthCheckStatusRequest(input *GetHealthCheckStatusInput) // Please also see https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/GetHealthCheckStatus func (c *Route53) GetHealthCheckStatus(input *GetHealthCheckStatusInput) (*GetHealthCheckStatusOutput, error) { req, out := c.GetHealthCheckStatusRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetHealthCheckStatusWithContext is the same as GetHealthCheckStatus with the addition of +// the ability to pass a context and additional request options. +// +// See GetHealthCheckStatus 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 *Route53) GetHealthCheckStatusWithContext(ctx aws.Context, input *GetHealthCheckStatusInput, opts ...request.Option) (*GetHealthCheckStatusOutput, error) { + req, out := c.GetHealthCheckStatusRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetHostedZone = "GetHostedZone" @@ -2197,9 +2543,8 @@ func (c *Route53) GetHostedZoneRequest(input *GetHostedZoneInput) (req *request. // GetHostedZone API operation for Amazon Route 53. // -// Retrieves the delegation set for a hosted zone, including the four name servers -// assigned to the hosted zone. Send a GET request to the /Amazon Route 53 API -// version/hostedzone/hosted zone ID resource. +// Gets information about a specified hosted zone including the four name servers +// assigned to the hosted zone. // // 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 @@ -2218,8 +2563,23 @@ func (c *Route53) GetHostedZoneRequest(input *GetHostedZoneInput) (req *request. // Please also see https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/GetHostedZone func (c *Route53) GetHostedZone(input *GetHostedZoneInput) (*GetHostedZoneOutput, error) { req, out := c.GetHostedZoneRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetHostedZoneWithContext is the same as GetHostedZone with the addition of +// the ability to pass a context and additional request options. +// +// See GetHostedZone 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 *Route53) GetHostedZoneWithContext(ctx aws.Context, input *GetHostedZoneInput, opts ...request.Option) (*GetHostedZoneOutput, error) { + req, out := c.GetHostedZoneRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetHostedZoneCount = "GetHostedZoneCount" @@ -2267,8 +2627,8 @@ func (c *Route53) GetHostedZoneCountRequest(input *GetHostedZoneCountInput) (req // GetHostedZoneCount API operation for Amazon Route 53. // -// Retrieves a count of all your hosted zones. Send a GET request to the /2013-04-01/hostedzonecount -// resource. +// Retrieves the number of hosted zones that are associated with the current +// AWS 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 @@ -2284,8 +2644,23 @@ func (c *Route53) GetHostedZoneCountRequest(input *GetHostedZoneCountInput) (req // Please also see https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/GetHostedZoneCount func (c *Route53) GetHostedZoneCount(input *GetHostedZoneCountInput) (*GetHostedZoneCountOutput, error) { req, out := c.GetHostedZoneCountRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetHostedZoneCountWithContext is the same as GetHostedZoneCount with the addition of +// the ability to pass a context and additional request options. +// +// See GetHostedZoneCount 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 *Route53) GetHostedZoneCountWithContext(ctx aws.Context, input *GetHostedZoneCountInput, opts ...request.Option) (*GetHostedZoneCountOutput, error) { + req, out := c.GetHostedZoneCountRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetReusableDelegationSet = "GetReusableDelegationSet" @@ -2333,8 +2708,8 @@ func (c *Route53) GetReusableDelegationSetRequest(input *GetReusableDelegationSe // GetReusableDelegationSet API operation for Amazon Route 53. // -// Retrieves the reusable delegation set. Send a GET request to the /2013-04-01/delegationset/delegation -// set ID resource. +// Retrieves information about a specified reusable delegation set, including +// the four name servers that are assigned to the delegation set. // // 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 @@ -2356,8 +2731,23 @@ func (c *Route53) GetReusableDelegationSetRequest(input *GetReusableDelegationSe // Please also see https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/GetReusableDelegationSet func (c *Route53) GetReusableDelegationSet(input *GetReusableDelegationSetInput) (*GetReusableDelegationSetOutput, error) { req, out := c.GetReusableDelegationSetRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetReusableDelegationSetWithContext is the same as GetReusableDelegationSet with the addition of +// the ability to pass a context and additional request options. +// +// See GetReusableDelegationSet 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 *Route53) GetReusableDelegationSetWithContext(ctx aws.Context, input *GetReusableDelegationSetInput, opts ...request.Option) (*GetReusableDelegationSetOutput, error) { + req, out := c.GetReusableDelegationSetRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetTrafficPolicy = "GetTrafficPolicy" @@ -2407,8 +2797,6 @@ func (c *Route53) GetTrafficPolicyRequest(input *GetTrafficPolicyInput) (req *re // // Gets information about a specific traffic policy version. // -// Send a GET request to the /Amazon Route 53 API version/trafficpolicy resource. -// // 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. @@ -2426,8 +2814,23 @@ func (c *Route53) GetTrafficPolicyRequest(input *GetTrafficPolicyInput) (req *re // Please also see https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/GetTrafficPolicy func (c *Route53) GetTrafficPolicy(input *GetTrafficPolicyInput) (*GetTrafficPolicyOutput, error) { req, out := c.GetTrafficPolicyRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetTrafficPolicyWithContext is the same as GetTrafficPolicy with the addition of +// the ability to pass a context and additional request options. +// +// See GetTrafficPolicy 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 *Route53) GetTrafficPolicyWithContext(ctx aws.Context, input *GetTrafficPolicyInput, opts ...request.Option) (*GetTrafficPolicyOutput, error) { + req, out := c.GetTrafficPolicyRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetTrafficPolicyInstance = "GetTrafficPolicyInstance" @@ -2477,9 +2880,6 @@ func (c *Route53) GetTrafficPolicyInstanceRequest(input *GetTrafficPolicyInstanc // // Gets information about a specified traffic policy instance. // -// Send a GET request to the /Amazon Route 53 API version/trafficpolicyinstance -// resource. -// // After you submit a CreateTrafficPolicyInstance or an UpdateTrafficPolicyInstance // request, there's a brief delay while Amazon Route 53 creates the resource // record sets that are specified in the traffic policy definition. For more @@ -2505,8 +2905,23 @@ func (c *Route53) GetTrafficPolicyInstanceRequest(input *GetTrafficPolicyInstanc // Please also see https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/GetTrafficPolicyInstance func (c *Route53) GetTrafficPolicyInstance(input *GetTrafficPolicyInstanceInput) (*GetTrafficPolicyInstanceOutput, error) { req, out := c.GetTrafficPolicyInstanceRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetTrafficPolicyInstanceWithContext is the same as GetTrafficPolicyInstance with the addition of +// the ability to pass a context and additional request options. +// +// See GetTrafficPolicyInstance 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 *Route53) GetTrafficPolicyInstanceWithContext(ctx aws.Context, input *GetTrafficPolicyInstanceInput, opts ...request.Option) (*GetTrafficPolicyInstanceOutput, error) { + req, out := c.GetTrafficPolicyInstanceRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetTrafficPolicyInstanceCount = "GetTrafficPolicyInstanceCount" @@ -2557,9 +2972,6 @@ func (c *Route53) GetTrafficPolicyInstanceCountRequest(input *GetTrafficPolicyIn // Gets the number of traffic policy instances that are associated with the // current AWS account. // -// To get the number of traffic policy instances, send a GET request to the -// /2013-04-01/trafficpolicyinstancecount resource. -// // 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. @@ -2569,8 +2981,23 @@ func (c *Route53) GetTrafficPolicyInstanceCountRequest(input *GetTrafficPolicyIn // Please also see https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/GetTrafficPolicyInstanceCount func (c *Route53) GetTrafficPolicyInstanceCount(input *GetTrafficPolicyInstanceCountInput) (*GetTrafficPolicyInstanceCountOutput, error) { req, out := c.GetTrafficPolicyInstanceCountRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetTrafficPolicyInstanceCountWithContext is the same as GetTrafficPolicyInstanceCount with the addition of +// the ability to pass a context and additional request options. +// +// See GetTrafficPolicyInstanceCount 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 *Route53) GetTrafficPolicyInstanceCountWithContext(ctx aws.Context, input *GetTrafficPolicyInstanceCountInput, opts ...request.Option) (*GetTrafficPolicyInstanceCountOutput, error) { + req, out := c.GetTrafficPolicyInstanceCountRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opListGeoLocations = "ListGeoLocations" @@ -2618,9 +3045,7 @@ func (c *Route53) ListGeoLocationsRequest(input *ListGeoLocationsInput) (req *re // ListGeoLocations API operation for Amazon Route 53. // -// Retrieves a list of supported geo locations. Send a GET request to the /2013-04-01/geolocations -// resource. The response to this request includes a GeoLocationDetailsList -// element for each location that Amazon Route 53 supports. +// Retrieves a list of supported geo locations. // // Countries are listed first, and continents are listed last. If Amazon Route // 53 supports subdivisions for a country (for example, states or provinces), @@ -2641,8 +3066,23 @@ func (c *Route53) ListGeoLocationsRequest(input *ListGeoLocationsInput) (req *re // Please also see https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/ListGeoLocations func (c *Route53) ListGeoLocations(input *ListGeoLocationsInput) (*ListGeoLocationsOutput, error) { req, out := c.ListGeoLocationsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListGeoLocationsWithContext is the same as ListGeoLocations with the addition of +// the ability to pass a context and additional request options. +// +// See ListGeoLocations 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 *Route53) ListGeoLocationsWithContext(ctx aws.Context, input *ListGeoLocationsInput, opts ...request.Option) (*ListGeoLocationsOutput, error) { + req, out := c.ListGeoLocationsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opListHealthChecks = "ListHealthChecks" @@ -2696,15 +3136,8 @@ func (c *Route53) ListHealthChecksRequest(input *ListHealthChecksInput) (req *re // ListHealthChecks API operation for Amazon Route 53. // -// Retrieve a list of your health checks. Send a GET request to the /2013-04-01/healthcheck -// resource. The response to this request includes a HealthChecks element with -// zero or more HealthCheck child elements. By default, the list of health checks -// is displayed on a single page. You can control the length of the page that -// is displayed by using the MaxItems parameter. You can use the Marker parameter -// to control the health check that the list begins with. -// -// For information about listing health checks using the Amazon Route 53 console, -// see Amazon Route 53 Health Checks and DNS Failover (http://docs.aws.amazon.com/Route53/latest/DeveloperGuide/dns-failover.html). +// Retrieve a list of the health checks that are associated with the current +// AWS 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 @@ -2724,8 +3157,23 @@ func (c *Route53) ListHealthChecksRequest(input *ListHealthChecksInput) (req *re // Please also see https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/ListHealthChecks func (c *Route53) ListHealthChecks(input *ListHealthChecksInput) (*ListHealthChecksOutput, error) { req, out := c.ListHealthChecksRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListHealthChecksWithContext is the same as ListHealthChecks with the addition of +// the ability to pass a context and additional request options. +// +// See ListHealthChecks 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 *Route53) ListHealthChecksWithContext(ctx aws.Context, input *ListHealthChecksInput, opts ...request.Option) (*ListHealthChecksOutput, error) { + req, out := c.ListHealthChecksRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // ListHealthChecksPages iterates over the pages of a ListHealthChecks operation, @@ -2745,12 +3193,37 @@ func (c *Route53) ListHealthChecks(input *ListHealthChecksInput) (*ListHealthChe // return pageNum <= 3 // }) // -func (c *Route53) ListHealthChecksPages(input *ListHealthChecksInput, fn func(p *ListHealthChecksOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.ListHealthChecksRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*ListHealthChecksOutput), lastPage) - }) +func (c *Route53) ListHealthChecksPages(input *ListHealthChecksInput, fn func(*ListHealthChecksOutput, bool) bool) error { + return c.ListHealthChecksPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListHealthChecksPagesWithContext same as ListHealthChecksPages 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 *Route53) ListHealthChecksPagesWithContext(ctx aws.Context, input *ListHealthChecksInput, fn func(*ListHealthChecksOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListHealthChecksInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListHealthChecksRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*ListHealthChecksOutput), !p.HasNextPage()) + } + return p.Err() } const opListHostedZones = "ListHostedZones" @@ -2804,32 +3277,13 @@ func (c *Route53) ListHostedZonesRequest(input *ListHostedZonesInput) (req *requ // ListHostedZones API operation for Amazon Route 53. // -// To retrieve a list of your public and private hosted zones, send a GET request -// to the /2013-04-01/hostedzone resource. The response to this request includes -// a HostedZones child element for each hosted zone created by the current AWS -// account. +// Retrieves a list of the public and private hosted zones that are associated +// with the current AWS account. The response includes a HostedZones child element +// for each hosted zone. // // Amazon Route 53 returns a maximum of 100 items in each response. If you have // a lot of hosted zones, you can use the maxitems parameter to list them in -// groups of up to 100. The response includes four values that help navigate -// from one group of maxitems hosted zones to the next: -// -// * MaxItems is the value specified for the maxitems parameter in the request -// that produced the current response. -// -// * If the value of IsTruncated in the response is true, there are more -// hosted zones associated with the current AWS account. -// -// * NextMarker is the hosted zone ID of the next hosted zone that is associated -// with the current AWS account. If you want to list more hosted zones, make -// another call to ListHostedZones, and specify the value of the NextMarker -// element in the marker parameter. -// -// If IsTruncated is false, the NextMarker element is omitted from the response. -// -// * If you're making the second or subsequent call to ListHostedZones, the -// Marker element matches the value that you specified in the marker parameter -// in the previous request. +// groups of up to 100. // // 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 @@ -2851,8 +3305,23 @@ func (c *Route53) ListHostedZonesRequest(input *ListHostedZonesInput) (req *requ // Please also see https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/ListHostedZones func (c *Route53) ListHostedZones(input *ListHostedZonesInput) (*ListHostedZonesOutput, error) { req, out := c.ListHostedZonesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListHostedZonesWithContext is the same as ListHostedZones with the addition of +// the ability to pass a context and additional request options. +// +// See ListHostedZones 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 *Route53) ListHostedZonesWithContext(ctx aws.Context, input *ListHostedZonesInput, opts ...request.Option) (*ListHostedZonesOutput, error) { + req, out := c.ListHostedZonesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // ListHostedZonesPages iterates over the pages of a ListHostedZones operation, @@ -2872,12 +3341,37 @@ func (c *Route53) ListHostedZones(input *ListHostedZonesInput) (*ListHostedZones // return pageNum <= 3 // }) // -func (c *Route53) ListHostedZonesPages(input *ListHostedZonesInput, fn func(p *ListHostedZonesOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.ListHostedZonesRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*ListHostedZonesOutput), lastPage) - }) +func (c *Route53) ListHostedZonesPages(input *ListHostedZonesInput, fn func(*ListHostedZonesOutput, bool) bool) error { + return c.ListHostedZonesPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListHostedZonesPagesWithContext same as ListHostedZonesPages 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 *Route53) ListHostedZonesPagesWithContext(ctx aws.Context, input *ListHostedZonesInput, fn func(*ListHostedZonesOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListHostedZonesInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListHostedZonesRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*ListHostedZonesOutput), !p.HasNextPage()) + } + return p.Err() } const opListHostedZonesByName = "ListHostedZonesByName" @@ -2925,25 +3419,24 @@ func (c *Route53) ListHostedZonesByNameRequest(input *ListHostedZonesByNameInput // ListHostedZonesByName API operation for Amazon Route 53. // -// Retrieves a list of your hosted zones in lexicographic order. Send a GET -// request to the /2013-04-01/hostedzonesbyname resource. The response includes -// a HostedZones child element for each hosted zone created by the current AWS -// account. +// Retrieves a list of your hosted zones in lexicographic order. The response +// includes a HostedZones child element for each hosted zone created by the +// current AWS account. // // ListHostedZonesByName sorts hosted zones by name with the labels reversed. // For example: // -// * com.example.www. +// com.example.www. // // Note the trailing dot, which can change the sort order in some circumstances. // // If the domain name includes escape characters or Punycode, ListHostedZonesByName // alphabetizes the domain name using the escaped or Punycoded value, which // is the format that Amazon Route 53 saves in its database. For example, to -// create a hosted zone for example.com, specify ex\344mple.com for the domain -// name. ListHostedZonesByName alphabetizes it as: +// create a hosted zone for exämple.com, you specify ex\344mple.com for the +// domain name. ListHostedZonesByName alphabetizes it as: // -// * com.ex\344mple. +// com.ex\344mple. // // The labels are reversed and alphabetized using the escaped value. For more // information about valid domain name formats, including internationalized @@ -2994,8 +3487,23 @@ func (c *Route53) ListHostedZonesByNameRequest(input *ListHostedZonesByNameInput // Please also see https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/ListHostedZonesByName func (c *Route53) ListHostedZonesByName(input *ListHostedZonesByNameInput) (*ListHostedZonesByNameOutput, error) { req, out := c.ListHostedZonesByNameRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListHostedZonesByNameWithContext is the same as ListHostedZonesByName with the addition of +// the ability to pass a context and additional request options. +// +// See ListHostedZonesByName 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 *Route53) ListHostedZonesByNameWithContext(ctx aws.Context, input *ListHostedZonesByNameInput, opts ...request.Option) (*ListHostedZonesByNameOutput, error) { + req, out := c.ListHostedZonesByNameRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opListResourceRecordSets = "ListResourceRecordSets" @@ -3106,8 +3614,23 @@ func (c *Route53) ListResourceRecordSetsRequest(input *ListResourceRecordSetsInp // Please also see https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/ListResourceRecordSets func (c *Route53) ListResourceRecordSets(input *ListResourceRecordSetsInput) (*ListResourceRecordSetsOutput, error) { req, out := c.ListResourceRecordSetsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListResourceRecordSetsWithContext is the same as ListResourceRecordSets with the addition of +// the ability to pass a context and additional request options. +// +// See ListResourceRecordSets 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 *Route53) ListResourceRecordSetsWithContext(ctx aws.Context, input *ListResourceRecordSetsInput, opts ...request.Option) (*ListResourceRecordSetsOutput, error) { + req, out := c.ListResourceRecordSetsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // ListResourceRecordSetsPages iterates over the pages of a ListResourceRecordSets operation, @@ -3127,12 +3650,37 @@ func (c *Route53) ListResourceRecordSets(input *ListResourceRecordSetsInput) (*L // return pageNum <= 3 // }) // -func (c *Route53) ListResourceRecordSetsPages(input *ListResourceRecordSetsInput, fn func(p *ListResourceRecordSetsOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.ListResourceRecordSetsRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*ListResourceRecordSetsOutput), lastPage) - }) +func (c *Route53) ListResourceRecordSetsPages(input *ListResourceRecordSetsInput, fn func(*ListResourceRecordSetsOutput, bool) bool) error { + return c.ListResourceRecordSetsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListResourceRecordSetsPagesWithContext same as ListResourceRecordSetsPages 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 *Route53) ListResourceRecordSetsPagesWithContext(ctx aws.Context, input *ListResourceRecordSetsInput, fn func(*ListResourceRecordSetsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListResourceRecordSetsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListResourceRecordSetsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*ListResourceRecordSetsOutput), !p.HasNextPage()) + } + return p.Err() } const opListReusableDelegationSets = "ListReusableDelegationSets" @@ -3180,16 +3728,8 @@ func (c *Route53) ListReusableDelegationSetsRequest(input *ListReusableDelegatio // ListReusableDelegationSets API operation for Amazon Route 53. // -// To retrieve a list of your reusable delegation sets, send a GET request to -// the /2013-04-01/delegationset resource. The response to this request includes -// a DelegationSets element with zero, one, or multiple DelegationSet child -// elements. By default, the list of delegation sets is displayed on a single -// page. You can control the length of the page that is displayed by using the -// MaxItems parameter. You can use the Marker parameter to control the delegation -// set that the list begins with. -// -// Amazon Route 53 returns a maximum of 100 items. If you set MaxItems to a -// value greater than 100, Amazon Route 53 returns only the first 100. +// Retrieves a list of the reusable delegation sets that are associated with +// the current AWS 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 @@ -3205,8 +3745,23 @@ func (c *Route53) ListReusableDelegationSetsRequest(input *ListReusableDelegatio // Please also see https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/ListReusableDelegationSets func (c *Route53) ListReusableDelegationSets(input *ListReusableDelegationSetsInput) (*ListReusableDelegationSetsOutput, error) { req, out := c.ListReusableDelegationSetsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListReusableDelegationSetsWithContext is the same as ListReusableDelegationSets with the addition of +// the ability to pass a context and additional request options. +// +// See ListReusableDelegationSets 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 *Route53) ListReusableDelegationSetsWithContext(ctx aws.Context, input *ListReusableDelegationSetsInput, opts ...request.Option) (*ListReusableDelegationSetsOutput, error) { + req, out := c.ListReusableDelegationSetsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opListTagsForResource = "ListTagsForResource" @@ -3291,8 +3846,23 @@ func (c *Route53) ListTagsForResourceRequest(input *ListTagsForResourceInput) (r // Please also see https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/ListTagsForResource func (c *Route53) ListTagsForResource(input *ListTagsForResourceInput) (*ListTagsForResourceOutput, error) { req, out := c.ListTagsForResourceRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListTagsForResourceWithContext is the same as ListTagsForResource with the addition of +// the ability to pass a context and additional request options. +// +// See ListTagsForResource 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 *Route53) ListTagsForResourceWithContext(ctx aws.Context, input *ListTagsForResourceInput, opts ...request.Option) (*ListTagsForResourceOutput, error) { + req, out := c.ListTagsForResourceRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opListTagsForResources = "ListTagsForResources" @@ -3377,8 +3947,23 @@ func (c *Route53) ListTagsForResourcesRequest(input *ListTagsForResourcesInput) // Please also see https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/ListTagsForResources func (c *Route53) ListTagsForResources(input *ListTagsForResourcesInput) (*ListTagsForResourcesOutput, error) { req, out := c.ListTagsForResourcesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListTagsForResourcesWithContext is the same as ListTagsForResources with the addition of +// the ability to pass a context and additional request options. +// +// See ListTagsForResources 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 *Route53) ListTagsForResourcesWithContext(ctx aws.Context, input *ListTagsForResourcesInput, opts ...request.Option) (*ListTagsForResourcesOutput, error) { + req, out := c.ListTagsForResourcesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opListTrafficPolicies = "ListTrafficPolicies" @@ -3427,39 +4012,8 @@ func (c *Route53) ListTrafficPoliciesRequest(input *ListTrafficPoliciesInput) (r // ListTrafficPolicies API operation for Amazon Route 53. // // Gets information about the latest version for every traffic policy that is -// associated with the current AWS account. Send a GET request to the /Amazon -// Route 53 API version/trafficpolicy resource. -// -// Amazon Route 53 returns a maximum of 100 items in each response. If you have -// a lot of traffic policies, you can use the maxitems parameter to list them -// in groups of up to 100. -// -// The response includes three values that help you navigate from one group -// of maxitems traffic policies to the next: -// -// * IsTruncated -// -// If the value of IsTruncated in the response is true, there are more traffic -// policies associated with the current AWS account. -// -// If IsTruncated is false, this response includes the last traffic policy that -// is associated with the current account. -// -// * TrafficPolicyIdMarker -// -// If IsTruncated is true, TrafficPolicyIdMarker is the ID of the first traffic -// policy in the next group of MaxItems traffic policies. If you want to -// list more traffic policies, make another call to ListTrafficPolicies, -// and specify the value of the TrafficPolicyIdMarker element from the response -// in the TrafficPolicyIdMarker request parameter. -// -// If IsTruncated is false, the TrafficPolicyIdMarker element is omitted from -// the response. -// -// * MaxItems -// -// The value that you specified for the MaxItems parameter in the request that -// produced the current response. +// associated with the current AWS account. Policies are listed in the order +// in which they were created. // // 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 @@ -3475,8 +4029,23 @@ func (c *Route53) ListTrafficPoliciesRequest(input *ListTrafficPoliciesInput) (r // Please also see https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/ListTrafficPolicies func (c *Route53) ListTrafficPolicies(input *ListTrafficPoliciesInput) (*ListTrafficPoliciesOutput, error) { req, out := c.ListTrafficPoliciesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListTrafficPoliciesWithContext is the same as ListTrafficPolicies with the addition of +// the ability to pass a context and additional request options. +// +// See ListTrafficPolicies 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 *Route53) ListTrafficPoliciesWithContext(ctx aws.Context, input *ListTrafficPoliciesInput, opts ...request.Option) (*ListTrafficPoliciesOutput, error) { + req, out := c.ListTrafficPoliciesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opListTrafficPolicyInstances = "ListTrafficPolicyInstances" @@ -3532,39 +4101,10 @@ func (c *Route53) ListTrafficPolicyInstancesRequest(input *ListTrafficPolicyInst // in the traffic policy definition. For more information, see the State response // element. // -// Send a GET request to the /Amazon Route 53 API version/trafficpolicyinstance -// resource. -// // Amazon Route 53 returns a maximum of 100 items in each response. If you have // a lot of traffic policy instances, you can use the MaxItems parameter to // list them in groups of up to 100. // -// The response includes five values that help you navigate from one group of -// MaxItems traffic policy instances to the next: -// -// * IsTruncated -// -// If the value of IsTruncated in the response is true, there are more traffic -// policy instances associated with the current AWS account. -// -// If IsTruncated is false, this response includes the last traffic policy instance -// that is associated with the current account. -// -// * MaxItems -// -// The value that you specified for the MaxItems parameter in the request that -// produced the current response. -// -// * HostedZoneIdMarker, TrafficPolicyInstanceNameMarker, and TrafficPolicyInstanceTypeMarker -// -// If IsTruncated is true, these three values in the response represent the -// first traffic policy instance in the next group of MaxItems traffic policy -// instances. To list more traffic policy instances, make another call to -// ListTrafficPolicyInstances, and specify these values in the corresponding -// request parameters. -// -// If IsTruncated is false, all three elements are omitted from the response. -// // 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. @@ -3582,8 +4122,23 @@ func (c *Route53) ListTrafficPolicyInstancesRequest(input *ListTrafficPolicyInst // Please also see https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/ListTrafficPolicyInstances func (c *Route53) ListTrafficPolicyInstances(input *ListTrafficPolicyInstancesInput) (*ListTrafficPolicyInstancesOutput, error) { req, out := c.ListTrafficPolicyInstancesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListTrafficPolicyInstancesWithContext is the same as ListTrafficPolicyInstances with the addition of +// the ability to pass a context and additional request options. +// +// See ListTrafficPolicyInstances 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 *Route53) ListTrafficPolicyInstancesWithContext(ctx aws.Context, input *ListTrafficPolicyInstancesInput, opts ...request.Option) (*ListTrafficPolicyInstancesOutput, error) { + req, out := c.ListTrafficPolicyInstancesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opListTrafficPolicyInstancesByHostedZone = "ListTrafficPolicyInstancesByHostedZone" @@ -3634,44 +4189,15 @@ func (c *Route53) ListTrafficPolicyInstancesByHostedZoneRequest(input *ListTraff // Gets information about the traffic policy instances that you created in a // specified hosted zone. // -// After you submit an UpdateTrafficPolicyInstance request, there's a brief -// delay while Amazon Route 53 creates the resource record sets that are specified -// in the traffic policy definition. For more information, see the State response -// element. -// -// Send a GET request to the /Amazon Route 53 API version/trafficpolicyinstance -// resource and include the ID of the hosted zone. +// After you submit a CreateTrafficPolicyInstance or an UpdateTrafficPolicyInstance +// request, there's a brief delay while Amazon Route 53 creates the resource +// record sets that are specified in the traffic policy definition. For more +// information, see the State response element. // // Amazon Route 53 returns a maximum of 100 items in each response. If you have // a lot of traffic policy instances, you can use the MaxItems parameter to // list them in groups of up to 100. // -// The response includes four values that help you navigate from one group of -// MaxItems traffic policy instances to the next: -// -// * IsTruncated -// -// If the value of IsTruncated in the response is true, there are more traffic -// policy instances associated with the current AWS account. -// -// * If IsTruncated is false, this response includes the last traffic policy -// instance that is associated with the current account. -// -// * MaxItems -// -// * The value that you specified for the MaxItems parameter in the request -// that produced the current response. -// -// * TrafficPolicyInstanceNameMarker and TrafficPolicyInstanceTypeMarker -// -// * If IsTruncated is true, these two values in the response represent the -// first traffic policy instance in the next group of MaxItems traffic policy -// instances. To list more traffic policy instances, make another call to -// ListTrafficPolicyInstancesByHostedZone, and specify these values in the -// corresponding request parameters. -// -// * If IsTruncated is false, all three elements are omitted from the response. -// // 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. @@ -3692,8 +4218,23 @@ func (c *Route53) ListTrafficPolicyInstancesByHostedZoneRequest(input *ListTraff // Please also see https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/ListTrafficPolicyInstancesByHostedZone func (c *Route53) ListTrafficPolicyInstancesByHostedZone(input *ListTrafficPolicyInstancesByHostedZoneInput) (*ListTrafficPolicyInstancesByHostedZoneOutput, error) { req, out := c.ListTrafficPolicyInstancesByHostedZoneRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListTrafficPolicyInstancesByHostedZoneWithContext is the same as ListTrafficPolicyInstancesByHostedZone with the addition of +// the ability to pass a context and additional request options. +// +// See ListTrafficPolicyInstancesByHostedZone 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 *Route53) ListTrafficPolicyInstancesByHostedZoneWithContext(ctx aws.Context, input *ListTrafficPolicyInstancesByHostedZoneInput, opts ...request.Option) (*ListTrafficPolicyInstancesByHostedZoneOutput, error) { + req, out := c.ListTrafficPolicyInstancesByHostedZoneRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opListTrafficPolicyInstancesByPolicy = "ListTrafficPolicyInstancesByPolicy" @@ -3749,38 +4290,10 @@ func (c *Route53) ListTrafficPolicyInstancesByPolicyRequest(input *ListTrafficPo // record sets that are specified in the traffic policy definition. For more // information, see the State response element. // -// Send a GET request to the /Route 53 API version/trafficpolicyinstance resource -// and include the ID and version of the traffic policy. -// // Amazon Route 53 returns a maximum of 100 items in each response. If you have // a lot of traffic policy instances, you can use the MaxItems parameter to // list them in groups of up to 100. // -// The response includes five values that help you navigate from one group of -// MaxItems traffic policy instances to the next: -// -// * IsTruncated -// -// If the value of IsTruncated in the response is true, there are more traffic -// policy instances associated with the specified traffic policy. -// -// If IsTruncated is false, this response includes the last traffic policy instance -// that is associated with the specified traffic policy. -// -// * MaxItems -// -// The value that you specified for the MaxItems parameter in the request that -// produced the current response. -// -// * HostedZoneIdMarker, TrafficPolicyInstanceNameMarker, and TrafficPolicyInstanceTypeMarker -// -// If IsTruncated is true, these values in the response represent the first -// traffic policy instance in the next group of MaxItems traffic policy instances. -// To list more traffic policy instances, make another call to ListTrafficPolicyInstancesByPolicy, -// and specify these values in the corresponding request parameters. -// -// If IsTruncated is false, all three elements are omitted from the response. -// // 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. @@ -3801,8 +4314,23 @@ func (c *Route53) ListTrafficPolicyInstancesByPolicyRequest(input *ListTrafficPo // Please also see https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/ListTrafficPolicyInstancesByPolicy func (c *Route53) ListTrafficPolicyInstancesByPolicy(input *ListTrafficPolicyInstancesByPolicyInput) (*ListTrafficPolicyInstancesByPolicyOutput, error) { req, out := c.ListTrafficPolicyInstancesByPolicyRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListTrafficPolicyInstancesByPolicyWithContext is the same as ListTrafficPolicyInstancesByPolicy with the addition of +// the ability to pass a context and additional request options. +// +// See ListTrafficPolicyInstancesByPolicy 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 *Route53) ListTrafficPolicyInstancesByPolicyWithContext(ctx aws.Context, input *ListTrafficPolicyInstancesByPolicyInput, opts ...request.Option) (*ListTrafficPolicyInstancesByPolicyOutput, error) { + req, out := c.ListTrafficPolicyInstancesByPolicyRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opListTrafficPolicyVersions = "ListTrafficPolicyVersions" @@ -3852,38 +4380,7 @@ func (c *Route53) ListTrafficPolicyVersionsRequest(input *ListTrafficPolicyVersi // // Gets information about all of the versions for a specified traffic policy. // -// Send a GET request to the /Amazon Route 53 API version/trafficpolicy resource -// and specify the ID of the traffic policy for which you want to list versions. -// -// Amazon Route 53 returns a maximum of 100 items in each response. If you have -// a lot of traffic policies, you can use the maxitems parameter to list them -// in groups of up to 100. -// -// The response includes three values that help you navigate from one group -// of maxitems traffic policies to the next: -// -// * IsTruncated -// -// If the value of IsTruncated in the response is true, there are more traffic -// policy versions associated with the specified traffic policy. -// -// If IsTruncated is false, this response includes the last traffic policy version -// that is associated with the specified traffic policy. -// -// * TrafficPolicyVersionMarker -// -// The ID of the next traffic policy version that is associated with the current -// AWS account. If you want to list more traffic policies, make another call -// to ListTrafficPolicyVersions, and specify the value of the TrafficPolicyVersionMarker -// element in the TrafficPolicyVersionMarker request parameter. -// -// If IsTruncated is false, Amazon Route 53 omits the TrafficPolicyVersionMarker -// element from the response. -// -// * MaxItems -// -// The value that you specified for the MaxItems parameter in the request that -// produced the current response. +// Traffic policy versions are listed in numerical order by VersionNumber. // // 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 @@ -3902,8 +4399,23 @@ func (c *Route53) ListTrafficPolicyVersionsRequest(input *ListTrafficPolicyVersi // Please also see https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/ListTrafficPolicyVersions func (c *Route53) ListTrafficPolicyVersions(input *ListTrafficPolicyVersionsInput) (*ListTrafficPolicyVersionsOutput, error) { req, out := c.ListTrafficPolicyVersionsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListTrafficPolicyVersionsWithContext is the same as ListTrafficPolicyVersions with the addition of +// the ability to pass a context and additional request options. +// +// See ListTrafficPolicyVersions 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 *Route53) ListTrafficPolicyVersionsWithContext(ctx aws.Context, input *ListTrafficPolicyVersionsInput, opts ...request.Option) (*ListTrafficPolicyVersionsOutput, error) { + req, out := c.ListTrafficPolicyVersionsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opListVPCAssociationAuthorizations = "ListVPCAssociationAuthorizations" @@ -3955,23 +4467,8 @@ func (c *Route53) ListVPCAssociationAuthorizationsRequest(input *ListVPCAssociat // be associated with a specified hosted zone because you've submitted one or // more CreateVPCAssociationAuthorization requests. // -// Send a GET request to the /2013-04-01/hostedzone/hosted zone ID/authorizevpcassociation -// resource. The response to this request includes a VPCs element with a VPC -// child element for each VPC that can be associated with the hosted zone. -// -// Amazon Route 53 returns up to 50 VPCs per page. To return fewer VPCs per -// page, include the MaxResults parameter: -// -// /2013-04-01/hostedzone/hosted zone ID/authorizevpcassociation?MaxItems=VPCs -// per page -// -// If the response includes a NextToken element, there are more VPCs to list. -// To get the next page of VPCs, submit another ListVPCAssociationAuthorizations -// request, and include the value of the NextToken element from the response -// in the NextToken request parameter: -// -// /2013-04-01/hostedzone/hosted zone ID/authorizevpcassociation?MaxItems=VPCs -// per page&NextToken= +// The response includes a VPCs element with a VPC child element for each VPC +// that can be associated with the hosted zone. // // 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 @@ -3992,8 +4489,23 @@ func (c *Route53) ListVPCAssociationAuthorizationsRequest(input *ListVPCAssociat // Please also see https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/ListVPCAssociationAuthorizations func (c *Route53) ListVPCAssociationAuthorizations(input *ListVPCAssociationAuthorizationsInput) (*ListVPCAssociationAuthorizationsOutput, error) { req, out := c.ListVPCAssociationAuthorizationsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListVPCAssociationAuthorizationsWithContext is the same as ListVPCAssociationAuthorizations with the addition of +// the ability to pass a context and additional request options. +// +// See ListVPCAssociationAuthorizations 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 *Route53) ListVPCAssociationAuthorizationsWithContext(ctx aws.Context, input *ListVPCAssociationAuthorizationsInput, opts ...request.Option) (*ListVPCAssociationAuthorizationsOutput, error) { + req, out := c.ListVPCAssociationAuthorizationsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opTestDNSAnswer = "TestDNSAnswer" @@ -4062,8 +4574,23 @@ func (c *Route53) TestDNSAnswerRequest(input *TestDNSAnswerInput) (req *request. // Please also see https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/TestDNSAnswer func (c *Route53) TestDNSAnswer(input *TestDNSAnswerInput) (*TestDNSAnswerOutput, error) { req, out := c.TestDNSAnswerRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// TestDNSAnswerWithContext is the same as TestDNSAnswer with the addition of +// the ability to pass a context and additional request options. +// +// See TestDNSAnswer 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 *Route53) TestDNSAnswerWithContext(ctx aws.Context, input *TestDNSAnswerInput, opts ...request.Option) (*TestDNSAnswerOutput, error) { + req, out := c.TestDNSAnswerRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opUpdateHealthCheck = "UpdateHealthCheck" @@ -4111,12 +4638,10 @@ func (c *Route53) UpdateHealthCheckRequest(input *UpdateHealthCheckInput) (req * // UpdateHealthCheck API operation for Amazon Route 53. // -// Updates an existing health check. +// Updates an existing health check. Note that some values can't be updated. // -// Send a POST request to the /2013-04-01/healthcheck/health check ID resource. -// The request body must include a document with an UpdateHealthCheckRequest -// element. For more information about updating health checks, see Creating, -// Updating, and Deleting Health Checks (http://docs.aws.amazon.com/Route53/latest/DeveloperGuide/health-checks-creating-deleting.html) +// For more information about updating health checks, see Creating, Updating, +// and Deleting Health Checks (http://docs.aws.amazon.com/Route53/latest/DeveloperGuide/health-checks-creating-deleting.html) // in the Amazon Route 53 Developer Guide. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions @@ -4141,8 +4666,23 @@ func (c *Route53) UpdateHealthCheckRequest(input *UpdateHealthCheckInput) (req * // Please also see https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/UpdateHealthCheck func (c *Route53) UpdateHealthCheck(input *UpdateHealthCheckInput) (*UpdateHealthCheckOutput, error) { req, out := c.UpdateHealthCheckRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// UpdateHealthCheckWithContext is the same as UpdateHealthCheck with the addition of +// the ability to pass a context and additional request options. +// +// See UpdateHealthCheck 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 *Route53) UpdateHealthCheckWithContext(ctx aws.Context, input *UpdateHealthCheckInput, opts ...request.Option) (*UpdateHealthCheckOutput, error) { + req, out := c.UpdateHealthCheckRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opUpdateHostedZoneComment = "UpdateHostedZoneComment" @@ -4190,8 +4730,7 @@ func (c *Route53) UpdateHostedZoneCommentRequest(input *UpdateHostedZoneCommentI // UpdateHostedZoneComment API operation for Amazon Route 53. // -// Updates the hosted zone comment. Send a POST request to the /2013-04-01/hostedzone/hosted -// zone ID resource. +// Updates the comment for a specified hosted zone. // // 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 @@ -4210,8 +4749,23 @@ func (c *Route53) UpdateHostedZoneCommentRequest(input *UpdateHostedZoneCommentI // Please also see https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/UpdateHostedZoneComment func (c *Route53) UpdateHostedZoneComment(input *UpdateHostedZoneCommentInput) (*UpdateHostedZoneCommentOutput, error) { req, out := c.UpdateHostedZoneCommentRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// UpdateHostedZoneCommentWithContext is the same as UpdateHostedZoneComment with the addition of +// the ability to pass a context and additional request options. +// +// See UpdateHostedZoneComment 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 *Route53) UpdateHostedZoneCommentWithContext(ctx aws.Context, input *UpdateHostedZoneCommentInput, opts ...request.Option) (*UpdateHostedZoneCommentOutput, error) { + req, out := c.UpdateHostedZoneCommentRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opUpdateTrafficPolicyComment = "UpdateTrafficPolicyComment" @@ -4261,11 +4815,6 @@ func (c *Route53) UpdateTrafficPolicyCommentRequest(input *UpdateTrafficPolicyCo // // Updates the comment for a specified traffic policy version. // -// Send a POST request to the /2013-04-01/trafficpolicy/ resource. -// -// The request body must include a document with an UpdateTrafficPolicyCommentRequest -// element. -// // 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. @@ -4287,8 +4836,23 @@ func (c *Route53) UpdateTrafficPolicyCommentRequest(input *UpdateTrafficPolicyCo // Please also see https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/UpdateTrafficPolicyComment func (c *Route53) UpdateTrafficPolicyComment(input *UpdateTrafficPolicyCommentInput) (*UpdateTrafficPolicyCommentOutput, error) { req, out := c.UpdateTrafficPolicyCommentRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// UpdateTrafficPolicyCommentWithContext is the same as UpdateTrafficPolicyComment with the addition of +// the ability to pass a context and additional request options. +// +// See UpdateTrafficPolicyComment 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 *Route53) UpdateTrafficPolicyCommentWithContext(ctx aws.Context, input *UpdateTrafficPolicyCommentInput, opts ...request.Option) (*UpdateTrafficPolicyCommentOutput, error) { + req, out := c.UpdateTrafficPolicyCommentRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opUpdateTrafficPolicyInstance = "UpdateTrafficPolicyInstance" @@ -4339,17 +4903,13 @@ func (c *Route53) UpdateTrafficPolicyInstanceRequest(input *UpdateTrafficPolicyI // Updates the resource record sets in a specified hosted zone that were created // based on the settings in a specified traffic policy version. // -// Send a POST request to the /2013-04-01/trafficpolicyinstance/traffic policy -// ID resource. The request body must include a document with an UpdateTrafficPolicyInstanceRequest -// element. -// // When you update a traffic policy instance, Amazon Route 53 continues to respond // to DNS queries for the root resource record set name (such as example.com) // while it replaces one group of resource record sets with another. Amazon // Route 53 performs the following operations: // // Amazon Route 53 creates a new group of resource record sets based on the -// specified traffic policy. This is true regardless of how substantial the +// specified traffic policy. This is true regardless of how significant the // differences are between the existing resource record sets and the new resource // record sets. // @@ -4392,8 +4952,23 @@ func (c *Route53) UpdateTrafficPolicyInstanceRequest(input *UpdateTrafficPolicyI // Please also see https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/UpdateTrafficPolicyInstance func (c *Route53) UpdateTrafficPolicyInstance(input *UpdateTrafficPolicyInstanceInput) (*UpdateTrafficPolicyInstanceOutput, error) { req, out := c.UpdateTrafficPolicyInstanceRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// UpdateTrafficPolicyInstanceWithContext is the same as UpdateTrafficPolicyInstance with the addition of +// the ability to pass a context and additional request options. +// +// See UpdateTrafficPolicyInstance 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 *Route53) UpdateTrafficPolicyInstanceWithContext(ctx aws.Context, input *UpdateTrafficPolicyInstanceInput, opts ...request.Option) (*UpdateTrafficPolicyInstanceOutput, error) { + req, out := c.UpdateTrafficPolicyInstanceRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // A complex type that identifies the CloudWatch alarm that you want Amazon @@ -4547,37 +5122,10 @@ type AliasTarget struct { // DNSName is a required field DNSName *string `type:"string" required:"true"` - // Applies only to alias, weighted alias, latency alias, and failover alias - // record sets: If you set the value of EvaluateTargetHealth to true for the - // resource record set or sets in an alias, weighted alias, latency alias, or - // failover alias resource record set, and if you specify a value for HealthCheck$Id - // for every resource record set that is referenced by these alias resource - // record sets, the alias resource record sets inherit the health of the referenced - // resource record sets. - // - // In this configuration, when Amazon Route 53 receives a DNS query for an alias - // resource record set: - // - // * Amazon Route 53 looks at the resource record sets that are referenced - // by the alias resource record sets to determine which health checks they're - // using. - // - // * Amazon Route 53 checks the current status of each health check. (Amazon - // Route 53 periodically checks the health of the endpoint that is specified - // in a health check; it doesn't perform the health check when the DNS query - // arrives.) - // - // * Based on the status of the health checks, Amazon Route 53 determines - // which resource record sets are healthy. Unhealthy resource record sets - // are immediately removed from consideration. In addition, if all of the - // resource record sets that are referenced by an alias resource record set - // are unhealthy, that alias resource record set also is immediately removed - // from consideration. - // - // * Based on the configuration of the alias resource record sets (weighted - // alias or latency alias, for example) and the configuration of the resource - // record sets that they reference, Amazon Route 53 chooses a resource record - // set from the healthy resource record sets, and responds to the query. + // Applies only to alias, failover alias, geolocation alias, latency alias, + // and weighted alias resource record sets: When EvaluateTargetHealth is true, + // an alias resource record set inherits the health of the referenced AWS resource, + // such as an ELB load balancer, or the referenced resource record set. // // Note the following: // @@ -4588,7 +5136,7 @@ type AliasTarget struct { // set or a group of resource record sets (for example, a group of weighted // resource record sets), but it is not another alias resource record set, // we recommend that you associate a health check with all of the resource - // record sets in the alias target.For more information, see What Happens + // record sets in the alias target. For more information, see What Happens // When You Omit Health Checks? (http://docs.aws.amazon.com/Route53/latest/DeveloperGuide/dns-failover-complex-configs.html#dns-failover-complex-configs-hc-omitting) // in the Amazon Route 53 Developer Guide. // @@ -4603,19 +5151,19 @@ type AliasTarget struct { // // If the environment contains a single EC2 instance, there are no special requirements. // - // * If you specify an ELB load balancer in AliasTarget, Elastic Load Balancing - // routes queries only to the healthy EC2 instances that are registered with - // the load balancer. If no EC2 instances are healthy or if the load balancer - // itself is unhealthy, and if EvaluateTargetHealth is true for the corresponding - // alias resource record set, Amazon Route 53 routes queries to other resources. - // When you create a load balancer, you configure settings for Elastic Load - // Balancing health checks; they're not Amazon Route 53 health checks, but - // they perform a similar function. Do not create Amazon Route 53 health - // checks for the EC2 instances that you register with an ELB load balancer. + // * If you specify an ELB load balancer in AliasTarget, ELB routes queries + // only to the healthy EC2 instances that are registered with the load balancer. + // If no EC2 instances are healthy or if the load balancer itself is unhealthy, + // and if EvaluateTargetHealth is true for the corresponding alias resource + // record set, Amazon Route 53 routes queries to other resources. When you + // create a load balancer, you configure settings for ELB health checks; + // they're not Amazon Route 53 health checks, but they perform a similar + // function. Do not create Amazon Route 53 health checks for the EC2 instances + // that you register with an ELB load balancer. // // For more information, see How Health Checks Work in More Complex Amazon Route // 53 Configurations (http://docs.aws.amazon.com/Route53/latest/DeveloperGuide/dns-failover-complex-configs.html) - // in the Amazon Route 53 Developers Guide. + // in the Amazon Route 53 Developer Guide. // // * We recommend that you set EvaluateTargetHealth to true only when you // have enough idle capacity to handle the failure of one or more endpoints. @@ -5022,9 +5570,10 @@ type ChangeInfo struct { // Status is a required field Status *string `type:"string" required:"true" enum:"ChangeStatus"` - // The date and time the change request was submitted, in Coordinated Universal - // Time (UTC) format: YYYY-MM-DDThh:mm:ssZ. For more information, see the Wikipedia - // entry ISO 8601 (https://en.wikipedia.org/wiki/ISO_8601). + // The date and time that the change request was submitted in ISO 8601 format + // (https://en.wikipedia.org/wiki/ISO_8601) and Coordinated Universal Time (UTC). + // For example, the value 2017-03-27T17:48:16.751Z represents March 27, 2017 + // at 17:48:16.751 UTC. // // SubmittedAt is a required field SubmittedAt *time.Time `type:"timestamp" timestampFormat:"iso8601" required:"true"` @@ -5162,8 +5711,8 @@ type ChangeTagsForResourceInput struct { _ struct{} `locationName:"ChangeTagsForResourceRequest" type:"structure" xmlURI:"https://route53.amazonaws.com/doc/2013-04-01/"` // A complex type that contains a list of the tags that you want to add to the - // specified health check or hosted zone and/or the tags for which you want - // to edit the Value element. + // specified health check or hosted zone and/or the tags that you want to edit + // Value for. // // You can add a maximum of 10 tags to a health check or a hosted zone. AddTags []*Tag `locationNameList:"Tag" min:"1" type:"list"` @@ -5272,7 +5821,7 @@ type CloudWatchAlarmConfiguration struct { ComparisonOperator *string `type:"string" required:"true" enum:"ComparisonOperator"` // For the metric that the CloudWatch alarm is associated with, a complex type - // that contains information about the dimensions for the metric.For information, + // that contains information about the dimensions for the metric. For information, // see Amazon CloudWatch Namespaces, Dimensions, and Metrics Reference (http://docs.aws.amazon.com/AmazonCloudWatch/latest/DeveloperGuide/CW_Support_For_AWS.html) // in the Amazon CloudWatch User Guide. Dimensions []*Dimension `locationNameList:"Dimension" type:"list"` @@ -5377,10 +5926,26 @@ func (s *CloudWatchAlarmConfiguration) SetThreshold(v float64) *CloudWatchAlarmC type CreateHealthCheckInput struct { _ struct{} `locationName:"CreateHealthCheckRequest" type:"structure" xmlURI:"https://route53.amazonaws.com/doc/2013-04-01/"` - // A unique string that identifies the request and that allows failed CreateHealthCheck - // requests to be retried without the risk of executing the operation twice. - // You must use a unique CallerReference string every time you create a health - // check. + // A unique string that identifies the request and that allows you to retry + // a failed CreateHealthCheck request without the risk of creating two identical + // health checks: + // + // * If you send a CreateHealthCheck request with the same CallerReference + // and settings as a previous request, and if the health check doesn't exist, + // Amazon Route 53 creates the health check. If the health check does exist, + // Amazon Route 53 returns the settings for the existing health check. + // + // * If you send a CreateHealthCheck request with the same CallerReference + // as a deleted health check, regardless of the settings, Amazon Route 53 + // returns a HealthCheckAlreadyExists error. + // + // * If you send a CreateHealthCheck request with the same CallerReference + // as an existing health check but with different settings, Amazon Route + // 53 returns a HealthCheckAlreadyExists error. + // + // * If you send a CreateHealthCheck request with a unique CallerReference + // but settings identical to an existing health check, Amazon Route 53 creates + // the health check. // // CallerReference is a required field CallerReference *string `min:"1" type:"string" required:"true"` @@ -5475,15 +6040,16 @@ func (s *CreateHealthCheckOutput) SetLocation(v string) *CreateHealthCheckOutput return s } -// A complex type containing the hosted zone request information. +// A complex type that contains information about the request to create a hosted +// zone. // Please also see https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/CreateHostedZoneRequest type CreateHostedZoneInput struct { _ struct{} `locationName:"CreateHostedZoneRequest" type:"structure" xmlURI:"https://route53.amazonaws.com/doc/2013-04-01/"` // A unique string that identifies the request and that allows failed CreateHostedZone // requests to be retried without the risk of executing the operation twice. - // You must use a unique CallerReference string every time you create a hosted - // zone. CallerReference can be any unique string, for example, a date/time + // You must use a unique CallerReference string every time you submit a CreateHostedZone + // request. CallerReference can be any unique string, for example, a date/time // stamp. // // CallerReference is a required field @@ -5493,17 +6059,16 @@ type CreateHostedZoneInput struct { // the ID that Amazon Route 53 assigned to the reusable delegation set when // you created it. For more information about reusable delegation sets, see // CreateReusableDelegationSet. - // - // TypeString - // - // DefaultNone - // - // ParentCreatedHostedZoneRequest DelegationSetId *string `type:"string"` - // (Optional) A complex type that contains an optional comment about your hosted - // zone. If you don't want to specify a comment, omit both the HostedZoneConfig - // and Comment elements. + // (Optional) A complex type that contains the following optional values: + // + // * For public and private hosted zones, an optional comment + // + // * For private hosted zones, an optional PrivateZone element + // + // If you don't specify a comment or the PrivateZone element, omit HostedZoneConfig + // and the other elements. HostedZoneConfig *HostedZoneConfig `type:"structure"` // The name of the domain. For resource record types that include a domain name, @@ -5515,14 +6080,17 @@ type CreateHostedZoneInput struct { // If you're creating a public hosted zone, this is the name you have registered // with your DNS registrar. If your domain name is registered with a registrar // other than Amazon Route 53, change the name servers for your domain to the - // set of NameServers that CreateHostedZone returns in the DelegationSet element. + // set of NameServers that CreateHostedZone returns in DelegationSet. // // Name is a required field Name *string `type:"string" required:"true"` - // The VPC that you want your hosted zone to be associated with. By providing - // this parameter, your newly created hosted can't be resolved anywhere other - // than the given VPC. + // (Private hosted zones only) A complex type that contains information about + // the Amazon VPC that you're associating with this hosted zone. + // + // You can specify only one Amazon VPC when you create a private hosted zone. + // To associate additional Amazon VPCs with the hosted zone, use AssociateVPCWithHostedZone + // after you create a hosted zone. VPC *VPC `type:"structure"` } @@ -5595,7 +6163,7 @@ func (s *CreateHostedZoneInput) SetVPC(v *VPC) *CreateHostedZoneInput { type CreateHostedZoneOutput struct { _ struct{} `type:"structure"` - // A complex type that describes the changes made to your hosted zone. + // A complex type that contains information about the CreateHostedZone request. // // ChangeInfo is a required field ChangeInfo *ChangeInfo `type:"structure" required:"true"` @@ -6005,8 +6573,8 @@ func (s *CreateTrafficPolicyOutput) SetTrafficPolicy(v *TrafficPolicy) *CreateTr return s } -// A complex type that contains information about the traffic policy for which -// you want to create a new version. +// A complex type that contains information about the traffic policy that you +// want to create a new version for. // Please also see https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/CreateTrafficPolicyVersionRequest type CreateTrafficPolicyVersionInput struct { _ struct{} `locationName:"CreateTrafficPolicyVersionRequest" type:"structure" xmlURI:"https://route53.amazonaws.com/doc/2013-04-01/"` @@ -6217,23 +6785,21 @@ func (s *CreateVPCAssociationAuthorizationOutput) SetVPC(v *VPC) *CreateVPCAssoc return s } -// A complex type that describes the name servers for this hosted zone. +// A complex type that lists the name servers in a delegation set, as well as +// the CallerReference and the ID for the delegation set. // Please also see https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/DelegationSet type DelegationSet struct { _ struct{} `type:"structure"` - // A unique string that identifies the request, and that allows you to retry - // failed CreateReusableDelegationSet requests without the risk of executing - // the operation twice. You must use a unique CallerReference string every time - // you submit a CreateReusableDelegationSet request. CallerReference can be - // any unique string, for example, a date/time stamp. + // The value that you specified for CallerReference when you created the reusable + // delegation set. CallerReference *string `min:"1" type:"string"` // The ID that Amazon Route 53 assigns to a reusable delegation set. Id *string `type:"string"` // A complex type that contains a list of the authoritative name servers for - // the hosted zone. + // a hosted zone or for a reusable delegation set. // // NameServers is a required field NameServers []*string `locationNameList:"NameServer" min:"1" type:"list" required:"true"` @@ -6267,8 +6833,7 @@ func (s *DelegationSet) SetNameServers(v []*string) *DelegationSet { return s } -// This action deletes a health check. Send a DELETE request to the /2013-04-01/DeleteHealthCheckRequest -// resource. +// This action deletes a health check. // Please also see https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/DeleteHealthCheckRequest type DeleteHealthCheckInput struct { _ struct{} `type:"structure"` @@ -6324,8 +6889,7 @@ func (s DeleteHealthCheckOutput) GoString() string { return s.String() } -// A complex type that contains information about the hosted zone that you want -// to delete. +// A request to delete a hosted zone. // Please also see https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/DeleteHostedZoneRequest type DeleteHostedZoneInput struct { _ struct{} `type:"structure"` @@ -6365,13 +6929,13 @@ func (s *DeleteHostedZoneInput) SetId(v string) *DeleteHostedZoneInput { return s } -// A complex type containing the response information for the request. +// A complex type that contains the response to a DeleteHostedZone request. // Please also see https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/DeleteHostedZoneResponse type DeleteHostedZoneOutput struct { _ struct{} `type:"structure"` // A complex type that contains the ID, the status, and the date and time of - // your delete request. + // a request to delete a hosted zone. // // ChangeInfo is a required field ChangeInfo *ChangeInfo `type:"structure" required:"true"` @@ -6393,12 +6957,12 @@ func (s *DeleteHostedZoneOutput) SetChangeInfo(v *ChangeInfo) *DeleteHostedZoneO return s } -// A complex type containing the information for the delete request. +// A request to delete a reusable delegation set. // Please also see https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/DeleteReusableDelegationSetRequest type DeleteReusableDelegationSetInput struct { _ struct{} `type:"structure"` - // The ID of the reusable delegation set you want to delete. + // The ID of the reusable delegation set that you want to delete. // // Id is a required field Id *string `location:"uri" locationName:"Id" type:"string" required:"true"` @@ -6509,8 +7073,7 @@ func (s *DeleteTrafficPolicyInput) SetVersion(v int64) *DeleteTrafficPolicyInput return s } -// A complex type that contains information about the traffic policy instance -// that you want to delete. +// A request to delete a specified traffic policy instance. // Please also see https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/DeleteTrafficPolicyInstanceRequest type DeleteTrafficPolicyInstanceInput struct { _ struct{} `type:"structure"` @@ -7059,7 +7622,8 @@ func (s *GetCheckerIpRangesOutput) SetCheckerIpRanges(v []*string) *GetCheckerIp return s } -// A complex type that contains information about the request to get a geo location. +// A request for information about whether a specified geographic location is +// supported for Amazon Route 53 geolocation resource record sets. // Please also see https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/GetGeoLocationRequest type GetGeoLocationInput struct { _ struct{} `type:"structure"` @@ -7168,8 +7732,8 @@ func (s *GetGeoLocationOutput) SetGeoLocationDetails(v *GeoLocationDetails) *Get return s } -// To retrieve a count of all your health checks, send a GET request to the -// /2013-04-01/healthcheckcount resource. +// A request for the number of health checks that are associated with the current +// AWS account. // Please also see https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/GetHealthCheckCountRequest type GetHealthCheckCountInput struct { _ struct{} `type:"structure"` @@ -7185,7 +7749,7 @@ func (s GetHealthCheckCountInput) GoString() string { return s.String() } -// A complex type that contains the response to a healthcheckcount request. +// A complex type that contains the response to a GetHealthCheckCount request. // Please also see https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/GetHealthCheckCountResponse type GetHealthCheckCountOutput struct { _ struct{} `type:"structure"` @@ -7212,15 +7776,7 @@ func (s *GetHealthCheckCountOutput) SetHealthCheckCount(v int64) *GetHealthCheck return s } -// This action gets information about a specified health check. -// -// Send a GET request to the /Amazon Route 53 API version/gethealthcheckrequest -// resource. -// -// For information about getting information about a health check using the -// Amazon Route 53 console, see Amazon Route 53 Health Checks and DNS Failover -// (http://docs.aws.amazon.com/Route53/latest/DeveloperGuide/dns-failover.html) -// in the Amazon Route 53 Developer Guide. +// A request to get information about a specified health check. // Please also see https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/GetHealthCheckRequest type GetHealthCheckInput struct { _ struct{} `type:"structure"` @@ -7263,15 +7819,7 @@ func (s *GetHealthCheckInput) SetHealthCheckId(v string) *GetHealthCheckInput { return s } -// This action gets the reason that a specified health check failed most recently. -// -// To get the reason for the last failure of a health check, send a GET request -// to the /2013-04-01/healthcheck/health check ID/lastfailurereason resource. -// -// For information about viewing the last failure reason for a health check -// using the Amazon Route 53 console, see Viewing Health Check Status and the -// Reason for Health Check Failures (http://docs.aws.amazon.com/Route53/latest/DeveloperGuide/health-checks-monitor-view-status.html) -// in the Amazon Route 53 Developer Guide. +// A request for the reason that a health check failed most recently. // Please also see https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/GetHealthCheckLastFailureReasonRequest type GetHealthCheckLastFailureReasonInput struct { _ struct{} `type:"structure"` @@ -7370,13 +7918,12 @@ func (s *GetHealthCheckOutput) SetHealthCheck(v *HealthCheck) *GetHealthCheckOut return s } -// A complex type that contains information about the request to get health -// check status for a health check. +// A request to get the status for a health check. // Please also see https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/GetHealthCheckStatusRequest type GetHealthCheckStatusInput struct { _ struct{} `type:"structure"` - // The ID for the health check for which you want the current status. When you + // The ID for the health check that you want the current status for. When you // created the health check, CreateHealthCheck returned the ID in the response, // in the HealthCheckId element. // @@ -7445,8 +7992,8 @@ func (s *GetHealthCheckStatusOutput) SetHealthCheckObservations(v []*HealthCheck return s } -// To retrieve a count of all your hosted zones, send a GET request to the /2013-04-01/hostedzonecount -// resource. +// A request to retrieve a count of all the hosted zones that are associated +// with the current AWS account. // Please also see https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/GetHostedZoneCountRequest type GetHostedZoneCountInput struct { _ struct{} `type:"structure"` @@ -7462,13 +8009,13 @@ func (s GetHostedZoneCountInput) GoString() string { return s.String() } -// A complex type that contains the response to a hostedzonecount request. +// A complex type that contains the response to a GetHostedZoneCount request. // Please also see https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/GetHostedZoneCountResponse type GetHostedZoneCountOutput struct { _ struct{} `type:"structure"` - // The total number of public and private hosted zones associated with the current - // AWS account. + // The total number of public and private hosted zones that are associated with + // the current AWS account. // // HostedZoneCount is a required field HostedZoneCount *int64 `type:"long" required:"true"` @@ -7490,13 +8037,12 @@ func (s *GetHostedZoneCountOutput) SetHostedZoneCount(v int64) *GetHostedZoneCou return s } -// The input for a GetHostedZone request. +// A request to get information about a specified hosted zone. // Please also see https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/GetHostedZoneRequest type GetHostedZoneInput struct { _ struct{} `type:"structure"` - // The ID of the hosted zone for which you want to get a list of the name servers - // in the delegation set. + // The ID of the hosted zone that you want to get information about. // // Id is a required field Id *string `location:"uri" locationName:"Id" type:"string" required:"true"` @@ -7531,21 +8077,23 @@ func (s *GetHostedZoneInput) SetId(v string) *GetHostedZoneInput { return s } -// A complex type containing the response information for the hosted zone. +// A complex type that contain the response to a GetHostedZone request. // Please also see https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/GetHostedZoneResponse type GetHostedZoneOutput struct { _ struct{} `type:"structure"` - // A complex type that describes the name servers for this hosted zone. + // A complex type that lists the Amazon Route 53 name servers for the specified + // hosted zone. DelegationSet *DelegationSet `type:"structure"` - // A complex type that contains general information about the hosted zone. + // A complex type that contains general information about the specified hosted + // zone. // // HostedZone is a required field HostedZone *HostedZone `type:"structure" required:"true"` - // A complex type that contains information about VPCs associated with the specified - // hosted zone. + // A complex type that contains information about the VPCs that are associated + // with the specified hosted zone. VPCs []*VPC `locationNameList:"VPC" min:"1" type:"list"` } @@ -7577,13 +8125,13 @@ func (s *GetHostedZoneOutput) SetVPCs(v []*VPC) *GetHostedZoneOutput { return s } -// The input for a GetReusableDelegationSet request. +// A request to get information about a specified reusable delegation set. // Please also see https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/GetReusableDelegationSetRequest type GetReusableDelegationSetInput struct { _ struct{} `type:"structure"` - // The ID of the reusable delegation set for which you want to get a list of - // the name server. + // The ID of the reusable delegation set that you want to get a list of name + // servers for. // // Id is a required field Id *string `location:"uri" locationName:"Id" type:"string" required:"true"` @@ -7646,9 +8194,7 @@ func (s *GetReusableDelegationSetOutput) SetDelegationSet(v *DelegationSet) *Get return s } -// Gets information about a specific traffic policy version. To get the information, -// send a GET request to the /2013-04-01/trafficpolicy resource, and specify -// the ID and the version of the traffic policy. +// Gets information about a specific traffic policy version. // Please also see https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/GetTrafficPolicyRequest type GetTrafficPolicyInput struct { _ struct{} `type:"structure"` @@ -7756,9 +8302,6 @@ func (s *GetTrafficPolicyInstanceCountOutput) SetTrafficPolicyInstanceCount(v in } // Gets information about a specified traffic policy instance. -// -// To get information about a traffic policy instance, send a GET request to -// the /Amazon Route 53 API version/trafficpolicyinstance/Id resource. // Please also see https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/GetTrafficPolicyInstanceRequest type GetTrafficPolicyInstanceInput struct { _ struct{} `type:"structure"` @@ -8098,10 +8641,10 @@ type HealthCheckConfig struct { // // * Unhealthy: Amazon Route 53 considers the health check to be unhealthy. // - // * LastKnownStatus: Amazon Route 53uses the status of the health check - // from the last time CloudWatch had sufficient data to determine the alarm - // state. For new health checks that have no last known status, the default - // status for the health check is healthy. + // * LastKnownStatus: Amazon Route 53 uses the status of the health check + // from the last time that CloudWatch had sufficient data to determine the + // alarm state. For new health checks that have no last known status, the + // default status for the health check is healthy. InsufficientDataHealthStatus *string `type:"string" enum:"InsufficientDataHealthStatus"` // Specify whether you want Amazon Route 53 to invert the status of a health @@ -8199,8 +8742,9 @@ type HealthCheckConfig struct { // Route 53 health checkers consider to be healthy and compares that number // with the value of HealthThreshold. // - // For more information about how Amazon Route 53 determines whether an endpoint - // is healthy, see the introduction to this topic. + // For more information, see How Amazon Route 53 Determines Whether an Endpoint + // Is Healthy (http://docs.aws.amazon.com/Route53/latest/DeveloperGuide/dns-failover-determining-health-of-endpoints.html) + // in the Amazon Route 53 Developer Guide. // // Type is a required field Type *string `type:"string" required:"true" enum:"HealthCheckType"` @@ -8500,15 +9044,8 @@ func (s *HostedZoneConfig) SetPrivateZone(v bool) *HostedZoneConfig { return s } -// To get a list of geographic locations that Amazon Route 53 supports for geolocation, -// send a GET request to the /Amazon Route 53 API version/geolocations resource. -// The response to this request includes a GeoLocationDetails element for each -// location that Amazon Route 53 supports. -// -// Countries are listed first, and continents are listed last. If Amazon Route -// 53 supports subdivisions for a country (for example, states or provinces), -// the subdivisions for that country are listed in alphabetical order immediately -// after the corresponding country. +// A request to get a list of geographic locations that Amazon Route 53 supports +// for geolocation resource record sets. // Please also see https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/ListGeoLocationsRequest type ListGeoLocationsInput struct { _ struct{} `type:"structure"` @@ -8630,17 +9167,17 @@ type ListGeoLocationsOutput struct { // If IsTruncated is true, you can make a follow-up request to display more // locations. Enter the value of NextContinentCode in the StartContinentCode - // parameter in another GETListGeoLocations request. + // parameter in another ListGeoLocations request. NextContinentCode *string `min:"2" type:"string"` // If IsTruncated is true, you can make a follow-up request to display more // locations. Enter the value of NextCountryCode in the StartCountryCode parameter - // in another GETListGeoLocations request. + // in another ListGeoLocations request. NextCountryCode *string `min:"1" type:"string"` // If IsTruncated is true, you can make a follow-up request to display more // locations. Enter the value of NextSubdivisionCode in the StartSubdivisionCode - // parameter in another GETListGeoLocations request. + // parameter in another ListGeoLocations request. NextSubdivisionCode *string `min:"1" type:"string"` } @@ -8690,41 +9227,27 @@ func (s *ListGeoLocationsOutput) SetNextSubdivisionCode(v string) *ListGeoLocati return s } -// To retrieve a list of your health checks, send a GET request to the /2013-04-01/healthcheck -// resource. The response to this request includes a HealthChecks element with -// zero or more HealthCheck child elements. By default, the list of health checks -// is displayed on a single page. You can control the length of the page that -// is displayed by using the MaxItems parameter. You can use the Marker parameter -// to control the health check that the list begins with. -// -// Amazon Route 53 returns a maximum of 100 items. If you set MaxItems to a -// value greater than 100, Amazon Route 53 returns only the first 100. +// A request to retrieve a list of the health checks that are associated with +// the current AWS account. // Please also see https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/ListHealthChecksRequest type ListHealthChecksInput struct { _ struct{} `type:"structure"` - // If the response to a ListHealthChecks is more than one page, marker is the - // health check ID for the first health check on the next page of results. For - // more information, see ListHealthChecksResponse$MaxItems. + // If the value of IsTruncated in the previous response was true, you have more + // health checks. To get another group, submit another ListHealthChecks request. + // + // For the value of marker, specify the value of NextMarker from the previous + // response, which is the ID of the first health check that Amazon Route 53 + // will return if you submit another request. + // + // If the value of IsTruncated in the previous response was false, there are + // no more health checks to get. Marker *string `location:"querystring" locationName:"marker" type:"string"` - // The maximum number of HealthCheck elements you want ListHealthChecks to return - // on each page of the response body. If the AWS account includes more HealthCheck - // elements than the value of maxitems, the response is broken into pages. Each - // page contains the number of HealthCheck elements specified by maxitems. - // - // For example, suppose you specify 10 for maxitems and the current AWS account - // has 51 health checks. In the response, ListHealthChecks sets ListHealthChecksResponse$IsTruncated - // to true and includes the ListHealthChecksResponse$NextMarker element. To - // access the second and subsequent pages, you resend the GETListHealthChecks - // request, add the ListHealthChecksResponse$Marker parameter to the request, - // and specify the value of the ListHealthChecksResponse$NextMarker element - // from the previous response. On the last (sixth) page of the response, which - // contains only one HealthCheck element: - // - // * The value of ListHealthChecksResponse$IsTruncated is false. - // - // * ListHealthChecksResponse$NextMarker is omitted. + // The maximum number of health checks that you want ListHealthChecks to return + // in response to the current request. Amazon Route 53 returns a maximum of + // 100 items. If you set MaxItems to a value greater than 100, Amazon Route + // 53 returns only the first 100 health checks. MaxItems *string `location:"querystring" locationName:"maxitems" type:"string"` } @@ -8762,11 +9285,9 @@ type ListHealthChecksOutput struct { HealthChecks []*HealthCheck `locationNameList:"HealthCheck" type:"list" required:"true"` // A flag that indicates whether there are more health checks to be listed. - // If the response was truncated, you can get the next group of maxitems health - // checks by calling ListHealthChecks again and specifying the value of the - // NextMarker element in the marker parameter. - // - // Valid Values: true | false + // If the response was truncated, you can get the next group of health checks + // by submitting another ListHealthChecks request and specifying the value of + // NextMarker in the marker parameter. // // IsTruncated is a required field IsTruncated *bool `type:"boolean" required:"true"` @@ -8784,8 +9305,8 @@ type ListHealthChecksOutput struct { MaxItems *string `type:"string" required:"true"` // If IsTruncated is true, the value of NextMarker identifies the first health - // check in the next group of maxitems health checks. Call ListHealthChecks - // again and specify the value of NextMarker in the marker parameter. + // check that Amazon Route 53 returns if you submit another ListHealthChecks + // request and specify the value of NextMarker in the marker parameter. NextMarker *string `type:"string"` } @@ -8829,52 +9350,8 @@ func (s *ListHealthChecksOutput) SetNextMarker(v string) *ListHealthChecksOutput return s } -// To retrieve a list of your public and private hosted zones in ASCII order -// by domain name, send a GET request to the /Amazon Route 53 API version/hostedzonesbyname -// resource. The response to this request includes a HostedZone child element -// for each hosted zone that was created by the current AWS account. ListHostedZonesByName -// sorts hosted zones by name with the labels reversed, for example: -// -// com.example.www. -// -// Note the trailing dot, which can change the sort order in some circumstances. -// -// If the domain name includes escape characters or Punycode, ListHostedZonesByName -// alphabetizes the domain name using the escaped or Punycoded value, which -// is the format that Amazon Route 53 saves in its database. For example, to -// create a hosted zone for exämple.com, you specify ex\344mple.com for the -// domain name. ListHostedZonesByName alphabetizes it as: com.ex\344mple. The -// labels are reversed, and it's alphabetized using the escaped value. For more -// information about valid domain name formats, including internationalized -// domain names, see DNS Domain Name Format (http://docs.aws.amazon.com/Route53/latest/DeveloperGuide/DomainNameFormat.html) -// in the Amazon Route 53 Developer Guide. -// -// Amazon Route 53 returns up to 100 items in each response. If you have a lot -// of hosted zones, you can use the MaxItems parameter to list them in groups -// of up to 100. The response includes values that help you navigate from one -// group of MaxItems hosted zones to the next: -// -// * The DNSName and HostedZoneId elements in the response contain the values, -// if any, that you specified for the dnsname and hostedzoneid parameters -// in the request that produced the current response. -// -// * The MaxItems element in the response contains the value, if any, that -// you specified for the maxitems parameter in the request that produced -// the current response. -// -// * If the value of IsTruncated in the response is true, there are more -// hosted zones associated with the current Amazon Route 53 account. -// -// If IsTruncated is false, this response includes the last hosted zone that -// is associated with the current account. The NextDNSName element and NextHostedZoneId -// elements are omitted from the response. -// -// * The NextDNSName and NextHostedZoneId elements in the response contain -// the domain name and the hosted zone ID of the next hosted zone that is -// associated with the current AWS account. If you want to list more hosted -// zones, make another call to ListHostedZonesByName, and specify the value -// of NextDNSName and NextHostedZoneId in the dnsname and hostedzoneid parameters, -// respectively. +// Retrieves a list of the public and private hosted zones that are associated +// with the current AWS account in ASCII order by domain name. // Please also see https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/ListHostedZonesByNameRequest type ListHostedZonesByNameInput struct { _ struct{} `type:"structure"` @@ -9037,35 +9514,8 @@ func (s *ListHostedZonesByNameOutput) SetNextHostedZoneId(v string) *ListHostedZ return s } -// To retrieve a list of your public and private hosted zones, send a GET request -// to the /2013-04-01/hostedzone resource. The response to this request includes -// a HostedZone child element for each hosted zone that was created by the current -// AWS account. -// -// Amazon Route 53 returns a maximum of 100 items in each response. If you have -// a lot of hosted zones, you can use the maxitems parameter to list them in -// groups of up to 100. The response includes four values that help you navigate -// from one group of maxitems hosted zones to the next: -// -// * MaxItems is the value that you specified for the maxitems parameter -// in the request that produced the current response. -// -// * If the value of IsTruncated in the response is true, there are more -// hosted zones associated with the current AWS account. -// -// If IsTruncated is false, this response includes the last hosted zone that -// is associated with the current account. -// -// * NextMarker is the hosted zone ID of the next hosted zone that is associated -// with the current AWS account. If you want to list more hosted zones, make -// another call to ListHostedZones, and specify the value of the NextMarker -// element in the marker parameter. -// -// If IsTruncated is false, the NextMarker element is omitted from the response. -// -// * If you're making the second or subsequent call to ListHostedZones, the -// Marker element matches the value that you specified in the marker parameter -// in the previous request. +// A request to retrieve a list of the public and private hosted zones that +// are associated with the current AWS account. // Please also see https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/ListHostedZonesRequest type ListHostedZonesInput struct { _ struct{} `type:"structure"` @@ -9075,20 +9525,22 @@ type ListHostedZonesInput struct { // the ID of that reusable delegation set. DelegationSetId *string `location:"querystring" locationName:"delegationsetid" type:"string"` - // (Optional) If you have more hosted zones than the value of maxitems, ListHostedZones - // returns only the first maxitems hosted zones. To get the next group of maxitems - // hosted zones, submit another request to ListHostedZones. For the value of - // marker, specify the value of the NextMarker element that was returned in - // the previous response. + // If the value of IsTruncated in the previous response was true, you have more + // hosted zones. To get more hosted zones, submit another ListHostedZones request. // - // Hosted zones are listed in the order in which they were created. + // For the value of marker, specify the value of NextMarker from the previous + // response, which is the ID of the first hosted zone that Amazon Route 53 will + // return if you submit another request. + // + // If the value of IsTruncated in the previous response was false, there are + // no more hosted zones to get. Marker *string `location:"querystring" locationName:"marker" type:"string"` - // (Optional) The maximum number of hosted zones to be included in the response - // body for this request. If you have more than maxitems hosted zones, the value - // of the IsTruncated element in the response is true, and the value of the - // NextMarker element is the hosted zone ID of the first hosted zone in the - // next group of maxitems hosted zones. + // (Optional) The maximum number of hosted zones that you want Amazon Route + // 53 to return. If you have more than maxitems hosted zones, the value of IsTruncated + // in the response is true, and the value of NextMarker is the hosted zone ID + // of the first hosted zone that Amazon Route 53 will return if you submit another + // request. MaxItems *string `location:"querystring" locationName:"maxitems" type:"string"` } @@ -9130,9 +9582,9 @@ type ListHostedZonesOutput struct { HostedZones []*HostedZone `locationNameList:"HostedZone" type:"list" required:"true"` // A flag indicating whether there are more hosted zones to be listed. If the - // response was truncated, you can get the next group of maxitems hosted zones - // by calling ListHostedZones again and specifying the value of the NextMarker - // element in the marker parameter. + // response was truncated, you can get more hosted zones by submitting another + // ListHostedZones request and specifying the value of NextMarker in the marker + // parameter. // // IsTruncated is a required field IsTruncated *bool `type:"boolean" required:"true"` @@ -9151,8 +9603,8 @@ type ListHostedZonesOutput struct { MaxItems *string `type:"string" required:"true"` // If IsTruncated is true, the value of NextMarker identifies the first hosted - // zone in the next group of maxitems hosted zones. Call ListHostedZones again - // and specify the value of NextMarker in the marker parameter. + // zone in the next group of hosted zones. Submit another ListHostedZones request, + // and specify the value of NextMarker from the response in the marker parameter. // // This element is present only if IsTruncated is true. NextMarker *string `type:"string"` @@ -9198,13 +9650,14 @@ func (s *ListHostedZonesOutput) SetNextMarker(v string) *ListHostedZonesOutput { return s } -// The input for a ListResourceRecordSets request. +// A request for the resource record sets that are associated with a specified +// hosted zone. // Please also see https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/ListResourceRecordSetsRequest type ListResourceRecordSetsInput struct { _ struct{} `type:"structure"` // The ID of the hosted zone that contains the resource record sets that you - // want to get. + // want to list. // // HostedZoneId is a required field HostedZoneId *string `location:"uri" locationName:"Id" type:"string" required:"true"` @@ -9223,8 +9676,8 @@ type ListResourceRecordSetsInput struct { // and type. StartRecordIdentifier *string `location:"querystring" locationName:"identifier" min:"1" type:"string"` - // The first name in the lexicographic ordering of domain names that you want - // the ListResourceRecordSets request to list. + // The first name in the lexicographic ordering of resource record sets that + // you want to list. StartRecordName *string `location:"querystring" locationName:"name" type:"string"` // The type of resource record set to begin the record listing from. @@ -9390,27 +9843,27 @@ func (s *ListResourceRecordSetsOutput) SetResourceRecordSets(v []*ResourceRecord return s } -// To retrieve a list of your reusable delegation sets, send a GET request to -// the /2013-04-01/delegationset resource. The response to this request includes -// a DelegationSets element with zero or more DelegationSet child elements. -// By default, the list of reusable delegation sets is displayed on a single -// page. You can control the length of the page that is displayed by using the -// MaxItems parameter. You can use the Marker parameter to control the delegation -// set that the list begins with. -// -// Amazon Route 53 returns a maximum of 100 items. If you set MaxItems to a -// value greater than 100, Amazon Route 53 returns only the first 100. +// A request to get a list of the reusable delegation sets that are associated +// with the current AWS account. // Please also see https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/ListReusableDelegationSetsRequest type ListReusableDelegationSetsInput struct { _ struct{} `type:"structure"` - // If you're making the second or subsequent call to ListReusableDelegationSets, - // the Marker element matches the value that you specified in the marker parameter - // in the previous request. + // If the value of IsTruncated in the previous response was true, you have more + // reusable delegation sets. To get another group, submit another ListReusableDelegationSets + // request. + // + // For the value of marker, specify the value of NextMarker from the previous + // response, which is the ID of the first reusable delegation set that Amazon + // Route 53 will return if you submit another request. + // + // If the value of IsTruncated in the previous response was false, there are + // no more reusable delegation sets to get. Marker *string `location:"querystring" locationName:"marker" type:"string"` - // The value that you specified for the maxitems parameter in the request that - // produced the current response. + // The number of reusable delegation sets that you want Amazon Route 53 to return + // in the response to this request. If you specify a value greater than 100, + // Amazon Route 53 returns only the first 100 reusable delegation sets. MaxItems *string `location:"querystring" locationName:"maxitems" type:"string"` } @@ -9449,9 +9902,7 @@ type ListReusableDelegationSetsOutput struct { DelegationSets []*DelegationSet `locationNameList:"DelegationSet" type:"list" required:"true"` // A flag that indicates whether there are more reusable delegation sets to - // be listed. If the response is truncated, you can get the next group of maxitems - // reusable delegation sets by calling ListReusableDelegationSets again and - // specifying the value of the NextMarker element in the marker parameter. + // be listed. // // IsTruncated is a required field IsTruncated *bool `type:"boolean" required:"true"` @@ -9469,10 +9920,9 @@ type ListReusableDelegationSetsOutput struct { // MaxItems is a required field MaxItems *string `type:"string" required:"true"` - // If IsTruncated is true, the value of NextMarker identifies the first reusable - // delegation set in the next group of maxitems reusable delegation sets. Call - // ListReusableDelegationSets again and specify the value of NextMarker in the - // marker parameter. + // If IsTruncated is true, the value of NextMarker identifies the next reusable + // delegation set that Amazon Route 53 will return if you submit another ListReusableDelegationSets + // request and specify the value of NextMarker in the marker parameter. NextMarker *string `type:"string"` } @@ -9699,23 +10149,21 @@ func (s *ListTagsForResourcesOutput) SetResourceTagSets(v []*ResourceTagSet) *Li type ListTrafficPoliciesInput struct { _ struct{} `type:"structure"` - // (Optional) The maximum number of traffic policies to be included in the response - // body for this request. If you have more than MaxItems traffic policies, the - // value of the IsTruncated element in the response is true, and the value of - // the TrafficPolicyIdMarker element is the ID of the first traffic policy in - // the next group of MaxItems traffic policies. + // (Optional) The maximum number of traffic policies that you want Amazon Route + // 53 to return in response to this request. If you have more than MaxItems + // traffic policies, the value of IsTruncated in the response is true, and the + // value of TrafficPolicyIdMarker is the ID of the first traffic policy that + // Amazon Route 53 will return if you submit another request. MaxItems *string `location:"querystring" locationName:"maxitems" type:"string"` - // (Conditional) For your first request to ListTrafficPolicies, do not include + // (Conditional) For your first request to ListTrafficPolicies, don't include // the TrafficPolicyIdMarker parameter. // // If you have more traffic policies than the value of MaxItems, ListTrafficPolicies // returns only the first MaxItems traffic policies. To get the next group of - // MaxItems policies, submit another request to ListTrafficPolicies. For the - // value of TrafficPolicyIdMarker, specify the value of the TrafficPolicyIdMarker - // element that was returned in the previous response. - // - // Policies are listed in the order in which they were created. + // policies, submit another request to ListTrafficPolicies. For the value of + // TrafficPolicyIdMarker, specify the value of TrafficPolicyIdMarker that was + // returned in the previous response. TrafficPolicyIdMarker *string `location:"querystring" locationName:"trafficpolicyid" min:"1" type:"string"` } @@ -9760,17 +10208,15 @@ type ListTrafficPoliciesOutput struct { _ struct{} `type:"structure"` // A flag that indicates whether there are more traffic policies to be listed. - // If the response was truncated, you can get the next group of MaxItems traffic - // policies by calling ListTrafficPolicies again and specifying the value of - // the TrafficPolicyIdMarker element in the TrafficPolicyIdMarker request parameter. - // - // Valid Values: true | false + // If the response was truncated, you can get the next group of traffic policies + // by submitting another ListTrafficPolicies request and specifying the value + // of TrafficPolicyIdMarker in the TrafficPolicyIdMarker request parameter. // // IsTruncated is a required field IsTruncated *bool `type:"boolean" required:"true"` - // The value that you specified for the MaxItems parameter in the call to ListTrafficPolicies - // that produced the current response. + // The value that you specified for the MaxItems parameter in the ListTrafficPolicies + // request that produced the current response. // // MaxItems is a required field MaxItems *string `type:"string" required:"true"` @@ -9828,7 +10274,8 @@ func (s *ListTrafficPoliciesOutput) SetTrafficPolicySummaries(v []*TrafficPolicy type ListTrafficPolicyInstancesByHostedZoneInput struct { _ struct{} `type:"structure"` - // The ID of the hosted zone for which you want to list traffic policy instances. + // The ID of the hosted zone that you want to list traffic policy instances + // for. // // HostedZoneId is a required field HostedZoneId *string `location:"querystring" locationName:"id" type:"string" required:"true"` @@ -9837,33 +10284,30 @@ type ListTrafficPolicyInstancesByHostedZoneInput struct { // body for this request. If you have more than MaxItems traffic policy instances, // the value of the IsTruncated element in the response is true, and the values // of HostedZoneIdMarker, TrafficPolicyInstanceNameMarker, and TrafficPolicyInstanceTypeMarker - // represent the first traffic policy instance in the next group of MaxItems - // traffic policy instances. + // represent the first traffic policy instance that Amazon Route 53 will return + // if you submit another request. MaxItems *string `location:"querystring" locationName:"maxitems" type:"string"` - // For the first request to ListTrafficPolicyInstancesByHostedZone, omit this - // value. - // - // If the value of IsTruncated in the previous response was true, TrafficPolicyInstanceNameMarker - // is the name of the first traffic policy instance in the next group of MaxItems - // traffic policy instances. + // If the value of IsTruncated in the previous response is true, you have more + // traffic policy instances. To get more traffic policy instances, submit another + // ListTrafficPolicyInstances request. For the value of trafficpolicyinstancename, + // specify the value of TrafficPolicyInstanceNameMarker from the previous response, + // which is the name of the first traffic policy instance in the next group + // of traffic policy instances. // // If the value of IsTruncated in the previous response was false, there are - // no more traffic policy instances to get for this hosted zone. - // - // If the value of IsTruncated in the previous response was false, omit this - // value. + // no more traffic policy instances to get. TrafficPolicyInstanceNameMarker *string `location:"querystring" locationName:"trafficpolicyinstancename" type:"string"` - // For the first request to ListTrafficPolicyInstancesByHostedZone, omit this - // value. - // - // If the value of IsTruncated in the previous response was true, TrafficPolicyInstanceTypeMarker - // is the DNS type of the first traffic policy instance in the next group of - // MaxItems traffic policy instances. + // If the value of IsTruncated in the previous response is true, you have more + // traffic policy instances. To get more traffic policy instances, submit another + // ListTrafficPolicyInstances request. For the value of trafficpolicyinstancetype, + // specify the value of TrafficPolicyInstanceTypeMarker from the previous response, + // which is the type of the first traffic policy instance in the next group + // of traffic policy instances. // // If the value of IsTruncated in the previous response was false, there are - // no more traffic policy instances to get for this hosted zone. + // no more traffic policy instances to get. TrafficPolicyInstanceTypeMarker *string `location:"querystring" locationName:"trafficpolicyinstancetype" type:"string" enum:"RRType"` } @@ -9920,29 +10364,27 @@ type ListTrafficPolicyInstancesByHostedZoneOutput struct { _ struct{} `type:"structure"` // A flag that indicates whether there are more traffic policy instances to - // be listed. If the response was truncated, you can get the next group of MaxItems - // traffic policy instances by calling ListTrafficPolicyInstancesByHostedZone - // again and specifying the values of the HostedZoneIdMarker, TrafficPolicyInstanceNameMarker, - // and TrafficPolicyInstanceTypeMarker elements in the corresponding request - // parameters. + // be listed. If the response was truncated, you can get the next group of traffic + // policy instances by submitting another ListTrafficPolicyInstancesByHostedZone + // request and specifying the values of HostedZoneIdMarker, TrafficPolicyInstanceNameMarker, + // and TrafficPolicyInstanceTypeMarker in the corresponding request parameters. // // IsTruncated is a required field IsTruncated *bool `type:"boolean" required:"true"` - // The value that you specified for the MaxItems parameter in the call to ListTrafficPolicyInstancesByHostedZone - // that produced the current response. + // The value that you specified for the MaxItems parameter in the ListTrafficPolicyInstancesByHostedZone + // request that produced the current response. // // MaxItems is a required field MaxItems *string `type:"string" required:"true"` // If IsTruncated is true, TrafficPolicyInstanceNameMarker is the name of the - // first traffic policy instance in the next group of MaxItems traffic policy - // instances. + // first traffic policy instance in the next group of traffic policy instances. TrafficPolicyInstanceNameMarker *string `type:"string"` // If IsTruncated is true, TrafficPolicyInstanceTypeMarker is the DNS type of // the resource record sets that are associated with the first traffic policy - // instance in the next group of MaxItems traffic policy instances. + // instance in the next group of traffic policy instances. TrafficPolicyInstanceTypeMarker *string `type:"string" enum:"RRType"` // A list that contains one TrafficPolicyInstance element for each traffic policy @@ -9998,25 +10440,24 @@ func (s *ListTrafficPolicyInstancesByHostedZoneOutput) SetTrafficPolicyInstances type ListTrafficPolicyInstancesByPolicyInput struct { _ struct{} `type:"structure"` - // For the first request to ListTrafficPolicyInstancesByPolicy, omit this value. + // If the value of IsTruncated in the previous response was true, you have more + // traffic policy instances. To get more traffic policy instances, submit another + // ListTrafficPolicyInstancesByPolicy request. // - // If the value of IsTruncated in the previous response was true, HostedZoneIdMarker - // is the ID of the hosted zone for the first traffic policy instance in the - // next group of MaxItems traffic policy instances. + // For the value of hostedzoneid, specify the value of HostedZoneIdMarker from + // the previous response, which is the hosted zone ID of the first traffic policy + // instance that Amazon Route 53 will return if you submit another request. // // If the value of IsTruncated in the previous response was false, there are - // no more traffic policy instances to get for this hosted zone. - // - // If the value of IsTruncated in the previous response was false, omit this - // value. + // no more traffic policy instances to get. HostedZoneIdMarker *string `location:"querystring" locationName:"hostedzoneid" type:"string"` // The maximum number of traffic policy instances to be included in the response // body for this request. If you have more than MaxItems traffic policy instances, // the value of the IsTruncated element in the response is true, and the values // of HostedZoneIdMarker, TrafficPolicyInstanceNameMarker, and TrafficPolicyInstanceTypeMarker - // represent the first traffic policy instance in the next group of MaxItems - // traffic policy instances. + // represent the first traffic policy instance that Amazon Route 53 will return + // if you submit another request. MaxItems *string `location:"querystring" locationName:"maxitems" type:"string"` // The ID of the traffic policy for which you want to list traffic policy instances. @@ -10024,27 +10465,28 @@ type ListTrafficPolicyInstancesByPolicyInput struct { // TrafficPolicyId is a required field TrafficPolicyId *string `location:"querystring" locationName:"id" min:"1" type:"string" required:"true"` - // For the first request to ListTrafficPolicyInstancesByPolicy, omit this value. + // If the value of IsTruncated in the previous response was true, you have more + // traffic policy instances. To get more traffic policy instances, submit another + // ListTrafficPolicyInstancesByPolicy request. // - // If the value of IsTruncated in the previous response was true, TrafficPolicyInstanceNameMarker - // is the name of the first traffic policy instance in the next group of MaxItems - // traffic policy instances. + // For the value of trafficpolicyinstancename, specify the value of TrafficPolicyInstanceNameMarker + // from the previous response, which is the name of the first traffic policy + // instance that Amazon Route 53 will return if you submit another request. // // If the value of IsTruncated in the previous response was false, there are - // no more traffic policy instances to get for this hosted zone. - // - // If the value of IsTruncated in the previous response was false, omit this - // value. + // no more traffic policy instances to get. TrafficPolicyInstanceNameMarker *string `location:"querystring" locationName:"trafficpolicyinstancename" type:"string"` - // For the first request to ListTrafficPolicyInstancesByPolicy, omit this value. + // If the value of IsTruncated in the previous response was true, you have more + // traffic policy instances. To get more traffic policy instances, submit another + // ListTrafficPolicyInstancesByPolicy request. // - // If the value of IsTruncated in the previous response was true, TrafficPolicyInstanceTypeMarker - // is the DNS type of the first traffic policy instance in the next group of - // MaxItems traffic policy instances. + // For the value of trafficpolicyinstancetype, specify the value of TrafficPolicyInstanceTypeMarker + // from the previous response, which is the name of the first traffic policy + // instance that Amazon Route 53 will return if you submit another request. // // If the value of IsTruncated in the previous response was false, there are - // no more traffic policy instances to get for this hosted zone. + // no more traffic policy instances to get. TrafficPolicyInstanceTypeMarker *string `location:"querystring" locationName:"trafficpolicyinstancetype" type:"string" enum:"RRType"` // The version of the traffic policy for which you want to list traffic policy @@ -10129,14 +10571,13 @@ type ListTrafficPolicyInstancesByPolicyOutput struct { _ struct{} `type:"structure"` // If IsTruncated is true, HostedZoneIdMarker is the ID of the hosted zone of - // the first traffic policy instance in the next group of MaxItems traffic policy - // instances. + // the first traffic policy instance in the next group of traffic policy instances. HostedZoneIdMarker *string `type:"string"` // A flag that indicates whether there are more traffic policy instances to - // be listed. If the response was truncated, you can get the next group of MaxItems - // traffic policy instances by calling ListTrafficPolicyInstancesByPolicy again - // and specifying the values of the HostedZoneIdMarker, TrafficPolicyInstanceNameMarker, + // be listed. If the response was truncated, you can get the next group of traffic + // policy instances by calling ListTrafficPolicyInstancesByPolicy again and + // specifying the values of the HostedZoneIdMarker, TrafficPolicyInstanceNameMarker, // and TrafficPolicyInstanceTypeMarker elements in the corresponding request // parameters. // @@ -10218,42 +10659,42 @@ func (s *ListTrafficPolicyInstancesByPolicyOutput) SetTrafficPolicyInstances(v [ type ListTrafficPolicyInstancesInput struct { _ struct{} `type:"structure"` - // For the first request to ListTrafficPolicyInstances, omit this value. - // // If the value of IsTruncated in the previous response was true, you have more - // traffic policy instances. To get the next group of MaxItems traffic policy - // instances, submit another ListTrafficPolicyInstances request. For the value - // of HostedZoneIdMarker, specify the value of HostedZoneIdMarker from the previous - // response, which is the hosted zone ID of the first traffic policy instance - // in the next group of MaxItems traffic policy instances. + // traffic policy instances. To get more traffic policy instances, submit another + // ListTrafficPolicyInstances request. For the value of HostedZoneId, specify + // the value of HostedZoneIdMarker from the previous response, which is the + // hosted zone ID of the first traffic policy instance in the next group of + // traffic policy instances. // // If the value of IsTruncated in the previous response was false, there are // no more traffic policy instances to get. HostedZoneIdMarker *string `location:"querystring" locationName:"hostedzoneid" type:"string"` - // The maximum number of traffic policy instances to be included in the response - // body for this request. If you have more than MaxItems traffic policy instances, - // the value of the IsTruncated element in the response is true, and the values - // of HostedZoneIdMarker, TrafficPolicyInstanceNameMarker, and TrafficPolicyInstanceTypeMarker - // represent the first traffic policy instance in the next group of MaxItems - // traffic policy instances. + // The maximum number of traffic policy instances that you want Amazon Route + // 53 to return in response to a ListTrafficPolicyInstances request. If you + // have more than MaxItems traffic policy instances, the value of the IsTruncated + // element in the response is true, and the values of HostedZoneIdMarker, TrafficPolicyInstanceNameMarker, + // and TrafficPolicyInstanceTypeMarker represent the first traffic policy instance + // in the next group of MaxItems traffic policy instances. MaxItems *string `location:"querystring" locationName:"maxitems" type:"string"` - // For the first request to ListTrafficPolicyInstances, omit this value. - // - // If the value of IsTruncated in the previous response was true, TrafficPolicyInstanceNameMarker - // is the name of the first traffic policy instance in the next group of MaxItems - // traffic policy instances. + // If the value of IsTruncated in the previous response was true, you have more + // traffic policy instances. To get more traffic policy instances, submit another + // ListTrafficPolicyInstances request. For the value of trafficpolicyinstancename, + // specify the value of TrafficPolicyInstanceNameMarker from the previous response, + // which is the name of the first traffic policy instance in the next group + // of traffic policy instances. // // If the value of IsTruncated in the previous response was false, there are // no more traffic policy instances to get. TrafficPolicyInstanceNameMarker *string `location:"querystring" locationName:"trafficpolicyinstancename" type:"string"` - // For the first request to ListTrafficPolicyInstances, omit this value. - // - // If the value of IsTruncated in the previous response was true, TrafficPolicyInstanceTypeMarker - // is the DNS type of the first traffic policy instance in the next group of - // MaxItems traffic policy instances. + // If the value of IsTruncated in the previous response was true, you have more + // traffic policy instances. To get more traffic policy instances, submit another + // ListTrafficPolicyInstances request. For the value of trafficpolicyinstancetype, + // specify the value of TrafficPolicyInstanceTypeMarker from the previous response, + // which is the type of the first traffic policy instance in the next group + // of traffic policy instances. // // If the value of IsTruncated in the previous response was false, there are // no more traffic policy instances to get. @@ -10300,16 +10741,15 @@ type ListTrafficPolicyInstancesOutput struct { _ struct{} `type:"structure"` // If IsTruncated is true, HostedZoneIdMarker is the ID of the hosted zone of - // the first traffic policy instance in the next group of MaxItems traffic policy - // instances. + // the first traffic policy instance that Amazon Route 53 will return if you + // submit another ListTrafficPolicyInstances request. HostedZoneIdMarker *string `type:"string"` // A flag that indicates whether there are more traffic policy instances to - // be listed. If the response was truncated, you can get the next group of MaxItems - // traffic policy instances by calling ListTrafficPolicyInstances again and - // specifying the values of the HostedZoneIdMarker, TrafficPolicyInstanceNameMarker, - // and TrafficPolicyInstanceTypeMarker elements in the corresponding request - // parameters. + // be listed. If the response was truncated, you can get more traffic policy + // instances by calling ListTrafficPolicyInstances again and specifying the + // values of the HostedZoneIdMarker, TrafficPolicyInstanceNameMarker, and TrafficPolicyInstanceTypeMarker + // in the corresponding request parameters. // // IsTruncated is a required field IsTruncated *bool `type:"boolean" required:"true"` @@ -10321,13 +10761,14 @@ type ListTrafficPolicyInstancesOutput struct { MaxItems *string `type:"string" required:"true"` // If IsTruncated is true, TrafficPolicyInstanceNameMarker is the name of the - // first traffic policy instance in the next group of MaxItems traffic policy - // instances. + // first traffic policy instance that Amazon Route 53 will return if you submit + // another ListTrafficPolicyInstances request. TrafficPolicyInstanceNameMarker *string `type:"string"` // If IsTruncated is true, TrafficPolicyInstanceTypeMarker is the DNS type of // the resource record sets that are associated with the first traffic policy - // instance in the next group of MaxItems traffic policy instances. + // instance that Amazon Route 53 will return if you submit another ListTrafficPolicyInstances + // request. TrafficPolicyInstanceTypeMarker *string `type:"string" enum:"RRType"` // A list that contains one TrafficPolicyInstance element for each traffic policy @@ -10397,22 +10838,20 @@ type ListTrafficPolicyVersionsInput struct { // The maximum number of traffic policy versions that you want Amazon Route // 53 to include in the response body for this request. If the specified traffic - // policy has more than MaxItems versions, the value of the IsTruncated element - // in the response is true, and the value of the TrafficPolicyVersionMarker - // element is the ID of the first version in the next group of MaxItems traffic - // policy versions. + // policy has more than MaxItems versions, the value of IsTruncated in the response + // is true, and the value of the TrafficPolicyVersionMarker element is the ID + // of the first version that Amazon Route 53 will return if you submit another + // request. MaxItems *string `location:"querystring" locationName:"maxitems" type:"string"` - // For your first request to ListTrafficPolicyVersions, do not include the TrafficPolicyVersionMarker + // For your first request to ListTrafficPolicyVersions, don't include the TrafficPolicyVersionMarker // parameter. // // If you have more traffic policy versions than the value of MaxItems, ListTrafficPolicyVersions - // returns only the first group of MaxItems versions. To get the next group - // of MaxItems traffic policy versions, submit another request to ListTrafficPolicyVersions. - // For the value of TrafficPolicyVersionMarker, specify the value of the TrafficPolicyVersionMarker - // element that was returned in the previous response. - // - // Traffic policy versions are listed in sequential order. + // returns only the first group of MaxItems versions. To get more traffic policy + // versions, submit another ListTrafficPolicyVersions request. For the value + // of TrafficPolicyVersionMarker, specify the value of TrafficPolicyVersionMarker + // in the previous response. TrafficPolicyVersionMarker *string `location:"querystring" locationName:"trafficpolicyversion" type:"string"` } @@ -10466,15 +10905,15 @@ type ListTrafficPolicyVersionsOutput struct { _ struct{} `type:"structure"` // A flag that indicates whether there are more traffic policies to be listed. - // If the response was truncated, you can get the next group of maxitems traffic - // policies by calling ListTrafficPolicyVersions again and specifying the value - // of the NextMarker element in the marker parameter. + // If the response was truncated, you can get the next group of traffic policies + // by submitting another ListTrafficPolicyVersions request and specifying the + // value of NextMarker in the marker parameter. // // IsTruncated is a required field IsTruncated *bool `type:"boolean" required:"true"` - // The value that you specified for the maxitems parameter in the call to ListTrafficPolicyVersions - // that produced the current response. + // The value that you specified for the maxitems parameter in the ListTrafficPolicyVersions + // request that produced the current response. // // MaxItems is a required field MaxItems *string `type:"string" required:"true"` @@ -10486,8 +10925,8 @@ type ListTrafficPolicyVersionsOutput struct { TrafficPolicies []*TrafficPolicy `locationNameList:"TrafficPolicy" type:"list" required:"true"` // If IsTruncated is true, the value of TrafficPolicyVersionMarker identifies - // the first traffic policy in the next group of MaxItems traffic policies. - // Call ListTrafficPolicyVersions again and specify the value of TrafficPolicyVersionMarker + // the first traffic policy that Amazon Route 53 will return if you submit another + // request. Call ListTrafficPolicyVersions again and specify the value of TrafficPolicyVersionMarker // in the TrafficPolicyVersionMarker request parameter. // // This element is present only if IsTruncated is true. @@ -10543,13 +10982,14 @@ type ListVPCAssociationAuthorizationsInput struct { HostedZoneId *string `location:"uri" locationName:"Id" type:"string" required:"true"` // Optional: An integer that specifies the maximum number of VPCs that you want - // Amazon Route 53 to return. + // Amazon Route 53 to return. If you don't specify a value for MaxResults, Amazon + // Route 53 returns up to 50 VPCs per page. MaxResults *string `location:"querystring" locationName:"maxresults" type:"string"` // Optional: If a response includes a NextToken element, there are more VPCs // that can be associated with the specified hosted zone. To get the next page - // of results, submit another request, and include the value of the NextToken - // element in from the response in the NextToken parameter in another ListVPCAssociationAuthorizations + // of results, submit another request, and include the value of NextToken from + // the response in the nexttoken parameter in another ListVPCAssociationAuthorizations // request. NextToken *string `location:"querystring" locationName:"nexttoken" type:"string"` } @@ -10608,11 +11048,8 @@ type ListVPCAssociationAuthorizationsOutput struct { // When the response includes a NextToken element, there are more VPCs that // can be associated with the specified hosted zone. To get the next page of // VPCs, submit another ListVPCAssociationAuthorizations request, and include - // the value of the NextToken element from the response in the NextToken request - // parameter: - // - // /2013-04-01/hostedzone/hosted zone ID/authorizevpcassociation?MaxItems=VPCs - // per page&NextToken= + // the value of the NextToken element from the response in the nexttoken request + // parameter. NextToken *string `type:"string"` // The list of VPCs that are authorized to be associated with the specified @@ -10765,8 +11202,6 @@ type ResourceRecordSet struct { // * Amazon Route 53 Health Checks and DNS Failover (http://docs.aws.amazon.com/Route53/latest/DeveloperGuide/dns-failover.html) // // * Configuring Failover in a Private Hosted Zone (http://docs.aws.amazon.com/Route53/latest/DeveloperGuide/dns-failover-private-hosted-zones.html) - // - // Valid values: PRIMARY | SECONDARY Failover *string `type:"string" enum:"ResourceRecordSetFailover"` // Geo location resource record sets only: A complex type that lets you control @@ -10892,7 +11327,7 @@ type ResourceRecordSet struct { // in the Amazon Route 53 Developer Guide. // // You can use the asterisk (*) wildcard to replace the leftmost label in a - // domain name. For example, *.example.com. Note the following: + // domain name, for example, *.example.com. Note the following: // // * The * must replace the entire label. For example, you can't specify // *prod.example.com or prod*.example.com. @@ -10913,8 +11348,8 @@ type ResourceRecordSet struct { // Name is a required field Name *string `type:"string" required:"true"` - // Latency-based resource record sets only: The Amazon EC2 Region where the - // resource that is specified in this resource record set resides. The resource + // Latency-based resource record sets only: The Amazon EC2 Region where you + // created the resource that this resource record set refers to. The resource // typically is an AWS resource, such as an EC2 instance or an ELB load balancer, // and is referred to by an IP address or a DNS domain name, depending on the // record type. @@ -10938,7 +11373,7 @@ type ResourceRecordSet struct { // // * You aren't required to create latency resource record sets for all Amazon // EC2 Regions. Amazon Route 53 will choose the region with the best latency - // from among the regions for which you create latency resource record sets. + // from among the regions that you create latency resource record sets for. // // * You can't create non-latency resource record sets that have the same // values for the Name and Type elements as latency resource record sets. @@ -10966,8 +11401,8 @@ type ResourceRecordSet struct { // a TTL of 60 seconds or less so clients respond quickly to changes in health // status. // - // * All of the resource record sets in a group of weighted, latency, geolocation, - // or failover resource record sets must have the same value for TTL. + // * All of the resource record sets in a group of weighted resource record + // sets must have the same value for TTL. // // * If a group of weighted resource record sets includes one or more weighted // alias resource record sets for which the alias target is an ELB load balancer, @@ -11251,10 +11686,10 @@ func (s *ResourceTagSet) SetTags(v []*Tag) *ResourceTagSet { type StatusReport struct { _ struct{} `type:"structure"` - // The time at which the health checker performed the health check in ISO 8601 - // format (https://en.wikipedia.org/wiki/ISO_8601) and Coordinated Universal - // Time (UTC). For example, the value 2014-10-27T17:48:16.751Z represents October - // 27, 2014 at 17:48:16.751 UTC. + // The date and time that the health checker performed the health check in ISO + // 8601 format (https://en.wikipedia.org/wiki/ISO_8601) and Coordinated Universal + // Time (UTC). For example, the value 2017-03-27T17:48:16.751Z represents March + // 27, 2017 at 17:48:16.751 UTC. CheckedTime *time.Time `type:"timestamp" timestampFormat:"iso8601"` // A description of the status of the health check endpoint as reported by one @@ -11295,8 +11730,8 @@ type Tag struct { // * Add a tag to a health check or hosted zone: Key is the name that you // want to give the new tag. // - // * Edit a tag: Key is the name of the tag whose Value element you want - // to remove. + // * Edit a tag: Key is the name of the tag that you want to change the Value + // for. // // * Delete a key: Key is the name of the tag you want to remove. // @@ -11339,43 +11774,21 @@ func (s *Tag) SetValue(v string) *Tag { // Gets the value that Amazon Route 53 returns in response to a DNS request // for a specified record name and type. You can optionally specify the IP address // of a DNS resolver, an EDNS0 client subnet IP address, and a subnet mask. -// -// Parameters -// -// hostedzoneidThe ID of the hosted zone that you want Amazon Route 53 to simulate -// a query for. -// -// recordnameThe name of the resource record set that you want Amazon Route -// 53 to simulate a query for. -// -// recordtypeThe type of the resource record set. -// -// resolverip (optional)If you want to simulate a request from a specific DNS -// resolver, specify the IP address for that resolver. If you omit this value, -// TestDNSAnswer uses the IP address of a DNS resolver in the AWS US East region. -// -// edns0clientsubnetip (optional)If the resolver that you specified for resolverip -// supports EDNS0, specify the IP address of a client in the applicable location. -// -// edns0clientsubnetmask (optional)If you specify an IP address for edns0clientsubnetip, -// you can optionally specify the number of bits of the IP address that you -// want the checking tool to include in the DNS query. For example, if you specify -// 192.0.2.44 for edns0clientsubnetip and 24 for edns0clientsubnetmask, the -// checking tool will simulate a request from 192.0.2.0/24. The default value -// is 24 bits. // Please also see https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/TestDNSAnswerRequest type TestDNSAnswerInput struct { _ struct{} `type:"structure"` // If the resolver that you specified for resolverip supports EDNS0, specify - // the IP address of a client in the applicable location. + // the IPv4 or IPv6 address of a client in the applicable location, for example, + // 192.0.2.44 or 2001:db8:85a3::8a2e:370:7334. EDNS0ClientSubnetIP *string `location:"querystring" locationName:"edns0clientsubnetip" type:"string"` // If you specify an IP address for edns0clientsubnetip, you can optionally // specify the number of bits of the IP address that you want the checking tool // to include in the DNS query. For example, if you specify 192.0.2.44 for edns0clientsubnetip // and 24 for edns0clientsubnetmask, the checking tool will simulate a request - // from 192.0.2.0/24. The default value is 24 bits. + // from 192.0.2.0/24. The default value is 24 bits for IPv4 addresses and 64 + // bits for IPv6 addresses. EDNS0ClientSubnetMask *string `location:"querystring" locationName:"edns0clientsubnetmask" type:"string"` // The ID of the hosted zone that you want Amazon Route 53 to simulate a query @@ -11397,7 +11810,8 @@ type TestDNSAnswerInput struct { // If you want to simulate a request from a specific DNS resolver, specify the // IP address for that resolver. If you omit this value, TestDnsAnswer uses - // the IP address of a DNS resolver in the AWS US East region. + // the IP address of a DNS resolver in the AWS US East (N. Virginia) Region + // (us-east-1). ResolverIP *string `location:"querystring" locationName:"resolverip" type:"string"` } @@ -11846,7 +12260,8 @@ func (s *TrafficPolicySummary) SetType(v string) *TrafficPolicySummary { return s } -// A complex type that contains the health check request information. +// A complex type that contains information about a request to update a health +// check. // Please also see https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/UpdateHealthCheckRequest type UpdateHealthCheckInput struct { _ struct{} `locationName:"UpdateHealthCheckRequest" type:"structure" xmlURI:"https://route53.amazonaws.com/doc/2013-04-01/"` @@ -11970,7 +12385,7 @@ type UpdateHealthCheckInput struct { // and that you include that value in your UpdateHealthCheck request. This prevents // Amazon Route 53 from overwriting an intervening update: // - // * f the value in the UpdateHealthCheck request matches the value of HealthCheckVersion + // * If the value in the UpdateHealthCheck request matches the value of HealthCheckVersion // in the health check, Amazon Route 53 updates the health check with the // new settings. // @@ -12015,8 +12430,13 @@ type UpdateHealthCheckInput struct { // If the endpoint is an EC2 instance, we recommend that you create an Elastic // IP address, associate it with your EC2 instance, and specify the Elastic // IP address for IPAddress. This ensures that the IP address of your instance - // never changes. For more information, see Elastic IP Addresses (EIP) (http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/elastic-ip-addresses-eip.html) - // in the Amazon EC2 User Guide for Linux Instances. + // never changes. For more information, see the applicable documentation: + // + // * Linux: Elastic IP Addresses (EIP) (http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/elastic-ip-addresses-eip.html) + // in the Amazon EC2 User Guide for Linux Instances + // + // * Windows: Elastic IP Addresses (EIP) (http://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/elastic-ip-addresses-eip.html) + // in the Amazon EC2 User Guide for Windows Instances // // If a health check already has a value for IPAddress, you can change the value. // However, you can't update an existing health check to add or remove the value @@ -12058,8 +12478,8 @@ type UpdateHealthCheckInput struct { // checks. Port *int64 `min:"1" type:"integer"` - // A complex type that contains one Region element for each region from which - // you want Amazon Route 53 health checkers to check the specified endpoint. + // A complex type that contains one Region element for each region that you + // want Amazon Route 53 health checkers to check the specified endpoint from. Regions []*string `locationNameList:"Region" min:"1" type:"list"` // The path that you want Amazon Route 53 to request when performing health @@ -12235,7 +12655,7 @@ func (s *UpdateHealthCheckOutput) SetHealthCheck(v *HealthCheck) *UpdateHealthCh return s } -// A complex type that contains the hosted zone request information. +// A request to update the comment for a hosted zone. // Please also see https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/UpdateHostedZoneCommentRequest type UpdateHostedZoneCommentInput struct { _ struct{} `locationName:"UpdateHostedZoneCommentRequest" type:"structure" xmlURI:"https://route53.amazonaws.com/doc/2013-04-01/"` @@ -12244,7 +12664,7 @@ type UpdateHostedZoneCommentInput struct { // Amazon Route 53 deletes the existing value of the Comment element, if any. Comment *string `type:"string"` - // The ID for the hosted zone for which you want to update the comment. + // The ID for the hosted zone that you want to update the comment for. // // Id is a required field Id *string `location:"uri" locationName:"Id" type:"string" required:"true"` @@ -12285,7 +12705,8 @@ func (s *UpdateHostedZoneCommentInput) SetId(v string) *UpdateHostedZoneCommentI return s } -// A complex type that contains the response to the UpdateHostedZoneCommentRequest. +// A complex type that contains the response to the UpdateHostedZoneComment +// request. // Please also see https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/UpdateHostedZoneCommentResponse type UpdateHostedZoneCommentOutput struct { _ struct{} `type:"structure"` @@ -12312,8 +12733,8 @@ func (s *UpdateHostedZoneCommentOutput) SetHostedZone(v *HostedZone) *UpdateHost return s } -// A complex type that contains information about the traffic policy for which -// you want to update the comment. +// A complex type that contains information about the traffic policy that you +// want to update the comment for. // Please also see https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/UpdateTrafficPolicyCommentRequest type UpdateTrafficPolicyCommentInput struct { _ struct{} `locationName:"UpdateTrafficPolicyCommentRequest" type:"structure" xmlURI:"https://route53.amazonaws.com/doc/2013-04-01/"` @@ -12323,13 +12744,14 @@ type UpdateTrafficPolicyCommentInput struct { // Comment is a required field Comment *string `type:"string" required:"true"` - // The value of Id for the traffic policy for which you want to update the comment. + // The value of Id for the traffic policy that you want to update the comment + // for. // // Id is a required field Id *string `location:"uri" locationName:"Id" min:"1" type:"string" required:"true"` - // The value of Version for the traffic policy for which you want to update - // the comment. + // The value of Version for the traffic policy that you want to update the comment + // for. // // Version is a required field Version *int64 `location:"uri" locationName:"Version" min:"1" type:"integer" required:"true"` @@ -12538,17 +12960,16 @@ func (s *UpdateTrafficPolicyInstanceOutput) SetTrafficPolicyInstance(v *TrafficP return s } -// A complex type that contains information about an Amazon VPC that is associated -// with a private hosted zone. +// (Private hosted zones only) A complex type that contains information about +// an Amazon VPC. // Please also see https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/VPC type VPC struct { _ struct{} `type:"structure"` - // The ID of an Amazon VPC. + // (Private hosted zones only) The ID of an Amazon VPC. VPCId *string `type:"string"` - // The region in which you created the VPC that you want to associate with the - // specified Amazon Route 53 hosted zone. + // (Private hosted zones only) The region in which you created an Amazon VPC. VPCRegion *string `min:"1" type:"string" enum:"VPCRegion"` } diff --git a/vendor/github.com/aws/aws-sdk-go/service/route53/doc.go b/vendor/github.com/aws/aws-sdk-go/service/route53/doc.go new file mode 100644 index 000000000..361449aa9 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/service/route53/doc.go @@ -0,0 +1,78 @@ +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. + +// Package route53 provides the client and types for making API +// requests to Amazon Route 53. +// +// See https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01 for more information on this service. +// +// See route53 package documentation for more information. +// https://docs.aws.amazon.com/sdk-for-go/api/service/route53/ +// +// Using the Client +// +// To use the client for Amazon Route 53 you will first need +// to create a new instance of it. +// +// When creating a client for an AWS service you'll first need to have a Session +// already created. The Session provides configuration that can be shared +// between multiple service clients. Additional configuration can be applied to +// the Session and service's client when they are constructed. The aws package's +// Config type contains several fields such as Region for the AWS Region the +// client should make API requests too. The optional Config value can be provided +// as the variadic argument for Sessions and client creation. +// +// Once the service's client is created you can use it to make API requests the +// AWS service. These clients are safe to use concurrently. +// +// // Create a session to share configuration, and load external configuration. +// sess := session.Must(session.NewSession()) +// +// // Create the service's client with the session. +// svc := route53.New(sess) +// +// See the SDK's documentation for more information on how to use service clients. +// https://docs.aws.amazon.com/sdk-for-go/api/ +// +// See aws package's Config type for more information on configuration options. +// https://docs.aws.amazon.com/sdk-for-go/api/aws/#Config +// +// See the Amazon Route 53 client Route53 for more +// information on creating the service's client. +// https://docs.aws.amazon.com/sdk-for-go/api/service/route53/#New +// +// Once the client is created you can make an API request to the service. +// Each API method takes a input parameter, and returns the service response +// and an error. +// +// The API method will document which error codes the service can be returned +// by the operation if the service models the API operation's errors. These +// errors will also be available as const strings prefixed with "ErrCode". +// +// result, err := svc.AssociateVPCWithHostedZone(params) +// if err != nil { +// // Cast err to awserr.Error to handle specific error codes. +// aerr, ok := err.(awserr.Error) +// if ok && aerr.Code() == { +// // Specific error code handling +// } +// return err +// } +// +// fmt.Println("AssociateVPCWithHostedZone result:") +// fmt.Println(result) +// +// Using the Client with Context +// +// The service's client also provides methods to make API requests with a Context +// value. This allows you to control the timeout, and cancellation of pending +// requests. These methods also take request Option as variadic parameter to apply +// additional configuration to the API request. +// +// ctx := context.Background() +// +// result, err := svc.AssociateVPCWithHostedZoneWithContext(ctx, params) +// +// See the request package documentation for more information on using Context pattern +// with the SDK. +// https://docs.aws.amazon.com/sdk-for-go/api/aws/request/ +package route53 diff --git a/vendor/github.com/aws/aws-sdk-go/service/route53/errors.go b/vendor/github.com/aws/aws-sdk-go/service/route53/errors.go index cbd875e70..a47d84260 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/route53/errors.go +++ b/vendor/github.com/aws/aws-sdk-go/service/route53/errors.go @@ -1,4 +1,4 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. package route53 @@ -69,8 +69,14 @@ const ( // "HealthCheckAlreadyExists". // // The health check you're attempting to create already exists. Amazon Route - // 53 returns this error when a health check has already been created with the - // specified value for CallerReference. + // 53 returns this error when you submit a request that has the following values: + // + // * The same value for CallerReference as an existing health check, and + // one or more values that differ from the existing health check that has + // the same caller reference. + // + // * The same value for CallerReference as a health check that you created + // and later deleted, regardless of the other settings in the request. ErrCodeHealthCheckAlreadyExists = "HealthCheckAlreadyExists" // ErrCodeHealthCheckInUse for service response error code diff --git a/vendor/github.com/aws/aws-sdk-go/service/route53/service.go b/vendor/github.com/aws/aws-sdk-go/service/route53/service.go index 287e7db7e..98ba1c8f8 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/route53/service.go +++ b/vendor/github.com/aws/aws-sdk-go/service/route53/service.go @@ -1,4 +1,4 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. package route53 @@ -11,10 +11,12 @@ import ( "github.com/aws/aws-sdk-go/private/protocol/restxml" ) -// Route53 is a client for Route 53. -// The service client's operations are safe to be used concurrently. -// It is not safe to mutate any of the client's properties though. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01 +// Route53 provides the API operation methods for making requests to +// Amazon Route 53. See this package's package overview docs +// for details on the service. +// +// Route53 methods are safe to use concurrently. It is not safe to +// modify mutate any of the struct's properties though. type Route53 struct { *client.Client } diff --git a/vendor/github.com/aws/aws-sdk-go/service/route53/waiters.go b/vendor/github.com/aws/aws-sdk-go/service/route53/waiters.go index 85a70ab5a..71d99e6ea 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/route53/waiters.go +++ b/vendor/github.com/aws/aws-sdk-go/service/route53/waiters.go @@ -1,9 +1,12 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. package route53 import ( - "github.com/aws/aws-sdk-go/private/waiter" + "time" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/request" ) // WaitUntilResourceRecordSetsChanged uses the Route 53 API operation @@ -11,24 +14,43 @@ import ( // If the condition is not meet within the max attempt window an error will // be returned. func (c *Route53) WaitUntilResourceRecordSetsChanged(input *GetChangeInput) error { - waiterCfg := waiter.Config{ - Operation: "GetChange", - Delay: 30, + return c.WaitUntilResourceRecordSetsChangedWithContext(aws.BackgroundContext(), input) +} + +// WaitUntilResourceRecordSetsChangedWithContext is an extended version of WaitUntilResourceRecordSetsChanged. +// 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 *Route53) WaitUntilResourceRecordSetsChangedWithContext(ctx aws.Context, input *GetChangeInput, opts ...request.WaiterOption) error { + w := request.Waiter{ + Name: "WaitUntilResourceRecordSetsChanged", MaxAttempts: 60, - Acceptors: []waiter.WaitAcceptor{ + Delay: request.ConstantWaiterDelay(30 * time.Second), + Acceptors: []request.WaiterAcceptor{ { - State: "success", - Matcher: "path", - Argument: "ChangeInfo.Status", + State: request.SuccessWaiterState, + Matcher: request.PathWaiterMatch, Argument: "ChangeInfo.Status", Expected: "INSYNC", }, }, + Logger: c.Config.Logger, + NewRequest: func(opts []request.Option) (*request.Request, error) { + var inCpy *GetChangeInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.GetChangeRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, } + w.ApplyOptions(opts...) - w := waiter.Waiter{ - Client: c, - Input: input, - Config: waiterCfg, - } - return w.Wait() + return w.WaitWithContext(ctx) } diff --git a/vendor/github.com/aws/aws-sdk-go/service/s3/api.go b/vendor/github.com/aws/aws-sdk-go/service/s3/api.go index 9b205f3f0..52ac02ca9 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/s3/api.go +++ b/vendor/github.com/aws/aws-sdk-go/service/s3/api.go @@ -1,6 +1,5 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. -// Package s3 provides a client for Amazon Simple Storage Service. package s3 import ( @@ -8,6 +7,7 @@ import ( "io" "time" + "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awsutil" "github.com/aws/aws-sdk-go/aws/request" "github.com/aws/aws-sdk-go/private/protocol" @@ -79,8 +79,23 @@ func (c *S3) AbortMultipartUploadRequest(input *AbortMultipartUploadInput) (req // Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/AbortMultipartUpload func (c *S3) AbortMultipartUpload(input *AbortMultipartUploadInput) (*AbortMultipartUploadOutput, error) { req, out := c.AbortMultipartUploadRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// AbortMultipartUploadWithContext is the same as AbortMultipartUpload with the addition of +// the ability to pass a context and additional request options. +// +// See AbortMultipartUpload for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) AbortMultipartUploadWithContext(ctx aws.Context, input *AbortMultipartUploadInput, opts ...request.Option) (*AbortMultipartUploadOutput, error) { + req, out := c.AbortMultipartUploadRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCompleteMultipartUpload = "CompleteMultipartUpload" @@ -139,8 +154,23 @@ func (c *S3) CompleteMultipartUploadRequest(input *CompleteMultipartUploadInput) // Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/CompleteMultipartUpload func (c *S3) CompleteMultipartUpload(input *CompleteMultipartUploadInput) (*CompleteMultipartUploadOutput, error) { req, out := c.CompleteMultipartUploadRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CompleteMultipartUploadWithContext is the same as CompleteMultipartUpload with the addition of +// the ability to pass a context and additional request options. +// +// See CompleteMultipartUpload for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) CompleteMultipartUploadWithContext(ctx aws.Context, input *CompleteMultipartUploadInput, opts ...request.Option) (*CompleteMultipartUploadOutput, error) { + req, out := c.CompleteMultipartUploadRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCopyObject = "CopyObject" @@ -205,8 +235,23 @@ func (c *S3) CopyObjectRequest(input *CopyObjectInput) (req *request.Request, ou // Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/CopyObject func (c *S3) CopyObject(input *CopyObjectInput) (*CopyObjectOutput, error) { req, out := c.CopyObjectRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CopyObjectWithContext is the same as CopyObject with the addition of +// the ability to pass a context and additional request options. +// +// See CopyObject for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) CopyObjectWithContext(ctx aws.Context, input *CopyObjectInput, opts ...request.Option) (*CopyObjectOutput, error) { + req, out := c.CopyObjectRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateBucket = "CreateBucket" @@ -273,8 +318,23 @@ func (c *S3) CreateBucketRequest(input *CreateBucketInput) (req *request.Request // Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/CreateBucket func (c *S3) CreateBucket(input *CreateBucketInput) (*CreateBucketOutput, error) { req, out := c.CreateBucketRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateBucketWithContext is the same as CreateBucket with the addition of +// the ability to pass a context and additional request options. +// +// See CreateBucket for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) CreateBucketWithContext(ctx aws.Context, input *CreateBucketInput, opts ...request.Option) (*CreateBucketOutput, error) { + req, out := c.CreateBucketRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateMultipartUpload = "CreateMultipartUpload" @@ -339,8 +399,23 @@ func (c *S3) CreateMultipartUploadRequest(input *CreateMultipartUploadInput) (re // Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/CreateMultipartUpload func (c *S3) CreateMultipartUpload(input *CreateMultipartUploadInput) (*CreateMultipartUploadOutput, error) { req, out := c.CreateMultipartUploadRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateMultipartUploadWithContext is the same as CreateMultipartUpload with the addition of +// the ability to pass a context and additional request options. +// +// See CreateMultipartUpload for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) CreateMultipartUploadWithContext(ctx aws.Context, input *CreateMultipartUploadInput, opts ...request.Option) (*CreateMultipartUploadOutput, error) { + req, out := c.CreateMultipartUploadRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteBucket = "DeleteBucket" @@ -402,8 +477,23 @@ func (c *S3) DeleteBucketRequest(input *DeleteBucketInput) (req *request.Request // Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteBucket func (c *S3) DeleteBucket(input *DeleteBucketInput) (*DeleteBucketOutput, error) { req, out := c.DeleteBucketRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteBucketWithContext is the same as DeleteBucket with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteBucket for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) DeleteBucketWithContext(ctx aws.Context, input *DeleteBucketInput, opts ...request.Option) (*DeleteBucketOutput, error) { + req, out := c.DeleteBucketRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteBucketAnalyticsConfiguration = "DeleteBucketAnalyticsConfiguration" @@ -465,8 +555,23 @@ func (c *S3) DeleteBucketAnalyticsConfigurationRequest(input *DeleteBucketAnalyt // Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteBucketAnalyticsConfiguration func (c *S3) DeleteBucketAnalyticsConfiguration(input *DeleteBucketAnalyticsConfigurationInput) (*DeleteBucketAnalyticsConfigurationOutput, error) { req, out := c.DeleteBucketAnalyticsConfigurationRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteBucketAnalyticsConfigurationWithContext is the same as DeleteBucketAnalyticsConfiguration with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteBucketAnalyticsConfiguration for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) DeleteBucketAnalyticsConfigurationWithContext(ctx aws.Context, input *DeleteBucketAnalyticsConfigurationInput, opts ...request.Option) (*DeleteBucketAnalyticsConfigurationOutput, error) { + req, out := c.DeleteBucketAnalyticsConfigurationRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteBucketCors = "DeleteBucketCors" @@ -527,8 +632,23 @@ func (c *S3) DeleteBucketCorsRequest(input *DeleteBucketCorsInput) (req *request // Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteBucketCors func (c *S3) DeleteBucketCors(input *DeleteBucketCorsInput) (*DeleteBucketCorsOutput, error) { req, out := c.DeleteBucketCorsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteBucketCorsWithContext is the same as DeleteBucketCors with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteBucketCors for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) DeleteBucketCorsWithContext(ctx aws.Context, input *DeleteBucketCorsInput, opts ...request.Option) (*DeleteBucketCorsOutput, error) { + req, out := c.DeleteBucketCorsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteBucketInventoryConfiguration = "DeleteBucketInventoryConfiguration" @@ -590,8 +710,23 @@ func (c *S3) DeleteBucketInventoryConfigurationRequest(input *DeleteBucketInvent // Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteBucketInventoryConfiguration func (c *S3) DeleteBucketInventoryConfiguration(input *DeleteBucketInventoryConfigurationInput) (*DeleteBucketInventoryConfigurationOutput, error) { req, out := c.DeleteBucketInventoryConfigurationRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteBucketInventoryConfigurationWithContext is the same as DeleteBucketInventoryConfiguration with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteBucketInventoryConfiguration for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) DeleteBucketInventoryConfigurationWithContext(ctx aws.Context, input *DeleteBucketInventoryConfigurationInput, opts ...request.Option) (*DeleteBucketInventoryConfigurationOutput, error) { + req, out := c.DeleteBucketInventoryConfigurationRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteBucketLifecycle = "DeleteBucketLifecycle" @@ -652,8 +787,23 @@ func (c *S3) DeleteBucketLifecycleRequest(input *DeleteBucketLifecycleInput) (re // Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteBucketLifecycle func (c *S3) DeleteBucketLifecycle(input *DeleteBucketLifecycleInput) (*DeleteBucketLifecycleOutput, error) { req, out := c.DeleteBucketLifecycleRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteBucketLifecycleWithContext is the same as DeleteBucketLifecycle with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteBucketLifecycle for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) DeleteBucketLifecycleWithContext(ctx aws.Context, input *DeleteBucketLifecycleInput, opts ...request.Option) (*DeleteBucketLifecycleOutput, error) { + req, out := c.DeleteBucketLifecycleRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteBucketMetricsConfiguration = "DeleteBucketMetricsConfiguration" @@ -715,8 +865,23 @@ func (c *S3) DeleteBucketMetricsConfigurationRequest(input *DeleteBucketMetricsC // Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteBucketMetricsConfiguration func (c *S3) DeleteBucketMetricsConfiguration(input *DeleteBucketMetricsConfigurationInput) (*DeleteBucketMetricsConfigurationOutput, error) { req, out := c.DeleteBucketMetricsConfigurationRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteBucketMetricsConfigurationWithContext is the same as DeleteBucketMetricsConfiguration with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteBucketMetricsConfiguration for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) DeleteBucketMetricsConfigurationWithContext(ctx aws.Context, input *DeleteBucketMetricsConfigurationInput, opts ...request.Option) (*DeleteBucketMetricsConfigurationOutput, error) { + req, out := c.DeleteBucketMetricsConfigurationRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteBucketPolicy = "DeleteBucketPolicy" @@ -777,8 +942,23 @@ func (c *S3) DeleteBucketPolicyRequest(input *DeleteBucketPolicyInput) (req *req // Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteBucketPolicy func (c *S3) DeleteBucketPolicy(input *DeleteBucketPolicyInput) (*DeleteBucketPolicyOutput, error) { req, out := c.DeleteBucketPolicyRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteBucketPolicyWithContext is the same as DeleteBucketPolicy with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteBucketPolicy for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) DeleteBucketPolicyWithContext(ctx aws.Context, input *DeleteBucketPolicyInput, opts ...request.Option) (*DeleteBucketPolicyOutput, error) { + req, out := c.DeleteBucketPolicyRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteBucketReplication = "DeleteBucketReplication" @@ -839,8 +1019,23 @@ func (c *S3) DeleteBucketReplicationRequest(input *DeleteBucketReplicationInput) // Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteBucketReplication func (c *S3) DeleteBucketReplication(input *DeleteBucketReplicationInput) (*DeleteBucketReplicationOutput, error) { req, out := c.DeleteBucketReplicationRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteBucketReplicationWithContext is the same as DeleteBucketReplication with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteBucketReplication for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) DeleteBucketReplicationWithContext(ctx aws.Context, input *DeleteBucketReplicationInput, opts ...request.Option) (*DeleteBucketReplicationOutput, error) { + req, out := c.DeleteBucketReplicationRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteBucketTagging = "DeleteBucketTagging" @@ -901,8 +1096,23 @@ func (c *S3) DeleteBucketTaggingRequest(input *DeleteBucketTaggingInput) (req *r // Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteBucketTagging func (c *S3) DeleteBucketTagging(input *DeleteBucketTaggingInput) (*DeleteBucketTaggingOutput, error) { req, out := c.DeleteBucketTaggingRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteBucketTaggingWithContext is the same as DeleteBucketTagging with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteBucketTagging for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) DeleteBucketTaggingWithContext(ctx aws.Context, input *DeleteBucketTaggingInput, opts ...request.Option) (*DeleteBucketTaggingOutput, error) { + req, out := c.DeleteBucketTaggingRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteBucketWebsite = "DeleteBucketWebsite" @@ -963,8 +1173,23 @@ func (c *S3) DeleteBucketWebsiteRequest(input *DeleteBucketWebsiteInput) (req *r // Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteBucketWebsite func (c *S3) DeleteBucketWebsite(input *DeleteBucketWebsiteInput) (*DeleteBucketWebsiteOutput, error) { req, out := c.DeleteBucketWebsiteRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteBucketWebsiteWithContext is the same as DeleteBucketWebsite with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteBucketWebsite for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) DeleteBucketWebsiteWithContext(ctx aws.Context, input *DeleteBucketWebsiteInput, opts ...request.Option) (*DeleteBucketWebsiteOutput, error) { + req, out := c.DeleteBucketWebsiteRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteObject = "DeleteObject" @@ -1025,8 +1250,23 @@ func (c *S3) DeleteObjectRequest(input *DeleteObjectInput) (req *request.Request // Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteObject func (c *S3) DeleteObject(input *DeleteObjectInput) (*DeleteObjectOutput, error) { req, out := c.DeleteObjectRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteObjectWithContext is the same as DeleteObject with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteObject for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) DeleteObjectWithContext(ctx aws.Context, input *DeleteObjectInput, opts ...request.Option) (*DeleteObjectOutput, error) { + req, out := c.DeleteObjectRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteObjectTagging = "DeleteObjectTagging" @@ -1085,8 +1325,23 @@ func (c *S3) DeleteObjectTaggingRequest(input *DeleteObjectTaggingInput) (req *r // Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteObjectTagging func (c *S3) DeleteObjectTagging(input *DeleteObjectTaggingInput) (*DeleteObjectTaggingOutput, error) { req, out := c.DeleteObjectTaggingRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteObjectTaggingWithContext is the same as DeleteObjectTagging with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteObjectTagging for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) DeleteObjectTaggingWithContext(ctx aws.Context, input *DeleteObjectTaggingInput, opts ...request.Option) (*DeleteObjectTaggingOutput, error) { + req, out := c.DeleteObjectTaggingRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteObjects = "DeleteObjects" @@ -1146,8 +1401,23 @@ func (c *S3) DeleteObjectsRequest(input *DeleteObjectsInput) (req *request.Reque // Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteObjects func (c *S3) DeleteObjects(input *DeleteObjectsInput) (*DeleteObjectsOutput, error) { req, out := c.DeleteObjectsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteObjectsWithContext is the same as DeleteObjects with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteObjects for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) DeleteObjectsWithContext(ctx aws.Context, input *DeleteObjectsInput, opts ...request.Option) (*DeleteObjectsOutput, error) { + req, out := c.DeleteObjectsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetBucketAccelerateConfiguration = "GetBucketAccelerateConfiguration" @@ -1206,8 +1476,23 @@ func (c *S3) GetBucketAccelerateConfigurationRequest(input *GetBucketAccelerateC // Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketAccelerateConfiguration func (c *S3) GetBucketAccelerateConfiguration(input *GetBucketAccelerateConfigurationInput) (*GetBucketAccelerateConfigurationOutput, error) { req, out := c.GetBucketAccelerateConfigurationRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetBucketAccelerateConfigurationWithContext is the same as GetBucketAccelerateConfiguration with the addition of +// the ability to pass a context and additional request options. +// +// See GetBucketAccelerateConfiguration for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) GetBucketAccelerateConfigurationWithContext(ctx aws.Context, input *GetBucketAccelerateConfigurationInput, opts ...request.Option) (*GetBucketAccelerateConfigurationOutput, error) { + req, out := c.GetBucketAccelerateConfigurationRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetBucketAcl = "GetBucketAcl" @@ -1266,8 +1551,23 @@ func (c *S3) GetBucketAclRequest(input *GetBucketAclInput) (req *request.Request // Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketAcl func (c *S3) GetBucketAcl(input *GetBucketAclInput) (*GetBucketAclOutput, error) { req, out := c.GetBucketAclRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetBucketAclWithContext is the same as GetBucketAcl with the addition of +// the ability to pass a context and additional request options. +// +// See GetBucketAcl for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) GetBucketAclWithContext(ctx aws.Context, input *GetBucketAclInput, opts ...request.Option) (*GetBucketAclOutput, error) { + req, out := c.GetBucketAclRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetBucketAnalyticsConfiguration = "GetBucketAnalyticsConfiguration" @@ -1327,8 +1627,23 @@ func (c *S3) GetBucketAnalyticsConfigurationRequest(input *GetBucketAnalyticsCon // Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketAnalyticsConfiguration func (c *S3) GetBucketAnalyticsConfiguration(input *GetBucketAnalyticsConfigurationInput) (*GetBucketAnalyticsConfigurationOutput, error) { req, out := c.GetBucketAnalyticsConfigurationRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetBucketAnalyticsConfigurationWithContext is the same as GetBucketAnalyticsConfiguration with the addition of +// the ability to pass a context and additional request options. +// +// See GetBucketAnalyticsConfiguration for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) GetBucketAnalyticsConfigurationWithContext(ctx aws.Context, input *GetBucketAnalyticsConfigurationInput, opts ...request.Option) (*GetBucketAnalyticsConfigurationOutput, error) { + req, out := c.GetBucketAnalyticsConfigurationRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetBucketCors = "GetBucketCors" @@ -1387,8 +1702,23 @@ func (c *S3) GetBucketCorsRequest(input *GetBucketCorsInput) (req *request.Reque // Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketCors func (c *S3) GetBucketCors(input *GetBucketCorsInput) (*GetBucketCorsOutput, error) { req, out := c.GetBucketCorsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetBucketCorsWithContext is the same as GetBucketCors with the addition of +// the ability to pass a context and additional request options. +// +// See GetBucketCors for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) GetBucketCorsWithContext(ctx aws.Context, input *GetBucketCorsInput, opts ...request.Option) (*GetBucketCorsOutput, error) { + req, out := c.GetBucketCorsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetBucketInventoryConfiguration = "GetBucketInventoryConfiguration" @@ -1448,8 +1778,23 @@ func (c *S3) GetBucketInventoryConfigurationRequest(input *GetBucketInventoryCon // Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketInventoryConfiguration func (c *S3) GetBucketInventoryConfiguration(input *GetBucketInventoryConfigurationInput) (*GetBucketInventoryConfigurationOutput, error) { req, out := c.GetBucketInventoryConfigurationRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetBucketInventoryConfigurationWithContext is the same as GetBucketInventoryConfiguration with the addition of +// the ability to pass a context and additional request options. +// +// See GetBucketInventoryConfiguration for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) GetBucketInventoryConfigurationWithContext(ctx aws.Context, input *GetBucketInventoryConfigurationInput, opts ...request.Option) (*GetBucketInventoryConfigurationOutput, error) { + req, out := c.GetBucketInventoryConfigurationRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetBucketLifecycle = "GetBucketLifecycle" @@ -1511,8 +1856,23 @@ func (c *S3) GetBucketLifecycleRequest(input *GetBucketLifecycleInput) (req *req // Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketLifecycle func (c *S3) GetBucketLifecycle(input *GetBucketLifecycleInput) (*GetBucketLifecycleOutput, error) { req, out := c.GetBucketLifecycleRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetBucketLifecycleWithContext is the same as GetBucketLifecycle with the addition of +// the ability to pass a context and additional request options. +// +// See GetBucketLifecycle for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) GetBucketLifecycleWithContext(ctx aws.Context, input *GetBucketLifecycleInput, opts ...request.Option) (*GetBucketLifecycleOutput, error) { + req, out := c.GetBucketLifecycleRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetBucketLifecycleConfiguration = "GetBucketLifecycleConfiguration" @@ -1571,8 +1931,23 @@ func (c *S3) GetBucketLifecycleConfigurationRequest(input *GetBucketLifecycleCon // Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketLifecycleConfiguration func (c *S3) GetBucketLifecycleConfiguration(input *GetBucketLifecycleConfigurationInput) (*GetBucketLifecycleConfigurationOutput, error) { req, out := c.GetBucketLifecycleConfigurationRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetBucketLifecycleConfigurationWithContext is the same as GetBucketLifecycleConfiguration with the addition of +// the ability to pass a context and additional request options. +// +// See GetBucketLifecycleConfiguration for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) GetBucketLifecycleConfigurationWithContext(ctx aws.Context, input *GetBucketLifecycleConfigurationInput, opts ...request.Option) (*GetBucketLifecycleConfigurationOutput, error) { + req, out := c.GetBucketLifecycleConfigurationRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetBucketLocation = "GetBucketLocation" @@ -1631,8 +2006,23 @@ func (c *S3) GetBucketLocationRequest(input *GetBucketLocationInput) (req *reque // Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketLocation func (c *S3) GetBucketLocation(input *GetBucketLocationInput) (*GetBucketLocationOutput, error) { req, out := c.GetBucketLocationRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetBucketLocationWithContext is the same as GetBucketLocation with the addition of +// the ability to pass a context and additional request options. +// +// See GetBucketLocation for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) GetBucketLocationWithContext(ctx aws.Context, input *GetBucketLocationInput, opts ...request.Option) (*GetBucketLocationOutput, error) { + req, out := c.GetBucketLocationRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetBucketLogging = "GetBucketLogging" @@ -1692,8 +2082,23 @@ func (c *S3) GetBucketLoggingRequest(input *GetBucketLoggingInput) (req *request // Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketLogging func (c *S3) GetBucketLogging(input *GetBucketLoggingInput) (*GetBucketLoggingOutput, error) { req, out := c.GetBucketLoggingRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetBucketLoggingWithContext is the same as GetBucketLogging with the addition of +// the ability to pass a context and additional request options. +// +// See GetBucketLogging for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) GetBucketLoggingWithContext(ctx aws.Context, input *GetBucketLoggingInput, opts ...request.Option) (*GetBucketLoggingOutput, error) { + req, out := c.GetBucketLoggingRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetBucketMetricsConfiguration = "GetBucketMetricsConfiguration" @@ -1753,8 +2158,23 @@ func (c *S3) GetBucketMetricsConfigurationRequest(input *GetBucketMetricsConfigu // Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketMetricsConfiguration func (c *S3) GetBucketMetricsConfiguration(input *GetBucketMetricsConfigurationInput) (*GetBucketMetricsConfigurationOutput, error) { req, out := c.GetBucketMetricsConfigurationRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetBucketMetricsConfigurationWithContext is the same as GetBucketMetricsConfiguration with the addition of +// the ability to pass a context and additional request options. +// +// See GetBucketMetricsConfiguration for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) GetBucketMetricsConfigurationWithContext(ctx aws.Context, input *GetBucketMetricsConfigurationInput, opts ...request.Option) (*GetBucketMetricsConfigurationOutput, error) { + req, out := c.GetBucketMetricsConfigurationRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetBucketNotification = "GetBucketNotification" @@ -1816,8 +2236,23 @@ func (c *S3) GetBucketNotificationRequest(input *GetBucketNotificationConfigurat // Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketNotification func (c *S3) GetBucketNotification(input *GetBucketNotificationConfigurationRequest) (*NotificationConfigurationDeprecated, error) { req, out := c.GetBucketNotificationRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetBucketNotificationWithContext is the same as GetBucketNotification with the addition of +// the ability to pass a context and additional request options. +// +// See GetBucketNotification for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) GetBucketNotificationWithContext(ctx aws.Context, input *GetBucketNotificationConfigurationRequest, opts ...request.Option) (*NotificationConfigurationDeprecated, error) { + req, out := c.GetBucketNotificationRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetBucketNotificationConfiguration = "GetBucketNotificationConfiguration" @@ -1876,8 +2311,23 @@ func (c *S3) GetBucketNotificationConfigurationRequest(input *GetBucketNotificat // Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketNotificationConfiguration func (c *S3) GetBucketNotificationConfiguration(input *GetBucketNotificationConfigurationRequest) (*NotificationConfiguration, error) { req, out := c.GetBucketNotificationConfigurationRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetBucketNotificationConfigurationWithContext is the same as GetBucketNotificationConfiguration with the addition of +// the ability to pass a context and additional request options. +// +// See GetBucketNotificationConfiguration for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) GetBucketNotificationConfigurationWithContext(ctx aws.Context, input *GetBucketNotificationConfigurationRequest, opts ...request.Option) (*NotificationConfiguration, error) { + req, out := c.GetBucketNotificationConfigurationRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetBucketPolicy = "GetBucketPolicy" @@ -1936,8 +2386,23 @@ func (c *S3) GetBucketPolicyRequest(input *GetBucketPolicyInput) (req *request.R // Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketPolicy func (c *S3) GetBucketPolicy(input *GetBucketPolicyInput) (*GetBucketPolicyOutput, error) { req, out := c.GetBucketPolicyRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetBucketPolicyWithContext is the same as GetBucketPolicy with the addition of +// the ability to pass a context and additional request options. +// +// See GetBucketPolicy for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) GetBucketPolicyWithContext(ctx aws.Context, input *GetBucketPolicyInput, opts ...request.Option) (*GetBucketPolicyOutput, error) { + req, out := c.GetBucketPolicyRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetBucketReplication = "GetBucketReplication" @@ -1996,8 +2461,23 @@ func (c *S3) GetBucketReplicationRequest(input *GetBucketReplicationInput) (req // Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketReplication func (c *S3) GetBucketReplication(input *GetBucketReplicationInput) (*GetBucketReplicationOutput, error) { req, out := c.GetBucketReplicationRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetBucketReplicationWithContext is the same as GetBucketReplication with the addition of +// the ability to pass a context and additional request options. +// +// See GetBucketReplication for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) GetBucketReplicationWithContext(ctx aws.Context, input *GetBucketReplicationInput, opts ...request.Option) (*GetBucketReplicationOutput, error) { + req, out := c.GetBucketReplicationRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetBucketRequestPayment = "GetBucketRequestPayment" @@ -2056,8 +2536,23 @@ func (c *S3) GetBucketRequestPaymentRequest(input *GetBucketRequestPaymentInput) // Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketRequestPayment func (c *S3) GetBucketRequestPayment(input *GetBucketRequestPaymentInput) (*GetBucketRequestPaymentOutput, error) { req, out := c.GetBucketRequestPaymentRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetBucketRequestPaymentWithContext is the same as GetBucketRequestPayment with the addition of +// the ability to pass a context and additional request options. +// +// See GetBucketRequestPayment for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) GetBucketRequestPaymentWithContext(ctx aws.Context, input *GetBucketRequestPaymentInput, opts ...request.Option) (*GetBucketRequestPaymentOutput, error) { + req, out := c.GetBucketRequestPaymentRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetBucketTagging = "GetBucketTagging" @@ -2116,8 +2611,23 @@ func (c *S3) GetBucketTaggingRequest(input *GetBucketTaggingInput) (req *request // Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketTagging func (c *S3) GetBucketTagging(input *GetBucketTaggingInput) (*GetBucketTaggingOutput, error) { req, out := c.GetBucketTaggingRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetBucketTaggingWithContext is the same as GetBucketTagging with the addition of +// the ability to pass a context and additional request options. +// +// See GetBucketTagging for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) GetBucketTaggingWithContext(ctx aws.Context, input *GetBucketTaggingInput, opts ...request.Option) (*GetBucketTaggingOutput, error) { + req, out := c.GetBucketTaggingRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetBucketVersioning = "GetBucketVersioning" @@ -2176,8 +2686,23 @@ func (c *S3) GetBucketVersioningRequest(input *GetBucketVersioningInput) (req *r // Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketVersioning func (c *S3) GetBucketVersioning(input *GetBucketVersioningInput) (*GetBucketVersioningOutput, error) { req, out := c.GetBucketVersioningRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetBucketVersioningWithContext is the same as GetBucketVersioning with the addition of +// the ability to pass a context and additional request options. +// +// See GetBucketVersioning for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) GetBucketVersioningWithContext(ctx aws.Context, input *GetBucketVersioningInput, opts ...request.Option) (*GetBucketVersioningOutput, error) { + req, out := c.GetBucketVersioningRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetBucketWebsite = "GetBucketWebsite" @@ -2236,8 +2761,23 @@ func (c *S3) GetBucketWebsiteRequest(input *GetBucketWebsiteInput) (req *request // Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketWebsite func (c *S3) GetBucketWebsite(input *GetBucketWebsiteInput) (*GetBucketWebsiteOutput, error) { req, out := c.GetBucketWebsiteRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetBucketWebsiteWithContext is the same as GetBucketWebsite with the addition of +// the ability to pass a context and additional request options. +// +// See GetBucketWebsite for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) GetBucketWebsiteWithContext(ctx aws.Context, input *GetBucketWebsiteInput, opts ...request.Option) (*GetBucketWebsiteOutput, error) { + req, out := c.GetBucketWebsiteRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetObject = "GetObject" @@ -2301,8 +2841,23 @@ func (c *S3) GetObjectRequest(input *GetObjectInput) (req *request.Request, outp // Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetObject func (c *S3) GetObject(input *GetObjectInput) (*GetObjectOutput, error) { req, out := c.GetObjectRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetObjectWithContext is the same as GetObject with the addition of +// the ability to pass a context and additional request options. +// +// See GetObject for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) GetObjectWithContext(ctx aws.Context, input *GetObjectInput, opts ...request.Option) (*GetObjectOutput, error) { + req, out := c.GetObjectRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetObjectAcl = "GetObjectAcl" @@ -2366,8 +2921,23 @@ func (c *S3) GetObjectAclRequest(input *GetObjectAclInput) (req *request.Request // Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetObjectAcl func (c *S3) GetObjectAcl(input *GetObjectAclInput) (*GetObjectAclOutput, error) { req, out := c.GetObjectAclRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetObjectAclWithContext is the same as GetObjectAcl with the addition of +// the ability to pass a context and additional request options. +// +// See GetObjectAcl for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) GetObjectAclWithContext(ctx aws.Context, input *GetObjectAclInput, opts ...request.Option) (*GetObjectAclOutput, error) { + req, out := c.GetObjectAclRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetObjectTagging = "GetObjectTagging" @@ -2426,8 +2996,23 @@ func (c *S3) GetObjectTaggingRequest(input *GetObjectTaggingInput) (req *request // Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetObjectTagging func (c *S3) GetObjectTagging(input *GetObjectTaggingInput) (*GetObjectTaggingOutput, error) { req, out := c.GetObjectTaggingRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetObjectTaggingWithContext is the same as GetObjectTagging with the addition of +// the ability to pass a context and additional request options. +// +// See GetObjectTagging for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) GetObjectTaggingWithContext(ctx aws.Context, input *GetObjectTaggingInput, opts ...request.Option) (*GetObjectTaggingOutput, error) { + req, out := c.GetObjectTaggingRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetObjectTorrent = "GetObjectTorrent" @@ -2486,8 +3071,23 @@ func (c *S3) GetObjectTorrentRequest(input *GetObjectTorrentInput) (req *request // Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetObjectTorrent func (c *S3) GetObjectTorrent(input *GetObjectTorrentInput) (*GetObjectTorrentOutput, error) { req, out := c.GetObjectTorrentRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetObjectTorrentWithContext is the same as GetObjectTorrent with the addition of +// the ability to pass a context and additional request options. +// +// See GetObjectTorrent for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) GetObjectTorrentWithContext(ctx aws.Context, input *GetObjectTorrentInput, opts ...request.Option) (*GetObjectTorrentOutput, error) { + req, out := c.GetObjectTorrentRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opHeadBucket = "HeadBucket" @@ -2554,8 +3154,23 @@ func (c *S3) HeadBucketRequest(input *HeadBucketInput) (req *request.Request, ou // Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/HeadBucket func (c *S3) HeadBucket(input *HeadBucketInput) (*HeadBucketOutput, error) { req, out := c.HeadBucketRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// HeadBucketWithContext is the same as HeadBucket with the addition of +// the ability to pass a context and additional request options. +// +// See HeadBucket for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) HeadBucketWithContext(ctx aws.Context, input *HeadBucketInput, opts ...request.Option) (*HeadBucketOutput, error) { + req, out := c.HeadBucketRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opHeadObject = "HeadObject" @@ -2607,22 +3222,35 @@ func (c *S3) HeadObjectRequest(input *HeadObjectInput) (req *request.Request, ou // object itself. This operation is useful if you're only interested in an object's // metadata. To use HEAD, you must have READ access to the object. // +// See http://docs.aws.amazon.com/AmazonS3/latest/API/ErrorResponses.html#RESTErrorResponses +// for more information on returned errors. +// // 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 Simple Storage Service's // API operation HeadObject for usage and error information. -// -// Returned Error Codes: -// * ErrCodeNoSuchKey "NoSuchKey" -// The specified key does not exist. -// // Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/HeadObject func (c *S3) HeadObject(input *HeadObjectInput) (*HeadObjectOutput, error) { req, out := c.HeadObjectRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// HeadObjectWithContext is the same as HeadObject with the addition of +// the ability to pass a context and additional request options. +// +// See HeadObject for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) HeadObjectWithContext(ctx aws.Context, input *HeadObjectInput, opts ...request.Option) (*HeadObjectOutput, error) { + req, out := c.HeadObjectRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opListBucketAnalyticsConfigurations = "ListBucketAnalyticsConfigurations" @@ -2681,8 +3309,23 @@ func (c *S3) ListBucketAnalyticsConfigurationsRequest(input *ListBucketAnalytics // Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/ListBucketAnalyticsConfigurations func (c *S3) ListBucketAnalyticsConfigurations(input *ListBucketAnalyticsConfigurationsInput) (*ListBucketAnalyticsConfigurationsOutput, error) { req, out := c.ListBucketAnalyticsConfigurationsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListBucketAnalyticsConfigurationsWithContext is the same as ListBucketAnalyticsConfigurations with the addition of +// the ability to pass a context and additional request options. +// +// See ListBucketAnalyticsConfigurations for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) ListBucketAnalyticsConfigurationsWithContext(ctx aws.Context, input *ListBucketAnalyticsConfigurationsInput, opts ...request.Option) (*ListBucketAnalyticsConfigurationsOutput, error) { + req, out := c.ListBucketAnalyticsConfigurationsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opListBucketInventoryConfigurations = "ListBucketInventoryConfigurations" @@ -2741,8 +3384,23 @@ func (c *S3) ListBucketInventoryConfigurationsRequest(input *ListBucketInventory // Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/ListBucketInventoryConfigurations func (c *S3) ListBucketInventoryConfigurations(input *ListBucketInventoryConfigurationsInput) (*ListBucketInventoryConfigurationsOutput, error) { req, out := c.ListBucketInventoryConfigurationsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListBucketInventoryConfigurationsWithContext is the same as ListBucketInventoryConfigurations with the addition of +// the ability to pass a context and additional request options. +// +// See ListBucketInventoryConfigurations for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) ListBucketInventoryConfigurationsWithContext(ctx aws.Context, input *ListBucketInventoryConfigurationsInput, opts ...request.Option) (*ListBucketInventoryConfigurationsOutput, error) { + req, out := c.ListBucketInventoryConfigurationsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opListBucketMetricsConfigurations = "ListBucketMetricsConfigurations" @@ -2801,8 +3459,23 @@ func (c *S3) ListBucketMetricsConfigurationsRequest(input *ListBucketMetricsConf // Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/ListBucketMetricsConfigurations func (c *S3) ListBucketMetricsConfigurations(input *ListBucketMetricsConfigurationsInput) (*ListBucketMetricsConfigurationsOutput, error) { req, out := c.ListBucketMetricsConfigurationsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListBucketMetricsConfigurationsWithContext is the same as ListBucketMetricsConfigurations with the addition of +// the ability to pass a context and additional request options. +// +// See ListBucketMetricsConfigurations for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) ListBucketMetricsConfigurationsWithContext(ctx aws.Context, input *ListBucketMetricsConfigurationsInput, opts ...request.Option) (*ListBucketMetricsConfigurationsOutput, error) { + req, out := c.ListBucketMetricsConfigurationsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opListBuckets = "ListBuckets" @@ -2861,8 +3534,23 @@ func (c *S3) ListBucketsRequest(input *ListBucketsInput) (req *request.Request, // Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/ListBuckets func (c *S3) ListBuckets(input *ListBucketsInput) (*ListBucketsOutput, error) { req, out := c.ListBucketsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListBucketsWithContext is the same as ListBuckets with the addition of +// the ability to pass a context and additional request options. +// +// See ListBuckets for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) ListBucketsWithContext(ctx aws.Context, input *ListBucketsInput, opts ...request.Option) (*ListBucketsOutput, error) { + req, out := c.ListBucketsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opListMultipartUploads = "ListMultipartUploads" @@ -2927,8 +3615,23 @@ func (c *S3) ListMultipartUploadsRequest(input *ListMultipartUploadsInput) (req // Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/ListMultipartUploads func (c *S3) ListMultipartUploads(input *ListMultipartUploadsInput) (*ListMultipartUploadsOutput, error) { req, out := c.ListMultipartUploadsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListMultipartUploadsWithContext is the same as ListMultipartUploads with the addition of +// the ability to pass a context and additional request options. +// +// See ListMultipartUploads for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) ListMultipartUploadsWithContext(ctx aws.Context, input *ListMultipartUploadsInput, opts ...request.Option) (*ListMultipartUploadsOutput, error) { + req, out := c.ListMultipartUploadsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // ListMultipartUploadsPages iterates over the pages of a ListMultipartUploads operation, @@ -2948,12 +3651,37 @@ func (c *S3) ListMultipartUploads(input *ListMultipartUploadsInput) (*ListMultip // return pageNum <= 3 // }) // -func (c *S3) ListMultipartUploadsPages(input *ListMultipartUploadsInput, fn func(p *ListMultipartUploadsOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.ListMultipartUploadsRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*ListMultipartUploadsOutput), lastPage) - }) +func (c *S3) ListMultipartUploadsPages(input *ListMultipartUploadsInput, fn func(*ListMultipartUploadsOutput, bool) bool) error { + return c.ListMultipartUploadsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListMultipartUploadsPagesWithContext same as ListMultipartUploadsPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) ListMultipartUploadsPagesWithContext(ctx aws.Context, input *ListMultipartUploadsInput, fn func(*ListMultipartUploadsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListMultipartUploadsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListMultipartUploadsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*ListMultipartUploadsOutput), !p.HasNextPage()) + } + return p.Err() } const opListObjectVersions = "ListObjectVersions" @@ -3018,8 +3746,23 @@ func (c *S3) ListObjectVersionsRequest(input *ListObjectVersionsInput) (req *req // Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/ListObjectVersions func (c *S3) ListObjectVersions(input *ListObjectVersionsInput) (*ListObjectVersionsOutput, error) { req, out := c.ListObjectVersionsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListObjectVersionsWithContext is the same as ListObjectVersions with the addition of +// the ability to pass a context and additional request options. +// +// See ListObjectVersions for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) ListObjectVersionsWithContext(ctx aws.Context, input *ListObjectVersionsInput, opts ...request.Option) (*ListObjectVersionsOutput, error) { + req, out := c.ListObjectVersionsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // ListObjectVersionsPages iterates over the pages of a ListObjectVersions operation, @@ -3039,12 +3782,37 @@ func (c *S3) ListObjectVersions(input *ListObjectVersionsInput) (*ListObjectVers // return pageNum <= 3 // }) // -func (c *S3) ListObjectVersionsPages(input *ListObjectVersionsInput, fn func(p *ListObjectVersionsOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.ListObjectVersionsRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*ListObjectVersionsOutput), lastPage) - }) +func (c *S3) ListObjectVersionsPages(input *ListObjectVersionsInput, fn func(*ListObjectVersionsOutput, bool) bool) error { + return c.ListObjectVersionsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListObjectVersionsPagesWithContext same as ListObjectVersionsPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) ListObjectVersionsPagesWithContext(ctx aws.Context, input *ListObjectVersionsInput, fn func(*ListObjectVersionsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListObjectVersionsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListObjectVersionsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*ListObjectVersionsOutput), !p.HasNextPage()) + } + return p.Err() } const opListObjects = "ListObjects" @@ -3116,8 +3884,23 @@ func (c *S3) ListObjectsRequest(input *ListObjectsInput) (req *request.Request, // Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/ListObjects func (c *S3) ListObjects(input *ListObjectsInput) (*ListObjectsOutput, error) { req, out := c.ListObjectsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListObjectsWithContext is the same as ListObjects with the addition of +// the ability to pass a context and additional request options. +// +// See ListObjects for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) ListObjectsWithContext(ctx aws.Context, input *ListObjectsInput, opts ...request.Option) (*ListObjectsOutput, error) { + req, out := c.ListObjectsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // ListObjectsPages iterates over the pages of a ListObjects operation, @@ -3137,12 +3920,37 @@ func (c *S3) ListObjects(input *ListObjectsInput) (*ListObjectsOutput, error) { // return pageNum <= 3 // }) // -func (c *S3) ListObjectsPages(input *ListObjectsInput, fn func(p *ListObjectsOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.ListObjectsRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*ListObjectsOutput), lastPage) - }) +func (c *S3) ListObjectsPages(input *ListObjectsInput, fn func(*ListObjectsOutput, bool) bool) error { + return c.ListObjectsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListObjectsPagesWithContext same as ListObjectsPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) ListObjectsPagesWithContext(ctx aws.Context, input *ListObjectsInput, fn func(*ListObjectsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListObjectsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListObjectsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*ListObjectsOutput), !p.HasNextPage()) + } + return p.Err() } const opListObjectsV2 = "ListObjectsV2" @@ -3215,8 +4023,23 @@ func (c *S3) ListObjectsV2Request(input *ListObjectsV2Input) (req *request.Reque // Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/ListObjectsV2 func (c *S3) ListObjectsV2(input *ListObjectsV2Input) (*ListObjectsV2Output, error) { req, out := c.ListObjectsV2Request(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListObjectsV2WithContext is the same as ListObjectsV2 with the addition of +// the ability to pass a context and additional request options. +// +// See ListObjectsV2 for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) ListObjectsV2WithContext(ctx aws.Context, input *ListObjectsV2Input, opts ...request.Option) (*ListObjectsV2Output, error) { + req, out := c.ListObjectsV2Request(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // ListObjectsV2Pages iterates over the pages of a ListObjectsV2 operation, @@ -3236,12 +4059,37 @@ func (c *S3) ListObjectsV2(input *ListObjectsV2Input) (*ListObjectsV2Output, err // return pageNum <= 3 // }) // -func (c *S3) ListObjectsV2Pages(input *ListObjectsV2Input, fn func(p *ListObjectsV2Output, lastPage bool) (shouldContinue bool)) error { - page, _ := c.ListObjectsV2Request(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*ListObjectsV2Output), lastPage) - }) +func (c *S3) ListObjectsV2Pages(input *ListObjectsV2Input, fn func(*ListObjectsV2Output, bool) bool) error { + return c.ListObjectsV2PagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListObjectsV2PagesWithContext same as ListObjectsV2Pages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) ListObjectsV2PagesWithContext(ctx aws.Context, input *ListObjectsV2Input, fn func(*ListObjectsV2Output, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListObjectsV2Input + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListObjectsV2Request(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*ListObjectsV2Output), !p.HasNextPage()) + } + return p.Err() } const opListParts = "ListParts" @@ -3306,8 +4154,23 @@ func (c *S3) ListPartsRequest(input *ListPartsInput) (req *request.Request, outp // Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/ListParts func (c *S3) ListParts(input *ListPartsInput) (*ListPartsOutput, error) { req, out := c.ListPartsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListPartsWithContext is the same as ListParts with the addition of +// the ability to pass a context and additional request options. +// +// See ListParts for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) ListPartsWithContext(ctx aws.Context, input *ListPartsInput, opts ...request.Option) (*ListPartsOutput, error) { + req, out := c.ListPartsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // ListPartsPages iterates over the pages of a ListParts operation, @@ -3327,12 +4190,37 @@ func (c *S3) ListParts(input *ListPartsInput) (*ListPartsOutput, error) { // return pageNum <= 3 // }) // -func (c *S3) ListPartsPages(input *ListPartsInput, fn func(p *ListPartsOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.ListPartsRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*ListPartsOutput), lastPage) - }) +func (c *S3) ListPartsPages(input *ListPartsInput, fn func(*ListPartsOutput, bool) bool) error { + return c.ListPartsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListPartsPagesWithContext same as ListPartsPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) ListPartsPagesWithContext(ctx aws.Context, input *ListPartsInput, fn func(*ListPartsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListPartsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListPartsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*ListPartsOutput), !p.HasNextPage()) + } + return p.Err() } const opPutBucketAccelerateConfiguration = "PutBucketAccelerateConfiguration" @@ -3393,8 +4281,23 @@ func (c *S3) PutBucketAccelerateConfigurationRequest(input *PutBucketAccelerateC // Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketAccelerateConfiguration func (c *S3) PutBucketAccelerateConfiguration(input *PutBucketAccelerateConfigurationInput) (*PutBucketAccelerateConfigurationOutput, error) { req, out := c.PutBucketAccelerateConfigurationRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// PutBucketAccelerateConfigurationWithContext is the same as PutBucketAccelerateConfiguration with the addition of +// the ability to pass a context and additional request options. +// +// See PutBucketAccelerateConfiguration for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) PutBucketAccelerateConfigurationWithContext(ctx aws.Context, input *PutBucketAccelerateConfigurationInput, opts ...request.Option) (*PutBucketAccelerateConfigurationOutput, error) { + req, out := c.PutBucketAccelerateConfigurationRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opPutBucketAcl = "PutBucketAcl" @@ -3455,8 +4358,23 @@ func (c *S3) PutBucketAclRequest(input *PutBucketAclInput) (req *request.Request // Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketAcl func (c *S3) PutBucketAcl(input *PutBucketAclInput) (*PutBucketAclOutput, error) { req, out := c.PutBucketAclRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// PutBucketAclWithContext is the same as PutBucketAcl with the addition of +// the ability to pass a context and additional request options. +// +// See PutBucketAcl for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) PutBucketAclWithContext(ctx aws.Context, input *PutBucketAclInput, opts ...request.Option) (*PutBucketAclOutput, error) { + req, out := c.PutBucketAclRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opPutBucketAnalyticsConfiguration = "PutBucketAnalyticsConfiguration" @@ -3518,8 +4436,23 @@ func (c *S3) PutBucketAnalyticsConfigurationRequest(input *PutBucketAnalyticsCon // Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketAnalyticsConfiguration func (c *S3) PutBucketAnalyticsConfiguration(input *PutBucketAnalyticsConfigurationInput) (*PutBucketAnalyticsConfigurationOutput, error) { req, out := c.PutBucketAnalyticsConfigurationRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// PutBucketAnalyticsConfigurationWithContext is the same as PutBucketAnalyticsConfiguration with the addition of +// the ability to pass a context and additional request options. +// +// See PutBucketAnalyticsConfiguration for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) PutBucketAnalyticsConfigurationWithContext(ctx aws.Context, input *PutBucketAnalyticsConfigurationInput, opts ...request.Option) (*PutBucketAnalyticsConfigurationOutput, error) { + req, out := c.PutBucketAnalyticsConfigurationRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opPutBucketCors = "PutBucketCors" @@ -3580,8 +4513,23 @@ func (c *S3) PutBucketCorsRequest(input *PutBucketCorsInput) (req *request.Reque // Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketCors func (c *S3) PutBucketCors(input *PutBucketCorsInput) (*PutBucketCorsOutput, error) { req, out := c.PutBucketCorsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// PutBucketCorsWithContext is the same as PutBucketCors with the addition of +// the ability to pass a context and additional request options. +// +// See PutBucketCors for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) PutBucketCorsWithContext(ctx aws.Context, input *PutBucketCorsInput, opts ...request.Option) (*PutBucketCorsOutput, error) { + req, out := c.PutBucketCorsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opPutBucketInventoryConfiguration = "PutBucketInventoryConfiguration" @@ -3643,8 +4591,23 @@ func (c *S3) PutBucketInventoryConfigurationRequest(input *PutBucketInventoryCon // Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketInventoryConfiguration func (c *S3) PutBucketInventoryConfiguration(input *PutBucketInventoryConfigurationInput) (*PutBucketInventoryConfigurationOutput, error) { req, out := c.PutBucketInventoryConfigurationRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// PutBucketInventoryConfigurationWithContext is the same as PutBucketInventoryConfiguration with the addition of +// the ability to pass a context and additional request options. +// +// See PutBucketInventoryConfiguration for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) PutBucketInventoryConfigurationWithContext(ctx aws.Context, input *PutBucketInventoryConfigurationInput, opts ...request.Option) (*PutBucketInventoryConfigurationOutput, error) { + req, out := c.PutBucketInventoryConfigurationRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opPutBucketLifecycle = "PutBucketLifecycle" @@ -3708,8 +4671,23 @@ func (c *S3) PutBucketLifecycleRequest(input *PutBucketLifecycleInput) (req *req // Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketLifecycle func (c *S3) PutBucketLifecycle(input *PutBucketLifecycleInput) (*PutBucketLifecycleOutput, error) { req, out := c.PutBucketLifecycleRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// PutBucketLifecycleWithContext is the same as PutBucketLifecycle with the addition of +// the ability to pass a context and additional request options. +// +// See PutBucketLifecycle for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) PutBucketLifecycleWithContext(ctx aws.Context, input *PutBucketLifecycleInput, opts ...request.Option) (*PutBucketLifecycleOutput, error) { + req, out := c.PutBucketLifecycleRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opPutBucketLifecycleConfiguration = "PutBucketLifecycleConfiguration" @@ -3771,8 +4749,23 @@ func (c *S3) PutBucketLifecycleConfigurationRequest(input *PutBucketLifecycleCon // Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketLifecycleConfiguration func (c *S3) PutBucketLifecycleConfiguration(input *PutBucketLifecycleConfigurationInput) (*PutBucketLifecycleConfigurationOutput, error) { req, out := c.PutBucketLifecycleConfigurationRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// PutBucketLifecycleConfigurationWithContext is the same as PutBucketLifecycleConfiguration with the addition of +// the ability to pass a context and additional request options. +// +// See PutBucketLifecycleConfiguration for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) PutBucketLifecycleConfigurationWithContext(ctx aws.Context, input *PutBucketLifecycleConfigurationInput, opts ...request.Option) (*PutBucketLifecycleConfigurationOutput, error) { + req, out := c.PutBucketLifecycleConfigurationRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opPutBucketLogging = "PutBucketLogging" @@ -3835,8 +4828,23 @@ func (c *S3) PutBucketLoggingRequest(input *PutBucketLoggingInput) (req *request // Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketLogging func (c *S3) PutBucketLogging(input *PutBucketLoggingInput) (*PutBucketLoggingOutput, error) { req, out := c.PutBucketLoggingRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// PutBucketLoggingWithContext is the same as PutBucketLogging with the addition of +// the ability to pass a context and additional request options. +// +// See PutBucketLogging for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) PutBucketLoggingWithContext(ctx aws.Context, input *PutBucketLoggingInput, opts ...request.Option) (*PutBucketLoggingOutput, error) { + req, out := c.PutBucketLoggingRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opPutBucketMetricsConfiguration = "PutBucketMetricsConfiguration" @@ -3898,8 +4906,23 @@ func (c *S3) PutBucketMetricsConfigurationRequest(input *PutBucketMetricsConfigu // Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketMetricsConfiguration func (c *S3) PutBucketMetricsConfiguration(input *PutBucketMetricsConfigurationInput) (*PutBucketMetricsConfigurationOutput, error) { req, out := c.PutBucketMetricsConfigurationRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// PutBucketMetricsConfigurationWithContext is the same as PutBucketMetricsConfiguration with the addition of +// the ability to pass a context and additional request options. +// +// See PutBucketMetricsConfiguration for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) PutBucketMetricsConfigurationWithContext(ctx aws.Context, input *PutBucketMetricsConfigurationInput, opts ...request.Option) (*PutBucketMetricsConfigurationOutput, error) { + req, out := c.PutBucketMetricsConfigurationRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opPutBucketNotification = "PutBucketNotification" @@ -3963,8 +4986,23 @@ func (c *S3) PutBucketNotificationRequest(input *PutBucketNotificationInput) (re // Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketNotification func (c *S3) PutBucketNotification(input *PutBucketNotificationInput) (*PutBucketNotificationOutput, error) { req, out := c.PutBucketNotificationRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// PutBucketNotificationWithContext is the same as PutBucketNotification with the addition of +// the ability to pass a context and additional request options. +// +// See PutBucketNotification for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) PutBucketNotificationWithContext(ctx aws.Context, input *PutBucketNotificationInput, opts ...request.Option) (*PutBucketNotificationOutput, error) { + req, out := c.PutBucketNotificationRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opPutBucketNotificationConfiguration = "PutBucketNotificationConfiguration" @@ -4025,8 +5063,23 @@ func (c *S3) PutBucketNotificationConfigurationRequest(input *PutBucketNotificat // Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketNotificationConfiguration func (c *S3) PutBucketNotificationConfiguration(input *PutBucketNotificationConfigurationInput) (*PutBucketNotificationConfigurationOutput, error) { req, out := c.PutBucketNotificationConfigurationRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// PutBucketNotificationConfigurationWithContext is the same as PutBucketNotificationConfiguration with the addition of +// the ability to pass a context and additional request options. +// +// See PutBucketNotificationConfiguration for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) PutBucketNotificationConfigurationWithContext(ctx aws.Context, input *PutBucketNotificationConfigurationInput, opts ...request.Option) (*PutBucketNotificationConfigurationOutput, error) { + req, out := c.PutBucketNotificationConfigurationRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opPutBucketPolicy = "PutBucketPolicy" @@ -4088,8 +5141,23 @@ func (c *S3) PutBucketPolicyRequest(input *PutBucketPolicyInput) (req *request.R // Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketPolicy func (c *S3) PutBucketPolicy(input *PutBucketPolicyInput) (*PutBucketPolicyOutput, error) { req, out := c.PutBucketPolicyRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// PutBucketPolicyWithContext is the same as PutBucketPolicy with the addition of +// the ability to pass a context and additional request options. +// +// See PutBucketPolicy for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) PutBucketPolicyWithContext(ctx aws.Context, input *PutBucketPolicyInput, opts ...request.Option) (*PutBucketPolicyOutput, error) { + req, out := c.PutBucketPolicyRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opPutBucketReplication = "PutBucketReplication" @@ -4151,8 +5219,23 @@ func (c *S3) PutBucketReplicationRequest(input *PutBucketReplicationInput) (req // Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketReplication func (c *S3) PutBucketReplication(input *PutBucketReplicationInput) (*PutBucketReplicationOutput, error) { req, out := c.PutBucketReplicationRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// PutBucketReplicationWithContext is the same as PutBucketReplication with the addition of +// the ability to pass a context and additional request options. +// +// See PutBucketReplication for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) PutBucketReplicationWithContext(ctx aws.Context, input *PutBucketReplicationInput, opts ...request.Option) (*PutBucketReplicationOutput, error) { + req, out := c.PutBucketReplicationRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opPutBucketRequestPayment = "PutBucketRequestPayment" @@ -4217,8 +5300,23 @@ func (c *S3) PutBucketRequestPaymentRequest(input *PutBucketRequestPaymentInput) // Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketRequestPayment func (c *S3) PutBucketRequestPayment(input *PutBucketRequestPaymentInput) (*PutBucketRequestPaymentOutput, error) { req, out := c.PutBucketRequestPaymentRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// PutBucketRequestPaymentWithContext is the same as PutBucketRequestPayment with the addition of +// the ability to pass a context and additional request options. +// +// See PutBucketRequestPayment for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) PutBucketRequestPaymentWithContext(ctx aws.Context, input *PutBucketRequestPaymentInput, opts ...request.Option) (*PutBucketRequestPaymentOutput, error) { + req, out := c.PutBucketRequestPaymentRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opPutBucketTagging = "PutBucketTagging" @@ -4279,8 +5377,23 @@ func (c *S3) PutBucketTaggingRequest(input *PutBucketTaggingInput) (req *request // Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketTagging func (c *S3) PutBucketTagging(input *PutBucketTaggingInput) (*PutBucketTaggingOutput, error) { req, out := c.PutBucketTaggingRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// PutBucketTaggingWithContext is the same as PutBucketTagging with the addition of +// the ability to pass a context and additional request options. +// +// See PutBucketTagging for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) PutBucketTaggingWithContext(ctx aws.Context, input *PutBucketTaggingInput, opts ...request.Option) (*PutBucketTaggingOutput, error) { + req, out := c.PutBucketTaggingRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opPutBucketVersioning = "PutBucketVersioning" @@ -4342,8 +5455,23 @@ func (c *S3) PutBucketVersioningRequest(input *PutBucketVersioningInput) (req *r // Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketVersioning func (c *S3) PutBucketVersioning(input *PutBucketVersioningInput) (*PutBucketVersioningOutput, error) { req, out := c.PutBucketVersioningRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// PutBucketVersioningWithContext is the same as PutBucketVersioning with the addition of +// the ability to pass a context and additional request options. +// +// See PutBucketVersioning for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) PutBucketVersioningWithContext(ctx aws.Context, input *PutBucketVersioningInput, opts ...request.Option) (*PutBucketVersioningOutput, error) { + req, out := c.PutBucketVersioningRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opPutBucketWebsite = "PutBucketWebsite" @@ -4404,8 +5532,23 @@ func (c *S3) PutBucketWebsiteRequest(input *PutBucketWebsiteInput) (req *request // Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketWebsite func (c *S3) PutBucketWebsite(input *PutBucketWebsiteInput) (*PutBucketWebsiteOutput, error) { req, out := c.PutBucketWebsiteRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// PutBucketWebsiteWithContext is the same as PutBucketWebsite with the addition of +// the ability to pass a context and additional request options. +// +// See PutBucketWebsite for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) PutBucketWebsiteWithContext(ctx aws.Context, input *PutBucketWebsiteInput, opts ...request.Option) (*PutBucketWebsiteOutput, error) { + req, out := c.PutBucketWebsiteRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opPutObject = "PutObject" @@ -4464,8 +5607,23 @@ func (c *S3) PutObjectRequest(input *PutObjectInput) (req *request.Request, outp // Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutObject func (c *S3) PutObject(input *PutObjectInput) (*PutObjectOutput, error) { req, out := c.PutObjectRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// PutObjectWithContext is the same as PutObject with the addition of +// the ability to pass a context and additional request options. +// +// See PutObject for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) PutObjectWithContext(ctx aws.Context, input *PutObjectInput, opts ...request.Option) (*PutObjectOutput, error) { + req, out := c.PutObjectRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opPutObjectAcl = "PutObjectAcl" @@ -4530,8 +5688,23 @@ func (c *S3) PutObjectAclRequest(input *PutObjectAclInput) (req *request.Request // Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutObjectAcl func (c *S3) PutObjectAcl(input *PutObjectAclInput) (*PutObjectAclOutput, error) { req, out := c.PutObjectAclRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// PutObjectAclWithContext is the same as PutObjectAcl with the addition of +// the ability to pass a context and additional request options. +// +// See PutObjectAcl for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) PutObjectAclWithContext(ctx aws.Context, input *PutObjectAclInput, opts ...request.Option) (*PutObjectAclOutput, error) { + req, out := c.PutObjectAclRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opPutObjectTagging = "PutObjectTagging" @@ -4590,8 +5763,23 @@ func (c *S3) PutObjectTaggingRequest(input *PutObjectTaggingInput) (req *request // Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutObjectTagging func (c *S3) PutObjectTagging(input *PutObjectTaggingInput) (*PutObjectTaggingOutput, error) { req, out := c.PutObjectTaggingRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// PutObjectTaggingWithContext is the same as PutObjectTagging with the addition of +// the ability to pass a context and additional request options. +// +// See PutObjectTagging for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) PutObjectTaggingWithContext(ctx aws.Context, input *PutObjectTaggingInput, opts ...request.Option) (*PutObjectTaggingOutput, error) { + req, out := c.PutObjectTaggingRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opRestoreObject = "RestoreObject" @@ -4655,8 +5843,23 @@ func (c *S3) RestoreObjectRequest(input *RestoreObjectInput) (req *request.Reque // Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/RestoreObject func (c *S3) RestoreObject(input *RestoreObjectInput) (*RestoreObjectOutput, error) { req, out := c.RestoreObjectRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// RestoreObjectWithContext is the same as RestoreObject with the addition of +// the ability to pass a context and additional request options. +// +// See RestoreObject for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) RestoreObjectWithContext(ctx aws.Context, input *RestoreObjectInput, opts ...request.Option) (*RestoreObjectOutput, error) { + req, out := c.RestoreObjectRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opUploadPart = "UploadPart" @@ -4721,8 +5924,23 @@ func (c *S3) UploadPartRequest(input *UploadPartInput) (req *request.Request, ou // Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/UploadPart func (c *S3) UploadPart(input *UploadPartInput) (*UploadPartOutput, error) { req, out := c.UploadPartRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// UploadPartWithContext is the same as UploadPart with the addition of +// the ability to pass a context and additional request options. +// +// See UploadPart for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) UploadPartWithContext(ctx aws.Context, input *UploadPartInput, opts ...request.Option) (*UploadPartOutput, error) { + req, out := c.UploadPartRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opUploadPartCopy = "UploadPartCopy" @@ -4781,8 +5999,23 @@ func (c *S3) UploadPartCopyRequest(input *UploadPartCopyInput) (req *request.Req // Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/UploadPartCopy func (c *S3) UploadPartCopy(input *UploadPartCopyInput) (*UploadPartCopyOutput, error) { req, out := c.UploadPartCopyRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// UploadPartCopyWithContext is the same as UploadPartCopy with the addition of +// the ability to pass a context and additional request options. +// +// See UploadPartCopy for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) UploadPartCopyWithContext(ctx aws.Context, input *UploadPartCopyInput, opts ...request.Option) (*UploadPartCopyOutput, error) { + req, out := c.UploadPartCopyRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // Specifies the days since the initiation of an Incomplete Multipart Upload diff --git a/vendor/github.com/aws/aws-sdk-go/service/s3/bucket_location.go b/vendor/github.com/aws/aws-sdk-go/service/s3/bucket_location.go index c3a2702da..bc68a46ac 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/s3/bucket_location.go +++ b/vendor/github.com/aws/aws-sdk-go/service/s3/bucket_location.go @@ -12,6 +12,69 @@ import ( var reBucketLocation = regexp.MustCompile(`>([^<>]+)<\/Location`) +// NormalizeBucketLocation is a utility function which will update the +// passed in value to always be a region ID. Generally this would be used +// with GetBucketLocation API operation. +// +// Replaces empty string with "us-east-1", and "EU" with "eu-west-1". +// +// See http://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketGETlocation.html +// for more information on the values that can be returned. +func NormalizeBucketLocation(loc string) string { + switch loc { + case "": + loc = "us-east-1" + case "EU": + loc = "eu-west-1" + } + + return loc +} + +// NormalizeBucketLocationHandler is a request handler which will update the +// GetBucketLocation's result LocationConstraint value to always be a region ID. +// +// Replaces empty string with "us-east-1", and "EU" with "eu-west-1". +// +// See http://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketGETlocation.html +// for more information on the values that can be returned. +// +// req, result := svc.GetBucketLocationRequest(&s3.GetBucketLocationInput{ +// Bucket: aws.String(bucket), +// }) +// req.Handlers.Unmarshal.PushBackNamed(NormalizeBucketLocationHandler) +// err := req.Send() +var NormalizeBucketLocationHandler = request.NamedHandler{ + Name: "awssdk.s3.NormalizeBucketLocation", + Fn: func(req *request.Request) { + if req.Error != nil { + return + } + + out := req.Data.(*GetBucketLocationOutput) + loc := NormalizeBucketLocation(aws.StringValue(out.LocationConstraint)) + out.LocationConstraint = aws.String(loc) + }, +} + +// WithNormalizeBucketLocation is a request option which will update the +// GetBucketLocation's result LocationConstraint value to always be a region ID. +// +// Replaces empty string with "us-east-1", and "EU" with "eu-west-1". +// +// See http://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketGETlocation.html +// for more information on the values that can be returned. +// +// result, err := svc.GetBucketLocationWithContext(ctx, +// &s3.GetBucketLocationInput{ +// Bucket: aws.String(bucket), +// }, +// s3.WithNormalizeBucketLocation, +// ) +func WithNormalizeBucketLocation(r *request.Request) { + r.Handlers.Unmarshal.PushBackNamed(NormalizeBucketLocationHandler) +} + func buildGetBucketLocation(r *request.Request) { if r.DataFilled() { out := r.Data.(*GetBucketLocationOutput) @@ -24,7 +87,7 @@ func buildGetBucketLocation(r *request.Request) { match := reBucketLocation.FindSubmatch(b) if len(match) > 1 { loc := string(match[1]) - out.LocationConstraint = &loc + out.LocationConstraint = aws.String(loc) } } } diff --git a/vendor/github.com/aws/aws-sdk-go/service/s3/doc.go b/vendor/github.com/aws/aws-sdk-go/service/s3/doc.go new file mode 100644 index 000000000..f045fd0db --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/service/s3/doc.go @@ -0,0 +1,78 @@ +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. + +// Package s3 provides the client and types for making API +// requests to Amazon Simple Storage Service. +// +// See https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01 for more information on this service. +// +// See s3 package documentation for more information. +// https://docs.aws.amazon.com/sdk-for-go/api/service/s3/ +// +// Using the Client +// +// To use the client for Amazon Simple Storage Service you will first need +// to create a new instance of it. +// +// When creating a client for an AWS service you'll first need to have a Session +// already created. The Session provides configuration that can be shared +// between multiple service clients. Additional configuration can be applied to +// the Session and service's client when they are constructed. The aws package's +// Config type contains several fields such as Region for the AWS Region the +// client should make API requests too. The optional Config value can be provided +// as the variadic argument for Sessions and client creation. +// +// Once the service's client is created you can use it to make API requests the +// AWS service. These clients are safe to use concurrently. +// +// // Create a session to share configuration, and load external configuration. +// sess := session.Must(session.NewSession()) +// +// // Create the service's client with the session. +// svc := s3.New(sess) +// +// See the SDK's documentation for more information on how to use service clients. +// https://docs.aws.amazon.com/sdk-for-go/api/ +// +// See aws package's Config type for more information on configuration options. +// https://docs.aws.amazon.com/sdk-for-go/api/aws/#Config +// +// See the Amazon Simple Storage Service client S3 for more +// information on creating the service's client. +// https://docs.aws.amazon.com/sdk-for-go/api/service/s3/#New +// +// Once the client is created you can make an API request to the service. +// Each API method takes a input parameter, and returns the service response +// and an error. +// +// The API method will document which error codes the service can be returned +// by the operation if the service models the API operation's errors. These +// errors will also be available as const strings prefixed with "ErrCode". +// +// result, err := svc.AbortMultipartUpload(params) +// if err != nil { +// // Cast err to awserr.Error to handle specific error codes. +// aerr, ok := err.(awserr.Error) +// if ok && aerr.Code() == { +// // Specific error code handling +// } +// return err +// } +// +// fmt.Println("AbortMultipartUpload result:") +// fmt.Println(result) +// +// Using the Client with Context +// +// The service's client also provides methods to make API requests with a Context +// value. This allows you to control the timeout, and cancellation of pending +// requests. These methods also take request Option as variadic parameter to apply +// additional configuration to the API request. +// +// ctx := context.Background() +// +// result, err := svc.AbortMultipartUploadWithContext(ctx, params) +// +// See the request package documentation for more information on using Context pattern +// with the SDK. +// https://docs.aws.amazon.com/sdk-for-go/api/aws/request/ +package s3 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 new file mode 100644 index 000000000..b794a63ba --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/service/s3/doc_custom.go @@ -0,0 +1,109 @@ +// Upload Managers +// +// The s3manager package's Uploader provides concurrent upload of content to S3 +// by taking advantage of S3's Multipart APIs. The Uploader also supports both +// io.Reader for streaming uploads, and will also take advantage of io.ReadSeeker +// for optimizations if the Body satisfies that type. Once the Uploader instance +// is created you can call Upload concurrently from multiple goroutines safely. +// +// // The session the S3 Uploader will use +// sess := session.Must(session.NewSession()) +// +// // Create an uploader with the session and default options +// uploader := s3manager.NewUploader(sess) +// +// f, err := os.Open(filename) +// if err != nil { +// return fmt.Errorf("failed to open file %q, %v", filename, err) +// } +// +// // Upload the file to S3. +// result, err := uploader.Upload(&s3manager.UploadInput{ +// Bucket: aws.String(myBucket), +// Key: aws.String(myString), +// Body: f, +// }) +// if err != nil { +// return fmt.Errorf("failed to upload file, %v", err) +// } +// fmt.Printf("file uploaded to, %s\n", aws.StringValue(result.Location)) +// +// See the s3manager package's Uploader type documentation for more information. +// https://docs.aws.amazon.com/sdk-for-go/api/service/s3/s3manager/#Uploader +// +// Download Manager +// +// The s3manager package's Downloader provides concurrently downloading of Objects +// from S3. The Downloader will write S3 Object content with an io.WriterAt. +// Once the Downloader instance is created you can call Upload concurrently from +// multiple goroutines safely. +// +// // The session the S3 Downloader will use +// sess := session.Must(session.NewSession()) +// +// // Create a downloader with the session and default options +// downloader := s3manager.NewDownloader(sess) +// +// // Create a file to write the S3 Object contents to. +// f, err := os.Create(filename) +// if err != nil { +// return fmt.Errorf("failed to create file %q, %v", filename, err) +// } +// +// // Write the contents of S3 Object to the file +// n, err := downloader.Download(f, &s3.GetObjectInput{ +// Bucket: aws.String(myBucket), +// Key: aws.String(myString), +// }) +// if err != nil { +// return fmt.Errorf("failed to upload file, %v", err) +// } +// fmt.Printf("file downloaded, %d bytes\n", n) +// +// See the s3manager package's Downloader type documentation for more information. +// https://docs.aws.amazon.com/sdk-for-go/api/service/s3/s3manager/#Downloader +// +// Get Bucket Region +// +// GetBucketRegion will attempt to get the region for a bucket using a region +// hint to determine which AWS partition to perform the query on. Use this utility +// to determine the region a bucket is in. +// +// sess := session.Must(session.NewSession()) +// +// bucket := "my-bucket" +// region, err := s3manager.GetBucketRegion(ctx, sess, bucket, "us-west-2") +// if err != nil { +// if aerr, ok := err.(awserr.Error); ok && aerr.Code() == "NotFound" { +// fmt.Fprintf(os.Stderr, "unable to find bucket %s's region not found\n", bucket) +// } +// return err +// } +// fmt.Printf("Bucket %s is in %s region\n", bucket, region) +// +// See the s3manager package's GetBucketRegion function documentation for more information +// https://docs.aws.amazon.com/sdk-for-go/api/service/s3/s3manager/#GetBucketRegion +// +// S3 Crypto Client +// +// The s3crypto package provides the tools to upload and download encrypted +// 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/ +// +package s3 diff --git a/vendor/github.com/aws/aws-sdk-go/service/s3/errors.go b/vendor/github.com/aws/aws-sdk-go/service/s3/errors.go index 13ebbdad9..931cb17bb 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/s3/errors.go +++ b/vendor/github.com/aws/aws-sdk-go/service/s3/errors.go @@ -1,4 +1,4 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. package s3 diff --git a/vendor/github.com/aws/aws-sdk-go/service/s3/service.go b/vendor/github.com/aws/aws-sdk-go/service/s3/service.go index 5e6f2299e..614e477d3 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/s3/service.go +++ b/vendor/github.com/aws/aws-sdk-go/service/s3/service.go @@ -1,4 +1,4 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. package s3 @@ -11,10 +11,12 @@ import ( "github.com/aws/aws-sdk-go/private/protocol/restxml" ) -// S3 is a client for Amazon S3. -// The service client's operations are safe to be used concurrently. -// It is not safe to mutate any of the client's properties though. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01 +// S3 provides the API operation methods for making requests to +// Amazon Simple Storage Service. See this package's package overview docs +// for details on the service. +// +// S3 methods are safe to use concurrently. It is not safe to +// modify mutate any of the struct's properties though. type S3 struct { *client.Client } 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 ed91c5872..bcca8627a 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/s3/unmarshal_error.go +++ b/vendor/github.com/aws/aws-sdk-go/service/s3/unmarshal_error.go @@ -23,17 +23,22 @@ func unmarshalError(r *request.Request) { defer r.HTTPResponse.Body.Close() defer io.Copy(ioutil.Discard, r.HTTPResponse.Body) + hostID := r.HTTPResponse.Header.Get("X-Amz-Id-2") + // Bucket exists in a different region, and request needs // to be made to the correct region. if r.HTTPResponse.StatusCode == http.StatusMovedPermanently { - r.Error = awserr.NewRequestFailure( - awserr.New("BucketRegionError", - fmt.Sprintf("incorrect region, the bucket is not in '%s' region", - aws.StringValue(r.Config.Region)), - nil), - r.HTTPResponse.StatusCode, - r.RequestID, - ) + r.Error = requestFailure{ + RequestFailure: awserr.NewRequestFailure( + awserr.New("BucketRegionError", + fmt.Sprintf("incorrect region, the bucket is not in '%s' region", + aws.StringValue(r.Config.Region)), + nil), + r.HTTPResponse.StatusCode, + r.RequestID, + ), + hostID: hostID, + } return } @@ -48,6 +53,7 @@ func unmarshalError(r *request.Request) { } else { errCode = resp.Code errMsg = resp.Message + err = nil } // Fallback to status code converted to message if still no error code @@ -57,9 +63,41 @@ func unmarshalError(r *request.Request) { errMsg = statusText } - r.Error = awserr.NewRequestFailure( - awserr.New(errCode, errMsg, nil), - r.HTTPResponse.StatusCode, - r.RequestID, - ) + r.Error = requestFailure{ + RequestFailure: awserr.NewRequestFailure( + awserr.New(errCode, errMsg, err), + r.HTTPResponse.StatusCode, + r.RequestID, + ), + hostID: hostID, + } +} + +// A RequestFailure provides access to the S3 Request ID and Host ID values +// returned from API operation errors. Getting the error as a string will +// return the formated error with the same information as awserr.RequestFailure, +// while also adding the HostID value from the response. +type RequestFailure interface { + awserr.RequestFailure + + // Host ID is the S3 Host ID needed for debug, and contacting support + HostID() string +} + +type requestFailure struct { + awserr.RequestFailure + + hostID string +} + +func (r requestFailure) Error() string { + extra := fmt.Sprintf("status code: %d, request id: %s, host id: %s", + r.StatusCode(), r.RequestID(), r.hostID) + return awserr.SprintError(r.Code(), r.Message(), extra, r.OrigErr()) +} +func (r requestFailure) String() string { + return r.Error() +} +func (r requestFailure) HostID() string { + return r.hostID } diff --git a/vendor/github.com/aws/aws-sdk-go/service/s3/waiters.go b/vendor/github.com/aws/aws-sdk-go/service/s3/waiters.go index 5e16be4ba..cccfa8c2b 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/s3/waiters.go +++ b/vendor/github.com/aws/aws-sdk-go/service/s3/waiters.go @@ -1,9 +1,12 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. package s3 import ( - "github.com/aws/aws-sdk-go/private/waiter" + "time" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/request" ) // WaitUntilBucketExists uses the Amazon S3 API operation @@ -11,44 +14,60 @@ import ( // If the condition is not meet within the max attempt window an error will // be returned. func (c *S3) WaitUntilBucketExists(input *HeadBucketInput) error { - waiterCfg := waiter.Config{ - Operation: "HeadBucket", - Delay: 5, + return c.WaitUntilBucketExistsWithContext(aws.BackgroundContext(), input) +} + +// WaitUntilBucketExistsWithContext is an extended version of WaitUntilBucketExists. +// With the support for passing in a context and options to configure the +// Waiter and the underlying request options. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) WaitUntilBucketExistsWithContext(ctx aws.Context, input *HeadBucketInput, opts ...request.WaiterOption) error { + w := request.Waiter{ + Name: "WaitUntilBucketExists", MaxAttempts: 20, - Acceptors: []waiter.WaitAcceptor{ + Delay: request.ConstantWaiterDelay(5 * time.Second), + Acceptors: []request.WaiterAcceptor{ { - State: "success", - Matcher: "status", - Argument: "", + State: request.SuccessWaiterState, + Matcher: request.StatusWaiterMatch, Expected: 200, }, { - State: "success", - Matcher: "status", - Argument: "", + State: request.SuccessWaiterState, + Matcher: request.StatusWaiterMatch, Expected: 301, }, { - State: "success", - Matcher: "status", - Argument: "", + State: request.SuccessWaiterState, + Matcher: request.StatusWaiterMatch, Expected: 403, }, { - State: "retry", - Matcher: "status", - Argument: "", + State: request.RetryWaiterState, + Matcher: request.StatusWaiterMatch, Expected: 404, }, }, + Logger: c.Config.Logger, + NewRequest: func(opts []request.Option) (*request.Request, error) { + var inCpy *HeadBucketInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.HeadBucketRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, } + w.ApplyOptions(opts...) - w := waiter.Waiter{ - Client: c, - Input: input, - Config: waiterCfg, - } - return w.Wait() + return w.WaitWithContext(ctx) } // WaitUntilBucketNotExists uses the Amazon S3 API operation @@ -56,26 +75,45 @@ func (c *S3) WaitUntilBucketExists(input *HeadBucketInput) error { // If the condition is not meet within the max attempt window an error will // be returned. func (c *S3) WaitUntilBucketNotExists(input *HeadBucketInput) error { - waiterCfg := waiter.Config{ - Operation: "HeadBucket", - Delay: 5, + return c.WaitUntilBucketNotExistsWithContext(aws.BackgroundContext(), input) +} + +// WaitUntilBucketNotExistsWithContext is an extended version of WaitUntilBucketNotExists. +// With the support for passing in a context and options to configure the +// Waiter and the underlying request options. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) WaitUntilBucketNotExistsWithContext(ctx aws.Context, input *HeadBucketInput, opts ...request.WaiterOption) error { + w := request.Waiter{ + Name: "WaitUntilBucketNotExists", MaxAttempts: 20, - Acceptors: []waiter.WaitAcceptor{ + Delay: request.ConstantWaiterDelay(5 * time.Second), + Acceptors: []request.WaiterAcceptor{ { - State: "success", - Matcher: "status", - Argument: "", + State: request.SuccessWaiterState, + Matcher: request.StatusWaiterMatch, Expected: 404, }, }, + Logger: c.Config.Logger, + NewRequest: func(opts []request.Option) (*request.Request, error) { + var inCpy *HeadBucketInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.HeadBucketRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, } + w.ApplyOptions(opts...) - w := waiter.Waiter{ - Client: c, - Input: input, - Config: waiterCfg, - } - return w.Wait() + return w.WaitWithContext(ctx) } // WaitUntilObjectExists uses the Amazon S3 API operation @@ -83,32 +121,50 @@ func (c *S3) WaitUntilBucketNotExists(input *HeadBucketInput) error { // If the condition is not meet within the max attempt window an error will // be returned. func (c *S3) WaitUntilObjectExists(input *HeadObjectInput) error { - waiterCfg := waiter.Config{ - Operation: "HeadObject", - Delay: 5, + return c.WaitUntilObjectExistsWithContext(aws.BackgroundContext(), input) +} + +// WaitUntilObjectExistsWithContext is an extended version of WaitUntilObjectExists. +// With the support for passing in a context and options to configure the +// Waiter and the underlying request options. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) WaitUntilObjectExistsWithContext(ctx aws.Context, input *HeadObjectInput, opts ...request.WaiterOption) error { + w := request.Waiter{ + Name: "WaitUntilObjectExists", MaxAttempts: 20, - Acceptors: []waiter.WaitAcceptor{ + Delay: request.ConstantWaiterDelay(5 * time.Second), + Acceptors: []request.WaiterAcceptor{ { - State: "success", - Matcher: "status", - Argument: "", + State: request.SuccessWaiterState, + Matcher: request.StatusWaiterMatch, Expected: 200, }, { - State: "retry", - Matcher: "status", - Argument: "", + State: request.RetryWaiterState, + Matcher: request.StatusWaiterMatch, Expected: 404, }, }, + Logger: c.Config.Logger, + NewRequest: func(opts []request.Option) (*request.Request, error) { + var inCpy *HeadObjectInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.HeadObjectRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, } + w.ApplyOptions(opts...) - w := waiter.Waiter{ - Client: c, - Input: input, - Config: waiterCfg, - } - return w.Wait() + return w.WaitWithContext(ctx) } // WaitUntilObjectNotExists uses the Amazon S3 API operation @@ -116,24 +172,43 @@ func (c *S3) WaitUntilObjectExists(input *HeadObjectInput) error { // If the condition is not meet within the max attempt window an error will // be returned. func (c *S3) WaitUntilObjectNotExists(input *HeadObjectInput) error { - waiterCfg := waiter.Config{ - Operation: "HeadObject", - Delay: 5, + return c.WaitUntilObjectNotExistsWithContext(aws.BackgroundContext(), input) +} + +// WaitUntilObjectNotExistsWithContext is an extended version of WaitUntilObjectNotExists. +// With the support for passing in a context and options to configure the +// Waiter and the underlying request options. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) WaitUntilObjectNotExistsWithContext(ctx aws.Context, input *HeadObjectInput, opts ...request.WaiterOption) error { + w := request.Waiter{ + Name: "WaitUntilObjectNotExists", MaxAttempts: 20, - Acceptors: []waiter.WaitAcceptor{ + Delay: request.ConstantWaiterDelay(5 * time.Second), + Acceptors: []request.WaiterAcceptor{ { - State: "success", - Matcher: "status", - Argument: "", + State: request.SuccessWaiterState, + Matcher: request.StatusWaiterMatch, Expected: 404, }, }, + Logger: c.Config.Logger, + NewRequest: func(opts []request.Option) (*request.Request, error) { + var inCpy *HeadObjectInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.HeadObjectRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, } + w.ApplyOptions(opts...) - w := waiter.Waiter{ - Client: c, - Input: input, - Config: waiterCfg, - } - return w.Wait() + return w.WaitWithContext(ctx) } diff --git a/vendor/github.com/aws/aws-sdk-go/service/ses/api.go b/vendor/github.com/aws/aws-sdk-go/service/ses/api.go index 79253784a..80e738ddc 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/ses/api.go +++ b/vendor/github.com/aws/aws-sdk-go/service/ses/api.go @@ -1,12 +1,12 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. -// Package ses provides a client for Amazon Simple Email Service. package ses import ( "fmt" "time" + "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awsutil" "github.com/aws/aws-sdk-go/aws/request" "github.com/aws/aws-sdk-go/private/protocol" @@ -88,8 +88,23 @@ func (c *SES) CloneReceiptRuleSetRequest(input *CloneReceiptRuleSetInput) (req * // Please also see https://docs.aws.amazon.com/goto/WebAPI/email-2010-12-01/CloneReceiptRuleSet func (c *SES) CloneReceiptRuleSet(input *CloneReceiptRuleSetInput) (*CloneReceiptRuleSetOutput, error) { req, out := c.CloneReceiptRuleSetRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CloneReceiptRuleSetWithContext is the same as CloneReceiptRuleSet with the addition of +// the ability to pass a context and additional request options. +// +// See CloneReceiptRuleSet 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 *SES) CloneReceiptRuleSetWithContext(ctx aws.Context, input *CloneReceiptRuleSetInput, opts ...request.Option) (*CloneReceiptRuleSetOutput, error) { + req, out := c.CloneReceiptRuleSetRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateConfigurationSet = "CreateConfigurationSet" @@ -167,8 +182,23 @@ func (c *SES) CreateConfigurationSetRequest(input *CreateConfigurationSetInput) // Please also see https://docs.aws.amazon.com/goto/WebAPI/email-2010-12-01/CreateConfigurationSet func (c *SES) CreateConfigurationSet(input *CreateConfigurationSetInput) (*CreateConfigurationSetOutput, error) { req, out := c.CreateConfigurationSetRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateConfigurationSetWithContext is the same as CreateConfigurationSet with the addition of +// the ability to pass a context and additional request options. +// +// See CreateConfigurationSet 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 *SES) CreateConfigurationSetWithContext(ctx aws.Context, input *CreateConfigurationSetInput, opts ...request.Option) (*CreateConfigurationSetOutput, error) { + req, out := c.CreateConfigurationSetRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateConfigurationSetEventDestination = "CreateConfigurationSetEventDestination" @@ -258,8 +288,23 @@ func (c *SES) CreateConfigurationSetEventDestinationRequest(input *CreateConfigu // Please also see https://docs.aws.amazon.com/goto/WebAPI/email-2010-12-01/CreateConfigurationSetEventDestination func (c *SES) CreateConfigurationSetEventDestination(input *CreateConfigurationSetEventDestinationInput) (*CreateConfigurationSetEventDestinationOutput, error) { req, out := c.CreateConfigurationSetEventDestinationRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateConfigurationSetEventDestinationWithContext is the same as CreateConfigurationSetEventDestination with the addition of +// the ability to pass a context and additional request options. +// +// See CreateConfigurationSetEventDestination 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 *SES) CreateConfigurationSetEventDestinationWithContext(ctx aws.Context, input *CreateConfigurationSetEventDestinationInput, opts ...request.Option) (*CreateConfigurationSetEventDestinationOutput, error) { + req, out := c.CreateConfigurationSetEventDestinationRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateReceiptFilter = "CreateReceiptFilter" @@ -332,8 +377,23 @@ func (c *SES) CreateReceiptFilterRequest(input *CreateReceiptFilterInput) (req * // Please also see https://docs.aws.amazon.com/goto/WebAPI/email-2010-12-01/CreateReceiptFilter func (c *SES) CreateReceiptFilter(input *CreateReceiptFilterInput) (*CreateReceiptFilterOutput, error) { req, out := c.CreateReceiptFilterRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateReceiptFilterWithContext is the same as CreateReceiptFilter with the addition of +// the ability to pass a context and additional request options. +// +// See CreateReceiptFilter 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 *SES) CreateReceiptFilterWithContext(ctx aws.Context, input *CreateReceiptFilterInput, opts ...request.Option) (*CreateReceiptFilterOutput, error) { + req, out := c.CreateReceiptFilterRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateReceiptRule = "CreateReceiptRule" @@ -429,8 +489,23 @@ func (c *SES) CreateReceiptRuleRequest(input *CreateReceiptRuleInput) (req *requ // Please also see https://docs.aws.amazon.com/goto/WebAPI/email-2010-12-01/CreateReceiptRule func (c *SES) CreateReceiptRule(input *CreateReceiptRuleInput) (*CreateReceiptRuleOutput, error) { req, out := c.CreateReceiptRuleRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateReceiptRuleWithContext is the same as CreateReceiptRule with the addition of +// the ability to pass a context and additional request options. +// +// See CreateReceiptRule 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 *SES) CreateReceiptRuleWithContext(ctx aws.Context, input *CreateReceiptRuleInput, opts ...request.Option) (*CreateReceiptRuleOutput, error) { + req, out := c.CreateReceiptRuleRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateReceiptRuleSet = "CreateReceiptRuleSet" @@ -503,8 +578,23 @@ func (c *SES) CreateReceiptRuleSetRequest(input *CreateReceiptRuleSetInput) (req // Please also see https://docs.aws.amazon.com/goto/WebAPI/email-2010-12-01/CreateReceiptRuleSet func (c *SES) CreateReceiptRuleSet(input *CreateReceiptRuleSetInput) (*CreateReceiptRuleSetOutput, error) { req, out := c.CreateReceiptRuleSetRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateReceiptRuleSetWithContext is the same as CreateReceiptRuleSet with the addition of +// the ability to pass a context and additional request options. +// +// See CreateReceiptRuleSet 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 *SES) CreateReceiptRuleSetWithContext(ctx aws.Context, input *CreateReceiptRuleSetInput, opts ...request.Option) (*CreateReceiptRuleSetOutput, error) { + req, out := c.CreateReceiptRuleSetRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteConfigurationSet = "DeleteConfigurationSet" @@ -573,8 +663,23 @@ func (c *SES) DeleteConfigurationSetRequest(input *DeleteConfigurationSetInput) // Please also see https://docs.aws.amazon.com/goto/WebAPI/email-2010-12-01/DeleteConfigurationSet func (c *SES) DeleteConfigurationSet(input *DeleteConfigurationSetInput) (*DeleteConfigurationSetOutput, error) { req, out := c.DeleteConfigurationSetRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteConfigurationSetWithContext is the same as DeleteConfigurationSet with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteConfigurationSet 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 *SES) DeleteConfigurationSetWithContext(ctx aws.Context, input *DeleteConfigurationSetInput, opts ...request.Option) (*DeleteConfigurationSetOutput, error) { + req, out := c.DeleteConfigurationSetRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteConfigurationSetEventDestination = "DeleteConfigurationSetEventDestination" @@ -647,8 +752,23 @@ func (c *SES) DeleteConfigurationSetEventDestinationRequest(input *DeleteConfigu // Please also see https://docs.aws.amazon.com/goto/WebAPI/email-2010-12-01/DeleteConfigurationSetEventDestination func (c *SES) DeleteConfigurationSetEventDestination(input *DeleteConfigurationSetEventDestinationInput) (*DeleteConfigurationSetEventDestinationOutput, error) { req, out := c.DeleteConfigurationSetEventDestinationRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteConfigurationSetEventDestinationWithContext is the same as DeleteConfigurationSetEventDestination with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteConfigurationSetEventDestination 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 *SES) DeleteConfigurationSetEventDestinationWithContext(ctx aws.Context, input *DeleteConfigurationSetEventDestinationInput, opts ...request.Option) (*DeleteConfigurationSetEventDestinationOutput, error) { + req, out := c.DeleteConfigurationSetEventDestinationRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteIdentity = "DeleteIdentity" @@ -710,8 +830,23 @@ func (c *SES) DeleteIdentityRequest(input *DeleteIdentityInput) (req *request.Re // Please also see https://docs.aws.amazon.com/goto/WebAPI/email-2010-12-01/DeleteIdentity func (c *SES) DeleteIdentity(input *DeleteIdentityInput) (*DeleteIdentityOutput, error) { req, out := c.DeleteIdentityRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteIdentityWithContext is the same as DeleteIdentity with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteIdentity 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 *SES) DeleteIdentityWithContext(ctx aws.Context, input *DeleteIdentityInput, opts ...request.Option) (*DeleteIdentityOutput, error) { + req, out := c.DeleteIdentityRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteIdentityPolicy = "DeleteIdentityPolicy" @@ -781,8 +916,23 @@ func (c *SES) DeleteIdentityPolicyRequest(input *DeleteIdentityPolicyInput) (req // Please also see https://docs.aws.amazon.com/goto/WebAPI/email-2010-12-01/DeleteIdentityPolicy func (c *SES) DeleteIdentityPolicy(input *DeleteIdentityPolicyInput) (*DeleteIdentityPolicyOutput, error) { req, out := c.DeleteIdentityPolicyRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteIdentityPolicyWithContext is the same as DeleteIdentityPolicy with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteIdentityPolicy 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 *SES) DeleteIdentityPolicyWithContext(ctx aws.Context, input *DeleteIdentityPolicyInput, opts ...request.Option) (*DeleteIdentityPolicyOutput, error) { + req, out := c.DeleteIdentityPolicyRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteReceiptFilter = "DeleteReceiptFilter" @@ -846,8 +996,23 @@ func (c *SES) DeleteReceiptFilterRequest(input *DeleteReceiptFilterInput) (req * // Please also see https://docs.aws.amazon.com/goto/WebAPI/email-2010-12-01/DeleteReceiptFilter func (c *SES) DeleteReceiptFilter(input *DeleteReceiptFilterInput) (*DeleteReceiptFilterOutput, error) { req, out := c.DeleteReceiptFilterRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteReceiptFilterWithContext is the same as DeleteReceiptFilter with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteReceiptFilter 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 *SES) DeleteReceiptFilterWithContext(ctx aws.Context, input *DeleteReceiptFilterInput, opts ...request.Option) (*DeleteReceiptFilterOutput, error) { + req, out := c.DeleteReceiptFilterRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteReceiptRule = "DeleteReceiptRule" @@ -916,8 +1081,23 @@ func (c *SES) DeleteReceiptRuleRequest(input *DeleteReceiptRuleInput) (req *requ // Please also see https://docs.aws.amazon.com/goto/WebAPI/email-2010-12-01/DeleteReceiptRule func (c *SES) DeleteReceiptRule(input *DeleteReceiptRuleInput) (*DeleteReceiptRuleOutput, error) { req, out := c.DeleteReceiptRuleRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteReceiptRuleWithContext is the same as DeleteReceiptRule with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteReceiptRule 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 *SES) DeleteReceiptRuleWithContext(ctx aws.Context, input *DeleteReceiptRuleInput, opts ...request.Option) (*DeleteReceiptRuleOutput, error) { + req, out := c.DeleteReceiptRuleRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteReceiptRuleSet = "DeleteReceiptRuleSet" @@ -988,8 +1168,23 @@ func (c *SES) DeleteReceiptRuleSetRequest(input *DeleteReceiptRuleSetInput) (req // Please also see https://docs.aws.amazon.com/goto/WebAPI/email-2010-12-01/DeleteReceiptRuleSet func (c *SES) DeleteReceiptRuleSet(input *DeleteReceiptRuleSetInput) (*DeleteReceiptRuleSetOutput, error) { req, out := c.DeleteReceiptRuleSetRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteReceiptRuleSetWithContext is the same as DeleteReceiptRuleSet with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteReceiptRuleSet 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 *SES) DeleteReceiptRuleSetWithContext(ctx aws.Context, input *DeleteReceiptRuleSetInput, opts ...request.Option) (*DeleteReceiptRuleSetOutput, error) { + req, out := c.DeleteReceiptRuleSetRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteVerifiedEmailAddress = "DeleteVerifiedEmailAddress" @@ -1055,8 +1250,23 @@ func (c *SES) DeleteVerifiedEmailAddressRequest(input *DeleteVerifiedEmailAddres // Please also see https://docs.aws.amazon.com/goto/WebAPI/email-2010-12-01/DeleteVerifiedEmailAddress func (c *SES) DeleteVerifiedEmailAddress(input *DeleteVerifiedEmailAddressInput) (*DeleteVerifiedEmailAddressOutput, error) { req, out := c.DeleteVerifiedEmailAddressRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteVerifiedEmailAddressWithContext is the same as DeleteVerifiedEmailAddress with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteVerifiedEmailAddress 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 *SES) DeleteVerifiedEmailAddressWithContext(ctx aws.Context, input *DeleteVerifiedEmailAddressInput, opts ...request.Option) (*DeleteVerifiedEmailAddressOutput, error) { + req, out := c.DeleteVerifiedEmailAddressRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeActiveReceiptRuleSet = "DescribeActiveReceiptRuleSet" @@ -1121,8 +1331,23 @@ func (c *SES) DescribeActiveReceiptRuleSetRequest(input *DescribeActiveReceiptRu // Please also see https://docs.aws.amazon.com/goto/WebAPI/email-2010-12-01/DescribeActiveReceiptRuleSet func (c *SES) DescribeActiveReceiptRuleSet(input *DescribeActiveReceiptRuleSetInput) (*DescribeActiveReceiptRuleSetOutput, error) { req, out := c.DescribeActiveReceiptRuleSetRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeActiveReceiptRuleSetWithContext is the same as DescribeActiveReceiptRuleSet with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeActiveReceiptRuleSet 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 *SES) DescribeActiveReceiptRuleSetWithContext(ctx aws.Context, input *DescribeActiveReceiptRuleSetInput, opts ...request.Option) (*DescribeActiveReceiptRuleSetOutput, error) { + req, out := c.DescribeActiveReceiptRuleSetRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeConfigurationSet = "DescribeConfigurationSet" @@ -1191,8 +1416,23 @@ func (c *SES) DescribeConfigurationSetRequest(input *DescribeConfigurationSetInp // Please also see https://docs.aws.amazon.com/goto/WebAPI/email-2010-12-01/DescribeConfigurationSet func (c *SES) DescribeConfigurationSet(input *DescribeConfigurationSetInput) (*DescribeConfigurationSetOutput, error) { req, out := c.DescribeConfigurationSetRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeConfigurationSetWithContext is the same as DescribeConfigurationSet with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeConfigurationSet 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 *SES) DescribeConfigurationSetWithContext(ctx aws.Context, input *DescribeConfigurationSetInput, opts ...request.Option) (*DescribeConfigurationSetOutput, error) { + req, out := c.DescribeConfigurationSetRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeReceiptRule = "DescribeReceiptRule" @@ -1264,8 +1504,23 @@ func (c *SES) DescribeReceiptRuleRequest(input *DescribeReceiptRuleInput) (req * // Please also see https://docs.aws.amazon.com/goto/WebAPI/email-2010-12-01/DescribeReceiptRule func (c *SES) DescribeReceiptRule(input *DescribeReceiptRuleInput) (*DescribeReceiptRuleOutput, error) { req, out := c.DescribeReceiptRuleRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeReceiptRuleWithContext is the same as DescribeReceiptRule with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeReceiptRule 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 *SES) DescribeReceiptRuleWithContext(ctx aws.Context, input *DescribeReceiptRuleInput, opts ...request.Option) (*DescribeReceiptRuleOutput, error) { + req, out := c.DescribeReceiptRuleRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeReceiptRuleSet = "DescribeReceiptRuleSet" @@ -1334,8 +1589,23 @@ func (c *SES) DescribeReceiptRuleSetRequest(input *DescribeReceiptRuleSetInput) // Please also see https://docs.aws.amazon.com/goto/WebAPI/email-2010-12-01/DescribeReceiptRuleSet func (c *SES) DescribeReceiptRuleSet(input *DescribeReceiptRuleSetInput) (*DescribeReceiptRuleSetOutput, error) { req, out := c.DescribeReceiptRuleSetRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeReceiptRuleSetWithContext is the same as DescribeReceiptRuleSet with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeReceiptRuleSet 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 *SES) DescribeReceiptRuleSetWithContext(ctx aws.Context, input *DescribeReceiptRuleSetInput, opts ...request.Option) (*DescribeReceiptRuleSetOutput, error) { + req, out := c.DescribeReceiptRuleSetRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetIdentityDkimAttributes = "GetIdentityDkimAttributes" @@ -1415,8 +1685,23 @@ func (c *SES) GetIdentityDkimAttributesRequest(input *GetIdentityDkimAttributesI // Please also see https://docs.aws.amazon.com/goto/WebAPI/email-2010-12-01/GetIdentityDkimAttributes func (c *SES) GetIdentityDkimAttributes(input *GetIdentityDkimAttributesInput) (*GetIdentityDkimAttributesOutput, error) { req, out := c.GetIdentityDkimAttributesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetIdentityDkimAttributesWithContext is the same as GetIdentityDkimAttributes with the addition of +// the ability to pass a context and additional request options. +// +// See GetIdentityDkimAttributes 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 *SES) GetIdentityDkimAttributesWithContext(ctx aws.Context, input *GetIdentityDkimAttributesInput, opts ...request.Option) (*GetIdentityDkimAttributesOutput, error) { + req, out := c.GetIdentityDkimAttributesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetIdentityMailFromDomainAttributes = "GetIdentityMailFromDomainAttributes" @@ -1479,8 +1764,23 @@ func (c *SES) GetIdentityMailFromDomainAttributesRequest(input *GetIdentityMailF // Please also see https://docs.aws.amazon.com/goto/WebAPI/email-2010-12-01/GetIdentityMailFromDomainAttributes func (c *SES) GetIdentityMailFromDomainAttributes(input *GetIdentityMailFromDomainAttributesInput) (*GetIdentityMailFromDomainAttributesOutput, error) { req, out := c.GetIdentityMailFromDomainAttributesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetIdentityMailFromDomainAttributesWithContext is the same as GetIdentityMailFromDomainAttributes with the addition of +// the ability to pass a context and additional request options. +// +// See GetIdentityMailFromDomainAttributes 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 *SES) GetIdentityMailFromDomainAttributesWithContext(ctx aws.Context, input *GetIdentityMailFromDomainAttributesInput, opts ...request.Option) (*GetIdentityMailFromDomainAttributesOutput, error) { + req, out := c.GetIdentityMailFromDomainAttributesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetIdentityNotificationAttributes = "GetIdentityNotificationAttributes" @@ -1546,8 +1846,23 @@ func (c *SES) GetIdentityNotificationAttributesRequest(input *GetIdentityNotific // Please also see https://docs.aws.amazon.com/goto/WebAPI/email-2010-12-01/GetIdentityNotificationAttributes func (c *SES) GetIdentityNotificationAttributes(input *GetIdentityNotificationAttributesInput) (*GetIdentityNotificationAttributesOutput, error) { req, out := c.GetIdentityNotificationAttributesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetIdentityNotificationAttributesWithContext is the same as GetIdentityNotificationAttributes with the addition of +// the ability to pass a context and additional request options. +// +// See GetIdentityNotificationAttributes 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 *SES) GetIdentityNotificationAttributesWithContext(ctx aws.Context, input *GetIdentityNotificationAttributesInput, opts ...request.Option) (*GetIdentityNotificationAttributesOutput, error) { + req, out := c.GetIdentityNotificationAttributesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetIdentityPolicies = "GetIdentityPolicies" @@ -1618,8 +1933,23 @@ func (c *SES) GetIdentityPoliciesRequest(input *GetIdentityPoliciesInput) (req * // Please also see https://docs.aws.amazon.com/goto/WebAPI/email-2010-12-01/GetIdentityPolicies func (c *SES) GetIdentityPolicies(input *GetIdentityPoliciesInput) (*GetIdentityPoliciesOutput, error) { req, out := c.GetIdentityPoliciesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetIdentityPoliciesWithContext is the same as GetIdentityPolicies with the addition of +// the ability to pass a context and additional request options. +// +// See GetIdentityPolicies 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 *SES) GetIdentityPoliciesWithContext(ctx aws.Context, input *GetIdentityPoliciesInput, opts ...request.Option) (*GetIdentityPoliciesOutput, error) { + req, out := c.GetIdentityPoliciesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetIdentityVerificationAttributes = "GetIdentityVerificationAttributes" @@ -1683,8 +2013,23 @@ func (c *SES) GetIdentityVerificationAttributesRequest(input *GetIdentityVerific // Please also see https://docs.aws.amazon.com/goto/WebAPI/email-2010-12-01/GetIdentityVerificationAttributes func (c *SES) GetIdentityVerificationAttributes(input *GetIdentityVerificationAttributesInput) (*GetIdentityVerificationAttributesOutput, error) { req, out := c.GetIdentityVerificationAttributesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetIdentityVerificationAttributesWithContext is the same as GetIdentityVerificationAttributes with the addition of +// the ability to pass a context and additional request options. +// +// See GetIdentityVerificationAttributes 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 *SES) GetIdentityVerificationAttributesWithContext(ctx aws.Context, input *GetIdentityVerificationAttributesInput, opts ...request.Option) (*GetIdentityVerificationAttributesOutput, error) { + req, out := c.GetIdentityVerificationAttributesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetSendQuota = "GetSendQuota" @@ -1745,8 +2090,23 @@ func (c *SES) GetSendQuotaRequest(input *GetSendQuotaInput) (req *request.Reques // Please also see https://docs.aws.amazon.com/goto/WebAPI/email-2010-12-01/GetSendQuota func (c *SES) GetSendQuota(input *GetSendQuotaInput) (*GetSendQuotaOutput, error) { req, out := c.GetSendQuotaRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetSendQuotaWithContext is the same as GetSendQuota with the addition of +// the ability to pass a context and additional request options. +// +// See GetSendQuota 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 *SES) GetSendQuotaWithContext(ctx aws.Context, input *GetSendQuotaInput, opts ...request.Option) (*GetSendQuotaOutput, error) { + req, out := c.GetSendQuotaRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetSendStatistics = "GetSendStatistics" @@ -1810,8 +2170,23 @@ func (c *SES) GetSendStatisticsRequest(input *GetSendStatisticsInput) (req *requ // Please also see https://docs.aws.amazon.com/goto/WebAPI/email-2010-12-01/GetSendStatistics func (c *SES) GetSendStatistics(input *GetSendStatisticsInput) (*GetSendStatisticsOutput, error) { req, out := c.GetSendStatisticsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetSendStatisticsWithContext is the same as GetSendStatistics with the addition of +// the ability to pass a context and additional request options. +// +// See GetSendStatistics 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 *SES) GetSendStatisticsWithContext(ctx aws.Context, input *GetSendStatisticsInput, opts ...request.Option) (*GetSendStatisticsOutput, error) { + req, out := c.GetSendStatisticsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opListConfigurationSets = "ListConfigurationSets" @@ -1876,8 +2251,23 @@ func (c *SES) ListConfigurationSetsRequest(input *ListConfigurationSetsInput) (r // Please also see https://docs.aws.amazon.com/goto/WebAPI/email-2010-12-01/ListConfigurationSets func (c *SES) ListConfigurationSets(input *ListConfigurationSetsInput) (*ListConfigurationSetsOutput, error) { req, out := c.ListConfigurationSetsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListConfigurationSetsWithContext is the same as ListConfigurationSets with the addition of +// the ability to pass a context and additional request options. +// +// See ListConfigurationSets 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 *SES) ListConfigurationSetsWithContext(ctx aws.Context, input *ListConfigurationSetsInput, opts ...request.Option) (*ListConfigurationSetsOutput, error) { + req, out := c.ListConfigurationSetsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opListIdentities = "ListIdentities" @@ -1945,8 +2335,23 @@ func (c *SES) ListIdentitiesRequest(input *ListIdentitiesInput) (req *request.Re // Please also see https://docs.aws.amazon.com/goto/WebAPI/email-2010-12-01/ListIdentities func (c *SES) ListIdentities(input *ListIdentitiesInput) (*ListIdentitiesOutput, error) { req, out := c.ListIdentitiesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListIdentitiesWithContext is the same as ListIdentities with the addition of +// the ability to pass a context and additional request options. +// +// See ListIdentities 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 *SES) ListIdentitiesWithContext(ctx aws.Context, input *ListIdentitiesInput, opts ...request.Option) (*ListIdentitiesOutput, error) { + req, out := c.ListIdentitiesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // ListIdentitiesPages iterates over the pages of a ListIdentities operation, @@ -1966,12 +2371,37 @@ func (c *SES) ListIdentities(input *ListIdentitiesInput) (*ListIdentitiesOutput, // return pageNum <= 3 // }) // -func (c *SES) ListIdentitiesPages(input *ListIdentitiesInput, fn func(p *ListIdentitiesOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.ListIdentitiesRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*ListIdentitiesOutput), lastPage) - }) +func (c *SES) ListIdentitiesPages(input *ListIdentitiesInput, fn func(*ListIdentitiesOutput, bool) bool) error { + return c.ListIdentitiesPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListIdentitiesPagesWithContext same as ListIdentitiesPages 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 *SES) ListIdentitiesPagesWithContext(ctx aws.Context, input *ListIdentitiesInput, fn func(*ListIdentitiesOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListIdentitiesInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListIdentitiesRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*ListIdentitiesOutput), !p.HasNextPage()) + } + return p.Err() } const opListIdentityPolicies = "ListIdentityPolicies" @@ -2041,8 +2471,23 @@ func (c *SES) ListIdentityPoliciesRequest(input *ListIdentityPoliciesInput) (req // Please also see https://docs.aws.amazon.com/goto/WebAPI/email-2010-12-01/ListIdentityPolicies func (c *SES) ListIdentityPolicies(input *ListIdentityPoliciesInput) (*ListIdentityPoliciesOutput, error) { req, out := c.ListIdentityPoliciesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListIdentityPoliciesWithContext is the same as ListIdentityPolicies with the addition of +// the ability to pass a context and additional request options. +// +// See ListIdentityPolicies 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 *SES) ListIdentityPoliciesWithContext(ctx aws.Context, input *ListIdentityPoliciesInput, opts ...request.Option) (*ListIdentityPoliciesOutput, error) { + req, out := c.ListIdentityPoliciesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opListReceiptFilters = "ListReceiptFilters" @@ -2106,8 +2551,23 @@ func (c *SES) ListReceiptFiltersRequest(input *ListReceiptFiltersInput) (req *re // Please also see https://docs.aws.amazon.com/goto/WebAPI/email-2010-12-01/ListReceiptFilters func (c *SES) ListReceiptFilters(input *ListReceiptFiltersInput) (*ListReceiptFiltersOutput, error) { req, out := c.ListReceiptFiltersRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListReceiptFiltersWithContext is the same as ListReceiptFilters with the addition of +// the ability to pass a context and additional request options. +// +// See ListReceiptFilters 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 *SES) ListReceiptFiltersWithContext(ctx aws.Context, input *ListReceiptFiltersInput, opts ...request.Option) (*ListReceiptFiltersOutput, error) { + req, out := c.ListReceiptFiltersRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opListReceiptRuleSets = "ListReceiptRuleSets" @@ -2174,8 +2634,23 @@ func (c *SES) ListReceiptRuleSetsRequest(input *ListReceiptRuleSetsInput) (req * // Please also see https://docs.aws.amazon.com/goto/WebAPI/email-2010-12-01/ListReceiptRuleSets func (c *SES) ListReceiptRuleSets(input *ListReceiptRuleSetsInput) (*ListReceiptRuleSetsOutput, error) { req, out := c.ListReceiptRuleSetsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListReceiptRuleSetsWithContext is the same as ListReceiptRuleSets with the addition of +// the ability to pass a context and additional request options. +// +// See ListReceiptRuleSets 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 *SES) ListReceiptRuleSetsWithContext(ctx aws.Context, input *ListReceiptRuleSetsInput, opts ...request.Option) (*ListReceiptRuleSetsOutput, error) { + req, out := c.ListReceiptRuleSetsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opListVerifiedEmailAddresses = "ListVerifiedEmailAddresses" @@ -2239,8 +2714,23 @@ func (c *SES) ListVerifiedEmailAddressesRequest(input *ListVerifiedEmailAddresse // Please also see https://docs.aws.amazon.com/goto/WebAPI/email-2010-12-01/ListVerifiedEmailAddresses func (c *SES) ListVerifiedEmailAddresses(input *ListVerifiedEmailAddressesInput) (*ListVerifiedEmailAddressesOutput, error) { req, out := c.ListVerifiedEmailAddressesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListVerifiedEmailAddressesWithContext is the same as ListVerifiedEmailAddresses with the addition of +// the ability to pass a context and additional request options. +// +// See ListVerifiedEmailAddresses 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 *SES) ListVerifiedEmailAddressesWithContext(ctx aws.Context, input *ListVerifiedEmailAddressesInput, opts ...request.Option) (*ListVerifiedEmailAddressesOutput, error) { + req, out := c.ListVerifiedEmailAddressesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opPutIdentityPolicy = "PutIdentityPolicy" @@ -2315,8 +2805,23 @@ func (c *SES) PutIdentityPolicyRequest(input *PutIdentityPolicyInput) (req *requ // Please also see https://docs.aws.amazon.com/goto/WebAPI/email-2010-12-01/PutIdentityPolicy func (c *SES) PutIdentityPolicy(input *PutIdentityPolicyInput) (*PutIdentityPolicyOutput, error) { req, out := c.PutIdentityPolicyRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// PutIdentityPolicyWithContext is the same as PutIdentityPolicy with the addition of +// the ability to pass a context and additional request options. +// +// See PutIdentityPolicy 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 *SES) PutIdentityPolicyWithContext(ctx aws.Context, input *PutIdentityPolicyInput, opts ...request.Option) (*PutIdentityPolicyOutput, error) { + req, out := c.PutIdentityPolicyRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opReorderReceiptRuleSet = "ReorderReceiptRuleSet" @@ -2392,8 +2897,23 @@ func (c *SES) ReorderReceiptRuleSetRequest(input *ReorderReceiptRuleSetInput) (r // Please also see https://docs.aws.amazon.com/goto/WebAPI/email-2010-12-01/ReorderReceiptRuleSet func (c *SES) ReorderReceiptRuleSet(input *ReorderReceiptRuleSetInput) (*ReorderReceiptRuleSetOutput, error) { req, out := c.ReorderReceiptRuleSetRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ReorderReceiptRuleSetWithContext is the same as ReorderReceiptRuleSet with the addition of +// the ability to pass a context and additional request options. +// +// See ReorderReceiptRuleSet 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 *SES) ReorderReceiptRuleSetWithContext(ctx aws.Context, input *ReorderReceiptRuleSetInput, opts ...request.Option) (*ReorderReceiptRuleSetOutput, error) { + req, out := c.ReorderReceiptRuleSetRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opSendBounce = "SendBounce" @@ -2468,8 +2988,23 @@ func (c *SES) SendBounceRequest(input *SendBounceInput) (req *request.Request, o // Please also see https://docs.aws.amazon.com/goto/WebAPI/email-2010-12-01/SendBounce func (c *SES) SendBounce(input *SendBounceInput) (*SendBounceOutput, error) { req, out := c.SendBounceRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// SendBounceWithContext is the same as SendBounce with the addition of +// the ability to pass a context and additional request options. +// +// See SendBounce 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 *SES) SendBounceWithContext(ctx aws.Context, input *SendBounceInput, opts ...request.Option) (*SendBounceOutput, error) { + req, out := c.SendBounceRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opSendEmail = "SendEmail" @@ -2567,8 +3102,23 @@ func (c *SES) SendEmailRequest(input *SendEmailInput) (req *request.Request, out // Please also see https://docs.aws.amazon.com/goto/WebAPI/email-2010-12-01/SendEmail func (c *SES) SendEmail(input *SendEmailInput) (*SendEmailOutput, error) { req, out := c.SendEmailRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// SendEmailWithContext is the same as SendEmail with the addition of +// the ability to pass a context and additional request options. +// +// See SendEmail 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 *SES) SendEmailWithContext(ctx aws.Context, input *SendEmailInput, opts ...request.Option) (*SendEmailOutput, error) { + req, out := c.SendEmailRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opSendRawEmail = "SendRawEmail" @@ -2698,8 +3248,23 @@ func (c *SES) SendRawEmailRequest(input *SendRawEmailInput) (req *request.Reques // Please also see https://docs.aws.amazon.com/goto/WebAPI/email-2010-12-01/SendRawEmail func (c *SES) SendRawEmail(input *SendRawEmailInput) (*SendRawEmailOutput, error) { req, out := c.SendRawEmailRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// SendRawEmailWithContext is the same as SendRawEmail with the addition of +// the ability to pass a context and additional request options. +// +// See SendRawEmail 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 *SES) SendRawEmailWithContext(ctx aws.Context, input *SendRawEmailInput, opts ...request.Option) (*SendRawEmailOutput, error) { + req, out := c.SendRawEmailRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opSetActiveReceiptRuleSet = "SetActiveReceiptRuleSet" @@ -2771,8 +3336,23 @@ func (c *SES) SetActiveReceiptRuleSetRequest(input *SetActiveReceiptRuleSetInput // Please also see https://docs.aws.amazon.com/goto/WebAPI/email-2010-12-01/SetActiveReceiptRuleSet func (c *SES) SetActiveReceiptRuleSet(input *SetActiveReceiptRuleSetInput) (*SetActiveReceiptRuleSetOutput, error) { req, out := c.SetActiveReceiptRuleSetRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// SetActiveReceiptRuleSetWithContext is the same as SetActiveReceiptRuleSet with the addition of +// the ability to pass a context and additional request options. +// +// See SetActiveReceiptRuleSet 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 *SES) SetActiveReceiptRuleSetWithContext(ctx aws.Context, input *SetActiveReceiptRuleSetInput, opts ...request.Option) (*SetActiveReceiptRuleSetOutput, error) { + req, out := c.SetActiveReceiptRuleSetRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opSetIdentityDkimEnabled = "SetIdentityDkimEnabled" @@ -2847,8 +3427,23 @@ func (c *SES) SetIdentityDkimEnabledRequest(input *SetIdentityDkimEnabledInput) // Please also see https://docs.aws.amazon.com/goto/WebAPI/email-2010-12-01/SetIdentityDkimEnabled func (c *SES) SetIdentityDkimEnabled(input *SetIdentityDkimEnabledInput) (*SetIdentityDkimEnabledOutput, error) { req, out := c.SetIdentityDkimEnabledRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// SetIdentityDkimEnabledWithContext is the same as SetIdentityDkimEnabled with the addition of +// the ability to pass a context and additional request options. +// +// See SetIdentityDkimEnabled 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 *SES) SetIdentityDkimEnabledWithContext(ctx aws.Context, input *SetIdentityDkimEnabledInput, opts ...request.Option) (*SetIdentityDkimEnabledOutput, error) { + req, out := c.SetIdentityDkimEnabledRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opSetIdentityFeedbackForwardingEnabled = "SetIdentityFeedbackForwardingEnabled" @@ -2918,8 +3513,23 @@ func (c *SES) SetIdentityFeedbackForwardingEnabledRequest(input *SetIdentityFeed // Please also see https://docs.aws.amazon.com/goto/WebAPI/email-2010-12-01/SetIdentityFeedbackForwardingEnabled func (c *SES) SetIdentityFeedbackForwardingEnabled(input *SetIdentityFeedbackForwardingEnabledInput) (*SetIdentityFeedbackForwardingEnabledOutput, error) { req, out := c.SetIdentityFeedbackForwardingEnabledRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// SetIdentityFeedbackForwardingEnabledWithContext is the same as SetIdentityFeedbackForwardingEnabled with the addition of +// the ability to pass a context and additional request options. +// +// See SetIdentityFeedbackForwardingEnabled 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 *SES) SetIdentityFeedbackForwardingEnabledWithContext(ctx aws.Context, input *SetIdentityFeedbackForwardingEnabledInput, opts ...request.Option) (*SetIdentityFeedbackForwardingEnabledOutput, error) { + req, out := c.SetIdentityFeedbackForwardingEnabledRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opSetIdentityHeadersInNotificationsEnabled = "SetIdentityHeadersInNotificationsEnabled" @@ -2985,8 +3595,23 @@ func (c *SES) SetIdentityHeadersInNotificationsEnabledRequest(input *SetIdentity // Please also see https://docs.aws.amazon.com/goto/WebAPI/email-2010-12-01/SetIdentityHeadersInNotificationsEnabled func (c *SES) SetIdentityHeadersInNotificationsEnabled(input *SetIdentityHeadersInNotificationsEnabledInput) (*SetIdentityHeadersInNotificationsEnabledOutput, error) { req, out := c.SetIdentityHeadersInNotificationsEnabledRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// SetIdentityHeadersInNotificationsEnabledWithContext is the same as SetIdentityHeadersInNotificationsEnabled with the addition of +// the ability to pass a context and additional request options. +// +// See SetIdentityHeadersInNotificationsEnabled 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 *SES) SetIdentityHeadersInNotificationsEnabledWithContext(ctx aws.Context, input *SetIdentityHeadersInNotificationsEnabledInput, opts ...request.Option) (*SetIdentityHeadersInNotificationsEnabledOutput, error) { + req, out := c.SetIdentityHeadersInNotificationsEnabledRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opSetIdentityMailFromDomain = "SetIdentityMailFromDomain" @@ -3053,8 +3678,23 @@ func (c *SES) SetIdentityMailFromDomainRequest(input *SetIdentityMailFromDomainI // Please also see https://docs.aws.amazon.com/goto/WebAPI/email-2010-12-01/SetIdentityMailFromDomain func (c *SES) SetIdentityMailFromDomain(input *SetIdentityMailFromDomainInput) (*SetIdentityMailFromDomainOutput, error) { req, out := c.SetIdentityMailFromDomainRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// SetIdentityMailFromDomainWithContext is the same as SetIdentityMailFromDomain with the addition of +// the ability to pass a context and additional request options. +// +// See SetIdentityMailFromDomain 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 *SES) SetIdentityMailFromDomainWithContext(ctx aws.Context, input *SetIdentityMailFromDomainInput, opts ...request.Option) (*SetIdentityMailFromDomainOutput, error) { + req, out := c.SetIdentityMailFromDomainRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opSetIdentityNotificationTopic = "SetIdentityNotificationTopic" @@ -3124,8 +3764,23 @@ func (c *SES) SetIdentityNotificationTopicRequest(input *SetIdentityNotification // Please also see https://docs.aws.amazon.com/goto/WebAPI/email-2010-12-01/SetIdentityNotificationTopic func (c *SES) SetIdentityNotificationTopic(input *SetIdentityNotificationTopicInput) (*SetIdentityNotificationTopicOutput, error) { req, out := c.SetIdentityNotificationTopicRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// SetIdentityNotificationTopicWithContext is the same as SetIdentityNotificationTopic with the addition of +// the ability to pass a context and additional request options. +// +// See SetIdentityNotificationTopic 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 *SES) SetIdentityNotificationTopicWithContext(ctx aws.Context, input *SetIdentityNotificationTopicInput, opts ...request.Option) (*SetIdentityNotificationTopicOutput, error) { + req, out := c.SetIdentityNotificationTopicRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opSetReceiptRulePosition = "SetReceiptRulePosition" @@ -3197,8 +3852,23 @@ func (c *SES) SetReceiptRulePositionRequest(input *SetReceiptRulePositionInput) // Please also see https://docs.aws.amazon.com/goto/WebAPI/email-2010-12-01/SetReceiptRulePosition func (c *SES) SetReceiptRulePosition(input *SetReceiptRulePositionInput) (*SetReceiptRulePositionOutput, error) { req, out := c.SetReceiptRulePositionRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// SetReceiptRulePositionWithContext is the same as SetReceiptRulePosition with the addition of +// the ability to pass a context and additional request options. +// +// See SetReceiptRulePosition 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 *SES) SetReceiptRulePositionWithContext(ctx aws.Context, input *SetReceiptRulePositionInput, opts ...request.Option) (*SetReceiptRulePositionOutput, error) { + req, out := c.SetReceiptRulePositionRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opUpdateConfigurationSetEventDestination = "UpdateConfigurationSetEventDestination" @@ -3284,8 +3954,23 @@ func (c *SES) UpdateConfigurationSetEventDestinationRequest(input *UpdateConfigu // Please also see https://docs.aws.amazon.com/goto/WebAPI/email-2010-12-01/UpdateConfigurationSetEventDestination func (c *SES) UpdateConfigurationSetEventDestination(input *UpdateConfigurationSetEventDestinationInput) (*UpdateConfigurationSetEventDestinationOutput, error) { req, out := c.UpdateConfigurationSetEventDestinationRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// UpdateConfigurationSetEventDestinationWithContext is the same as UpdateConfigurationSetEventDestination with the addition of +// the ability to pass a context and additional request options. +// +// See UpdateConfigurationSetEventDestination 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 *SES) UpdateConfigurationSetEventDestinationWithContext(ctx aws.Context, input *UpdateConfigurationSetEventDestinationInput, opts ...request.Option) (*UpdateConfigurationSetEventDestinationOutput, error) { + req, out := c.UpdateConfigurationSetEventDestinationRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opUpdateReceiptRule = "UpdateReceiptRule" @@ -3378,8 +4063,23 @@ func (c *SES) UpdateReceiptRuleRequest(input *UpdateReceiptRuleInput) (req *requ // Please also see https://docs.aws.amazon.com/goto/WebAPI/email-2010-12-01/UpdateReceiptRule func (c *SES) UpdateReceiptRule(input *UpdateReceiptRuleInput) (*UpdateReceiptRuleOutput, error) { req, out := c.UpdateReceiptRuleRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// UpdateReceiptRuleWithContext is the same as UpdateReceiptRule with the addition of +// the ability to pass a context and additional request options. +// +// See UpdateReceiptRule 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 *SES) UpdateReceiptRuleWithContext(ctx aws.Context, input *UpdateReceiptRuleInput, opts ...request.Option) (*UpdateReceiptRuleOutput, error) { + req, out := c.UpdateReceiptRuleRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opVerifyDomainDkim = "VerifyDomainDkim" @@ -3452,8 +4152,23 @@ func (c *SES) VerifyDomainDkimRequest(input *VerifyDomainDkimInput) (req *reques // Please also see https://docs.aws.amazon.com/goto/WebAPI/email-2010-12-01/VerifyDomainDkim func (c *SES) VerifyDomainDkim(input *VerifyDomainDkimInput) (*VerifyDomainDkimOutput, error) { req, out := c.VerifyDomainDkimRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// VerifyDomainDkimWithContext is the same as VerifyDomainDkim with the addition of +// the ability to pass a context and additional request options. +// +// See VerifyDomainDkim 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 *SES) VerifyDomainDkimWithContext(ctx aws.Context, input *VerifyDomainDkimInput, opts ...request.Option) (*VerifyDomainDkimOutput, error) { + req, out := c.VerifyDomainDkimRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opVerifyDomainIdentity = "VerifyDomainIdentity" @@ -3514,8 +4229,23 @@ func (c *SES) VerifyDomainIdentityRequest(input *VerifyDomainIdentityInput) (req // Please also see https://docs.aws.amazon.com/goto/WebAPI/email-2010-12-01/VerifyDomainIdentity func (c *SES) VerifyDomainIdentity(input *VerifyDomainIdentityInput) (*VerifyDomainIdentityOutput, error) { req, out := c.VerifyDomainIdentityRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// VerifyDomainIdentityWithContext is the same as VerifyDomainIdentity with the addition of +// the ability to pass a context and additional request options. +// +// See VerifyDomainIdentity 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 *SES) VerifyDomainIdentityWithContext(ctx aws.Context, input *VerifyDomainIdentityInput, opts ...request.Option) (*VerifyDomainIdentityOutput, error) { + req, out := c.VerifyDomainIdentityRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opVerifyEmailAddress = "VerifyEmailAddress" @@ -3582,8 +4312,23 @@ func (c *SES) VerifyEmailAddressRequest(input *VerifyEmailAddressInput) (req *re // Please also see https://docs.aws.amazon.com/goto/WebAPI/email-2010-12-01/VerifyEmailAddress func (c *SES) VerifyEmailAddress(input *VerifyEmailAddressInput) (*VerifyEmailAddressOutput, error) { req, out := c.VerifyEmailAddressRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// VerifyEmailAddressWithContext is the same as VerifyEmailAddress with the addition of +// the ability to pass a context and additional request options. +// +// See VerifyEmailAddress 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 *SES) VerifyEmailAddressWithContext(ctx aws.Context, input *VerifyEmailAddressInput, opts ...request.Option) (*VerifyEmailAddressOutput, error) { + req, out := c.VerifyEmailAddressRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opVerifyEmailIdentity = "VerifyEmailIdentity" @@ -3645,8 +4390,23 @@ func (c *SES) VerifyEmailIdentityRequest(input *VerifyEmailIdentityInput) (req * // Please also see https://docs.aws.amazon.com/goto/WebAPI/email-2010-12-01/VerifyEmailIdentity func (c *SES) VerifyEmailIdentity(input *VerifyEmailIdentityInput) (*VerifyEmailIdentityOutput, error) { req, out := c.VerifyEmailIdentityRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// VerifyEmailIdentityWithContext is the same as VerifyEmailIdentity with the addition of +// the ability to pass a context and additional request options. +// +// See VerifyEmailIdentity 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 *SES) VerifyEmailIdentityWithContext(ctx aws.Context, input *VerifyEmailIdentityInput, opts ...request.Option) (*VerifyEmailIdentityOutput, error) { + req, out := c.VerifyEmailIdentityRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // When included in a receipt rule, this action adds a header to the received diff --git a/vendor/github.com/aws/aws-sdk-go/service/ses/doc.go b/vendor/github.com/aws/aws-sdk-go/service/ses/doc.go new file mode 100644 index 000000000..21c30ecba --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/service/ses/doc.go @@ -0,0 +1,86 @@ +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. + +// Package ses provides the client and types for making API +// requests to Amazon Simple Email Service. +// +// This is the API Reference for Amazon Simple Email Service (Amazon SES). This +// documentation is intended to be used in conjunction with the Amazon SES Developer +// Guide (http://docs.aws.amazon.com/ses/latest/DeveloperGuide/Welcome.html). +// +// For a list of Amazon SES endpoints to use in service requests, see Regions +// and Amazon SES (http://docs.aws.amazon.com/ses/latest/DeveloperGuide/regions.html) +// in the Amazon SES Developer Guide. +// +// See https://docs.aws.amazon.com/goto/WebAPI/email-2010-12-01 for more information on this service. +// +// See ses package documentation for more information. +// https://docs.aws.amazon.com/sdk-for-go/api/service/ses/ +// +// Using the Client +// +// To use the client for Amazon Simple Email Service you will first need +// to create a new instance of it. +// +// When creating a client for an AWS service you'll first need to have a Session +// already created. The Session provides configuration that can be shared +// between multiple service clients. Additional configuration can be applied to +// the Session and service's client when they are constructed. The aws package's +// Config type contains several fields such as Region for the AWS Region the +// client should make API requests too. The optional Config value can be provided +// as the variadic argument for Sessions and client creation. +// +// Once the service's client is created you can use it to make API requests the +// AWS service. These clients are safe to use concurrently. +// +// // Create a session to share configuration, and load external configuration. +// sess := session.Must(session.NewSession()) +// +// // Create the service's client with the session. +// svc := ses.New(sess) +// +// See the SDK's documentation for more information on how to use service clients. +// https://docs.aws.amazon.com/sdk-for-go/api/ +// +// See aws package's Config type for more information on configuration options. +// https://docs.aws.amazon.com/sdk-for-go/api/aws/#Config +// +// See the Amazon Simple Email Service client SES for more +// information on creating the service's client. +// https://docs.aws.amazon.com/sdk-for-go/api/service/ses/#New +// +// Once the client is created you can make an API request to the service. +// Each API method takes a input parameter, and returns the service response +// and an error. +// +// The API method will document which error codes the service can be returned +// by the operation if the service models the API operation's errors. These +// errors will also be available as const strings prefixed with "ErrCode". +// +// result, err := svc.CloneReceiptRuleSet(params) +// if err != nil { +// // Cast err to awserr.Error to handle specific error codes. +// aerr, ok := err.(awserr.Error) +// if ok && aerr.Code() == { +// // Specific error code handling +// } +// return err +// } +// +// fmt.Println("CloneReceiptRuleSet result:") +// fmt.Println(result) +// +// Using the Client with Context +// +// The service's client also provides methods to make API requests with a Context +// value. This allows you to control the timeout, and cancellation of pending +// requests. These methods also take request Option as variadic parameter to apply +// additional configuration to the API request. +// +// ctx := context.Background() +// +// result, err := svc.CloneReceiptRuleSetWithContext(ctx, params) +// +// See the request package documentation for more information on using Context pattern +// with the SDK. +// https://docs.aws.amazon.com/sdk-for-go/api/aws/request/ +package ses diff --git a/vendor/github.com/aws/aws-sdk-go/service/ses/errors.go b/vendor/github.com/aws/aws-sdk-go/service/ses/errors.go index 704f87e6a..ef5f15819 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/ses/errors.go +++ b/vendor/github.com/aws/aws-sdk-go/service/ses/errors.go @@ -1,4 +1,4 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. package ses diff --git a/vendor/github.com/aws/aws-sdk-go/service/ses/service.go b/vendor/github.com/aws/aws-sdk-go/service/ses/service.go index 187c1d6af..b07889307 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/ses/service.go +++ b/vendor/github.com/aws/aws-sdk-go/service/ses/service.go @@ -1,4 +1,4 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. package ses @@ -11,16 +11,12 @@ import ( "github.com/aws/aws-sdk-go/private/protocol/query" ) -// This is the API Reference for Amazon Simple Email Service (Amazon SES). This -// documentation is intended to be used in conjunction with the Amazon SES Developer -// Guide (http://docs.aws.amazon.com/ses/latest/DeveloperGuide/Welcome.html). +// SES provides the API operation methods for making requests to +// Amazon Simple Email Service. See this package's package overview docs +// for details on the service. // -// For a list of Amazon SES endpoints to use in service requests, see Regions -// and Amazon SES (http://docs.aws.amazon.com/ses/latest/DeveloperGuide/regions.html) -// in the Amazon SES Developer Guide. -// The service client's operations are safe to be used concurrently. -// It is not safe to mutate any of the client's properties though. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/email-2010-12-01 +// SES methods are safe to use concurrently. It is not safe to +// modify mutate any of the struct's properties though. type SES struct { *client.Client } diff --git a/vendor/github.com/aws/aws-sdk-go/service/ses/waiters.go b/vendor/github.com/aws/aws-sdk-go/service/ses/waiters.go index bf79344b8..6597b6b77 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/ses/waiters.go +++ b/vendor/github.com/aws/aws-sdk-go/service/ses/waiters.go @@ -1,9 +1,12 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. package ses import ( - "github.com/aws/aws-sdk-go/private/waiter" + "time" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/request" ) // WaitUntilIdentityExists uses the Amazon SES API operation @@ -11,24 +14,43 @@ import ( // If the condition is not meet within the max attempt window an error will // be returned. func (c *SES) WaitUntilIdentityExists(input *GetIdentityVerificationAttributesInput) error { - waiterCfg := waiter.Config{ - Operation: "GetIdentityVerificationAttributes", - Delay: 3, + return c.WaitUntilIdentityExistsWithContext(aws.BackgroundContext(), input) +} + +// WaitUntilIdentityExistsWithContext is an extended version of WaitUntilIdentityExists. +// 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 *SES) WaitUntilIdentityExistsWithContext(ctx aws.Context, input *GetIdentityVerificationAttributesInput, opts ...request.WaiterOption) error { + w := request.Waiter{ + Name: "WaitUntilIdentityExists", MaxAttempts: 20, - Acceptors: []waiter.WaitAcceptor{ + Delay: request.ConstantWaiterDelay(3 * time.Second), + Acceptors: []request.WaiterAcceptor{ { - State: "success", - Matcher: "pathAll", - Argument: "VerificationAttributes.*.VerificationStatus", + State: request.SuccessWaiterState, + Matcher: request.PathAllWaiterMatch, Argument: "VerificationAttributes.*.VerificationStatus", Expected: "Success", }, }, + Logger: c.Config.Logger, + NewRequest: func(opts []request.Option) (*request.Request, error) { + var inCpy *GetIdentityVerificationAttributesInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.GetIdentityVerificationAttributesRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, } + w.ApplyOptions(opts...) - w := waiter.Waiter{ - Client: c, - Input: input, - Config: waiterCfg, - } - return w.Wait() + return w.WaitWithContext(ctx) } diff --git a/vendor/github.com/aws/aws-sdk-go/service/sfn/api.go b/vendor/github.com/aws/aws-sdk-go/service/sfn/api.go index c6b207e1c..57f442379 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/sfn/api.go +++ b/vendor/github.com/aws/aws-sdk-go/service/sfn/api.go @@ -1,11 +1,11 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. -// Package sfn provides a client for AWS Step Functions. package sfn import ( "time" + "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awsutil" "github.com/aws/aws-sdk-go/aws/request" ) @@ -75,8 +75,23 @@ func (c *SFN) CreateActivityRequest(input *CreateActivityInput) (req *request.Re // Please also see https://docs.aws.amazon.com/goto/WebAPI/states-2016-11-23/CreateActivity func (c *SFN) CreateActivity(input *CreateActivityInput) (*CreateActivityOutput, error) { req, out := c.CreateActivityRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateActivityWithContext is the same as CreateActivity with the addition of +// the ability to pass a context and additional request options. +// +// See CreateActivity 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 *SFN) CreateActivityWithContext(ctx aws.Context, input *CreateActivityInput, opts ...request.Option) (*CreateActivityOutput, error) { + req, out := c.CreateActivityRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateStateMachine = "CreateStateMachine" @@ -157,8 +172,23 @@ func (c *SFN) CreateStateMachineRequest(input *CreateStateMachineInput) (req *re // Please also see https://docs.aws.amazon.com/goto/WebAPI/states-2016-11-23/CreateStateMachine func (c *SFN) CreateStateMachine(input *CreateStateMachineInput) (*CreateStateMachineOutput, error) { req, out := c.CreateStateMachineRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateStateMachineWithContext is the same as CreateStateMachine with the addition of +// the ability to pass a context and additional request options. +// +// See CreateStateMachine 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 *SFN) CreateStateMachineWithContext(ctx aws.Context, input *CreateStateMachineInput, opts ...request.Option) (*CreateStateMachineOutput, error) { + req, out := c.CreateStateMachineRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteActivity = "DeleteActivity" @@ -222,8 +252,23 @@ func (c *SFN) DeleteActivityRequest(input *DeleteActivityInput) (req *request.Re // Please also see https://docs.aws.amazon.com/goto/WebAPI/states-2016-11-23/DeleteActivity func (c *SFN) DeleteActivity(input *DeleteActivityInput) (*DeleteActivityOutput, error) { req, out := c.DeleteActivityRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteActivityWithContext is the same as DeleteActivity with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteActivity 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 *SFN) DeleteActivityWithContext(ctx aws.Context, input *DeleteActivityInput, opts ...request.Option) (*DeleteActivityOutput, error) { + req, out := c.DeleteActivityRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteStateMachine = "DeleteStateMachine" @@ -288,8 +333,23 @@ func (c *SFN) DeleteStateMachineRequest(input *DeleteStateMachineInput) (req *re // Please also see https://docs.aws.amazon.com/goto/WebAPI/states-2016-11-23/DeleteStateMachine func (c *SFN) DeleteStateMachine(input *DeleteStateMachineInput) (*DeleteStateMachineOutput, error) { req, out := c.DeleteStateMachineRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteStateMachineWithContext is the same as DeleteStateMachine with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteStateMachine 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 *SFN) DeleteStateMachineWithContext(ctx aws.Context, input *DeleteStateMachineInput, opts ...request.Option) (*DeleteStateMachineOutput, error) { + req, out := c.DeleteStateMachineRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeActivity = "DescribeActivity" @@ -356,8 +416,23 @@ func (c *SFN) DescribeActivityRequest(input *DescribeActivityInput) (req *reques // Please also see https://docs.aws.amazon.com/goto/WebAPI/states-2016-11-23/DescribeActivity func (c *SFN) DescribeActivity(input *DescribeActivityInput) (*DescribeActivityOutput, error) { req, out := c.DescribeActivityRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeActivityWithContext is the same as DescribeActivity with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeActivity 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 *SFN) DescribeActivityWithContext(ctx aws.Context, input *DescribeActivityInput, opts ...request.Option) (*DescribeActivityOutput, error) { + req, out := c.DescribeActivityRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeExecution = "DescribeExecution" @@ -424,8 +499,23 @@ func (c *SFN) DescribeExecutionRequest(input *DescribeExecutionInput) (req *requ // Please also see https://docs.aws.amazon.com/goto/WebAPI/states-2016-11-23/DescribeExecution func (c *SFN) DescribeExecution(input *DescribeExecutionInput) (*DescribeExecutionOutput, error) { req, out := c.DescribeExecutionRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeExecutionWithContext is the same as DescribeExecution with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeExecution 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 *SFN) DescribeExecutionWithContext(ctx aws.Context, input *DescribeExecutionInput, opts ...request.Option) (*DescribeExecutionOutput, error) { + req, out := c.DescribeExecutionRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeStateMachine = "DescribeStateMachine" @@ -492,8 +582,23 @@ func (c *SFN) DescribeStateMachineRequest(input *DescribeStateMachineInput) (req // Please also see https://docs.aws.amazon.com/goto/WebAPI/states-2016-11-23/DescribeStateMachine func (c *SFN) DescribeStateMachine(input *DescribeStateMachineInput) (*DescribeStateMachineOutput, error) { req, out := c.DescribeStateMachineRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeStateMachineWithContext is the same as DescribeStateMachine with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeStateMachine 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 *SFN) DescribeStateMachineWithContext(ctx aws.Context, input *DescribeStateMachineInput, opts ...request.Option) (*DescribeStateMachineOutput, error) { + req, out := c.DescribeStateMachineRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetActivityTask = "GetActivityTask" @@ -573,8 +678,23 @@ func (c *SFN) GetActivityTaskRequest(input *GetActivityTaskInput) (req *request. // Please also see https://docs.aws.amazon.com/goto/WebAPI/states-2016-11-23/GetActivityTask func (c *SFN) GetActivityTask(input *GetActivityTaskInput) (*GetActivityTaskOutput, error) { req, out := c.GetActivityTaskRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetActivityTaskWithContext is the same as GetActivityTask with the addition of +// the ability to pass a context and additional request options. +// +// See GetActivityTask 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 *SFN) GetActivityTaskWithContext(ctx aws.Context, input *GetActivityTaskInput, opts ...request.Option) (*GetActivityTaskOutput, error) { + req, out := c.GetActivityTaskRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetExecutionHistory = "GetExecutionHistory" @@ -654,8 +774,23 @@ func (c *SFN) GetExecutionHistoryRequest(input *GetExecutionHistoryInput) (req * // Please also see https://docs.aws.amazon.com/goto/WebAPI/states-2016-11-23/GetExecutionHistory func (c *SFN) GetExecutionHistory(input *GetExecutionHistoryInput) (*GetExecutionHistoryOutput, error) { req, out := c.GetExecutionHistoryRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetExecutionHistoryWithContext is the same as GetExecutionHistory with the addition of +// the ability to pass a context and additional request options. +// +// See GetExecutionHistory 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 *SFN) GetExecutionHistoryWithContext(ctx aws.Context, input *GetExecutionHistoryInput, opts ...request.Option) (*GetExecutionHistoryOutput, error) { + req, out := c.GetExecutionHistoryRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // GetExecutionHistoryPages iterates over the pages of a GetExecutionHistory operation, @@ -675,12 +810,37 @@ func (c *SFN) GetExecutionHistory(input *GetExecutionHistoryInput) (*GetExecutio // return pageNum <= 3 // }) // -func (c *SFN) GetExecutionHistoryPages(input *GetExecutionHistoryInput, fn func(p *GetExecutionHistoryOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.GetExecutionHistoryRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*GetExecutionHistoryOutput), lastPage) - }) +func (c *SFN) GetExecutionHistoryPages(input *GetExecutionHistoryInput, fn func(*GetExecutionHistoryOutput, bool) bool) error { + return c.GetExecutionHistoryPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// GetExecutionHistoryPagesWithContext same as GetExecutionHistoryPages 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 *SFN) GetExecutionHistoryPagesWithContext(ctx aws.Context, input *GetExecutionHistoryInput, fn func(*GetExecutionHistoryOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *GetExecutionHistoryInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.GetExecutionHistoryRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*GetExecutionHistoryOutput), !p.HasNextPage()) + } + return p.Err() } const opListActivities = "ListActivities" @@ -752,8 +912,23 @@ func (c *SFN) ListActivitiesRequest(input *ListActivitiesInput) (req *request.Re // Please also see https://docs.aws.amazon.com/goto/WebAPI/states-2016-11-23/ListActivities func (c *SFN) ListActivities(input *ListActivitiesInput) (*ListActivitiesOutput, error) { req, out := c.ListActivitiesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListActivitiesWithContext is the same as ListActivities with the addition of +// the ability to pass a context and additional request options. +// +// See ListActivities 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 *SFN) ListActivitiesWithContext(ctx aws.Context, input *ListActivitiesInput, opts ...request.Option) (*ListActivitiesOutput, error) { + req, out := c.ListActivitiesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // ListActivitiesPages iterates over the pages of a ListActivities operation, @@ -773,12 +948,37 @@ func (c *SFN) ListActivities(input *ListActivitiesInput) (*ListActivitiesOutput, // return pageNum <= 3 // }) // -func (c *SFN) ListActivitiesPages(input *ListActivitiesInput, fn func(p *ListActivitiesOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.ListActivitiesRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*ListActivitiesOutput), lastPage) - }) +func (c *SFN) ListActivitiesPages(input *ListActivitiesInput, fn func(*ListActivitiesOutput, bool) bool) error { + return c.ListActivitiesPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListActivitiesPagesWithContext same as ListActivitiesPages 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 *SFN) ListActivitiesPagesWithContext(ctx aws.Context, input *ListActivitiesInput, fn func(*ListActivitiesOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListActivitiesInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListActivitiesRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*ListActivitiesOutput), !p.HasNextPage()) + } + return p.Err() } const opListExecutions = "ListExecutions" @@ -856,8 +1056,23 @@ func (c *SFN) ListExecutionsRequest(input *ListExecutionsInput) (req *request.Re // Please also see https://docs.aws.amazon.com/goto/WebAPI/states-2016-11-23/ListExecutions func (c *SFN) ListExecutions(input *ListExecutionsInput) (*ListExecutionsOutput, error) { req, out := c.ListExecutionsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListExecutionsWithContext is the same as ListExecutions with the addition of +// the ability to pass a context and additional request options. +// +// See ListExecutions 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 *SFN) ListExecutionsWithContext(ctx aws.Context, input *ListExecutionsInput, opts ...request.Option) (*ListExecutionsOutput, error) { + req, out := c.ListExecutionsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // ListExecutionsPages iterates over the pages of a ListExecutions operation, @@ -877,12 +1092,37 @@ func (c *SFN) ListExecutions(input *ListExecutionsInput) (*ListExecutionsOutput, // return pageNum <= 3 // }) // -func (c *SFN) ListExecutionsPages(input *ListExecutionsInput, fn func(p *ListExecutionsOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.ListExecutionsRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*ListExecutionsOutput), lastPage) - }) +func (c *SFN) ListExecutionsPages(input *ListExecutionsInput, fn func(*ListExecutionsOutput, bool) bool) error { + return c.ListExecutionsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListExecutionsPagesWithContext same as ListExecutionsPages 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 *SFN) ListExecutionsPagesWithContext(ctx aws.Context, input *ListExecutionsInput, fn func(*ListExecutionsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListExecutionsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListExecutionsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*ListExecutionsOutput), !p.HasNextPage()) + } + return p.Err() } const opListStateMachines = "ListStateMachines" @@ -954,8 +1194,23 @@ func (c *SFN) ListStateMachinesRequest(input *ListStateMachinesInput) (req *requ // Please also see https://docs.aws.amazon.com/goto/WebAPI/states-2016-11-23/ListStateMachines func (c *SFN) ListStateMachines(input *ListStateMachinesInput) (*ListStateMachinesOutput, error) { req, out := c.ListStateMachinesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListStateMachinesWithContext is the same as ListStateMachines with the addition of +// the ability to pass a context and additional request options. +// +// See ListStateMachines 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 *SFN) ListStateMachinesWithContext(ctx aws.Context, input *ListStateMachinesInput, opts ...request.Option) (*ListStateMachinesOutput, error) { + req, out := c.ListStateMachinesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // ListStateMachinesPages iterates over the pages of a ListStateMachines operation, @@ -975,12 +1230,37 @@ func (c *SFN) ListStateMachines(input *ListStateMachinesInput) (*ListStateMachin // return pageNum <= 3 // }) // -func (c *SFN) ListStateMachinesPages(input *ListStateMachinesInput, fn func(p *ListStateMachinesOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.ListStateMachinesRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*ListStateMachinesOutput), lastPage) - }) +func (c *SFN) ListStateMachinesPages(input *ListStateMachinesInput, fn func(*ListStateMachinesOutput, bool) bool) error { + return c.ListStateMachinesPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListStateMachinesPagesWithContext same as ListStateMachinesPages 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 *SFN) ListStateMachinesPagesWithContext(ctx aws.Context, input *ListStateMachinesInput, fn func(*ListStateMachinesOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListStateMachinesInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListStateMachinesRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*ListStateMachinesOutput), !p.HasNextPage()) + } + return p.Err() } const opSendTaskFailure = "SendTaskFailure" @@ -1048,8 +1328,23 @@ func (c *SFN) SendTaskFailureRequest(input *SendTaskFailureInput) (req *request. // Please also see https://docs.aws.amazon.com/goto/WebAPI/states-2016-11-23/SendTaskFailure func (c *SFN) SendTaskFailure(input *SendTaskFailureInput) (*SendTaskFailureOutput, error) { req, out := c.SendTaskFailureRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// SendTaskFailureWithContext is the same as SendTaskFailure with the addition of +// the ability to pass a context and additional request options. +// +// See SendTaskFailure 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 *SFN) SendTaskFailureWithContext(ctx aws.Context, input *SendTaskFailureInput, opts ...request.Option) (*SendTaskFailureOutput, error) { + req, out := c.SendTaskFailureRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opSendTaskHeartbeat = "SendTaskHeartbeat" @@ -1129,8 +1424,23 @@ func (c *SFN) SendTaskHeartbeatRequest(input *SendTaskHeartbeatInput) (req *requ // Please also see https://docs.aws.amazon.com/goto/WebAPI/states-2016-11-23/SendTaskHeartbeat func (c *SFN) SendTaskHeartbeat(input *SendTaskHeartbeatInput) (*SendTaskHeartbeatOutput, error) { req, out := c.SendTaskHeartbeatRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// SendTaskHeartbeatWithContext is the same as SendTaskHeartbeat with the addition of +// the ability to pass a context and additional request options. +// +// See SendTaskHeartbeat 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 *SFN) SendTaskHeartbeatWithContext(ctx aws.Context, input *SendTaskHeartbeatInput, opts ...request.Option) (*SendTaskHeartbeatOutput, error) { + req, out := c.SendTaskHeartbeatRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opSendTaskSuccess = "SendTaskSuccess" @@ -1202,8 +1512,23 @@ func (c *SFN) SendTaskSuccessRequest(input *SendTaskSuccessInput) (req *request. // Please also see https://docs.aws.amazon.com/goto/WebAPI/states-2016-11-23/SendTaskSuccess func (c *SFN) SendTaskSuccess(input *SendTaskSuccessInput) (*SendTaskSuccessOutput, error) { req, out := c.SendTaskSuccessRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// SendTaskSuccessWithContext is the same as SendTaskSuccess with the addition of +// the ability to pass a context and additional request options. +// +// See SendTaskSuccess 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 *SFN) SendTaskSuccessWithContext(ctx aws.Context, input *SendTaskSuccessInput, opts ...request.Option) (*SendTaskSuccessOutput, error) { + req, out := c.SendTaskSuccessRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opStartExecution = "StartExecution" @@ -1286,8 +1611,23 @@ func (c *SFN) StartExecutionRequest(input *StartExecutionInput) (req *request.Re // Please also see https://docs.aws.amazon.com/goto/WebAPI/states-2016-11-23/StartExecution func (c *SFN) StartExecution(input *StartExecutionInput) (*StartExecutionOutput, error) { req, out := c.StartExecutionRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// StartExecutionWithContext is the same as StartExecution with the addition of +// the ability to pass a context and additional request options. +// +// See StartExecution 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 *SFN) StartExecutionWithContext(ctx aws.Context, input *StartExecutionInput, opts ...request.Option) (*StartExecutionOutput, error) { + req, out := c.StartExecutionRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opStopExecution = "StopExecution" @@ -1354,8 +1694,23 @@ func (c *SFN) StopExecutionRequest(input *StopExecutionInput) (req *request.Requ // Please also see https://docs.aws.amazon.com/goto/WebAPI/states-2016-11-23/StopExecution func (c *SFN) StopExecution(input *StopExecutionInput) (*StopExecutionOutput, error) { req, out := c.StopExecutionRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// StopExecutionWithContext is the same as StopExecution with the addition of +// the ability to pass a context and additional request options. +// +// See StopExecution 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 *SFN) StopExecutionWithContext(ctx aws.Context, input *StopExecutionInput, opts ...request.Option) (*StopExecutionOutput, error) { + req, out := c.StopExecutionRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // Please also see https://docs.aws.amazon.com/goto/WebAPI/states-2016-11-23/ActivityFailedEventDetails diff --git a/vendor/github.com/aws/aws-sdk-go/service/sfn/doc.go b/vendor/github.com/aws/aws-sdk-go/service/sfn/doc.go new file mode 100644 index 000000000..09e2ce50c --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/service/sfn/doc.go @@ -0,0 +1,95 @@ +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. + +// Package sfn provides the client and types for making API +// requests to AWS Step Functions. +// +// AWS Step Functions is a web service that enables you to coordinate the components +// of distributed applications and microservices using visual workflows. You +// build applications from individual components that each perform a discrete +// function, or task, allowing you to scale and change applications quickly. +// Step Functions provides a graphical console to visualize the components of +// your application as a series of steps. It automatically triggers and tracks +// each step, and retries when there are errors, so your application executes +// in order and as expected, every time. Step Functions logs the state of each +// step, so when things do go wrong, you can diagnose and debug problems quickly. +// +// Step Functions manages the operations and underlying infrastructure for you +// to ensure your application is available at any scale. You can run tasks on +// the AWS cloud, on your own servers, or an any system that has access to AWS. +// Step Functions can be accessed and used with the Step Functions console, +// the AWS SDKs (included with your Beta release invitation email), or an HTTP +// API (the subject of this document). +// +// See https://docs.aws.amazon.com/goto/WebAPI/states-2016-11-23 for more information on this service. +// +// See sfn package documentation for more information. +// https://docs.aws.amazon.com/sdk-for-go/api/service/sfn/ +// +// Using the Client +// +// To use the client for AWS Step Functions you will first need +// to create a new instance of it. +// +// When creating a client for an AWS service you'll first need to have a Session +// already created. The Session provides configuration that can be shared +// between multiple service clients. Additional configuration can be applied to +// the Session and service's client when they are constructed. The aws package's +// Config type contains several fields such as Region for the AWS Region the +// client should make API requests too. The optional Config value can be provided +// as the variadic argument for Sessions and client creation. +// +// Once the service's client is created you can use it to make API requests the +// AWS service. These clients are safe to use concurrently. +// +// // Create a session to share configuration, and load external configuration. +// sess := session.Must(session.NewSession()) +// +// // Create the service's client with the session. +// svc := sfn.New(sess) +// +// See the SDK's documentation for more information on how to use service clients. +// https://docs.aws.amazon.com/sdk-for-go/api/ +// +// See aws package's Config type for more information on configuration options. +// https://docs.aws.amazon.com/sdk-for-go/api/aws/#Config +// +// See the AWS Step Functions client SFN for more +// information on creating the service's client. +// https://docs.aws.amazon.com/sdk-for-go/api/service/sfn/#New +// +// Once the client is created you can make an API request to the service. +// Each API method takes a input parameter, and returns the service response +// and an error. +// +// The API method will document which error codes the service can be returned +// by the operation if the service models the API operation's errors. These +// errors will also be available as const strings prefixed with "ErrCode". +// +// result, err := svc.CreateActivity(params) +// if err != nil { +// // Cast err to awserr.Error to handle specific error codes. +// aerr, ok := err.(awserr.Error) +// if ok && aerr.Code() == { +// // Specific error code handling +// } +// return err +// } +// +// fmt.Println("CreateActivity result:") +// fmt.Println(result) +// +// Using the Client with Context +// +// The service's client also provides methods to make API requests with a Context +// value. This allows you to control the timeout, and cancellation of pending +// requests. These methods also take request Option as variadic parameter to apply +// additional configuration to the API request. +// +// ctx := context.Background() +// +// result, err := svc.CreateActivityWithContext(ctx, params) +// +// See the request package documentation for more information on using Context pattern +// with the SDK. +// https://docs.aws.amazon.com/sdk-for-go/api/aws/request/ +package sfn diff --git a/vendor/github.com/aws/aws-sdk-go/service/sfn/errors.go b/vendor/github.com/aws/aws-sdk-go/service/sfn/errors.go index 2a438eb66..ee02f364d 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/sfn/errors.go +++ b/vendor/github.com/aws/aws-sdk-go/service/sfn/errors.go @@ -1,4 +1,4 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. package sfn diff --git a/vendor/github.com/aws/aws-sdk-go/service/sfn/service.go b/vendor/github.com/aws/aws-sdk-go/service/sfn/service.go index 77bf817e7..f9d12a58f 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/sfn/service.go +++ b/vendor/github.com/aws/aws-sdk-go/service/sfn/service.go @@ -1,4 +1,4 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. package sfn @@ -11,25 +11,12 @@ import ( "github.com/aws/aws-sdk-go/private/protocol/jsonrpc" ) -// AWS Step Functions is a web service that enables you to coordinate the components -// of distributed applications and microservices using visual workflows. You -// build applications from individual components that each perform a discrete -// function, or task, allowing you to scale and change applications quickly. -// Step Functions provides a graphical console to visualize the components of -// your application as a series of steps. It automatically triggers and tracks -// each step, and retries when there are errors, so your application executes -// in order and as expected, every time. Step Functions logs the state of each -// step, so when things do go wrong, you can diagnose and debug problems quickly. +// SFN provides the API operation methods for making requests to +// AWS Step Functions. See this package's package overview docs +// for details on the service. // -// Step Functions manages the operations and underlying infrastructure for you -// to ensure your application is available at any scale. You can run tasks on -// the AWS cloud, on your own servers, or an any system that has access to AWS. -// Step Functions can be accessed and used with the Step Functions console, -// the AWS SDKs (included with your Beta release invitation email), or an HTTP -// API (the subject of this document). -// The service client's operations are safe to be used concurrently. -// It is not safe to mutate any of the client's properties though. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/states-2016-11-23 +// SFN methods are safe to use concurrently. It is not safe to +// modify mutate any of the struct's properties though. type SFN struct { *client.Client } diff --git a/vendor/github.com/aws/aws-sdk-go/service/simpledb/api.go b/vendor/github.com/aws/aws-sdk-go/service/simpledb/api.go index 9308ec37c..9bc84823c 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/simpledb/api.go +++ b/vendor/github.com/aws/aws-sdk-go/service/simpledb/api.go @@ -1,11 +1,11 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. -// Package simpledb provides a client for Amazon SimpleDB. package simpledb import ( "fmt" + "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awsutil" "github.com/aws/aws-sdk-go/aws/request" "github.com/aws/aws-sdk-go/private/protocol" @@ -37,8 +37,6 @@ const opBatchDeleteAttributes = "BatchDeleteAttributes" // if err == nil { // resp is now filled // fmt.Println(resp) // } -// -// Please also see https://docs.aws.amazon.com/goto/WebAPI//BatchDeleteAttributes func (c *SimpleDB) BatchDeleteAttributesRequest(input *BatchDeleteAttributesInput) (req *request.Request, output *BatchDeleteAttributesOutput) { op := &request.Operation{ Name: opBatchDeleteAttributes, @@ -90,11 +88,25 @@ func (c *SimpleDB) BatchDeleteAttributesRequest(input *BatchDeleteAttributesInpu // // See the AWS API reference guide for Amazon SimpleDB's // API operation BatchDeleteAttributes for usage and error information. -// Please also see https://docs.aws.amazon.com/goto/WebAPI//BatchDeleteAttributes func (c *SimpleDB) BatchDeleteAttributes(input *BatchDeleteAttributesInput) (*BatchDeleteAttributesOutput, error) { req, out := c.BatchDeleteAttributesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// BatchDeleteAttributesWithContext is the same as BatchDeleteAttributes with the addition of +// the ability to pass a context and additional request options. +// +// See BatchDeleteAttributes 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 *SimpleDB) BatchDeleteAttributesWithContext(ctx aws.Context, input *BatchDeleteAttributesInput, opts ...request.Option) (*BatchDeleteAttributesOutput, error) { + req, out := c.BatchDeleteAttributesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opBatchPutAttributes = "BatchPutAttributes" @@ -122,8 +134,6 @@ const opBatchPutAttributes = "BatchPutAttributes" // if err == nil { // resp is now filled // fmt.Println(resp) // } -// -// Please also see https://docs.aws.amazon.com/goto/WebAPI//BatchPutAttributes func (c *SimpleDB) BatchPutAttributesRequest(input *BatchPutAttributesInput) (req *request.Request, output *BatchPutAttributesOutput) { op := &request.Operation{ Name: opBatchPutAttributes, @@ -223,11 +233,25 @@ func (c *SimpleDB) BatchPutAttributesRequest(input *BatchPutAttributesInput) (re // * ErrCodeNumberSubmittedAttributesExceeded "NumberSubmittedAttributesExceeded" // Too many attributes exist in a single call. // -// Please also see https://docs.aws.amazon.com/goto/WebAPI//BatchPutAttributes func (c *SimpleDB) BatchPutAttributes(input *BatchPutAttributesInput) (*BatchPutAttributesOutput, error) { req, out := c.BatchPutAttributesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// BatchPutAttributesWithContext is the same as BatchPutAttributes with the addition of +// the ability to pass a context and additional request options. +// +// See BatchPutAttributes 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 *SimpleDB) BatchPutAttributesWithContext(ctx aws.Context, input *BatchPutAttributesInput, opts ...request.Option) (*BatchPutAttributesOutput, error) { + req, out := c.BatchPutAttributesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateDomain = "CreateDomain" @@ -255,8 +279,6 @@ const opCreateDomain = "CreateDomain" // if err == nil { // resp is now filled // fmt.Println(resp) // } -// -// Please also see https://docs.aws.amazon.com/goto/WebAPI//CreateDomain func (c *SimpleDB) CreateDomainRequest(input *CreateDomainInput) (req *request.Request, output *CreateDomainOutput) { op := &request.Operation{ Name: opCreateDomain, @@ -304,11 +326,25 @@ func (c *SimpleDB) CreateDomainRequest(input *CreateDomainInput) (req *request.R // * ErrCodeNumberDomainsExceeded "NumberDomainsExceeded" // Too many domains exist per this account. // -// Please also see https://docs.aws.amazon.com/goto/WebAPI//CreateDomain func (c *SimpleDB) CreateDomain(input *CreateDomainInput) (*CreateDomainOutput, error) { req, out := c.CreateDomainRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateDomainWithContext is the same as CreateDomain with the addition of +// the ability to pass a context and additional request options. +// +// See CreateDomain 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 *SimpleDB) CreateDomainWithContext(ctx aws.Context, input *CreateDomainInput, opts ...request.Option) (*CreateDomainOutput, error) { + req, out := c.CreateDomainRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteAttributes = "DeleteAttributes" @@ -336,8 +372,6 @@ const opDeleteAttributes = "DeleteAttributes" // if err == nil { // resp is now filled // fmt.Println(resp) // } -// -// Please also see https://docs.aws.amazon.com/goto/WebAPI//DeleteAttributes func (c *SimpleDB) DeleteAttributesRequest(input *DeleteAttributesInput) (req *request.Request, output *DeleteAttributesOutput) { op := &request.Operation{ Name: opDeleteAttributes, @@ -390,11 +424,25 @@ func (c *SimpleDB) DeleteAttributesRequest(input *DeleteAttributesInput) (req *r // * ErrCodeAttributeDoesNotExist "AttributeDoesNotExist" // The specified attribute does not exist. // -// Please also see https://docs.aws.amazon.com/goto/WebAPI//DeleteAttributes func (c *SimpleDB) DeleteAttributes(input *DeleteAttributesInput) (*DeleteAttributesOutput, error) { req, out := c.DeleteAttributesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteAttributesWithContext is the same as DeleteAttributes with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteAttributes 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 *SimpleDB) DeleteAttributesWithContext(ctx aws.Context, input *DeleteAttributesInput, opts ...request.Option) (*DeleteAttributesOutput, error) { + req, out := c.DeleteAttributesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteDomain = "DeleteDomain" @@ -422,8 +470,6 @@ const opDeleteDomain = "DeleteDomain" // if err == nil { // resp is now filled // fmt.Println(resp) // } -// -// Please also see https://docs.aws.amazon.com/goto/WebAPI//DeleteDomain func (c *SimpleDB) DeleteDomainRequest(input *DeleteDomainInput) (req *request.Request, output *DeleteDomainOutput) { op := &request.Operation{ Name: opDeleteDomain, @@ -462,11 +508,25 @@ func (c *SimpleDB) DeleteDomainRequest(input *DeleteDomainInput) (req *request.R // * ErrCodeMissingParameter "MissingParameter" // The request must contain the specified missing parameter. // -// Please also see https://docs.aws.amazon.com/goto/WebAPI//DeleteDomain func (c *SimpleDB) DeleteDomain(input *DeleteDomainInput) (*DeleteDomainOutput, error) { req, out := c.DeleteDomainRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteDomainWithContext is the same as DeleteDomain with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteDomain 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 *SimpleDB) DeleteDomainWithContext(ctx aws.Context, input *DeleteDomainInput, opts ...request.Option) (*DeleteDomainOutput, error) { + req, out := c.DeleteDomainRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDomainMetadata = "DomainMetadata" @@ -494,8 +554,6 @@ const opDomainMetadata = "DomainMetadata" // if err == nil { // resp is now filled // fmt.Println(resp) // } -// -// Please also see https://docs.aws.amazon.com/goto/WebAPI//DomainMetadata func (c *SimpleDB) DomainMetadataRequest(input *DomainMetadataInput) (req *request.Request, output *DomainMetadataOutput) { op := &request.Operation{ Name: opDomainMetadata, @@ -532,11 +590,25 @@ func (c *SimpleDB) DomainMetadataRequest(input *DomainMetadataInput) (req *reque // * ErrCodeNoSuchDomain "NoSuchDomain" // The specified domain does not exist. // -// Please also see https://docs.aws.amazon.com/goto/WebAPI//DomainMetadata func (c *SimpleDB) DomainMetadata(input *DomainMetadataInput) (*DomainMetadataOutput, error) { req, out := c.DomainMetadataRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DomainMetadataWithContext is the same as DomainMetadata with the addition of +// the ability to pass a context and additional request options. +// +// See DomainMetadata 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 *SimpleDB) DomainMetadataWithContext(ctx aws.Context, input *DomainMetadataInput, opts ...request.Option) (*DomainMetadataOutput, error) { + req, out := c.DomainMetadataRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetAttributes = "GetAttributes" @@ -564,8 +636,6 @@ const opGetAttributes = "GetAttributes" // if err == nil { // resp is now filled // fmt.Println(resp) // } -// -// Please also see https://docs.aws.amazon.com/goto/WebAPI//GetAttributes func (c *SimpleDB) GetAttributesRequest(input *GetAttributesInput) (req *request.Request, output *GetAttributesOutput) { op := &request.Operation{ Name: opGetAttributes, @@ -612,11 +682,25 @@ func (c *SimpleDB) GetAttributesRequest(input *GetAttributesInput) (req *request // * ErrCodeNoSuchDomain "NoSuchDomain" // The specified domain does not exist. // -// Please also see https://docs.aws.amazon.com/goto/WebAPI//GetAttributes func (c *SimpleDB) GetAttributes(input *GetAttributesInput) (*GetAttributesOutput, error) { req, out := c.GetAttributesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetAttributesWithContext is the same as GetAttributes with the addition of +// the ability to pass a context and additional request options. +// +// See GetAttributes 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 *SimpleDB) GetAttributesWithContext(ctx aws.Context, input *GetAttributesInput, opts ...request.Option) (*GetAttributesOutput, error) { + req, out := c.GetAttributesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opListDomains = "ListDomains" @@ -644,8 +728,6 @@ const opListDomains = "ListDomains" // if err == nil { // resp is now filled // fmt.Println(resp) // } -// -// Please also see https://docs.aws.amazon.com/goto/WebAPI//ListDomains func (c *SimpleDB) ListDomainsRequest(input *ListDomainsInput) (req *request.Request, output *ListDomainsOutput) { op := &request.Operation{ Name: opListDomains, @@ -691,11 +773,25 @@ func (c *SimpleDB) ListDomainsRequest(input *ListDomainsInput) (req *request.Req // * ErrCodeInvalidNextToken "InvalidNextToken" // The specified NextToken is not valid. // -// Please also see https://docs.aws.amazon.com/goto/WebAPI//ListDomains func (c *SimpleDB) ListDomains(input *ListDomainsInput) (*ListDomainsOutput, error) { req, out := c.ListDomainsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListDomainsWithContext is the same as ListDomains with the addition of +// the ability to pass a context and additional request options. +// +// See ListDomains 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 *SimpleDB) ListDomainsWithContext(ctx aws.Context, input *ListDomainsInput, opts ...request.Option) (*ListDomainsOutput, error) { + req, out := c.ListDomainsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // ListDomainsPages iterates over the pages of a ListDomains operation, @@ -715,12 +811,37 @@ func (c *SimpleDB) ListDomains(input *ListDomainsInput) (*ListDomainsOutput, err // return pageNum <= 3 // }) // -func (c *SimpleDB) ListDomainsPages(input *ListDomainsInput, fn func(p *ListDomainsOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.ListDomainsRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*ListDomainsOutput), lastPage) - }) +func (c *SimpleDB) ListDomainsPages(input *ListDomainsInput, fn func(*ListDomainsOutput, bool) bool) error { + return c.ListDomainsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListDomainsPagesWithContext same as ListDomainsPages 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 *SimpleDB) ListDomainsPagesWithContext(ctx aws.Context, input *ListDomainsInput, fn func(*ListDomainsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListDomainsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListDomainsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*ListDomainsOutput), !p.HasNextPage()) + } + return p.Err() } const opPutAttributes = "PutAttributes" @@ -748,8 +869,6 @@ const opPutAttributes = "PutAttributes" // if err == nil { // resp is now filled // fmt.Println(resp) // } -// -// Please also see https://docs.aws.amazon.com/goto/WebAPI//PutAttributes func (c *SimpleDB) PutAttributesRequest(input *PutAttributesInput) (req *request.Request, output *PutAttributesOutput) { op := &request.Operation{ Name: opPutAttributes, @@ -831,11 +950,25 @@ func (c *SimpleDB) PutAttributesRequest(input *PutAttributesInput) (req *request // * ErrCodeAttributeDoesNotExist "AttributeDoesNotExist" // The specified attribute does not exist. // -// Please also see https://docs.aws.amazon.com/goto/WebAPI//PutAttributes func (c *SimpleDB) PutAttributes(input *PutAttributesInput) (*PutAttributesOutput, error) { req, out := c.PutAttributesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// PutAttributesWithContext is the same as PutAttributes with the addition of +// the ability to pass a context and additional request options. +// +// See PutAttributes 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 *SimpleDB) PutAttributesWithContext(ctx aws.Context, input *PutAttributesInput, opts ...request.Option) (*PutAttributesOutput, error) { + req, out := c.PutAttributesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opSelect = "Select" @@ -863,8 +996,6 @@ const opSelect = "Select" // if err == nil { // resp is now filled // fmt.Println(resp) // } -// -// Please also see https://docs.aws.amazon.com/goto/WebAPI//Select func (c *SimpleDB) SelectRequest(input *SelectInput) (req *request.Request, output *SelectOutput) { op := &request.Operation{ Name: opSelect, @@ -937,11 +1068,25 @@ func (c *SimpleDB) SelectRequest(input *SelectInput) (req *request.Request, outp // * ErrCodeTooManyRequestedAttributes "TooManyRequestedAttributes" // Too many attributes requested. // -// Please also see https://docs.aws.amazon.com/goto/WebAPI//Select func (c *SimpleDB) Select(input *SelectInput) (*SelectOutput, error) { req, out := c.SelectRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// SelectWithContext is the same as Select with the addition of +// the ability to pass a context and additional request options. +// +// See Select 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 *SimpleDB) SelectWithContext(ctx aws.Context, input *SelectInput, opts ...request.Option) (*SelectOutput, error) { + req, out := c.SelectRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // SelectPages iterates over the pages of a Select operation, @@ -961,15 +1106,39 @@ func (c *SimpleDB) Select(input *SelectInput) (*SelectOutput, error) { // return pageNum <= 3 // }) // -func (c *SimpleDB) SelectPages(input *SelectInput, fn func(p *SelectOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.SelectRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*SelectOutput), lastPage) - }) +func (c *SimpleDB) SelectPages(input *SelectInput, fn func(*SelectOutput, bool) bool) error { + return c.SelectPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// SelectPagesWithContext same as SelectPages 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 *SimpleDB) SelectPagesWithContext(ctx aws.Context, input *SelectInput, fn func(*SelectOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *SelectInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.SelectRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*SelectOutput), !p.HasNextPage()) + } + return p.Err() } -// Please also see https://docs.aws.amazon.com/goto/WebAPI//Attribute type Attribute struct { _ struct{} `type:"structure"` @@ -1022,7 +1191,6 @@ func (s *Attribute) SetValue(v string) *Attribute { return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI//BatchDeleteAttributesRequest type BatchDeleteAttributesInput struct { _ struct{} `type:"structure"` @@ -1085,7 +1253,6 @@ func (s *BatchDeleteAttributesInput) SetItems(v []*DeletableItem) *BatchDeleteAt return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI//BatchDeleteAttributesOutput type BatchDeleteAttributesOutput struct { _ struct{} `type:"structure"` } @@ -1100,7 +1267,6 @@ func (s BatchDeleteAttributesOutput) GoString() string { return s.String() } -// Please also see https://docs.aws.amazon.com/goto/WebAPI//BatchPutAttributesRequest type BatchPutAttributesInput struct { _ struct{} `type:"structure"` @@ -1163,7 +1329,6 @@ func (s *BatchPutAttributesInput) SetItems(v []*ReplaceableItem) *BatchPutAttrib return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI//BatchPutAttributesOutput type BatchPutAttributesOutput struct { _ struct{} `type:"structure"` } @@ -1178,7 +1343,6 @@ func (s BatchPutAttributesOutput) GoString() string { return s.String() } -// Please also see https://docs.aws.amazon.com/goto/WebAPI//CreateDomainRequest type CreateDomainInput struct { _ struct{} `type:"structure"` @@ -1218,7 +1382,6 @@ func (s *CreateDomainInput) SetDomainName(v string) *CreateDomainInput { return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI//CreateDomainOutput type CreateDomainOutput struct { _ struct{} `type:"structure"` } @@ -1233,7 +1396,6 @@ func (s CreateDomainOutput) GoString() string { return s.String() } -// Please also see https://docs.aws.amazon.com/goto/WebAPI//DeletableAttribute type DeletableAttribute struct { _ struct{} `type:"structure"` @@ -1281,7 +1443,6 @@ func (s *DeletableAttribute) SetValue(v string) *DeletableAttribute { return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI//DeletableItem type DeletableItem struct { _ struct{} `type:"structure"` @@ -1336,7 +1497,6 @@ func (s *DeletableItem) SetName(v string) *DeletableItem { return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI//DeleteAttributesRequest type DeleteAttributesInput struct { _ struct{} `type:"structure"` @@ -1421,7 +1581,6 @@ func (s *DeleteAttributesInput) SetItemName(v string) *DeleteAttributesInput { return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI//DeleteAttributesOutput type DeleteAttributesOutput struct { _ struct{} `type:"structure"` } @@ -1436,7 +1595,6 @@ func (s DeleteAttributesOutput) GoString() string { return s.String() } -// Please also see https://docs.aws.amazon.com/goto/WebAPI//DeleteDomainRequest type DeleteDomainInput struct { _ struct{} `type:"structure"` @@ -1475,7 +1633,6 @@ func (s *DeleteDomainInput) SetDomainName(v string) *DeleteDomainInput { return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI//DeleteDomainOutput type DeleteDomainOutput struct { _ struct{} `type:"structure"` } @@ -1490,7 +1647,6 @@ func (s DeleteDomainOutput) GoString() string { return s.String() } -// Please also see https://docs.aws.amazon.com/goto/WebAPI//DomainMetadataRequest type DomainMetadataInput struct { _ struct{} `type:"structure"` @@ -1529,7 +1685,6 @@ func (s *DomainMetadataInput) SetDomainName(v string) *DomainMetadataInput { return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI//DomainMetadataResult type DomainMetadataOutput struct { _ struct{} `type:"structure"` @@ -1607,7 +1762,6 @@ func (s *DomainMetadataOutput) SetTimestamp(v int64) *DomainMetadataOutput { return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI//GetAttributesRequest type GetAttributesInput struct { _ struct{} `type:"structure"` @@ -1679,7 +1833,6 @@ func (s *GetAttributesInput) SetItemName(v string) *GetAttributesInput { return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI//GetAttributesResult type GetAttributesOutput struct { _ struct{} `type:"structure"` @@ -1703,7 +1856,6 @@ func (s *GetAttributesOutput) SetAttributes(v []*Attribute) *GetAttributesOutput return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI//Item type Item struct { _ struct{} `type:"structure"` @@ -1748,7 +1900,6 @@ func (s *Item) SetName(v string) *Item { return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI//ListDomainsRequest type ListDomainsInput struct { _ struct{} `type:"structure"` @@ -1783,7 +1934,6 @@ func (s *ListDomainsInput) SetNextToken(v string) *ListDomainsInput { return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI//ListDomainsResult type ListDomainsOutput struct { _ struct{} `type:"structure"` @@ -1817,7 +1967,6 @@ func (s *ListDomainsOutput) SetNextToken(v string) *ListDomainsOutput { return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI//PutAttributesRequest type PutAttributesInput struct { _ struct{} `type:"structure"` @@ -1905,7 +2054,6 @@ func (s *PutAttributesInput) SetItemName(v string) *PutAttributesInput { return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI//PutAttributesOutput type PutAttributesOutput struct { _ struct{} `type:"structure"` } @@ -1920,7 +2068,6 @@ func (s PutAttributesOutput) GoString() string { return s.String() } -// Please also see https://docs.aws.amazon.com/goto/WebAPI//ReplaceableAttribute type ReplaceableAttribute struct { _ struct{} `type:"structure"` @@ -1983,7 +2130,6 @@ func (s *ReplaceableAttribute) SetValue(v string) *ReplaceableAttribute { return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI//ReplaceableItem type ReplaceableItem struct { _ struct{} `type:"structure"` @@ -2046,7 +2192,6 @@ func (s *ReplaceableItem) SetName(v string) *ReplaceableItem { return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI//SelectRequest type SelectInput struct { _ struct{} `type:"structure"` @@ -2104,7 +2249,6 @@ func (s *SelectInput) SetSelectExpression(v string) *SelectInput { return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI//SelectResult type SelectOutput struct { _ struct{} `type:"structure"` @@ -2141,7 +2285,6 @@ func (s *SelectOutput) SetNextToken(v string) *SelectOutput { // condition is specified for a request, the data will only be updated if the // condition is satisfied. For example, if an attribute with a specific name // and value exists, or if a specific attribute doesn't exist. -// Please also see https://docs.aws.amazon.com/goto/WebAPI//UpdateCondition type UpdateCondition struct { _ struct{} `type:"structure"` diff --git a/vendor/github.com/aws/aws-sdk-go/service/simpledb/doc.go b/vendor/github.com/aws/aws-sdk-go/service/simpledb/doc.go new file mode 100644 index 000000000..cb06efc4a --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/service/simpledb/doc.go @@ -0,0 +1,92 @@ +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. + +// Package simpledb provides the client and types for making API +// requests to Amazon SimpleDB. +// +// Amazon SimpleDB is a web service providing the core database functions of +// data indexing and querying in the cloud. By offloading the time and effort +// associated with building and operating a web-scale database, SimpleDB provides +// developers the freedom to focus on application development. A traditional, +// clustered relational database requires a sizable upfront capital outlay, +// is complex to design, and often requires extensive and repetitive database +// administration. Amazon SimpleDB is dramatically simpler, requiring no schema, +// automatically indexing your data and providing a simple API for storage and +// access. This approach eliminates the administrative burden of data modeling, +// index maintenance, and performance tuning. Developers gain access to this +// functionality within Amazon's proven computing environment, are able to scale +// instantly, and pay only for what they use. +// +// Visit http://aws.amazon.com/simpledb/ (http://aws.amazon.com/simpledb/) for +// more information. +// +// See simpledb package documentation for more information. +// https://docs.aws.amazon.com/sdk-for-go/api/service/simpledb/ +// +// Using the Client +// +// To use the client for Amazon SimpleDB you will first need +// to create a new instance of it. +// +// When creating a client for an AWS service you'll first need to have a Session +// already created. The Session provides configuration that can be shared +// between multiple service clients. Additional configuration can be applied to +// the Session and service's client when they are constructed. The aws package's +// Config type contains several fields such as Region for the AWS Region the +// client should make API requests too. The optional Config value can be provided +// as the variadic argument for Sessions and client creation. +// +// Once the service's client is created you can use it to make API requests the +// AWS service. These clients are safe to use concurrently. +// +// // Create a session to share configuration, and load external configuration. +// sess := session.Must(session.NewSession()) +// +// // Create the service's client with the session. +// svc := simpledb.New(sess) +// +// See the SDK's documentation for more information on how to use service clients. +// https://docs.aws.amazon.com/sdk-for-go/api/ +// +// See aws package's Config type for more information on configuration options. +// https://docs.aws.amazon.com/sdk-for-go/api/aws/#Config +// +// See the Amazon SimpleDB client SimpleDB for more +// information on creating the service's client. +// https://docs.aws.amazon.com/sdk-for-go/api/service/simpledb/#New +// +// Once the client is created you can make an API request to the service. +// Each API method takes a input parameter, and returns the service response +// and an error. +// +// The API method will document which error codes the service can be returned +// by the operation if the service models the API operation's errors. These +// errors will also be available as const strings prefixed with "ErrCode". +// +// result, err := svc.BatchDeleteAttributes(params) +// if err != nil { +// // Cast err to awserr.Error to handle specific error codes. +// aerr, ok := err.(awserr.Error) +// if ok && aerr.Code() == { +// // Specific error code handling +// } +// return err +// } +// +// fmt.Println("BatchDeleteAttributes result:") +// fmt.Println(result) +// +// Using the Client with Context +// +// The service's client also provides methods to make API requests with a Context +// value. This allows you to control the timeout, and cancellation of pending +// requests. These methods also take request Option as variadic parameter to apply +// additional configuration to the API request. +// +// ctx := context.Background() +// +// result, err := svc.BatchDeleteAttributesWithContext(ctx, params) +// +// See the request package documentation for more information on using Context pattern +// with the SDK. +// https://docs.aws.amazon.com/sdk-for-go/api/aws/request/ +package simpledb diff --git a/vendor/github.com/aws/aws-sdk-go/service/simpledb/errors.go b/vendor/github.com/aws/aws-sdk-go/service/simpledb/errors.go index f12143a0d..5fa4dd477 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/simpledb/errors.go +++ b/vendor/github.com/aws/aws-sdk-go/service/simpledb/errors.go @@ -1,4 +1,4 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. package simpledb diff --git a/vendor/github.com/aws/aws-sdk-go/service/simpledb/service.go b/vendor/github.com/aws/aws-sdk-go/service/simpledb/service.go index dd5bf1da3..fb3a0e3cd 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/simpledb/service.go +++ b/vendor/github.com/aws/aws-sdk-go/service/simpledb/service.go @@ -1,4 +1,4 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. package simpledb @@ -12,24 +12,12 @@ import ( "github.com/aws/aws-sdk-go/private/signer/v2" ) -// Amazon SimpleDB is a web service providing the core database functions of -// data indexing and querying in the cloud. By offloading the time and effort -// associated with building and operating a web-scale database, SimpleDB provides -// developers the freedom to focus on application development. A traditional, -// clustered relational database requires a sizable upfront capital outlay, -// is complex to design, and often requires extensive and repetitive database -// administration. Amazon SimpleDB is dramatically simpler, requiring no schema, -// automatically indexing your data and providing a simple API for storage and -// access. This approach eliminates the administrative burden of data modeling, -// index maintenance, and performance tuning. Developers gain access to this -// functionality within Amazon's proven computing environment, are able to scale -// instantly, and pay only for what they use. +// SimpleDB provides the API operation methods for making requests to +// Amazon SimpleDB. See this package's package overview docs +// for details on the service. // -// Visit http://aws.amazon.com/simpledb/ (http://aws.amazon.com/simpledb/) for -// more information. -// The service client's operations are safe to be used concurrently. -// It is not safe to mutate any of the client's properties though. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/ +// SimpleDB methods are safe to use concurrently. It is not safe to +// modify mutate any of the struct's properties though. type SimpleDB struct { *client.Client } diff --git a/vendor/github.com/aws/aws-sdk-go/service/sns/api.go b/vendor/github.com/aws/aws-sdk-go/service/sns/api.go index ee7f647e9..d5664abfc 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/sns/api.go +++ b/vendor/github.com/aws/aws-sdk-go/service/sns/api.go @@ -1,11 +1,11 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. -// Package sns provides a client for Amazon Simple Notification Service. package sns import ( "fmt" + "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awsutil" "github.com/aws/aws-sdk-go/aws/request" "github.com/aws/aws-sdk-go/private/protocol" @@ -85,8 +85,23 @@ func (c *SNS) AddPermissionRequest(input *AddPermissionInput) (req *request.Requ // Please also see https://docs.aws.amazon.com/goto/WebAPI/sns-2010-03-31/AddPermission func (c *SNS) AddPermission(input *AddPermissionInput) (*AddPermissionOutput, error) { req, out := c.AddPermissionRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// AddPermissionWithContext is the same as AddPermission with the addition of +// the ability to pass a context and additional request options. +// +// See AddPermission 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 *SNS) AddPermissionWithContext(ctx aws.Context, input *AddPermissionInput, opts ...request.Option) (*AddPermissionOutput, error) { + req, out := c.AddPermissionRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCheckIfPhoneNumberIsOptedOut = "CheckIfPhoneNumberIsOptedOut" @@ -165,8 +180,23 @@ func (c *SNS) CheckIfPhoneNumberIsOptedOutRequest(input *CheckIfPhoneNumberIsOpt // Please also see https://docs.aws.amazon.com/goto/WebAPI/sns-2010-03-31/CheckIfPhoneNumberIsOptedOut func (c *SNS) CheckIfPhoneNumberIsOptedOut(input *CheckIfPhoneNumberIsOptedOutInput) (*CheckIfPhoneNumberIsOptedOutOutput, error) { req, out := c.CheckIfPhoneNumberIsOptedOutRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CheckIfPhoneNumberIsOptedOutWithContext is the same as CheckIfPhoneNumberIsOptedOut with the addition of +// the ability to pass a context and additional request options. +// +// See CheckIfPhoneNumberIsOptedOut 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 *SNS) CheckIfPhoneNumberIsOptedOutWithContext(ctx aws.Context, input *CheckIfPhoneNumberIsOptedOutInput, opts ...request.Option) (*CheckIfPhoneNumberIsOptedOutOutput, error) { + req, out := c.CheckIfPhoneNumberIsOptedOutRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opConfirmSubscription = "ConfirmSubscription" @@ -246,8 +276,23 @@ func (c *SNS) ConfirmSubscriptionRequest(input *ConfirmSubscriptionInput) (req * // Please also see https://docs.aws.amazon.com/goto/WebAPI/sns-2010-03-31/ConfirmSubscription func (c *SNS) ConfirmSubscription(input *ConfirmSubscriptionInput) (*ConfirmSubscriptionOutput, error) { req, out := c.ConfirmSubscriptionRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ConfirmSubscriptionWithContext is the same as ConfirmSubscription with the addition of +// the ability to pass a context and additional request options. +// +// See ConfirmSubscription 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 *SNS) ConfirmSubscriptionWithContext(ctx aws.Context, input *ConfirmSubscriptionInput, opts ...request.Option) (*ConfirmSubscriptionOutput, error) { + req, out := c.ConfirmSubscriptionRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreatePlatformApplication = "CreatePlatformApplication" @@ -342,8 +387,23 @@ func (c *SNS) CreatePlatformApplicationRequest(input *CreatePlatformApplicationI // Please also see https://docs.aws.amazon.com/goto/WebAPI/sns-2010-03-31/CreatePlatformApplication func (c *SNS) CreatePlatformApplication(input *CreatePlatformApplicationInput) (*CreatePlatformApplicationOutput, error) { req, out := c.CreatePlatformApplicationRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreatePlatformApplicationWithContext is the same as CreatePlatformApplication with the addition of +// the ability to pass a context and additional request options. +// +// See CreatePlatformApplication 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 *SNS) CreatePlatformApplicationWithContext(ctx aws.Context, input *CreatePlatformApplicationInput, opts ...request.Option) (*CreatePlatformApplicationOutput, error) { + req, out := c.CreatePlatformApplicationRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreatePlatformEndpoint = "CreatePlatformEndpoint" @@ -429,8 +489,23 @@ func (c *SNS) CreatePlatformEndpointRequest(input *CreatePlatformEndpointInput) // Please also see https://docs.aws.amazon.com/goto/WebAPI/sns-2010-03-31/CreatePlatformEndpoint func (c *SNS) CreatePlatformEndpoint(input *CreatePlatformEndpointInput) (*CreatePlatformEndpointOutput, error) { req, out := c.CreatePlatformEndpointRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreatePlatformEndpointWithContext is the same as CreatePlatformEndpoint with the addition of +// the ability to pass a context and additional request options. +// +// See CreatePlatformEndpoint 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 *SNS) CreatePlatformEndpointWithContext(ctx aws.Context, input *CreatePlatformEndpointInput, opts ...request.Option) (*CreatePlatformEndpointOutput, error) { + req, out := c.CreatePlatformEndpointRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateTopic = "CreateTopic" @@ -507,8 +582,23 @@ func (c *SNS) CreateTopicRequest(input *CreateTopicInput) (req *request.Request, // Please also see https://docs.aws.amazon.com/goto/WebAPI/sns-2010-03-31/CreateTopic func (c *SNS) CreateTopic(input *CreateTopicInput) (*CreateTopicOutput, error) { req, out := c.CreateTopicRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateTopicWithContext is the same as CreateTopic with the addition of +// the ability to pass a context and additional request options. +// +// See CreateTopic 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 *SNS) CreateTopicWithContext(ctx aws.Context, input *CreateTopicInput, opts ...request.Option) (*CreateTopicOutput, error) { + req, out := c.CreateTopicRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteEndpoint = "DeleteEndpoint" @@ -585,8 +675,23 @@ func (c *SNS) DeleteEndpointRequest(input *DeleteEndpointInput) (req *request.Re // Please also see https://docs.aws.amazon.com/goto/WebAPI/sns-2010-03-31/DeleteEndpoint func (c *SNS) DeleteEndpoint(input *DeleteEndpointInput) (*DeleteEndpointOutput, error) { req, out := c.DeleteEndpointRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteEndpointWithContext is the same as DeleteEndpoint with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteEndpoint 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 *SNS) DeleteEndpointWithContext(ctx aws.Context, input *DeleteEndpointInput, opts ...request.Option) (*DeleteEndpointOutput, error) { + req, out := c.DeleteEndpointRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeletePlatformApplication = "DeletePlatformApplication" @@ -660,8 +765,23 @@ func (c *SNS) DeletePlatformApplicationRequest(input *DeletePlatformApplicationI // Please also see https://docs.aws.amazon.com/goto/WebAPI/sns-2010-03-31/DeletePlatformApplication func (c *SNS) DeletePlatformApplication(input *DeletePlatformApplicationInput) (*DeletePlatformApplicationOutput, error) { req, out := c.DeletePlatformApplicationRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeletePlatformApplicationWithContext is the same as DeletePlatformApplication with the addition of +// the ability to pass a context and additional request options. +// +// See DeletePlatformApplication 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 *SNS) DeletePlatformApplicationWithContext(ctx aws.Context, input *DeletePlatformApplicationInput, opts ...request.Option) (*DeletePlatformApplicationOutput, error) { + req, out := c.DeletePlatformApplicationRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteTopic = "DeleteTopic" @@ -739,8 +859,23 @@ func (c *SNS) DeleteTopicRequest(input *DeleteTopicInput) (req *request.Request, // Please also see https://docs.aws.amazon.com/goto/WebAPI/sns-2010-03-31/DeleteTopic func (c *SNS) DeleteTopic(input *DeleteTopicInput) (*DeleteTopicOutput, error) { req, out := c.DeleteTopicRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteTopicWithContext is the same as DeleteTopic with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteTopic 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 *SNS) DeleteTopicWithContext(ctx aws.Context, input *DeleteTopicInput, opts ...request.Option) (*DeleteTopicOutput, error) { + req, out := c.DeleteTopicRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetEndpointAttributes = "GetEndpointAttributes" @@ -815,8 +950,23 @@ func (c *SNS) GetEndpointAttributesRequest(input *GetEndpointAttributesInput) (r // Please also see https://docs.aws.amazon.com/goto/WebAPI/sns-2010-03-31/GetEndpointAttributes func (c *SNS) GetEndpointAttributes(input *GetEndpointAttributesInput) (*GetEndpointAttributesOutput, error) { req, out := c.GetEndpointAttributesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetEndpointAttributesWithContext is the same as GetEndpointAttributes with the addition of +// the ability to pass a context and additional request options. +// +// See GetEndpointAttributes 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 *SNS) GetEndpointAttributesWithContext(ctx aws.Context, input *GetEndpointAttributesInput, opts ...request.Option) (*GetEndpointAttributesOutput, error) { + req, out := c.GetEndpointAttributesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetPlatformApplicationAttributes = "GetPlatformApplicationAttributes" @@ -891,8 +1041,23 @@ func (c *SNS) GetPlatformApplicationAttributesRequest(input *GetPlatformApplicat // Please also see https://docs.aws.amazon.com/goto/WebAPI/sns-2010-03-31/GetPlatformApplicationAttributes func (c *SNS) GetPlatformApplicationAttributes(input *GetPlatformApplicationAttributesInput) (*GetPlatformApplicationAttributesOutput, error) { req, out := c.GetPlatformApplicationAttributesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetPlatformApplicationAttributesWithContext is the same as GetPlatformApplicationAttributes with the addition of +// the ability to pass a context and additional request options. +// +// See GetPlatformApplicationAttributes 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 *SNS) GetPlatformApplicationAttributesWithContext(ctx aws.Context, input *GetPlatformApplicationAttributesInput, opts ...request.Option) (*GetPlatformApplicationAttributesOutput, error) { + req, out := c.GetPlatformApplicationAttributesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetSMSAttributes = "GetSMSAttributes" @@ -968,8 +1133,23 @@ func (c *SNS) GetSMSAttributesRequest(input *GetSMSAttributesInput) (req *reques // Please also see https://docs.aws.amazon.com/goto/WebAPI/sns-2010-03-31/GetSMSAttributes func (c *SNS) GetSMSAttributes(input *GetSMSAttributesInput) (*GetSMSAttributesOutput, error) { req, out := c.GetSMSAttributesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetSMSAttributesWithContext is the same as GetSMSAttributes with the addition of +// the ability to pass a context and additional request options. +// +// See GetSMSAttributes 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 *SNS) GetSMSAttributesWithContext(ctx aws.Context, input *GetSMSAttributesInput, opts ...request.Option) (*GetSMSAttributesOutput, error) { + req, out := c.GetSMSAttributesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetSubscriptionAttributes = "GetSubscriptionAttributes" @@ -1042,8 +1222,23 @@ func (c *SNS) GetSubscriptionAttributesRequest(input *GetSubscriptionAttributesI // Please also see https://docs.aws.amazon.com/goto/WebAPI/sns-2010-03-31/GetSubscriptionAttributes func (c *SNS) GetSubscriptionAttributes(input *GetSubscriptionAttributesInput) (*GetSubscriptionAttributesOutput, error) { req, out := c.GetSubscriptionAttributesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetSubscriptionAttributesWithContext is the same as GetSubscriptionAttributes with the addition of +// the ability to pass a context and additional request options. +// +// See GetSubscriptionAttributes 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 *SNS) GetSubscriptionAttributesWithContext(ctx aws.Context, input *GetSubscriptionAttributesInput, opts ...request.Option) (*GetSubscriptionAttributesOutput, error) { + req, out := c.GetSubscriptionAttributesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetTopicAttributes = "GetTopicAttributes" @@ -1117,8 +1312,23 @@ func (c *SNS) GetTopicAttributesRequest(input *GetTopicAttributesInput) (req *re // Please also see https://docs.aws.amazon.com/goto/WebAPI/sns-2010-03-31/GetTopicAttributes func (c *SNS) GetTopicAttributes(input *GetTopicAttributesInput) (*GetTopicAttributesOutput, error) { req, out := c.GetTopicAttributesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetTopicAttributesWithContext is the same as GetTopicAttributes with the addition of +// the ability to pass a context and additional request options. +// +// See GetTopicAttributes 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 *SNS) GetTopicAttributesWithContext(ctx aws.Context, input *GetTopicAttributesInput, opts ...request.Option) (*GetTopicAttributesOutput, error) { + req, out := c.GetTopicAttributesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opListEndpointsByPlatformApplication = "ListEndpointsByPlatformApplication" @@ -1204,8 +1414,23 @@ func (c *SNS) ListEndpointsByPlatformApplicationRequest(input *ListEndpointsByPl // Please also see https://docs.aws.amazon.com/goto/WebAPI/sns-2010-03-31/ListEndpointsByPlatformApplication func (c *SNS) ListEndpointsByPlatformApplication(input *ListEndpointsByPlatformApplicationInput) (*ListEndpointsByPlatformApplicationOutput, error) { req, out := c.ListEndpointsByPlatformApplicationRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListEndpointsByPlatformApplicationWithContext is the same as ListEndpointsByPlatformApplication with the addition of +// the ability to pass a context and additional request options. +// +// See ListEndpointsByPlatformApplication 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 *SNS) ListEndpointsByPlatformApplicationWithContext(ctx aws.Context, input *ListEndpointsByPlatformApplicationInput, opts ...request.Option) (*ListEndpointsByPlatformApplicationOutput, error) { + req, out := c.ListEndpointsByPlatformApplicationRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // ListEndpointsByPlatformApplicationPages iterates over the pages of a ListEndpointsByPlatformApplication operation, @@ -1225,12 +1450,37 @@ func (c *SNS) ListEndpointsByPlatformApplication(input *ListEndpointsByPlatformA // return pageNum <= 3 // }) // -func (c *SNS) ListEndpointsByPlatformApplicationPages(input *ListEndpointsByPlatformApplicationInput, fn func(p *ListEndpointsByPlatformApplicationOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.ListEndpointsByPlatformApplicationRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*ListEndpointsByPlatformApplicationOutput), lastPage) - }) +func (c *SNS) ListEndpointsByPlatformApplicationPages(input *ListEndpointsByPlatformApplicationInput, fn func(*ListEndpointsByPlatformApplicationOutput, bool) bool) error { + return c.ListEndpointsByPlatformApplicationPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListEndpointsByPlatformApplicationPagesWithContext same as ListEndpointsByPlatformApplicationPages 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 *SNS) ListEndpointsByPlatformApplicationPagesWithContext(ctx aws.Context, input *ListEndpointsByPlatformApplicationInput, fn func(*ListEndpointsByPlatformApplicationOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListEndpointsByPlatformApplicationInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListEndpointsByPlatformApplicationRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*ListEndpointsByPlatformApplicationOutput), !p.HasNextPage()) + } + return p.Err() } const opListPhoneNumbersOptedOut = "ListPhoneNumbersOptedOut" @@ -1312,8 +1562,23 @@ func (c *SNS) ListPhoneNumbersOptedOutRequest(input *ListPhoneNumbersOptedOutInp // Please also see https://docs.aws.amazon.com/goto/WebAPI/sns-2010-03-31/ListPhoneNumbersOptedOut func (c *SNS) ListPhoneNumbersOptedOut(input *ListPhoneNumbersOptedOutInput) (*ListPhoneNumbersOptedOutOutput, error) { req, out := c.ListPhoneNumbersOptedOutRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListPhoneNumbersOptedOutWithContext is the same as ListPhoneNumbersOptedOut with the addition of +// the ability to pass a context and additional request options. +// +// See ListPhoneNumbersOptedOut 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 *SNS) ListPhoneNumbersOptedOutWithContext(ctx aws.Context, input *ListPhoneNumbersOptedOutInput, opts ...request.Option) (*ListPhoneNumbersOptedOutOutput, error) { + req, out := c.ListPhoneNumbersOptedOutRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opListPlatformApplications = "ListPlatformApplications" @@ -1396,8 +1661,23 @@ func (c *SNS) ListPlatformApplicationsRequest(input *ListPlatformApplicationsInp // Please also see https://docs.aws.amazon.com/goto/WebAPI/sns-2010-03-31/ListPlatformApplications func (c *SNS) ListPlatformApplications(input *ListPlatformApplicationsInput) (*ListPlatformApplicationsOutput, error) { req, out := c.ListPlatformApplicationsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListPlatformApplicationsWithContext is the same as ListPlatformApplications with the addition of +// the ability to pass a context and additional request options. +// +// See ListPlatformApplications 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 *SNS) ListPlatformApplicationsWithContext(ctx aws.Context, input *ListPlatformApplicationsInput, opts ...request.Option) (*ListPlatformApplicationsOutput, error) { + req, out := c.ListPlatformApplicationsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // ListPlatformApplicationsPages iterates over the pages of a ListPlatformApplications operation, @@ -1417,12 +1697,37 @@ func (c *SNS) ListPlatformApplications(input *ListPlatformApplicationsInput) (*L // return pageNum <= 3 // }) // -func (c *SNS) ListPlatformApplicationsPages(input *ListPlatformApplicationsInput, fn func(p *ListPlatformApplicationsOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.ListPlatformApplicationsRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*ListPlatformApplicationsOutput), lastPage) - }) +func (c *SNS) ListPlatformApplicationsPages(input *ListPlatformApplicationsInput, fn func(*ListPlatformApplicationsOutput, bool) bool) error { + return c.ListPlatformApplicationsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListPlatformApplicationsPagesWithContext same as ListPlatformApplicationsPages 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 *SNS) ListPlatformApplicationsPagesWithContext(ctx aws.Context, input *ListPlatformApplicationsInput, fn func(*ListPlatformApplicationsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListPlatformApplicationsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListPlatformApplicationsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*ListPlatformApplicationsOutput), !p.HasNextPage()) + } + return p.Err() } const opListSubscriptions = "ListSubscriptions" @@ -1501,8 +1806,23 @@ func (c *SNS) ListSubscriptionsRequest(input *ListSubscriptionsInput) (req *requ // Please also see https://docs.aws.amazon.com/goto/WebAPI/sns-2010-03-31/ListSubscriptions func (c *SNS) ListSubscriptions(input *ListSubscriptionsInput) (*ListSubscriptionsOutput, error) { req, out := c.ListSubscriptionsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListSubscriptionsWithContext is the same as ListSubscriptions with the addition of +// the ability to pass a context and additional request options. +// +// See ListSubscriptions 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 *SNS) ListSubscriptionsWithContext(ctx aws.Context, input *ListSubscriptionsInput, opts ...request.Option) (*ListSubscriptionsOutput, error) { + req, out := c.ListSubscriptionsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // ListSubscriptionsPages iterates over the pages of a ListSubscriptions operation, @@ -1522,12 +1842,37 @@ func (c *SNS) ListSubscriptions(input *ListSubscriptionsInput) (*ListSubscriptio // return pageNum <= 3 // }) // -func (c *SNS) ListSubscriptionsPages(input *ListSubscriptionsInput, fn func(p *ListSubscriptionsOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.ListSubscriptionsRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*ListSubscriptionsOutput), lastPage) - }) +func (c *SNS) ListSubscriptionsPages(input *ListSubscriptionsInput, fn func(*ListSubscriptionsOutput, bool) bool) error { + return c.ListSubscriptionsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListSubscriptionsPagesWithContext same as ListSubscriptionsPages 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 *SNS) ListSubscriptionsPagesWithContext(ctx aws.Context, input *ListSubscriptionsInput, fn func(*ListSubscriptionsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListSubscriptionsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListSubscriptionsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*ListSubscriptionsOutput), !p.HasNextPage()) + } + return p.Err() } const opListSubscriptionsByTopic = "ListSubscriptionsByTopic" @@ -1609,8 +1954,23 @@ func (c *SNS) ListSubscriptionsByTopicRequest(input *ListSubscriptionsByTopicInp // Please also see https://docs.aws.amazon.com/goto/WebAPI/sns-2010-03-31/ListSubscriptionsByTopic func (c *SNS) ListSubscriptionsByTopic(input *ListSubscriptionsByTopicInput) (*ListSubscriptionsByTopicOutput, error) { req, out := c.ListSubscriptionsByTopicRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListSubscriptionsByTopicWithContext is the same as ListSubscriptionsByTopic with the addition of +// the ability to pass a context and additional request options. +// +// See ListSubscriptionsByTopic 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 *SNS) ListSubscriptionsByTopicWithContext(ctx aws.Context, input *ListSubscriptionsByTopicInput, opts ...request.Option) (*ListSubscriptionsByTopicOutput, error) { + req, out := c.ListSubscriptionsByTopicRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // ListSubscriptionsByTopicPages iterates over the pages of a ListSubscriptionsByTopic operation, @@ -1630,12 +1990,37 @@ func (c *SNS) ListSubscriptionsByTopic(input *ListSubscriptionsByTopicInput) (*L // return pageNum <= 3 // }) // -func (c *SNS) ListSubscriptionsByTopicPages(input *ListSubscriptionsByTopicInput, fn func(p *ListSubscriptionsByTopicOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.ListSubscriptionsByTopicRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*ListSubscriptionsByTopicOutput), lastPage) - }) +func (c *SNS) ListSubscriptionsByTopicPages(input *ListSubscriptionsByTopicInput, fn func(*ListSubscriptionsByTopicOutput, bool) bool) error { + return c.ListSubscriptionsByTopicPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListSubscriptionsByTopicPagesWithContext same as ListSubscriptionsByTopicPages 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 *SNS) ListSubscriptionsByTopicPagesWithContext(ctx aws.Context, input *ListSubscriptionsByTopicInput, fn func(*ListSubscriptionsByTopicOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListSubscriptionsByTopicInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListSubscriptionsByTopicRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*ListSubscriptionsByTopicOutput), !p.HasNextPage()) + } + return p.Err() } const opListTopics = "ListTopics" @@ -1713,8 +2098,23 @@ func (c *SNS) ListTopicsRequest(input *ListTopicsInput) (req *request.Request, o // Please also see https://docs.aws.amazon.com/goto/WebAPI/sns-2010-03-31/ListTopics func (c *SNS) ListTopics(input *ListTopicsInput) (*ListTopicsOutput, error) { req, out := c.ListTopicsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListTopicsWithContext is the same as ListTopics with the addition of +// the ability to pass a context and additional request options. +// +// See ListTopics 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 *SNS) ListTopicsWithContext(ctx aws.Context, input *ListTopicsInput, opts ...request.Option) (*ListTopicsOutput, error) { + req, out := c.ListTopicsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // ListTopicsPages iterates over the pages of a ListTopics operation, @@ -1734,12 +2134,37 @@ func (c *SNS) ListTopics(input *ListTopicsInput) (*ListTopicsOutput, error) { // return pageNum <= 3 // }) // -func (c *SNS) ListTopicsPages(input *ListTopicsInput, fn func(p *ListTopicsOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.ListTopicsRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*ListTopicsOutput), lastPage) - }) +func (c *SNS) ListTopicsPages(input *ListTopicsInput, fn func(*ListTopicsOutput, bool) bool) error { + return c.ListTopicsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListTopicsPagesWithContext same as ListTopicsPages 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 *SNS) ListTopicsPagesWithContext(ctx aws.Context, input *ListTopicsInput, fn func(*ListTopicsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListTopicsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListTopicsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*ListTopicsOutput), !p.HasNextPage()) + } + return p.Err() } const opOptInPhoneNumber = "OptInPhoneNumber" @@ -1816,8 +2241,23 @@ func (c *SNS) OptInPhoneNumberRequest(input *OptInPhoneNumberInput) (req *reques // Please also see https://docs.aws.amazon.com/goto/WebAPI/sns-2010-03-31/OptInPhoneNumber func (c *SNS) OptInPhoneNumber(input *OptInPhoneNumberInput) (*OptInPhoneNumberOutput, error) { req, out := c.OptInPhoneNumberRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// OptInPhoneNumberWithContext is the same as OptInPhoneNumber with the addition of +// the ability to pass a context and additional request options. +// +// See OptInPhoneNumber 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 *SNS) OptInPhoneNumberWithContext(ctx aws.Context, input *OptInPhoneNumberInput, opts ...request.Option) (*OptInPhoneNumberOutput, error) { + req, out := c.OptInPhoneNumberRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opPublish = "Publish" @@ -1910,8 +2350,23 @@ func (c *SNS) PublishRequest(input *PublishInput) (req *request.Request, output // Please also see https://docs.aws.amazon.com/goto/WebAPI/sns-2010-03-31/Publish func (c *SNS) Publish(input *PublishInput) (*PublishOutput, error) { req, out := c.PublishRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// PublishWithContext is the same as Publish with the addition of +// the ability to pass a context and additional request options. +// +// See Publish 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 *SNS) PublishWithContext(ctx aws.Context, input *PublishInput, opts ...request.Option) (*PublishOutput, error) { + req, out := c.PublishRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opRemovePermission = "RemovePermission" @@ -1986,8 +2441,23 @@ func (c *SNS) RemovePermissionRequest(input *RemovePermissionInput) (req *reques // Please also see https://docs.aws.amazon.com/goto/WebAPI/sns-2010-03-31/RemovePermission func (c *SNS) RemovePermission(input *RemovePermissionInput) (*RemovePermissionOutput, error) { req, out := c.RemovePermissionRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// RemovePermissionWithContext is the same as RemovePermission with the addition of +// the ability to pass a context and additional request options. +// +// See RemovePermission 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 *SNS) RemovePermissionWithContext(ctx aws.Context, input *RemovePermissionInput, opts ...request.Option) (*RemovePermissionOutput, error) { + req, out := c.RemovePermissionRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opSetEndpointAttributes = "SetEndpointAttributes" @@ -2064,8 +2534,23 @@ func (c *SNS) SetEndpointAttributesRequest(input *SetEndpointAttributesInput) (r // Please also see https://docs.aws.amazon.com/goto/WebAPI/sns-2010-03-31/SetEndpointAttributes func (c *SNS) SetEndpointAttributes(input *SetEndpointAttributesInput) (*SetEndpointAttributesOutput, error) { req, out := c.SetEndpointAttributesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// SetEndpointAttributesWithContext is the same as SetEndpointAttributes with the addition of +// the ability to pass a context and additional request options. +// +// See SetEndpointAttributes 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 *SNS) SetEndpointAttributesWithContext(ctx aws.Context, input *SetEndpointAttributesInput, opts ...request.Option) (*SetEndpointAttributesOutput, error) { + req, out := c.SetEndpointAttributesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opSetPlatformApplicationAttributes = "SetPlatformApplicationAttributes" @@ -2144,8 +2629,23 @@ func (c *SNS) SetPlatformApplicationAttributesRequest(input *SetPlatformApplicat // Please also see https://docs.aws.amazon.com/goto/WebAPI/sns-2010-03-31/SetPlatformApplicationAttributes func (c *SNS) SetPlatformApplicationAttributes(input *SetPlatformApplicationAttributesInput) (*SetPlatformApplicationAttributesOutput, error) { req, out := c.SetPlatformApplicationAttributesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// SetPlatformApplicationAttributesWithContext is the same as SetPlatformApplicationAttributes with the addition of +// the ability to pass a context and additional request options. +// +// See SetPlatformApplicationAttributes 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 *SNS) SetPlatformApplicationAttributesWithContext(ctx aws.Context, input *SetPlatformApplicationAttributesInput, opts ...request.Option) (*SetPlatformApplicationAttributesOutput, error) { + req, out := c.SetPlatformApplicationAttributesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opSetSMSAttributes = "SetSMSAttributes" @@ -2225,8 +2725,23 @@ func (c *SNS) SetSMSAttributesRequest(input *SetSMSAttributesInput) (req *reques // Please also see https://docs.aws.amazon.com/goto/WebAPI/sns-2010-03-31/SetSMSAttributes func (c *SNS) SetSMSAttributes(input *SetSMSAttributesInput) (*SetSMSAttributesOutput, error) { req, out := c.SetSMSAttributesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// SetSMSAttributesWithContext is the same as SetSMSAttributes with the addition of +// the ability to pass a context and additional request options. +// +// See SetSMSAttributes 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 *SNS) SetSMSAttributesWithContext(ctx aws.Context, input *SetSMSAttributesInput, opts ...request.Option) (*SetSMSAttributesOutput, error) { + req, out := c.SetSMSAttributesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opSetSubscriptionAttributes = "SetSubscriptionAttributes" @@ -2301,8 +2816,23 @@ func (c *SNS) SetSubscriptionAttributesRequest(input *SetSubscriptionAttributesI // Please also see https://docs.aws.amazon.com/goto/WebAPI/sns-2010-03-31/SetSubscriptionAttributes func (c *SNS) SetSubscriptionAttributes(input *SetSubscriptionAttributesInput) (*SetSubscriptionAttributesOutput, error) { req, out := c.SetSubscriptionAttributesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// SetSubscriptionAttributesWithContext is the same as SetSubscriptionAttributes with the addition of +// the ability to pass a context and additional request options. +// +// See SetSubscriptionAttributes 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 *SNS) SetSubscriptionAttributesWithContext(ctx aws.Context, input *SetSubscriptionAttributesInput, opts ...request.Option) (*SetSubscriptionAttributesOutput, error) { + req, out := c.SetSubscriptionAttributesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opSetTopicAttributes = "SetTopicAttributes" @@ -2377,8 +2907,23 @@ func (c *SNS) SetTopicAttributesRequest(input *SetTopicAttributesInput) (req *re // Please also see https://docs.aws.amazon.com/goto/WebAPI/sns-2010-03-31/SetTopicAttributes func (c *SNS) SetTopicAttributes(input *SetTopicAttributesInput) (*SetTopicAttributesOutput, error) { req, out := c.SetTopicAttributesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// SetTopicAttributesWithContext is the same as SetTopicAttributes with the addition of +// the ability to pass a context and additional request options. +// +// See SetTopicAttributes 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 *SNS) SetTopicAttributesWithContext(ctx aws.Context, input *SetTopicAttributesInput, opts ...request.Option) (*SetTopicAttributesOutput, error) { + req, out := c.SetTopicAttributesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opSubscribe = "Subscribe" @@ -2457,8 +3002,23 @@ func (c *SNS) SubscribeRequest(input *SubscribeInput) (req *request.Request, out // Please also see https://docs.aws.amazon.com/goto/WebAPI/sns-2010-03-31/Subscribe func (c *SNS) Subscribe(input *SubscribeInput) (*SubscribeOutput, error) { req, out := c.SubscribeRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// SubscribeWithContext is the same as Subscribe with the addition of +// the ability to pass a context and additional request options. +// +// See Subscribe 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 *SNS) SubscribeWithContext(ctx aws.Context, input *SubscribeInput, opts ...request.Option) (*SubscribeOutput, error) { + req, out := c.SubscribeRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opUnsubscribe = "Unsubscribe" @@ -2538,8 +3098,23 @@ func (c *SNS) UnsubscribeRequest(input *UnsubscribeInput) (req *request.Request, // Please also see https://docs.aws.amazon.com/goto/WebAPI/sns-2010-03-31/Unsubscribe func (c *SNS) Unsubscribe(input *UnsubscribeInput) (*UnsubscribeOutput, error) { req, out := c.UnsubscribeRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// UnsubscribeWithContext is the same as Unsubscribe with the addition of +// the ability to pass a context and additional request options. +// +// See Unsubscribe 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 *SNS) UnsubscribeWithContext(ctx aws.Context, input *UnsubscribeInput, opts ...request.Option) (*UnsubscribeOutput, error) { + req, out := c.UnsubscribeRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // Please also see https://docs.aws.amazon.com/goto/WebAPI/sns-2010-03-31/AddPermissionInput diff --git a/vendor/github.com/aws/aws-sdk-go/service/sns/doc.go b/vendor/github.com/aws/aws-sdk-go/service/sns/doc.go new file mode 100644 index 000000000..52461d3d4 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/service/sns/doc.go @@ -0,0 +1,92 @@ +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. + +// Package sns provides the client and types for making API +// requests to Amazon Simple Notification Service. +// +// Amazon Simple Notification Service (Amazon SNS) is a web service that enables +// you to build distributed web-enabled applications. Applications can use Amazon +// SNS to easily push real-time notification messages to interested subscribers +// over multiple delivery protocols. For more information about this product +// see http://aws.amazon.com/sns (http://aws.amazon.com/sns/). For detailed +// information about Amazon SNS features and their associated API calls, see +// the Amazon SNS Developer Guide (http://docs.aws.amazon.com/sns/latest/dg/). +// +// We also provide SDKs that enable you to access Amazon SNS from your preferred +// programming language. The SDKs contain functionality that automatically takes +// care of tasks such as: cryptographically signing your service requests, retrying +// requests, and handling error responses. For a list of available SDKs, go +// to Tools for Amazon Web Services (http://aws.amazon.com/tools/). +// +// See https://docs.aws.amazon.com/goto/WebAPI/sns-2010-03-31 for more information on this service. +// +// See sns package documentation for more information. +// https://docs.aws.amazon.com/sdk-for-go/api/service/sns/ +// +// Using the Client +// +// To use the client for Amazon Simple Notification Service you will first need +// to create a new instance of it. +// +// When creating a client for an AWS service you'll first need to have a Session +// already created. The Session provides configuration that can be shared +// between multiple service clients. Additional configuration can be applied to +// the Session and service's client when they are constructed. The aws package's +// Config type contains several fields such as Region for the AWS Region the +// client should make API requests too. The optional Config value can be provided +// as the variadic argument for Sessions and client creation. +// +// Once the service's client is created you can use it to make API requests the +// AWS service. These clients are safe to use concurrently. +// +// // Create a session to share configuration, and load external configuration. +// sess := session.Must(session.NewSession()) +// +// // Create the service's client with the session. +// svc := sns.New(sess) +// +// See the SDK's documentation for more information on how to use service clients. +// https://docs.aws.amazon.com/sdk-for-go/api/ +// +// See aws package's Config type for more information on configuration options. +// https://docs.aws.amazon.com/sdk-for-go/api/aws/#Config +// +// See the Amazon Simple Notification Service client SNS for more +// information on creating the service's client. +// https://docs.aws.amazon.com/sdk-for-go/api/service/sns/#New +// +// Once the client is created you can make an API request to the service. +// Each API method takes a input parameter, and returns the service response +// and an error. +// +// The API method will document which error codes the service can be returned +// by the operation if the service models the API operation's errors. These +// errors will also be available as const strings prefixed with "ErrCode". +// +// result, err := svc.AddPermission(params) +// if err != nil { +// // Cast err to awserr.Error to handle specific error codes. +// aerr, ok := err.(awserr.Error) +// if ok && aerr.Code() == { +// // Specific error code handling +// } +// return err +// } +// +// fmt.Println("AddPermission result:") +// fmt.Println(result) +// +// Using the Client with Context +// +// The service's client also provides methods to make API requests with a Context +// value. This allows you to control the timeout, and cancellation of pending +// requests. These methods also take request Option as variadic parameter to apply +// additional configuration to the API request. +// +// ctx := context.Background() +// +// result, err := svc.AddPermissionWithContext(ctx, params) +// +// See the request package documentation for more information on using Context pattern +// with the SDK. +// https://docs.aws.amazon.com/sdk-for-go/api/aws/request/ +package sns diff --git a/vendor/github.com/aws/aws-sdk-go/service/sns/errors.go b/vendor/github.com/aws/aws-sdk-go/service/sns/errors.go index c6e3dbe20..60e503f25 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/sns/errors.go +++ b/vendor/github.com/aws/aws-sdk-go/service/sns/errors.go @@ -1,4 +1,4 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. package sns diff --git a/vendor/github.com/aws/aws-sdk-go/service/sns/service.go b/vendor/github.com/aws/aws-sdk-go/service/sns/service.go index 6bb73fa7c..fb75ea60a 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/sns/service.go +++ b/vendor/github.com/aws/aws-sdk-go/service/sns/service.go @@ -1,4 +1,4 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. package sns @@ -11,22 +11,12 @@ import ( "github.com/aws/aws-sdk-go/private/protocol/query" ) -// Amazon Simple Notification Service (Amazon SNS) is a web service that enables -// you to build distributed web-enabled applications. Applications can use Amazon -// SNS to easily push real-time notification messages to interested subscribers -// over multiple delivery protocols. For more information about this product -// see http://aws.amazon.com/sns (http://aws.amazon.com/sns/). For detailed -// information about Amazon SNS features and their associated API calls, see -// the Amazon SNS Developer Guide (http://docs.aws.amazon.com/sns/latest/dg/). +// SNS provides the API operation methods for making requests to +// Amazon Simple Notification Service. See this package's package overview docs +// for details on the service. // -// We also provide SDKs that enable you to access Amazon SNS from your preferred -// programming language. The SDKs contain functionality that automatically takes -// care of tasks such as: cryptographically signing your service requests, retrying -// requests, and handling error responses. For a list of available SDKs, go -// to Tools for Amazon Web Services (http://aws.amazon.com/tools/). -// The service client's operations are safe to be used concurrently. -// It is not safe to mutate any of the client's properties though. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/sns-2010-03-31 +// SNS methods are safe to use concurrently. It is not safe to +// modify mutate any of the struct's properties though. type SNS struct { *client.Client } diff --git a/vendor/github.com/aws/aws-sdk-go/service/sqs/api.go b/vendor/github.com/aws/aws-sdk-go/service/sqs/api.go index 207ef6d49..97ba16313 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/sqs/api.go +++ b/vendor/github.com/aws/aws-sdk-go/service/sqs/api.go @@ -1,11 +1,11 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. -// Package sqs provides a client for Amazon Simple Queue Service. package sqs import ( "fmt" + "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awsutil" "github.com/aws/aws-sdk-go/aws/request" "github.com/aws/aws-sdk-go/private/protocol" @@ -97,8 +97,23 @@ func (c *SQS) AddPermissionRequest(input *AddPermissionInput) (req *request.Requ // Please also see https://docs.aws.amazon.com/goto/WebAPI/sqs-2012-11-05/AddPermission func (c *SQS) AddPermission(input *AddPermissionInput) (*AddPermissionOutput, error) { req, out := c.AddPermissionRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// AddPermissionWithContext is the same as AddPermission with the addition of +// the ability to pass a context and additional request options. +// +// See AddPermission 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 *SQS) AddPermissionWithContext(ctx aws.Context, input *AddPermissionInput, opts ...request.Option) (*AddPermissionOutput, error) { + req, out := c.AddPermissionRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opChangeMessageVisibility = "ChangeMessageVisibility" @@ -203,8 +218,23 @@ func (c *SQS) ChangeMessageVisibilityRequest(input *ChangeMessageVisibilityInput // Please also see https://docs.aws.amazon.com/goto/WebAPI/sqs-2012-11-05/ChangeMessageVisibility func (c *SQS) ChangeMessageVisibility(input *ChangeMessageVisibilityInput) (*ChangeMessageVisibilityOutput, error) { req, out := c.ChangeMessageVisibilityRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ChangeMessageVisibilityWithContext is the same as ChangeMessageVisibility with the addition of +// the ability to pass a context and additional request options. +// +// See ChangeMessageVisibility 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 *SQS) ChangeMessageVisibilityWithContext(ctx aws.Context, input *ChangeMessageVisibilityInput, opts ...request.Option) (*ChangeMessageVisibilityOutput, error) { + req, out := c.ChangeMessageVisibilityRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opChangeMessageVisibilityBatch = "ChangeMessageVisibilityBatch" @@ -292,8 +322,23 @@ func (c *SQS) ChangeMessageVisibilityBatchRequest(input *ChangeMessageVisibility // Please also see https://docs.aws.amazon.com/goto/WebAPI/sqs-2012-11-05/ChangeMessageVisibilityBatch func (c *SQS) ChangeMessageVisibilityBatch(input *ChangeMessageVisibilityBatchInput) (*ChangeMessageVisibilityBatchOutput, error) { req, out := c.ChangeMessageVisibilityBatchRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ChangeMessageVisibilityBatchWithContext is the same as ChangeMessageVisibilityBatch with the addition of +// the ability to pass a context and additional request options. +// +// See ChangeMessageVisibilityBatch 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 *SQS) ChangeMessageVisibilityBatchWithContext(ctx aws.Context, input *ChangeMessageVisibilityBatchInput, opts ...request.Option) (*ChangeMessageVisibilityBatchOutput, error) { + req, out := c.ChangeMessageVisibilityBatchRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateQueue = "CreateQueue" @@ -341,9 +386,8 @@ func (c *SQS) CreateQueueRequest(input *CreateQueueInput) (req *request.Request, // CreateQueue API operation for Amazon Simple Queue Service. // -// Creates a new standard or FIFO queue or returns the URL of an existing queue. -// You can pass one or more attributes in the request. Keep the following caveats -// in mind: +// Creates a new standard or FIFO queue. You can pass one or more attributes +// in the request. Keep the following caveats in mind: // // * If you don't specify the FifoQueue attribute, Amazon SQS creates a standard // queue. @@ -403,8 +447,23 @@ func (c *SQS) CreateQueueRequest(input *CreateQueueInput) (req *request.Request, // Please also see https://docs.aws.amazon.com/goto/WebAPI/sqs-2012-11-05/CreateQueue func (c *SQS) CreateQueue(input *CreateQueueInput) (*CreateQueueOutput, error) { req, out := c.CreateQueueRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateQueueWithContext is the same as CreateQueue with the addition of +// the ability to pass a context and additional request options. +// +// See CreateQueue 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 *SQS) CreateQueueWithContext(ctx aws.Context, input *CreateQueueInput, opts ...request.Option) (*CreateQueueOutput, error) { + req, out := c.CreateQueueRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteMessage = "DeleteMessage" @@ -468,7 +527,7 @@ func (c *SQS) DeleteMessageRequest(input *DeleteMessageInput) (req *request.Requ // DeleteMessage action, the request succeeds, but the message might not be // deleted. // -// For standard queues, it is possible to receive a message even after you deleting +// For standard queues, it is possible to receive a message even after you delete // it. This might happen on rare occasions if one of the servers storing a copy // of the message is unavailable when you send the request to delete the message. // The copy remains on the server and might be returned to you on a subsequent @@ -492,8 +551,23 @@ func (c *SQS) DeleteMessageRequest(input *DeleteMessageInput) (req *request.Requ // Please also see https://docs.aws.amazon.com/goto/WebAPI/sqs-2012-11-05/DeleteMessage func (c *SQS) DeleteMessage(input *DeleteMessageInput) (*DeleteMessageOutput, error) { req, out := c.DeleteMessageRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteMessageWithContext is the same as DeleteMessage with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteMessage 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 *SQS) DeleteMessageWithContext(ctx aws.Context, input *DeleteMessageInput, opts ...request.Option) (*DeleteMessageOutput, error) { + req, out := c.DeleteMessageRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteMessageBatch = "DeleteMessageBatch" @@ -580,8 +654,23 @@ func (c *SQS) DeleteMessageBatchRequest(input *DeleteMessageBatchInput) (req *re // Please also see https://docs.aws.amazon.com/goto/WebAPI/sqs-2012-11-05/DeleteMessageBatch func (c *SQS) DeleteMessageBatch(input *DeleteMessageBatchInput) (*DeleteMessageBatchOutput, error) { req, out := c.DeleteMessageBatchRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteMessageBatchWithContext is the same as DeleteMessageBatch with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteMessageBatch 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 *SQS) DeleteMessageBatchWithContext(ctx aws.Context, input *DeleteMessageBatchInput, opts ...request.Option) (*DeleteMessageBatchOutput, error) { + req, out := c.DeleteMessageBatchRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteQueue = "DeleteQueue" @@ -654,8 +743,23 @@ func (c *SQS) DeleteQueueRequest(input *DeleteQueueInput) (req *request.Request, // Please also see https://docs.aws.amazon.com/goto/WebAPI/sqs-2012-11-05/DeleteQueue func (c *SQS) DeleteQueue(input *DeleteQueueInput) (*DeleteQueueOutput, error) { req, out := c.DeleteQueueRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteQueueWithContext is the same as DeleteQueue with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteQueue 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 *SQS) DeleteQueueWithContext(ctx aws.Context, input *DeleteQueueInput, opts ...request.Option) (*DeleteQueueOutput, error) { + req, out := c.DeleteQueueRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetQueueAttributes = "GetQueueAttributes" @@ -705,6 +809,9 @@ func (c *SQS) GetQueueAttributesRequest(input *GetQueueAttributesInput) (req *re // // Gets attributes for the specified queue. // +// To determine whether a queue is FIFO (http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/FIFO-queues.html), +// you can check whether QueueName ends with the .fifo suffix. +// // Some actions take lists of parameters. These lists are specified using the // param.n notation. Values of n are integers starting from 1. For example, // a parameter list with two elements looks like this: @@ -727,8 +834,23 @@ func (c *SQS) GetQueueAttributesRequest(input *GetQueueAttributesInput) (req *re // Please also see https://docs.aws.amazon.com/goto/WebAPI/sqs-2012-11-05/GetQueueAttributes func (c *SQS) GetQueueAttributes(input *GetQueueAttributesInput) (*GetQueueAttributesOutput, error) { req, out := c.GetQueueAttributesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetQueueAttributesWithContext is the same as GetQueueAttributes with the addition of +// the ability to pass a context and additional request options. +// +// See GetQueueAttributes 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 *SQS) GetQueueAttributesWithContext(ctx aws.Context, input *GetQueueAttributesInput, opts ...request.Option) (*GetQueueAttributesOutput, error) { + req, out := c.GetQueueAttributesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetQueueUrl = "GetQueueUrl" @@ -799,8 +921,23 @@ func (c *SQS) GetQueueUrlRequest(input *GetQueueUrlInput) (req *request.Request, // Please also see https://docs.aws.amazon.com/goto/WebAPI/sqs-2012-11-05/GetQueueUrl func (c *SQS) GetQueueUrl(input *GetQueueUrlInput) (*GetQueueUrlOutput, error) { req, out := c.GetQueueUrlRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetQueueUrlWithContext is the same as GetQueueUrl with the addition of +// the ability to pass a context and additional request options. +// +// See GetQueueUrl 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 *SQS) GetQueueUrlWithContext(ctx aws.Context, input *GetQueueUrlInput, opts ...request.Option) (*GetQueueUrlOutput, error) { + req, out := c.GetQueueUrlRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opListDeadLetterSourceQueues = "ListDeadLetterSourceQueues" @@ -869,8 +1006,23 @@ func (c *SQS) ListDeadLetterSourceQueuesRequest(input *ListDeadLetterSourceQueue // Please also see https://docs.aws.amazon.com/goto/WebAPI/sqs-2012-11-05/ListDeadLetterSourceQueues func (c *SQS) ListDeadLetterSourceQueues(input *ListDeadLetterSourceQueuesInput) (*ListDeadLetterSourceQueuesOutput, error) { req, out := c.ListDeadLetterSourceQueuesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListDeadLetterSourceQueuesWithContext is the same as ListDeadLetterSourceQueues with the addition of +// the ability to pass a context and additional request options. +// +// See ListDeadLetterSourceQueues 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 *SQS) ListDeadLetterSourceQueuesWithContext(ctx aws.Context, input *ListDeadLetterSourceQueuesInput, opts ...request.Option) (*ListDeadLetterSourceQueuesOutput, error) { + req, out := c.ListDeadLetterSourceQueuesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opListQueues = "ListQueues" @@ -931,8 +1083,23 @@ func (c *SQS) ListQueuesRequest(input *ListQueuesInput) (req *request.Request, o // Please also see https://docs.aws.amazon.com/goto/WebAPI/sqs-2012-11-05/ListQueues func (c *SQS) ListQueues(input *ListQueuesInput) (*ListQueuesOutput, error) { req, out := c.ListQueuesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListQueuesWithContext is the same as ListQueues with the addition of +// the ability to pass a context and additional request options. +// +// See ListQueues 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 *SQS) ListQueuesWithContext(ctx aws.Context, input *ListQueuesInput, opts ...request.Option) (*ListQueuesOutput, error) { + req, out := c.ListQueuesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opPurgeQueue = "PurgeQueue" @@ -1012,8 +1179,23 @@ func (c *SQS) PurgeQueueRequest(input *PurgeQueueInput) (req *request.Request, o // Please also see https://docs.aws.amazon.com/goto/WebAPI/sqs-2012-11-05/PurgeQueue func (c *SQS) PurgeQueue(input *PurgeQueueInput) (*PurgeQueueOutput, error) { req, out := c.PurgeQueueRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// PurgeQueueWithContext is the same as PurgeQueue with the addition of +// the ability to pass a context and additional request options. +// +// See PurgeQueue 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 *SQS) PurgeQueueWithContext(ctx aws.Context, input *PurgeQueueInput, opts ...request.Option) (*PurgeQueueOutput, error) { + req, out := c.PurgeQueueRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opReceiveMessage = "ReceiveMessage" @@ -1078,7 +1260,7 @@ func (c *SQS) ReceiveMessageRequest(input *ReceiveMessageInput) (req *request.Re // // * The message body. // -// * An MD5 digest of the message body. For information on MD5, see RFC1321 +// * An MD5 digest of the message body. For information about MD5, see RFC1321 // (https://www.ietf.org/rfc/rfc1321.txt). // // * The MessageId you received when you sent the message to the queue. @@ -1126,8 +1308,23 @@ func (c *SQS) ReceiveMessageRequest(input *ReceiveMessageInput) (req *request.Re // Please also see https://docs.aws.amazon.com/goto/WebAPI/sqs-2012-11-05/ReceiveMessage func (c *SQS) ReceiveMessage(input *ReceiveMessageInput) (*ReceiveMessageOutput, error) { req, out := c.ReceiveMessageRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ReceiveMessageWithContext is the same as ReceiveMessage with the addition of +// the ability to pass a context and additional request options. +// +// See ReceiveMessage 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 *SQS) ReceiveMessageWithContext(ctx aws.Context, input *ReceiveMessageInput, opts ...request.Option) (*ReceiveMessageOutput, error) { + req, out := c.ReceiveMessageRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opRemovePermission = "RemovePermission" @@ -1189,8 +1386,23 @@ func (c *SQS) RemovePermissionRequest(input *RemovePermissionInput) (req *reques // Please also see https://docs.aws.amazon.com/goto/WebAPI/sqs-2012-11-05/RemovePermission func (c *SQS) RemovePermission(input *RemovePermissionInput) (*RemovePermissionOutput, error) { req, out := c.RemovePermissionRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// RemovePermissionWithContext is the same as RemovePermission with the addition of +// the ability to pass a context and additional request options. +// +// See RemovePermission 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 *SQS) RemovePermissionWithContext(ctx aws.Context, input *RemovePermissionInput, opts ...request.Option) (*RemovePermissionOutput, error) { + req, out := c.RemovePermissionRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opSendMessage = "SendMessage" @@ -1240,24 +1452,13 @@ func (c *SQS) SendMessageRequest(input *SendMessageInput) (req *request.Request, // // Delivers a message to the specified queue. // -// The following list shows the characters (in Unicode) that are allowed in -// your message, according to the W3C XML specification: +// A message can include only XML, JSON, and unformatted text. The following +// Unicode characters are allowed: // -// #x9 +// #x9 | #xA | #xD | #x20 to #xD7FF | #xE000 to #xFFFD | #x10000 to #x10FFFF // -// #xA -// -// #xD -// -// #x20 to #xD7FF -// -// #xE000 to #xFFFD -// -// #x10000 to #x10FFFF -// -// For more information, see RFC1321 (https://www.ietf.org/rfc/rfc1321.txt). -// If you send any characters that aren't included in this list, your request -// is rejected. +// Any characters not included in this list will be rejected. For more information, +// see the W3C specification for characters (http://www.w3.org/TR/REC-xml/#charsets). // // 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 @@ -1276,8 +1477,23 @@ func (c *SQS) SendMessageRequest(input *SendMessageInput) (req *request.Request, // Please also see https://docs.aws.amazon.com/goto/WebAPI/sqs-2012-11-05/SendMessage func (c *SQS) SendMessage(input *SendMessageInput) (*SendMessageOutput, error) { req, out := c.SendMessageRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// SendMessageWithContext is the same as SendMessage with the addition of +// the ability to pass a context and additional request options. +// +// See SendMessage 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 *SQS) SendMessageWithContext(ctx aws.Context, input *SendMessageInput, opts ...request.Option) (*SendMessageOutput, error) { + req, out := c.SendMessageRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opSendMessageBatch = "SendMessageBatch" @@ -1338,24 +1554,13 @@ func (c *SQS) SendMessageBatchRequest(input *SendMessageBatchInput) (req *reques // size (the sum of the individual lengths of all of the batched messages) are // both 256 KB (262,144 bytes). // -// The following list shows the characters (in Unicode) that are allowed in -// your message, according to the W3C XML specification: +// A message can include only XML, JSON, and unformatted text. The following +// Unicode characters are allowed: // -// #x9 +// #x9 | #xA | #xD | #x20 to #xD7FF | #xE000 to #xFFFD | #x10000 to #x10FFFF // -// #xA -// -// #xD -// -// #x20 to #xD7FF -// -// #xE000 to #xFFFD -// -// #x10000 to #x10FFFF -// -// For more information, see RFC1321 (https://www.ietf.org/rfc/rfc1321.txt). -// If you send any characters that aren't included in this list, your request -// is rejected. +// Any characters not included in this list will be rejected. For more information, +// see the W3C specification for characters (http://www.w3.org/TR/REC-xml/#charsets). // // If you don't specify the DelaySeconds parameter for an entry, Amazon SQS // uses the default value for the queue. @@ -1397,8 +1602,23 @@ func (c *SQS) SendMessageBatchRequest(input *SendMessageBatchInput) (req *reques // Please also see https://docs.aws.amazon.com/goto/WebAPI/sqs-2012-11-05/SendMessageBatch func (c *SQS) SendMessageBatch(input *SendMessageBatchInput) (*SendMessageBatchOutput, error) { req, out := c.SendMessageBatchRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// SendMessageBatchWithContext is the same as SendMessageBatch with the addition of +// the ability to pass a context and additional request options. +// +// See SendMessageBatch 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 *SQS) SendMessageBatchWithContext(ctx aws.Context, input *SendMessageBatchInput, opts ...request.Option) (*SendMessageBatchOutput, error) { + req, out := c.SendMessageBatchRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opSetQueueAttributes = "SetQueueAttributes" @@ -1471,8 +1691,23 @@ func (c *SQS) SetQueueAttributesRequest(input *SetQueueAttributesInput) (req *re // Please also see https://docs.aws.amazon.com/goto/WebAPI/sqs-2012-11-05/SetQueueAttributes func (c *SQS) SetQueueAttributes(input *SetQueueAttributesInput) (*SetQueueAttributesOutput, error) { req, out := c.SetQueueAttributesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// SetQueueAttributesWithContext is the same as SetQueueAttributes with the addition of +// the ability to pass a context and additional request options. +// +// See SetQueueAttributes 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 *SQS) SetQueueAttributesWithContext(ctx aws.Context, input *SetQueueAttributesInput, opts ...request.Option) (*SetQueueAttributesOutput, error) { + req, out := c.SetQueueAttributesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // Please also see https://docs.aws.amazon.com/goto/WebAPI/sqs-2012-11-05/AddPermissionRequest @@ -1964,26 +2199,26 @@ type CreateQueueInput struct { // The following lists the names, descriptions, and values of the special request // parameters that the CreateQueue action uses: // - // * DelaySeconds - The number of seconds for which the delivery of all messages - // in the queue is delayed. Valid values: An integer from 0 to 900 seconds - // (15 minutes). The default is 0 (zero). + // * DelaySeconds - The length of time, in seconds, for which the delivery + // of all messages in the queue is delayed. Valid values: An integer from + // 0 to 900 seconds (15 minutes). The default is 0 (zero). // // * MaximumMessageSize - The limit of how many bytes a message can contain // before Amazon SQS rejects it. Valid values: An integer from 1,024 bytes // (1 KiB) to 262,144 bytes (256 KiB). The default is 262,144 (256 KiB). // // - // * MessageRetentionPeriod - The number of seconds for which Amazon SQS - // retains a message. Valid values: An integer from 60 seconds (1 minute) + // * MessageRetentionPeriod - The length of time, in seconds, for which Amazon + // SQS retains a message. Valid values: An integer from 60 seconds (1 minute) // to 1,209,600 seconds (14 days). The default is 345,600 (4 days). // // * Policy - The queue's policy. A valid AWS policy. For more information // about policy structure, see Overview of AWS IAM Policies (http://docs.aws.amazon.com/IAM/latest/UserGuide/PoliciesOverview.html) // in the Amazon IAM User Guide. // - // * ReceiveMessageWaitTimeSeconds - The number of seconds for which a ReceiveMessage - // action waits for a message to arrive. Valid values: An integer from 0 - // to 20 (seconds). The default is 0 (zero). + // * ReceiveMessageWaitTimeSeconds - The length of time, in seconds, for + // which a ReceiveMessage action waits for a message to arrive. Valid values: + // An integer from 0 to 20 (seconds). The default is 0 (zero). // // * RedrivePolicy - The parameters for the dead letter queue functionality // of the source queue. For more information about the redrive policy and @@ -1998,17 +2233,38 @@ type CreateQueueInput struct { // about the visibility timeout, see Visibility Timeout (http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-visibility-timeout.html) // in the Amazon SQS Developer Guide. // + // The following attributes apply only to server-side-encryption (http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-server-side-encryption.html): + // + // * KmsMasterKeyId - The ID of an AWS-managed customer master key (CMK) + // for Amazon SQS or a custom CMK. For more information, see Key Terms (http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-server-side-encryption.html#sqs-sse-key-terms). + // While the alias of the AWS-managed CMK for Amazon SQS is always alias/aws/sqs, + // the alias of a custom CMK can, for example, be alias/aws/sqs. For more + // examples, see KeyId (http://docs.aws.amazon.com/kms/latest/APIReference/API_DescribeKey.html#API_DescribeKey_RequestParameters) + // in the AWS Key Management Service API Reference. + // + // * KmsDataKeyReusePeriodSeconds - The length of time, in seconds, for which + // Amazon SQS can reuse a data key (http://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#data-keys) + // to encrypt or decrypt messages before calling AWS KMS again. An integer + // representing seconds, between 60 seconds (1 minute) and 86,400 seconds + // (24 hours). The default is 300 (5 minutes). A shorter time period provides + // better security but results in more calls to KMS which incur charges after + // Free Tier. For more information, see How Does the Data Key Reuse Period + // Work? (http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-server-side-encryption.html#sqs-how-does-the-data-key-reuse-period-work). + // + // // The following attributes apply only to FIFO (first-in-first-out) queues (http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/FIFO-queues.html): // - // * FifoQueue - Designates a queue as FIFO. You can provide this attribute - // only during queue creation. You can't change it for an existing queue. - // When you set this attribute, you must provide a MessageGroupId explicitly. + // * FifoQueue - Designates a queue as FIFO. Valid values: true, false. You + // can provide this attribute only during queue creation. You can't change + // it for an existing queue. When you set this attribute, you must also provide + // the MessageGroupId for your messages explicitly. // // For more information, see FIFO Queue Logic (http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/FIFO-queues.html#FIFO-queues-understanding-logic) // in the Amazon SQS Developer Guide. // - // * ContentBasedDeduplication - Enables content-based deduplication. For - // more information, see Exactly-Once Processing (http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/FIFO-queues.html#FIFO-queues-exactly-once-processing) + // * ContentBasedDeduplication - Enables content-based deduplication. Valid + // values: true, false. For more information, see Exactly-Once Processing + // (http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/FIFO-queues.html#FIFO-queues-exactly-once-processing) // in the Amazon SQS Developer Guide. // // Every message must have a unique MessageDeduplicationId, @@ -2030,9 +2286,6 @@ type CreateQueueInput struct { // sent within the deduplication interval are treated as duplicates and only // one copy of the message is delivered. // - // You can also use ContentBasedDeduplication for messages with identical content - // to be treated as duplicates. - // // If you send one message with ContentBasedDeduplication enabled and then another // message with a MessageDeduplicationId that is the same as the one generated // for the first MessageDeduplicationId, the two messages are treated as @@ -2481,15 +2734,15 @@ type GetQueueAttributesInput struct { // * MaximumMessageSize - Returns the limit of how many bytes a message can // contain before Amazon SQS rejects it. // - // * MessageRetentionPeriod - Returns the number of seconds for which Amazon - // SQS retains a message. + // * MessageRetentionPeriod - Returns the length of time, in seconds, for + // which Amazon SQS retains a message. // // * Policy - Returns the policy of the queue. // // * QueueArn - Returns the Amazon resource name (ARN) of the queue. // - // * ReceiveMessageWaitTimeSeconds - Returns the number of seconds for which - // the ReceiveMessage action waits for a message to arrive. + // * ReceiveMessageWaitTimeSeconds - Returns the length of time, in seconds, + // for which the ReceiveMessage action waits for a message to arrive. // // * RedrivePolicy - Returns the parameters for dead letter queue functionality // of the source queue. For more information about the redrive policy and @@ -2501,12 +2754,26 @@ type GetQueueAttributesInput struct { // (http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-visibility-timeout.html) // in the Amazon SQS Developer Guide. // + // The following attributes apply only to server-side-encryption (http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-server-side-encryption.html): + // + // * KmsMasterKeyId - Returns the ID of an AWS-managed customer master key + // (CMK) for Amazon SQS or a custom CMK. For more information, see Key Terms + // (http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-server-side-encryption.html#sqs-sse-key-terms). + // + // + // * KmsDataKeyReusePeriodSeconds - Returns the length of time, in seconds, + // for which Amazon SQS can reuse a data key to encrypt or decrypt messages + // before calling AWS KMS again. + // // The following attributes apply only to FIFO (first-in-first-out) queues (http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/FIFO-queues.html): // // * FifoQueue - Returns whether the queue is FIFO. For more information, // see FIFO Queue Logic (http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/FIFO-queues.html#FIFO-queues-understanding-logic) // in the Amazon SQS Developer Guide. // + // To determine whether a queue is FIFO (http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/FIFO-queues.html), + // you can check whether QueueName ends with the .fifo suffix. + // // * ContentBasedDeduplication - Returns whether content-based deduplication // is enabled for the queue. For more information, see Exactly-Once Processing // (http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/FIFO-queues.html#FIFO-queues-exactly-once-processing) @@ -2799,7 +3066,7 @@ type Message struct { // An MD5 digest of the non-URL-encoded message attribute string. You can use // this attribute to verify that Amazon SQS received the message correctly. // Amazon SQS URL-decodes the message before creating the MD5 digest. For information - // on MD5, see RFC1321 (https://www.ietf.org/rfc/rfc1321.txt). + // about MD5, see RFC1321 (https://www.ietf.org/rfc/rfc1321.txt). MD5OfMessageAttributes *string `type:"string"` // Each message attribute consists of a Name, Type, and Value. For more information, @@ -3454,10 +3721,10 @@ func (s *SendMessageBatchOutput) SetSuccessful(v []*SendMessageBatchResultEntry) type SendMessageBatchRequestEntry struct { _ struct{} `type:"structure"` - // The number of seconds for which a specific message is delayed. Valid values: - // 0 to 900. Maximum: 15 minutes. Messages with a positive DelaySeconds value - // become available for processing after the delay period is finished. If you - // don't specify a value, the default value for the queue is applied. + // The length of time, in seconds, for which a specific message is delayed. + // Valid values: 0 to 900. Maximum: 15 minutes. Messages with a positive DelaySeconds + // value become available for processing after the delay period is finished. + // If you don't specify a value, the default value for the queue is applied. // // When you set FifoQueue, you can't set DelaySeconds per message. You can set // this parameter only on a queue level. @@ -3508,9 +3775,6 @@ type SendMessageBatchRequestEntry struct { // content sent within the deduplication interval are treated as duplicates // and only one copy of the message is delivered. // - // * You can also use ContentBasedDeduplication for messages with identical - // content to be treated as duplicates. - // // * If you send one message with ContentBasedDeduplication enabled and then // another message with a MessageDeduplicationId that is the same as the // one generated for the first MessageDeduplicationId, the two messages are @@ -3554,6 +3818,9 @@ type SendMessageBatchRequestEntry struct { // For best practices of using MessageGroupId, see Using the MessageGroupId // Property (http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/FIFO-queue-recommendations.html#using-messagegroupid-property) // in the Amazon Simple Queue Service Developer Guide. + // + // MessageGroupId is required for FIFO queues. You can't use it for Standard + // queues. MessageGroupId *string `type:"string"` } @@ -3642,13 +3909,13 @@ type SendMessageBatchResultEntry struct { // An MD5 digest of the non-URL-encoded message attribute string. You can use // this attribute to verify that Amazon SQS received the message correctly. // Amazon SQS URL-decodes the message before creating the MD5 digest. For information - // on MD5, see RFC1321 (https://www.ietf.org/rfc/rfc1321.txt). + // about MD5, see RFC1321 (https://www.ietf.org/rfc/rfc1321.txt). MD5OfMessageAttributes *string `type:"string"` // An MD5 digest of the non-URL-encoded message attribute string. You can use // this attribute to verify that Amazon SQS received the message correctly. // Amazon SQS URL-decodes the message before creating the MD5 digest. For information - // on MD5, see RFC1321 (https://www.ietf.org/rfc/rfc1321.txt). + // about MD5, see RFC1321 (https://www.ietf.org/rfc/rfc1321.txt). // // MD5OfMessageBody is a required field MD5OfMessageBody *string `type:"string" required:"true"` @@ -3660,7 +3927,7 @@ type SendMessageBatchResultEntry struct { // This parameter applies only to FIFO (first-in-first-out) queues. // - // A large, non-consecutive number that Amazon SQS assigns to each message. + // The large, non-consecutive number that Amazon SQS assigns to each message. // // The length of SequenceNumber is 128 bits. As SequenceNumber continues to // increase for a particular MessageGroupId. @@ -3711,10 +3978,10 @@ func (s *SendMessageBatchResultEntry) SetSequenceNumber(v string) *SendMessageBa type SendMessageInput struct { _ struct{} `type:"structure"` - // The number of seconds to delay a specific message. Valid values: 0 to 900. - // Maximum: 15 minutes. Messages with a positive DelaySeconds value become available - // for processing after the delay period is finished. If you don't specify a - // value, the default value for the queue applies. + // The length of time, in seconds, for which to delay a specific message. Valid + // values: 0 to 900. Maximum: 15 minutes. Messages with a positive DelaySeconds + // value become available for processing after the delay period is finished. + // If you don't specify a value, the default value for the queue applies. // // When you set FifoQueue, you can't set DelaySeconds per message. You can set // this parameter only on a queue level. @@ -3727,24 +3994,13 @@ type SendMessageInput struct { // The message to send. The maximum string size is 256 KB. // - // The following list shows the characters (in Unicode) that are allowed in - // your message, according to the W3C XML specification: + // A message can include only XML, JSON, and unformatted text. The following + // Unicode characters are allowed: // - // #x9 + // #x9 | #xA | #xD | #x20 to #xD7FF | #xE000 to #xFFFD | #x10000 to #x10FFFF // - // #xA - // - // #xD - // - // #x20 to #xD7FF - // - // #xE000 to #xFFFD - // - // #x10000 to #x10FFFF - // - // For more information, see RFC1321 (https://www.ietf.org/rfc/rfc1321.txt). - // If you send any characters that aren't included in this list, your request - // is rejected. + // Any characters not included in this list will be rejected. For more information, + // see the W3C specification for characters (http://www.w3.org/TR/REC-xml/#charsets). // // MessageBody is a required field MessageBody *string `type:"string" required:"true"` @@ -3777,9 +4033,6 @@ type SendMessageInput struct { // content sent within the deduplication interval are treated as duplicates // and only one copy of the message is delivered. // - // * You can also use ContentBasedDeduplication for messages with identical - // content to be treated as duplicates. - // // * If you send one message with ContentBasedDeduplication enabled and then // another message with a MessageDeduplicationId that is the same as the // one generated for the first MessageDeduplicationId, the two messages are @@ -3823,6 +4076,9 @@ type SendMessageInput struct { // For best practices of using MessageGroupId, see Using the MessageGroupId // Property (http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/FIFO-queue-recommendations.html#using-messagegroupid-property) // in the Amazon Simple Queue Service Developer Guide. + // + // MessageGroupId is required for FIFO queues. You can't use it for Standard + // queues. MessageGroupId *string `type:"string"` // The URL of the Amazon SQS queue to which a message is sent. @@ -3913,13 +4169,13 @@ type SendMessageOutput struct { // An MD5 digest of the non-URL-encoded message attribute string. You can use // this attribute to verify that Amazon SQS received the message correctly. // Amazon SQS URL-decodes the message before creating the MD5 digest. For information - // on MD5, see RFC1321 (https://www.ietf.org/rfc/rfc1321.txt). + // about MD5, see RFC1321 (https://www.ietf.org/rfc/rfc1321.txt). MD5OfMessageAttributes *string `type:"string"` // An MD5 digest of the non-URL-encoded message attribute string. You can use // this attribute to verify that Amazon SQS received the message correctly. // Amazon SQS URL-decodes the message before creating the MD5 digest. For information - // on MD5, see RFC1321 (https://www.ietf.org/rfc/rfc1321.txt). + // about MD5, see RFC1321 (https://www.ietf.org/rfc/rfc1321.txt). MD5OfMessageBody *string `type:"string"` // An attribute containing the MessageId of the message sent to the queue. For @@ -3929,7 +4185,7 @@ type SendMessageOutput struct { // This parameter applies only to FIFO (first-in-first-out) queues. // - // A large, non-consecutive number that Amazon SQS assigns to each message. + // The large, non-consecutive number that Amazon SQS assigns to each message. // // The length of SequenceNumber is 128 bits. SequenceNumber continues to increase // for a particular MessageGroupId. @@ -3979,27 +4235,27 @@ type SetQueueAttributesInput struct { // The following lists the names, descriptions, and values of the special request // parameters that the SetQueueAttributes action uses: // - // * DelaySeconds - The number of seconds for which the delivery of all messages - // in the queue is delayed. Valid values: An integer from 0 to 900 (15 minutes). - // The default is 0 (zero). + // * DelaySeconds - The length of time, in seconds, for which the delivery + // of all messages in the queue is delayed. Valid values: An integer from + // 0 to 900 (15 minutes). The default is 0 (zero). // // * MaximumMessageSize - The limit of how many bytes a message can contain // before Amazon SQS rejects it. Valid values: An integer from 1,024 bytes // (1 KiB) up to 262,144 bytes (256 KiB). The default is 262,144 (256 KiB). // // - // * MessageRetentionPeriod - The number of seconds for which Amazon SQS - // retains a message. Valid values: An integer representing seconds, from - // 60 (1 minute) to 1,209,600 (14 days). The default is 345,600 (4 days). + // * MessageRetentionPeriod - The length of time, in seconds, for which Amazon + // SQS retains a message. Valid values: An integer representing seconds, + // from 60 (1 minute) to 1,209,600 (14 days). The default is 345,600 (4 days). // // // * Policy - The queue's policy. A valid AWS policy. For more information // about policy structure, see Overview of AWS IAM Policies (http://docs.aws.amazon.com/IAM/latest/UserGuide/PoliciesOverview.html) // in the Amazon IAM User Guide. // - // * ReceiveMessageWaitTimeSeconds - The number of seconds for which a ReceiveMessage - // action waits for a message to arrive. Valid values: an integer from 0 - // to 20 (seconds). The default is 0. + // * ReceiveMessageWaitTimeSeconds - The length of time, in seconds, for + // which a ReceiveMessage action waits for a message to arrive. Valid values: + // an integer from 0 to 20 (seconds). The default is 0. // // * RedrivePolicy - The parameters for the dead letter queue functionality // of the source queue. For more information about the redrive policy and @@ -4014,6 +4270,25 @@ type SetQueueAttributesInput struct { // about the visibility timeout, see Visibility Timeout (http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-visibility-timeout.html) // in the Amazon SQS Developer Guide. // + // The following attributes apply only to server-side-encryption (http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-server-side-encryption.html): + // + // * KmsMasterKeyId - The ID of an AWS-managed customer master key (CMK) + // for Amazon SQS or a custom CMK. For more information, see Key Terms (http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-server-side-encryption.html#sqs-sse-key-terms). + // While the alias of the AWS-managed CMK for Amazon SQS is always alias/aws/sqs, + // the alias of a custom CMK can, for example, be alias/aws/sqs. For more + // examples, see KeyId (http://docs.aws.amazon.com/kms/latest/APIReference/API_DescribeKey.html#API_DescribeKey_RequestParameters) + // in the AWS Key Management Service API Reference. + // + // * KmsDataKeyReusePeriodSeconds - The length of time, in seconds, for which + // Amazon SQS can reuse a data key (http://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#data-keys) + // to encrypt or decrypt messages before calling AWS KMS again. An integer + // representing seconds, between 60 seconds (1 minute) and 86,400 seconds + // (24 hours). The default is 300 (5 minutes). A shorter time period provides + // better security but results in more calls to KMS which incur charges after + // Free Tier. For more information, see How Does the Data Key Reuse Period + // Work? (http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-server-side-encryption.html#sqs-how-does-the-data-key-reuse-period-work). + // + // // The following attribute applies only to FIFO (first-in-first-out) queues // (http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/FIFO-queues.html): // @@ -4040,9 +4315,6 @@ type SetQueueAttributesInput struct { // sent within the deduplication interval are treated as duplicates and only // one copy of the message is delivered. // - // You can also use ContentBasedDeduplication for messages with identical content - // to be treated as duplicates. - // // If you send one message with ContentBasedDeduplication enabled and then another // message with a MessageDeduplicationId that is the same as the one generated // for the first MessageDeduplicationId, the two messages are treated as @@ -4197,4 +4469,10 @@ const ( // QueueAttributeNameContentBasedDeduplication is a QueueAttributeName enum value QueueAttributeNameContentBasedDeduplication = "ContentBasedDeduplication" + + // QueueAttributeNameKmsMasterKeyId is a QueueAttributeName enum value + QueueAttributeNameKmsMasterKeyId = "KmsMasterKeyId" + + // QueueAttributeNameKmsDataKeyReusePeriodSeconds is a QueueAttributeName enum value + QueueAttributeNameKmsDataKeyReusePeriodSeconds = "KmsDataKeyReusePeriodSeconds" ) diff --git a/vendor/github.com/aws/aws-sdk-go/service/sqs/doc.go b/vendor/github.com/aws/aws-sdk-go/service/sqs/doc.go new file mode 100644 index 000000000..24189f539 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/service/sqs/doc.go @@ -0,0 +1,115 @@ +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. + +// Package sqs provides the client and types for making API +// requests to Amazon Simple Queue Service. +// +// Welcome to the Amazon Simple Queue Service API Reference. +// +// Amazon Simple Queue Service (Amazon SQS) is a reliable, highly-scalable hosted +// queue for storing messages as they travel between applications or microservices. +// Amazon SQS moves data between distributed application components and helps +// you decouple these components. +// +// Standard queues (http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/standard-queues.html) +// are available in all regions. FIFO queues (http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/FIFO-queues.html) +// are available in US West (Oregon) and US East (Ohio). +// +// You can use AWS SDKs (http://aws.amazon.com/tools/#sdk) to access Amazon +// SQS using your favorite programming language. The SDKs perform tasks such +// as the following automatically: +// +// * Cryptographically sign your service requests +// +// * Retry requests +// +// * Handle error responses +// +// Additional Information +// +// * Amazon SQS Product Page (http://aws.amazon.com/sqs/) +// +// * Amazon SQS Developer Guide +// +// Making API Requests (http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/MakingRequestsArticle.html) +// +// Using Amazon SQS Message Attributes (http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-message-attributes.html) +// +// Using Amazon SQS Dead Letter Queues (http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-dead-letter-queues.html) +// +// * Amazon Web Services General Reference +// +// Regions and Endpoints (http://docs.aws.amazon.com/general/latest/gr/rande.html#sqs_region) +// +// See https://docs.aws.amazon.com/goto/WebAPI/sqs-2012-11-05 for more information on this service. +// +// See sqs package documentation for more information. +// https://docs.aws.amazon.com/sdk-for-go/api/service/sqs/ +// +// Using the Client +// +// To use the client for Amazon Simple Queue Service you will first need +// to create a new instance of it. +// +// When creating a client for an AWS service you'll first need to have a Session +// already created. The Session provides configuration that can be shared +// between multiple service clients. Additional configuration can be applied to +// the Session and service's client when they are constructed. The aws package's +// Config type contains several fields such as Region for the AWS Region the +// client should make API requests too. The optional Config value can be provided +// as the variadic argument for Sessions and client creation. +// +// Once the service's client is created you can use it to make API requests the +// AWS service. These clients are safe to use concurrently. +// +// // Create a session to share configuration, and load external configuration. +// sess := session.Must(session.NewSession()) +// +// // Create the service's client with the session. +// svc := sqs.New(sess) +// +// See the SDK's documentation for more information on how to use service clients. +// https://docs.aws.amazon.com/sdk-for-go/api/ +// +// See aws package's Config type for more information on configuration options. +// https://docs.aws.amazon.com/sdk-for-go/api/aws/#Config +// +// See the Amazon Simple Queue Service client SQS for more +// information on creating the service's client. +// https://docs.aws.amazon.com/sdk-for-go/api/service/sqs/#New +// +// Once the client is created you can make an API request to the service. +// Each API method takes a input parameter, and returns the service response +// and an error. +// +// The API method will document which error codes the service can be returned +// by the operation if the service models the API operation's errors. These +// errors will also be available as const strings prefixed with "ErrCode". +// +// result, err := svc.AddPermission(params) +// if err != nil { +// // Cast err to awserr.Error to handle specific error codes. +// aerr, ok := err.(awserr.Error) +// if ok && aerr.Code() == { +// // Specific error code handling +// } +// return err +// } +// +// fmt.Println("AddPermission result:") +// fmt.Println(result) +// +// Using the Client with Context +// +// The service's client also provides methods to make API requests with a Context +// value. This allows you to control the timeout, and cancellation of pending +// requests. These methods also take request Option as variadic parameter to apply +// additional configuration to the API request. +// +// ctx := context.Background() +// +// result, err := svc.AddPermissionWithContext(ctx, params) +// +// See the request package documentation for more information on using Context pattern +// with the SDK. +// https://docs.aws.amazon.com/sdk-for-go/api/aws/request/ +package sqs diff --git a/vendor/github.com/aws/aws-sdk-go/service/sqs/errors.go b/vendor/github.com/aws/aws-sdk-go/service/sqs/errors.go index d4f394e0e..722867d32 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/sqs/errors.go +++ b/vendor/github.com/aws/aws-sdk-go/service/sqs/errors.go @@ -1,4 +1,4 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. package sqs diff --git a/vendor/github.com/aws/aws-sdk-go/service/sqs/service.go b/vendor/github.com/aws/aws-sdk-go/service/sqs/service.go index 7df1fbc7e..50b5f4b80 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/sqs/service.go +++ b/vendor/github.com/aws/aws-sdk-go/service/sqs/service.go @@ -1,4 +1,4 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. package sqs @@ -11,45 +11,12 @@ import ( "github.com/aws/aws-sdk-go/private/protocol/query" ) -// Welcome to the Amazon Simple Queue Service API Reference. +// SQS provides the API operation methods for making requests to +// Amazon Simple Queue Service. See this package's package overview docs +// for details on the service. // -// Amazon Simple Queue Service (Amazon SQS) is a reliable, highly-scalable hosted -// queue for storing messages as they travel between applications or microservices. -// Amazon SQS moves data between distributed application components and helps -// you decouple these components. -// -// Standard queues (http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/standard-queues.html) -// are available in all regions. FIFO queues (http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/FIFO-queues.html) -// are available in US West (Oregon) and US East (Ohio). -// -// You can use AWS SDKs (http://aws.amazon.com/tools/#sdk) to access Amazon -// SQS using your favorite programming language. The SDKs perform tasks such -// as the following automatically: -// -// * Cryptographically sign your service requests -// -// * Retry requests -// -// * Handle error responses -// -// Additional Information -// -// * Amazon SQS Product Page (http://aws.amazon.com/sqs/) -// -// * Amazon SQS Developer Guide -// -// Making API Requests (http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/MakingRequestsArticle.html) -// -// Using Amazon SQS Message Attributes (http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-message-attributes.html) -// -// Using Amazon SQS Dead Letter Queues (http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-dead-letter-queues.html) -// -// * Amazon Web Services General Reference -// -// Regions and Endpoints (http://docs.aws.amazon.com/general/latest/gr/rande.html#sqs_region) -// The service client's operations are safe to be used concurrently. -// It is not safe to mutate any of the client's properties though. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/sqs-2012-11-05 +// SQS methods are safe to use concurrently. It is not safe to +// modify mutate any of the struct's properties though. type SQS struct { *client.Client } 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 56bbee8ee..f0170b780 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 @@ -1,12 +1,12 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. -// Package ssm provides a client for Amazon Simple Systems Manager (SSM). package ssm import ( "fmt" "time" + "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awsutil" "github.com/aws/aws-sdk-go/aws/request" ) @@ -101,8 +101,23 @@ func (c *SSM) AddTagsToResourceRequest(input *AddTagsToResourceInput) (req *requ // Please also see https://docs.aws.amazon.com/goto/WebAPI/ssm-2014-11-06/AddTagsToResource func (c *SSM) AddTagsToResource(input *AddTagsToResourceInput) (*AddTagsToResourceOutput, error) { req, out := c.AddTagsToResourceRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// AddTagsToResourceWithContext is the same as AddTagsToResource with the addition of +// the ability to pass a context and additional request options. +// +// See AddTagsToResource 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 *SSM) AddTagsToResourceWithContext(ctx aws.Context, input *AddTagsToResourceInput, opts ...request.Option) (*AddTagsToResourceOutput, error) { + req, out := c.AddTagsToResourceRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCancelCommand = "CancelCommand" @@ -171,12 +186,12 @@ func (c *SSM) CancelCommandRequest(input *CancelCommandInput) (req *request.Requ // // You do not have permission to access the instance. // -// The SSM agent is not running. On managed instances and Linux instances, verify -// that the SSM agent is running. On EC2 Windows instances, verify that the +// The SSM Agent is not running. On managed instances and Linux instances, verify +// that the SSM Agent is running. On EC2 Windows instances, verify that the // EC2Config service is running. // -// The SSM agent or EC2Config service is not registered to the SSM endpoint. -// Try reinstalling the SSM agent or EC2Config service. +// The SSM Agent or EC2Config service is not registered to the SSM endpoint. +// Try reinstalling the SSM Agent or EC2Config service. // // The instance is not in valid state. Valid states are: Running, Pending, Stopped, // Stopping. Invalid states are: Shutting-down and Terminated. @@ -187,8 +202,23 @@ func (c *SSM) CancelCommandRequest(input *CancelCommandInput) (req *request.Requ // Please also see https://docs.aws.amazon.com/goto/WebAPI/ssm-2014-11-06/CancelCommand func (c *SSM) CancelCommand(input *CancelCommandInput) (*CancelCommandOutput, error) { req, out := c.CancelCommandRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CancelCommandWithContext is the same as CancelCommand with the addition of +// the ability to pass a context and additional request options. +// +// See CancelCommand 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 *SSM) CancelCommandWithContext(ctx aws.Context, input *CancelCommandInput, opts ...request.Option) (*CancelCommandOutput, error) { + req, out := c.CancelCommandRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateActivation = "CreateActivation" @@ -239,10 +269,8 @@ func (c *SSM) CreateActivationRequest(input *CreateActivationInput) (req *reques // Registers your on-premises server or virtual machine with Amazon EC2 so that // you can manage these resources using Run Command. An on-premises server or // virtual machine that has been registered with EC2 is called a managed instance. -// For more information about activations, see Setting Up Managed Instances -// (Linux) (http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/managed-instances.html) -// or Setting Up Managed Instances (Windows) (http://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/managed-instances.html) -// in the Amazon EC2 User Guide. +// For more information about activations, see Setting Up Systems Manager in +// Hybrid Environments (http://docs.aws.amazon.com/systems-manager/latest/userguide/systems-manager-managedinstances.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 @@ -258,8 +286,23 @@ func (c *SSM) CreateActivationRequest(input *CreateActivationInput) (req *reques // Please also see https://docs.aws.amazon.com/goto/WebAPI/ssm-2014-11-06/CreateActivation func (c *SSM) CreateActivation(input *CreateActivationInput) (*CreateActivationOutput, error) { req, out := c.CreateActivationRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateActivationWithContext is the same as CreateActivation with the addition of +// the ability to pass a context and additional request options. +// +// See CreateActivation 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 *SSM) CreateActivationWithContext(ctx aws.Context, input *CreateActivationInput, opts ...request.Option) (*CreateActivationOutput, error) { + req, out := c.CreateActivationRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateAssociation = "CreateAssociation" @@ -307,11 +350,12 @@ func (c *SSM) CreateAssociationRequest(input *CreateAssociationInput) (req *requ // CreateAssociation API operation for Amazon Simple Systems Manager (SSM). // -// Associates the specified SSM document with the specified instances or targets. +// Associates the specified Systems Manager document with the specified instances +// or targets. // -// When you associate an SSM document with one or more instances using instance -// IDs or tags, the SSM agent running on the instance processes the document -// and configures the instance as specified. +// When you associate a document with one or more instances using instance IDs +// or tags, the 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 throws the AssociationAlreadyExists exception. @@ -344,19 +388,19 @@ func (c *SSM) CreateAssociationRequest(input *CreateAssociationInput) (req *requ // // You do not have permission to access the instance. // -// The SSM agent is not running. On managed instances and Linux instances, verify -// that the SSM agent is running. On EC2 Windows instances, verify that the +// The SSM Agent is not running. On managed instances and Linux instances, verify +// that the SSM Agent is running. On EC2 Windows instances, verify that the // EC2Config service is running. // -// The SSM agent or EC2Config service is not registered to the SSM endpoint. -// Try reinstalling the SSM agent or EC2Config service. +// The SSM Agent or EC2Config service is not registered to the SSM endpoint. +// Try reinstalling the SSM Agent or EC2Config service. // // The instance is not in valid state. Valid states are: Running, Pending, Stopped, // Stopping. Invalid states are: Shutting-down and Terminated. // // * ErrCodeUnsupportedPlatformType "UnsupportedPlatformType" // The document does not support the platform type of the given instance ID(s). -// For example, you sent an SSM document for a Windows instance to a Linux instance. +// For example, you sent an document for a Windows instance to a Linux instance. // // * ErrCodeInvalidOutputLocation "InvalidOutputLocation" // The output location is not valid or does not exist. @@ -375,8 +419,23 @@ func (c *SSM) CreateAssociationRequest(input *CreateAssociationInput) (req *requ // Please also see https://docs.aws.amazon.com/goto/WebAPI/ssm-2014-11-06/CreateAssociation func (c *SSM) CreateAssociation(input *CreateAssociationInput) (*CreateAssociationOutput, error) { req, out := c.CreateAssociationRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateAssociationWithContext is the same as CreateAssociation with the addition of +// the ability to pass a context and additional request options. +// +// See CreateAssociation 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 *SSM) CreateAssociationWithContext(ctx aws.Context, input *CreateAssociationInput, opts ...request.Option) (*CreateAssociationOutput, error) { + req, out := c.CreateAssociationRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateAssociationBatch = "CreateAssociationBatch" @@ -424,11 +483,12 @@ func (c *SSM) CreateAssociationBatchRequest(input *CreateAssociationBatchInput) // CreateAssociationBatch API operation for Amazon Simple Systems Manager (SSM). // -// Associates the specified SSM document with the specified instances or targets. +// Associates the specified Systems Manager document with the specified instances +// or targets. // -// When you associate an SSM document with one or more instances using instance -// IDs or tags, the SSM agent running on the instance processes the document -// and configures the instance as specified. +// When you associate a document with one or more instances using instance IDs +// or tags, the 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 throws the AssociationAlreadyExists exception. @@ -455,12 +515,12 @@ func (c *SSM) CreateAssociationBatchRequest(input *CreateAssociationBatchInput) // // You do not have permission to access the instance. // -// The SSM agent is not running. On managed instances and Linux instances, verify -// that the SSM agent is running. On EC2 Windows instances, verify that the +// The SSM Agent is not running. On managed instances and Linux instances, verify +// that the SSM Agent is running. On EC2 Windows instances, verify that the // EC2Config service is running. // -// The SSM agent or EC2Config service is not registered to the SSM endpoint. -// Try reinstalling the SSM agent or EC2Config service. +// The SSM Agent or EC2Config service is not registered to the SSM endpoint. +// Try reinstalling the SSM Agent or EC2Config service. // // The instance is not in valid state. Valid states are: Running, Pending, Stopped, // Stopping. Invalid states are: Shutting-down and Terminated. @@ -477,7 +537,7 @@ func (c *SSM) CreateAssociationBatchRequest(input *CreateAssociationBatchInput) // // * ErrCodeUnsupportedPlatformType "UnsupportedPlatformType" // The document does not support the platform type of the given instance ID(s). -// For example, you sent an SSM document for a Windows instance to a Linux instance. +// For example, you sent an document for a Windows instance to a Linux instance. // // * ErrCodeInvalidOutputLocation "InvalidOutputLocation" // The output location is not valid or does not exist. @@ -492,8 +552,23 @@ func (c *SSM) CreateAssociationBatchRequest(input *CreateAssociationBatchInput) // Please also see https://docs.aws.amazon.com/goto/WebAPI/ssm-2014-11-06/CreateAssociationBatch func (c *SSM) CreateAssociationBatch(input *CreateAssociationBatchInput) (*CreateAssociationBatchOutput, error) { req, out := c.CreateAssociationBatchRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateAssociationBatchWithContext is the same as CreateAssociationBatch with the addition of +// the ability to pass a context and additional request options. +// +// See CreateAssociationBatch 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 *SSM) CreateAssociationBatchWithContext(ctx aws.Context, input *CreateAssociationBatchInput, opts ...request.Option) (*CreateAssociationBatchOutput, error) { + req, out := c.CreateAssociationBatchRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateDocument = "CreateDocument" @@ -541,10 +616,10 @@ func (c *SSM) CreateDocumentRequest(input *CreateDocumentInput) (req *request.Re // CreateDocument API operation for Amazon Simple Systems Manager (SSM). // -// Creates an SSM document. +// Creates a Systems Manager document. // -// After you create an SSM document, you can use CreateAssociation to associate -// it with one or more running instances. +// After you create a document, you can use CreateAssociation to associate it +// with one or more running 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 @@ -555,16 +630,16 @@ func (c *SSM) CreateDocumentRequest(input *CreateDocumentInput) (req *request.Re // // Returned Error Codes: // * ErrCodeDocumentAlreadyExists "DocumentAlreadyExists" -// The specified SSM document already exists. +// The specified document already exists. // // * ErrCodeMaxDocumentSizeExceeded "MaxDocumentSizeExceeded" -// The size limit of an SSM document is 64 KB. +// The size limit of a document is 64 KB. // // * ErrCodeInternalServerError "InternalServerError" // An error occurred on the server side. // // * ErrCodeInvalidDocumentContent "InvalidDocumentContent" -// The content for the SSM document is not valid. +// The content for the document is not valid. // // * ErrCodeDocumentLimitExceeded "DocumentLimitExceeded" // You can have at most 200 active SSM documents. @@ -575,8 +650,23 @@ func (c *SSM) CreateDocumentRequest(input *CreateDocumentInput) (req *request.Re // Please also see https://docs.aws.amazon.com/goto/WebAPI/ssm-2014-11-06/CreateDocument func (c *SSM) CreateDocument(input *CreateDocumentInput) (*CreateDocumentOutput, error) { req, out := c.CreateDocumentRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateDocumentWithContext is the same as CreateDocument with the addition of +// the ability to pass a context and additional request options. +// +// See CreateDocument 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 *SSM) CreateDocumentWithContext(ctx aws.Context, input *CreateDocumentInput, opts ...request.Option) (*CreateDocumentOutput, error) { + req, out := c.CreateDocumentRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateMaintenanceWindow = "CreateMaintenanceWindow" @@ -648,8 +738,23 @@ func (c *SSM) CreateMaintenanceWindowRequest(input *CreateMaintenanceWindowInput // Please also see https://docs.aws.amazon.com/goto/WebAPI/ssm-2014-11-06/CreateMaintenanceWindow func (c *SSM) CreateMaintenanceWindow(input *CreateMaintenanceWindowInput) (*CreateMaintenanceWindowOutput, error) { req, out := c.CreateMaintenanceWindowRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateMaintenanceWindowWithContext is the same as CreateMaintenanceWindow with the addition of +// the ability to pass a context and additional request options. +// +// See CreateMaintenanceWindow 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 *SSM) CreateMaintenanceWindowWithContext(ctx aws.Context, input *CreateMaintenanceWindowInput, opts ...request.Option) (*CreateMaintenanceWindowOutput, error) { + req, out := c.CreateMaintenanceWindowRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreatePatchBaseline = "CreatePatchBaseline" @@ -721,8 +826,23 @@ func (c *SSM) CreatePatchBaselineRequest(input *CreatePatchBaselineInput) (req * // Please also see https://docs.aws.amazon.com/goto/WebAPI/ssm-2014-11-06/CreatePatchBaseline func (c *SSM) CreatePatchBaseline(input *CreatePatchBaselineInput) (*CreatePatchBaselineOutput, error) { req, out := c.CreatePatchBaselineRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreatePatchBaselineWithContext is the same as CreatePatchBaseline with the addition of +// the ability to pass a context and additional request options. +// +// See CreatePatchBaseline 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 *SSM) CreatePatchBaselineWithContext(ctx aws.Context, input *CreatePatchBaselineInput, opts ...request.Option) (*CreatePatchBaselineOutput, error) { + req, out := c.CreatePatchBaselineRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteActivation = "DeleteActivation" @@ -797,8 +917,23 @@ func (c *SSM) DeleteActivationRequest(input *DeleteActivationInput) (req *reques // Please also see https://docs.aws.amazon.com/goto/WebAPI/ssm-2014-11-06/DeleteActivation func (c *SSM) DeleteActivation(input *DeleteActivationInput) (*DeleteActivationOutput, error) { req, out := c.DeleteActivationRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteActivationWithContext is the same as DeleteActivation with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteActivation 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 *SSM) DeleteActivationWithContext(ctx aws.Context, input *DeleteActivationInput, opts ...request.Option) (*DeleteActivationOutput, error) { + req, out := c.DeleteActivationRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteAssociation = "DeleteAssociation" @@ -846,12 +981,12 @@ func (c *SSM) DeleteAssociationRequest(input *DeleteAssociationInput) (req *requ // DeleteAssociation API operation for Amazon Simple Systems Manager (SSM). // -// Disassociates the specified SSM document from the specified instance. +// Disassociates the specified Systems Manager document from the specified instance. // -// When you disassociate an SSM document from an instance, it does not change -// the configuration of the instance. To change the configuration state of an -// instance after you disassociate a document, you must create a new document -// with the desired configuration and associate it with the instance. +// When you disassociate a document from an instance, it does not change the +// configuration of the instance. To change the configuration state of an instance +// after you disassociate a document, you must create a new document with the +// desired configuration and associate it with the 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 @@ -875,12 +1010,12 @@ func (c *SSM) DeleteAssociationRequest(input *DeleteAssociationInput) (req *requ // // You do not have permission to access the instance. // -// The SSM agent is not running. On managed instances and Linux instances, verify -// that the SSM agent is running. On EC2 Windows instances, verify that the +// The SSM Agent is not running. On managed instances and Linux instances, verify +// that the SSM Agent is running. On EC2 Windows instances, verify that the // EC2Config service is running. // -// The SSM agent or EC2Config service is not registered to the SSM endpoint. -// Try reinstalling the SSM agent or EC2Config service. +// The SSM Agent or EC2Config service is not registered to the SSM endpoint. +// Try reinstalling the SSM Agent or EC2Config service. // // The instance is not in valid state. Valid states are: Running, Pending, Stopped, // Stopping. Invalid states are: Shutting-down and Terminated. @@ -892,8 +1027,23 @@ func (c *SSM) DeleteAssociationRequest(input *DeleteAssociationInput) (req *requ // Please also see https://docs.aws.amazon.com/goto/WebAPI/ssm-2014-11-06/DeleteAssociation func (c *SSM) DeleteAssociation(input *DeleteAssociationInput) (*DeleteAssociationOutput, error) { req, out := c.DeleteAssociationRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteAssociationWithContext is the same as DeleteAssociation with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteAssociation 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 *SSM) DeleteAssociationWithContext(ctx aws.Context, input *DeleteAssociationInput, opts ...request.Option) (*DeleteAssociationOutput, error) { + req, out := c.DeleteAssociationRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteDocument = "DeleteDocument" @@ -941,9 +1091,10 @@ func (c *SSM) DeleteDocumentRequest(input *DeleteDocumentInput) (req *request.Re // DeleteDocument API operation for Amazon Simple Systems Manager (SSM). // -// Deletes the SSM document and all instance associations to the document. +// Deletes the Systems Manager document and all instance associations to the +// document. // -// Before you delete the SSM document, we recommend that you use DeleteAssociation +// Before you delete the document, we recommend that you use DeleteAssociation // to disassociate all instances that are associated with the document. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions @@ -965,14 +1116,29 @@ func (c *SSM) DeleteDocumentRequest(input *DeleteDocumentInput) (req *request.Re // sharing the document before you can delete it. // // * ErrCodeAssociatedInstances "AssociatedInstances" -// You must disassociate an SSM document from all instances before you can delete +// You must disassociate a document from all instances before you can delete // it. // // Please also see https://docs.aws.amazon.com/goto/WebAPI/ssm-2014-11-06/DeleteDocument func (c *SSM) DeleteDocument(input *DeleteDocumentInput) (*DeleteDocumentOutput, error) { req, out := c.DeleteDocumentRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteDocumentWithContext is the same as DeleteDocument with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteDocument 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 *SSM) DeleteDocumentWithContext(ctx aws.Context, input *DeleteDocumentInput, opts ...request.Option) (*DeleteDocumentOutput, error) { + req, out := c.DeleteDocumentRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteMaintenanceWindow = "DeleteMaintenanceWindow" @@ -1036,8 +1202,23 @@ func (c *SSM) DeleteMaintenanceWindowRequest(input *DeleteMaintenanceWindowInput // Please also see https://docs.aws.amazon.com/goto/WebAPI/ssm-2014-11-06/DeleteMaintenanceWindow func (c *SSM) DeleteMaintenanceWindow(input *DeleteMaintenanceWindowInput) (*DeleteMaintenanceWindowOutput, error) { req, out := c.DeleteMaintenanceWindowRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteMaintenanceWindowWithContext is the same as DeleteMaintenanceWindow with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteMaintenanceWindow 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 *SSM) DeleteMaintenanceWindowWithContext(ctx aws.Context, input *DeleteMaintenanceWindowInput, opts ...request.Option) (*DeleteMaintenanceWindowOutput, error) { + req, out := c.DeleteMaintenanceWindowRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteParameter = "DeleteParameter" @@ -1104,8 +1285,23 @@ func (c *SSM) DeleteParameterRequest(input *DeleteParameterInput) (req *request. // Please also see https://docs.aws.amazon.com/goto/WebAPI/ssm-2014-11-06/DeleteParameter func (c *SSM) DeleteParameter(input *DeleteParameterInput) (*DeleteParameterOutput, error) { req, out := c.DeleteParameterRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteParameterWithContext is the same as DeleteParameter with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteParameter 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 *SSM) DeleteParameterWithContext(ctx aws.Context, input *DeleteParameterInput, opts ...request.Option) (*DeleteParameterOutput, error) { + req, out := c.DeleteParameterRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeletePatchBaseline = "DeletePatchBaseline" @@ -1173,8 +1369,23 @@ func (c *SSM) DeletePatchBaselineRequest(input *DeletePatchBaselineInput) (req * // Please also see https://docs.aws.amazon.com/goto/WebAPI/ssm-2014-11-06/DeletePatchBaseline func (c *SSM) DeletePatchBaseline(input *DeletePatchBaselineInput) (*DeletePatchBaselineOutput, error) { req, out := c.DeletePatchBaselineRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeletePatchBaselineWithContext is the same as DeletePatchBaseline with the addition of +// the ability to pass a context and additional request options. +// +// See DeletePatchBaseline 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 *SSM) DeletePatchBaselineWithContext(ctx aws.Context, input *DeletePatchBaselineInput, opts ...request.Option) (*DeletePatchBaselineOutput, error) { + req, out := c.DeletePatchBaselineRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeregisterManagedInstance = "DeregisterManagedInstance" @@ -1224,7 +1435,7 @@ func (c *SSM) DeregisterManagedInstanceRequest(input *DeregisterManagedInstanceI // // Removes the server or virtual machine from the list of registered servers. // You can reregister the instance again at any time. If you don’t plan to use -// Run Command on the server, we suggest uninstalling the SSM agent first. +// Run Command on the server, we suggest uninstalling the SSM Agent first. // // 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 @@ -1239,12 +1450,12 @@ func (c *SSM) DeregisterManagedInstanceRequest(input *DeregisterManagedInstanceI // // You do not have permission to access the instance. // -// The SSM agent is not running. On managed instances and Linux instances, verify -// that the SSM agent is running. On EC2 Windows instances, verify that the +// The SSM Agent is not running. On managed instances and Linux instances, verify +// that the SSM Agent is running. On EC2 Windows instances, verify that the // EC2Config service is running. // -// The SSM agent or EC2Config service is not registered to the SSM endpoint. -// Try reinstalling the SSM agent or EC2Config service. +// The SSM Agent or EC2Config service is not registered to the SSM endpoint. +// Try reinstalling the SSM Agent or EC2Config service. // // The instance is not in valid state. Valid states are: Running, Pending, Stopped, // Stopping. Invalid states are: Shutting-down and Terminated. @@ -1255,8 +1466,23 @@ func (c *SSM) DeregisterManagedInstanceRequest(input *DeregisterManagedInstanceI // Please also see https://docs.aws.amazon.com/goto/WebAPI/ssm-2014-11-06/DeregisterManagedInstance func (c *SSM) DeregisterManagedInstance(input *DeregisterManagedInstanceInput) (*DeregisterManagedInstanceOutput, error) { req, out := c.DeregisterManagedInstanceRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeregisterManagedInstanceWithContext is the same as DeregisterManagedInstance with the addition of +// the ability to pass a context and additional request options. +// +// See DeregisterManagedInstance 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 *SSM) DeregisterManagedInstanceWithContext(ctx aws.Context, input *DeregisterManagedInstanceInput, opts ...request.Option) (*DeregisterManagedInstanceOutput, error) { + req, out := c.DeregisterManagedInstanceRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeregisterPatchBaselineForPatchGroup = "DeregisterPatchBaselineForPatchGroup" @@ -1324,8 +1550,23 @@ func (c *SSM) DeregisterPatchBaselineForPatchGroupRequest(input *DeregisterPatch // Please also see https://docs.aws.amazon.com/goto/WebAPI/ssm-2014-11-06/DeregisterPatchBaselineForPatchGroup func (c *SSM) DeregisterPatchBaselineForPatchGroup(input *DeregisterPatchBaselineForPatchGroupInput) (*DeregisterPatchBaselineForPatchGroupOutput, error) { req, out := c.DeregisterPatchBaselineForPatchGroupRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeregisterPatchBaselineForPatchGroupWithContext is the same as DeregisterPatchBaselineForPatchGroup with the addition of +// the ability to pass a context and additional request options. +// +// See DeregisterPatchBaselineForPatchGroup 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 *SSM) DeregisterPatchBaselineForPatchGroupWithContext(ctx aws.Context, input *DeregisterPatchBaselineForPatchGroupInput, opts ...request.Option) (*DeregisterPatchBaselineForPatchGroupOutput, error) { + req, out := c.DeregisterPatchBaselineForPatchGroupRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeregisterTargetFromMaintenanceWindow = "DeregisterTargetFromMaintenanceWindow" @@ -1393,8 +1634,23 @@ func (c *SSM) DeregisterTargetFromMaintenanceWindowRequest(input *DeregisterTarg // Please also see https://docs.aws.amazon.com/goto/WebAPI/ssm-2014-11-06/DeregisterTargetFromMaintenanceWindow func (c *SSM) DeregisterTargetFromMaintenanceWindow(input *DeregisterTargetFromMaintenanceWindowInput) (*DeregisterTargetFromMaintenanceWindowOutput, error) { req, out := c.DeregisterTargetFromMaintenanceWindowRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeregisterTargetFromMaintenanceWindowWithContext is the same as DeregisterTargetFromMaintenanceWindow with the addition of +// the ability to pass a context and additional request options. +// +// See DeregisterTargetFromMaintenanceWindow 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 *SSM) DeregisterTargetFromMaintenanceWindowWithContext(ctx aws.Context, input *DeregisterTargetFromMaintenanceWindowInput, opts ...request.Option) (*DeregisterTargetFromMaintenanceWindowOutput, error) { + req, out := c.DeregisterTargetFromMaintenanceWindowRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeregisterTaskFromMaintenanceWindow = "DeregisterTaskFromMaintenanceWindow" @@ -1462,8 +1718,23 @@ func (c *SSM) DeregisterTaskFromMaintenanceWindowRequest(input *DeregisterTaskFr // Please also see https://docs.aws.amazon.com/goto/WebAPI/ssm-2014-11-06/DeregisterTaskFromMaintenanceWindow func (c *SSM) DeregisterTaskFromMaintenanceWindow(input *DeregisterTaskFromMaintenanceWindowInput) (*DeregisterTaskFromMaintenanceWindowOutput, error) { req, out := c.DeregisterTaskFromMaintenanceWindowRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeregisterTaskFromMaintenanceWindowWithContext is the same as DeregisterTaskFromMaintenanceWindow with the addition of +// the ability to pass a context and additional request options. +// +// See DeregisterTaskFromMaintenanceWindow 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 *SSM) DeregisterTaskFromMaintenanceWindowWithContext(ctx aws.Context, input *DeregisterTaskFromMaintenanceWindowInput, opts ...request.Option) (*DeregisterTaskFromMaintenanceWindowOutput, error) { + req, out := c.DeregisterTaskFromMaintenanceWindowRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeActivations = "DescribeActivations" @@ -1542,8 +1813,23 @@ func (c *SSM) DescribeActivationsRequest(input *DescribeActivationsInput) (req * // Please also see https://docs.aws.amazon.com/goto/WebAPI/ssm-2014-11-06/DescribeActivations func (c *SSM) DescribeActivations(input *DescribeActivationsInput) (*DescribeActivationsOutput, error) { req, out := c.DescribeActivationsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeActivationsWithContext is the same as DescribeActivations with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeActivations 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 *SSM) DescribeActivationsWithContext(ctx aws.Context, input *DescribeActivationsInput, opts ...request.Option) (*DescribeActivationsOutput, error) { + req, out := c.DescribeActivationsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // DescribeActivationsPages iterates over the pages of a DescribeActivations operation, @@ -1563,12 +1849,37 @@ func (c *SSM) DescribeActivations(input *DescribeActivationsInput) (*DescribeAct // return pageNum <= 3 // }) // -func (c *SSM) DescribeActivationsPages(input *DescribeActivationsInput, fn func(p *DescribeActivationsOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.DescribeActivationsRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*DescribeActivationsOutput), lastPage) - }) +func (c *SSM) DescribeActivationsPages(input *DescribeActivationsInput, fn func(*DescribeActivationsOutput, bool) bool) error { + return c.DescribeActivationsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// DescribeActivationsPagesWithContext same as DescribeActivationsPages 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) DescribeActivationsPagesWithContext(ctx aws.Context, input *DescribeActivationsInput, fn func(*DescribeActivationsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *DescribeActivationsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeActivationsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*DescribeActivationsOutput), !p.HasNextPage()) + } + return p.Err() } const opDescribeAssociation = "DescribeAssociation" @@ -1616,7 +1927,8 @@ func (c *SSM) DescribeAssociationRequest(input *DescribeAssociationInput) (req * // DescribeAssociation API operation for Amazon Simple Systems Manager (SSM). // -// Describes the associations for the specified SSM document or instance. +// Describes the associations for the specified Systems Manager document or +// 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 @@ -1640,12 +1952,12 @@ func (c *SSM) DescribeAssociationRequest(input *DescribeAssociationInput) (req * // // You do not have permission to access the instance. // -// The SSM agent is not running. On managed instances and Linux instances, verify -// that the SSM agent is running. On EC2 Windows instances, verify that the +// The SSM Agent is not running. On managed instances and Linux instances, verify +// that the SSM Agent is running. On EC2 Windows instances, verify that the // EC2Config service is running. // -// The SSM agent or EC2Config service is not registered to the SSM endpoint. -// Try reinstalling the SSM agent or EC2Config service. +// The SSM Agent or EC2Config service is not registered to the SSM endpoint. +// Try reinstalling the SSM Agent or EC2Config service. // // The instance is not in valid state. Valid states are: Running, Pending, Stopped, // Stopping. Invalid states are: Shutting-down and Terminated. @@ -1653,8 +1965,23 @@ func (c *SSM) DescribeAssociationRequest(input *DescribeAssociationInput) (req * // Please also see https://docs.aws.amazon.com/goto/WebAPI/ssm-2014-11-06/DescribeAssociation func (c *SSM) DescribeAssociation(input *DescribeAssociationInput) (*DescribeAssociationOutput, error) { req, out := c.DescribeAssociationRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeAssociationWithContext is the same as DescribeAssociation with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeAssociation 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 *SSM) DescribeAssociationWithContext(ctx aws.Context, input *DescribeAssociationInput, opts ...request.Option) (*DescribeAssociationOutput, error) { + req, out := c.DescribeAssociationRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeAutomationExecutions = "DescribeAutomationExecutions" @@ -1721,8 +2048,23 @@ func (c *SSM) DescribeAutomationExecutionsRequest(input *DescribeAutomationExecu // Please also see https://docs.aws.amazon.com/goto/WebAPI/ssm-2014-11-06/DescribeAutomationExecutions func (c *SSM) DescribeAutomationExecutions(input *DescribeAutomationExecutionsInput) (*DescribeAutomationExecutionsOutput, error) { req, out := c.DescribeAutomationExecutionsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeAutomationExecutionsWithContext is the same as DescribeAutomationExecutions with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeAutomationExecutions 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 *SSM) DescribeAutomationExecutionsWithContext(ctx aws.Context, input *DescribeAutomationExecutionsInput, opts ...request.Option) (*DescribeAutomationExecutionsOutput, error) { + req, out := c.DescribeAutomationExecutionsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeAvailablePatches = "DescribeAvailablePatches" @@ -1786,8 +2128,23 @@ func (c *SSM) DescribeAvailablePatchesRequest(input *DescribeAvailablePatchesInp // Please also see https://docs.aws.amazon.com/goto/WebAPI/ssm-2014-11-06/DescribeAvailablePatches func (c *SSM) DescribeAvailablePatches(input *DescribeAvailablePatchesInput) (*DescribeAvailablePatchesOutput, error) { req, out := c.DescribeAvailablePatchesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeAvailablePatchesWithContext is the same as DescribeAvailablePatches with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeAvailablePatches 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 *SSM) DescribeAvailablePatchesWithContext(ctx aws.Context, input *DescribeAvailablePatchesInput, opts ...request.Option) (*DescribeAvailablePatchesOutput, error) { + req, out := c.DescribeAvailablePatchesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeDocument = "DescribeDocument" @@ -1857,8 +2214,23 @@ func (c *SSM) DescribeDocumentRequest(input *DescribeDocumentInput) (req *reques // Please also see https://docs.aws.amazon.com/goto/WebAPI/ssm-2014-11-06/DescribeDocument func (c *SSM) DescribeDocument(input *DescribeDocumentInput) (*DescribeDocumentOutput, error) { req, out := c.DescribeDocumentRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeDocumentWithContext is the same as DescribeDocument with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeDocument 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 *SSM) DescribeDocumentWithContext(ctx aws.Context, input *DescribeDocumentInput, opts ...request.Option) (*DescribeDocumentOutput, error) { + req, out := c.DescribeDocumentRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeDocumentPermission = "DescribeDocumentPermission" @@ -1906,9 +2278,9 @@ func (c *SSM) DescribeDocumentPermissionRequest(input *DescribeDocumentPermissio // DescribeDocumentPermission API operation for Amazon Simple Systems Manager (SSM). // -// Describes the permissions for an SSM document. If you created the document, -// you are the owner. If a document is shared, it can either be shared privately -// (by specifying a user’s AWS account ID) or publicly (All). +// Describes the permissions for a Systems Manager document. If you created +// the document, you are the owner. If a document is shared, it can either be +// shared privately (by specifying a user’s AWS account ID) or publicly (All). // // 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 @@ -1931,8 +2303,23 @@ func (c *SSM) DescribeDocumentPermissionRequest(input *DescribeDocumentPermissio // Please also see https://docs.aws.amazon.com/goto/WebAPI/ssm-2014-11-06/DescribeDocumentPermission func (c *SSM) DescribeDocumentPermission(input *DescribeDocumentPermissionInput) (*DescribeDocumentPermissionOutput, error) { req, out := c.DescribeDocumentPermissionRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeDocumentPermissionWithContext is the same as DescribeDocumentPermission with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeDocumentPermission 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 *SSM) DescribeDocumentPermissionWithContext(ctx aws.Context, input *DescribeDocumentPermissionInput, opts ...request.Option) (*DescribeDocumentPermissionOutput, error) { + req, out := c.DescribeDocumentPermissionRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeEffectiveInstanceAssociations = "DescribeEffectiveInstanceAssociations" @@ -1998,12 +2385,12 @@ func (c *SSM) DescribeEffectiveInstanceAssociationsRequest(input *DescribeEffect // // You do not have permission to access the instance. // -// The SSM agent is not running. On managed instances and Linux instances, verify -// that the SSM agent is running. On EC2 Windows instances, verify that the +// The SSM Agent is not running. On managed instances and Linux instances, verify +// that the SSM Agent is running. On EC2 Windows instances, verify that the // EC2Config service is running. // -// The SSM agent or EC2Config service is not registered to the SSM endpoint. -// Try reinstalling the SSM agent or EC2Config service. +// The SSM Agent or EC2Config service is not registered to the SSM endpoint. +// Try reinstalling the SSM Agent or EC2Config service. // // The instance is not in valid state. Valid states are: Running, Pending, Stopped, // Stopping. Invalid states are: Shutting-down and Terminated. @@ -2014,8 +2401,23 @@ func (c *SSM) DescribeEffectiveInstanceAssociationsRequest(input *DescribeEffect // Please also see https://docs.aws.amazon.com/goto/WebAPI/ssm-2014-11-06/DescribeEffectiveInstanceAssociations func (c *SSM) DescribeEffectiveInstanceAssociations(input *DescribeEffectiveInstanceAssociationsInput) (*DescribeEffectiveInstanceAssociationsOutput, error) { req, out := c.DescribeEffectiveInstanceAssociationsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeEffectiveInstanceAssociationsWithContext is the same as DescribeEffectiveInstanceAssociations with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeEffectiveInstanceAssociations 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 *SSM) DescribeEffectiveInstanceAssociationsWithContext(ctx aws.Context, input *DescribeEffectiveInstanceAssociationsInput, opts ...request.Option) (*DescribeEffectiveInstanceAssociationsOutput, error) { + req, out := c.DescribeEffectiveInstanceAssociationsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeEffectivePatchesForPatchBaseline = "DescribeEffectivePatchesForPatchBaseline" @@ -2088,8 +2490,23 @@ func (c *SSM) DescribeEffectivePatchesForPatchBaselineRequest(input *DescribeEff // Please also see https://docs.aws.amazon.com/goto/WebAPI/ssm-2014-11-06/DescribeEffectivePatchesForPatchBaseline func (c *SSM) DescribeEffectivePatchesForPatchBaseline(input *DescribeEffectivePatchesForPatchBaselineInput) (*DescribeEffectivePatchesForPatchBaselineOutput, error) { req, out := c.DescribeEffectivePatchesForPatchBaselineRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeEffectivePatchesForPatchBaselineWithContext is the same as DescribeEffectivePatchesForPatchBaseline with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeEffectivePatchesForPatchBaseline 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 *SSM) DescribeEffectivePatchesForPatchBaselineWithContext(ctx aws.Context, input *DescribeEffectivePatchesForPatchBaselineInput, opts ...request.Option) (*DescribeEffectivePatchesForPatchBaselineOutput, error) { + req, out := c.DescribeEffectivePatchesForPatchBaselineRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeInstanceAssociationsStatus = "DescribeInstanceAssociationsStatus" @@ -2155,12 +2572,12 @@ func (c *SSM) DescribeInstanceAssociationsStatusRequest(input *DescribeInstanceA // // You do not have permission to access the instance. // -// The SSM agent is not running. On managed instances and Linux instances, verify -// that the SSM agent is running. On EC2 Windows instances, verify that the +// The SSM Agent is not running. On managed instances and Linux instances, verify +// that the SSM Agent is running. On EC2 Windows instances, verify that the // EC2Config service is running. // -// The SSM agent or EC2Config service is not registered to the SSM endpoint. -// Try reinstalling the SSM agent or EC2Config service. +// The SSM Agent or EC2Config service is not registered to the SSM endpoint. +// Try reinstalling the SSM Agent or EC2Config service. // // The instance is not in valid state. Valid states are: Running, Pending, Stopped, // Stopping. Invalid states are: Shutting-down and Terminated. @@ -2171,8 +2588,23 @@ func (c *SSM) DescribeInstanceAssociationsStatusRequest(input *DescribeInstanceA // Please also see https://docs.aws.amazon.com/goto/WebAPI/ssm-2014-11-06/DescribeInstanceAssociationsStatus func (c *SSM) DescribeInstanceAssociationsStatus(input *DescribeInstanceAssociationsStatusInput) (*DescribeInstanceAssociationsStatusOutput, error) { req, out := c.DescribeInstanceAssociationsStatusRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeInstanceAssociationsStatusWithContext is the same as DescribeInstanceAssociationsStatus with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeInstanceAssociationsStatus 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 *SSM) DescribeInstanceAssociationsStatusWithContext(ctx aws.Context, input *DescribeInstanceAssociationsStatusInput, opts ...request.Option) (*DescribeInstanceAssociationsStatusOutput, error) { + req, out := c.DescribeInstanceAssociationsStatusRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeInstanceInformation = "DescribeInstanceInformation" @@ -2227,7 +2659,7 @@ 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 +// 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 @@ -2249,12 +2681,12 @@ func (c *SSM) DescribeInstanceInformationRequest(input *DescribeInstanceInformat // // You do not have permission to access the instance. // -// The SSM agent is not running. On managed instances and Linux instances, verify -// that the SSM agent is running. On EC2 Windows instances, verify that the +// The SSM Agent is not running. On managed instances and Linux instances, verify +// that the SSM Agent is running. On EC2 Windows instances, verify that the // EC2Config service is running. // -// The SSM agent or EC2Config service is not registered to the SSM endpoint. -// Try reinstalling the SSM agent or EC2Config service. +// The SSM Agent or EC2Config service is not registered to the SSM endpoint. +// Try reinstalling the SSM Agent or EC2Config service. // // The instance is not in valid state. Valid states are: Running, Pending, Stopped, // Stopping. Invalid states are: Shutting-down and Terminated. @@ -2271,8 +2703,23 @@ func (c *SSM) DescribeInstanceInformationRequest(input *DescribeInstanceInformat // Please also see https://docs.aws.amazon.com/goto/WebAPI/ssm-2014-11-06/DescribeInstanceInformation func (c *SSM) DescribeInstanceInformation(input *DescribeInstanceInformationInput) (*DescribeInstanceInformationOutput, error) { req, out := c.DescribeInstanceInformationRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeInstanceInformationWithContext is the same as DescribeInstanceInformation with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeInstanceInformation 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 *SSM) DescribeInstanceInformationWithContext(ctx aws.Context, input *DescribeInstanceInformationInput, opts ...request.Option) (*DescribeInstanceInformationOutput, error) { + req, out := c.DescribeInstanceInformationRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // DescribeInstanceInformationPages iterates over the pages of a DescribeInstanceInformation operation, @@ -2292,12 +2739,37 @@ func (c *SSM) DescribeInstanceInformation(input *DescribeInstanceInformationInpu // return pageNum <= 3 // }) // -func (c *SSM) DescribeInstanceInformationPages(input *DescribeInstanceInformationInput, fn func(p *DescribeInstanceInformationOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.DescribeInstanceInformationRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*DescribeInstanceInformationOutput), lastPage) - }) +func (c *SSM) DescribeInstanceInformationPages(input *DescribeInstanceInformationInput, fn func(*DescribeInstanceInformationOutput, bool) bool) error { + return c.DescribeInstanceInformationPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// DescribeInstanceInformationPagesWithContext same as DescribeInstanceInformationPages 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) DescribeInstanceInformationPagesWithContext(ctx aws.Context, input *DescribeInstanceInformationInput, fn func(*DescribeInstanceInformationOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *DescribeInstanceInformationInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeInstanceInformationRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*DescribeInstanceInformationOutput), !p.HasNextPage()) + } + return p.Err() } const opDescribeInstancePatchStates = "DescribeInstancePatchStates" @@ -2364,8 +2836,23 @@ func (c *SSM) DescribeInstancePatchStatesRequest(input *DescribeInstancePatchSta // Please also see https://docs.aws.amazon.com/goto/WebAPI/ssm-2014-11-06/DescribeInstancePatchStates func (c *SSM) DescribeInstancePatchStates(input *DescribeInstancePatchStatesInput) (*DescribeInstancePatchStatesOutput, error) { req, out := c.DescribeInstancePatchStatesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeInstancePatchStatesWithContext is the same as DescribeInstancePatchStates with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeInstancePatchStates 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 *SSM) DescribeInstancePatchStatesWithContext(ctx aws.Context, input *DescribeInstancePatchStatesInput, opts ...request.Option) (*DescribeInstancePatchStatesOutput, error) { + req, out := c.DescribeInstancePatchStatesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeInstancePatchStatesForPatchGroup = "DescribeInstancePatchStatesForPatchGroup" @@ -2437,8 +2924,23 @@ func (c *SSM) DescribeInstancePatchStatesForPatchGroupRequest(input *DescribeIns // Please also see https://docs.aws.amazon.com/goto/WebAPI/ssm-2014-11-06/DescribeInstancePatchStatesForPatchGroup func (c *SSM) DescribeInstancePatchStatesForPatchGroup(input *DescribeInstancePatchStatesForPatchGroupInput) (*DescribeInstancePatchStatesForPatchGroupOutput, error) { req, out := c.DescribeInstancePatchStatesForPatchGroupRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeInstancePatchStatesForPatchGroupWithContext is the same as DescribeInstancePatchStatesForPatchGroup with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeInstancePatchStatesForPatchGroup 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 *SSM) DescribeInstancePatchStatesForPatchGroupWithContext(ctx aws.Context, input *DescribeInstancePatchStatesForPatchGroupInput, opts ...request.Option) (*DescribeInstancePatchStatesForPatchGroupOutput, error) { + req, out := c.DescribeInstancePatchStatesForPatchGroupRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeInstancePatches = "DescribeInstancePatches" @@ -2505,12 +3007,12 @@ func (c *SSM) DescribeInstancePatchesRequest(input *DescribeInstancePatchesInput // // You do not have permission to access the instance. // -// The SSM agent is not running. On managed instances and Linux instances, verify -// that the SSM agent is running. On EC2 Windows instances, verify that the +// The SSM Agent is not running. On managed instances and Linux instances, verify +// that the SSM Agent is running. On EC2 Windows instances, verify that the // EC2Config service is running. // -// The SSM agent or EC2Config service is not registered to the SSM endpoint. -// Try reinstalling the SSM agent or EC2Config service. +// The SSM Agent or EC2Config service is not registered to the SSM endpoint. +// Try reinstalling the SSM Agent or EC2Config service. // // The instance is not in valid state. Valid states are: Running, Pending, Stopped, // Stopping. Invalid states are: Shutting-down and Terminated. @@ -2525,8 +3027,23 @@ func (c *SSM) DescribeInstancePatchesRequest(input *DescribeInstancePatchesInput // Please also see https://docs.aws.amazon.com/goto/WebAPI/ssm-2014-11-06/DescribeInstancePatches func (c *SSM) DescribeInstancePatches(input *DescribeInstancePatchesInput) (*DescribeInstancePatchesOutput, error) { req, out := c.DescribeInstancePatchesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeInstancePatchesWithContext is the same as DescribeInstancePatches with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeInstancePatches 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 *SSM) DescribeInstancePatchesWithContext(ctx aws.Context, input *DescribeInstancePatchesInput, opts ...request.Option) (*DescribeInstancePatchesOutput, error) { + req, out := c.DescribeInstancePatchesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeMaintenanceWindowExecutionTaskInvocations = "DescribeMaintenanceWindowExecutionTaskInvocations" @@ -2595,8 +3112,23 @@ func (c *SSM) DescribeMaintenanceWindowExecutionTaskInvocationsRequest(input *De // Please also see https://docs.aws.amazon.com/goto/WebAPI/ssm-2014-11-06/DescribeMaintenanceWindowExecutionTaskInvocations func (c *SSM) DescribeMaintenanceWindowExecutionTaskInvocations(input *DescribeMaintenanceWindowExecutionTaskInvocationsInput) (*DescribeMaintenanceWindowExecutionTaskInvocationsOutput, error) { req, out := c.DescribeMaintenanceWindowExecutionTaskInvocationsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeMaintenanceWindowExecutionTaskInvocationsWithContext is the same as DescribeMaintenanceWindowExecutionTaskInvocations with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeMaintenanceWindowExecutionTaskInvocations 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 *SSM) DescribeMaintenanceWindowExecutionTaskInvocationsWithContext(ctx aws.Context, input *DescribeMaintenanceWindowExecutionTaskInvocationsInput, opts ...request.Option) (*DescribeMaintenanceWindowExecutionTaskInvocationsOutput, error) { + req, out := c.DescribeMaintenanceWindowExecutionTaskInvocationsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeMaintenanceWindowExecutionTasks = "DescribeMaintenanceWindowExecutionTasks" @@ -2664,8 +3196,23 @@ func (c *SSM) DescribeMaintenanceWindowExecutionTasksRequest(input *DescribeMain // Please also see https://docs.aws.amazon.com/goto/WebAPI/ssm-2014-11-06/DescribeMaintenanceWindowExecutionTasks func (c *SSM) DescribeMaintenanceWindowExecutionTasks(input *DescribeMaintenanceWindowExecutionTasksInput) (*DescribeMaintenanceWindowExecutionTasksOutput, error) { req, out := c.DescribeMaintenanceWindowExecutionTasksRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeMaintenanceWindowExecutionTasksWithContext is the same as DescribeMaintenanceWindowExecutionTasks with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeMaintenanceWindowExecutionTasks 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 *SSM) DescribeMaintenanceWindowExecutionTasksWithContext(ctx aws.Context, input *DescribeMaintenanceWindowExecutionTasksInput, opts ...request.Option) (*DescribeMaintenanceWindowExecutionTasksOutput, error) { + req, out := c.DescribeMaintenanceWindowExecutionTasksRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeMaintenanceWindowExecutions = "DescribeMaintenanceWindowExecutions" @@ -2731,8 +3278,23 @@ func (c *SSM) DescribeMaintenanceWindowExecutionsRequest(input *DescribeMaintena // Please also see https://docs.aws.amazon.com/goto/WebAPI/ssm-2014-11-06/DescribeMaintenanceWindowExecutions func (c *SSM) DescribeMaintenanceWindowExecutions(input *DescribeMaintenanceWindowExecutionsInput) (*DescribeMaintenanceWindowExecutionsOutput, error) { req, out := c.DescribeMaintenanceWindowExecutionsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeMaintenanceWindowExecutionsWithContext is the same as DescribeMaintenanceWindowExecutions with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeMaintenanceWindowExecutions 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 *SSM) DescribeMaintenanceWindowExecutionsWithContext(ctx aws.Context, input *DescribeMaintenanceWindowExecutionsInput, opts ...request.Option) (*DescribeMaintenanceWindowExecutionsOutput, error) { + req, out := c.DescribeMaintenanceWindowExecutionsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeMaintenanceWindowTargets = "DescribeMaintenanceWindowTargets" @@ -2800,8 +3362,23 @@ func (c *SSM) DescribeMaintenanceWindowTargetsRequest(input *DescribeMaintenance // Please also see https://docs.aws.amazon.com/goto/WebAPI/ssm-2014-11-06/DescribeMaintenanceWindowTargets func (c *SSM) DescribeMaintenanceWindowTargets(input *DescribeMaintenanceWindowTargetsInput) (*DescribeMaintenanceWindowTargetsOutput, error) { req, out := c.DescribeMaintenanceWindowTargetsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeMaintenanceWindowTargetsWithContext is the same as DescribeMaintenanceWindowTargets with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeMaintenanceWindowTargets 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 *SSM) DescribeMaintenanceWindowTargetsWithContext(ctx aws.Context, input *DescribeMaintenanceWindowTargetsInput, opts ...request.Option) (*DescribeMaintenanceWindowTargetsOutput, error) { + req, out := c.DescribeMaintenanceWindowTargetsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeMaintenanceWindowTasks = "DescribeMaintenanceWindowTasks" @@ -2869,8 +3446,23 @@ func (c *SSM) DescribeMaintenanceWindowTasksRequest(input *DescribeMaintenanceWi // Please also see https://docs.aws.amazon.com/goto/WebAPI/ssm-2014-11-06/DescribeMaintenanceWindowTasks func (c *SSM) DescribeMaintenanceWindowTasks(input *DescribeMaintenanceWindowTasksInput) (*DescribeMaintenanceWindowTasksOutput, error) { req, out := c.DescribeMaintenanceWindowTasksRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeMaintenanceWindowTasksWithContext is the same as DescribeMaintenanceWindowTasks with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeMaintenanceWindowTasks 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 *SSM) DescribeMaintenanceWindowTasksWithContext(ctx aws.Context, input *DescribeMaintenanceWindowTasksInput, opts ...request.Option) (*DescribeMaintenanceWindowTasksOutput, error) { + req, out := c.DescribeMaintenanceWindowTasksRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeMaintenanceWindows = "DescribeMaintenanceWindows" @@ -2934,8 +3526,23 @@ func (c *SSM) DescribeMaintenanceWindowsRequest(input *DescribeMaintenanceWindow // Please also see https://docs.aws.amazon.com/goto/WebAPI/ssm-2014-11-06/DescribeMaintenanceWindows func (c *SSM) DescribeMaintenanceWindows(input *DescribeMaintenanceWindowsInput) (*DescribeMaintenanceWindowsOutput, error) { req, out := c.DescribeMaintenanceWindowsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeMaintenanceWindowsWithContext is the same as DescribeMaintenanceWindows with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeMaintenanceWindows 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 *SSM) DescribeMaintenanceWindowsWithContext(ctx aws.Context, input *DescribeMaintenanceWindowsInput, opts ...request.Option) (*DescribeMaintenanceWindowsOutput, error) { + req, out := c.DescribeMaintenanceWindowsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeParameters = "DescribeParameters" @@ -3005,8 +3612,23 @@ func (c *SSM) DescribeParametersRequest(input *DescribeParametersInput) (req *re // Please also see https://docs.aws.amazon.com/goto/WebAPI/ssm-2014-11-06/DescribeParameters func (c *SSM) DescribeParameters(input *DescribeParametersInput) (*DescribeParametersOutput, error) { req, out := c.DescribeParametersRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeParametersWithContext is the same as DescribeParameters with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeParameters 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 *SSM) DescribeParametersWithContext(ctx aws.Context, input *DescribeParametersInput, opts ...request.Option) (*DescribeParametersOutput, error) { + req, out := c.DescribeParametersRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribePatchBaselines = "DescribePatchBaselines" @@ -3070,8 +3692,23 @@ func (c *SSM) DescribePatchBaselinesRequest(input *DescribePatchBaselinesInput) // Please also see https://docs.aws.amazon.com/goto/WebAPI/ssm-2014-11-06/DescribePatchBaselines func (c *SSM) DescribePatchBaselines(input *DescribePatchBaselinesInput) (*DescribePatchBaselinesOutput, error) { req, out := c.DescribePatchBaselinesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribePatchBaselinesWithContext is the same as DescribePatchBaselines with the addition of +// the ability to pass a context and additional request options. +// +// See DescribePatchBaselines 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 *SSM) DescribePatchBaselinesWithContext(ctx aws.Context, input *DescribePatchBaselinesInput, opts ...request.Option) (*DescribePatchBaselinesOutput, error) { + req, out := c.DescribePatchBaselinesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribePatchGroupState = "DescribePatchGroupState" @@ -3138,8 +3775,23 @@ func (c *SSM) DescribePatchGroupStateRequest(input *DescribePatchGroupStateInput // Please also see https://docs.aws.amazon.com/goto/WebAPI/ssm-2014-11-06/DescribePatchGroupState func (c *SSM) DescribePatchGroupState(input *DescribePatchGroupStateInput) (*DescribePatchGroupStateOutput, error) { req, out := c.DescribePatchGroupStateRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribePatchGroupStateWithContext is the same as DescribePatchGroupState with the addition of +// the ability to pass a context and additional request options. +// +// See DescribePatchGroupState 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 *SSM) DescribePatchGroupStateWithContext(ctx aws.Context, input *DescribePatchGroupStateInput, opts ...request.Option) (*DescribePatchGroupStateOutput, error) { + req, out := c.DescribePatchGroupStateRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribePatchGroups = "DescribePatchGroups" @@ -3203,8 +3855,23 @@ func (c *SSM) DescribePatchGroupsRequest(input *DescribePatchGroupsInput) (req * // Please also see https://docs.aws.amazon.com/goto/WebAPI/ssm-2014-11-06/DescribePatchGroups func (c *SSM) DescribePatchGroups(input *DescribePatchGroupsInput) (*DescribePatchGroupsOutput, error) { req, out := c.DescribePatchGroupsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribePatchGroupsWithContext is the same as DescribePatchGroups with the addition of +// the ability to pass a context and additional request options. +// +// See DescribePatchGroups 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 *SSM) DescribePatchGroupsWithContext(ctx aws.Context, input *DescribePatchGroupsInput, opts ...request.Option) (*DescribePatchGroupsOutput, error) { + req, out := c.DescribePatchGroupsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetAutomationExecution = "GetAutomationExecution" @@ -3272,8 +3939,23 @@ func (c *SSM) GetAutomationExecutionRequest(input *GetAutomationExecutionInput) // Please also see https://docs.aws.amazon.com/goto/WebAPI/ssm-2014-11-06/GetAutomationExecution func (c *SSM) GetAutomationExecution(input *GetAutomationExecutionInput) (*GetAutomationExecutionOutput, error) { req, out := c.GetAutomationExecutionRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetAutomationExecutionWithContext is the same as GetAutomationExecution with the addition of +// the ability to pass a context and additional request options. +// +// See GetAutomationExecution 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 *SSM) GetAutomationExecutionWithContext(ctx aws.Context, input *GetAutomationExecutionInput, opts ...request.Option) (*GetAutomationExecutionOutput, error) { + req, out := c.GetAutomationExecutionRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetCommandInvocation = "GetCommandInvocation" @@ -3342,12 +4024,12 @@ func (c *SSM) GetCommandInvocationRequest(input *GetCommandInvocationInput) (req // // You do not have permission to access the instance. // -// The SSM agent is not running. On managed instances and Linux instances, verify -// that the SSM agent is running. On EC2 Windows instances, verify that the +// The SSM Agent is not running. On managed instances and Linux instances, verify +// that the SSM Agent is running. On EC2 Windows instances, verify that the // EC2Config service is running. // -// The SSM agent or EC2Config service is not registered to the SSM endpoint. -// Try reinstalling the SSM agent or EC2Config service. +// The SSM Agent or EC2Config service is not registered to the SSM endpoint. +// Try reinstalling the SSM Agent or EC2Config service. // // The instance is not in valid state. Valid states are: Running, Pending, Stopped, // Stopping. Invalid states are: Shutting-down and Terminated. @@ -3362,8 +4044,23 @@ func (c *SSM) GetCommandInvocationRequest(input *GetCommandInvocationInput) (req // Please also see https://docs.aws.amazon.com/goto/WebAPI/ssm-2014-11-06/GetCommandInvocation func (c *SSM) GetCommandInvocation(input *GetCommandInvocationInput) (*GetCommandInvocationOutput, error) { req, out := c.GetCommandInvocationRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetCommandInvocationWithContext is the same as GetCommandInvocation with the addition of +// the ability to pass a context and additional request options. +// +// See GetCommandInvocation 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 *SSM) GetCommandInvocationWithContext(ctx aws.Context, input *GetCommandInvocationInput, opts ...request.Option) (*GetCommandInvocationOutput, error) { + req, out := c.GetCommandInvocationRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetDefaultPatchBaseline = "GetDefaultPatchBaseline" @@ -3427,8 +4124,23 @@ func (c *SSM) GetDefaultPatchBaselineRequest(input *GetDefaultPatchBaselineInput // Please also see https://docs.aws.amazon.com/goto/WebAPI/ssm-2014-11-06/GetDefaultPatchBaseline func (c *SSM) GetDefaultPatchBaseline(input *GetDefaultPatchBaselineInput) (*GetDefaultPatchBaselineOutput, error) { req, out := c.GetDefaultPatchBaselineRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetDefaultPatchBaselineWithContext is the same as GetDefaultPatchBaseline with the addition of +// the ability to pass a context and additional request options. +// +// See GetDefaultPatchBaseline 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 *SSM) GetDefaultPatchBaselineWithContext(ctx aws.Context, input *GetDefaultPatchBaselineInput, opts ...request.Option) (*GetDefaultPatchBaselineOutput, error) { + req, out := c.GetDefaultPatchBaselineRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetDeployablePatchSnapshotForInstance = "GetDeployablePatchSnapshotForInstance" @@ -3494,8 +4206,23 @@ func (c *SSM) GetDeployablePatchSnapshotForInstanceRequest(input *GetDeployableP // Please also see https://docs.aws.amazon.com/goto/WebAPI/ssm-2014-11-06/GetDeployablePatchSnapshotForInstance func (c *SSM) GetDeployablePatchSnapshotForInstance(input *GetDeployablePatchSnapshotForInstanceInput) (*GetDeployablePatchSnapshotForInstanceOutput, error) { req, out := c.GetDeployablePatchSnapshotForInstanceRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetDeployablePatchSnapshotForInstanceWithContext is the same as GetDeployablePatchSnapshotForInstance with the addition of +// the ability to pass a context and additional request options. +// +// See GetDeployablePatchSnapshotForInstance 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 *SSM) GetDeployablePatchSnapshotForInstanceWithContext(ctx aws.Context, input *GetDeployablePatchSnapshotForInstanceInput, opts ...request.Option) (*GetDeployablePatchSnapshotForInstanceOutput, error) { + req, out := c.GetDeployablePatchSnapshotForInstanceRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetDocument = "GetDocument" @@ -3565,8 +4292,23 @@ func (c *SSM) GetDocumentRequest(input *GetDocumentInput) (req *request.Request, // Please also see https://docs.aws.amazon.com/goto/WebAPI/ssm-2014-11-06/GetDocument func (c *SSM) GetDocument(input *GetDocumentInput) (*GetDocumentOutput, error) { req, out := c.GetDocumentRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetDocumentWithContext is the same as GetDocument with the addition of +// the ability to pass a context and additional request options. +// +// See GetDocument 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 *SSM) GetDocumentWithContext(ctx aws.Context, input *GetDocumentInput, opts ...request.Option) (*GetDocumentOutput, error) { + req, out := c.GetDocumentRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetInventory = "GetInventory" @@ -3643,8 +4385,23 @@ func (c *SSM) GetInventoryRequest(input *GetInventoryInput) (req *request.Reques // Please also see https://docs.aws.amazon.com/goto/WebAPI/ssm-2014-11-06/GetInventory func (c *SSM) GetInventory(input *GetInventoryInput) (*GetInventoryOutput, error) { req, out := c.GetInventoryRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetInventoryWithContext is the same as GetInventory with the addition of +// the ability to pass a context and additional request options. +// +// See GetInventory 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 *SSM) GetInventoryWithContext(ctx aws.Context, input *GetInventoryInput, opts ...request.Option) (*GetInventoryOutput, error) { + req, out := c.GetInventoryRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetInventorySchema = "GetInventorySchema" @@ -3715,8 +4472,23 @@ func (c *SSM) GetInventorySchemaRequest(input *GetInventorySchemaInput) (req *re // Please also see https://docs.aws.amazon.com/goto/WebAPI/ssm-2014-11-06/GetInventorySchema func (c *SSM) GetInventorySchema(input *GetInventorySchemaInput) (*GetInventorySchemaOutput, error) { req, out := c.GetInventorySchemaRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetInventorySchemaWithContext is the same as GetInventorySchema with the addition of +// the ability to pass a context and additional request options. +// +// See GetInventorySchema 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 *SSM) GetInventorySchemaWithContext(ctx aws.Context, input *GetInventorySchemaInput, opts ...request.Option) (*GetInventorySchemaOutput, error) { + req, out := c.GetInventorySchemaRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetMaintenanceWindow = "GetMaintenanceWindow" @@ -3784,8 +4556,23 @@ func (c *SSM) GetMaintenanceWindowRequest(input *GetMaintenanceWindowInput) (req // Please also see https://docs.aws.amazon.com/goto/WebAPI/ssm-2014-11-06/GetMaintenanceWindow func (c *SSM) GetMaintenanceWindow(input *GetMaintenanceWindowInput) (*GetMaintenanceWindowOutput, error) { req, out := c.GetMaintenanceWindowRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetMaintenanceWindowWithContext is the same as GetMaintenanceWindow with the addition of +// the ability to pass a context and additional request options. +// +// See GetMaintenanceWindow 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 *SSM) GetMaintenanceWindowWithContext(ctx aws.Context, input *GetMaintenanceWindowInput, opts ...request.Option) (*GetMaintenanceWindowOutput, error) { + req, out := c.GetMaintenanceWindowRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetMaintenanceWindowExecution = "GetMaintenanceWindowExecution" @@ -3854,8 +4641,23 @@ func (c *SSM) GetMaintenanceWindowExecutionRequest(input *GetMaintenanceWindowEx // Please also see https://docs.aws.amazon.com/goto/WebAPI/ssm-2014-11-06/GetMaintenanceWindowExecution func (c *SSM) GetMaintenanceWindowExecution(input *GetMaintenanceWindowExecutionInput) (*GetMaintenanceWindowExecutionOutput, error) { req, out := c.GetMaintenanceWindowExecutionRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetMaintenanceWindowExecutionWithContext is the same as GetMaintenanceWindowExecution with the addition of +// the ability to pass a context and additional request options. +// +// See GetMaintenanceWindowExecution 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 *SSM) GetMaintenanceWindowExecutionWithContext(ctx aws.Context, input *GetMaintenanceWindowExecutionInput, opts ...request.Option) (*GetMaintenanceWindowExecutionOutput, error) { + req, out := c.GetMaintenanceWindowExecutionRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetMaintenanceWindowExecutionTask = "GetMaintenanceWindowExecutionTask" @@ -3924,8 +4726,23 @@ func (c *SSM) GetMaintenanceWindowExecutionTaskRequest(input *GetMaintenanceWind // Please also see https://docs.aws.amazon.com/goto/WebAPI/ssm-2014-11-06/GetMaintenanceWindowExecutionTask func (c *SSM) GetMaintenanceWindowExecutionTask(input *GetMaintenanceWindowExecutionTaskInput) (*GetMaintenanceWindowExecutionTaskOutput, error) { req, out := c.GetMaintenanceWindowExecutionTaskRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetMaintenanceWindowExecutionTaskWithContext is the same as GetMaintenanceWindowExecutionTask with the addition of +// the ability to pass a context and additional request options. +// +// See GetMaintenanceWindowExecutionTask 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 *SSM) GetMaintenanceWindowExecutionTaskWithContext(ctx aws.Context, input *GetMaintenanceWindowExecutionTaskInput, opts ...request.Option) (*GetMaintenanceWindowExecutionTaskOutput, error) { + req, out := c.GetMaintenanceWindowExecutionTaskRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetParameterHistory = "GetParameterHistory" @@ -3995,8 +4812,23 @@ func (c *SSM) GetParameterHistoryRequest(input *GetParameterHistoryInput) (req * // Please also see https://docs.aws.amazon.com/goto/WebAPI/ssm-2014-11-06/GetParameterHistory func (c *SSM) GetParameterHistory(input *GetParameterHistoryInput) (*GetParameterHistoryOutput, error) { req, out := c.GetParameterHistoryRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetParameterHistoryWithContext is the same as GetParameterHistory with the addition of +// the ability to pass a context and additional request options. +// +// See GetParameterHistory 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 *SSM) GetParameterHistoryWithContext(ctx aws.Context, input *GetParameterHistoryInput, opts ...request.Option) (*GetParameterHistoryOutput, error) { + req, out := c.GetParameterHistoryRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetParameters = "GetParameters" @@ -4044,7 +4876,7 @@ func (c *SSM) GetParametersRequest(input *GetParametersInput) (req *request.Requ // GetParameters API operation for Amazon Simple Systems Manager (SSM). // -// Get a list of parameters used by the AWS account.> +// Get details of a parameter. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -4060,8 +4892,23 @@ func (c *SSM) GetParametersRequest(input *GetParametersInput) (req *request.Requ // Please also see https://docs.aws.amazon.com/goto/WebAPI/ssm-2014-11-06/GetParameters func (c *SSM) GetParameters(input *GetParametersInput) (*GetParametersOutput, error) { req, out := c.GetParametersRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetParametersWithContext is the same as GetParameters with the addition of +// the ability to pass a context and additional request options. +// +// See GetParameters 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 *SSM) GetParametersWithContext(ctx aws.Context, input *GetParametersInput, opts ...request.Option) (*GetParametersOutput, error) { + req, out := c.GetParametersRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetPatchBaseline = "GetPatchBaseline" @@ -4133,8 +4980,23 @@ func (c *SSM) GetPatchBaselineRequest(input *GetPatchBaselineInput) (req *reques // Please also see https://docs.aws.amazon.com/goto/WebAPI/ssm-2014-11-06/GetPatchBaseline func (c *SSM) GetPatchBaseline(input *GetPatchBaselineInput) (*GetPatchBaselineOutput, error) { req, out := c.GetPatchBaselineRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetPatchBaselineWithContext is the same as GetPatchBaseline with the addition of +// the ability to pass a context and additional request options. +// +// See GetPatchBaseline 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 *SSM) GetPatchBaselineWithContext(ctx aws.Context, input *GetPatchBaselineInput, opts ...request.Option) (*GetPatchBaselineOutput, error) { + req, out := c.GetPatchBaselineRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetPatchBaselineForPatchGroup = "GetPatchBaselineForPatchGroup" @@ -4199,8 +5061,23 @@ func (c *SSM) GetPatchBaselineForPatchGroupRequest(input *GetPatchBaselineForPat // Please also see https://docs.aws.amazon.com/goto/WebAPI/ssm-2014-11-06/GetPatchBaselineForPatchGroup func (c *SSM) GetPatchBaselineForPatchGroup(input *GetPatchBaselineForPatchGroupInput) (*GetPatchBaselineForPatchGroupOutput, error) { req, out := c.GetPatchBaselineForPatchGroupRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetPatchBaselineForPatchGroupWithContext is the same as GetPatchBaselineForPatchGroup with the addition of +// the ability to pass a context and additional request options. +// +// See GetPatchBaselineForPatchGroup 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 *SSM) GetPatchBaselineForPatchGroupWithContext(ctx aws.Context, input *GetPatchBaselineForPatchGroupInput, opts ...request.Option) (*GetPatchBaselineForPatchGroupOutput, error) { + req, out := c.GetPatchBaselineForPatchGroupRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opListAssociations = "ListAssociations" @@ -4254,7 +5131,7 @@ func (c *SSM) ListAssociationsRequest(input *ListAssociationsInput) (req *reques // ListAssociations API operation for Amazon Simple Systems Manager (SSM). // -// Lists the associations for the specified SSM document or instance. +// Lists the associations for the specified Systems Manager document or 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 @@ -4273,8 +5150,23 @@ func (c *SSM) ListAssociationsRequest(input *ListAssociationsInput) (req *reques // Please also see https://docs.aws.amazon.com/goto/WebAPI/ssm-2014-11-06/ListAssociations func (c *SSM) ListAssociations(input *ListAssociationsInput) (*ListAssociationsOutput, error) { req, out := c.ListAssociationsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListAssociationsWithContext is the same as ListAssociations with the addition of +// the ability to pass a context and additional request options. +// +// See ListAssociations 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 *SSM) ListAssociationsWithContext(ctx aws.Context, input *ListAssociationsInput, opts ...request.Option) (*ListAssociationsOutput, error) { + req, out := c.ListAssociationsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // ListAssociationsPages iterates over the pages of a ListAssociations operation, @@ -4294,12 +5186,37 @@ func (c *SSM) ListAssociations(input *ListAssociationsInput) (*ListAssociationsO // return pageNum <= 3 // }) // -func (c *SSM) ListAssociationsPages(input *ListAssociationsInput, fn func(p *ListAssociationsOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.ListAssociationsRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*ListAssociationsOutput), lastPage) - }) +func (c *SSM) ListAssociationsPages(input *ListAssociationsInput, fn func(*ListAssociationsOutput, bool) bool) error { + return c.ListAssociationsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListAssociationsPagesWithContext same as ListAssociationsPages 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) ListAssociationsPagesWithContext(ctx aws.Context, input *ListAssociationsInput, fn func(*ListAssociationsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListAssociationsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListAssociationsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*ListAssociationsOutput), !p.HasNextPage()) + } + return p.Err() } const opListCommandInvocations = "ListCommandInvocations" @@ -4377,12 +5294,12 @@ func (c *SSM) ListCommandInvocationsRequest(input *ListCommandInvocationsInput) // // You do not have permission to access the instance. // -// The SSM agent is not running. On managed instances and Linux instances, verify -// that the SSM agent is running. On EC2 Windows instances, verify that the +// The SSM Agent is not running. On managed instances and Linux instances, verify +// that the SSM Agent is running. On EC2 Windows instances, verify that the // EC2Config service is running. // -// The SSM agent or EC2Config service is not registered to the SSM endpoint. -// Try reinstalling the SSM agent or EC2Config service. +// The SSM Agent or EC2Config service is not registered to the SSM endpoint. +// Try reinstalling the SSM Agent or EC2Config service. // // The instance is not in valid state. Valid states are: Running, Pending, Stopped, // Stopping. Invalid states are: Shutting-down and Terminated. @@ -4396,8 +5313,23 @@ func (c *SSM) ListCommandInvocationsRequest(input *ListCommandInvocationsInput) // Please also see https://docs.aws.amazon.com/goto/WebAPI/ssm-2014-11-06/ListCommandInvocations func (c *SSM) ListCommandInvocations(input *ListCommandInvocationsInput) (*ListCommandInvocationsOutput, error) { req, out := c.ListCommandInvocationsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListCommandInvocationsWithContext is the same as ListCommandInvocations with the addition of +// the ability to pass a context and additional request options. +// +// See ListCommandInvocations 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 *SSM) ListCommandInvocationsWithContext(ctx aws.Context, input *ListCommandInvocationsInput, opts ...request.Option) (*ListCommandInvocationsOutput, error) { + req, out := c.ListCommandInvocationsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // ListCommandInvocationsPages iterates over the pages of a ListCommandInvocations operation, @@ -4417,12 +5349,37 @@ func (c *SSM) ListCommandInvocations(input *ListCommandInvocationsInput) (*ListC // return pageNum <= 3 // }) // -func (c *SSM) ListCommandInvocationsPages(input *ListCommandInvocationsInput, fn func(p *ListCommandInvocationsOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.ListCommandInvocationsRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*ListCommandInvocationsOutput), lastPage) - }) +func (c *SSM) ListCommandInvocationsPages(input *ListCommandInvocationsInput, fn func(*ListCommandInvocationsOutput, bool) bool) error { + return c.ListCommandInvocationsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListCommandInvocationsPagesWithContext same as ListCommandInvocationsPages 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) ListCommandInvocationsPagesWithContext(ctx aws.Context, input *ListCommandInvocationsInput, fn func(*ListCommandInvocationsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListCommandInvocationsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListCommandInvocationsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*ListCommandInvocationsOutput), !p.HasNextPage()) + } + return p.Err() } const opListCommands = "ListCommands" @@ -4496,12 +5453,12 @@ func (c *SSM) ListCommandsRequest(input *ListCommandsInput) (req *request.Reques // // You do not have permission to access the instance. // -// The SSM agent is not running. On managed instances and Linux instances, verify -// that the SSM agent is running. On EC2 Windows instances, verify that the +// The SSM Agent is not running. On managed instances and Linux instances, verify +// that the SSM Agent is running. On EC2 Windows instances, verify that the // EC2Config service is running. // -// The SSM agent or EC2Config service is not registered to the SSM endpoint. -// Try reinstalling the SSM agent or EC2Config service. +// The SSM Agent or EC2Config service is not registered to the SSM endpoint. +// Try reinstalling the SSM Agent or EC2Config service. // // The instance is not in valid state. Valid states are: Running, Pending, Stopped, // Stopping. Invalid states are: Shutting-down and Terminated. @@ -4515,8 +5472,23 @@ func (c *SSM) ListCommandsRequest(input *ListCommandsInput) (req *request.Reques // Please also see https://docs.aws.amazon.com/goto/WebAPI/ssm-2014-11-06/ListCommands func (c *SSM) ListCommands(input *ListCommandsInput) (*ListCommandsOutput, error) { req, out := c.ListCommandsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListCommandsWithContext is the same as ListCommands with the addition of +// the ability to pass a context and additional request options. +// +// See ListCommands 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 *SSM) ListCommandsWithContext(ctx aws.Context, input *ListCommandsInput, opts ...request.Option) (*ListCommandsOutput, error) { + req, out := c.ListCommandsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // ListCommandsPages iterates over the pages of a ListCommands operation, @@ -4536,12 +5508,37 @@ func (c *SSM) ListCommands(input *ListCommandsInput) (*ListCommandsOutput, error // return pageNum <= 3 // }) // -func (c *SSM) ListCommandsPages(input *ListCommandsInput, fn func(p *ListCommandsOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.ListCommandsRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*ListCommandsOutput), lastPage) - }) +func (c *SSM) ListCommandsPages(input *ListCommandsInput, fn func(*ListCommandsOutput, bool) bool) error { + return c.ListCommandsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListCommandsPagesWithContext same as ListCommandsPages 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) ListCommandsPagesWithContext(ctx aws.Context, input *ListCommandsInput, fn func(*ListCommandsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListCommandsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListCommandsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*ListCommandsOutput), !p.HasNextPage()) + } + return p.Err() } const opListDocumentVersions = "ListDocumentVersions" @@ -4611,8 +5608,23 @@ func (c *SSM) ListDocumentVersionsRequest(input *ListDocumentVersionsInput) (req // Please also see https://docs.aws.amazon.com/goto/WebAPI/ssm-2014-11-06/ListDocumentVersions func (c *SSM) ListDocumentVersions(input *ListDocumentVersionsInput) (*ListDocumentVersionsOutput, error) { req, out := c.ListDocumentVersionsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListDocumentVersionsWithContext is the same as ListDocumentVersions with the addition of +// the ability to pass a context and additional request options. +// +// See ListDocumentVersions 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 *SSM) ListDocumentVersionsWithContext(ctx aws.Context, input *ListDocumentVersionsInput, opts ...request.Option) (*ListDocumentVersionsOutput, error) { + req, out := c.ListDocumentVersionsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opListDocuments = "ListDocuments" @@ -4688,8 +5700,23 @@ func (c *SSM) ListDocumentsRequest(input *ListDocumentsInput) (req *request.Requ // Please also see https://docs.aws.amazon.com/goto/WebAPI/ssm-2014-11-06/ListDocuments func (c *SSM) ListDocuments(input *ListDocumentsInput) (*ListDocumentsOutput, error) { req, out := c.ListDocumentsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListDocumentsWithContext is the same as ListDocuments with the addition of +// the ability to pass a context and additional request options. +// +// See ListDocuments 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 *SSM) ListDocumentsWithContext(ctx aws.Context, input *ListDocumentsInput, opts ...request.Option) (*ListDocumentsOutput, error) { + req, out := c.ListDocumentsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // ListDocumentsPages iterates over the pages of a ListDocuments operation, @@ -4709,12 +5736,37 @@ func (c *SSM) ListDocuments(input *ListDocumentsInput) (*ListDocumentsOutput, er // return pageNum <= 3 // }) // -func (c *SSM) ListDocumentsPages(input *ListDocumentsInput, fn func(p *ListDocumentsOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.ListDocumentsRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*ListDocumentsOutput), lastPage) - }) +func (c *SSM) ListDocumentsPages(input *ListDocumentsInput, fn func(*ListDocumentsOutput, bool) bool) error { + return c.ListDocumentsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListDocumentsPagesWithContext same as ListDocumentsPages 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) ListDocumentsPagesWithContext(ctx aws.Context, input *ListDocumentsInput, fn func(*ListDocumentsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListDocumentsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListDocumentsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*ListDocumentsOutput), !p.HasNextPage()) + } + return p.Err() } const opListInventoryEntries = "ListInventoryEntries" @@ -4780,12 +5832,12 @@ func (c *SSM) ListInventoryEntriesRequest(input *ListInventoryEntriesInput) (req // // You do not have permission to access the instance. // -// The SSM agent is not running. On managed instances and Linux instances, verify -// that the SSM agent is running. On EC2 Windows instances, verify that the +// The SSM Agent is not running. On managed instances and Linux instances, verify +// that the SSM Agent is running. On EC2 Windows instances, verify that the // EC2Config service is running. // -// The SSM agent or EC2Config service is not registered to the SSM endpoint. -// Try reinstalling the SSM agent or EC2Config service. +// The SSM Agent or EC2Config service is not registered to the SSM endpoint. +// Try reinstalling the SSM Agent or EC2Config service. // // The instance is not in valid state. Valid states are: Running, Pending, Stopped, // Stopping. Invalid states are: Shutting-down and Terminated. @@ -4803,8 +5855,23 @@ func (c *SSM) ListInventoryEntriesRequest(input *ListInventoryEntriesInput) (req // Please also see https://docs.aws.amazon.com/goto/WebAPI/ssm-2014-11-06/ListInventoryEntries func (c *SSM) ListInventoryEntries(input *ListInventoryEntriesInput) (*ListInventoryEntriesOutput, error) { req, out := c.ListInventoryEntriesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListInventoryEntriesWithContext is the same as ListInventoryEntries with the addition of +// the ability to pass a context and additional request options. +// +// See ListInventoryEntries 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 *SSM) ListInventoryEntriesWithContext(ctx aws.Context, input *ListInventoryEntriesInput, opts ...request.Option) (*ListInventoryEntriesOutput, error) { + req, out := c.ListInventoryEntriesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opListTagsForResource = "ListTagsForResource" @@ -4876,8 +5943,23 @@ func (c *SSM) ListTagsForResourceRequest(input *ListTagsForResourceInput) (req * // Please also see https://docs.aws.amazon.com/goto/WebAPI/ssm-2014-11-06/ListTagsForResource func (c *SSM) ListTagsForResource(input *ListTagsForResourceInput) (*ListTagsForResourceOutput, error) { req, out := c.ListTagsForResourceRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListTagsForResourceWithContext is the same as ListTagsForResource with the addition of +// the ability to pass a context and additional request options. +// +// See ListTagsForResource 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 *SSM) ListTagsForResourceWithContext(ctx aws.Context, input *ListTagsForResourceInput, opts ...request.Option) (*ListTagsForResourceOutput, error) { + req, out := c.ListTagsForResourceRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opModifyDocumentPermission = "ModifyDocumentPermission" @@ -4925,10 +6007,10 @@ func (c *SSM) ModifyDocumentPermissionRequest(input *ModifyDocumentPermissionInp // ModifyDocumentPermission API operation for Amazon Simple Systems Manager (SSM). // -// Share a document publicly or privately. If you share a document privately, -// you must specify the AWS user account IDs for those people who can use the -// document. If you share a document publicly, you must specify All as the account -// ID. +// Shares a Systems Manager document publicly or privately. If you share a document +// privately, you must specify the AWS user account IDs for those people who +// can use the document. If you share a document publicly, you must specify +// All as the account ID. // // 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 @@ -4959,8 +6041,23 @@ func (c *SSM) ModifyDocumentPermissionRequest(input *ModifyDocumentPermissionInp // Please also see https://docs.aws.amazon.com/goto/WebAPI/ssm-2014-11-06/ModifyDocumentPermission func (c *SSM) ModifyDocumentPermission(input *ModifyDocumentPermissionInput) (*ModifyDocumentPermissionOutput, error) { req, out := c.ModifyDocumentPermissionRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ModifyDocumentPermissionWithContext is the same as ModifyDocumentPermission with the addition of +// the ability to pass a context and additional request options. +// +// See ModifyDocumentPermission 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 *SSM) ModifyDocumentPermissionWithContext(ctx aws.Context, input *ModifyDocumentPermissionInput, opts ...request.Option) (*ModifyDocumentPermissionOutput, error) { + req, out := c.ModifyDocumentPermissionRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opPutInventory = "PutInventory" @@ -5028,12 +6125,12 @@ func (c *SSM) PutInventoryRequest(input *PutInventoryInput) (req *request.Reques // // You do not have permission to access the instance. // -// The SSM agent is not running. On managed instances and Linux instances, verify -// that the SSM agent is running. On EC2 Windows instances, verify that the +// The SSM Agent is not running. On managed instances and Linux instances, verify +// that the SSM Agent is running. On EC2 Windows instances, verify that the // EC2Config service is running. // -// The SSM agent or EC2Config service is not registered to the SSM endpoint. -// Try reinstalling the SSM agent or EC2Config service. +// The SSM Agent or EC2Config service is not registered to the SSM endpoint. +// Try reinstalling the SSM Agent or EC2Config service. // // The instance is not in valid state. Valid states are: Running, Pending, Stopped, // Stopping. Invalid states are: Shutting-down and Terminated. @@ -5065,8 +6162,23 @@ func (c *SSM) PutInventoryRequest(input *PutInventoryInput) (req *request.Reques // Please also see https://docs.aws.amazon.com/goto/WebAPI/ssm-2014-11-06/PutInventory func (c *SSM) PutInventory(input *PutInventoryInput) (*PutInventoryOutput, error) { req, out := c.PutInventoryRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// PutInventoryWithContext is the same as PutInventory with the addition of +// the ability to pass a context and additional request options. +// +// See PutInventory 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 *SSM) PutInventoryWithContext(ctx aws.Context, input *PutInventoryInput, opts ...request.Option) (*PutInventoryOutput, error) { + req, out := c.PutInventoryRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opPutParameter = "PutParameter" @@ -5147,8 +6259,23 @@ func (c *SSM) PutParameterRequest(input *PutParameterInput) (req *request.Reques // Please also see https://docs.aws.amazon.com/goto/WebAPI/ssm-2014-11-06/PutParameter func (c *SSM) PutParameter(input *PutParameterInput) (*PutParameterOutput, error) { req, out := c.PutParameterRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// PutParameterWithContext is the same as PutParameter with the addition of +// the ability to pass a context and additional request options. +// +// See PutParameter 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 *SSM) PutParameterWithContext(ctx aws.Context, input *PutParameterInput, opts ...request.Option) (*PutParameterOutput, error) { + req, out := c.PutParameterRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opRegisterDefaultPatchBaseline = "RegisterDefaultPatchBaseline" @@ -5220,8 +6347,23 @@ func (c *SSM) RegisterDefaultPatchBaselineRequest(input *RegisterDefaultPatchBas // Please also see https://docs.aws.amazon.com/goto/WebAPI/ssm-2014-11-06/RegisterDefaultPatchBaseline func (c *SSM) RegisterDefaultPatchBaseline(input *RegisterDefaultPatchBaselineInput) (*RegisterDefaultPatchBaselineOutput, error) { req, out := c.RegisterDefaultPatchBaselineRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// RegisterDefaultPatchBaselineWithContext is the same as RegisterDefaultPatchBaseline with the addition of +// the ability to pass a context and additional request options. +// +// See RegisterDefaultPatchBaseline 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 *SSM) RegisterDefaultPatchBaselineWithContext(ctx aws.Context, input *RegisterDefaultPatchBaselineInput, opts ...request.Option) (*RegisterDefaultPatchBaselineOutput, error) { + req, out := c.RegisterDefaultPatchBaselineRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opRegisterPatchBaselineForPatchGroup = "RegisterPatchBaselineForPatchGroup" @@ -5301,8 +6443,23 @@ func (c *SSM) RegisterPatchBaselineForPatchGroupRequest(input *RegisterPatchBase // Please also see https://docs.aws.amazon.com/goto/WebAPI/ssm-2014-11-06/RegisterPatchBaselineForPatchGroup func (c *SSM) RegisterPatchBaselineForPatchGroup(input *RegisterPatchBaselineForPatchGroupInput) (*RegisterPatchBaselineForPatchGroupOutput, error) { req, out := c.RegisterPatchBaselineForPatchGroupRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// RegisterPatchBaselineForPatchGroupWithContext is the same as RegisterPatchBaselineForPatchGroup with the addition of +// the ability to pass a context and additional request options. +// +// See RegisterPatchBaselineForPatchGroup 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 *SSM) RegisterPatchBaselineForPatchGroupWithContext(ctx aws.Context, input *RegisterPatchBaselineForPatchGroupInput, opts ...request.Option) (*RegisterPatchBaselineForPatchGroupOutput, error) { + req, out := c.RegisterPatchBaselineForPatchGroupRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opRegisterTargetWithMaintenanceWindow = "RegisterTargetWithMaintenanceWindow" @@ -5378,8 +6535,23 @@ func (c *SSM) RegisterTargetWithMaintenanceWindowRequest(input *RegisterTargetWi // Please also see https://docs.aws.amazon.com/goto/WebAPI/ssm-2014-11-06/RegisterTargetWithMaintenanceWindow func (c *SSM) RegisterTargetWithMaintenanceWindow(input *RegisterTargetWithMaintenanceWindowInput) (*RegisterTargetWithMaintenanceWindowOutput, error) { req, out := c.RegisterTargetWithMaintenanceWindowRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// RegisterTargetWithMaintenanceWindowWithContext is the same as RegisterTargetWithMaintenanceWindow with the addition of +// the ability to pass a context and additional request options. +// +// See RegisterTargetWithMaintenanceWindow 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 *SSM) RegisterTargetWithMaintenanceWindowWithContext(ctx aws.Context, input *RegisterTargetWithMaintenanceWindowInput, opts ...request.Option) (*RegisterTargetWithMaintenanceWindowOutput, error) { + req, out := c.RegisterTargetWithMaintenanceWindowRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opRegisterTaskWithMaintenanceWindow = "RegisterTaskWithMaintenanceWindow" @@ -5455,8 +6627,23 @@ func (c *SSM) RegisterTaskWithMaintenanceWindowRequest(input *RegisterTaskWithMa // Please also see https://docs.aws.amazon.com/goto/WebAPI/ssm-2014-11-06/RegisterTaskWithMaintenanceWindow func (c *SSM) RegisterTaskWithMaintenanceWindow(input *RegisterTaskWithMaintenanceWindowInput) (*RegisterTaskWithMaintenanceWindowOutput, error) { req, out := c.RegisterTaskWithMaintenanceWindowRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// RegisterTaskWithMaintenanceWindowWithContext is the same as RegisterTaskWithMaintenanceWindow with the addition of +// the ability to pass a context and additional request options. +// +// See RegisterTaskWithMaintenanceWindow 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 *SSM) RegisterTaskWithMaintenanceWindowWithContext(ctx aws.Context, input *RegisterTaskWithMaintenanceWindowInput, opts ...request.Option) (*RegisterTaskWithMaintenanceWindowOutput, error) { + req, out := c.RegisterTaskWithMaintenanceWindowRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opRemoveTagsFromResource = "RemoveTagsFromResource" @@ -5528,8 +6715,23 @@ func (c *SSM) RemoveTagsFromResourceRequest(input *RemoveTagsFromResourceInput) // Please also see https://docs.aws.amazon.com/goto/WebAPI/ssm-2014-11-06/RemoveTagsFromResource func (c *SSM) RemoveTagsFromResource(input *RemoveTagsFromResourceInput) (*RemoveTagsFromResourceOutput, error) { req, out := c.RemoveTagsFromResourceRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// RemoveTagsFromResourceWithContext is the same as RemoveTagsFromResource with the addition of +// the ability to pass a context and additional request options. +// +// See RemoveTagsFromResource 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 *SSM) RemoveTagsFromResourceWithContext(ctx aws.Context, input *RemoveTagsFromResourceInput, opts ...request.Option) (*RemoveTagsFromResourceOutput, error) { + req, out := c.RemoveTagsFromResourceRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opSendCommand = "SendCommand" @@ -5598,12 +6800,12 @@ func (c *SSM) SendCommandRequest(input *SendCommandInput) (req *request.Request, // // You do not have permission to access the instance. // -// The SSM agent is not running. On managed instances and Linux instances, verify -// that the SSM agent is running. On EC2 Windows instances, verify that the +// The SSM Agent is not running. On managed instances and Linux instances, verify +// that the SSM Agent is running. On EC2 Windows instances, verify that the // EC2Config service is running. // -// The SSM agent or EC2Config service is not registered to the SSM endpoint. -// Try reinstalling the SSM agent or EC2Config service. +// The SSM Agent or EC2Config service is not registered to the SSM endpoint. +// Try reinstalling the SSM Agent or EC2Config service. // // The instance is not in valid state. Valid states are: Running, Pending, Stopped, // Stopping. Invalid states are: Shutting-down and Terminated. @@ -5620,17 +6822,17 @@ func (c *SSM) SendCommandRequest(input *SendCommandInput) (req *request.Request, // // * ErrCodeUnsupportedPlatformType "UnsupportedPlatformType" // The document does not support the platform type of the given instance ID(s). -// For example, you sent an SSM document for a Windows instance to a Linux instance. +// For example, you sent an document for a Windows instance to a Linux instance. // // * ErrCodeMaxDocumentSizeExceeded "MaxDocumentSizeExceeded" -// The size limit of an SSM document is 64 KB. +// The size limit of a document is 64 KB. // // * ErrCodeInvalidRole "InvalidRole" // 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 Getting Amazon SNS Notifications When a Command Changes Status (http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/rc-sns.html) -// in the Amazon Elastic Compute Cloud User Guide . +// see Configuring Amazon SNS Notifications for Run Command (http://docs.aws.amazon.com/systems-manager/latest/userguide/rc-sns-notifications.html) +// in the Amazon EC2 Systems Manager User Guide. // // * ErrCodeInvalidNotificationConfig "InvalidNotificationConfig" // One or more configuration items is not valid. Verify that a valid Amazon @@ -5639,8 +6841,23 @@ func (c *SSM) SendCommandRequest(input *SendCommandInput) (req *request.Request, // Please also see https://docs.aws.amazon.com/goto/WebAPI/ssm-2014-11-06/SendCommand func (c *SSM) SendCommand(input *SendCommandInput) (*SendCommandOutput, error) { req, out := c.SendCommandRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// SendCommandWithContext is the same as SendCommand with the addition of +// the ability to pass a context and additional request options. +// +// See SendCommand 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 *SSM) SendCommandWithContext(ctx aws.Context, input *SendCommandInput, opts ...request.Option) (*SendCommandOutput, error) { + req, out := c.SendCommandRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opStartAutomationExecution = "StartAutomationExecution" @@ -5719,8 +6936,23 @@ func (c *SSM) StartAutomationExecutionRequest(input *StartAutomationExecutionInp // Please also see https://docs.aws.amazon.com/goto/WebAPI/ssm-2014-11-06/StartAutomationExecution func (c *SSM) StartAutomationExecution(input *StartAutomationExecutionInput) (*StartAutomationExecutionOutput, error) { req, out := c.StartAutomationExecutionRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// StartAutomationExecutionWithContext is the same as StartAutomationExecution with the addition of +// the ability to pass a context and additional request options. +// +// See StartAutomationExecution 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 *SSM) StartAutomationExecutionWithContext(ctx aws.Context, input *StartAutomationExecutionInput, opts ...request.Option) (*StartAutomationExecutionOutput, error) { + req, out := c.StartAutomationExecutionRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opStopAutomationExecution = "StopAutomationExecution" @@ -5788,8 +7020,23 @@ func (c *SSM) StopAutomationExecutionRequest(input *StopAutomationExecutionInput // Please also see https://docs.aws.amazon.com/goto/WebAPI/ssm-2014-11-06/StopAutomationExecution func (c *SSM) StopAutomationExecution(input *StopAutomationExecutionInput) (*StopAutomationExecutionOutput, error) { req, out := c.StopAutomationExecutionRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// StopAutomationExecutionWithContext is the same as StopAutomationExecution with the addition of +// the ability to pass a context and additional request options. +// +// See StopAutomationExecution 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 *SSM) StopAutomationExecutionWithContext(ctx aws.Context, input *StopAutomationExecutionInput, opts ...request.Option) (*StopAutomationExecutionOutput, error) { + req, out := c.StopAutomationExecutionRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opUpdateAssociation = "UpdateAssociation" @@ -5877,8 +7124,23 @@ func (c *SSM) UpdateAssociationRequest(input *UpdateAssociationInput) (req *requ // Please also see https://docs.aws.amazon.com/goto/WebAPI/ssm-2014-11-06/UpdateAssociation func (c *SSM) UpdateAssociation(input *UpdateAssociationInput) (*UpdateAssociationOutput, error) { req, out := c.UpdateAssociationRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// UpdateAssociationWithContext is the same as UpdateAssociation with the addition of +// the ability to pass a context and additional request options. +// +// See UpdateAssociation 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 *SSM) UpdateAssociationWithContext(ctx aws.Context, input *UpdateAssociationInput, opts ...request.Option) (*UpdateAssociationOutput, error) { + req, out := c.UpdateAssociationRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opUpdateAssociationStatus = "UpdateAssociationStatus" @@ -5926,7 +7188,8 @@ func (c *SSM) UpdateAssociationStatusRequest(input *UpdateAssociationStatusInput // UpdateAssociationStatus API operation for Amazon Simple Systems Manager (SSM). // -// Updates the status of the SSM document associated with the specified instance. +// Updates the status of the Systems Manager document associated with the specified +// 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 @@ -5944,12 +7207,12 @@ func (c *SSM) UpdateAssociationStatusRequest(input *UpdateAssociationStatusInput // // You do not have permission to access the instance. // -// The SSM agent is not running. On managed instances and Linux instances, verify -// that the SSM agent is running. On EC2 Windows instances, verify that the +// The SSM Agent is not running. On managed instances and Linux instances, verify +// that the SSM Agent is running. On EC2 Windows instances, verify that the // EC2Config service is running. // -// The SSM agent or EC2Config service is not registered to the SSM endpoint. -// Try reinstalling the SSM agent or EC2Config service. +// The SSM Agent or EC2Config service is not registered to the SSM endpoint. +// Try reinstalling the SSM Agent or EC2Config service. // // The instance is not in valid state. Valid states are: Running, Pending, Stopped, // Stopping. Invalid states are: Shutting-down and Terminated. @@ -5970,8 +7233,23 @@ func (c *SSM) UpdateAssociationStatusRequest(input *UpdateAssociationStatusInput // Please also see https://docs.aws.amazon.com/goto/WebAPI/ssm-2014-11-06/UpdateAssociationStatus func (c *SSM) UpdateAssociationStatus(input *UpdateAssociationStatusInput) (*UpdateAssociationStatusOutput, error) { req, out := c.UpdateAssociationStatusRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// UpdateAssociationStatusWithContext is the same as UpdateAssociationStatus with the addition of +// the ability to pass a context and additional request options. +// +// See UpdateAssociationStatus 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 *SSM) UpdateAssociationStatusWithContext(ctx aws.Context, input *UpdateAssociationStatusInput, opts ...request.Option) (*UpdateAssociationStatusOutput, error) { + req, out := c.UpdateAssociationStatusRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opUpdateDocument = "UpdateDocument" @@ -6030,7 +7308,7 @@ func (c *SSM) UpdateDocumentRequest(input *UpdateDocumentInput) (req *request.Re // // Returned Error Codes: // * ErrCodeMaxDocumentSizeExceeded "MaxDocumentSizeExceeded" -// The size limit of an SSM document is 64 KB. +// The size limit of a document is 64 KB. // // * ErrCodeDocumentVersionLimitExceeded "DocumentVersionLimitExceeded" // The document has too many versions. Delete one or more document versions @@ -6044,7 +7322,7 @@ func (c *SSM) UpdateDocumentRequest(input *UpdateDocumentInput) (req *request.Re // the content of the document and try again. // // * ErrCodeInvalidDocumentContent "InvalidDocumentContent" -// The content for the SSM document is not valid. +// The content for the document is not valid. // // * ErrCodeInvalidDocumentVersion "InvalidDocumentVersion" // The document version is not valid or does not exist. @@ -6058,8 +7336,23 @@ func (c *SSM) UpdateDocumentRequest(input *UpdateDocumentInput) (req *request.Re // Please also see https://docs.aws.amazon.com/goto/WebAPI/ssm-2014-11-06/UpdateDocument func (c *SSM) UpdateDocument(input *UpdateDocumentInput) (*UpdateDocumentOutput, error) { req, out := c.UpdateDocumentRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// UpdateDocumentWithContext is the same as UpdateDocument with the addition of +// the ability to pass a context and additional request options. +// +// See UpdateDocument 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 *SSM) UpdateDocumentWithContext(ctx aws.Context, input *UpdateDocumentInput, opts ...request.Option) (*UpdateDocumentOutput, error) { + req, out := c.UpdateDocumentRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opUpdateDocumentDefaultVersion = "UpdateDocumentDefaultVersion" @@ -6132,8 +7425,23 @@ func (c *SSM) UpdateDocumentDefaultVersionRequest(input *UpdateDocumentDefaultVe // Please also see https://docs.aws.amazon.com/goto/WebAPI/ssm-2014-11-06/UpdateDocumentDefaultVersion func (c *SSM) UpdateDocumentDefaultVersion(input *UpdateDocumentDefaultVersionInput) (*UpdateDocumentDefaultVersionOutput, error) { req, out := c.UpdateDocumentDefaultVersionRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// UpdateDocumentDefaultVersionWithContext is the same as UpdateDocumentDefaultVersion with the addition of +// the ability to pass a context and additional request options. +// +// See UpdateDocumentDefaultVersion 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 *SSM) UpdateDocumentDefaultVersionWithContext(ctx aws.Context, input *UpdateDocumentDefaultVersionInput, opts ...request.Option) (*UpdateDocumentDefaultVersionOutput, error) { + req, out := c.UpdateDocumentDefaultVersionRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opUpdateMaintenanceWindow = "UpdateMaintenanceWindow" @@ -6201,8 +7509,23 @@ func (c *SSM) UpdateMaintenanceWindowRequest(input *UpdateMaintenanceWindowInput // Please also see https://docs.aws.amazon.com/goto/WebAPI/ssm-2014-11-06/UpdateMaintenanceWindow func (c *SSM) UpdateMaintenanceWindow(input *UpdateMaintenanceWindowInput) (*UpdateMaintenanceWindowOutput, error) { req, out := c.UpdateMaintenanceWindowRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// UpdateMaintenanceWindowWithContext is the same as UpdateMaintenanceWindow with the addition of +// the ability to pass a context and additional request options. +// +// See UpdateMaintenanceWindow 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 *SSM) UpdateMaintenanceWindowWithContext(ctx aws.Context, input *UpdateMaintenanceWindowInput, opts ...request.Option) (*UpdateMaintenanceWindowOutput, error) { + req, out := c.UpdateMaintenanceWindowRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opUpdateManagedInstanceRole = "UpdateManagedInstanceRole" @@ -6266,12 +7589,12 @@ func (c *SSM) UpdateManagedInstanceRoleRequest(input *UpdateManagedInstanceRoleI // // You do not have permission to access the instance. // -// The SSM agent is not running. On managed instances and Linux instances, verify -// that the SSM agent is running. On EC2 Windows instances, verify that the +// The SSM Agent is not running. On managed instances and Linux instances, verify +// that the SSM Agent is running. On EC2 Windows instances, verify that the // EC2Config service is running. // -// The SSM agent or EC2Config service is not registered to the SSM endpoint. -// Try reinstalling the SSM agent or EC2Config service. +// The SSM Agent or EC2Config service is not registered to the SSM endpoint. +// Try reinstalling the SSM Agent or EC2Config service. // // The instance is not in valid state. Valid states are: Running, Pending, Stopped, // Stopping. Invalid states are: Shutting-down and Terminated. @@ -6282,8 +7605,23 @@ func (c *SSM) UpdateManagedInstanceRoleRequest(input *UpdateManagedInstanceRoleI // Please also see https://docs.aws.amazon.com/goto/WebAPI/ssm-2014-11-06/UpdateManagedInstanceRole func (c *SSM) UpdateManagedInstanceRole(input *UpdateManagedInstanceRoleInput) (*UpdateManagedInstanceRoleOutput, error) { req, out := c.UpdateManagedInstanceRoleRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// UpdateManagedInstanceRoleWithContext is the same as UpdateManagedInstanceRole with the addition of +// the ability to pass a context and additional request options. +// +// See UpdateManagedInstanceRole 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 *SSM) UpdateManagedInstanceRoleWithContext(ctx aws.Context, input *UpdateManagedInstanceRoleInput, opts ...request.Option) (*UpdateManagedInstanceRoleOutput, error) { + req, out := c.UpdateManagedInstanceRoleRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opUpdatePatchBaseline = "UpdatePatchBaseline" @@ -6352,8 +7690,23 @@ func (c *SSM) UpdatePatchBaselineRequest(input *UpdatePatchBaselineInput) (req * // Please also see https://docs.aws.amazon.com/goto/WebAPI/ssm-2014-11-06/UpdatePatchBaseline func (c *SSM) UpdatePatchBaseline(input *UpdatePatchBaselineInput) (*UpdatePatchBaselineOutput, error) { req, out := c.UpdatePatchBaselineRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// UpdatePatchBaselineWithContext is the same as UpdatePatchBaseline with the addition of +// the ability to pass a context and additional request options. +// +// See UpdatePatchBaseline 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 *SSM) UpdatePatchBaselineWithContext(ctx aws.Context, input *UpdatePatchBaselineInput, opts ...request.Option) (*UpdatePatchBaselineOutput, error) { + req, out := c.UpdatePatchBaselineRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // An activation registers one or more on-premises servers or virtual machines @@ -6551,7 +7904,7 @@ func (s AddTagsToResourceOutput) GoString() string { return s.String() } -// Describes an association of an SSM document and an instance. +// Describes an association of a Systems Manager document and an instance. // Please also see https://docs.aws.amazon.com/goto/WebAPI/ssm-2014-11-06/Association type Association struct { _ struct{} `type:"structure"` @@ -7319,7 +8672,7 @@ type Command struct { // Timed Out, Delivery Timed Out, Canceled, Terminated, or Undeliverable. CompletedCount *int64 `type:"integer"` - // The name of the SSM document requested for execution. + // The name of the document requested for execution. DocumentName *string `type:"string"` // The number of targets for which the status is Failed or Execution Timed Out. @@ -7336,19 +8689,15 @@ type Command struct { // The maximum number of instances that are allowed to execute 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 Executing a Command Using Amazon EC2 - // Run Command (http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/run-command.html) - // (Linux) or Executing a Command Using Amazon EC2 Run Command (http://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/run-command.html) - // (Windows). + // about how to use MaxConcurrency, see Executing a Command Using Systems Manager + // Run Command (http://docs.aws.amazon.com/systems-manager/latest/userguide/run-command.html). 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 50. For // more information about how to use MaxErrors, see Executing a Command Using - // Amazon EC2 Run Command (http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/run-command.html) - // (Linux) or Executing a Command Using Amazon EC2 Run Command (http://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/run-command.html) - // (Windows). + // Systems Manager Run Command (http://docs.aws.amazon.com/systems-manager/latest/userguide/run-command.html). MaxErrors *string `min:"1" type:"string"` // Configurations for sending notifications about command status changes. @@ -7366,8 +8715,7 @@ type Command struct { // is located. The default value is the region where Run Command is being called. OutputS3Region *string `min:"3" type:"string"` - // The parameter values to be inserted in the SSM document when executing the - // command. + // The parameter values to be inserted in the document when executing the command. Parameters map[string][]*string `type:"map"` // The date and time the command was requested. @@ -7383,9 +8731,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 Monitor Commands (http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/monitor-commands.html) - // (Linux) or Monitor Commands (http://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/monitor-commands.html) - // (Windows). StatusDetails can be one of the following values: + // For more information about these statuses, see Run Command Status (http://docs.aws.amazon.com/systems-manager/latest/userguide/monitor-about-status.html). + // StatusDetails can be one of the following values: // // * Pending – The command has not been sent to any instances. // @@ -7419,7 +8766,7 @@ type Command struct { // The number of targets for the command. TargetCount *int64 `type:"integer"` - // An array of search criteria that targets instances using a Key;Value combination + // 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. Targets []*Target `type:"list"` @@ -7671,9 +9018,8 @@ 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 Monitor Commands (http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/monitor-commands.html) - // (Linux) or Monitor Commands (http://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/monitor-commands.html) - // (Windows). StatusDetails can be one of the following values: + // about these statuses, see Run Command Status (http://docs.aws.amazon.com/systems-manager/latest/userguide/monitor-about-status.html). + // StatusDetails can be one of the following values: // // * Pending – The command has not been sent to the instance. // @@ -7881,9 +9227,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 Monitor Commands (http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/monitor-commands.html) - // (Linux) or Monitor Commands (http://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/monitor-commands.html) - // (Windows). StatusDetails can be one of the following values: + // For more information about these statuses, see Run Command Status (http://docs.aws.amazon.com/systems-manager/latest/userguide/monitor-about-status.html). + // StatusDetails can be one of the following values: // // * Pending – The command has not been sent to the instance. // @@ -8208,7 +9553,7 @@ func (s *CreateAssociationBatchOutput) SetSuccessful(v []*AssociationDescription return s } -// Describes the association of an SSM document and an instance. +// Describes the association of a Systems Manager document and an instance. // Please also see https://docs.aws.amazon.com/goto/WebAPI/ssm-2014-11-06/CreateAssociationBatchRequestEntry type CreateAssociationBatchRequestEntry struct { _ struct{} `type:"structure"` @@ -8331,7 +9676,7 @@ type CreateAssociationInput struct { // The instance ID. InstanceId *string `type:"string"` - // The name of the SSM document. + // The name of the Systems Manager document. // // Name is a required field Name *string `type:"string" required:"true"` @@ -8479,7 +9824,7 @@ type CreateDocumentInput struct { // and Command. DocumentType *string `type:"string" enum:"DocumentType"` - // A name for the SSM document. + // A name for the Systems Manager document. // // Name is a required field Name *string `type:"string" required:"true"` @@ -8536,7 +9881,7 @@ func (s *CreateDocumentInput) SetName(v string) *CreateDocumentInput { type CreateDocumentOutput struct { _ struct{} `type:"structure"` - // Information about the SSM document. + // Information about the Systems Manager document. DocumentDescription *DocumentDescription `type:"structure"` } @@ -8898,7 +10243,7 @@ type DeleteAssociationInput struct { // The ID of the instance. InstanceId *string `type:"string"` - // The name of the SSM document. + // The name of the Systems Manager document. Name *string `type:"string"` } @@ -8949,7 +10294,7 @@ func (s DeleteAssociationOutput) GoString() string { type DeleteDocumentInput struct { _ struct{} `type:"structure"` - // The name of the SSM document. + // The name of the document. // // Name is a required field Name *string `type:"string" required:"true"` @@ -12005,7 +13350,7 @@ func (s *DocumentDefaultVersionDescription) SetName(v string) *DocumentDefaultVe type DocumentDescription struct { _ struct{} `type:"structure"` - // The date when the SSM document was created. + // The date when the document was created. CreatedDate *time.Time `type:"timestamp" timestampFormat:"unix"` // The default version. @@ -12282,8 +13627,8 @@ func (s *DocumentIdentifier) SetSchemaVersion(v string) *DocumentIdentifier { return s } -// Parameters specified in the SSM document that execute on the server when -// the command is run. +// Parameters specified in a System Manager document that execute on the server +// when the command is run. // Please also see https://docs.aws.amazon.com/goto/WebAPI/ssm-2014-11-06/DocumentParameter type DocumentParameter struct { _ struct{} `type:"structure"` @@ -12559,8 +13904,8 @@ type GetCommandInvocationInput struct { InstanceId *string `type:"string" required:"true"` // (Optional) The name of the plugin for which you want detailed results. If - // the SSM document contains only one plugin, the name can be omitted and the - // details will be returned. + // the document contains only one plugin, the name can be omitted and the details + // will be returned. PluginName *string `min:"4" type:"string"` } @@ -12624,8 +13969,7 @@ type GetCommandInvocationOutput struct { // The comment text for the command. Comment *string `type:"string"` - // The name of the SSM document that was executed. For example, AWS-RunShellScript - // is an SSM document. + // The name of the document that was executed. For example, AWS-RunShellScript. DocumentName *string `type:"string"` // Duration since ExecutionStartDateTime. @@ -12679,10 +14023,9 @@ type GetCommandInvocationOutput struct { // A detailed status of the command execution for an invocation. 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 Monitor - // Commands (http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/monitor-commands.html) - // (Linux) or Monitor Commands (http://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/monitor-commands.html) - // (Windows). StatusDetails can be one of the following values: + // results than Status. For more information about these statuses, see Run Command + // Status (http://docs.aws.amazon.com/systems-manager/latest/userguide/monitor-about-status.html). + // StatusDetails can be one of the following values: // // * Pending – The command has not been sent to the instance. // @@ -13904,7 +15247,7 @@ type GetParametersOutput struct { // executed. InvalidParameters []*string `min:"1" type:"list"` - // A list of parameters used by the AWS account. + // A list of details for a parameter. Parameters []*Parameter `type:"list"` } @@ -14409,7 +15752,7 @@ type InstanceInformation struct { // The activation ID created by Systems Manager when the server or VM was registered. ActivationId *string `type:"string"` - // The version of the SSM agent running on your Linux instance. + // The version of the SSM Agent running on your Linux instance. AgentVersion *string `type:"string"` // Information about the association. @@ -14431,7 +15774,7 @@ type InstanceInformation struct { // The instance ID. InstanceId *string `type:"string"` - // Indicates whether latest version of the SSM agent is running on your instance. + // Indicates whether latest version of the SSM Agent is running on your instance. IsLatestVersion *bool `type:"boolean"` // The date the association was last executed. @@ -14446,7 +15789,7 @@ type InstanceInformation struct { // The name of the managed instance. Name *string `type:"string"` - // Connection status of the SSM agent. + // Connection status of the SSM Agent. PingStatus *string `type:"string" enum:"PingStatus"` // The name of the operating system platform running on your instance. @@ -16894,8 +18237,9 @@ 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 Monitoring Commands (http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/monitor-commands.html) - // in the Amazon Elastic Compute Cloud User Guide . + // Failed. To learn more about these events, see Setting Up Events and Notifications + // (http://docs.aws.amazon.com/systems-manager/latest/userguide/monitor-commands.html) + // in the Amazon EC2 Systems Manager User Guide. NotificationEvents []*string `type:"list"` // Command: Receive notification when the status of a command changes. Invocation: @@ -17879,7 +19223,7 @@ type PutParameterInput struct { // Name is a required field Name *string `min:"1" type:"string" required:"true"` - // Overwrite an existing parameter. + // Overwrite an existing parameter. If not specified, will default to "false". Overwrite *bool `type:"boolean"` // The type of parameter that you want to add to the system. @@ -18720,8 +20064,8 @@ type SendCommandInput struct { // Sha1 hashes have been deprecated. DocumentHashType *string `type:"string" enum:"DocumentHashType"` - // Required. The name of the SSM document to execute. This can be an SSM public - // document or a custom document. + // Required. The name of the Systems Manager document to execute. This can be + // a public document or a custom document. // // DocumentName is a required field DocumentName *string `type:"string" required:"true"` @@ -18733,20 +20077,16 @@ type SendCommandInput struct { // (Optional) The maximum number of instances that are allowed to execute 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 Executing a Command Using Amazon EC2 Run Command - // (http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/run-command.html) (Linux) - // or Executing a Command Using Amazon EC2 Run Command (http://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/run-command.html) - // (Windows). + // use MaxConcurrency, see Executing a Command Using Systems Manager Run Command + // (http://docs.aws.amazon.com/systems-manager/latest/userguide/run-command.html). MaxConcurrency *string `min:"1" type:"string"` // The maximum number of errors allowed without the command failing. When the // 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 50. For more information - // about how to use MaxErrors, see Executing a Command Using Amazon EC2 Run - // Command (http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/run-command.html) - // (Linux) or Executing a Command Using Amazon EC2 Run Command (http://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/run-command.html) - // (Windows). + // about how to use MaxErrors, see Executing a Command Using Systems Manager + // Run Command (http://docs.aws.amazon.com/systems-manager/latest/userguide/run-command.html). MaxErrors *string `min:"1" type:"string"` // Configurations for sending notifications. @@ -18764,19 +20104,16 @@ type SendCommandInput struct { // is being called. OutputS3Region *string `min:"3" type:"string"` - // The required and optional parameters specified in the SSM document being - // executed. + // The required and optional parameters specified in the document being executed. Parameters map[string][]*string `type:"map"` // The IAM role that Systems Manager uses to send notifications. ServiceRoleArn *string `type:"string"` - // (Optional) An array of search criteria that targets instances using a Key;Value + // (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 Executing a Command Using Amazon EC2 Run Command (http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/run-command.html) - // (Linux) or Executing a Command Using Amazon EC2 Run Command (http://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/run-command.html) - // (Windows). + // see Executing a Command Using Systems Manager Run Command (http://docs.aws.amazon.com/systems-manager/latest/userguide/run-command.html). Targets []*Target `type:"list"` // If this time is reached and the command has not already started executing, @@ -19261,7 +20598,7 @@ func (s *Tag) SetValue(v string) *Tag { return s } -// An array of search criteria that targets instances using a Key;Value combination +// 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. // Please also see https://docs.aws.amazon.com/goto/WebAPI/ssm-2014-11-06/Target @@ -19269,21 +20606,16 @@ type Target struct { _ struct{} `type:"structure"` // User-defined criteria for sending commands that target instances that meet - // the criteria. Key can be tag: or name:. For example, tag:ServerRole or name:0123456789012345. For more information - // about how to send commands that target instances using Key;Value parameters, - // see Executing a Command Using Amazon EC2 Run Command (http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/run-command.html) - // (Linux) or Executing a Command Using Amazon EC2 Run Command (http://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/run-command.html) - // (Windows). + // the criteria. Key can be tag: or InstanceIds. For more information + // about how to send commands that target instances using Key,Value parameters, + // see Executing a Command Using Systems Manager Run Command (http://docs.aws.amazon.com/systems-manager/latest/userguide/run-command.html). Key *string `min:"1" type:"string"` // User-defined criteria that maps to Key. For example, if you specified tag:ServerRole, // you could specify value:WebServer to execute a command on instances that - // include Amazon EC2 tags of ServerRole;WebServer. For more information about - // how to send commands that target instances using Key;Value parameters, see - // Executing a Command Using Amazon EC2 Run Command (http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/run-command.html) - // (Linux) or Executing a Command Using Amazon EC2 Run Command (http://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/run-command.html) - // (Windows). + // include Amazon EC2 tags of ServerRole,WebServer. For more information about + // how to send commands that target instances using Key,Value parameters, see + // Executing a Command Using Systems Manager Run Command (http://docs.aws.amazon.com/systems-manager/latest/userguide/run-command.html). Values []*string `type:"list"` } 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 new file mode 100644 index 000000000..8f15668bd --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/service/ssm/doc.go @@ -0,0 +1,92 @@ +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. + +// Package ssm provides the client and types for making API +// requests to Amazon Simple Systems Manager (SSM). +// +// Amazon EC2 Systems Manager is a collection of capabilities that helps you +// automate management tasks such as collecting system inventory, applying operating +// 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. +// +// This reference is intended to be used with the Amazon EC2 Systems Manager +// User Guide (http://docs.aws.amazon.com/systems-manager/latest/userguide/). +// +// To get started, verify prerequisites and configure managed instances. For +// more information, see Systems Manager Prerequisites (http://docs.aws.amazon.com/systems-manager/latest/userguide/systems-manager-prereqs.html). +// +// See https://docs.aws.amazon.com/goto/WebAPI/ssm-2014-11-06 for more information on this service. +// +// See ssm package documentation for more information. +// https://docs.aws.amazon.com/sdk-for-go/api/service/ssm/ +// +// Using the Client +// +// To use the client for Amazon Simple Systems Manager (SSM) you will first need +// to create a new instance of it. +// +// When creating a client for an AWS service you'll first need to have a Session +// already created. The Session provides configuration that can be shared +// between multiple service clients. Additional configuration can be applied to +// the Session and service's client when they are constructed. The aws package's +// Config type contains several fields such as Region for the AWS Region the +// client should make API requests too. The optional Config value can be provided +// as the variadic argument for Sessions and client creation. +// +// Once the service's client is created you can use it to make API requests the +// AWS service. These clients are safe to use concurrently. +// +// // Create a session to share configuration, and load external configuration. +// sess := session.Must(session.NewSession()) +// +// // Create the service's client with the session. +// svc := ssm.New(sess) +// +// See the SDK's documentation for more information on how to use service clients. +// https://docs.aws.amazon.com/sdk-for-go/api/ +// +// See aws package's Config type for more information on configuration options. +// https://docs.aws.amazon.com/sdk-for-go/api/aws/#Config +// +// See the Amazon Simple Systems Manager (SSM) client SSM for more +// information on creating the service's client. +// https://docs.aws.amazon.com/sdk-for-go/api/service/ssm/#New +// +// Once the client is created you can make an API request to the service. +// Each API method takes a input parameter, and returns the service response +// and an error. +// +// The API method will document which error codes the service can be returned +// by the operation if the service models the API operation's errors. These +// errors will also be available as const strings prefixed with "ErrCode". +// +// result, err := svc.AddTagsToResource(params) +// if err != nil { +// // Cast err to awserr.Error to handle specific error codes. +// aerr, ok := err.(awserr.Error) +// if ok && aerr.Code() == { +// // Specific error code handling +// } +// return err +// } +// +// fmt.Println("AddTagsToResource result:") +// fmt.Println(result) +// +// Using the Client with Context +// +// The service's client also provides methods to make API requests with a Context +// value. This allows you to control the timeout, and cancellation of pending +// requests. These methods also take request Option as variadic parameter to apply +// additional configuration to the API request. +// +// ctx := context.Background() +// +// result, err := svc.AddTagsToResourceWithContext(ctx, params) +// +// See the request package documentation for more information on using Context pattern +// with the SDK. +// https://docs.aws.amazon.com/sdk-for-go/api/aws/request/ +package ssm 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 bea03cfa9..2107a874f 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 @@ -1,4 +1,4 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. package ssm @@ -14,7 +14,7 @@ const ( // ErrCodeAssociatedInstances for service response error code // "AssociatedInstances". // - // You must disassociate an SSM document from all instances before you can delete + // You must disassociate a document from all instances before you can delete // it. ErrCodeAssociatedInstances = "AssociatedInstances" @@ -72,7 +72,7 @@ const ( // ErrCodeDocumentAlreadyExists for service response error code // "DocumentAlreadyExists". // - // The specified SSM document already exists. + // The specified document already exists. ErrCodeDocumentAlreadyExists = "DocumentAlreadyExists" // ErrCodeDocumentLimitExceeded for service response error code @@ -164,7 +164,7 @@ const ( // ErrCodeInvalidDocumentContent for service response error code // "InvalidDocumentContent". // - // The content for the SSM document is not valid. + // The content for the document is not valid. ErrCodeInvalidDocumentContent = "InvalidDocumentContent" // ErrCodeInvalidDocumentOperation for service response error code @@ -212,12 +212,12 @@ const ( // // You do not have permission to access the instance. // - // The SSM agent is not running. On managed instances and Linux instances, verify - // that the SSM agent is running. On EC2 Windows instances, verify that the + // The SSM Agent is not running. On managed instances and Linux instances, verify + // that the SSM Agent is running. On EC2 Windows instances, verify that the // EC2Config service is running. // - // The SSM agent or EC2Config service is not registered to the SSM endpoint. - // Try reinstalling the SSM agent or EC2Config service. + // The SSM Agent or EC2Config service is not registered to the SSM endpoint. + // Try reinstalling the SSM Agent or EC2Config service. // // The instance is not in valid state. Valid states are: Running, Pending, Stopped, // Stopping. Invalid states are: Shutting-down and Terminated. @@ -312,8 +312,8 @@ 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 Getting Amazon SNS Notifications When a Command Changes Status (http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/rc-sns.html) - // in the Amazon Elastic Compute Cloud User Guide . + // see Configuring Amazon SNS Notifications for Run Command (http://docs.aws.amazon.com/systems-manager/latest/userguide/rc-sns-notifications.html) + // in the Amazon EC2 Systems Manager User Guide. ErrCodeInvalidRole = "InvalidRole" // ErrCodeInvalidSchedule for service response error code @@ -363,7 +363,7 @@ const ( // ErrCodeMaxDocumentSizeExceeded for service response error code // "MaxDocumentSizeExceeded". // - // The size limit of an SSM document is 64 KB. + // The size limit of a document is 64 KB. ErrCodeMaxDocumentSizeExceeded = "MaxDocumentSizeExceeded" // ErrCodeParameterAlreadyExists for service response error code @@ -443,6 +443,6 @@ const ( // "UnsupportedPlatformType". // // The document does not support the platform type of the given instance ID(s). - // For example, you sent an SSM document for a Windows instance to a Linux instance. + // For example, you sent an document for a Windows instance to a Linux instance. ErrCodeUnsupportedPlatformType = "UnsupportedPlatformType" ) diff --git a/vendor/github.com/aws/aws-sdk-go/service/ssm/service.go b/vendor/github.com/aws/aws-sdk-go/service/ssm/service.go index 9e9026883..d414fb7d8 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/ssm/service.go +++ b/vendor/github.com/aws/aws-sdk-go/service/ssm/service.go @@ -1,4 +1,4 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. package ssm @@ -11,24 +11,12 @@ import ( "github.com/aws/aws-sdk-go/private/protocol/jsonrpc" ) -// Amazon EC2 Systems Manager is a collection of capabilities that helps you -// automate management tasks such as collecting system inventory, applying operating -// system (OS) patches, automating the creation of Amazon Machine Images (AMIs), -// and configuring operating systems (OSs) and applications at scale. Systems -// Manager works with managed instances: Amazon EC2 instances and servers or -// virtual machines (VMs) in your on-premises environment that are configured -// for Systems Manager. +// SSM provides the API operation methods for making requests to +// Amazon Simple Systems Manager (SSM). See this package's package overview docs +// for details on the service. // -// This references is intended to be used with the EC2 Systems Manager User -// Guide (Linux (http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/systems-manager.html)) -// (Windows (http://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/systems-manager.html)). -// -// To get started, verify prerequisites and configure managed instances (Linux -// (http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/systems-manager-prereqs.html)) -// (Windows (http://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/systems-manager-prereqs.html)). -// The service client's operations are safe to be used concurrently. -// It is not safe to mutate any of the client's properties though. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/ssm-2014-11-06 +// SSM methods are safe to use concurrently. It is not safe to +// modify mutate any of the struct's properties though. type SSM struct { *client.Client } 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 ad42b4c97..2de65288b 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/sts/api.go +++ b/vendor/github.com/aws/aws-sdk-go/service/sts/api.go @@ -1,11 +1,11 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. -// Package sts provides a client for AWS Security Token Service. package sts import ( "time" + "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awsutil" "github.com/aws/aws-sdk-go/aws/request" ) @@ -172,8 +172,23 @@ func (c *STS) AssumeRoleRequest(input *AssumeRoleInput) (req *request.Request, o // Please also see https://docs.aws.amazon.com/goto/WebAPI/sts-2011-06-15/AssumeRole func (c *STS) AssumeRole(input *AssumeRoleInput) (*AssumeRoleOutput, error) { req, out := c.AssumeRoleRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// AssumeRoleWithContext is the same as AssumeRole with the addition of +// the ability to pass a context and additional request options. +// +// See AssumeRole for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *STS) AssumeRoleWithContext(ctx aws.Context, input *AssumeRoleInput, opts ...request.Option) (*AssumeRoleOutput, error) { + req, out := c.AssumeRoleRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opAssumeRoleWithSAML = "AssumeRoleWithSAML" @@ -331,8 +346,23 @@ func (c *STS) AssumeRoleWithSAMLRequest(input *AssumeRoleWithSAMLInput) (req *re // Please also see https://docs.aws.amazon.com/goto/WebAPI/sts-2011-06-15/AssumeRoleWithSAML func (c *STS) AssumeRoleWithSAML(input *AssumeRoleWithSAMLInput) (*AssumeRoleWithSAMLOutput, error) { req, out := c.AssumeRoleWithSAMLRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// AssumeRoleWithSAMLWithContext is the same as AssumeRoleWithSAML with the addition of +// the ability to pass a context and additional request options. +// +// See AssumeRoleWithSAML for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *STS) AssumeRoleWithSAMLWithContext(ctx aws.Context, input *AssumeRoleWithSAMLInput, opts ...request.Option) (*AssumeRoleWithSAMLOutput, error) { + req, out := c.AssumeRoleWithSAMLRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opAssumeRoleWithWebIdentity = "AssumeRoleWithWebIdentity" @@ -519,8 +549,23 @@ func (c *STS) AssumeRoleWithWebIdentityRequest(input *AssumeRoleWithWebIdentityI // Please also see https://docs.aws.amazon.com/goto/WebAPI/sts-2011-06-15/AssumeRoleWithWebIdentity func (c *STS) AssumeRoleWithWebIdentity(input *AssumeRoleWithWebIdentityInput) (*AssumeRoleWithWebIdentityOutput, error) { req, out := c.AssumeRoleWithWebIdentityRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// AssumeRoleWithWebIdentityWithContext is the same as AssumeRoleWithWebIdentity with the addition of +// the ability to pass a context and additional request options. +// +// See AssumeRoleWithWebIdentity for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *STS) AssumeRoleWithWebIdentityWithContext(ctx aws.Context, input *AssumeRoleWithWebIdentityInput, opts ...request.Option) (*AssumeRoleWithWebIdentityOutput, error) { + req, out := c.AssumeRoleWithWebIdentityRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDecodeAuthorizationMessage = "DecodeAuthorizationMessage" @@ -617,8 +662,23 @@ func (c *STS) DecodeAuthorizationMessageRequest(input *DecodeAuthorizationMessag // Please also see https://docs.aws.amazon.com/goto/WebAPI/sts-2011-06-15/DecodeAuthorizationMessage func (c *STS) DecodeAuthorizationMessage(input *DecodeAuthorizationMessageInput) (*DecodeAuthorizationMessageOutput, error) { req, out := c.DecodeAuthorizationMessageRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DecodeAuthorizationMessageWithContext is the same as DecodeAuthorizationMessage with the addition of +// the ability to pass a context and additional request options. +// +// See DecodeAuthorizationMessage for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *STS) DecodeAuthorizationMessageWithContext(ctx aws.Context, input *DecodeAuthorizationMessageInput, opts ...request.Option) (*DecodeAuthorizationMessageOutput, error) { + req, out := c.DecodeAuthorizationMessageRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetCallerIdentity = "GetCallerIdentity" @@ -678,8 +738,23 @@ func (c *STS) GetCallerIdentityRequest(input *GetCallerIdentityInput) (req *requ // Please also see https://docs.aws.amazon.com/goto/WebAPI/sts-2011-06-15/GetCallerIdentity func (c *STS) GetCallerIdentity(input *GetCallerIdentityInput) (*GetCallerIdentityOutput, error) { req, out := c.GetCallerIdentityRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetCallerIdentityWithContext is the same as GetCallerIdentity with the addition of +// the ability to pass a context and additional request options. +// +// See GetCallerIdentity for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *STS) GetCallerIdentityWithContext(ctx aws.Context, input *GetCallerIdentityInput, opts ...request.Option) (*GetCallerIdentityOutput, error) { + req, out := c.GetCallerIdentityRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetFederationToken = "GetFederationToken" @@ -833,8 +908,23 @@ func (c *STS) GetFederationTokenRequest(input *GetFederationTokenInput) (req *re // Please also see https://docs.aws.amazon.com/goto/WebAPI/sts-2011-06-15/GetFederationToken func (c *STS) GetFederationToken(input *GetFederationTokenInput) (*GetFederationTokenOutput, error) { req, out := c.GetFederationTokenRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetFederationTokenWithContext is the same as GetFederationToken with the addition of +// the ability to pass a context and additional request options. +// +// See GetFederationToken for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *STS) GetFederationTokenWithContext(ctx aws.Context, input *GetFederationTokenInput, opts ...request.Option) (*GetFederationTokenOutput, error) { + req, out := c.GetFederationTokenRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetSessionToken = "GetSessionToken" @@ -947,8 +1037,23 @@ func (c *STS) GetSessionTokenRequest(input *GetSessionTokenInput) (req *request. // Please also see https://docs.aws.amazon.com/goto/WebAPI/sts-2011-06-15/GetSessionToken func (c *STS) GetSessionToken(input *GetSessionTokenInput) (*GetSessionTokenOutput, error) { req, out := c.GetSessionTokenRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetSessionTokenWithContext is the same as GetSessionToken with the addition of +// the ability to pass a context and additional request options. +// +// See GetSessionToken for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *STS) GetSessionTokenWithContext(ctx aws.Context, input *GetSessionTokenInput, opts ...request.Option) (*GetSessionTokenOutput, error) { + req, out := c.GetSessionTokenRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // Please also see https://docs.aws.amazon.com/goto/WebAPI/sts-2011-06-15/AssumeRoleRequest diff --git a/vendor/github.com/aws/aws-sdk-go/service/sts/doc.go b/vendor/github.com/aws/aws-sdk-go/service/sts/doc.go new file mode 100644 index 000000000..d2af518cf --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/service/sts/doc.go @@ -0,0 +1,124 @@ +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. + +// Package sts provides the client and types for making API +// requests to AWS Security Token Service. +// +// The AWS Security Token Service (STS) is a web service that enables you to +// request temporary, limited-privilege credentials for AWS Identity and Access +// Management (IAM) users or for users that you authenticate (federated users). +// This guide provides descriptions of the STS API. For more detailed information +// about using this service, go to Temporary Security Credentials (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp.html). +// +// 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 (Java, Ruby, .NET, iOS, Android, etc.). The SDKs provide a convenient +// way to create programmatic access to STS. For example, the SDKs take care +// of cryptographically signing requests, 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 page (http://aws.amazon.com/tools/). +// +// For information about setting up signatures and authorization through the +// API, go to Signing AWS API Requests (http://docs.aws.amazon.com/general/latest/gr/signing_aws_api_requests.html) +// in the AWS General Reference. For general information about the Query API, +// go to Making Query Requests (http://docs.aws.amazon.com/IAM/latest/UserGuide/IAM_UsingQueryAPI.html) +// in Using IAM. For information about using security tokens with other AWS +// products, go to AWS Services That Work with IAM (http://docs.aws.amazon.com/IAM/latest/UserGuide/reference_aws-services-that-work-with-iam.html) +// in the IAM User Guide. +// +// If you're new to AWS and need additional technical information about a specific +// AWS product, you can find the product's technical documentation at http://aws.amazon.com/documentation/ +// (http://aws.amazon.com/documentation/). +// +// Endpoints +// +// The AWS Security Token Service (STS) has a default endpoint of https://sts.amazonaws.com +// that maps to the US East (N. Virginia) region. Additional regions are available +// and are activated by default. For more information, see Activating and Deactivating +// AWS STS in an AWS Region (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_enable-regions.html) +// in the IAM User Guide. +// +// For information about STS endpoints, see Regions and Endpoints (http://docs.aws.amazon.com/general/latest/gr/rande.html#sts_region) +// in the AWS General Reference. +// +// Recording API requests +// +// STS supports AWS CloudTrail, which is a service that records AWS calls for +// your AWS account and delivers log files to an Amazon S3 bucket. By using +// information collected by CloudTrail, you can determine what requests were +// successfully made to STS, who made the request, when it was made, and so +// on. To learn more about CloudTrail, including how to turn it on and find +// your log files, see the AWS CloudTrail User Guide (http://docs.aws.amazon.com/awscloudtrail/latest/userguide/what_is_cloud_trail_top_level.html). +// +// See https://docs.aws.amazon.com/goto/WebAPI/sts-2011-06-15 for more information on this service. +// +// See sts package documentation for more information. +// https://docs.aws.amazon.com/sdk-for-go/api/service/sts/ +// +// Using the Client +// +// To use the client for AWS Security Token Service you will first need +// to create a new instance of it. +// +// When creating a client for an AWS service you'll first need to have a Session +// already created. The Session provides configuration that can be shared +// between multiple service clients. Additional configuration can be applied to +// the Session and service's client when they are constructed. The aws package's +// Config type contains several fields such as Region for the AWS Region the +// client should make API requests too. The optional Config value can be provided +// as the variadic argument for Sessions and client creation. +// +// Once the service's client is created you can use it to make API requests the +// AWS service. These clients are safe to use concurrently. +// +// // Create a session to share configuration, and load external configuration. +// sess := session.Must(session.NewSession()) +// +// // Create the service's client with the session. +// svc := sts.New(sess) +// +// See the SDK's documentation for more information on how to use service clients. +// https://docs.aws.amazon.com/sdk-for-go/api/ +// +// See aws package's Config type for more information on configuration options. +// https://docs.aws.amazon.com/sdk-for-go/api/aws/#Config +// +// See the AWS Security Token Service client STS for more +// information on creating the service's client. +// https://docs.aws.amazon.com/sdk-for-go/api/service/sts/#New +// +// Once the client is created you can make an API request to the service. +// Each API method takes a input parameter, and returns the service response +// and an error. +// +// The API method will document which error codes the service can be returned +// by the operation if the service models the API operation's errors. These +// errors will also be available as const strings prefixed with "ErrCode". +// +// result, err := svc.AssumeRole(params) +// if err != nil { +// // Cast err to awserr.Error to handle specific error codes. +// aerr, ok := err.(awserr.Error) +// if ok && aerr.Code() == { +// // Specific error code handling +// } +// return err +// } +// +// fmt.Println("AssumeRole result:") +// fmt.Println(result) +// +// Using the Client with Context +// +// The service's client also provides methods to make API requests with a Context +// value. This allows you to control the timeout, and cancellation of pending +// requests. These methods also take request Option as variadic parameter to apply +// additional configuration to the API request. +// +// ctx := context.Background() +// +// result, err := svc.AssumeRoleWithContext(ctx, params) +// +// See the request package documentation for more information on using Context pattern +// with the SDK. +// https://docs.aws.amazon.com/sdk-for-go/api/aws/request/ +package sts diff --git a/vendor/github.com/aws/aws-sdk-go/service/sts/errors.go b/vendor/github.com/aws/aws-sdk-go/service/sts/errors.go index dbcd66759..e24884ef3 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/sts/errors.go +++ b/vendor/github.com/aws/aws-sdk-go/service/sts/errors.go @@ -1,4 +1,4 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. package sts diff --git a/vendor/github.com/aws/aws-sdk-go/service/sts/service.go b/vendor/github.com/aws/aws-sdk-go/service/sts/service.go index 9c4bfb838..1ee5839e0 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/sts/service.go +++ b/vendor/github.com/aws/aws-sdk-go/service/sts/service.go @@ -1,4 +1,4 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. package sts @@ -11,54 +11,12 @@ import ( "github.com/aws/aws-sdk-go/private/protocol/query" ) -// The AWS Security Token Service (STS) is a web service that enables you to -// request temporary, limited-privilege credentials for AWS Identity and Access -// Management (IAM) users or for users that you authenticate (federated users). -// This guide provides descriptions of the STS API. For more detailed information -// about using this service, go to Temporary Security Credentials (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp.html). +// STS provides the API operation methods for making requests to +// AWS Security Token Service. See this package's package overview docs +// for details on the service. // -// 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 (Java, Ruby, .NET, iOS, Android, etc.). The SDKs provide a convenient -// way to create programmatic access to STS. For example, the SDKs take care -// of cryptographically signing requests, 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 page (http://aws.amazon.com/tools/). -// -// For information about setting up signatures and authorization through the -// API, go to Signing AWS API Requests (http://docs.aws.amazon.com/general/latest/gr/signing_aws_api_requests.html) -// in the AWS General Reference. For general information about the Query API, -// go to Making Query Requests (http://docs.aws.amazon.com/IAM/latest/UserGuide/IAM_UsingQueryAPI.html) -// in Using IAM. For information about using security tokens with other AWS -// products, go to AWS Services That Work with IAM (http://docs.aws.amazon.com/IAM/latest/UserGuide/reference_aws-services-that-work-with-iam.html) -// in the IAM User Guide. -// -// If you're new to AWS and need additional technical information about a specific -// AWS product, you can find the product's technical documentation at http://aws.amazon.com/documentation/ -// (http://aws.amazon.com/documentation/). -// -// Endpoints -// -// The AWS Security Token Service (STS) has a default endpoint of https://sts.amazonaws.com -// that maps to the US East (N. Virginia) region. Additional regions are available -// and are activated by default. For more information, see Activating and Deactivating -// AWS STS in an AWS Region (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_enable-regions.html) -// in the IAM User Guide. -// -// For information about STS endpoints, see Regions and Endpoints (http://docs.aws.amazon.com/general/latest/gr/rande.html#sts_region) -// in the AWS General Reference. -// -// Recording API requests -// -// STS supports AWS CloudTrail, which is a service that records AWS calls for -// your AWS account and delivers log files to an Amazon S3 bucket. By using -// information collected by CloudTrail, you can determine what requests were -// successfully made to STS, who made the request, when it was made, and so -// on. To learn more about CloudTrail, including how to turn it on and find -// your log files, see the AWS CloudTrail User Guide (http://docs.aws.amazon.com/awscloudtrail/latest/userguide/what_is_cloud_trail_top_level.html). -// The service client's operations are safe to be used concurrently. -// It is not safe to mutate any of the client's properties though. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/sts-2011-06-15 +// STS methods are safe to use concurrently. It is not safe to +// modify mutate any of the struct's properties though. type STS struct { *client.Client } diff --git a/vendor/github.com/aws/aws-sdk-go/service/waf/api.go b/vendor/github.com/aws/aws-sdk-go/service/waf/api.go index 153e3a71e..c8d9b0b62 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/waf/api.go +++ b/vendor/github.com/aws/aws-sdk-go/service/waf/api.go @@ -1,12 +1,12 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. -// Package waf provides a client for AWS WAF. package waf import ( "fmt" "time" + "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awsutil" "github.com/aws/aws-sdk-go/aws/request" ) @@ -137,8 +137,23 @@ func (c *WAF) CreateByteMatchSetRequest(input *CreateByteMatchSetInput) (req *re // Please also see https://docs.aws.amazon.com/goto/WebAPI/waf-2015-08-24/CreateByteMatchSet func (c *WAF) CreateByteMatchSet(input *CreateByteMatchSetInput) (*CreateByteMatchSetOutput, error) { req, out := c.CreateByteMatchSetRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateByteMatchSetWithContext is the same as CreateByteMatchSet with the addition of +// the ability to pass a context and additional request options. +// +// See CreateByteMatchSet 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 *WAF) CreateByteMatchSetWithContext(ctx aws.Context, input *CreateByteMatchSetInput, opts ...request.Option) (*CreateByteMatchSetOutput, error) { + req, out := c.CreateByteMatchSetRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateIPSet = "CreateIPSet" @@ -267,8 +282,23 @@ func (c *WAF) CreateIPSetRequest(input *CreateIPSetInput) (req *request.Request, // Please also see https://docs.aws.amazon.com/goto/WebAPI/waf-2015-08-24/CreateIPSet func (c *WAF) CreateIPSet(input *CreateIPSetInput) (*CreateIPSetOutput, error) { req, out := c.CreateIPSetRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateIPSetWithContext is the same as CreateIPSet with the addition of +// the ability to pass a context and additional request options. +// +// See CreateIPSet 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 *WAF) CreateIPSetWithContext(ctx aws.Context, input *CreateIPSetInput, opts ...request.Option) (*CreateIPSetOutput, error) { + req, out := c.CreateIPSetRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateRule = "CreateRule" @@ -407,8 +437,23 @@ func (c *WAF) CreateRuleRequest(input *CreateRuleInput) (req *request.Request, o // Please also see https://docs.aws.amazon.com/goto/WebAPI/waf-2015-08-24/CreateRule func (c *WAF) CreateRule(input *CreateRuleInput) (*CreateRuleOutput, error) { req, out := c.CreateRuleRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateRuleWithContext is the same as CreateRule with the addition of +// the ability to pass a context and additional request options. +// +// See CreateRule 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 *WAF) CreateRuleWithContext(ctx aws.Context, input *CreateRuleInput, opts ...request.Option) (*CreateRuleOutput, error) { + req, out := c.CreateRuleRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateSizeConstraintSet = "CreateSizeConstraintSet" @@ -538,8 +583,23 @@ func (c *WAF) CreateSizeConstraintSetRequest(input *CreateSizeConstraintSetInput // Please also see https://docs.aws.amazon.com/goto/WebAPI/waf-2015-08-24/CreateSizeConstraintSet func (c *WAF) CreateSizeConstraintSet(input *CreateSizeConstraintSetInput) (*CreateSizeConstraintSetOutput, error) { req, out := c.CreateSizeConstraintSetRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateSizeConstraintSetWithContext is the same as CreateSizeConstraintSet with the addition of +// the ability to pass a context and additional request options. +// +// See CreateSizeConstraintSet 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 *WAF) CreateSizeConstraintSetWithContext(ctx aws.Context, input *CreateSizeConstraintSetInput, opts ...request.Option) (*CreateSizeConstraintSetOutput, error) { + req, out := c.CreateSizeConstraintSetRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateSqlInjectionMatchSet = "CreateSqlInjectionMatchSet" @@ -665,8 +725,23 @@ func (c *WAF) CreateSqlInjectionMatchSetRequest(input *CreateSqlInjectionMatchSe // Please also see https://docs.aws.amazon.com/goto/WebAPI/waf-2015-08-24/CreateSqlInjectionMatchSet func (c *WAF) CreateSqlInjectionMatchSet(input *CreateSqlInjectionMatchSetInput) (*CreateSqlInjectionMatchSetOutput, error) { req, out := c.CreateSqlInjectionMatchSetRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateSqlInjectionMatchSetWithContext is the same as CreateSqlInjectionMatchSet with the addition of +// the ability to pass a context and additional request options. +// +// See CreateSqlInjectionMatchSet 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 *WAF) CreateSqlInjectionMatchSetWithContext(ctx aws.Context, input *CreateSqlInjectionMatchSetInput, opts ...request.Option) (*CreateSqlInjectionMatchSetOutput, error) { + req, out := c.CreateSqlInjectionMatchSetRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateWebACL = "CreateWebACL" @@ -804,8 +879,23 @@ func (c *WAF) CreateWebACLRequest(input *CreateWebACLInput) (req *request.Reques // Please also see https://docs.aws.amazon.com/goto/WebAPI/waf-2015-08-24/CreateWebACL func (c *WAF) CreateWebACL(input *CreateWebACLInput) (*CreateWebACLOutput, error) { req, out := c.CreateWebACLRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateWebACLWithContext is the same as CreateWebACL with the addition of +// the ability to pass a context and additional request options. +// +// See CreateWebACL 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 *WAF) CreateWebACLWithContext(ctx aws.Context, input *CreateWebACLInput, opts ...request.Option) (*CreateWebACLOutput, error) { + req, out := c.CreateWebACLRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateXssMatchSet = "CreateXssMatchSet" @@ -932,8 +1022,23 @@ func (c *WAF) CreateXssMatchSetRequest(input *CreateXssMatchSetInput) (req *requ // Please also see https://docs.aws.amazon.com/goto/WebAPI/waf-2015-08-24/CreateXssMatchSet func (c *WAF) CreateXssMatchSet(input *CreateXssMatchSetInput) (*CreateXssMatchSetOutput, error) { req, out := c.CreateXssMatchSetRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateXssMatchSetWithContext is the same as CreateXssMatchSet with the addition of +// the ability to pass a context and additional request options. +// +// See CreateXssMatchSet 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 *WAF) CreateXssMatchSetWithContext(ctx aws.Context, input *CreateXssMatchSetInput, opts ...request.Option) (*CreateXssMatchSetOutput, error) { + req, out := c.CreateXssMatchSetRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteByteMatchSet = "DeleteByteMatchSet" @@ -1045,8 +1150,23 @@ func (c *WAF) DeleteByteMatchSetRequest(input *DeleteByteMatchSetInput) (req *re // Please also see https://docs.aws.amazon.com/goto/WebAPI/waf-2015-08-24/DeleteByteMatchSet func (c *WAF) DeleteByteMatchSet(input *DeleteByteMatchSetInput) (*DeleteByteMatchSetOutput, error) { req, out := c.DeleteByteMatchSetRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteByteMatchSetWithContext is the same as DeleteByteMatchSet with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteByteMatchSet 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 *WAF) DeleteByteMatchSetWithContext(ctx aws.Context, input *DeleteByteMatchSetInput, opts ...request.Option) (*DeleteByteMatchSetOutput, error) { + req, out := c.DeleteByteMatchSetRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteIPSet = "DeleteIPSet" @@ -1157,8 +1277,23 @@ func (c *WAF) DeleteIPSetRequest(input *DeleteIPSetInput) (req *request.Request, // Please also see https://docs.aws.amazon.com/goto/WebAPI/waf-2015-08-24/DeleteIPSet func (c *WAF) DeleteIPSet(input *DeleteIPSetInput) (*DeleteIPSetOutput, error) { req, out := c.DeleteIPSetRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteIPSetWithContext is the same as DeleteIPSet with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteIPSet 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 *WAF) DeleteIPSetWithContext(ctx aws.Context, input *DeleteIPSetInput, opts ...request.Option) (*DeleteIPSetOutput, error) { + req, out := c.DeleteIPSetRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteRule = "DeleteRule" @@ -1269,8 +1404,23 @@ func (c *WAF) DeleteRuleRequest(input *DeleteRuleInput) (req *request.Request, o // Please also see https://docs.aws.amazon.com/goto/WebAPI/waf-2015-08-24/DeleteRule func (c *WAF) DeleteRule(input *DeleteRuleInput) (*DeleteRuleOutput, error) { req, out := c.DeleteRuleRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteRuleWithContext is the same as DeleteRule with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteRule 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 *WAF) DeleteRuleWithContext(ctx aws.Context, input *DeleteRuleInput, opts ...request.Option) (*DeleteRuleOutput, error) { + req, out := c.DeleteRuleRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteSizeConstraintSet = "DeleteSizeConstraintSet" @@ -1382,8 +1532,23 @@ func (c *WAF) DeleteSizeConstraintSetRequest(input *DeleteSizeConstraintSetInput // Please also see https://docs.aws.amazon.com/goto/WebAPI/waf-2015-08-24/DeleteSizeConstraintSet func (c *WAF) DeleteSizeConstraintSet(input *DeleteSizeConstraintSetInput) (*DeleteSizeConstraintSetOutput, error) { req, out := c.DeleteSizeConstraintSetRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteSizeConstraintSetWithContext is the same as DeleteSizeConstraintSet with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteSizeConstraintSet 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 *WAF) DeleteSizeConstraintSetWithContext(ctx aws.Context, input *DeleteSizeConstraintSetInput, opts ...request.Option) (*DeleteSizeConstraintSetOutput, error) { + req, out := c.DeleteSizeConstraintSetRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteSqlInjectionMatchSet = "DeleteSqlInjectionMatchSet" @@ -1496,8 +1661,23 @@ func (c *WAF) DeleteSqlInjectionMatchSetRequest(input *DeleteSqlInjectionMatchSe // Please also see https://docs.aws.amazon.com/goto/WebAPI/waf-2015-08-24/DeleteSqlInjectionMatchSet func (c *WAF) DeleteSqlInjectionMatchSet(input *DeleteSqlInjectionMatchSetInput) (*DeleteSqlInjectionMatchSetOutput, error) { req, out := c.DeleteSqlInjectionMatchSetRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteSqlInjectionMatchSetWithContext is the same as DeleteSqlInjectionMatchSet with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteSqlInjectionMatchSet 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 *WAF) DeleteSqlInjectionMatchSetWithContext(ctx aws.Context, input *DeleteSqlInjectionMatchSetInput, opts ...request.Option) (*DeleteSqlInjectionMatchSetOutput, error) { + req, out := c.DeleteSqlInjectionMatchSetRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteWebACL = "DeleteWebACL" @@ -1605,8 +1785,23 @@ func (c *WAF) DeleteWebACLRequest(input *DeleteWebACLInput) (req *request.Reques // Please also see https://docs.aws.amazon.com/goto/WebAPI/waf-2015-08-24/DeleteWebACL func (c *WAF) DeleteWebACL(input *DeleteWebACLInput) (*DeleteWebACLOutput, error) { req, out := c.DeleteWebACLRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteWebACLWithContext is the same as DeleteWebACL with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteWebACL 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 *WAF) DeleteWebACLWithContext(ctx aws.Context, input *DeleteWebACLInput, opts ...request.Option) (*DeleteWebACLOutput, error) { + req, out := c.DeleteWebACLRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteXssMatchSet = "DeleteXssMatchSet" @@ -1718,8 +1913,23 @@ func (c *WAF) DeleteXssMatchSetRequest(input *DeleteXssMatchSetInput) (req *requ // Please also see https://docs.aws.amazon.com/goto/WebAPI/waf-2015-08-24/DeleteXssMatchSet func (c *WAF) DeleteXssMatchSet(input *DeleteXssMatchSetInput) (*DeleteXssMatchSetOutput, error) { req, out := c.DeleteXssMatchSetRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteXssMatchSetWithContext is the same as DeleteXssMatchSet with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteXssMatchSet 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 *WAF) DeleteXssMatchSetWithContext(ctx aws.Context, input *DeleteXssMatchSetInput, opts ...request.Option) (*DeleteXssMatchSetOutput, error) { + req, out := c.DeleteXssMatchSetRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetByteMatchSet = "GetByteMatchSet" @@ -1791,8 +2001,23 @@ func (c *WAF) GetByteMatchSetRequest(input *GetByteMatchSetInput) (req *request. // Please also see https://docs.aws.amazon.com/goto/WebAPI/waf-2015-08-24/GetByteMatchSet func (c *WAF) GetByteMatchSet(input *GetByteMatchSetInput) (*GetByteMatchSetOutput, error) { req, out := c.GetByteMatchSetRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetByteMatchSetWithContext is the same as GetByteMatchSet with the addition of +// the ability to pass a context and additional request options. +// +// See GetByteMatchSet 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 *WAF) GetByteMatchSetWithContext(ctx aws.Context, input *GetByteMatchSetInput, opts ...request.Option) (*GetByteMatchSetOutput, error) { + req, out := c.GetByteMatchSetRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetChangeToken = "GetChangeToken" @@ -1871,8 +2096,23 @@ func (c *WAF) GetChangeTokenRequest(input *GetChangeTokenInput) (req *request.Re // Please also see https://docs.aws.amazon.com/goto/WebAPI/waf-2015-08-24/GetChangeToken func (c *WAF) GetChangeToken(input *GetChangeTokenInput) (*GetChangeTokenOutput, error) { req, out := c.GetChangeTokenRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetChangeTokenWithContext is the same as GetChangeToken with the addition of +// the ability to pass a context and additional request options. +// +// See GetChangeToken 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 *WAF) GetChangeTokenWithContext(ctx aws.Context, input *GetChangeTokenInput, opts ...request.Option) (*GetChangeTokenOutput, error) { + req, out := c.GetChangeTokenRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetChangeTokenStatus = "GetChangeTokenStatus" @@ -1950,8 +2190,23 @@ func (c *WAF) GetChangeTokenStatusRequest(input *GetChangeTokenStatusInput) (req // Please also see https://docs.aws.amazon.com/goto/WebAPI/waf-2015-08-24/GetChangeTokenStatus func (c *WAF) GetChangeTokenStatus(input *GetChangeTokenStatusInput) (*GetChangeTokenStatusOutput, error) { req, out := c.GetChangeTokenStatusRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetChangeTokenStatusWithContext is the same as GetChangeTokenStatus with the addition of +// the ability to pass a context and additional request options. +// +// See GetChangeTokenStatus 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 *WAF) GetChangeTokenStatusWithContext(ctx aws.Context, input *GetChangeTokenStatusInput, opts ...request.Option) (*GetChangeTokenStatusOutput, error) { + req, out := c.GetChangeTokenStatusRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetIPSet = "GetIPSet" @@ -2023,8 +2278,23 @@ func (c *WAF) GetIPSetRequest(input *GetIPSetInput) (req *request.Request, outpu // Please also see https://docs.aws.amazon.com/goto/WebAPI/waf-2015-08-24/GetIPSet func (c *WAF) GetIPSet(input *GetIPSetInput) (*GetIPSetOutput, error) { req, out := c.GetIPSetRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetIPSetWithContext is the same as GetIPSet with the addition of +// the ability to pass a context and additional request options. +// +// See GetIPSet 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 *WAF) GetIPSetWithContext(ctx aws.Context, input *GetIPSetInput, opts ...request.Option) (*GetIPSetOutput, error) { + req, out := c.GetIPSetRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetRule = "GetRule" @@ -2097,8 +2367,23 @@ func (c *WAF) GetRuleRequest(input *GetRuleInput) (req *request.Request, output // Please also see https://docs.aws.amazon.com/goto/WebAPI/waf-2015-08-24/GetRule func (c *WAF) GetRule(input *GetRuleInput) (*GetRuleOutput, error) { req, out := c.GetRuleRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetRuleWithContext is the same as GetRule with the addition of +// the ability to pass a context and additional request options. +// +// See GetRule 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 *WAF) GetRuleWithContext(ctx aws.Context, input *GetRuleInput, opts ...request.Option) (*GetRuleOutput, error) { + req, out := c.GetRuleRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetSampledRequests = "GetSampledRequests" @@ -2176,8 +2461,23 @@ func (c *WAF) GetSampledRequestsRequest(input *GetSampledRequestsInput) (req *re // Please also see https://docs.aws.amazon.com/goto/WebAPI/waf-2015-08-24/GetSampledRequests func (c *WAF) GetSampledRequests(input *GetSampledRequestsInput) (*GetSampledRequestsOutput, error) { req, out := c.GetSampledRequestsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetSampledRequestsWithContext is the same as GetSampledRequests with the addition of +// the ability to pass a context and additional request options. +// +// See GetSampledRequests 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 *WAF) GetSampledRequestsWithContext(ctx aws.Context, input *GetSampledRequestsInput, opts ...request.Option) (*GetSampledRequestsOutput, error) { + req, out := c.GetSampledRequestsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetSizeConstraintSet = "GetSizeConstraintSet" @@ -2249,8 +2549,23 @@ func (c *WAF) GetSizeConstraintSetRequest(input *GetSizeConstraintSetInput) (req // Please also see https://docs.aws.amazon.com/goto/WebAPI/waf-2015-08-24/GetSizeConstraintSet func (c *WAF) GetSizeConstraintSet(input *GetSizeConstraintSetInput) (*GetSizeConstraintSetOutput, error) { req, out := c.GetSizeConstraintSetRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetSizeConstraintSetWithContext is the same as GetSizeConstraintSet with the addition of +// the ability to pass a context and additional request options. +// +// See GetSizeConstraintSet 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 *WAF) GetSizeConstraintSetWithContext(ctx aws.Context, input *GetSizeConstraintSetInput, opts ...request.Option) (*GetSizeConstraintSetOutput, error) { + req, out := c.GetSizeConstraintSetRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetSqlInjectionMatchSet = "GetSqlInjectionMatchSet" @@ -2322,8 +2637,23 @@ func (c *WAF) GetSqlInjectionMatchSetRequest(input *GetSqlInjectionMatchSetInput // Please also see https://docs.aws.amazon.com/goto/WebAPI/waf-2015-08-24/GetSqlInjectionMatchSet func (c *WAF) GetSqlInjectionMatchSet(input *GetSqlInjectionMatchSetInput) (*GetSqlInjectionMatchSetOutput, error) { req, out := c.GetSqlInjectionMatchSetRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetSqlInjectionMatchSetWithContext is the same as GetSqlInjectionMatchSet with the addition of +// the ability to pass a context and additional request options. +// +// See GetSqlInjectionMatchSet 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 *WAF) GetSqlInjectionMatchSetWithContext(ctx aws.Context, input *GetSqlInjectionMatchSetInput, opts ...request.Option) (*GetSqlInjectionMatchSetOutput, error) { + req, out := c.GetSqlInjectionMatchSetRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetWebACL = "GetWebACL" @@ -2395,8 +2725,23 @@ func (c *WAF) GetWebACLRequest(input *GetWebACLInput) (req *request.Request, out // Please also see https://docs.aws.amazon.com/goto/WebAPI/waf-2015-08-24/GetWebACL func (c *WAF) GetWebACL(input *GetWebACLInput) (*GetWebACLOutput, error) { req, out := c.GetWebACLRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetWebACLWithContext is the same as GetWebACL with the addition of +// the ability to pass a context and additional request options. +// +// See GetWebACL 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 *WAF) GetWebACLWithContext(ctx aws.Context, input *GetWebACLInput, opts ...request.Option) (*GetWebACLOutput, error) { + req, out := c.GetWebACLRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetXssMatchSet = "GetXssMatchSet" @@ -2468,8 +2813,23 @@ func (c *WAF) GetXssMatchSetRequest(input *GetXssMatchSetInput) (req *request.Re // Please also see https://docs.aws.amazon.com/goto/WebAPI/waf-2015-08-24/GetXssMatchSet func (c *WAF) GetXssMatchSet(input *GetXssMatchSetInput) (*GetXssMatchSetOutput, error) { req, out := c.GetXssMatchSetRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetXssMatchSetWithContext is the same as GetXssMatchSet with the addition of +// the ability to pass a context and additional request options. +// +// See GetXssMatchSet 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 *WAF) GetXssMatchSetWithContext(ctx aws.Context, input *GetXssMatchSetInput, opts ...request.Option) (*GetXssMatchSetOutput, error) { + req, out := c.GetXssMatchSetRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opListByteMatchSets = "ListByteMatchSets" @@ -2538,8 +2898,23 @@ func (c *WAF) ListByteMatchSetsRequest(input *ListByteMatchSetsInput) (req *requ // Please also see https://docs.aws.amazon.com/goto/WebAPI/waf-2015-08-24/ListByteMatchSets func (c *WAF) ListByteMatchSets(input *ListByteMatchSetsInput) (*ListByteMatchSetsOutput, error) { req, out := c.ListByteMatchSetsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListByteMatchSetsWithContext is the same as ListByteMatchSets with the addition of +// the ability to pass a context and additional request options. +// +// See ListByteMatchSets 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 *WAF) ListByteMatchSetsWithContext(ctx aws.Context, input *ListByteMatchSetsInput, opts ...request.Option) (*ListByteMatchSetsOutput, error) { + req, out := c.ListByteMatchSetsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opListIPSets = "ListIPSets" @@ -2608,8 +2983,23 @@ func (c *WAF) ListIPSetsRequest(input *ListIPSetsInput) (req *request.Request, o // Please also see https://docs.aws.amazon.com/goto/WebAPI/waf-2015-08-24/ListIPSets func (c *WAF) ListIPSets(input *ListIPSetsInput) (*ListIPSetsOutput, error) { req, out := c.ListIPSetsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListIPSetsWithContext is the same as ListIPSets with the addition of +// the ability to pass a context and additional request options. +// +// See ListIPSets 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 *WAF) ListIPSetsWithContext(ctx aws.Context, input *ListIPSetsInput, opts ...request.Option) (*ListIPSetsOutput, error) { + req, out := c.ListIPSetsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opListRules = "ListRules" @@ -2678,8 +3068,23 @@ func (c *WAF) ListRulesRequest(input *ListRulesInput) (req *request.Request, out // Please also see https://docs.aws.amazon.com/goto/WebAPI/waf-2015-08-24/ListRules func (c *WAF) ListRules(input *ListRulesInput) (*ListRulesOutput, error) { req, out := c.ListRulesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListRulesWithContext is the same as ListRules with the addition of +// the ability to pass a context and additional request options. +// +// See ListRules 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 *WAF) ListRulesWithContext(ctx aws.Context, input *ListRulesInput, opts ...request.Option) (*ListRulesOutput, error) { + req, out := c.ListRulesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opListSizeConstraintSets = "ListSizeConstraintSets" @@ -2748,8 +3153,23 @@ func (c *WAF) ListSizeConstraintSetsRequest(input *ListSizeConstraintSetsInput) // Please also see https://docs.aws.amazon.com/goto/WebAPI/waf-2015-08-24/ListSizeConstraintSets func (c *WAF) ListSizeConstraintSets(input *ListSizeConstraintSetsInput) (*ListSizeConstraintSetsOutput, error) { req, out := c.ListSizeConstraintSetsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListSizeConstraintSetsWithContext is the same as ListSizeConstraintSets with the addition of +// the ability to pass a context and additional request options. +// +// See ListSizeConstraintSets 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 *WAF) ListSizeConstraintSetsWithContext(ctx aws.Context, input *ListSizeConstraintSetsInput, opts ...request.Option) (*ListSizeConstraintSetsOutput, error) { + req, out := c.ListSizeConstraintSetsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opListSqlInjectionMatchSets = "ListSqlInjectionMatchSets" @@ -2818,8 +3238,23 @@ func (c *WAF) ListSqlInjectionMatchSetsRequest(input *ListSqlInjectionMatchSetsI // Please also see https://docs.aws.amazon.com/goto/WebAPI/waf-2015-08-24/ListSqlInjectionMatchSets func (c *WAF) ListSqlInjectionMatchSets(input *ListSqlInjectionMatchSetsInput) (*ListSqlInjectionMatchSetsOutput, error) { req, out := c.ListSqlInjectionMatchSetsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListSqlInjectionMatchSetsWithContext is the same as ListSqlInjectionMatchSets with the addition of +// the ability to pass a context and additional request options. +// +// See ListSqlInjectionMatchSets 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 *WAF) ListSqlInjectionMatchSetsWithContext(ctx aws.Context, input *ListSqlInjectionMatchSetsInput, opts ...request.Option) (*ListSqlInjectionMatchSetsOutput, error) { + req, out := c.ListSqlInjectionMatchSetsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opListWebACLs = "ListWebACLs" @@ -2888,8 +3323,23 @@ func (c *WAF) ListWebACLsRequest(input *ListWebACLsInput) (req *request.Request, // Please also see https://docs.aws.amazon.com/goto/WebAPI/waf-2015-08-24/ListWebACLs func (c *WAF) ListWebACLs(input *ListWebACLsInput) (*ListWebACLsOutput, error) { req, out := c.ListWebACLsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListWebACLsWithContext is the same as ListWebACLs with the addition of +// the ability to pass a context and additional request options. +// +// See ListWebACLs 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 *WAF) ListWebACLsWithContext(ctx aws.Context, input *ListWebACLsInput, opts ...request.Option) (*ListWebACLsOutput, error) { + req, out := c.ListWebACLsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opListXssMatchSets = "ListXssMatchSets" @@ -2958,8 +3408,23 @@ func (c *WAF) ListXssMatchSetsRequest(input *ListXssMatchSetsInput) (req *reques // Please also see https://docs.aws.amazon.com/goto/WebAPI/waf-2015-08-24/ListXssMatchSets func (c *WAF) ListXssMatchSets(input *ListXssMatchSetsInput) (*ListXssMatchSetsOutput, error) { req, out := c.ListXssMatchSetsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListXssMatchSetsWithContext is the same as ListXssMatchSets with the addition of +// the ability to pass a context and additional request options. +// +// See ListXssMatchSets 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 *WAF) ListXssMatchSetsWithContext(ctx aws.Context, input *ListXssMatchSetsInput, opts ...request.Option) (*ListXssMatchSetsOutput, error) { + req, out := c.ListXssMatchSetsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opUpdateByteMatchSet = "UpdateByteMatchSet" @@ -3140,8 +3605,23 @@ func (c *WAF) UpdateByteMatchSetRequest(input *UpdateByteMatchSetInput) (req *re // Please also see https://docs.aws.amazon.com/goto/WebAPI/waf-2015-08-24/UpdateByteMatchSet func (c *WAF) UpdateByteMatchSet(input *UpdateByteMatchSetInput) (*UpdateByteMatchSetOutput, error) { req, out := c.UpdateByteMatchSetRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// UpdateByteMatchSetWithContext is the same as UpdateByteMatchSet with the addition of +// the ability to pass a context and additional request options. +// +// See UpdateByteMatchSet 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 *WAF) UpdateByteMatchSetWithContext(ctx aws.Context, input *UpdateByteMatchSetInput, opts ...request.Option) (*UpdateByteMatchSetOutput, error) { + req, out := c.UpdateByteMatchSetRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opUpdateIPSet = "UpdateIPSet" @@ -3342,8 +3822,23 @@ func (c *WAF) UpdateIPSetRequest(input *UpdateIPSetInput) (req *request.Request, // Please also see https://docs.aws.amazon.com/goto/WebAPI/waf-2015-08-24/UpdateIPSet func (c *WAF) UpdateIPSet(input *UpdateIPSetInput) (*UpdateIPSetOutput, error) { req, out := c.UpdateIPSetRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// UpdateIPSetWithContext is the same as UpdateIPSet with the addition of +// the ability to pass a context and additional request options. +// +// See UpdateIPSet 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 *WAF) UpdateIPSetWithContext(ctx aws.Context, input *UpdateIPSetInput, opts ...request.Option) (*UpdateIPSetOutput, error) { + req, out := c.UpdateIPSetRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opUpdateRule = "UpdateRule" @@ -3528,8 +4023,23 @@ func (c *WAF) UpdateRuleRequest(input *UpdateRuleInput) (req *request.Request, o // Please also see https://docs.aws.amazon.com/goto/WebAPI/waf-2015-08-24/UpdateRule func (c *WAF) UpdateRule(input *UpdateRuleInput) (*UpdateRuleOutput, error) { req, out := c.UpdateRuleRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// UpdateRuleWithContext is the same as UpdateRule with the addition of +// the ability to pass a context and additional request options. +// +// See UpdateRule 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 *WAF) UpdateRuleWithContext(ctx aws.Context, input *UpdateRuleInput, opts ...request.Option) (*UpdateRuleOutput, error) { + req, out := c.UpdateRuleRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opUpdateSizeConstraintSet = "UpdateSizeConstraintSet" @@ -3720,8 +4230,23 @@ func (c *WAF) UpdateSizeConstraintSetRequest(input *UpdateSizeConstraintSetInput // Please also see https://docs.aws.amazon.com/goto/WebAPI/waf-2015-08-24/UpdateSizeConstraintSet func (c *WAF) UpdateSizeConstraintSet(input *UpdateSizeConstraintSetInput) (*UpdateSizeConstraintSetOutput, error) { req, out := c.UpdateSizeConstraintSetRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// UpdateSizeConstraintSetWithContext is the same as UpdateSizeConstraintSet with the addition of +// the ability to pass a context and additional request options. +// +// See UpdateSizeConstraintSet 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 *WAF) UpdateSizeConstraintSetWithContext(ctx aws.Context, input *UpdateSizeConstraintSetInput, opts ...request.Option) (*UpdateSizeConstraintSetOutput, error) { + req, out := c.UpdateSizeConstraintSetRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opUpdateSqlInjectionMatchSet = "UpdateSqlInjectionMatchSet" @@ -3897,8 +4422,23 @@ func (c *WAF) UpdateSqlInjectionMatchSetRequest(input *UpdateSqlInjectionMatchSe // Please also see https://docs.aws.amazon.com/goto/WebAPI/waf-2015-08-24/UpdateSqlInjectionMatchSet func (c *WAF) UpdateSqlInjectionMatchSet(input *UpdateSqlInjectionMatchSetInput) (*UpdateSqlInjectionMatchSetOutput, error) { req, out := c.UpdateSqlInjectionMatchSetRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// UpdateSqlInjectionMatchSetWithContext is the same as UpdateSqlInjectionMatchSet with the addition of +// the ability to pass a context and additional request options. +// +// See UpdateSqlInjectionMatchSet 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 *WAF) UpdateSqlInjectionMatchSetWithContext(ctx aws.Context, input *UpdateSqlInjectionMatchSetInput, opts ...request.Option) (*UpdateSqlInjectionMatchSetOutput, error) { + req, out := c.UpdateSqlInjectionMatchSetRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opUpdateWebACL = "UpdateWebACL" @@ -4093,8 +4633,23 @@ func (c *WAF) UpdateWebACLRequest(input *UpdateWebACLInput) (req *request.Reques // Please also see https://docs.aws.amazon.com/goto/WebAPI/waf-2015-08-24/UpdateWebACL func (c *WAF) UpdateWebACL(input *UpdateWebACLInput) (*UpdateWebACLOutput, error) { req, out := c.UpdateWebACLRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// UpdateWebACLWithContext is the same as UpdateWebACL with the addition of +// the ability to pass a context and additional request options. +// +// See UpdateWebACL 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 *WAF) UpdateWebACLWithContext(ctx aws.Context, input *UpdateWebACLInput, opts ...request.Option) (*UpdateWebACLOutput, error) { + req, out := c.UpdateWebACLRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opUpdateXssMatchSet = "UpdateXssMatchSet" @@ -4270,8 +4825,23 @@ func (c *WAF) UpdateXssMatchSetRequest(input *UpdateXssMatchSetInput) (req *requ // Please also see https://docs.aws.amazon.com/goto/WebAPI/waf-2015-08-24/UpdateXssMatchSet func (c *WAF) UpdateXssMatchSet(input *UpdateXssMatchSetInput) (*UpdateXssMatchSetOutput, error) { req, out := c.UpdateXssMatchSetRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// UpdateXssMatchSetWithContext is the same as UpdateXssMatchSet with the addition of +// the ability to pass a context and additional request options. +// +// See UpdateXssMatchSet 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 *WAF) UpdateXssMatchSetWithContext(ctx aws.Context, input *UpdateXssMatchSetInput, opts ...request.Option) (*UpdateXssMatchSetOutput, error) { + req, out := c.UpdateXssMatchSetRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // The ActivatedRule object in an UpdateWebACL request specifies a Rule that diff --git a/vendor/github.com/aws/aws-sdk-go/service/waf/doc.go b/vendor/github.com/aws/aws-sdk-go/service/waf/doc.go new file mode 100644 index 000000000..e2fbbfddf --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/service/waf/doc.go @@ -0,0 +1,86 @@ +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. + +// Package waf provides the client and types for making API +// requests to AWS WAF. +// +// This is the AWS WAF API Reference for using AWS WAF with Amazon CloudFront. +// The AWS WAF actions and data types listed in the reference are available +// for protecting Amazon CloudFront distributions. You can use these actions +// and data types via the endpoint waf.amazonaws.com. This guide is for developers +// who need detailed information about the AWS WAF API actions, data types, +// and errors. For detailed information about AWS WAF features and an overview +// of how to use the AWS WAF API, see the AWS WAF Developer Guide (http://docs.aws.amazon.com/waf/latest/developerguide/). +// +// See https://docs.aws.amazon.com/goto/WebAPI/waf-2015-08-24 for more information on this service. +// +// See waf package documentation for more information. +// https://docs.aws.amazon.com/sdk-for-go/api/service/waf/ +// +// Using the Client +// +// To use the client for AWS WAF you will first need +// to create a new instance of it. +// +// When creating a client for an AWS service you'll first need to have a Session +// already created. The Session provides configuration that can be shared +// between multiple service clients. Additional configuration can be applied to +// the Session and service's client when they are constructed. The aws package's +// Config type contains several fields such as Region for the AWS Region the +// client should make API requests too. The optional Config value can be provided +// as the variadic argument for Sessions and client creation. +// +// Once the service's client is created you can use it to make API requests the +// AWS service. These clients are safe to use concurrently. +// +// // Create a session to share configuration, and load external configuration. +// sess := session.Must(session.NewSession()) +// +// // Create the service's client with the session. +// svc := waf.New(sess) +// +// See the SDK's documentation for more information on how to use service clients. +// https://docs.aws.amazon.com/sdk-for-go/api/ +// +// See aws package's Config type for more information on configuration options. +// https://docs.aws.amazon.com/sdk-for-go/api/aws/#Config +// +// See the AWS WAF client WAF for more +// information on creating the service's client. +// https://docs.aws.amazon.com/sdk-for-go/api/service/waf/#New +// +// Once the client is created you can make an API request to the service. +// Each API method takes a input parameter, and returns the service response +// and an error. +// +// The API method will document which error codes the service can be returned +// by the operation if the service models the API operation's errors. These +// errors will also be available as const strings prefixed with "ErrCode". +// +// result, err := svc.CreateByteMatchSet(params) +// if err != nil { +// // Cast err to awserr.Error to handle specific error codes. +// aerr, ok := err.(awserr.Error) +// if ok && aerr.Code() == { +// // Specific error code handling +// } +// return err +// } +// +// fmt.Println("CreateByteMatchSet result:") +// fmt.Println(result) +// +// Using the Client with Context +// +// The service's client also provides methods to make API requests with a Context +// value. This allows you to control the timeout, and cancellation of pending +// requests. These methods also take request Option as variadic parameter to apply +// additional configuration to the API request. +// +// ctx := context.Background() +// +// result, err := svc.CreateByteMatchSetWithContext(ctx, params) +// +// See the request package documentation for more information on using Context pattern +// with the SDK. +// https://docs.aws.amazon.com/sdk-for-go/api/aws/request/ +package waf diff --git a/vendor/github.com/aws/aws-sdk-go/service/waf/errors.go b/vendor/github.com/aws/aws-sdk-go/service/waf/errors.go index e5671e050..9a4b8884f 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/waf/errors.go +++ b/vendor/github.com/aws/aws-sdk-go/service/waf/errors.go @@ -1,4 +1,4 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. package waf diff --git a/vendor/github.com/aws/aws-sdk-go/service/waf/service.go b/vendor/github.com/aws/aws-sdk-go/service/waf/service.go index 700ef9cfd..91648a19f 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/waf/service.go +++ b/vendor/github.com/aws/aws-sdk-go/service/waf/service.go @@ -1,4 +1,4 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. package waf @@ -11,16 +11,12 @@ import ( "github.com/aws/aws-sdk-go/private/protocol/jsonrpc" ) -// This is the AWS WAF API Reference for using AWS WAF with Amazon CloudFront. -// The AWS WAF actions and data types listed in the reference are available -// for protecting Amazon CloudFront distributions. You can use these actions -// and data types via the endpoint waf.amazonaws.com. This guide is for developers -// who need detailed information about the AWS WAF API actions, data types, -// and errors. For detailed information about AWS WAF features and an overview -// of how to use the AWS WAF API, see the AWS WAF Developer Guide (http://docs.aws.amazon.com/waf/latest/developerguide/). -// The service client's operations are safe to be used concurrently. -// It is not safe to mutate any of the client's properties though. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/waf-2015-08-24 +// WAF provides the API operation methods for making requests to +// AWS WAF. See this package's package overview docs +// for details on the service. +// +// WAF methods are safe to use concurrently. It is not safe to +// modify mutate any of the struct's properties though. type WAF struct { *client.Client } diff --git a/vendor/github.com/aws/aws-sdk-go/service/wafregional/api.go b/vendor/github.com/aws/aws-sdk-go/service/wafregional/api.go new file mode 100644 index 000000000..a772109bf --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/service/wafregional/api.go @@ -0,0 +1,5715 @@ +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. + +package wafregional + +import ( + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/awsutil" + "github.com/aws/aws-sdk-go/aws/request" + "github.com/aws/aws-sdk-go/service/waf" +) + +const opAssociateWebACL = "AssociateWebACL" + +// AssociateWebACLRequest generates a "aws/request.Request" representing the +// client's request for the AssociateWebACL operation. The "output" return +// value can be used to capture response data after the request's "Send" method +// is called. +// +// See AssociateWebACL for usage and error information. +// +// Creating a request object using this method should be used when you want to inject +// custom logic into the request's lifecycle using a custom handler, or if you want to +// access properties on the request object before or after sending the request. If +// you just want the service response, call the AssociateWebACL method directly +// instead. +// +// Note: You must call the "Send" method on the returned request object in order +// to execute the request. +// +// // Example sending a request using the AssociateWebACLRequest method. +// req, resp := client.AssociateWebACLRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/waf-regional-2016-11-28/AssociateWebACL +func (c *WAFRegional) AssociateWebACLRequest(input *AssociateWebACLInput) (req *request.Request, output *AssociateWebACLOutput) { + op := &request.Operation{ + Name: opAssociateWebACL, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &AssociateWebACLInput{} + } + + output = &AssociateWebACLOutput{} + req = c.newRequest(op, input, output) + return +} + +// AssociateWebACL API operation for AWS WAF Regional. +// +// Associates a web ACL with a resource. +// +// 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 WAF Regional's +// API operation AssociateWebACL for usage and error information. +// +// Returned Error Codes: +// * ErrCodeWAFInternalErrorException "WAFInternalErrorException" +// The operation failed because of a system problem, even though the request +// was valid. Retry your request. +// +// * ErrCodeWAFInvalidAccountException "WAFInvalidAccountException" +// The operation failed because you tried to create, update, or delete an object +// by using an invalid account identifier. +// +// * ErrCodeWAFInvalidParameterException "WAFInvalidParameterException" +// The operation failed because AWS WAF didn't recognize a parameter in the +// request. For example: +// +// * You specified an invalid parameter name. +// +// * You specified an invalid value. +// +// * You tried to update an object (ByteMatchSet, IPSet, Rule, or WebACL) +// using an action other than INSERT or DELETE. +// +// * You tried to create a WebACL with a DefaultActionType other than ALLOW, +// BLOCK, or COUNT. +// +// * You tried to update a WebACL with a WafActionType other than ALLOW, +// BLOCK, or COUNT. +// +// * You tried to update a ByteMatchSet with a FieldToMatchType other than +// HEADER, QUERY_STRING, or URI. +// +// * You tried to update a ByteMatchSet with a Field of HEADER but no value +// for Data. +// +// * Your request references an ARN that is malformed, or corresponds to +// a resource with which a web ACL cannot be associated. +// +// * ErrCodeWAFNonexistentItemException "WAFNonexistentItemException" +// The operation failed because the referenced object doesn't exist. +// +// * ErrCodeWAFUnavailableEntityException "WAFUnavailableEntityException" +// The operation failed because the entity referenced is temporarily unavailable. +// Retry your request. +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/waf-regional-2016-11-28/AssociateWebACL +func (c *WAFRegional) AssociateWebACL(input *AssociateWebACLInput) (*AssociateWebACLOutput, error) { + req, out := c.AssociateWebACLRequest(input) + return out, req.Send() +} + +// AssociateWebACLWithContext is the same as AssociateWebACL with the addition of +// the ability to pass a context and additional request options. +// +// See AssociateWebACL 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 *WAFRegional) AssociateWebACLWithContext(ctx aws.Context, input *AssociateWebACLInput, opts ...request.Option) (*AssociateWebACLOutput, error) { + req, out := c.AssociateWebACLRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opCreateByteMatchSet = "CreateByteMatchSet" + +// CreateByteMatchSetRequest generates a "aws/request.Request" representing the +// client's request for the CreateByteMatchSet operation. The "output" return +// value can be used to capture response data after the request's "Send" method +// is called. +// +// See CreateByteMatchSet for usage and error information. +// +// Creating a request object using this method should be used when you want to inject +// custom logic into the request's lifecycle using a custom handler, or if you want to +// access properties on the request object before or after sending the request. If +// you just want the service response, call the CreateByteMatchSet method directly +// instead. +// +// Note: You must call the "Send" method on the returned request object in order +// to execute the request. +// +// // Example sending a request using the CreateByteMatchSetRequest method. +// req, resp := client.CreateByteMatchSetRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/waf-regional-2016-11-28/CreateByteMatchSet +func (c *WAFRegional) CreateByteMatchSetRequest(input *waf.CreateByteMatchSetInput) (req *request.Request, output *waf.CreateByteMatchSetOutput) { + op := &request.Operation{ + Name: opCreateByteMatchSet, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &waf.CreateByteMatchSetInput{} + } + + output = &waf.CreateByteMatchSetOutput{} + req = c.newRequest(op, input, output) + return +} + +// CreateByteMatchSet API operation for AWS WAF Regional. +// +// Creates a ByteMatchSet. You then use UpdateByteMatchSet to identify the part +// of a web request that you want AWS WAF to inspect, such as the values of +// the User-Agent header or the query string. For example, you can create a +// ByteMatchSet that matches any requests with User-Agent headers that contain +// the string BadBot. You can then configure AWS WAF to reject those requests. +// +// To create and configure a ByteMatchSet, perform the following steps: +// +// Use GetChangeToken to get the change token that you provide in the ChangeToken +// parameter of a CreateByteMatchSet request. +// +// Submit a CreateByteMatchSet request. +// +// Use GetChangeToken to get the change token that you provide in the ChangeToken +// parameter of an UpdateByteMatchSet request. +// +// Submit an UpdateByteMatchSet request to specify the part of the request that +// you want AWS WAF to inspect (for example, the header or the URI) and the +// value that you want AWS WAF to watch for. +// +// For more information about how to use the AWS WAF API to allow or block HTTP +// requests, see the AWS WAF Developer Guide (http://docs.aws.amazon.com/waf/latest/developerguide/). +// +// 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 WAF Regional's +// API operation CreateByteMatchSet for usage and error information. +// +// Returned Error Codes: +// * ErrCodeWAFDisallowedNameException "WAFDisallowedNameException" +// The name specified is invalid. +// +// * ErrCodeWAFInternalErrorException "WAFInternalErrorException" +// The operation failed because of a system problem, even though the request +// was valid. Retry your request. +// +// * ErrCodeWAFInvalidAccountException "WAFInvalidAccountException" +// The operation failed because you tried to create, update, or delete an object +// by using an invalid account identifier. +// +// * ErrCodeWAFInvalidParameterException "WAFInvalidParameterException" +// The operation failed because AWS WAF didn't recognize a parameter in the +// request. For example: +// +// * You specified an invalid parameter name. +// +// * You specified an invalid value. +// +// * You tried to update an object (ByteMatchSet, IPSet, Rule, or WebACL) +// using an action other than INSERT or DELETE. +// +// * You tried to create a WebACL with a DefaultActionType other than ALLOW, +// BLOCK, or COUNT. +// +// * You tried to update a WebACL with a WafActionType other than ALLOW, +// BLOCK, or COUNT. +// +// * You tried to update a ByteMatchSet with a FieldToMatchType other than +// HEADER, QUERY_STRING, or URI. +// +// * You tried to update a ByteMatchSet with a Field of HEADER but no value +// for Data. +// +// * Your request references an ARN that is malformed, or corresponds to +// a resource with which a web ACL cannot be associated. +// +// * ErrCodeWAFStaleDataException "WAFStaleDataException" +// The operation failed because you tried to create, update, or delete an object +// by using a change token that has already been used. +// +// * ErrCodeWAFLimitsExceededException "WAFLimitsExceededException" +// The operation exceeds a resource limit, for example, the maximum number of +// WebACL objects that you can create for an AWS account. For more information, +// see Limits (http://docs.aws.amazon.com/waf/latest/developerguide/limits.html) +// in the AWS WAF Developer Guide. +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/waf-regional-2016-11-28/CreateByteMatchSet +func (c *WAFRegional) CreateByteMatchSet(input *waf.CreateByteMatchSetInput) (*waf.CreateByteMatchSetOutput, error) { + req, out := c.CreateByteMatchSetRequest(input) + return out, req.Send() +} + +// CreateByteMatchSetWithContext is the same as CreateByteMatchSet with the addition of +// the ability to pass a context and additional request options. +// +// See CreateByteMatchSet 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 *WAFRegional) CreateByteMatchSetWithContext(ctx aws.Context, input *waf.CreateByteMatchSetInput, opts ...request.Option) (*waf.CreateByteMatchSetOutput, error) { + req, out := c.CreateByteMatchSetRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opCreateIPSet = "CreateIPSet" + +// CreateIPSetRequest generates a "aws/request.Request" representing the +// client's request for the CreateIPSet operation. The "output" return +// value can be used to capture response data after the request's "Send" method +// is called. +// +// See CreateIPSet for usage and error information. +// +// Creating a request object using this method should be used when you want to inject +// custom logic into the request's lifecycle using a custom handler, or if you want to +// access properties on the request object before or after sending the request. If +// you just want the service response, call the CreateIPSet method directly +// instead. +// +// Note: You must call the "Send" method on the returned request object in order +// to execute the request. +// +// // Example sending a request using the CreateIPSetRequest method. +// req, resp := client.CreateIPSetRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/waf-regional-2016-11-28/CreateIPSet +func (c *WAFRegional) CreateIPSetRequest(input *waf.CreateIPSetInput) (req *request.Request, output *waf.CreateIPSetOutput) { + op := &request.Operation{ + Name: opCreateIPSet, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &waf.CreateIPSetInput{} + } + + output = &waf.CreateIPSetOutput{} + req = c.newRequest(op, input, output) + return +} + +// CreateIPSet API operation for AWS WAF Regional. +// +// Creates an IPSet, which you use to specify which web requests you want to +// allow or block based on the IP addresses that the requests originate from. +// For example, if you're receiving a lot of requests from one or more individual +// IP addresses or one or more ranges of IP addresses and you want to block +// the requests, you can create an IPSet that contains those IP addresses and +// then configure AWS WAF to block the requests. +// +// To create and configure an IPSet, perform the following steps: +// +// Use GetChangeToken to get the change token that you provide in the ChangeToken +// parameter of a CreateIPSet request. +// +// Submit a CreateIPSet request. +// +// Use GetChangeToken to get the change token that you provide in the ChangeToken +// parameter of an UpdateIPSet request. +// +// Submit an UpdateIPSet request to specify the IP addresses that you want AWS +// WAF to watch for. +// +// For more information about how to use the AWS WAF API to allow or block HTTP +// requests, see the AWS WAF Developer Guide (http://docs.aws.amazon.com/waf/latest/developerguide/). +// +// 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 WAF Regional's +// API operation CreateIPSet for usage and error information. +// +// Returned Error Codes: +// * ErrCodeWAFStaleDataException "WAFStaleDataException" +// The operation failed because you tried to create, update, or delete an object +// by using a change token that has already been used. +// +// * ErrCodeWAFInternalErrorException "WAFInternalErrorException" +// The operation failed because of a system problem, even though the request +// was valid. Retry your request. +// +// * ErrCodeWAFInvalidAccountException "WAFInvalidAccountException" +// The operation failed because you tried to create, update, or delete an object +// by using an invalid account identifier. +// +// * ErrCodeWAFDisallowedNameException "WAFDisallowedNameException" +// The name specified is invalid. +// +// * ErrCodeWAFInvalidParameterException "WAFInvalidParameterException" +// The operation failed because AWS WAF didn't recognize a parameter in the +// request. For example: +// +// * You specified an invalid parameter name. +// +// * You specified an invalid value. +// +// * You tried to update an object (ByteMatchSet, IPSet, Rule, or WebACL) +// using an action other than INSERT or DELETE. +// +// * You tried to create a WebACL with a DefaultActionType other than ALLOW, +// BLOCK, or COUNT. +// +// * You tried to update a WebACL with a WafActionType other than ALLOW, +// BLOCK, or COUNT. +// +// * You tried to update a ByteMatchSet with a FieldToMatchType other than +// HEADER, QUERY_STRING, or URI. +// +// * You tried to update a ByteMatchSet with a Field of HEADER but no value +// for Data. +// +// * Your request references an ARN that is malformed, or corresponds to +// a resource with which a web ACL cannot be associated. +// +// * ErrCodeWAFLimitsExceededException "WAFLimitsExceededException" +// The operation exceeds a resource limit, for example, the maximum number of +// WebACL objects that you can create for an AWS account. For more information, +// see Limits (http://docs.aws.amazon.com/waf/latest/developerguide/limits.html) +// in the AWS WAF Developer Guide. +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/waf-regional-2016-11-28/CreateIPSet +func (c *WAFRegional) CreateIPSet(input *waf.CreateIPSetInput) (*waf.CreateIPSetOutput, error) { + req, out := c.CreateIPSetRequest(input) + return out, req.Send() +} + +// CreateIPSetWithContext is the same as CreateIPSet with the addition of +// the ability to pass a context and additional request options. +// +// See CreateIPSet 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 *WAFRegional) CreateIPSetWithContext(ctx aws.Context, input *waf.CreateIPSetInput, opts ...request.Option) (*waf.CreateIPSetOutput, error) { + req, out := c.CreateIPSetRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opCreateRule = "CreateRule" + +// CreateRuleRequest generates a "aws/request.Request" representing the +// client's request for the CreateRule operation. The "output" return +// value can be used to capture response data after the request's "Send" method +// is called. +// +// See CreateRule for usage and error information. +// +// Creating a request object using this method should be used when you want to inject +// custom logic into the request's lifecycle using a custom handler, or if you want to +// access properties on the request object before or after sending the request. If +// you just want the service response, call the CreateRule method directly +// instead. +// +// Note: You must call the "Send" method on the returned request object in order +// to execute the request. +// +// // Example sending a request using the CreateRuleRequest method. +// req, resp := client.CreateRuleRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/waf-regional-2016-11-28/CreateRule +func (c *WAFRegional) CreateRuleRequest(input *waf.CreateRuleInput) (req *request.Request, output *waf.CreateRuleOutput) { + op := &request.Operation{ + Name: opCreateRule, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &waf.CreateRuleInput{} + } + + output = &waf.CreateRuleOutput{} + req = c.newRequest(op, input, output) + return +} + +// CreateRule API operation for AWS WAF Regional. +// +// Creates a Rule, which contains the IPSet objects, ByteMatchSet objects, and +// other predicates that identify the requests that you want to block. If you +// add more than one predicate to a Rule, a request must match all of the specifications +// to be allowed or blocked. For example, suppose you add the following to a +// Rule: +// +// * An IPSet that matches the IP address 192.0.2.44/32 +// +// * A ByteMatchSet that matches BadBot in the User-Agent header +// +// You then add the Rule to a WebACL and specify that you want to blocks requests +// that satisfy the Rule. For a request to be blocked, it must come from the +// IP address 192.0.2.44 and the User-Agent header in the request must contain +// the value BadBot. +// +// To create and configure a Rule, perform the following steps: +// +// Create and update the predicates that you want to include in the Rule. For +// more information, see CreateByteMatchSet, CreateIPSet, and CreateSqlInjectionMatchSet. +// +// Use GetChangeToken to get the change token that you provide in the ChangeToken +// parameter of a CreateRule request. +// +// Submit a CreateRule request. +// +// Use GetChangeToken to get the change token that you provide in the ChangeToken +// parameter of an UpdateRule request. +// +// Submit an UpdateRule request to specify the predicates that you want to include +// in the Rule. +// +// Create and update a WebACL that contains the Rule. For more information, +// see CreateWebACL. +// +// For more information about how to use the AWS WAF API to allow or block HTTP +// requests, see the AWS WAF Developer Guide (http://docs.aws.amazon.com/waf/latest/developerguide/). +// +// 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 WAF Regional's +// API operation CreateRule for usage and error information. +// +// Returned Error Codes: +// * ErrCodeWAFStaleDataException "WAFStaleDataException" +// The operation failed because you tried to create, update, or delete an object +// by using a change token that has already been used. +// +// * ErrCodeWAFInternalErrorException "WAFInternalErrorException" +// The operation failed because of a system problem, even though the request +// was valid. Retry your request. +// +// * ErrCodeWAFDisallowedNameException "WAFDisallowedNameException" +// The name specified is invalid. +// +// * ErrCodeWAFInvalidParameterException "WAFInvalidParameterException" +// The operation failed because AWS WAF didn't recognize a parameter in the +// request. For example: +// +// * You specified an invalid parameter name. +// +// * You specified an invalid value. +// +// * You tried to update an object (ByteMatchSet, IPSet, Rule, or WebACL) +// using an action other than INSERT or DELETE. +// +// * You tried to create a WebACL with a DefaultActionType other than ALLOW, +// BLOCK, or COUNT. +// +// * You tried to update a WebACL with a WafActionType other than ALLOW, +// BLOCK, or COUNT. +// +// * You tried to update a ByteMatchSet with a FieldToMatchType other than +// HEADER, QUERY_STRING, or URI. +// +// * You tried to update a ByteMatchSet with a Field of HEADER but no value +// for Data. +// +// * Your request references an ARN that is malformed, or corresponds to +// a resource with which a web ACL cannot be associated. +// +// * ErrCodeWAFLimitsExceededException "WAFLimitsExceededException" +// The operation exceeds a resource limit, for example, the maximum number of +// WebACL objects that you can create for an AWS account. For more information, +// see Limits (http://docs.aws.amazon.com/waf/latest/developerguide/limits.html) +// in the AWS WAF Developer Guide. +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/waf-regional-2016-11-28/CreateRule +func (c *WAFRegional) CreateRule(input *waf.CreateRuleInput) (*waf.CreateRuleOutput, error) { + req, out := c.CreateRuleRequest(input) + return out, req.Send() +} + +// CreateRuleWithContext is the same as CreateRule with the addition of +// the ability to pass a context and additional request options. +// +// See CreateRule 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 *WAFRegional) CreateRuleWithContext(ctx aws.Context, input *waf.CreateRuleInput, opts ...request.Option) (*waf.CreateRuleOutput, error) { + req, out := c.CreateRuleRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opCreateSizeConstraintSet = "CreateSizeConstraintSet" + +// CreateSizeConstraintSetRequest generates a "aws/request.Request" representing the +// client's request for the CreateSizeConstraintSet operation. The "output" return +// value can be used to capture response data after the request's "Send" method +// is called. +// +// See CreateSizeConstraintSet for usage and error information. +// +// Creating a request object using this method should be used when you want to inject +// custom logic into the request's lifecycle using a custom handler, or if you want to +// access properties on the request object before or after sending the request. If +// you just want the service response, call the CreateSizeConstraintSet method directly +// instead. +// +// Note: You must call the "Send" method on the returned request object in order +// to execute the request. +// +// // Example sending a request using the CreateSizeConstraintSetRequest method. +// req, resp := client.CreateSizeConstraintSetRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/waf-regional-2016-11-28/CreateSizeConstraintSet +func (c *WAFRegional) CreateSizeConstraintSetRequest(input *waf.CreateSizeConstraintSetInput) (req *request.Request, output *waf.CreateSizeConstraintSetOutput) { + op := &request.Operation{ + Name: opCreateSizeConstraintSet, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &waf.CreateSizeConstraintSetInput{} + } + + output = &waf.CreateSizeConstraintSetOutput{} + req = c.newRequest(op, input, output) + return +} + +// CreateSizeConstraintSet API operation for AWS WAF Regional. +// +// Creates a SizeConstraintSet. You then use UpdateSizeConstraintSet to identify +// the part of a web request that you want AWS WAF to check for length, such +// as the length of the User-Agent header or the length of the query string. +// For example, you can create a SizeConstraintSet that matches any requests +// that have a query string that is longer than 100 bytes. You can then configure +// AWS WAF to reject those requests. +// +// To create and configure a SizeConstraintSet, perform the following steps: +// +// Use GetChangeToken to get the change token that you provide in the ChangeToken +// parameter of a CreateSizeConstraintSet request. +// +// Submit a CreateSizeConstraintSet request. +// +// Use GetChangeToken to get the change token that you provide in the ChangeToken +// parameter of an UpdateSizeConstraintSet request. +// +// Submit an UpdateSizeConstraintSet request to specify the part of the request +// that you want AWS WAF to inspect (for example, the header or the URI) and +// the value that you want AWS WAF to watch for. +// +// For more information about how to use the AWS WAF API to allow or block HTTP +// requests, see the AWS WAF Developer Guide (http://docs.aws.amazon.com/waf/latest/developerguide/). +// +// 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 WAF Regional's +// API operation CreateSizeConstraintSet for usage and error information. +// +// Returned Error Codes: +// * ErrCodeWAFStaleDataException "WAFStaleDataException" +// The operation failed because you tried to create, update, or delete an object +// by using a change token that has already been used. +// +// * ErrCodeWAFInternalErrorException "WAFInternalErrorException" +// The operation failed because of a system problem, even though the request +// was valid. Retry your request. +// +// * ErrCodeWAFInvalidAccountException "WAFInvalidAccountException" +// The operation failed because you tried to create, update, or delete an object +// by using an invalid account identifier. +// +// * ErrCodeWAFDisallowedNameException "WAFDisallowedNameException" +// The name specified is invalid. +// +// * ErrCodeWAFInvalidParameterException "WAFInvalidParameterException" +// The operation failed because AWS WAF didn't recognize a parameter in the +// request. For example: +// +// * You specified an invalid parameter name. +// +// * You specified an invalid value. +// +// * You tried to update an object (ByteMatchSet, IPSet, Rule, or WebACL) +// using an action other than INSERT or DELETE. +// +// * You tried to create a WebACL with a DefaultActionType other than ALLOW, +// BLOCK, or COUNT. +// +// * You tried to update a WebACL with a WafActionType other than ALLOW, +// BLOCK, or COUNT. +// +// * You tried to update a ByteMatchSet with a FieldToMatchType other than +// HEADER, QUERY_STRING, or URI. +// +// * You tried to update a ByteMatchSet with a Field of HEADER but no value +// for Data. +// +// * Your request references an ARN that is malformed, or corresponds to +// a resource with which a web ACL cannot be associated. +// +// * ErrCodeWAFLimitsExceededException "WAFLimitsExceededException" +// The operation exceeds a resource limit, for example, the maximum number of +// WebACL objects that you can create for an AWS account. For more information, +// see Limits (http://docs.aws.amazon.com/waf/latest/developerguide/limits.html) +// in the AWS WAF Developer Guide. +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/waf-regional-2016-11-28/CreateSizeConstraintSet +func (c *WAFRegional) CreateSizeConstraintSet(input *waf.CreateSizeConstraintSetInput) (*waf.CreateSizeConstraintSetOutput, error) { + req, out := c.CreateSizeConstraintSetRequest(input) + return out, req.Send() +} + +// CreateSizeConstraintSetWithContext is the same as CreateSizeConstraintSet with the addition of +// the ability to pass a context and additional request options. +// +// See CreateSizeConstraintSet 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 *WAFRegional) CreateSizeConstraintSetWithContext(ctx aws.Context, input *waf.CreateSizeConstraintSetInput, opts ...request.Option) (*waf.CreateSizeConstraintSetOutput, error) { + req, out := c.CreateSizeConstraintSetRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opCreateSqlInjectionMatchSet = "CreateSqlInjectionMatchSet" + +// CreateSqlInjectionMatchSetRequest generates a "aws/request.Request" representing the +// client's request for the CreateSqlInjectionMatchSet operation. The "output" return +// value can be used to capture response data after the request's "Send" method +// is called. +// +// See CreateSqlInjectionMatchSet for usage and error information. +// +// Creating a request object using this method should be used when you want to inject +// custom logic into the request's lifecycle using a custom handler, or if you want to +// access properties on the request object before or after sending the request. If +// you just want the service response, call the CreateSqlInjectionMatchSet method directly +// instead. +// +// Note: You must call the "Send" method on the returned request object in order +// to execute the request. +// +// // Example sending a request using the CreateSqlInjectionMatchSetRequest method. +// req, resp := client.CreateSqlInjectionMatchSetRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/waf-regional-2016-11-28/CreateSqlInjectionMatchSet +func (c *WAFRegional) CreateSqlInjectionMatchSetRequest(input *waf.CreateSqlInjectionMatchSetInput) (req *request.Request, output *waf.CreateSqlInjectionMatchSetOutput) { + op := &request.Operation{ + Name: opCreateSqlInjectionMatchSet, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &waf.CreateSqlInjectionMatchSetInput{} + } + + output = &waf.CreateSqlInjectionMatchSetOutput{} + req = c.newRequest(op, input, output) + return +} + +// CreateSqlInjectionMatchSet API operation for AWS WAF Regional. +// +// Creates a SqlInjectionMatchSet, which you use to allow, block, or count requests +// that contain snippets of SQL code in a specified part of web requests. AWS +// WAF searches for character sequences that are likely to be malicious strings. +// +// To create and configure a SqlInjectionMatchSet, perform the following steps: +// +// Use GetChangeToken to get the change token that you provide in the ChangeToken +// parameter of a CreateSqlInjectionMatchSet request. +// +// Submit a CreateSqlInjectionMatchSet request. +// +// Use GetChangeToken to get the change token that you provide in the ChangeToken +// parameter of an UpdateSqlInjectionMatchSet request. +// +// Submit an UpdateSqlInjectionMatchSet request to specify the parts of web +// requests in which you want to allow, block, or count malicious SQL code. +// +// For more information about how to use the AWS WAF API to allow or block HTTP +// requests, see the AWS WAF Developer Guide (http://docs.aws.amazon.com/waf/latest/developerguide/). +// +// 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 WAF Regional's +// API operation CreateSqlInjectionMatchSet for usage and error information. +// +// Returned Error Codes: +// * ErrCodeWAFDisallowedNameException "WAFDisallowedNameException" +// The name specified is invalid. +// +// * ErrCodeWAFInternalErrorException "WAFInternalErrorException" +// The operation failed because of a system problem, even though the request +// was valid. Retry your request. +// +// * ErrCodeWAFInvalidAccountException "WAFInvalidAccountException" +// The operation failed because you tried to create, update, or delete an object +// by using an invalid account identifier. +// +// * ErrCodeWAFInvalidParameterException "WAFInvalidParameterException" +// The operation failed because AWS WAF didn't recognize a parameter in the +// request. For example: +// +// * You specified an invalid parameter name. +// +// * You specified an invalid value. +// +// * You tried to update an object (ByteMatchSet, IPSet, Rule, or WebACL) +// using an action other than INSERT or DELETE. +// +// * You tried to create a WebACL with a DefaultActionType other than ALLOW, +// BLOCK, or COUNT. +// +// * You tried to update a WebACL with a WafActionType other than ALLOW, +// BLOCK, or COUNT. +// +// * You tried to update a ByteMatchSet with a FieldToMatchType other than +// HEADER, QUERY_STRING, or URI. +// +// * You tried to update a ByteMatchSet with a Field of HEADER but no value +// for Data. +// +// * Your request references an ARN that is malformed, or corresponds to +// a resource with which a web ACL cannot be associated. +// +// * ErrCodeWAFStaleDataException "WAFStaleDataException" +// The operation failed because you tried to create, update, or delete an object +// by using a change token that has already been used. +// +// * ErrCodeWAFLimitsExceededException "WAFLimitsExceededException" +// The operation exceeds a resource limit, for example, the maximum number of +// WebACL objects that you can create for an AWS account. For more information, +// see Limits (http://docs.aws.amazon.com/waf/latest/developerguide/limits.html) +// in the AWS WAF Developer Guide. +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/waf-regional-2016-11-28/CreateSqlInjectionMatchSet +func (c *WAFRegional) CreateSqlInjectionMatchSet(input *waf.CreateSqlInjectionMatchSetInput) (*waf.CreateSqlInjectionMatchSetOutput, error) { + req, out := c.CreateSqlInjectionMatchSetRequest(input) + return out, req.Send() +} + +// CreateSqlInjectionMatchSetWithContext is the same as CreateSqlInjectionMatchSet with the addition of +// the ability to pass a context and additional request options. +// +// See CreateSqlInjectionMatchSet 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 *WAFRegional) CreateSqlInjectionMatchSetWithContext(ctx aws.Context, input *waf.CreateSqlInjectionMatchSetInput, opts ...request.Option) (*waf.CreateSqlInjectionMatchSetOutput, error) { + req, out := c.CreateSqlInjectionMatchSetRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opCreateWebACL = "CreateWebACL" + +// CreateWebACLRequest generates a "aws/request.Request" representing the +// client's request for the CreateWebACL operation. The "output" return +// value can be used to capture response data after the request's "Send" method +// is called. +// +// See CreateWebACL for usage and error information. +// +// Creating a request object using this method should be used when you want to inject +// custom logic into the request's lifecycle using a custom handler, or if you want to +// access properties on the request object before or after sending the request. If +// you just want the service response, call the CreateWebACL method directly +// instead. +// +// Note: You must call the "Send" method on the returned request object in order +// to execute the request. +// +// // Example sending a request using the CreateWebACLRequest method. +// req, resp := client.CreateWebACLRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/waf-regional-2016-11-28/CreateWebACL +func (c *WAFRegional) CreateWebACLRequest(input *waf.CreateWebACLInput) (req *request.Request, output *waf.CreateWebACLOutput) { + op := &request.Operation{ + Name: opCreateWebACL, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &waf.CreateWebACLInput{} + } + + output = &waf.CreateWebACLOutput{} + req = c.newRequest(op, input, output) + return +} + +// CreateWebACL API operation for AWS WAF Regional. +// +// Creates a WebACL, which contains the Rules that identify the CloudFront web +// requests that you want to allow, block, or count. AWS WAF evaluates Rules +// in order based on the value of Priority for each Rule. +// +// You also specify a default action, either ALLOW or BLOCK. If a web request +// doesn't match any of the Rules in a WebACL, AWS WAF responds to the request +// with the default action. +// +// To create and configure a WebACL, perform the following steps: +// +// Create and update the ByteMatchSet objects and other predicates that you +// want to include in Rules. For more information, see CreateByteMatchSet, UpdateByteMatchSet, +// CreateIPSet, UpdateIPSet, CreateSqlInjectionMatchSet, and UpdateSqlInjectionMatchSet. +// +// Create and update the Rules that you want to include in the WebACL. For more +// information, see CreateRule and UpdateRule. +// +// Use GetChangeToken to get the change token that you provide in the ChangeToken +// parameter of a CreateWebACL request. +// +// Submit a CreateWebACL request. +// +// Use GetChangeToken to get the change token that you provide in the ChangeToken +// parameter of an UpdateWebACL request. +// +// Submit an UpdateWebACL request to specify the Rules that you want to include +// in the WebACL, to specify the default action, and to associate the WebACL +// with a CloudFront distribution. +// +// For more information about how to use the AWS WAF API, see the AWS WAF Developer +// Guide (http://docs.aws.amazon.com/waf/latest/developerguide/). +// +// 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 WAF Regional's +// API operation CreateWebACL for usage and error information. +// +// Returned Error Codes: +// * ErrCodeWAFStaleDataException "WAFStaleDataException" +// The operation failed because you tried to create, update, or delete an object +// by using a change token that has already been used. +// +// * ErrCodeWAFInternalErrorException "WAFInternalErrorException" +// The operation failed because of a system problem, even though the request +// was valid. Retry your request. +// +// * ErrCodeWAFInvalidAccountException "WAFInvalidAccountException" +// The operation failed because you tried to create, update, or delete an object +// by using an invalid account identifier. +// +// * ErrCodeWAFDisallowedNameException "WAFDisallowedNameException" +// The name specified is invalid. +// +// * ErrCodeWAFInvalidParameterException "WAFInvalidParameterException" +// The operation failed because AWS WAF didn't recognize a parameter in the +// request. For example: +// +// * You specified an invalid parameter name. +// +// * You specified an invalid value. +// +// * You tried to update an object (ByteMatchSet, IPSet, Rule, or WebACL) +// using an action other than INSERT or DELETE. +// +// * You tried to create a WebACL with a DefaultActionType other than ALLOW, +// BLOCK, or COUNT. +// +// * You tried to update a WebACL with a WafActionType other than ALLOW, +// BLOCK, or COUNT. +// +// * You tried to update a ByteMatchSet with a FieldToMatchType other than +// HEADER, QUERY_STRING, or URI. +// +// * You tried to update a ByteMatchSet with a Field of HEADER but no value +// for Data. +// +// * Your request references an ARN that is malformed, or corresponds to +// a resource with which a web ACL cannot be associated. +// +// * ErrCodeWAFLimitsExceededException "WAFLimitsExceededException" +// The operation exceeds a resource limit, for example, the maximum number of +// WebACL objects that you can create for an AWS account. For more information, +// see Limits (http://docs.aws.amazon.com/waf/latest/developerguide/limits.html) +// in the AWS WAF Developer Guide. +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/waf-regional-2016-11-28/CreateWebACL +func (c *WAFRegional) CreateWebACL(input *waf.CreateWebACLInput) (*waf.CreateWebACLOutput, error) { + req, out := c.CreateWebACLRequest(input) + return out, req.Send() +} + +// CreateWebACLWithContext is the same as CreateWebACL with the addition of +// the ability to pass a context and additional request options. +// +// See CreateWebACL 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 *WAFRegional) CreateWebACLWithContext(ctx aws.Context, input *waf.CreateWebACLInput, opts ...request.Option) (*waf.CreateWebACLOutput, error) { + req, out := c.CreateWebACLRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opCreateXssMatchSet = "CreateXssMatchSet" + +// CreateXssMatchSetRequest generates a "aws/request.Request" representing the +// client's request for the CreateXssMatchSet operation. The "output" return +// value can be used to capture response data after the request's "Send" method +// is called. +// +// See CreateXssMatchSet for usage and error information. +// +// Creating a request object using this method should be used when you want to inject +// custom logic into the request's lifecycle using a custom handler, or if you want to +// access properties on the request object before or after sending the request. If +// you just want the service response, call the CreateXssMatchSet method directly +// instead. +// +// Note: You must call the "Send" method on the returned request object in order +// to execute the request. +// +// // Example sending a request using the CreateXssMatchSetRequest method. +// req, resp := client.CreateXssMatchSetRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/waf-regional-2016-11-28/CreateXssMatchSet +func (c *WAFRegional) CreateXssMatchSetRequest(input *waf.CreateXssMatchSetInput) (req *request.Request, output *waf.CreateXssMatchSetOutput) { + op := &request.Operation{ + Name: opCreateXssMatchSet, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &waf.CreateXssMatchSetInput{} + } + + output = &waf.CreateXssMatchSetOutput{} + req = c.newRequest(op, input, output) + return +} + +// CreateXssMatchSet API operation for AWS WAF Regional. +// +// Creates an XssMatchSet, which you use to allow, block, or count requests +// that contain cross-site scripting attacks in the specified part of web requests. +// AWS WAF searches for character sequences that are likely to be malicious +// strings. +// +// To create and configure an XssMatchSet, perform the following steps: +// +// Use GetChangeToken to get the change token that you provide in the ChangeToken +// parameter of a CreateXssMatchSet request. +// +// Submit a CreateXssMatchSet request. +// +// Use GetChangeToken to get the change token that you provide in the ChangeToken +// parameter of an UpdateXssMatchSet request. +// +// Submit an UpdateXssMatchSet request to specify the parts of web requests +// in which you want to allow, block, or count cross-site scripting attacks. +// +// For more information about how to use the AWS WAF API to allow or block HTTP +// requests, see the AWS WAF Developer Guide (http://docs.aws.amazon.com/waf/latest/developerguide/). +// +// 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 WAF Regional's +// API operation CreateXssMatchSet for usage and error information. +// +// Returned Error Codes: +// * ErrCodeWAFDisallowedNameException "WAFDisallowedNameException" +// The name specified is invalid. +// +// * ErrCodeWAFInternalErrorException "WAFInternalErrorException" +// The operation failed because of a system problem, even though the request +// was valid. Retry your request. +// +// * ErrCodeWAFInvalidAccountException "WAFInvalidAccountException" +// The operation failed because you tried to create, update, or delete an object +// by using an invalid account identifier. +// +// * ErrCodeWAFInvalidParameterException "WAFInvalidParameterException" +// The operation failed because AWS WAF didn't recognize a parameter in the +// request. For example: +// +// * You specified an invalid parameter name. +// +// * You specified an invalid value. +// +// * You tried to update an object (ByteMatchSet, IPSet, Rule, or WebACL) +// using an action other than INSERT or DELETE. +// +// * You tried to create a WebACL with a DefaultActionType other than ALLOW, +// BLOCK, or COUNT. +// +// * You tried to update a WebACL with a WafActionType other than ALLOW, +// BLOCK, or COUNT. +// +// * You tried to update a ByteMatchSet with a FieldToMatchType other than +// HEADER, QUERY_STRING, or URI. +// +// * You tried to update a ByteMatchSet with a Field of HEADER but no value +// for Data. +// +// * Your request references an ARN that is malformed, or corresponds to +// a resource with which a web ACL cannot be associated. +// +// * ErrCodeWAFStaleDataException "WAFStaleDataException" +// The operation failed because you tried to create, update, or delete an object +// by using a change token that has already been used. +// +// * ErrCodeWAFLimitsExceededException "WAFLimitsExceededException" +// The operation exceeds a resource limit, for example, the maximum number of +// WebACL objects that you can create for an AWS account. For more information, +// see Limits (http://docs.aws.amazon.com/waf/latest/developerguide/limits.html) +// in the AWS WAF Developer Guide. +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/waf-regional-2016-11-28/CreateXssMatchSet +func (c *WAFRegional) CreateXssMatchSet(input *waf.CreateXssMatchSetInput) (*waf.CreateXssMatchSetOutput, error) { + req, out := c.CreateXssMatchSetRequest(input) + return out, req.Send() +} + +// CreateXssMatchSetWithContext is the same as CreateXssMatchSet with the addition of +// the ability to pass a context and additional request options. +// +// See CreateXssMatchSet 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 *WAFRegional) CreateXssMatchSetWithContext(ctx aws.Context, input *waf.CreateXssMatchSetInput, opts ...request.Option) (*waf.CreateXssMatchSetOutput, error) { + req, out := c.CreateXssMatchSetRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opDeleteByteMatchSet = "DeleteByteMatchSet" + +// DeleteByteMatchSetRequest generates a "aws/request.Request" representing the +// client's request for the DeleteByteMatchSet operation. The "output" return +// value can be used to capture response data after the request's "Send" method +// is called. +// +// See DeleteByteMatchSet for usage and error information. +// +// Creating a request object using this method should be used when you want to inject +// custom logic into the request's lifecycle using a custom handler, or if you want to +// access properties on the request object before or after sending the request. If +// you just want the service response, call the DeleteByteMatchSet method directly +// instead. +// +// Note: You must call the "Send" method on the returned request object in order +// to execute the request. +// +// // Example sending a request using the DeleteByteMatchSetRequest method. +// req, resp := client.DeleteByteMatchSetRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/waf-regional-2016-11-28/DeleteByteMatchSet +func (c *WAFRegional) DeleteByteMatchSetRequest(input *waf.DeleteByteMatchSetInput) (req *request.Request, output *waf.DeleteByteMatchSetOutput) { + op := &request.Operation{ + Name: opDeleteByteMatchSet, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &waf.DeleteByteMatchSetInput{} + } + + output = &waf.DeleteByteMatchSetOutput{} + req = c.newRequest(op, input, output) + return +} + +// DeleteByteMatchSet API operation for AWS WAF Regional. +// +// Permanently deletes a ByteMatchSet. You can't delete a ByteMatchSet if it's +// still used in any Rules or if it still includes any ByteMatchTuple objects +// (any filters). +// +// If you just want to remove a ByteMatchSet from a Rule, use UpdateRule. +// +// To permanently delete a ByteMatchSet, perform the following steps: +// +// Update the ByteMatchSet to remove filters, if any. For more information, +// see UpdateByteMatchSet. +// +// Use GetChangeToken to get the change token that you provide in the ChangeToken +// parameter of a DeleteByteMatchSet request. +// +// Submit a DeleteByteMatchSet 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. +// +// See the AWS API reference guide for AWS WAF Regional's +// API operation DeleteByteMatchSet for usage and error information. +// +// Returned Error Codes: +// * ErrCodeWAFInternalErrorException "WAFInternalErrorException" +// The operation failed because of a system problem, even though the request +// was valid. Retry your request. +// +// * ErrCodeWAFInvalidAccountException "WAFInvalidAccountException" +// The operation failed because you tried to create, update, or delete an object +// by using an invalid account identifier. +// +// * ErrCodeWAFNonexistentItemException "WAFNonexistentItemException" +// The operation failed because the referenced object doesn't exist. +// +// * ErrCodeWAFReferencedItemException "WAFReferencedItemException" +// The operation failed because you tried to delete an object that is still +// in use. For example: +// +// * You tried to delete a ByteMatchSet that is still referenced by a Rule. +// +// * You tried to delete a Rule that is still referenced by a WebACL. +// +// * ErrCodeWAFStaleDataException "WAFStaleDataException" +// The operation failed because you tried to create, update, or delete an object +// by using a change token that has already been used. +// +// * ErrCodeWAFNonEmptyEntityException "WAFNonEmptyEntityException" +// The operation failed because you tried to delete an object that isn't empty. +// For example: +// +// * You tried to delete a WebACL that still contains one or more Rule objects. +// +// * You tried to delete a Rule that still contains one or more ByteMatchSet +// objects or other predicates. +// +// * You tried to delete a ByteMatchSet that contains one or more ByteMatchTuple +// objects. +// +// * You tried to delete an IPSet that references one or more IP addresses. +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/waf-regional-2016-11-28/DeleteByteMatchSet +func (c *WAFRegional) DeleteByteMatchSet(input *waf.DeleteByteMatchSetInput) (*waf.DeleteByteMatchSetOutput, error) { + req, out := c.DeleteByteMatchSetRequest(input) + return out, req.Send() +} + +// DeleteByteMatchSetWithContext is the same as DeleteByteMatchSet with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteByteMatchSet 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 *WAFRegional) DeleteByteMatchSetWithContext(ctx aws.Context, input *waf.DeleteByteMatchSetInput, opts ...request.Option) (*waf.DeleteByteMatchSetOutput, error) { + req, out := c.DeleteByteMatchSetRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opDeleteIPSet = "DeleteIPSet" + +// DeleteIPSetRequest generates a "aws/request.Request" representing the +// client's request for the DeleteIPSet operation. The "output" return +// value can be used to capture response data after the request's "Send" method +// is called. +// +// See DeleteIPSet for usage and error information. +// +// Creating a request object using this method should be used when you want to inject +// custom logic into the request's lifecycle using a custom handler, or if you want to +// access properties on the request object before or after sending the request. If +// you just want the service response, call the DeleteIPSet method directly +// instead. +// +// Note: You must call the "Send" method on the returned request object in order +// to execute the request. +// +// // Example sending a request using the DeleteIPSetRequest method. +// req, resp := client.DeleteIPSetRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/waf-regional-2016-11-28/DeleteIPSet +func (c *WAFRegional) DeleteIPSetRequest(input *waf.DeleteIPSetInput) (req *request.Request, output *waf.DeleteIPSetOutput) { + op := &request.Operation{ + Name: opDeleteIPSet, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &waf.DeleteIPSetInput{} + } + + output = &waf.DeleteIPSetOutput{} + req = c.newRequest(op, input, output) + return +} + +// DeleteIPSet API operation for AWS WAF Regional. +// +// Permanently deletes an IPSet. You can't delete an IPSet if it's still used +// in any Rules or if it still includes any IP addresses. +// +// If you just want to remove an IPSet from a Rule, use UpdateRule. +// +// To permanently delete an IPSet from AWS WAF, perform the following steps: +// +// Update the IPSet to remove IP address ranges, if any. For more information, +// see UpdateIPSet. +// +// Use GetChangeToken to get the change token that you provide in the ChangeToken +// parameter of a DeleteIPSet request. +// +// Submit a DeleteIPSet 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. +// +// See the AWS API reference guide for AWS WAF Regional's +// API operation DeleteIPSet for usage and error information. +// +// Returned Error Codes: +// * ErrCodeWAFStaleDataException "WAFStaleDataException" +// The operation failed because you tried to create, update, or delete an object +// by using a change token that has already been used. +// +// * ErrCodeWAFInternalErrorException "WAFInternalErrorException" +// The operation failed because of a system problem, even though the request +// was valid. Retry your request. +// +// * ErrCodeWAFInvalidAccountException "WAFInvalidAccountException" +// The operation failed because you tried to create, update, or delete an object +// by using an invalid account identifier. +// +// * ErrCodeWAFNonexistentItemException "WAFNonexistentItemException" +// The operation failed because the referenced object doesn't exist. +// +// * ErrCodeWAFReferencedItemException "WAFReferencedItemException" +// The operation failed because you tried to delete an object that is still +// in use. For example: +// +// * You tried to delete a ByteMatchSet that is still referenced by a Rule. +// +// * You tried to delete a Rule that is still referenced by a WebACL. +// +// * ErrCodeWAFNonEmptyEntityException "WAFNonEmptyEntityException" +// The operation failed because you tried to delete an object that isn't empty. +// For example: +// +// * You tried to delete a WebACL that still contains one or more Rule objects. +// +// * You tried to delete a Rule that still contains one or more ByteMatchSet +// objects or other predicates. +// +// * You tried to delete a ByteMatchSet that contains one or more ByteMatchTuple +// objects. +// +// * You tried to delete an IPSet that references one or more IP addresses. +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/waf-regional-2016-11-28/DeleteIPSet +func (c *WAFRegional) DeleteIPSet(input *waf.DeleteIPSetInput) (*waf.DeleteIPSetOutput, error) { + req, out := c.DeleteIPSetRequest(input) + return out, req.Send() +} + +// DeleteIPSetWithContext is the same as DeleteIPSet with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteIPSet 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 *WAFRegional) DeleteIPSetWithContext(ctx aws.Context, input *waf.DeleteIPSetInput, opts ...request.Option) (*waf.DeleteIPSetOutput, error) { + req, out := c.DeleteIPSetRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opDeleteRule = "DeleteRule" + +// DeleteRuleRequest generates a "aws/request.Request" representing the +// client's request for the DeleteRule operation. The "output" return +// value can be used to capture response data after the request's "Send" method +// is called. +// +// See DeleteRule for usage and error information. +// +// Creating a request object using this method should be used when you want to inject +// custom logic into the request's lifecycle using a custom handler, or if you want to +// access properties on the request object before or after sending the request. If +// you just want the service response, call the DeleteRule method directly +// instead. +// +// Note: You must call the "Send" method on the returned request object in order +// to execute the request. +// +// // Example sending a request using the DeleteRuleRequest method. +// req, resp := client.DeleteRuleRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/waf-regional-2016-11-28/DeleteRule +func (c *WAFRegional) DeleteRuleRequest(input *waf.DeleteRuleInput) (req *request.Request, output *waf.DeleteRuleOutput) { + op := &request.Operation{ + Name: opDeleteRule, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &waf.DeleteRuleInput{} + } + + output = &waf.DeleteRuleOutput{} + req = c.newRequest(op, input, output) + return +} + +// DeleteRule API operation for AWS WAF Regional. +// +// Permanently deletes a Rule. You can't delete a Rule if it's still used in +// any WebACL objects or if it still includes any predicates, such as ByteMatchSet +// objects. +// +// If you just want to remove a Rule from a WebACL, use UpdateWebACL. +// +// To permanently delete a Rule from AWS WAF, perform the following steps: +// +// Update the Rule to remove predicates, if any. For more information, see UpdateRule. +// +// Use GetChangeToken to get the change token that you provide in the ChangeToken +// parameter of a DeleteRule request. +// +// Submit a DeleteRule 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. +// +// See the AWS API reference guide for AWS WAF Regional's +// API operation DeleteRule for usage and error information. +// +// Returned Error Codes: +// * ErrCodeWAFStaleDataException "WAFStaleDataException" +// The operation failed because you tried to create, update, or delete an object +// by using a change token that has already been used. +// +// * ErrCodeWAFInternalErrorException "WAFInternalErrorException" +// The operation failed because of a system problem, even though the request +// was valid. Retry your request. +// +// * ErrCodeWAFInvalidAccountException "WAFInvalidAccountException" +// The operation failed because you tried to create, update, or delete an object +// by using an invalid account identifier. +// +// * ErrCodeWAFNonexistentItemException "WAFNonexistentItemException" +// The operation failed because the referenced object doesn't exist. +// +// * ErrCodeWAFReferencedItemException "WAFReferencedItemException" +// The operation failed because you tried to delete an object that is still +// in use. For example: +// +// * You tried to delete a ByteMatchSet that is still referenced by a Rule. +// +// * You tried to delete a Rule that is still referenced by a WebACL. +// +// * ErrCodeWAFNonEmptyEntityException "WAFNonEmptyEntityException" +// The operation failed because you tried to delete an object that isn't empty. +// For example: +// +// * You tried to delete a WebACL that still contains one or more Rule objects. +// +// * You tried to delete a Rule that still contains one or more ByteMatchSet +// objects or other predicates. +// +// * You tried to delete a ByteMatchSet that contains one or more ByteMatchTuple +// objects. +// +// * You tried to delete an IPSet that references one or more IP addresses. +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/waf-regional-2016-11-28/DeleteRule +func (c *WAFRegional) DeleteRule(input *waf.DeleteRuleInput) (*waf.DeleteRuleOutput, error) { + req, out := c.DeleteRuleRequest(input) + return out, req.Send() +} + +// DeleteRuleWithContext is the same as DeleteRule with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteRule 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 *WAFRegional) DeleteRuleWithContext(ctx aws.Context, input *waf.DeleteRuleInput, opts ...request.Option) (*waf.DeleteRuleOutput, error) { + req, out := c.DeleteRuleRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opDeleteSizeConstraintSet = "DeleteSizeConstraintSet" + +// DeleteSizeConstraintSetRequest generates a "aws/request.Request" representing the +// client's request for the DeleteSizeConstraintSet operation. The "output" return +// value can be used to capture response data after the request's "Send" method +// is called. +// +// See DeleteSizeConstraintSet for usage and error information. +// +// Creating a request object using this method should be used when you want to inject +// custom logic into the request's lifecycle using a custom handler, or if you want to +// access properties on the request object before or after sending the request. If +// you just want the service response, call the DeleteSizeConstraintSet method directly +// instead. +// +// Note: You must call the "Send" method on the returned request object in order +// to execute the request. +// +// // Example sending a request using the DeleteSizeConstraintSetRequest method. +// req, resp := client.DeleteSizeConstraintSetRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/waf-regional-2016-11-28/DeleteSizeConstraintSet +func (c *WAFRegional) DeleteSizeConstraintSetRequest(input *waf.DeleteSizeConstraintSetInput) (req *request.Request, output *waf.DeleteSizeConstraintSetOutput) { + op := &request.Operation{ + Name: opDeleteSizeConstraintSet, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &waf.DeleteSizeConstraintSetInput{} + } + + output = &waf.DeleteSizeConstraintSetOutput{} + req = c.newRequest(op, input, output) + return +} + +// DeleteSizeConstraintSet API operation for AWS WAF Regional. +// +// Permanently deletes a SizeConstraintSet. You can't delete a SizeConstraintSet +// if it's still used in any Rules or if it still includes any SizeConstraint +// objects (any filters). +// +// If you just want to remove a SizeConstraintSet from a Rule, use UpdateRule. +// +// To permanently delete a SizeConstraintSet, perform the following steps: +// +// Update the SizeConstraintSet to remove filters, if any. For more information, +// see UpdateSizeConstraintSet. +// +// Use GetChangeToken to get the change token that you provide in the ChangeToken +// parameter of a DeleteSizeConstraintSet request. +// +// Submit a DeleteSizeConstraintSet 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. +// +// See the AWS API reference guide for AWS WAF Regional's +// API operation DeleteSizeConstraintSet for usage and error information. +// +// Returned Error Codes: +// * ErrCodeWAFStaleDataException "WAFStaleDataException" +// The operation failed because you tried to create, update, or delete an object +// by using a change token that has already been used. +// +// * ErrCodeWAFInternalErrorException "WAFInternalErrorException" +// The operation failed because of a system problem, even though the request +// was valid. Retry your request. +// +// * ErrCodeWAFInvalidAccountException "WAFInvalidAccountException" +// The operation failed because you tried to create, update, or delete an object +// by using an invalid account identifier. +// +// * ErrCodeWAFNonexistentItemException "WAFNonexistentItemException" +// The operation failed because the referenced object doesn't exist. +// +// * ErrCodeWAFReferencedItemException "WAFReferencedItemException" +// The operation failed because you tried to delete an object that is still +// in use. For example: +// +// * You tried to delete a ByteMatchSet that is still referenced by a Rule. +// +// * You tried to delete a Rule that is still referenced by a WebACL. +// +// * ErrCodeWAFNonEmptyEntityException "WAFNonEmptyEntityException" +// The operation failed because you tried to delete an object that isn't empty. +// For example: +// +// * You tried to delete a WebACL that still contains one or more Rule objects. +// +// * You tried to delete a Rule that still contains one or more ByteMatchSet +// objects or other predicates. +// +// * You tried to delete a ByteMatchSet that contains one or more ByteMatchTuple +// objects. +// +// * You tried to delete an IPSet that references one or more IP addresses. +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/waf-regional-2016-11-28/DeleteSizeConstraintSet +func (c *WAFRegional) DeleteSizeConstraintSet(input *waf.DeleteSizeConstraintSetInput) (*waf.DeleteSizeConstraintSetOutput, error) { + req, out := c.DeleteSizeConstraintSetRequest(input) + return out, req.Send() +} + +// DeleteSizeConstraintSetWithContext is the same as DeleteSizeConstraintSet with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteSizeConstraintSet 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 *WAFRegional) DeleteSizeConstraintSetWithContext(ctx aws.Context, input *waf.DeleteSizeConstraintSetInput, opts ...request.Option) (*waf.DeleteSizeConstraintSetOutput, error) { + req, out := c.DeleteSizeConstraintSetRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opDeleteSqlInjectionMatchSet = "DeleteSqlInjectionMatchSet" + +// DeleteSqlInjectionMatchSetRequest generates a "aws/request.Request" representing the +// client's request for the DeleteSqlInjectionMatchSet operation. The "output" return +// value can be used to capture response data after the request's "Send" method +// is called. +// +// See DeleteSqlInjectionMatchSet for usage and error information. +// +// Creating a request object using this method should be used when you want to inject +// custom logic into the request's lifecycle using a custom handler, or if you want to +// access properties on the request object before or after sending the request. If +// you just want the service response, call the DeleteSqlInjectionMatchSet method directly +// instead. +// +// Note: You must call the "Send" method on the returned request object in order +// to execute the request. +// +// // Example sending a request using the DeleteSqlInjectionMatchSetRequest method. +// req, resp := client.DeleteSqlInjectionMatchSetRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/waf-regional-2016-11-28/DeleteSqlInjectionMatchSet +func (c *WAFRegional) DeleteSqlInjectionMatchSetRequest(input *waf.DeleteSqlInjectionMatchSetInput) (req *request.Request, output *waf.DeleteSqlInjectionMatchSetOutput) { + op := &request.Operation{ + Name: opDeleteSqlInjectionMatchSet, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &waf.DeleteSqlInjectionMatchSetInput{} + } + + output = &waf.DeleteSqlInjectionMatchSetOutput{} + req = c.newRequest(op, input, output) + return +} + +// DeleteSqlInjectionMatchSet API operation for AWS WAF Regional. +// +// Permanently deletes a SqlInjectionMatchSet. You can't delete a SqlInjectionMatchSet +// if it's still used in any Rules or if it still contains any SqlInjectionMatchTuple +// objects. +// +// If you just want to remove a SqlInjectionMatchSet from a Rule, use UpdateRule. +// +// To permanently delete a SqlInjectionMatchSet from AWS WAF, perform the following +// steps: +// +// Update the SqlInjectionMatchSet to remove filters, if any. For more information, +// see UpdateSqlInjectionMatchSet. +// +// Use GetChangeToken to get the change token that you provide in the ChangeToken +// parameter of a DeleteSqlInjectionMatchSet request. +// +// Submit a DeleteSqlInjectionMatchSet 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. +// +// See the AWS API reference guide for AWS WAF Regional's +// API operation DeleteSqlInjectionMatchSet for usage and error information. +// +// Returned Error Codes: +// * ErrCodeWAFInternalErrorException "WAFInternalErrorException" +// The operation failed because of a system problem, even though the request +// was valid. Retry your request. +// +// * ErrCodeWAFInvalidAccountException "WAFInvalidAccountException" +// The operation failed because you tried to create, update, or delete an object +// by using an invalid account identifier. +// +// * ErrCodeWAFNonexistentItemException "WAFNonexistentItemException" +// The operation failed because the referenced object doesn't exist. +// +// * ErrCodeWAFReferencedItemException "WAFReferencedItemException" +// The operation failed because you tried to delete an object that is still +// in use. For example: +// +// * You tried to delete a ByteMatchSet that is still referenced by a Rule. +// +// * You tried to delete a Rule that is still referenced by a WebACL. +// +// * ErrCodeWAFStaleDataException "WAFStaleDataException" +// The operation failed because you tried to create, update, or delete an object +// by using a change token that has already been used. +// +// * ErrCodeWAFNonEmptyEntityException "WAFNonEmptyEntityException" +// The operation failed because you tried to delete an object that isn't empty. +// For example: +// +// * You tried to delete a WebACL that still contains one or more Rule objects. +// +// * You tried to delete a Rule that still contains one or more ByteMatchSet +// objects or other predicates. +// +// * You tried to delete a ByteMatchSet that contains one or more ByteMatchTuple +// objects. +// +// * You tried to delete an IPSet that references one or more IP addresses. +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/waf-regional-2016-11-28/DeleteSqlInjectionMatchSet +func (c *WAFRegional) DeleteSqlInjectionMatchSet(input *waf.DeleteSqlInjectionMatchSetInput) (*waf.DeleteSqlInjectionMatchSetOutput, error) { + req, out := c.DeleteSqlInjectionMatchSetRequest(input) + return out, req.Send() +} + +// DeleteSqlInjectionMatchSetWithContext is the same as DeleteSqlInjectionMatchSet with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteSqlInjectionMatchSet 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 *WAFRegional) DeleteSqlInjectionMatchSetWithContext(ctx aws.Context, input *waf.DeleteSqlInjectionMatchSetInput, opts ...request.Option) (*waf.DeleteSqlInjectionMatchSetOutput, error) { + req, out := c.DeleteSqlInjectionMatchSetRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opDeleteWebACL = "DeleteWebACL" + +// DeleteWebACLRequest generates a "aws/request.Request" representing the +// client's request for the DeleteWebACL operation. The "output" return +// value can be used to capture response data after the request's "Send" method +// is called. +// +// See DeleteWebACL for usage and error information. +// +// Creating a request object using this method should be used when you want to inject +// custom logic into the request's lifecycle using a custom handler, or if you want to +// access properties on the request object before or after sending the request. If +// you just want the service response, call the DeleteWebACL method directly +// instead. +// +// Note: You must call the "Send" method on the returned request object in order +// to execute the request. +// +// // Example sending a request using the DeleteWebACLRequest method. +// req, resp := client.DeleteWebACLRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/waf-regional-2016-11-28/DeleteWebACL +func (c *WAFRegional) DeleteWebACLRequest(input *waf.DeleteWebACLInput) (req *request.Request, output *waf.DeleteWebACLOutput) { + op := &request.Operation{ + Name: opDeleteWebACL, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &waf.DeleteWebACLInput{} + } + + output = &waf.DeleteWebACLOutput{} + req = c.newRequest(op, input, output) + return +} + +// DeleteWebACL API operation for AWS WAF Regional. +// +// Permanently deletes a WebACL. You can't delete a WebACL if it still contains +// any Rules. +// +// To delete a WebACL, perform the following steps: +// +// Update the WebACL to remove Rules, if any. For more information, see UpdateWebACL. +// +// Use GetChangeToken to get the change token that you provide in the ChangeToken +// parameter of a DeleteWebACL request. +// +// Submit a DeleteWebACL 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. +// +// See the AWS API reference guide for AWS WAF Regional's +// API operation DeleteWebACL for usage and error information. +// +// Returned Error Codes: +// * ErrCodeWAFStaleDataException "WAFStaleDataException" +// The operation failed because you tried to create, update, or delete an object +// by using a change token that has already been used. +// +// * ErrCodeWAFInternalErrorException "WAFInternalErrorException" +// The operation failed because of a system problem, even though the request +// was valid. Retry your request. +// +// * ErrCodeWAFInvalidAccountException "WAFInvalidAccountException" +// The operation failed because you tried to create, update, or delete an object +// by using an invalid account identifier. +// +// * ErrCodeWAFNonexistentItemException "WAFNonexistentItemException" +// The operation failed because the referenced object doesn't exist. +// +// * ErrCodeWAFReferencedItemException "WAFReferencedItemException" +// The operation failed because you tried to delete an object that is still +// in use. For example: +// +// * You tried to delete a ByteMatchSet that is still referenced by a Rule. +// +// * You tried to delete a Rule that is still referenced by a WebACL. +// +// * ErrCodeWAFNonEmptyEntityException "WAFNonEmptyEntityException" +// The operation failed because you tried to delete an object that isn't empty. +// For example: +// +// * You tried to delete a WebACL that still contains one or more Rule objects. +// +// * You tried to delete a Rule that still contains one or more ByteMatchSet +// objects or other predicates. +// +// * You tried to delete a ByteMatchSet that contains one or more ByteMatchTuple +// objects. +// +// * You tried to delete an IPSet that references one or more IP addresses. +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/waf-regional-2016-11-28/DeleteWebACL +func (c *WAFRegional) DeleteWebACL(input *waf.DeleteWebACLInput) (*waf.DeleteWebACLOutput, error) { + req, out := c.DeleteWebACLRequest(input) + return out, req.Send() +} + +// DeleteWebACLWithContext is the same as DeleteWebACL with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteWebACL 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 *WAFRegional) DeleteWebACLWithContext(ctx aws.Context, input *waf.DeleteWebACLInput, opts ...request.Option) (*waf.DeleteWebACLOutput, error) { + req, out := c.DeleteWebACLRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opDeleteXssMatchSet = "DeleteXssMatchSet" + +// DeleteXssMatchSetRequest generates a "aws/request.Request" representing the +// client's request for the DeleteXssMatchSet operation. The "output" return +// value can be used to capture response data after the request's "Send" method +// is called. +// +// See DeleteXssMatchSet for usage and error information. +// +// Creating a request object using this method should be used when you want to inject +// custom logic into the request's lifecycle using a custom handler, or if you want to +// access properties on the request object before or after sending the request. If +// you just want the service response, call the DeleteXssMatchSet method directly +// instead. +// +// Note: You must call the "Send" method on the returned request object in order +// to execute the request. +// +// // Example sending a request using the DeleteXssMatchSetRequest method. +// req, resp := client.DeleteXssMatchSetRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/waf-regional-2016-11-28/DeleteXssMatchSet +func (c *WAFRegional) DeleteXssMatchSetRequest(input *waf.DeleteXssMatchSetInput) (req *request.Request, output *waf.DeleteXssMatchSetOutput) { + op := &request.Operation{ + Name: opDeleteXssMatchSet, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &waf.DeleteXssMatchSetInput{} + } + + output = &waf.DeleteXssMatchSetOutput{} + req = c.newRequest(op, input, output) + return +} + +// DeleteXssMatchSet API operation for AWS WAF Regional. +// +// Permanently deletes an XssMatchSet. You can't delete an XssMatchSet if it's +// still used in any Rules or if it still contains any XssMatchTuple objects. +// +// If you just want to remove an XssMatchSet from a Rule, use UpdateRule. +// +// To permanently delete an XssMatchSet from AWS WAF, perform the following +// steps: +// +// Update the XssMatchSet to remove filters, if any. For more information, see +// UpdateXssMatchSet. +// +// Use GetChangeToken to get the change token that you provide in the ChangeToken +// parameter of a DeleteXssMatchSet request. +// +// Submit a DeleteXssMatchSet 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. +// +// See the AWS API reference guide for AWS WAF Regional's +// API operation DeleteXssMatchSet for usage and error information. +// +// Returned Error Codes: +// * ErrCodeWAFInternalErrorException "WAFInternalErrorException" +// The operation failed because of a system problem, even though the request +// was valid. Retry your request. +// +// * ErrCodeWAFInvalidAccountException "WAFInvalidAccountException" +// The operation failed because you tried to create, update, or delete an object +// by using an invalid account identifier. +// +// * ErrCodeWAFNonexistentItemException "WAFNonexistentItemException" +// The operation failed because the referenced object doesn't exist. +// +// * ErrCodeWAFReferencedItemException "WAFReferencedItemException" +// The operation failed because you tried to delete an object that is still +// in use. For example: +// +// * You tried to delete a ByteMatchSet that is still referenced by a Rule. +// +// * You tried to delete a Rule that is still referenced by a WebACL. +// +// * ErrCodeWAFStaleDataException "WAFStaleDataException" +// The operation failed because you tried to create, update, or delete an object +// by using a change token that has already been used. +// +// * ErrCodeWAFNonEmptyEntityException "WAFNonEmptyEntityException" +// The operation failed because you tried to delete an object that isn't empty. +// For example: +// +// * You tried to delete a WebACL that still contains one or more Rule objects. +// +// * You tried to delete a Rule that still contains one or more ByteMatchSet +// objects or other predicates. +// +// * You tried to delete a ByteMatchSet that contains one or more ByteMatchTuple +// objects. +// +// * You tried to delete an IPSet that references one or more IP addresses. +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/waf-regional-2016-11-28/DeleteXssMatchSet +func (c *WAFRegional) DeleteXssMatchSet(input *waf.DeleteXssMatchSetInput) (*waf.DeleteXssMatchSetOutput, error) { + req, out := c.DeleteXssMatchSetRequest(input) + return out, req.Send() +} + +// DeleteXssMatchSetWithContext is the same as DeleteXssMatchSet with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteXssMatchSet 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 *WAFRegional) DeleteXssMatchSetWithContext(ctx aws.Context, input *waf.DeleteXssMatchSetInput, opts ...request.Option) (*waf.DeleteXssMatchSetOutput, error) { + req, out := c.DeleteXssMatchSetRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opDisassociateWebACL = "DisassociateWebACL" + +// DisassociateWebACLRequest generates a "aws/request.Request" representing the +// client's request for the DisassociateWebACL operation. The "output" return +// value can be used to capture response data after the request's "Send" method +// is called. +// +// See DisassociateWebACL for usage and error information. +// +// Creating a request object using this method should be used when you want to inject +// custom logic into the request's lifecycle using a custom handler, or if you want to +// access properties on the request object before or after sending the request. If +// you just want the service response, call the DisassociateWebACL method directly +// instead. +// +// Note: You must call the "Send" method on the returned request object in order +// to execute the request. +// +// // Example sending a request using the DisassociateWebACLRequest method. +// req, resp := client.DisassociateWebACLRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/waf-regional-2016-11-28/DisassociateWebACL +func (c *WAFRegional) DisassociateWebACLRequest(input *DisassociateWebACLInput) (req *request.Request, output *DisassociateWebACLOutput) { + op := &request.Operation{ + Name: opDisassociateWebACL, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &DisassociateWebACLInput{} + } + + output = &DisassociateWebACLOutput{} + req = c.newRequest(op, input, output) + return +} + +// DisassociateWebACL API operation for AWS WAF Regional. +// +// Removes a web ACL from the specified resource. +// +// 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 WAF Regional's +// API operation DisassociateWebACL for usage and error information. +// +// Returned Error Codes: +// * ErrCodeWAFInternalErrorException "WAFInternalErrorException" +// The operation failed because of a system problem, even though the request +// was valid. Retry your request. +// +// * ErrCodeWAFInvalidAccountException "WAFInvalidAccountException" +// The operation failed because you tried to create, update, or delete an object +// by using an invalid account identifier. +// +// * ErrCodeWAFInvalidParameterException "WAFInvalidParameterException" +// The operation failed because AWS WAF didn't recognize a parameter in the +// request. For example: +// +// * You specified an invalid parameter name. +// +// * You specified an invalid value. +// +// * You tried to update an object (ByteMatchSet, IPSet, Rule, or WebACL) +// using an action other than INSERT or DELETE. +// +// * You tried to create a WebACL with a DefaultActionType other than ALLOW, +// BLOCK, or COUNT. +// +// * You tried to update a WebACL with a WafActionType other than ALLOW, +// BLOCK, or COUNT. +// +// * You tried to update a ByteMatchSet with a FieldToMatchType other than +// HEADER, QUERY_STRING, or URI. +// +// * You tried to update a ByteMatchSet with a Field of HEADER but no value +// for Data. +// +// * Your request references an ARN that is malformed, or corresponds to +// a resource with which a web ACL cannot be associated. +// +// * ErrCodeWAFNonexistentItemException "WAFNonexistentItemException" +// The operation failed because the referenced object doesn't exist. +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/waf-regional-2016-11-28/DisassociateWebACL +func (c *WAFRegional) DisassociateWebACL(input *DisassociateWebACLInput) (*DisassociateWebACLOutput, error) { + req, out := c.DisassociateWebACLRequest(input) + return out, req.Send() +} + +// DisassociateWebACLWithContext is the same as DisassociateWebACL with the addition of +// the ability to pass a context and additional request options. +// +// See DisassociateWebACL 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 *WAFRegional) DisassociateWebACLWithContext(ctx aws.Context, input *DisassociateWebACLInput, opts ...request.Option) (*DisassociateWebACLOutput, error) { + req, out := c.DisassociateWebACLRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opGetByteMatchSet = "GetByteMatchSet" + +// GetByteMatchSetRequest generates a "aws/request.Request" representing the +// client's request for the GetByteMatchSet operation. The "output" return +// value can be used to capture response data after the request's "Send" method +// is called. +// +// See GetByteMatchSet for usage and error information. +// +// Creating a request object using this method should be used when you want to inject +// custom logic into the request's lifecycle using a custom handler, or if you want to +// access properties on the request object before or after sending the request. If +// you just want the service response, call the GetByteMatchSet method directly +// instead. +// +// Note: You must call the "Send" method on the returned request object in order +// to execute the request. +// +// // Example sending a request using the GetByteMatchSetRequest method. +// req, resp := client.GetByteMatchSetRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/waf-regional-2016-11-28/GetByteMatchSet +func (c *WAFRegional) GetByteMatchSetRequest(input *waf.GetByteMatchSetInput) (req *request.Request, output *waf.GetByteMatchSetOutput) { + op := &request.Operation{ + Name: opGetByteMatchSet, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &waf.GetByteMatchSetInput{} + } + + output = &waf.GetByteMatchSetOutput{} + req = c.newRequest(op, input, output) + return +} + +// GetByteMatchSet API operation for AWS WAF Regional. +// +// Returns the ByteMatchSet specified by ByteMatchSetId. +// +// 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 WAF Regional's +// API operation GetByteMatchSet for usage and error information. +// +// Returned Error Codes: +// * ErrCodeWAFInternalErrorException "WAFInternalErrorException" +// The operation failed because of a system problem, even though the request +// was valid. Retry your request. +// +// * ErrCodeWAFInvalidAccountException "WAFInvalidAccountException" +// The operation failed because you tried to create, update, or delete an object +// by using an invalid account identifier. +// +// * ErrCodeWAFNonexistentItemException "WAFNonexistentItemException" +// The operation failed because the referenced object doesn't exist. +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/waf-regional-2016-11-28/GetByteMatchSet +func (c *WAFRegional) GetByteMatchSet(input *waf.GetByteMatchSetInput) (*waf.GetByteMatchSetOutput, error) { + req, out := c.GetByteMatchSetRequest(input) + return out, req.Send() +} + +// GetByteMatchSetWithContext is the same as GetByteMatchSet with the addition of +// the ability to pass a context and additional request options. +// +// See GetByteMatchSet 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 *WAFRegional) GetByteMatchSetWithContext(ctx aws.Context, input *waf.GetByteMatchSetInput, opts ...request.Option) (*waf.GetByteMatchSetOutput, error) { + req, out := c.GetByteMatchSetRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opGetChangeToken = "GetChangeToken" + +// GetChangeTokenRequest generates a "aws/request.Request" representing the +// client's request for the GetChangeToken operation. The "output" return +// value can be used to capture response data after the request's "Send" method +// is called. +// +// See GetChangeToken for usage and error information. +// +// Creating a request object using this method should be used when you want to inject +// custom logic into the request's lifecycle using a custom handler, or if you want to +// access properties on the request object before or after sending the request. If +// you just want the service response, call the GetChangeToken method directly +// instead. +// +// Note: You must call the "Send" method on the returned request object in order +// to execute the request. +// +// // Example sending a request using the GetChangeTokenRequest method. +// req, resp := client.GetChangeTokenRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/waf-regional-2016-11-28/GetChangeToken +func (c *WAFRegional) GetChangeTokenRequest(input *waf.GetChangeTokenInput) (req *request.Request, output *waf.GetChangeTokenOutput) { + op := &request.Operation{ + Name: opGetChangeToken, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &waf.GetChangeTokenInput{} + } + + output = &waf.GetChangeTokenOutput{} + req = c.newRequest(op, input, output) + return +} + +// GetChangeToken API operation for AWS WAF Regional. +// +// When you want to create, update, or delete AWS WAF objects, get a change +// token and include the change token in the create, update, or delete request. +// Change tokens ensure that your application doesn't submit conflicting requests +// to AWS WAF. +// +// Each create, update, or delete request must use a unique change token. If +// your application submits a GetChangeToken request and then submits a second +// GetChangeToken request before submitting a create, update, or delete request, +// the second GetChangeToken request returns the same value as the first GetChangeToken +// request. +// +// When you use a change token in a create, update, or delete request, the status +// of the change token changes to PENDING, which indicates that AWS WAF is propagating +// the change to all AWS WAF servers. Use GetChangeTokenStatus to determine +// the status of your change token. +// +// 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 WAF Regional's +// API operation GetChangeToken for usage and error information. +// +// Returned Error Codes: +// * ErrCodeWAFInternalErrorException "WAFInternalErrorException" +// The operation failed because of a system problem, even though the request +// was valid. Retry your request. +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/waf-regional-2016-11-28/GetChangeToken +func (c *WAFRegional) GetChangeToken(input *waf.GetChangeTokenInput) (*waf.GetChangeTokenOutput, error) { + req, out := c.GetChangeTokenRequest(input) + return out, req.Send() +} + +// GetChangeTokenWithContext is the same as GetChangeToken with the addition of +// the ability to pass a context and additional request options. +// +// See GetChangeToken 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 *WAFRegional) GetChangeTokenWithContext(ctx aws.Context, input *waf.GetChangeTokenInput, opts ...request.Option) (*waf.GetChangeTokenOutput, error) { + req, out := c.GetChangeTokenRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opGetChangeTokenStatus = "GetChangeTokenStatus" + +// GetChangeTokenStatusRequest generates a "aws/request.Request" representing the +// client's request for the GetChangeTokenStatus operation. The "output" return +// value can be used to capture response data after the request's "Send" method +// is called. +// +// See GetChangeTokenStatus for usage and error information. +// +// Creating a request object using this method should be used when you want to inject +// custom logic into the request's lifecycle using a custom handler, or if you want to +// access properties on the request object before or after sending the request. If +// you just want the service response, call the GetChangeTokenStatus method directly +// instead. +// +// Note: You must call the "Send" method on the returned request object in order +// to execute the request. +// +// // Example sending a request using the GetChangeTokenStatusRequest method. +// req, resp := client.GetChangeTokenStatusRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/waf-regional-2016-11-28/GetChangeTokenStatus +func (c *WAFRegional) GetChangeTokenStatusRequest(input *waf.GetChangeTokenStatusInput) (req *request.Request, output *waf.GetChangeTokenStatusOutput) { + op := &request.Operation{ + Name: opGetChangeTokenStatus, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &waf.GetChangeTokenStatusInput{} + } + + output = &waf.GetChangeTokenStatusOutput{} + req = c.newRequest(op, input, output) + return +} + +// GetChangeTokenStatus API operation for AWS WAF Regional. +// +// Returns the status of a ChangeToken that you got by calling GetChangeToken. +// ChangeTokenStatus is one of the following values: +// +// * PROVISIONED: You requested the change token by calling GetChangeToken, +// but you haven't used it yet in a call to create, update, or delete an +// AWS WAF object. +// +// * PENDING: AWS WAF is propagating the create, update, or delete request +// to all AWS WAF servers. +// +// * IN_SYNC: Propagation is complete. +// +// 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 WAF Regional's +// API operation GetChangeTokenStatus for usage and error information. +// +// Returned Error Codes: +// * ErrCodeWAFNonexistentItemException "WAFNonexistentItemException" +// The operation failed because the referenced object doesn't exist. +// +// * ErrCodeWAFInternalErrorException "WAFInternalErrorException" +// The operation failed because of a system problem, even though the request +// was valid. Retry your request. +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/waf-regional-2016-11-28/GetChangeTokenStatus +func (c *WAFRegional) GetChangeTokenStatus(input *waf.GetChangeTokenStatusInput) (*waf.GetChangeTokenStatusOutput, error) { + req, out := c.GetChangeTokenStatusRequest(input) + return out, req.Send() +} + +// GetChangeTokenStatusWithContext is the same as GetChangeTokenStatus with the addition of +// the ability to pass a context and additional request options. +// +// See GetChangeTokenStatus 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 *WAFRegional) GetChangeTokenStatusWithContext(ctx aws.Context, input *waf.GetChangeTokenStatusInput, opts ...request.Option) (*waf.GetChangeTokenStatusOutput, error) { + req, out := c.GetChangeTokenStatusRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opGetIPSet = "GetIPSet" + +// GetIPSetRequest generates a "aws/request.Request" representing the +// client's request for the GetIPSet operation. The "output" return +// value can be used to capture response data after the request's "Send" method +// is called. +// +// See GetIPSet for usage and error information. +// +// Creating a request object using this method should be used when you want to inject +// custom logic into the request's lifecycle using a custom handler, or if you want to +// access properties on the request object before or after sending the request. If +// you just want the service response, call the GetIPSet method directly +// instead. +// +// Note: You must call the "Send" method on the returned request object in order +// to execute the request. +// +// // Example sending a request using the GetIPSetRequest method. +// req, resp := client.GetIPSetRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/waf-regional-2016-11-28/GetIPSet +func (c *WAFRegional) GetIPSetRequest(input *waf.GetIPSetInput) (req *request.Request, output *waf.GetIPSetOutput) { + op := &request.Operation{ + Name: opGetIPSet, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &waf.GetIPSetInput{} + } + + output = &waf.GetIPSetOutput{} + req = c.newRequest(op, input, output) + return +} + +// GetIPSet API operation for AWS WAF Regional. +// +// Returns the IPSet that is specified by IPSetId. +// +// 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 WAF Regional's +// API operation GetIPSet for usage and error information. +// +// Returned Error Codes: +// * ErrCodeWAFInternalErrorException "WAFInternalErrorException" +// The operation failed because of a system problem, even though the request +// was valid. Retry your request. +// +// * ErrCodeWAFInvalidAccountException "WAFInvalidAccountException" +// The operation failed because you tried to create, update, or delete an object +// by using an invalid account identifier. +// +// * ErrCodeWAFNonexistentItemException "WAFNonexistentItemException" +// The operation failed because the referenced object doesn't exist. +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/waf-regional-2016-11-28/GetIPSet +func (c *WAFRegional) GetIPSet(input *waf.GetIPSetInput) (*waf.GetIPSetOutput, error) { + req, out := c.GetIPSetRequest(input) + return out, req.Send() +} + +// GetIPSetWithContext is the same as GetIPSet with the addition of +// the ability to pass a context and additional request options. +// +// See GetIPSet 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 *WAFRegional) GetIPSetWithContext(ctx aws.Context, input *waf.GetIPSetInput, opts ...request.Option) (*waf.GetIPSetOutput, error) { + req, out := c.GetIPSetRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opGetRule = "GetRule" + +// GetRuleRequest generates a "aws/request.Request" representing the +// client's request for the GetRule operation. The "output" return +// value can be used to capture response data after the request's "Send" method +// is called. +// +// See GetRule for usage and error information. +// +// Creating a request object using this method should be used when you want to inject +// custom logic into the request's lifecycle using a custom handler, or if you want to +// access properties on the request object before or after sending the request. If +// you just want the service response, call the GetRule method directly +// instead. +// +// Note: You must call the "Send" method on the returned request object in order +// to execute the request. +// +// // Example sending a request using the GetRuleRequest method. +// req, resp := client.GetRuleRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/waf-regional-2016-11-28/GetRule +func (c *WAFRegional) GetRuleRequest(input *waf.GetRuleInput) (req *request.Request, output *waf.GetRuleOutput) { + op := &request.Operation{ + Name: opGetRule, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &waf.GetRuleInput{} + } + + output = &waf.GetRuleOutput{} + req = c.newRequest(op, input, output) + return +} + +// GetRule API operation for AWS WAF Regional. +// +// Returns the Rule that is specified by the RuleId that you included in the +// GetRule 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. +// +// See the AWS API reference guide for AWS WAF Regional's +// API operation GetRule for usage and error information. +// +// Returned Error Codes: +// * ErrCodeWAFInternalErrorException "WAFInternalErrorException" +// The operation failed because of a system problem, even though the request +// was valid. Retry your request. +// +// * ErrCodeWAFInvalidAccountException "WAFInvalidAccountException" +// The operation failed because you tried to create, update, or delete an object +// by using an invalid account identifier. +// +// * ErrCodeWAFNonexistentItemException "WAFNonexistentItemException" +// The operation failed because the referenced object doesn't exist. +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/waf-regional-2016-11-28/GetRule +func (c *WAFRegional) GetRule(input *waf.GetRuleInput) (*waf.GetRuleOutput, error) { + req, out := c.GetRuleRequest(input) + return out, req.Send() +} + +// GetRuleWithContext is the same as GetRule with the addition of +// the ability to pass a context and additional request options. +// +// See GetRule 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 *WAFRegional) GetRuleWithContext(ctx aws.Context, input *waf.GetRuleInput, opts ...request.Option) (*waf.GetRuleOutput, error) { + req, out := c.GetRuleRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opGetSampledRequests = "GetSampledRequests" + +// GetSampledRequestsRequest generates a "aws/request.Request" representing the +// client's request for the GetSampledRequests operation. The "output" return +// value can be used to capture response data after the request's "Send" method +// is called. +// +// See GetSampledRequests for usage and error information. +// +// Creating a request object using this method should be used when you want to inject +// custom logic into the request's lifecycle using a custom handler, or if you want to +// access properties on the request object before or after sending the request. If +// you just want the service response, call the GetSampledRequests method directly +// instead. +// +// Note: You must call the "Send" method on the returned request object in order +// to execute the request. +// +// // Example sending a request using the GetSampledRequestsRequest method. +// req, resp := client.GetSampledRequestsRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/waf-regional-2016-11-28/GetSampledRequests +func (c *WAFRegional) GetSampledRequestsRequest(input *waf.GetSampledRequestsInput) (req *request.Request, output *waf.GetSampledRequestsOutput) { + op := &request.Operation{ + Name: opGetSampledRequests, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &waf.GetSampledRequestsInput{} + } + + output = &waf.GetSampledRequestsOutput{} + req = c.newRequest(op, input, output) + return +} + +// GetSampledRequests API operation for AWS WAF Regional. +// +// Gets detailed information about a specified number of requests--a sample--that +// AWS WAF randomly selects from among the first 5,000 requests that your AWS +// resource received during a time range that you choose. You can specify a +// sample size of up to 500 requests, and you can specify any time range in +// the previous three hours. +// +// GetSampledRequests returns a time range, which is usually the time range +// that you specified. However, if your resource (such as a CloudFront distribution) +// received 5,000 requests before the specified time range elapsed, GetSampledRequests +// returns an updated time range. This new time range indicates the actual period +// during which AWS WAF selected the requests in the sample. +// +// 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 WAF Regional's +// API operation GetSampledRequests for usage and error information. +// +// Returned Error Codes: +// * ErrCodeWAFNonexistentItemException "WAFNonexistentItemException" +// The operation failed because the referenced object doesn't exist. +// +// * ErrCodeWAFInternalErrorException "WAFInternalErrorException" +// The operation failed because of a system problem, even though the request +// was valid. Retry your request. +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/waf-regional-2016-11-28/GetSampledRequests +func (c *WAFRegional) GetSampledRequests(input *waf.GetSampledRequestsInput) (*waf.GetSampledRequestsOutput, error) { + req, out := c.GetSampledRequestsRequest(input) + return out, req.Send() +} + +// GetSampledRequestsWithContext is the same as GetSampledRequests with the addition of +// the ability to pass a context and additional request options. +// +// See GetSampledRequests 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 *WAFRegional) GetSampledRequestsWithContext(ctx aws.Context, input *waf.GetSampledRequestsInput, opts ...request.Option) (*waf.GetSampledRequestsOutput, error) { + req, out := c.GetSampledRequestsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opGetSizeConstraintSet = "GetSizeConstraintSet" + +// GetSizeConstraintSetRequest generates a "aws/request.Request" representing the +// client's request for the GetSizeConstraintSet operation. The "output" return +// value can be used to capture response data after the request's "Send" method +// is called. +// +// See GetSizeConstraintSet for usage and error information. +// +// Creating a request object using this method should be used when you want to inject +// custom logic into the request's lifecycle using a custom handler, or if you want to +// access properties on the request object before or after sending the request. If +// you just want the service response, call the GetSizeConstraintSet method directly +// instead. +// +// Note: You must call the "Send" method on the returned request object in order +// to execute the request. +// +// // Example sending a request using the GetSizeConstraintSetRequest method. +// req, resp := client.GetSizeConstraintSetRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/waf-regional-2016-11-28/GetSizeConstraintSet +func (c *WAFRegional) GetSizeConstraintSetRequest(input *waf.GetSizeConstraintSetInput) (req *request.Request, output *waf.GetSizeConstraintSetOutput) { + op := &request.Operation{ + Name: opGetSizeConstraintSet, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &waf.GetSizeConstraintSetInput{} + } + + output = &waf.GetSizeConstraintSetOutput{} + req = c.newRequest(op, input, output) + return +} + +// GetSizeConstraintSet API operation for AWS WAF Regional. +// +// Returns the SizeConstraintSet specified by SizeConstraintSetId. +// +// 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 WAF Regional's +// API operation GetSizeConstraintSet for usage and error information. +// +// Returned Error Codes: +// * ErrCodeWAFInternalErrorException "WAFInternalErrorException" +// The operation failed because of a system problem, even though the request +// was valid. Retry your request. +// +// * ErrCodeWAFInvalidAccountException "WAFInvalidAccountException" +// The operation failed because you tried to create, update, or delete an object +// by using an invalid account identifier. +// +// * ErrCodeWAFNonexistentItemException "WAFNonexistentItemException" +// The operation failed because the referenced object doesn't exist. +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/waf-regional-2016-11-28/GetSizeConstraintSet +func (c *WAFRegional) GetSizeConstraintSet(input *waf.GetSizeConstraintSetInput) (*waf.GetSizeConstraintSetOutput, error) { + req, out := c.GetSizeConstraintSetRequest(input) + return out, req.Send() +} + +// GetSizeConstraintSetWithContext is the same as GetSizeConstraintSet with the addition of +// the ability to pass a context and additional request options. +// +// See GetSizeConstraintSet 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 *WAFRegional) GetSizeConstraintSetWithContext(ctx aws.Context, input *waf.GetSizeConstraintSetInput, opts ...request.Option) (*waf.GetSizeConstraintSetOutput, error) { + req, out := c.GetSizeConstraintSetRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opGetSqlInjectionMatchSet = "GetSqlInjectionMatchSet" + +// GetSqlInjectionMatchSetRequest generates a "aws/request.Request" representing the +// client's request for the GetSqlInjectionMatchSet operation. The "output" return +// value can be used to capture response data after the request's "Send" method +// is called. +// +// See GetSqlInjectionMatchSet for usage and error information. +// +// Creating a request object using this method should be used when you want to inject +// custom logic into the request's lifecycle using a custom handler, or if you want to +// access properties on the request object before or after sending the request. If +// you just want the service response, call the GetSqlInjectionMatchSet method directly +// instead. +// +// Note: You must call the "Send" method on the returned request object in order +// to execute the request. +// +// // Example sending a request using the GetSqlInjectionMatchSetRequest method. +// req, resp := client.GetSqlInjectionMatchSetRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/waf-regional-2016-11-28/GetSqlInjectionMatchSet +func (c *WAFRegional) GetSqlInjectionMatchSetRequest(input *waf.GetSqlInjectionMatchSetInput) (req *request.Request, output *waf.GetSqlInjectionMatchSetOutput) { + op := &request.Operation{ + Name: opGetSqlInjectionMatchSet, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &waf.GetSqlInjectionMatchSetInput{} + } + + output = &waf.GetSqlInjectionMatchSetOutput{} + req = c.newRequest(op, input, output) + return +} + +// GetSqlInjectionMatchSet API operation for AWS WAF Regional. +// +// Returns the SqlInjectionMatchSet that is specified by SqlInjectionMatchSetId. +// +// 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 WAF Regional's +// API operation GetSqlInjectionMatchSet for usage and error information. +// +// Returned Error Codes: +// * ErrCodeWAFInternalErrorException "WAFInternalErrorException" +// The operation failed because of a system problem, even though the request +// was valid. Retry your request. +// +// * ErrCodeWAFInvalidAccountException "WAFInvalidAccountException" +// The operation failed because you tried to create, update, or delete an object +// by using an invalid account identifier. +// +// * ErrCodeWAFNonexistentItemException "WAFNonexistentItemException" +// The operation failed because the referenced object doesn't exist. +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/waf-regional-2016-11-28/GetSqlInjectionMatchSet +func (c *WAFRegional) GetSqlInjectionMatchSet(input *waf.GetSqlInjectionMatchSetInput) (*waf.GetSqlInjectionMatchSetOutput, error) { + req, out := c.GetSqlInjectionMatchSetRequest(input) + return out, req.Send() +} + +// GetSqlInjectionMatchSetWithContext is the same as GetSqlInjectionMatchSet with the addition of +// the ability to pass a context and additional request options. +// +// See GetSqlInjectionMatchSet 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 *WAFRegional) GetSqlInjectionMatchSetWithContext(ctx aws.Context, input *waf.GetSqlInjectionMatchSetInput, opts ...request.Option) (*waf.GetSqlInjectionMatchSetOutput, error) { + req, out := c.GetSqlInjectionMatchSetRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opGetWebACL = "GetWebACL" + +// GetWebACLRequest generates a "aws/request.Request" representing the +// client's request for the GetWebACL operation. The "output" return +// value can be used to capture response data after the request's "Send" method +// is called. +// +// See GetWebACL for usage and error information. +// +// Creating a request object using this method should be used when you want to inject +// custom logic into the request's lifecycle using a custom handler, or if you want to +// access properties on the request object before or after sending the request. If +// you just want the service response, call the GetWebACL method directly +// instead. +// +// Note: You must call the "Send" method on the returned request object in order +// to execute the request. +// +// // Example sending a request using the GetWebACLRequest method. +// req, resp := client.GetWebACLRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/waf-regional-2016-11-28/GetWebACL +func (c *WAFRegional) GetWebACLRequest(input *waf.GetWebACLInput) (req *request.Request, output *waf.GetWebACLOutput) { + op := &request.Operation{ + Name: opGetWebACL, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &waf.GetWebACLInput{} + } + + output = &waf.GetWebACLOutput{} + req = c.newRequest(op, input, output) + return +} + +// GetWebACL API operation for AWS WAF Regional. +// +// Returns the WebACL that is specified by WebACLId. +// +// 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 WAF Regional's +// API operation GetWebACL for usage and error information. +// +// Returned Error Codes: +// * ErrCodeWAFInternalErrorException "WAFInternalErrorException" +// The operation failed because of a system problem, even though the request +// was valid. Retry your request. +// +// * ErrCodeWAFInvalidAccountException "WAFInvalidAccountException" +// The operation failed because you tried to create, update, or delete an object +// by using an invalid account identifier. +// +// * ErrCodeWAFNonexistentItemException "WAFNonexistentItemException" +// The operation failed because the referenced object doesn't exist. +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/waf-regional-2016-11-28/GetWebACL +func (c *WAFRegional) GetWebACL(input *waf.GetWebACLInput) (*waf.GetWebACLOutput, error) { + req, out := c.GetWebACLRequest(input) + return out, req.Send() +} + +// GetWebACLWithContext is the same as GetWebACL with the addition of +// the ability to pass a context and additional request options. +// +// See GetWebACL 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 *WAFRegional) GetWebACLWithContext(ctx aws.Context, input *waf.GetWebACLInput, opts ...request.Option) (*waf.GetWebACLOutput, error) { + req, out := c.GetWebACLRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opGetWebACLForResource = "GetWebACLForResource" + +// GetWebACLForResourceRequest generates a "aws/request.Request" representing the +// client's request for the GetWebACLForResource operation. The "output" return +// value can be used to capture response data after the request's "Send" method +// is called. +// +// See GetWebACLForResource for usage and error information. +// +// Creating a request object using this method should be used when you want to inject +// custom logic into the request's lifecycle using a custom handler, or if you want to +// access properties on the request object before or after sending the request. If +// you just want the service response, call the GetWebACLForResource method directly +// instead. +// +// Note: You must call the "Send" method on the returned request object in order +// to execute the request. +// +// // Example sending a request using the GetWebACLForResourceRequest method. +// req, resp := client.GetWebACLForResourceRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/waf-regional-2016-11-28/GetWebACLForResource +func (c *WAFRegional) GetWebACLForResourceRequest(input *GetWebACLForResourceInput) (req *request.Request, output *GetWebACLForResourceOutput) { + op := &request.Operation{ + Name: opGetWebACLForResource, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &GetWebACLForResourceInput{} + } + + output = &GetWebACLForResourceOutput{} + req = c.newRequest(op, input, output) + return +} + +// GetWebACLForResource API operation for AWS WAF Regional. +// +// Returns the web ACL for the specified resource. +// +// 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 WAF Regional's +// API operation GetWebACLForResource for usage and error information. +// +// Returned Error Codes: +// * ErrCodeWAFInternalErrorException "WAFInternalErrorException" +// The operation failed because of a system problem, even though the request +// was valid. Retry your request. +// +// * ErrCodeWAFInvalidAccountException "WAFInvalidAccountException" +// The operation failed because you tried to create, update, or delete an object +// by using an invalid account identifier. +// +// * ErrCodeWAFNonexistentItemException "WAFNonexistentItemException" +// The operation failed because the referenced object doesn't exist. +// +// * ErrCodeWAFInvalidParameterException "WAFInvalidParameterException" +// The operation failed because AWS WAF didn't recognize a parameter in the +// request. For example: +// +// * You specified an invalid parameter name. +// +// * You specified an invalid value. +// +// * You tried to update an object (ByteMatchSet, IPSet, Rule, or WebACL) +// using an action other than INSERT or DELETE. +// +// * You tried to create a WebACL with a DefaultActionType other than ALLOW, +// BLOCK, or COUNT. +// +// * You tried to update a WebACL with a WafActionType other than ALLOW, +// BLOCK, or COUNT. +// +// * You tried to update a ByteMatchSet with a FieldToMatchType other than +// HEADER, QUERY_STRING, or URI. +// +// * You tried to update a ByteMatchSet with a Field of HEADER but no value +// for Data. +// +// * Your request references an ARN that is malformed, or corresponds to +// a resource with which a web ACL cannot be associated. +// +// * ErrCodeWAFUnavailableEntityException "WAFUnavailableEntityException" +// The operation failed because the entity referenced is temporarily unavailable. +// Retry your request. +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/waf-regional-2016-11-28/GetWebACLForResource +func (c *WAFRegional) GetWebACLForResource(input *GetWebACLForResourceInput) (*GetWebACLForResourceOutput, error) { + req, out := c.GetWebACLForResourceRequest(input) + return out, req.Send() +} + +// GetWebACLForResourceWithContext is the same as GetWebACLForResource with the addition of +// the ability to pass a context and additional request options. +// +// See GetWebACLForResource 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 *WAFRegional) GetWebACLForResourceWithContext(ctx aws.Context, input *GetWebACLForResourceInput, opts ...request.Option) (*GetWebACLForResourceOutput, error) { + req, out := c.GetWebACLForResourceRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opGetXssMatchSet = "GetXssMatchSet" + +// GetXssMatchSetRequest generates a "aws/request.Request" representing the +// client's request for the GetXssMatchSet operation. The "output" return +// value can be used to capture response data after the request's "Send" method +// is called. +// +// See GetXssMatchSet for usage and error information. +// +// Creating a request object using this method should be used when you want to inject +// custom logic into the request's lifecycle using a custom handler, or if you want to +// access properties on the request object before or after sending the request. If +// you just want the service response, call the GetXssMatchSet method directly +// instead. +// +// Note: You must call the "Send" method on the returned request object in order +// to execute the request. +// +// // Example sending a request using the GetXssMatchSetRequest method. +// req, resp := client.GetXssMatchSetRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/waf-regional-2016-11-28/GetXssMatchSet +func (c *WAFRegional) GetXssMatchSetRequest(input *waf.GetXssMatchSetInput) (req *request.Request, output *waf.GetXssMatchSetOutput) { + op := &request.Operation{ + Name: opGetXssMatchSet, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &waf.GetXssMatchSetInput{} + } + + output = &waf.GetXssMatchSetOutput{} + req = c.newRequest(op, input, output) + return +} + +// GetXssMatchSet API operation for AWS WAF Regional. +// +// Returns the XssMatchSet that is specified by XssMatchSetId. +// +// 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 WAF Regional's +// API operation GetXssMatchSet for usage and error information. +// +// Returned Error Codes: +// * ErrCodeWAFInternalErrorException "WAFInternalErrorException" +// The operation failed because of a system problem, even though the request +// was valid. Retry your request. +// +// * ErrCodeWAFInvalidAccountException "WAFInvalidAccountException" +// The operation failed because you tried to create, update, or delete an object +// by using an invalid account identifier. +// +// * ErrCodeWAFNonexistentItemException "WAFNonexistentItemException" +// The operation failed because the referenced object doesn't exist. +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/waf-regional-2016-11-28/GetXssMatchSet +func (c *WAFRegional) GetXssMatchSet(input *waf.GetXssMatchSetInput) (*waf.GetXssMatchSetOutput, error) { + req, out := c.GetXssMatchSetRequest(input) + return out, req.Send() +} + +// GetXssMatchSetWithContext is the same as GetXssMatchSet with the addition of +// the ability to pass a context and additional request options. +// +// See GetXssMatchSet 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 *WAFRegional) GetXssMatchSetWithContext(ctx aws.Context, input *waf.GetXssMatchSetInput, opts ...request.Option) (*waf.GetXssMatchSetOutput, error) { + req, out := c.GetXssMatchSetRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opListByteMatchSets = "ListByteMatchSets" + +// ListByteMatchSetsRequest generates a "aws/request.Request" representing the +// client's request for the ListByteMatchSets operation. The "output" return +// value can be used to capture response data after the request's "Send" method +// is called. +// +// See ListByteMatchSets for usage and error information. +// +// Creating a request object using this method should be used when you want to inject +// custom logic into the request's lifecycle using a custom handler, or if you want to +// access properties on the request object before or after sending the request. If +// you just want the service response, call the ListByteMatchSets method directly +// instead. +// +// Note: You must call the "Send" method on the returned request object in order +// to execute the request. +// +// // Example sending a request using the ListByteMatchSetsRequest method. +// req, resp := client.ListByteMatchSetsRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/waf-regional-2016-11-28/ListByteMatchSets +func (c *WAFRegional) ListByteMatchSetsRequest(input *waf.ListByteMatchSetsInput) (req *request.Request, output *waf.ListByteMatchSetsOutput) { + op := &request.Operation{ + Name: opListByteMatchSets, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &waf.ListByteMatchSetsInput{} + } + + output = &waf.ListByteMatchSetsOutput{} + req = c.newRequest(op, input, output) + return +} + +// ListByteMatchSets API operation for AWS WAF Regional. +// +// Returns an array of ByteMatchSetSummary objects. +// +// 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 WAF Regional's +// API operation ListByteMatchSets for usage and error information. +// +// Returned Error Codes: +// * ErrCodeWAFInternalErrorException "WAFInternalErrorException" +// The operation failed because of a system problem, even though the request +// was valid. Retry your request. +// +// * ErrCodeWAFInvalidAccountException "WAFInvalidAccountException" +// The operation failed because you tried to create, update, or delete an object +// by using an invalid account identifier. +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/waf-regional-2016-11-28/ListByteMatchSets +func (c *WAFRegional) ListByteMatchSets(input *waf.ListByteMatchSetsInput) (*waf.ListByteMatchSetsOutput, error) { + req, out := c.ListByteMatchSetsRequest(input) + return out, req.Send() +} + +// ListByteMatchSetsWithContext is the same as ListByteMatchSets with the addition of +// the ability to pass a context and additional request options. +// +// See ListByteMatchSets 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 *WAFRegional) ListByteMatchSetsWithContext(ctx aws.Context, input *waf.ListByteMatchSetsInput, opts ...request.Option) (*waf.ListByteMatchSetsOutput, error) { + req, out := c.ListByteMatchSetsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opListIPSets = "ListIPSets" + +// ListIPSetsRequest generates a "aws/request.Request" representing the +// client's request for the ListIPSets operation. The "output" return +// value can be used to capture response data after the request's "Send" method +// is called. +// +// See ListIPSets for usage and error information. +// +// Creating a request object using this method should be used when you want to inject +// custom logic into the request's lifecycle using a custom handler, or if you want to +// access properties on the request object before or after sending the request. If +// you just want the service response, call the ListIPSets method directly +// instead. +// +// Note: You must call the "Send" method on the returned request object in order +// to execute the request. +// +// // Example sending a request using the ListIPSetsRequest method. +// req, resp := client.ListIPSetsRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/waf-regional-2016-11-28/ListIPSets +func (c *WAFRegional) ListIPSetsRequest(input *waf.ListIPSetsInput) (req *request.Request, output *waf.ListIPSetsOutput) { + op := &request.Operation{ + Name: opListIPSets, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &waf.ListIPSetsInput{} + } + + output = &waf.ListIPSetsOutput{} + req = c.newRequest(op, input, output) + return +} + +// ListIPSets API operation for AWS WAF Regional. +// +// Returns an array of IPSetSummary objects in the response. +// +// 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 WAF Regional's +// API operation ListIPSets for usage and error information. +// +// Returned Error Codes: +// * ErrCodeWAFInternalErrorException "WAFInternalErrorException" +// The operation failed because of a system problem, even though the request +// was valid. Retry your request. +// +// * ErrCodeWAFInvalidAccountException "WAFInvalidAccountException" +// The operation failed because you tried to create, update, or delete an object +// by using an invalid account identifier. +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/waf-regional-2016-11-28/ListIPSets +func (c *WAFRegional) ListIPSets(input *waf.ListIPSetsInput) (*waf.ListIPSetsOutput, error) { + req, out := c.ListIPSetsRequest(input) + return out, req.Send() +} + +// ListIPSetsWithContext is the same as ListIPSets with the addition of +// the ability to pass a context and additional request options. +// +// See ListIPSets 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 *WAFRegional) ListIPSetsWithContext(ctx aws.Context, input *waf.ListIPSetsInput, opts ...request.Option) (*waf.ListIPSetsOutput, error) { + req, out := c.ListIPSetsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opListResourcesForWebACL = "ListResourcesForWebACL" + +// ListResourcesForWebACLRequest generates a "aws/request.Request" representing the +// client's request for the ListResourcesForWebACL operation. The "output" return +// value can be used to capture response data after the request's "Send" method +// is called. +// +// See ListResourcesForWebACL for usage and error information. +// +// Creating a request object using this method should be used when you want to inject +// custom logic into the request's lifecycle using a custom handler, or if you want to +// access properties on the request object before or after sending the request. If +// you just want the service response, call the ListResourcesForWebACL method directly +// instead. +// +// Note: You must call the "Send" method on the returned request object in order +// to execute the request. +// +// // Example sending a request using the ListResourcesForWebACLRequest method. +// req, resp := client.ListResourcesForWebACLRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/waf-regional-2016-11-28/ListResourcesForWebACL +func (c *WAFRegional) ListResourcesForWebACLRequest(input *ListResourcesForWebACLInput) (req *request.Request, output *ListResourcesForWebACLOutput) { + op := &request.Operation{ + Name: opListResourcesForWebACL, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &ListResourcesForWebACLInput{} + } + + output = &ListResourcesForWebACLOutput{} + req = c.newRequest(op, input, output) + return +} + +// ListResourcesForWebACL API operation for AWS WAF Regional. +// +// Returns an array of resources associated with the specified web ACL. +// +// 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 WAF Regional's +// API operation ListResourcesForWebACL for usage and error information. +// +// Returned Error Codes: +// * ErrCodeWAFInternalErrorException "WAFInternalErrorException" +// The operation failed because of a system problem, even though the request +// was valid. Retry your request. +// +// * ErrCodeWAFInvalidAccountException "WAFInvalidAccountException" +// The operation failed because you tried to create, update, or delete an object +// by using an invalid account identifier. +// +// * ErrCodeWAFNonexistentItemException "WAFNonexistentItemException" +// The operation failed because the referenced object doesn't exist. +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/waf-regional-2016-11-28/ListResourcesForWebACL +func (c *WAFRegional) ListResourcesForWebACL(input *ListResourcesForWebACLInput) (*ListResourcesForWebACLOutput, error) { + req, out := c.ListResourcesForWebACLRequest(input) + return out, req.Send() +} + +// ListResourcesForWebACLWithContext is the same as ListResourcesForWebACL with the addition of +// the ability to pass a context and additional request options. +// +// See ListResourcesForWebACL 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 *WAFRegional) ListResourcesForWebACLWithContext(ctx aws.Context, input *ListResourcesForWebACLInput, opts ...request.Option) (*ListResourcesForWebACLOutput, error) { + req, out := c.ListResourcesForWebACLRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opListRules = "ListRules" + +// ListRulesRequest generates a "aws/request.Request" representing the +// client's request for the ListRules operation. The "output" return +// value can be used to capture response data after the request's "Send" method +// is called. +// +// See ListRules for usage and error information. +// +// Creating a request object using this method should be used when you want to inject +// custom logic into the request's lifecycle using a custom handler, or if you want to +// access properties on the request object before or after sending the request. If +// you just want the service response, call the ListRules method directly +// instead. +// +// Note: You must call the "Send" method on the returned request object in order +// to execute the request. +// +// // Example sending a request using the ListRulesRequest method. +// req, resp := client.ListRulesRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/waf-regional-2016-11-28/ListRules +func (c *WAFRegional) ListRulesRequest(input *waf.ListRulesInput) (req *request.Request, output *waf.ListRulesOutput) { + op := &request.Operation{ + Name: opListRules, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &waf.ListRulesInput{} + } + + output = &waf.ListRulesOutput{} + req = c.newRequest(op, input, output) + return +} + +// ListRules API operation for AWS WAF Regional. +// +// Returns an array of RuleSummary objects. +// +// 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 WAF Regional's +// API operation ListRules for usage and error information. +// +// Returned Error Codes: +// * ErrCodeWAFInternalErrorException "WAFInternalErrorException" +// The operation failed because of a system problem, even though the request +// was valid. Retry your request. +// +// * ErrCodeWAFInvalidAccountException "WAFInvalidAccountException" +// The operation failed because you tried to create, update, or delete an object +// by using an invalid account identifier. +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/waf-regional-2016-11-28/ListRules +func (c *WAFRegional) ListRules(input *waf.ListRulesInput) (*waf.ListRulesOutput, error) { + req, out := c.ListRulesRequest(input) + return out, req.Send() +} + +// ListRulesWithContext is the same as ListRules with the addition of +// the ability to pass a context and additional request options. +// +// See ListRules 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 *WAFRegional) ListRulesWithContext(ctx aws.Context, input *waf.ListRulesInput, opts ...request.Option) (*waf.ListRulesOutput, error) { + req, out := c.ListRulesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opListSizeConstraintSets = "ListSizeConstraintSets" + +// ListSizeConstraintSetsRequest generates a "aws/request.Request" representing the +// client's request for the ListSizeConstraintSets operation. The "output" return +// value can be used to capture response data after the request's "Send" method +// is called. +// +// See ListSizeConstraintSets for usage and error information. +// +// Creating a request object using this method should be used when you want to inject +// custom logic into the request's lifecycle using a custom handler, or if you want to +// access properties on the request object before or after sending the request. If +// you just want the service response, call the ListSizeConstraintSets method directly +// instead. +// +// Note: You must call the "Send" method on the returned request object in order +// to execute the request. +// +// // Example sending a request using the ListSizeConstraintSetsRequest method. +// req, resp := client.ListSizeConstraintSetsRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/waf-regional-2016-11-28/ListSizeConstraintSets +func (c *WAFRegional) ListSizeConstraintSetsRequest(input *waf.ListSizeConstraintSetsInput) (req *request.Request, output *waf.ListSizeConstraintSetsOutput) { + op := &request.Operation{ + Name: opListSizeConstraintSets, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &waf.ListSizeConstraintSetsInput{} + } + + output = &waf.ListSizeConstraintSetsOutput{} + req = c.newRequest(op, input, output) + return +} + +// ListSizeConstraintSets API operation for AWS WAF Regional. +// +// Returns an array of SizeConstraintSetSummary objects. +// +// 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 WAF Regional's +// API operation ListSizeConstraintSets for usage and error information. +// +// Returned Error Codes: +// * ErrCodeWAFInternalErrorException "WAFInternalErrorException" +// The operation failed because of a system problem, even though the request +// was valid. Retry your request. +// +// * ErrCodeWAFInvalidAccountException "WAFInvalidAccountException" +// The operation failed because you tried to create, update, or delete an object +// by using an invalid account identifier. +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/waf-regional-2016-11-28/ListSizeConstraintSets +func (c *WAFRegional) ListSizeConstraintSets(input *waf.ListSizeConstraintSetsInput) (*waf.ListSizeConstraintSetsOutput, error) { + req, out := c.ListSizeConstraintSetsRequest(input) + return out, req.Send() +} + +// ListSizeConstraintSetsWithContext is the same as ListSizeConstraintSets with the addition of +// the ability to pass a context and additional request options. +// +// See ListSizeConstraintSets 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 *WAFRegional) ListSizeConstraintSetsWithContext(ctx aws.Context, input *waf.ListSizeConstraintSetsInput, opts ...request.Option) (*waf.ListSizeConstraintSetsOutput, error) { + req, out := c.ListSizeConstraintSetsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opListSqlInjectionMatchSets = "ListSqlInjectionMatchSets" + +// ListSqlInjectionMatchSetsRequest generates a "aws/request.Request" representing the +// client's request for the ListSqlInjectionMatchSets operation. The "output" return +// value can be used to capture response data after the request's "Send" method +// is called. +// +// See ListSqlInjectionMatchSets for usage and error information. +// +// Creating a request object using this method should be used when you want to inject +// custom logic into the request's lifecycle using a custom handler, or if you want to +// access properties on the request object before or after sending the request. If +// you just want the service response, call the ListSqlInjectionMatchSets method directly +// instead. +// +// Note: You must call the "Send" method on the returned request object in order +// to execute the request. +// +// // Example sending a request using the ListSqlInjectionMatchSetsRequest method. +// req, resp := client.ListSqlInjectionMatchSetsRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/waf-regional-2016-11-28/ListSqlInjectionMatchSets +func (c *WAFRegional) ListSqlInjectionMatchSetsRequest(input *waf.ListSqlInjectionMatchSetsInput) (req *request.Request, output *waf.ListSqlInjectionMatchSetsOutput) { + op := &request.Operation{ + Name: opListSqlInjectionMatchSets, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &waf.ListSqlInjectionMatchSetsInput{} + } + + output = &waf.ListSqlInjectionMatchSetsOutput{} + req = c.newRequest(op, input, output) + return +} + +// ListSqlInjectionMatchSets API operation for AWS WAF Regional. +// +// Returns an array of SqlInjectionMatchSet objects. +// +// 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 WAF Regional's +// API operation ListSqlInjectionMatchSets for usage and error information. +// +// Returned Error Codes: +// * ErrCodeWAFInternalErrorException "WAFInternalErrorException" +// The operation failed because of a system problem, even though the request +// was valid. Retry your request. +// +// * ErrCodeWAFInvalidAccountException "WAFInvalidAccountException" +// The operation failed because you tried to create, update, or delete an object +// by using an invalid account identifier. +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/waf-regional-2016-11-28/ListSqlInjectionMatchSets +func (c *WAFRegional) ListSqlInjectionMatchSets(input *waf.ListSqlInjectionMatchSetsInput) (*waf.ListSqlInjectionMatchSetsOutput, error) { + req, out := c.ListSqlInjectionMatchSetsRequest(input) + return out, req.Send() +} + +// ListSqlInjectionMatchSetsWithContext is the same as ListSqlInjectionMatchSets with the addition of +// the ability to pass a context and additional request options. +// +// See ListSqlInjectionMatchSets 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 *WAFRegional) ListSqlInjectionMatchSetsWithContext(ctx aws.Context, input *waf.ListSqlInjectionMatchSetsInput, opts ...request.Option) (*waf.ListSqlInjectionMatchSetsOutput, error) { + req, out := c.ListSqlInjectionMatchSetsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opListWebACLs = "ListWebACLs" + +// ListWebACLsRequest generates a "aws/request.Request" representing the +// client's request for the ListWebACLs operation. The "output" return +// value can be used to capture response data after the request's "Send" method +// is called. +// +// See ListWebACLs for usage and error information. +// +// Creating a request object using this method should be used when you want to inject +// custom logic into the request's lifecycle using a custom handler, or if you want to +// access properties on the request object before or after sending the request. If +// you just want the service response, call the ListWebACLs method directly +// instead. +// +// Note: You must call the "Send" method on the returned request object in order +// to execute the request. +// +// // Example sending a request using the ListWebACLsRequest method. +// req, resp := client.ListWebACLsRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/waf-regional-2016-11-28/ListWebACLs +func (c *WAFRegional) ListWebACLsRequest(input *waf.ListWebACLsInput) (req *request.Request, output *waf.ListWebACLsOutput) { + op := &request.Operation{ + Name: opListWebACLs, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &waf.ListWebACLsInput{} + } + + output = &waf.ListWebACLsOutput{} + req = c.newRequest(op, input, output) + return +} + +// ListWebACLs API operation for AWS WAF Regional. +// +// Returns an array of WebACLSummary objects in the response. +// +// 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 WAF Regional's +// API operation ListWebACLs for usage and error information. +// +// Returned Error Codes: +// * ErrCodeWAFInternalErrorException "WAFInternalErrorException" +// The operation failed because of a system problem, even though the request +// was valid. Retry your request. +// +// * ErrCodeWAFInvalidAccountException "WAFInvalidAccountException" +// The operation failed because you tried to create, update, or delete an object +// by using an invalid account identifier. +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/waf-regional-2016-11-28/ListWebACLs +func (c *WAFRegional) ListWebACLs(input *waf.ListWebACLsInput) (*waf.ListWebACLsOutput, error) { + req, out := c.ListWebACLsRequest(input) + return out, req.Send() +} + +// ListWebACLsWithContext is the same as ListWebACLs with the addition of +// the ability to pass a context and additional request options. +// +// See ListWebACLs 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 *WAFRegional) ListWebACLsWithContext(ctx aws.Context, input *waf.ListWebACLsInput, opts ...request.Option) (*waf.ListWebACLsOutput, error) { + req, out := c.ListWebACLsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opListXssMatchSets = "ListXssMatchSets" + +// ListXssMatchSetsRequest generates a "aws/request.Request" representing the +// client's request for the ListXssMatchSets operation. The "output" return +// value can be used to capture response data after the request's "Send" method +// is called. +// +// See ListXssMatchSets for usage and error information. +// +// Creating a request object using this method should be used when you want to inject +// custom logic into the request's lifecycle using a custom handler, or if you want to +// access properties on the request object before or after sending the request. If +// you just want the service response, call the ListXssMatchSets method directly +// instead. +// +// Note: You must call the "Send" method on the returned request object in order +// to execute the request. +// +// // Example sending a request using the ListXssMatchSetsRequest method. +// req, resp := client.ListXssMatchSetsRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/waf-regional-2016-11-28/ListXssMatchSets +func (c *WAFRegional) ListXssMatchSetsRequest(input *waf.ListXssMatchSetsInput) (req *request.Request, output *waf.ListXssMatchSetsOutput) { + op := &request.Operation{ + Name: opListXssMatchSets, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &waf.ListXssMatchSetsInput{} + } + + output = &waf.ListXssMatchSetsOutput{} + req = c.newRequest(op, input, output) + return +} + +// ListXssMatchSets API operation for AWS WAF Regional. +// +// Returns an array of XssMatchSet objects. +// +// 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 WAF Regional's +// API operation ListXssMatchSets for usage and error information. +// +// Returned Error Codes: +// * ErrCodeWAFInternalErrorException "WAFInternalErrorException" +// The operation failed because of a system problem, even though the request +// was valid. Retry your request. +// +// * ErrCodeWAFInvalidAccountException "WAFInvalidAccountException" +// The operation failed because you tried to create, update, or delete an object +// by using an invalid account identifier. +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/waf-regional-2016-11-28/ListXssMatchSets +func (c *WAFRegional) ListXssMatchSets(input *waf.ListXssMatchSetsInput) (*waf.ListXssMatchSetsOutput, error) { + req, out := c.ListXssMatchSetsRequest(input) + return out, req.Send() +} + +// ListXssMatchSetsWithContext is the same as ListXssMatchSets with the addition of +// the ability to pass a context and additional request options. +// +// See ListXssMatchSets 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 *WAFRegional) ListXssMatchSetsWithContext(ctx aws.Context, input *waf.ListXssMatchSetsInput, opts ...request.Option) (*waf.ListXssMatchSetsOutput, error) { + req, out := c.ListXssMatchSetsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opUpdateByteMatchSet = "UpdateByteMatchSet" + +// UpdateByteMatchSetRequest generates a "aws/request.Request" representing the +// client's request for the UpdateByteMatchSet operation. The "output" return +// value can be used to capture response data after the request's "Send" method +// is called. +// +// See UpdateByteMatchSet for usage and error information. +// +// Creating a request object using this method should be used when you want to inject +// custom logic into the request's lifecycle using a custom handler, or if you want to +// access properties on the request object before or after sending the request. If +// you just want the service response, call the UpdateByteMatchSet method directly +// instead. +// +// Note: You must call the "Send" method on the returned request object in order +// to execute the request. +// +// // Example sending a request using the UpdateByteMatchSetRequest method. +// req, resp := client.UpdateByteMatchSetRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/waf-regional-2016-11-28/UpdateByteMatchSet +func (c *WAFRegional) UpdateByteMatchSetRequest(input *waf.UpdateByteMatchSetInput) (req *request.Request, output *waf.UpdateByteMatchSetOutput) { + op := &request.Operation{ + Name: opUpdateByteMatchSet, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &waf.UpdateByteMatchSetInput{} + } + + output = &waf.UpdateByteMatchSetOutput{} + req = c.newRequest(op, input, output) + return +} + +// UpdateByteMatchSet API operation for AWS WAF Regional. +// +// Inserts or deletes ByteMatchTuple objects (filters) in a ByteMatchSet. For +// each ByteMatchTuple object, you specify the following values: +// +// * Whether to insert or delete the object from the array. If you want to +// change a ByteMatchSetUpdate object, you delete the existing object and +// add a new one. +// +// * The part of a web request that you want AWS WAF to inspect, such as +// a query string or the value of the User-Agent header. +// +// * The bytes (typically a string that corresponds with ASCII characters) +// that you want AWS WAF to look for. For more information, including how +// you specify the values for the AWS WAF API and the AWS CLI or SDKs, see +// TargetString in the ByteMatchTuple data type. +// +// * Where to look, such as at the beginning or the end of a query string. +// +// * Whether to perform any conversions on the request, such as converting +// it to lowercase, before inspecting it for the specified string. +// +// For example, you can add a ByteMatchSetUpdate object that matches web requests +// in which User-Agent headers contain the string BadBot. You can then configure +// AWS WAF to block those requests. +// +// To create and configure a ByteMatchSet, perform the following steps: +// +// Create a ByteMatchSet. For more information, see CreateByteMatchSet. +// +// Use GetChangeToken to get the change token that you provide in the ChangeToken +// parameter of an UpdateByteMatchSet request. +// +// Submit an UpdateByteMatchSet request to specify the part of the request that +// you want AWS WAF to inspect (for example, the header or the URI) and the +// value that you want AWS WAF to watch for. +// +// For more information about how to use the AWS WAF API to allow or block HTTP +// requests, see the AWS WAF Developer Guide (http://docs.aws.amazon.com/waf/latest/developerguide/). +// +// 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 WAF Regional's +// API operation UpdateByteMatchSet for usage and error information. +// +// Returned Error Codes: +// * ErrCodeWAFInternalErrorException "WAFInternalErrorException" +// The operation failed because of a system problem, even though the request +// was valid. Retry your request. +// +// * ErrCodeWAFInvalidAccountException "WAFInvalidAccountException" +// The operation failed because you tried to create, update, or delete an object +// by using an invalid account identifier. +// +// * ErrCodeWAFInvalidOperationException "WAFInvalidOperationException" +// The operation failed because there was nothing to do. For example: +// +// * You tried to remove a Rule from a WebACL, but the Rule isn't in the +// specified WebACL. +// +// * You tried to remove an IP address from an IPSet, but the IP address +// isn't in the specified IPSet. +// +// * You tried to remove a ByteMatchTuple from a ByteMatchSet, but the ByteMatchTuple +// isn't in the specified WebACL. +// +// * You tried to add a Rule to a WebACL, but the Rule already exists in +// the specified WebACL. +// +// * You tried to add an IP address to an IPSet, but the IP address already +// exists in the specified IPSet. +// +// * You tried to add a ByteMatchTuple to a ByteMatchSet, but the ByteMatchTuple +// already exists in the specified WebACL. +// +// * ErrCodeWAFInvalidParameterException "WAFInvalidParameterException" +// The operation failed because AWS WAF didn't recognize a parameter in the +// request. For example: +// +// * You specified an invalid parameter name. +// +// * You specified an invalid value. +// +// * You tried to update an object (ByteMatchSet, IPSet, Rule, or WebACL) +// using an action other than INSERT or DELETE. +// +// * You tried to create a WebACL with a DefaultActionType other than ALLOW, +// BLOCK, or COUNT. +// +// * You tried to update a WebACL with a WafActionType other than ALLOW, +// BLOCK, or COUNT. +// +// * You tried to update a ByteMatchSet with a FieldToMatchType other than +// HEADER, QUERY_STRING, or URI. +// +// * You tried to update a ByteMatchSet with a Field of HEADER but no value +// for Data. +// +// * Your request references an ARN that is malformed, or corresponds to +// a resource with which a web ACL cannot be associated. +// +// * ErrCodeWAFNonexistentContainerException "WAFNonexistentContainerException" +// The operation failed because you tried to add an object to or delete an object +// from another object that doesn't exist. For example: +// +// * You tried to add a Rule to or delete a Rule from a WebACL that doesn't +// exist. +// +// * You tried to add a ByteMatchSet to or delete a ByteMatchSet from a Rule +// that doesn't exist. +// +// * You tried to add an IP address to or delete an IP address from an IPSet +// that doesn't exist. +// +// * You tried to add a ByteMatchTuple to or delete a ByteMatchTuple from +// a ByteMatchSet that doesn't exist. +// +// * ErrCodeWAFNonexistentItemException "WAFNonexistentItemException" +// The operation failed because the referenced object doesn't exist. +// +// * ErrCodeWAFStaleDataException "WAFStaleDataException" +// The operation failed because you tried to create, update, or delete an object +// by using a change token that has already been used. +// +// * ErrCodeWAFLimitsExceededException "WAFLimitsExceededException" +// The operation exceeds a resource limit, for example, the maximum number of +// WebACL objects that you can create for an AWS account. For more information, +// see Limits (http://docs.aws.amazon.com/waf/latest/developerguide/limits.html) +// in the AWS WAF Developer Guide. +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/waf-regional-2016-11-28/UpdateByteMatchSet +func (c *WAFRegional) UpdateByteMatchSet(input *waf.UpdateByteMatchSetInput) (*waf.UpdateByteMatchSetOutput, error) { + req, out := c.UpdateByteMatchSetRequest(input) + return out, req.Send() +} + +// UpdateByteMatchSetWithContext is the same as UpdateByteMatchSet with the addition of +// the ability to pass a context and additional request options. +// +// See UpdateByteMatchSet 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 *WAFRegional) UpdateByteMatchSetWithContext(ctx aws.Context, input *waf.UpdateByteMatchSetInput, opts ...request.Option) (*waf.UpdateByteMatchSetOutput, error) { + req, out := c.UpdateByteMatchSetRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opUpdateIPSet = "UpdateIPSet" + +// UpdateIPSetRequest generates a "aws/request.Request" representing the +// client's request for the UpdateIPSet operation. The "output" return +// value can be used to capture response data after the request's "Send" method +// is called. +// +// See UpdateIPSet for usage and error information. +// +// Creating a request object using this method should be used when you want to inject +// custom logic into the request's lifecycle using a custom handler, or if you want to +// access properties on the request object before or after sending the request. If +// you just want the service response, call the UpdateIPSet method directly +// instead. +// +// Note: You must call the "Send" method on the returned request object in order +// to execute the request. +// +// // Example sending a request using the UpdateIPSetRequest method. +// req, resp := client.UpdateIPSetRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/waf-regional-2016-11-28/UpdateIPSet +func (c *WAFRegional) UpdateIPSetRequest(input *waf.UpdateIPSetInput) (req *request.Request, output *waf.UpdateIPSetOutput) { + op := &request.Operation{ + Name: opUpdateIPSet, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &waf.UpdateIPSetInput{} + } + + output = &waf.UpdateIPSetOutput{} + req = c.newRequest(op, input, output) + return +} + +// UpdateIPSet API operation for AWS WAF Regional. +// +// Inserts or deletes IPSetDescriptor objects in an IPSet. For each IPSetDescriptor +// object, you specify the following values: +// +// * Whether to insert or delete the object from the array. If you want to +// change an IPSetDescriptor object, you delete the existing object and add +// a new one. +// +// * The IP address version, IPv4 or IPv6. +// +// * The IP address in CIDR notation, for example, 192.0.2.0/24 (for the +// range of IP addresses from 192.0.2.0 to 192.0.2.255) or 192.0.2.44/32 +// (for the individual IP address 192.0.2.44). +// +// AWS WAF supports /8, /16, /24, and /32 IP address ranges for IPv4, and /24, +// /32, /48, /56, /64 and /128 for IPv6. For more information about CIDR notation, +// see the Wikipedia entry Classless Inter-Domain Routing (https://en.wikipedia.org/wiki/Classless_Inter-Domain_Routing). +// +// IPv6 addresses can be represented using any of the following formats: +// +// * 1111:0000:0000:0000:0000:0000:0000:0111/128 +// +// * 1111:0:0:0:0:0:0:0111/128 +// +// * 1111::0111/128 +// +// * 1111::111/128 +// +// You use an IPSet to specify which web requests you want to allow or block +// based on the IP addresses that the requests originated from. For example, +// if you're receiving a lot of requests from one or a small number of IP addresses +// and you want to block the requests, you can create an IPSet that specifies +// those IP addresses, and then configure AWS WAF to block the requests. +// +// To create and configure an IPSet, perform the following steps: +// +// Submit a CreateIPSet request. +// +// Use GetChangeToken to get the change token that you provide in the ChangeToken +// parameter of an UpdateIPSet request. +// +// Submit an UpdateIPSet request to specify the IP addresses that you want AWS +// WAF to watch for. +// +// When you update an IPSet, you specify the IP addresses that you want to add +// and/or the IP addresses that you want to delete. If you want to change an +// IP address, you delete the existing IP address and add the new one. +// +// For more information about how to use the AWS WAF API to allow or block HTTP +// requests, see the AWS WAF Developer Guide (http://docs.aws.amazon.com/waf/latest/developerguide/). +// +// 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 WAF Regional's +// API operation UpdateIPSet for usage and error information. +// +// Returned Error Codes: +// * ErrCodeWAFStaleDataException "WAFStaleDataException" +// The operation failed because you tried to create, update, or delete an object +// by using a change token that has already been used. +// +// * ErrCodeWAFInternalErrorException "WAFInternalErrorException" +// The operation failed because of a system problem, even though the request +// was valid. Retry your request. +// +// * ErrCodeWAFInvalidAccountException "WAFInvalidAccountException" +// The operation failed because you tried to create, update, or delete an object +// by using an invalid account identifier. +// +// * ErrCodeWAFInvalidOperationException "WAFInvalidOperationException" +// The operation failed because there was nothing to do. For example: +// +// * You tried to remove a Rule from a WebACL, but the Rule isn't in the +// specified WebACL. +// +// * You tried to remove an IP address from an IPSet, but the IP address +// isn't in the specified IPSet. +// +// * You tried to remove a ByteMatchTuple from a ByteMatchSet, but the ByteMatchTuple +// isn't in the specified WebACL. +// +// * You tried to add a Rule to a WebACL, but the Rule already exists in +// the specified WebACL. +// +// * You tried to add an IP address to an IPSet, but the IP address already +// exists in the specified IPSet. +// +// * You tried to add a ByteMatchTuple to a ByteMatchSet, but the ByteMatchTuple +// already exists in the specified WebACL. +// +// * ErrCodeWAFInvalidParameterException "WAFInvalidParameterException" +// The operation failed because AWS WAF didn't recognize a parameter in the +// request. For example: +// +// * You specified an invalid parameter name. +// +// * You specified an invalid value. +// +// * You tried to update an object (ByteMatchSet, IPSet, Rule, or WebACL) +// using an action other than INSERT or DELETE. +// +// * You tried to create a WebACL with a DefaultActionType other than ALLOW, +// BLOCK, or COUNT. +// +// * You tried to update a WebACL with a WafActionType other than ALLOW, +// BLOCK, or COUNT. +// +// * You tried to update a ByteMatchSet with a FieldToMatchType other than +// HEADER, QUERY_STRING, or URI. +// +// * You tried to update a ByteMatchSet with a Field of HEADER but no value +// for Data. +// +// * Your request references an ARN that is malformed, or corresponds to +// a resource with which a web ACL cannot be associated. +// +// * ErrCodeWAFNonexistentContainerException "WAFNonexistentContainerException" +// The operation failed because you tried to add an object to or delete an object +// from another object that doesn't exist. For example: +// +// * You tried to add a Rule to or delete a Rule from a WebACL that doesn't +// exist. +// +// * You tried to add a ByteMatchSet to or delete a ByteMatchSet from a Rule +// that doesn't exist. +// +// * You tried to add an IP address to or delete an IP address from an IPSet +// that doesn't exist. +// +// * You tried to add a ByteMatchTuple to or delete a ByteMatchTuple from +// a ByteMatchSet that doesn't exist. +// +// * ErrCodeWAFNonexistentItemException "WAFNonexistentItemException" +// The operation failed because the referenced object doesn't exist. +// +// * ErrCodeWAFReferencedItemException "WAFReferencedItemException" +// The operation failed because you tried to delete an object that is still +// in use. For example: +// +// * You tried to delete a ByteMatchSet that is still referenced by a Rule. +// +// * You tried to delete a Rule that is still referenced by a WebACL. +// +// * ErrCodeWAFLimitsExceededException "WAFLimitsExceededException" +// The operation exceeds a resource limit, for example, the maximum number of +// WebACL objects that you can create for an AWS account. For more information, +// see Limits (http://docs.aws.amazon.com/waf/latest/developerguide/limits.html) +// in the AWS WAF Developer Guide. +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/waf-regional-2016-11-28/UpdateIPSet +func (c *WAFRegional) UpdateIPSet(input *waf.UpdateIPSetInput) (*waf.UpdateIPSetOutput, error) { + req, out := c.UpdateIPSetRequest(input) + return out, req.Send() +} + +// UpdateIPSetWithContext is the same as UpdateIPSet with the addition of +// the ability to pass a context and additional request options. +// +// See UpdateIPSet 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 *WAFRegional) UpdateIPSetWithContext(ctx aws.Context, input *waf.UpdateIPSetInput, opts ...request.Option) (*waf.UpdateIPSetOutput, error) { + req, out := c.UpdateIPSetRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opUpdateRule = "UpdateRule" + +// UpdateRuleRequest generates a "aws/request.Request" representing the +// client's request for the UpdateRule operation. The "output" return +// value can be used to capture response data after the request's "Send" method +// is called. +// +// See UpdateRule for usage and error information. +// +// Creating a request object using this method should be used when you want to inject +// custom logic into the request's lifecycle using a custom handler, or if you want to +// access properties on the request object before or after sending the request. If +// you just want the service response, call the UpdateRule method directly +// instead. +// +// Note: You must call the "Send" method on the returned request object in order +// to execute the request. +// +// // Example sending a request using the UpdateRuleRequest method. +// req, resp := client.UpdateRuleRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/waf-regional-2016-11-28/UpdateRule +func (c *WAFRegional) UpdateRuleRequest(input *waf.UpdateRuleInput) (req *request.Request, output *waf.UpdateRuleOutput) { + op := &request.Operation{ + Name: opUpdateRule, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &waf.UpdateRuleInput{} + } + + output = &waf.UpdateRuleOutput{} + req = c.newRequest(op, input, output) + return +} + +// UpdateRule API operation for AWS WAF Regional. +// +// Inserts or deletes Predicate objects in a Rule. Each Predicate object identifies +// a predicate, such as a ByteMatchSet or an IPSet, that specifies the web requests +// that you want to allow, block, or count. If you add more than one predicate +// to a Rule, a request must match all of the specifications to be allowed, +// blocked, or counted. For example, suppose you add the following to a Rule: +// +// * A ByteMatchSet that matches the value BadBot in the User-Agent header +// +// * An IPSet that matches the IP address 192.0.2.44 +// +// You then add the Rule to a WebACL and specify that you want to block requests +// that satisfy the Rule. For a request to be blocked, the User-Agent header +// in the request must contain the value BadBotand the request must originate +// from the IP address 192.0.2.44. +// +// To create and configure a Rule, perform the following steps: +// +// Create and update the predicates that you want to include in the Rule. +// +// Create the Rule. See CreateRule. +// +// Use GetChangeToken to get the change token that you provide in the ChangeToken +// parameter of an UpdateRule request. +// +// Submit an UpdateRule request to add predicates to the Rule. +// +// Create and update a WebACL that contains the Rule. See CreateWebACL. +// +// If you want to replace one ByteMatchSet or IPSet with another, you delete +// the existing one and add the new one. +// +// For more information about how to use the AWS WAF API to allow or block HTTP +// requests, see the AWS WAF Developer Guide (http://docs.aws.amazon.com/waf/latest/developerguide/). +// +// 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 WAF Regional's +// API operation UpdateRule for usage and error information. +// +// Returned Error Codes: +// * ErrCodeWAFStaleDataException "WAFStaleDataException" +// The operation failed because you tried to create, update, or delete an object +// by using a change token that has already been used. +// +// * ErrCodeWAFInternalErrorException "WAFInternalErrorException" +// The operation failed because of a system problem, even though the request +// was valid. Retry your request. +// +// * ErrCodeWAFInvalidAccountException "WAFInvalidAccountException" +// The operation failed because you tried to create, update, or delete an object +// by using an invalid account identifier. +// +// * ErrCodeWAFInvalidOperationException "WAFInvalidOperationException" +// The operation failed because there was nothing to do. For example: +// +// * You tried to remove a Rule from a WebACL, but the Rule isn't in the +// specified WebACL. +// +// * You tried to remove an IP address from an IPSet, but the IP address +// isn't in the specified IPSet. +// +// * You tried to remove a ByteMatchTuple from a ByteMatchSet, but the ByteMatchTuple +// isn't in the specified WebACL. +// +// * You tried to add a Rule to a WebACL, but the Rule already exists in +// the specified WebACL. +// +// * You tried to add an IP address to an IPSet, but the IP address already +// exists in the specified IPSet. +// +// * You tried to add a ByteMatchTuple to a ByteMatchSet, but the ByteMatchTuple +// already exists in the specified WebACL. +// +// * ErrCodeWAFInvalidParameterException "WAFInvalidParameterException" +// The operation failed because AWS WAF didn't recognize a parameter in the +// request. For example: +// +// * You specified an invalid parameter name. +// +// * You specified an invalid value. +// +// * You tried to update an object (ByteMatchSet, IPSet, Rule, or WebACL) +// using an action other than INSERT or DELETE. +// +// * You tried to create a WebACL with a DefaultActionType other than ALLOW, +// BLOCK, or COUNT. +// +// * You tried to update a WebACL with a WafActionType other than ALLOW, +// BLOCK, or COUNT. +// +// * You tried to update a ByteMatchSet with a FieldToMatchType other than +// HEADER, QUERY_STRING, or URI. +// +// * You tried to update a ByteMatchSet with a Field of HEADER but no value +// for Data. +// +// * Your request references an ARN that is malformed, or corresponds to +// a resource with which a web ACL cannot be associated. +// +// * ErrCodeWAFNonexistentContainerException "WAFNonexistentContainerException" +// The operation failed because you tried to add an object to or delete an object +// from another object that doesn't exist. For example: +// +// * You tried to add a Rule to or delete a Rule from a WebACL that doesn't +// exist. +// +// * You tried to add a ByteMatchSet to or delete a ByteMatchSet from a Rule +// that doesn't exist. +// +// * You tried to add an IP address to or delete an IP address from an IPSet +// that doesn't exist. +// +// * You tried to add a ByteMatchTuple to or delete a ByteMatchTuple from +// a ByteMatchSet that doesn't exist. +// +// * ErrCodeWAFNonexistentItemException "WAFNonexistentItemException" +// The operation failed because the referenced object doesn't exist. +// +// * ErrCodeWAFReferencedItemException "WAFReferencedItemException" +// The operation failed because you tried to delete an object that is still +// in use. For example: +// +// * You tried to delete a ByteMatchSet that is still referenced by a Rule. +// +// * You tried to delete a Rule that is still referenced by a WebACL. +// +// * ErrCodeWAFLimitsExceededException "WAFLimitsExceededException" +// The operation exceeds a resource limit, for example, the maximum number of +// WebACL objects that you can create for an AWS account. For more information, +// see Limits (http://docs.aws.amazon.com/waf/latest/developerguide/limits.html) +// in the AWS WAF Developer Guide. +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/waf-regional-2016-11-28/UpdateRule +func (c *WAFRegional) UpdateRule(input *waf.UpdateRuleInput) (*waf.UpdateRuleOutput, error) { + req, out := c.UpdateRuleRequest(input) + return out, req.Send() +} + +// UpdateRuleWithContext is the same as UpdateRule with the addition of +// the ability to pass a context and additional request options. +// +// See UpdateRule 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 *WAFRegional) UpdateRuleWithContext(ctx aws.Context, input *waf.UpdateRuleInput, opts ...request.Option) (*waf.UpdateRuleOutput, error) { + req, out := c.UpdateRuleRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opUpdateSizeConstraintSet = "UpdateSizeConstraintSet" + +// UpdateSizeConstraintSetRequest generates a "aws/request.Request" representing the +// client's request for the UpdateSizeConstraintSet operation. The "output" return +// value can be used to capture response data after the request's "Send" method +// is called. +// +// See UpdateSizeConstraintSet for usage and error information. +// +// Creating a request object using this method should be used when you want to inject +// custom logic into the request's lifecycle using a custom handler, or if you want to +// access properties on the request object before or after sending the request. If +// you just want the service response, call the UpdateSizeConstraintSet method directly +// instead. +// +// Note: You must call the "Send" method on the returned request object in order +// to execute the request. +// +// // Example sending a request using the UpdateSizeConstraintSetRequest method. +// req, resp := client.UpdateSizeConstraintSetRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/waf-regional-2016-11-28/UpdateSizeConstraintSet +func (c *WAFRegional) UpdateSizeConstraintSetRequest(input *waf.UpdateSizeConstraintSetInput) (req *request.Request, output *waf.UpdateSizeConstraintSetOutput) { + op := &request.Operation{ + Name: opUpdateSizeConstraintSet, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &waf.UpdateSizeConstraintSetInput{} + } + + output = &waf.UpdateSizeConstraintSetOutput{} + req = c.newRequest(op, input, output) + return +} + +// UpdateSizeConstraintSet API operation for AWS WAF Regional. +// +// Inserts or deletes SizeConstraint objects (filters) in a SizeConstraintSet. +// For each SizeConstraint object, you specify the following values: +// +// * Whether to insert or delete the object from the array. If you want to +// change a SizeConstraintSetUpdate object, you delete the existing object +// and add a new one. +// +// * The part of a web request that you want AWS WAF to evaluate, such as +// the length of a query string or the length of the User-Agent header. +// +// * Whether to perform any transformations on the request, such as converting +// it to lowercase, before checking its length. Note that transformations +// of the request body are not supported because the AWS resource forwards +// only the first 8192 bytes of your request to AWS WAF. +// +// * A ComparisonOperator used for evaluating the selected part of the request +// against the specified Size, such as equals, greater than, less than, and +// so on. +// +// * The length, in bytes, that you want AWS WAF to watch for in selected +// part of the request. The length is computed after applying the transformation. +// +// For example, you can add a SizeConstraintSetUpdate object that matches web +// requests in which the length of the User-Agent header is greater than 100 +// bytes. You can then configure AWS WAF to block those requests. +// +// To create and configure a SizeConstraintSet, perform the following steps: +// +// Create a SizeConstraintSet. For more information, see CreateSizeConstraintSet. +// +// Use GetChangeToken to get the change token that you provide in the ChangeToken +// parameter of an UpdateSizeConstraintSet request. +// +// Submit an UpdateSizeConstraintSet request to specify the part of the request +// that you want AWS WAF to inspect (for example, the header or the URI) and +// the value that you want AWS WAF to watch for. +// +// For more information about how to use the AWS WAF API to allow or block HTTP +// requests, see the AWS WAF Developer Guide (http://docs.aws.amazon.com/waf/latest/developerguide/). +// +// 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 WAF Regional's +// API operation UpdateSizeConstraintSet for usage and error information. +// +// Returned Error Codes: +// * ErrCodeWAFStaleDataException "WAFStaleDataException" +// The operation failed because you tried to create, update, or delete an object +// by using a change token that has already been used. +// +// * ErrCodeWAFInternalErrorException "WAFInternalErrorException" +// The operation failed because of a system problem, even though the request +// was valid. Retry your request. +// +// * ErrCodeWAFInvalidAccountException "WAFInvalidAccountException" +// The operation failed because you tried to create, update, or delete an object +// by using an invalid account identifier. +// +// * ErrCodeWAFInvalidOperationException "WAFInvalidOperationException" +// The operation failed because there was nothing to do. For example: +// +// * You tried to remove a Rule from a WebACL, but the Rule isn't in the +// specified WebACL. +// +// * You tried to remove an IP address from an IPSet, but the IP address +// isn't in the specified IPSet. +// +// * You tried to remove a ByteMatchTuple from a ByteMatchSet, but the ByteMatchTuple +// isn't in the specified WebACL. +// +// * You tried to add a Rule to a WebACL, but the Rule already exists in +// the specified WebACL. +// +// * You tried to add an IP address to an IPSet, but the IP address already +// exists in the specified IPSet. +// +// * You tried to add a ByteMatchTuple to a ByteMatchSet, but the ByteMatchTuple +// already exists in the specified WebACL. +// +// * ErrCodeWAFInvalidParameterException "WAFInvalidParameterException" +// The operation failed because AWS WAF didn't recognize a parameter in the +// request. For example: +// +// * You specified an invalid parameter name. +// +// * You specified an invalid value. +// +// * You tried to update an object (ByteMatchSet, IPSet, Rule, or WebACL) +// using an action other than INSERT or DELETE. +// +// * You tried to create a WebACL with a DefaultActionType other than ALLOW, +// BLOCK, or COUNT. +// +// * You tried to update a WebACL with a WafActionType other than ALLOW, +// BLOCK, or COUNT. +// +// * You tried to update a ByteMatchSet with a FieldToMatchType other than +// HEADER, QUERY_STRING, or URI. +// +// * You tried to update a ByteMatchSet with a Field of HEADER but no value +// for Data. +// +// * Your request references an ARN that is malformed, or corresponds to +// a resource with which a web ACL cannot be associated. +// +// * ErrCodeWAFNonexistentContainerException "WAFNonexistentContainerException" +// The operation failed because you tried to add an object to or delete an object +// from another object that doesn't exist. For example: +// +// * You tried to add a Rule to or delete a Rule from a WebACL that doesn't +// exist. +// +// * You tried to add a ByteMatchSet to or delete a ByteMatchSet from a Rule +// that doesn't exist. +// +// * You tried to add an IP address to or delete an IP address from an IPSet +// that doesn't exist. +// +// * You tried to add a ByteMatchTuple to or delete a ByteMatchTuple from +// a ByteMatchSet that doesn't exist. +// +// * ErrCodeWAFNonexistentItemException "WAFNonexistentItemException" +// The operation failed because the referenced object doesn't exist. +// +// * ErrCodeWAFReferencedItemException "WAFReferencedItemException" +// The operation failed because you tried to delete an object that is still +// in use. For example: +// +// * You tried to delete a ByteMatchSet that is still referenced by a Rule. +// +// * You tried to delete a Rule that is still referenced by a WebACL. +// +// * ErrCodeWAFLimitsExceededException "WAFLimitsExceededException" +// The operation exceeds a resource limit, for example, the maximum number of +// WebACL objects that you can create for an AWS account. For more information, +// see Limits (http://docs.aws.amazon.com/waf/latest/developerguide/limits.html) +// in the AWS WAF Developer Guide. +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/waf-regional-2016-11-28/UpdateSizeConstraintSet +func (c *WAFRegional) UpdateSizeConstraintSet(input *waf.UpdateSizeConstraintSetInput) (*waf.UpdateSizeConstraintSetOutput, error) { + req, out := c.UpdateSizeConstraintSetRequest(input) + return out, req.Send() +} + +// UpdateSizeConstraintSetWithContext is the same as UpdateSizeConstraintSet with the addition of +// the ability to pass a context and additional request options. +// +// See UpdateSizeConstraintSet 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 *WAFRegional) UpdateSizeConstraintSetWithContext(ctx aws.Context, input *waf.UpdateSizeConstraintSetInput, opts ...request.Option) (*waf.UpdateSizeConstraintSetOutput, error) { + req, out := c.UpdateSizeConstraintSetRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opUpdateSqlInjectionMatchSet = "UpdateSqlInjectionMatchSet" + +// UpdateSqlInjectionMatchSetRequest generates a "aws/request.Request" representing the +// client's request for the UpdateSqlInjectionMatchSet operation. The "output" return +// value can be used to capture response data after the request's "Send" method +// is called. +// +// See UpdateSqlInjectionMatchSet for usage and error information. +// +// Creating a request object using this method should be used when you want to inject +// custom logic into the request's lifecycle using a custom handler, or if you want to +// access properties on the request object before or after sending the request. If +// you just want the service response, call the UpdateSqlInjectionMatchSet method directly +// instead. +// +// Note: You must call the "Send" method on the returned request object in order +// to execute the request. +// +// // Example sending a request using the UpdateSqlInjectionMatchSetRequest method. +// req, resp := client.UpdateSqlInjectionMatchSetRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/waf-regional-2016-11-28/UpdateSqlInjectionMatchSet +func (c *WAFRegional) UpdateSqlInjectionMatchSetRequest(input *waf.UpdateSqlInjectionMatchSetInput) (req *request.Request, output *waf.UpdateSqlInjectionMatchSetOutput) { + op := &request.Operation{ + Name: opUpdateSqlInjectionMatchSet, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &waf.UpdateSqlInjectionMatchSetInput{} + } + + output = &waf.UpdateSqlInjectionMatchSetOutput{} + req = c.newRequest(op, input, output) + return +} + +// UpdateSqlInjectionMatchSet API operation for AWS WAF Regional. +// +// Inserts or deletes SqlInjectionMatchTuple objects (filters) in a SqlInjectionMatchSet. +// For each SqlInjectionMatchTuple object, you specify the following values: +// +// * Action: Whether to insert the object into or delete the object from +// the array. To change a SqlInjectionMatchTuple, you delete the existing +// object and add a new one. +// +// * FieldToMatch: The part of web requests that you want AWS WAF to inspect +// and, if you want AWS WAF to inspect a header, the name of the header. +// +// * TextTransformation: Which text transformation, if any, to perform on +// the web request before inspecting the request for snippets of malicious +// SQL code. +// +// You use SqlInjectionMatchSet objects to specify which CloudFront requests +// you want to allow, block, or count. For example, if you're receiving requests +// that contain snippets of SQL code in the query string and you want to block +// the requests, you can create a SqlInjectionMatchSet with the applicable settings, +// and then configure AWS WAF to block the requests. +// +// To create and configure a SqlInjectionMatchSet, perform the following steps: +// +// Submit a CreateSqlInjectionMatchSet request. +// +// Use GetChangeToken to get the change token that you provide in the ChangeToken +// parameter of an UpdateIPSet request. +// +// Submit an UpdateSqlInjectionMatchSet request to specify the parts of web +// requests that you want AWS WAF to inspect for snippets of SQL code. +// +// For more information about how to use the AWS WAF API to allow or block HTTP +// requests, see the AWS WAF Developer Guide (http://docs.aws.amazon.com/waf/latest/developerguide/). +// +// 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 WAF Regional's +// API operation UpdateSqlInjectionMatchSet for usage and error information. +// +// Returned Error Codes: +// * ErrCodeWAFInternalErrorException "WAFInternalErrorException" +// The operation failed because of a system problem, even though the request +// was valid. Retry your request. +// +// * ErrCodeWAFInvalidAccountException "WAFInvalidAccountException" +// The operation failed because you tried to create, update, or delete an object +// by using an invalid account identifier. +// +// * ErrCodeWAFInvalidOperationException "WAFInvalidOperationException" +// The operation failed because there was nothing to do. For example: +// +// * You tried to remove a Rule from a WebACL, but the Rule isn't in the +// specified WebACL. +// +// * You tried to remove an IP address from an IPSet, but the IP address +// isn't in the specified IPSet. +// +// * You tried to remove a ByteMatchTuple from a ByteMatchSet, but the ByteMatchTuple +// isn't in the specified WebACL. +// +// * You tried to add a Rule to a WebACL, but the Rule already exists in +// the specified WebACL. +// +// * You tried to add an IP address to an IPSet, but the IP address already +// exists in the specified IPSet. +// +// * You tried to add a ByteMatchTuple to a ByteMatchSet, but the ByteMatchTuple +// already exists in the specified WebACL. +// +// * ErrCodeWAFInvalidParameterException "WAFInvalidParameterException" +// The operation failed because AWS WAF didn't recognize a parameter in the +// request. For example: +// +// * You specified an invalid parameter name. +// +// * You specified an invalid value. +// +// * You tried to update an object (ByteMatchSet, IPSet, Rule, or WebACL) +// using an action other than INSERT or DELETE. +// +// * You tried to create a WebACL with a DefaultActionType other than ALLOW, +// BLOCK, or COUNT. +// +// * You tried to update a WebACL with a WafActionType other than ALLOW, +// BLOCK, or COUNT. +// +// * You tried to update a ByteMatchSet with a FieldToMatchType other than +// HEADER, QUERY_STRING, or URI. +// +// * You tried to update a ByteMatchSet with a Field of HEADER but no value +// for Data. +// +// * Your request references an ARN that is malformed, or corresponds to +// a resource with which a web ACL cannot be associated. +// +// * ErrCodeWAFNonexistentContainerException "WAFNonexistentContainerException" +// The operation failed because you tried to add an object to or delete an object +// from another object that doesn't exist. For example: +// +// * You tried to add a Rule to or delete a Rule from a WebACL that doesn't +// exist. +// +// * You tried to add a ByteMatchSet to or delete a ByteMatchSet from a Rule +// that doesn't exist. +// +// * You tried to add an IP address to or delete an IP address from an IPSet +// that doesn't exist. +// +// * You tried to add a ByteMatchTuple to or delete a ByteMatchTuple from +// a ByteMatchSet that doesn't exist. +// +// * ErrCodeWAFNonexistentItemException "WAFNonexistentItemException" +// The operation failed because the referenced object doesn't exist. +// +// * ErrCodeWAFStaleDataException "WAFStaleDataException" +// The operation failed because you tried to create, update, or delete an object +// by using a change token that has already been used. +// +// * ErrCodeWAFLimitsExceededException "WAFLimitsExceededException" +// The operation exceeds a resource limit, for example, the maximum number of +// WebACL objects that you can create for an AWS account. For more information, +// see Limits (http://docs.aws.amazon.com/waf/latest/developerguide/limits.html) +// in the AWS WAF Developer Guide. +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/waf-regional-2016-11-28/UpdateSqlInjectionMatchSet +func (c *WAFRegional) UpdateSqlInjectionMatchSet(input *waf.UpdateSqlInjectionMatchSetInput) (*waf.UpdateSqlInjectionMatchSetOutput, error) { + req, out := c.UpdateSqlInjectionMatchSetRequest(input) + return out, req.Send() +} + +// UpdateSqlInjectionMatchSetWithContext is the same as UpdateSqlInjectionMatchSet with the addition of +// the ability to pass a context and additional request options. +// +// See UpdateSqlInjectionMatchSet 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 *WAFRegional) UpdateSqlInjectionMatchSetWithContext(ctx aws.Context, input *waf.UpdateSqlInjectionMatchSetInput, opts ...request.Option) (*waf.UpdateSqlInjectionMatchSetOutput, error) { + req, out := c.UpdateSqlInjectionMatchSetRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opUpdateWebACL = "UpdateWebACL" + +// UpdateWebACLRequest generates a "aws/request.Request" representing the +// client's request for the UpdateWebACL operation. The "output" return +// value can be used to capture response data after the request's "Send" method +// is called. +// +// See UpdateWebACL for usage and error information. +// +// Creating a request object using this method should be used when you want to inject +// custom logic into the request's lifecycle using a custom handler, or if you want to +// access properties on the request object before or after sending the request. If +// you just want the service response, call the UpdateWebACL method directly +// instead. +// +// Note: You must call the "Send" method on the returned request object in order +// to execute the request. +// +// // Example sending a request using the UpdateWebACLRequest method. +// req, resp := client.UpdateWebACLRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/waf-regional-2016-11-28/UpdateWebACL +func (c *WAFRegional) UpdateWebACLRequest(input *waf.UpdateWebACLInput) (req *request.Request, output *waf.UpdateWebACLOutput) { + op := &request.Operation{ + Name: opUpdateWebACL, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &waf.UpdateWebACLInput{} + } + + output = &waf.UpdateWebACLOutput{} + req = c.newRequest(op, input, output) + return +} + +// UpdateWebACL API operation for AWS WAF Regional. +// +// Inserts or deletes ActivatedRule objects in a WebACL. Each Rule identifies +// web requests that you want to allow, block, or count. When you update a WebACL, +// you specify the following values: +// +// * A default action for the WebACL, either ALLOW or BLOCK. AWS WAF performs +// the default action if a request doesn't match the criteria in any of the +// Rules in a WebACL. +// +// * The Rules that you want to add and/or delete. If you want to replace +// one Rule with another, you delete the existing Rule and add the new one. +// +// * For each Rule, whether you want AWS WAF to allow requests, block requests, +// or count requests that match the conditions in the Rule. +// +// * The order in which you want AWS WAF to evaluate the Rules in a WebACL. +// If you add more than one Rule to a WebACL, AWS WAF evaluates each request +// against the Rules in order based on the value of Priority. (The Rule that +// has the lowest value for Priority is evaluated first.) When a web request +// matches all of the predicates (such as ByteMatchSets and IPSets) in a +// Rule, AWS WAF immediately takes the corresponding action, allow or block, +// and doesn't evaluate the request against the remaining Rules in the WebACL, +// if any. +// +// To create and configure a WebACL, perform the following steps: +// +// Create and update the predicates that you want to include in Rules. For more +// information, see CreateByteMatchSet, UpdateByteMatchSet, CreateIPSet, UpdateIPSet, +// CreateSqlInjectionMatchSet, and UpdateSqlInjectionMatchSet. +// +// Create and update the Rules that you want to include in the WebACL. For more +// information, see CreateRule and UpdateRule. +// +// Create a WebACL. See CreateWebACL. +// +// Use GetChangeToken to get the change token that you provide in the ChangeToken +// parameter of an UpdateWebACL request. +// +// Submit an UpdateWebACL request to specify the Rules that you want to include +// in the WebACL, to specify the default action, and to associate the WebACL +// with a CloudFront distribution. +// +// For more information about how to use the AWS WAF API to allow or block HTTP +// requests, see the AWS WAF Developer Guide (http://docs.aws.amazon.com/waf/latest/developerguide/). +// +// 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 WAF Regional's +// API operation UpdateWebACL for usage and error information. +// +// Returned Error Codes: +// * ErrCodeWAFStaleDataException "WAFStaleDataException" +// The operation failed because you tried to create, update, or delete an object +// by using a change token that has already been used. +// +// * ErrCodeWAFInternalErrorException "WAFInternalErrorException" +// The operation failed because of a system problem, even though the request +// was valid. Retry your request. +// +// * ErrCodeWAFInvalidAccountException "WAFInvalidAccountException" +// The operation failed because you tried to create, update, or delete an object +// by using an invalid account identifier. +// +// * ErrCodeWAFInvalidOperationException "WAFInvalidOperationException" +// The operation failed because there was nothing to do. For example: +// +// * You tried to remove a Rule from a WebACL, but the Rule isn't in the +// specified WebACL. +// +// * You tried to remove an IP address from an IPSet, but the IP address +// isn't in the specified IPSet. +// +// * You tried to remove a ByteMatchTuple from a ByteMatchSet, but the ByteMatchTuple +// isn't in the specified WebACL. +// +// * You tried to add a Rule to a WebACL, but the Rule already exists in +// the specified WebACL. +// +// * You tried to add an IP address to an IPSet, but the IP address already +// exists in the specified IPSet. +// +// * You tried to add a ByteMatchTuple to a ByteMatchSet, but the ByteMatchTuple +// already exists in the specified WebACL. +// +// * ErrCodeWAFInvalidParameterException "WAFInvalidParameterException" +// The operation failed because AWS WAF didn't recognize a parameter in the +// request. For example: +// +// * You specified an invalid parameter name. +// +// * You specified an invalid value. +// +// * You tried to update an object (ByteMatchSet, IPSet, Rule, or WebACL) +// using an action other than INSERT or DELETE. +// +// * You tried to create a WebACL with a DefaultActionType other than ALLOW, +// BLOCK, or COUNT. +// +// * You tried to update a WebACL with a WafActionType other than ALLOW, +// BLOCK, or COUNT. +// +// * You tried to update a ByteMatchSet with a FieldToMatchType other than +// HEADER, QUERY_STRING, or URI. +// +// * You tried to update a ByteMatchSet with a Field of HEADER but no value +// for Data. +// +// * Your request references an ARN that is malformed, or corresponds to +// a resource with which a web ACL cannot be associated. +// +// * ErrCodeWAFNonexistentContainerException "WAFNonexistentContainerException" +// The operation failed because you tried to add an object to or delete an object +// from another object that doesn't exist. For example: +// +// * You tried to add a Rule to or delete a Rule from a WebACL that doesn't +// exist. +// +// * You tried to add a ByteMatchSet to or delete a ByteMatchSet from a Rule +// that doesn't exist. +// +// * You tried to add an IP address to or delete an IP address from an IPSet +// that doesn't exist. +// +// * You tried to add a ByteMatchTuple to or delete a ByteMatchTuple from +// a ByteMatchSet that doesn't exist. +// +// * ErrCodeWAFNonexistentItemException "WAFNonexistentItemException" +// The operation failed because the referenced object doesn't exist. +// +// * ErrCodeWAFReferencedItemException "WAFReferencedItemException" +// The operation failed because you tried to delete an object that is still +// in use. For example: +// +// * You tried to delete a ByteMatchSet that is still referenced by a Rule. +// +// * You tried to delete a Rule that is still referenced by a WebACL. +// +// * ErrCodeWAFLimitsExceededException "WAFLimitsExceededException" +// The operation exceeds a resource limit, for example, the maximum number of +// WebACL objects that you can create for an AWS account. For more information, +// see Limits (http://docs.aws.amazon.com/waf/latest/developerguide/limits.html) +// in the AWS WAF Developer Guide. +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/waf-regional-2016-11-28/UpdateWebACL +func (c *WAFRegional) UpdateWebACL(input *waf.UpdateWebACLInput) (*waf.UpdateWebACLOutput, error) { + req, out := c.UpdateWebACLRequest(input) + return out, req.Send() +} + +// UpdateWebACLWithContext is the same as UpdateWebACL with the addition of +// the ability to pass a context and additional request options. +// +// See UpdateWebACL 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 *WAFRegional) UpdateWebACLWithContext(ctx aws.Context, input *waf.UpdateWebACLInput, opts ...request.Option) (*waf.UpdateWebACLOutput, error) { + req, out := c.UpdateWebACLRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opUpdateXssMatchSet = "UpdateXssMatchSet" + +// UpdateXssMatchSetRequest generates a "aws/request.Request" representing the +// client's request for the UpdateXssMatchSet operation. The "output" return +// value can be used to capture response data after the request's "Send" method +// is called. +// +// See UpdateXssMatchSet for usage and error information. +// +// Creating a request object using this method should be used when you want to inject +// custom logic into the request's lifecycle using a custom handler, or if you want to +// access properties on the request object before or after sending the request. If +// you just want the service response, call the UpdateXssMatchSet method directly +// instead. +// +// Note: You must call the "Send" method on the returned request object in order +// to execute the request. +// +// // Example sending a request using the UpdateXssMatchSetRequest method. +// req, resp := client.UpdateXssMatchSetRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/waf-regional-2016-11-28/UpdateXssMatchSet +func (c *WAFRegional) UpdateXssMatchSetRequest(input *waf.UpdateXssMatchSetInput) (req *request.Request, output *waf.UpdateXssMatchSetOutput) { + op := &request.Operation{ + Name: opUpdateXssMatchSet, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &waf.UpdateXssMatchSetInput{} + } + + output = &waf.UpdateXssMatchSetOutput{} + req = c.newRequest(op, input, output) + return +} + +// UpdateXssMatchSet API operation for AWS WAF Regional. +// +// Inserts or deletes XssMatchTuple objects (filters) in an XssMatchSet. For +// each XssMatchTuple object, you specify the following values: +// +// * Action: Whether to insert the object into or delete the object from +// the array. To change a XssMatchTuple, you delete the existing object and +// add a new one. +// +// * FieldToMatch: The part of web requests that you want AWS WAF to inspect +// and, if you want AWS WAF to inspect a header, the name of the header. +// +// * TextTransformation: Which text transformation, if any, to perform on +// the web request before inspecting the request for cross-site scripting +// attacks. +// +// You use XssMatchSet objects to specify which CloudFront requests you want +// to allow, block, or count. For example, if you're receiving requests that +// contain cross-site scripting attacks in the request body and you want to +// block the requests, you can create an XssMatchSet with the applicable settings, +// and then configure AWS WAF to block the requests. +// +// To create and configure an XssMatchSet, perform the following steps: +// +// Submit a CreateXssMatchSet request. +// +// Use GetChangeToken to get the change token that you provide in the ChangeToken +// parameter of an UpdateIPSet request. +// +// Submit an UpdateXssMatchSet request to specify the parts of web requests +// that you want AWS WAF to inspect for cross-site scripting attacks. +// +// For more information about how to use the AWS WAF API to allow or block HTTP +// requests, see the AWS WAF Developer Guide (http://docs.aws.amazon.com/waf/latest/developerguide/). +// +// 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 WAF Regional's +// API operation UpdateXssMatchSet for usage and error information. +// +// Returned Error Codes: +// * ErrCodeWAFInternalErrorException "WAFInternalErrorException" +// The operation failed because of a system problem, even though the request +// was valid. Retry your request. +// +// * ErrCodeWAFInvalidAccountException "WAFInvalidAccountException" +// The operation failed because you tried to create, update, or delete an object +// by using an invalid account identifier. +// +// * ErrCodeWAFInvalidOperationException "WAFInvalidOperationException" +// The operation failed because there was nothing to do. For example: +// +// * You tried to remove a Rule from a WebACL, but the Rule isn't in the +// specified WebACL. +// +// * You tried to remove an IP address from an IPSet, but the IP address +// isn't in the specified IPSet. +// +// * You tried to remove a ByteMatchTuple from a ByteMatchSet, but the ByteMatchTuple +// isn't in the specified WebACL. +// +// * You tried to add a Rule to a WebACL, but the Rule already exists in +// the specified WebACL. +// +// * You tried to add an IP address to an IPSet, but the IP address already +// exists in the specified IPSet. +// +// * You tried to add a ByteMatchTuple to a ByteMatchSet, but the ByteMatchTuple +// already exists in the specified WebACL. +// +// * ErrCodeWAFInvalidParameterException "WAFInvalidParameterException" +// The operation failed because AWS WAF didn't recognize a parameter in the +// request. For example: +// +// * You specified an invalid parameter name. +// +// * You specified an invalid value. +// +// * You tried to update an object (ByteMatchSet, IPSet, Rule, or WebACL) +// using an action other than INSERT or DELETE. +// +// * You tried to create a WebACL with a DefaultActionType other than ALLOW, +// BLOCK, or COUNT. +// +// * You tried to update a WebACL with a WafActionType other than ALLOW, +// BLOCK, or COUNT. +// +// * You tried to update a ByteMatchSet with a FieldToMatchType other than +// HEADER, QUERY_STRING, or URI. +// +// * You tried to update a ByteMatchSet with a Field of HEADER but no value +// for Data. +// +// * Your request references an ARN that is malformed, or corresponds to +// a resource with which a web ACL cannot be associated. +// +// * ErrCodeWAFNonexistentContainerException "WAFNonexistentContainerException" +// The operation failed because you tried to add an object to or delete an object +// from another object that doesn't exist. For example: +// +// * You tried to add a Rule to or delete a Rule from a WebACL that doesn't +// exist. +// +// * You tried to add a ByteMatchSet to or delete a ByteMatchSet from a Rule +// that doesn't exist. +// +// * You tried to add an IP address to or delete an IP address from an IPSet +// that doesn't exist. +// +// * You tried to add a ByteMatchTuple to or delete a ByteMatchTuple from +// a ByteMatchSet that doesn't exist. +// +// * ErrCodeWAFNonexistentItemException "WAFNonexistentItemException" +// The operation failed because the referenced object doesn't exist. +// +// * ErrCodeWAFStaleDataException "WAFStaleDataException" +// The operation failed because you tried to create, update, or delete an object +// by using a change token that has already been used. +// +// * ErrCodeWAFLimitsExceededException "WAFLimitsExceededException" +// The operation exceeds a resource limit, for example, the maximum number of +// WebACL objects that you can create for an AWS account. For more information, +// see Limits (http://docs.aws.amazon.com/waf/latest/developerguide/limits.html) +// in the AWS WAF Developer Guide. +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/waf-regional-2016-11-28/UpdateXssMatchSet +func (c *WAFRegional) UpdateXssMatchSet(input *waf.UpdateXssMatchSetInput) (*waf.UpdateXssMatchSetOutput, error) { + req, out := c.UpdateXssMatchSetRequest(input) + return out, req.Send() +} + +// UpdateXssMatchSetWithContext is the same as UpdateXssMatchSet with the addition of +// the ability to pass a context and additional request options. +// +// See UpdateXssMatchSet 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 *WAFRegional) UpdateXssMatchSetWithContext(ctx aws.Context, input *waf.UpdateXssMatchSetInput, opts ...request.Option) (*waf.UpdateXssMatchSetOutput, error) { + req, out := c.UpdateXssMatchSetRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +// Please also see https://docs.aws.amazon.com/goto/WebAPI/waf-regional-2016-11-28/AssociateWebACLRequest +type AssociateWebACLInput struct { + _ struct{} `type:"structure"` + + // The ARN (Amazon Resource Name) of the resource to be protected. + // + // ResourceArn is a required field + ResourceArn *string `min:"1" type:"string" required:"true"` + + // A unique identifier (ID) for the web ACL. + // + // WebACLId is a required field + WebACLId *string `min:"1" type:"string" required:"true"` +} + +// String returns the string representation +func (s AssociateWebACLInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s AssociateWebACLInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *AssociateWebACLInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "AssociateWebACLInput"} + if s.ResourceArn == nil { + invalidParams.Add(request.NewErrParamRequired("ResourceArn")) + } + if s.ResourceArn != nil && len(*s.ResourceArn) < 1 { + invalidParams.Add(request.NewErrParamMinLen("ResourceArn", 1)) + } + if s.WebACLId == nil { + invalidParams.Add(request.NewErrParamRequired("WebACLId")) + } + if s.WebACLId != nil && len(*s.WebACLId) < 1 { + invalidParams.Add(request.NewErrParamMinLen("WebACLId", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetResourceArn sets the ResourceArn field's value. +func (s *AssociateWebACLInput) SetResourceArn(v string) *AssociateWebACLInput { + s.ResourceArn = &v + return s +} + +// SetWebACLId sets the WebACLId field's value. +func (s *AssociateWebACLInput) SetWebACLId(v string) *AssociateWebACLInput { + s.WebACLId = &v + return s +} + +// Please also see https://docs.aws.amazon.com/goto/WebAPI/waf-regional-2016-11-28/AssociateWebACLResponse +type AssociateWebACLOutput struct { + _ struct{} `type:"structure"` +} + +// String returns the string representation +func (s AssociateWebACLOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s AssociateWebACLOutput) GoString() string { + return s.String() +} + +// Please also see https://docs.aws.amazon.com/goto/WebAPI/waf-regional-2016-11-28/DisassociateWebACLRequest +type DisassociateWebACLInput struct { + _ struct{} `type:"structure"` + + // The ARN (Amazon Resource Name) of the resource from which the web ACL is + // being removed. + // + // ResourceArn is a required field + ResourceArn *string `min:"1" type:"string" required:"true"` +} + +// String returns the string representation +func (s DisassociateWebACLInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DisassociateWebACLInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *DisassociateWebACLInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DisassociateWebACLInput"} + if s.ResourceArn == nil { + invalidParams.Add(request.NewErrParamRequired("ResourceArn")) + } + if s.ResourceArn != nil && len(*s.ResourceArn) < 1 { + invalidParams.Add(request.NewErrParamMinLen("ResourceArn", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetResourceArn sets the ResourceArn field's value. +func (s *DisassociateWebACLInput) SetResourceArn(v string) *DisassociateWebACLInput { + s.ResourceArn = &v + return s +} + +// Please also see https://docs.aws.amazon.com/goto/WebAPI/waf-regional-2016-11-28/DisassociateWebACLResponse +type DisassociateWebACLOutput struct { + _ struct{} `type:"structure"` +} + +// String returns the string representation +func (s DisassociateWebACLOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DisassociateWebACLOutput) GoString() string { + return s.String() +} + +// Please also see https://docs.aws.amazon.com/goto/WebAPI/waf-regional-2016-11-28/GetWebACLForResourceRequest +type GetWebACLForResourceInput struct { + _ struct{} `type:"structure"` + + // The ARN (Amazon Resource Name) of the resource for which to get the web ACL. + // + // ResourceArn is a required field + ResourceArn *string `min:"1" type:"string" required:"true"` +} + +// String returns the string representation +func (s GetWebACLForResourceInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s GetWebACLForResourceInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *GetWebACLForResourceInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "GetWebACLForResourceInput"} + if s.ResourceArn == nil { + invalidParams.Add(request.NewErrParamRequired("ResourceArn")) + } + if s.ResourceArn != nil && len(*s.ResourceArn) < 1 { + invalidParams.Add(request.NewErrParamMinLen("ResourceArn", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetResourceArn sets the ResourceArn field's value. +func (s *GetWebACLForResourceInput) SetResourceArn(v string) *GetWebACLForResourceInput { + s.ResourceArn = &v + return s +} + +// Please also see https://docs.aws.amazon.com/goto/WebAPI/waf-regional-2016-11-28/GetWebACLForResourceResponse +type GetWebACLForResourceOutput struct { + _ struct{} `type:"structure"` + + // Information about the web ACL that you specified in the GetWebACLForResource + // request. If there is no associated resource, a null WebACLSummary is returned. + WebACLSummary *waf.WebACLSummary `type:"structure"` +} + +// String returns the string representation +func (s GetWebACLForResourceOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s GetWebACLForResourceOutput) GoString() string { + return s.String() +} + +// SetWebACLSummary sets the WebACLSummary field's value. +func (s *GetWebACLForResourceOutput) SetWebACLSummary(v *waf.WebACLSummary) *GetWebACLForResourceOutput { + s.WebACLSummary = v + return s +} + +// Please also see https://docs.aws.amazon.com/goto/WebAPI/waf-regional-2016-11-28/ListResourcesForWebACLRequest +type ListResourcesForWebACLInput struct { + _ struct{} `type:"structure"` + + // The unique identifier (ID) of the web ACL for which to list the associated + // resources. + // + // WebACLId is a required field + WebACLId *string `min:"1" type:"string" required:"true"` +} + +// String returns the string representation +func (s ListResourcesForWebACLInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ListResourcesForWebACLInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *ListResourcesForWebACLInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "ListResourcesForWebACLInput"} + if s.WebACLId == nil { + invalidParams.Add(request.NewErrParamRequired("WebACLId")) + } + if s.WebACLId != nil && len(*s.WebACLId) < 1 { + invalidParams.Add(request.NewErrParamMinLen("WebACLId", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetWebACLId sets the WebACLId field's value. +func (s *ListResourcesForWebACLInput) SetWebACLId(v string) *ListResourcesForWebACLInput { + s.WebACLId = &v + return s +} + +// Please also see https://docs.aws.amazon.com/goto/WebAPI/waf-regional-2016-11-28/ListResourcesForWebACLResponse +type ListResourcesForWebACLOutput struct { + _ struct{} `type:"structure"` + + // An array of ARNs (Amazon Resource Names) of the resources associated with + // the specified web ACL. An array with zero elements is returned if there are + // no resources associated with the web ACL. + ResourceArns []*string `type:"list"` +} + +// String returns the string representation +func (s ListResourcesForWebACLOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ListResourcesForWebACLOutput) GoString() string { + return s.String() +} + +// SetResourceArns sets the ResourceArns field's value. +func (s *ListResourcesForWebACLOutput) SetResourceArns(v []*string) *ListResourcesForWebACLOutput { + s.ResourceArns = v + return s +} + +const ( + // ChangeActionInsert is a ChangeAction enum value + ChangeActionInsert = "INSERT" + + // ChangeActionDelete is a ChangeAction enum value + ChangeActionDelete = "DELETE" +) + +const ( + // ChangeTokenStatusProvisioned is a ChangeTokenStatus enum value + ChangeTokenStatusProvisioned = "PROVISIONED" + + // ChangeTokenStatusPending is a ChangeTokenStatus enum value + ChangeTokenStatusPending = "PENDING" + + // ChangeTokenStatusInsync is a ChangeTokenStatus enum value + ChangeTokenStatusInsync = "INSYNC" +) + +const ( + // ComparisonOperatorEq is a ComparisonOperator enum value + ComparisonOperatorEq = "EQ" + + // ComparisonOperatorNe is a ComparisonOperator enum value + ComparisonOperatorNe = "NE" + + // ComparisonOperatorLe is a ComparisonOperator enum value + ComparisonOperatorLe = "LE" + + // ComparisonOperatorLt is a ComparisonOperator enum value + ComparisonOperatorLt = "LT" + + // ComparisonOperatorGe is a ComparisonOperator enum value + ComparisonOperatorGe = "GE" + + // ComparisonOperatorGt is a ComparisonOperator enum value + ComparisonOperatorGt = "GT" +) + +const ( + // IPSetDescriptorTypeIpv4 is a IPSetDescriptorType enum value + IPSetDescriptorTypeIpv4 = "IPV4" + + // IPSetDescriptorTypeIpv6 is a IPSetDescriptorType enum value + IPSetDescriptorTypeIpv6 = "IPV6" +) + +const ( + // MatchFieldTypeUri is a MatchFieldType enum value + MatchFieldTypeUri = "URI" + + // MatchFieldTypeQueryString is a MatchFieldType enum value + MatchFieldTypeQueryString = "QUERY_STRING" + + // MatchFieldTypeHeader is a MatchFieldType enum value + MatchFieldTypeHeader = "HEADER" + + // MatchFieldTypeMethod is a MatchFieldType enum value + MatchFieldTypeMethod = "METHOD" + + // MatchFieldTypeBody is a MatchFieldType enum value + MatchFieldTypeBody = "BODY" +) + +const ( + // ParameterExceptionFieldChangeAction is a ParameterExceptionField enum value + ParameterExceptionFieldChangeAction = "CHANGE_ACTION" + + // ParameterExceptionFieldWafAction is a ParameterExceptionField enum value + ParameterExceptionFieldWafAction = "WAF_ACTION" + + // ParameterExceptionFieldPredicateType is a ParameterExceptionField enum value + ParameterExceptionFieldPredicateType = "PREDICATE_TYPE" + + // ParameterExceptionFieldIpsetType is a ParameterExceptionField enum value + ParameterExceptionFieldIpsetType = "IPSET_TYPE" + + // ParameterExceptionFieldByteMatchFieldType is a ParameterExceptionField enum value + ParameterExceptionFieldByteMatchFieldType = "BYTE_MATCH_FIELD_TYPE" + + // ParameterExceptionFieldSqlInjectionMatchFieldType is a ParameterExceptionField enum value + ParameterExceptionFieldSqlInjectionMatchFieldType = "SQL_INJECTION_MATCH_FIELD_TYPE" + + // ParameterExceptionFieldByteMatchTextTransformation is a ParameterExceptionField enum value + ParameterExceptionFieldByteMatchTextTransformation = "BYTE_MATCH_TEXT_TRANSFORMATION" + + // ParameterExceptionFieldByteMatchPositionalConstraint is a ParameterExceptionField enum value + ParameterExceptionFieldByteMatchPositionalConstraint = "BYTE_MATCH_POSITIONAL_CONSTRAINT" + + // ParameterExceptionFieldSizeConstraintComparisonOperator is a ParameterExceptionField enum value + ParameterExceptionFieldSizeConstraintComparisonOperator = "SIZE_CONSTRAINT_COMPARISON_OPERATOR" +) + +const ( + // ParameterExceptionReasonInvalidOption is a ParameterExceptionReason enum value + ParameterExceptionReasonInvalidOption = "INVALID_OPTION" + + // ParameterExceptionReasonIllegalCombination is a ParameterExceptionReason enum value + ParameterExceptionReasonIllegalCombination = "ILLEGAL_COMBINATION" +) + +const ( + // PositionalConstraintExactly is a PositionalConstraint enum value + PositionalConstraintExactly = "EXACTLY" + + // PositionalConstraintStartsWith is a PositionalConstraint enum value + PositionalConstraintStartsWith = "STARTS_WITH" + + // PositionalConstraintEndsWith is a PositionalConstraint enum value + PositionalConstraintEndsWith = "ENDS_WITH" + + // PositionalConstraintContains is a PositionalConstraint enum value + PositionalConstraintContains = "CONTAINS" + + // PositionalConstraintContainsWord is a PositionalConstraint enum value + PositionalConstraintContainsWord = "CONTAINS_WORD" +) + +const ( + // PredicateTypeIpmatch is a PredicateType enum value + PredicateTypeIpmatch = "IPMatch" + + // PredicateTypeByteMatch is a PredicateType enum value + PredicateTypeByteMatch = "ByteMatch" + + // PredicateTypeSqlInjectionMatch is a PredicateType enum value + PredicateTypeSqlInjectionMatch = "SqlInjectionMatch" + + // PredicateTypeSizeConstraint is a PredicateType enum value + PredicateTypeSizeConstraint = "SizeConstraint" + + // PredicateTypeXssMatch is a PredicateType enum value + PredicateTypeXssMatch = "XssMatch" +) + +const ( + // TextTransformationNone is a TextTransformation enum value + TextTransformationNone = "NONE" + + // TextTransformationCompressWhiteSpace is a TextTransformation enum value + TextTransformationCompressWhiteSpace = "COMPRESS_WHITE_SPACE" + + // TextTransformationHtmlEntityDecode is a TextTransformation enum value + TextTransformationHtmlEntityDecode = "HTML_ENTITY_DECODE" + + // TextTransformationLowercase is a TextTransformation enum value + TextTransformationLowercase = "LOWERCASE" + + // TextTransformationCmdLine is a TextTransformation enum value + TextTransformationCmdLine = "CMD_LINE" + + // TextTransformationUrlDecode is a TextTransformation enum value + TextTransformationUrlDecode = "URL_DECODE" +) + +const ( + // WafActionTypeBlock is a WafActionType enum value + WafActionTypeBlock = "BLOCK" + + // WafActionTypeAllow is a WafActionType enum value + WafActionTypeAllow = "ALLOW" + + // WafActionTypeCount is a WafActionType enum value + WafActionTypeCount = "COUNT" +) diff --git a/vendor/github.com/aws/aws-sdk-go/service/wafregional/doc.go b/vendor/github.com/aws/aws-sdk-go/service/wafregional/doc.go new file mode 100644 index 000000000..0e8126553 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/service/wafregional/doc.go @@ -0,0 +1,88 @@ +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. + +// Package wafregional provides the client and types for making API +// requests to AWS WAF Regional. +// +// This is the AWS WAF Regional API Reference for using AWS WAF with Elastic +// Load Balancing (ELB) Application Load Balancers. The AWS WAF actions and +// data types listed in the reference are available for protecting Application +// Load Balancers. You can use these actions and data types by means of the +// endpoints listed in AWS Regions and Endpoints (http://docs.aws.amazon.com/general/latest/gr/rande.html#waf_region). +// This guide is for developers who need detailed information about the AWS +// WAF API actions, data types, and errors. For detailed information about AWS +// WAF features and an overview of how to use the AWS WAF API, see the AWS WAF +// Developer Guide (http://docs.aws.amazon.com/waf/latest/developerguide/). +// +// See https://docs.aws.amazon.com/goto/WebAPI/waf-regional-2016-11-28 for more information on this service. +// +// See wafregional package documentation for more information. +// https://docs.aws.amazon.com/sdk-for-go/api/service/wafregional/ +// +// Using the Client +// +// To use the client for AWS WAF Regional you will first need +// to create a new instance of it. +// +// When creating a client for an AWS service you'll first need to have a Session +// already created. The Session provides configuration that can be shared +// between multiple service clients. Additional configuration can be applied to +// the Session and service's client when they are constructed. The aws package's +// Config type contains several fields such as Region for the AWS Region the +// client should make API requests too. The optional Config value can be provided +// as the variadic argument for Sessions and client creation. +// +// Once the service's client is created you can use it to make API requests the +// AWS service. These clients are safe to use concurrently. +// +// // Create a session to share configuration, and load external configuration. +// sess := session.Must(session.NewSession()) +// +// // Create the service's client with the session. +// svc := wafregional.New(sess) +// +// See the SDK's documentation for more information on how to use service clients. +// https://docs.aws.amazon.com/sdk-for-go/api/ +// +// See aws package's Config type for more information on configuration options. +// https://docs.aws.amazon.com/sdk-for-go/api/aws/#Config +// +// See the AWS WAF Regional client WAFRegional for more +// information on creating the service's client. +// https://docs.aws.amazon.com/sdk-for-go/api/service/wafregional/#New +// +// Once the client is created you can make an API request to the service. +// Each API method takes a input parameter, and returns the service response +// and an error. +// +// The API method will document which error codes the service can be returned +// by the operation if the service models the API operation's errors. These +// errors will also be available as const strings prefixed with "ErrCode". +// +// result, err := svc.AssociateWebACL(params) +// if err != nil { +// // Cast err to awserr.Error to handle specific error codes. +// aerr, ok := err.(awserr.Error) +// if ok && aerr.Code() == { +// // Specific error code handling +// } +// return err +// } +// +// fmt.Println("AssociateWebACL result:") +// fmt.Println(result) +// +// Using the Client with Context +// +// The service's client also provides methods to make API requests with a Context +// value. This allows you to control the timeout, and cancellation of pending +// requests. These methods also take request Option as variadic parameter to apply +// additional configuration to the API request. +// +// ctx := context.Background() +// +// result, err := svc.AssociateWebACLWithContext(ctx, params) +// +// See the request package documentation for more information on using Context pattern +// with the SDK. +// https://docs.aws.amazon.com/sdk-for-go/api/aws/request/ +package wafregional diff --git a/vendor/github.com/aws/aws-sdk-go/service/wafregional/errors.go b/vendor/github.com/aws/aws-sdk-go/service/wafregional/errors.go new file mode 100644 index 000000000..77000526a --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/service/wafregional/errors.go @@ -0,0 +1,155 @@ +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. + +package wafregional + +const ( + + // ErrCodeWAFDisallowedNameException for service response error code + // "WAFDisallowedNameException". + // + // The name specified is invalid. + ErrCodeWAFDisallowedNameException = "WAFDisallowedNameException" + + // ErrCodeWAFInternalErrorException for service response error code + // "WAFInternalErrorException". + // + // The operation failed because of a system problem, even though the request + // was valid. Retry your request. + ErrCodeWAFInternalErrorException = "WAFInternalErrorException" + + // ErrCodeWAFInvalidAccountException for service response error code + // "WAFInvalidAccountException". + // + // The operation failed because you tried to create, update, or delete an object + // by using an invalid account identifier. + ErrCodeWAFInvalidAccountException = "WAFInvalidAccountException" + + // ErrCodeWAFInvalidOperationException for service response error code + // "WAFInvalidOperationException". + // + // The operation failed because there was nothing to do. For example: + // + // * You tried to remove a Rule from a WebACL, but the Rule isn't in the + // specified WebACL. + // + // * You tried to remove an IP address from an IPSet, but the IP address + // isn't in the specified IPSet. + // + // * You tried to remove a ByteMatchTuple from a ByteMatchSet, but the ByteMatchTuple + // isn't in the specified WebACL. + // + // * You tried to add a Rule to a WebACL, but the Rule already exists in + // the specified WebACL. + // + // * You tried to add an IP address to an IPSet, but the IP address already + // exists in the specified IPSet. + // + // * You tried to add a ByteMatchTuple to a ByteMatchSet, but the ByteMatchTuple + // already exists in the specified WebACL. + ErrCodeWAFInvalidOperationException = "WAFInvalidOperationException" + + // ErrCodeWAFInvalidParameterException for service response error code + // "WAFInvalidParameterException". + // + // The operation failed because AWS WAF didn't recognize a parameter in the + // request. For example: + // + // * You specified an invalid parameter name. + // + // * You specified an invalid value. + // + // * You tried to update an object (ByteMatchSet, IPSet, Rule, or WebACL) + // using an action other than INSERT or DELETE. + // + // * You tried to create a WebACL with a DefaultActionType other than ALLOW, + // BLOCK, or COUNT. + // + // * You tried to update a WebACL with a WafActionType other than ALLOW, + // BLOCK, or COUNT. + // + // * You tried to update a ByteMatchSet with a FieldToMatchType other than + // HEADER, QUERY_STRING, or URI. + // + // * You tried to update a ByteMatchSet with a Field of HEADER but no value + // for Data. + // + // * Your request references an ARN that is malformed, or corresponds to + // a resource with which a web ACL cannot be associated. + ErrCodeWAFInvalidParameterException = "WAFInvalidParameterException" + + // ErrCodeWAFLimitsExceededException for service response error code + // "WAFLimitsExceededException". + // + // The operation exceeds a resource limit, for example, the maximum number of + // WebACL objects that you can create for an AWS account. For more information, + // see Limits (http://docs.aws.amazon.com/waf/latest/developerguide/limits.html) + // in the AWS WAF Developer Guide. + ErrCodeWAFLimitsExceededException = "WAFLimitsExceededException" + + // ErrCodeWAFNonEmptyEntityException for service response error code + // "WAFNonEmptyEntityException". + // + // The operation failed because you tried to delete an object that isn't empty. + // For example: + // + // * You tried to delete a WebACL that still contains one or more Rule objects. + // + // * You tried to delete a Rule that still contains one or more ByteMatchSet + // objects or other predicates. + // + // * You tried to delete a ByteMatchSet that contains one or more ByteMatchTuple + // objects. + // + // * You tried to delete an IPSet that references one or more IP addresses. + ErrCodeWAFNonEmptyEntityException = "WAFNonEmptyEntityException" + + // ErrCodeWAFNonexistentContainerException for service response error code + // "WAFNonexistentContainerException". + // + // The operation failed because you tried to add an object to or delete an object + // from another object that doesn't exist. For example: + // + // * You tried to add a Rule to or delete a Rule from a WebACL that doesn't + // exist. + // + // * You tried to add a ByteMatchSet to or delete a ByteMatchSet from a Rule + // that doesn't exist. + // + // * You tried to add an IP address to or delete an IP address from an IPSet + // that doesn't exist. + // + // * You tried to add a ByteMatchTuple to or delete a ByteMatchTuple from + // a ByteMatchSet that doesn't exist. + ErrCodeWAFNonexistentContainerException = "WAFNonexistentContainerException" + + // ErrCodeWAFNonexistentItemException for service response error code + // "WAFNonexistentItemException". + // + // The operation failed because the referenced object doesn't exist. + ErrCodeWAFNonexistentItemException = "WAFNonexistentItemException" + + // ErrCodeWAFReferencedItemException for service response error code + // "WAFReferencedItemException". + // + // The operation failed because you tried to delete an object that is still + // in use. For example: + // + // * You tried to delete a ByteMatchSet that is still referenced by a Rule. + // + // * You tried to delete a Rule that is still referenced by a WebACL. + ErrCodeWAFReferencedItemException = "WAFReferencedItemException" + + // ErrCodeWAFStaleDataException for service response error code + // "WAFStaleDataException". + // + // The operation failed because you tried to create, update, or delete an object + // by using a change token that has already been used. + ErrCodeWAFStaleDataException = "WAFStaleDataException" + + // ErrCodeWAFUnavailableEntityException for service response error code + // "WAFUnavailableEntityException". + // + // The operation failed because the entity referenced is temporarily unavailable. + // Retry your request. + ErrCodeWAFUnavailableEntityException = "WAFUnavailableEntityException" +) diff --git a/vendor/github.com/aws/aws-sdk-go/service/wafregional/service.go b/vendor/github.com/aws/aws-sdk-go/service/wafregional/service.go new file mode 100644 index 000000000..8f0e70947 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/service/wafregional/service.go @@ -0,0 +1,95 @@ +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. + +package wafregional + +import ( + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/client" + "github.com/aws/aws-sdk-go/aws/client/metadata" + "github.com/aws/aws-sdk-go/aws/request" + "github.com/aws/aws-sdk-go/aws/signer/v4" + "github.com/aws/aws-sdk-go/private/protocol/jsonrpc" +) + +// WAFRegional provides the API operation methods for making requests to +// AWS WAF Regional. See this package's package overview docs +// for details on the service. +// +// WAFRegional methods are safe to use concurrently. It is not safe to +// modify mutate any of the struct's properties though. +type WAFRegional struct { + *client.Client +} + +// Used for custom client initialization logic +var initClient func(*client.Client) + +// Used for custom request initialization logic +var initRequest func(*request.Request) + +// Service information constants +const ( + ServiceName = "waf-regional" // Service endpoint prefix API calls made to. + EndpointsID = ServiceName // Service ID for Regions and Endpoints metadata. +) + +// New creates a new instance of the WAFRegional client with a session. +// If additional configuration is needed for the client instance use the optional +// aws.Config parameter to add your extra config. +// +// Example: +// // Create a WAFRegional client from just a session. +// svc := wafregional.New(mySession) +// +// // Create a WAFRegional client with additional configuration +// svc := wafregional.New(mySession, aws.NewConfig().WithRegion("us-west-2")) +func New(p client.ConfigProvider, cfgs ...*aws.Config) *WAFRegional { + c := p.ClientConfig(EndpointsID, cfgs...) + return newClient(*c.Config, c.Handlers, c.Endpoint, c.SigningRegion, c.SigningName) +} + +// newClient creates, initializes and returns a new service client instance. +func newClient(cfg aws.Config, handlers request.Handlers, endpoint, signingRegion, signingName string) *WAFRegional { + svc := &WAFRegional{ + Client: client.New( + cfg, + metadata.ClientInfo{ + ServiceName: ServiceName, + SigningName: signingName, + SigningRegion: signingRegion, + Endpoint: endpoint, + APIVersion: "2016-11-28", + JSONVersion: "1.1", + TargetPrefix: "AWSWAF_Regional_20161128", + }, + handlers, + ), + } + + // Handlers + svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler) + svc.Handlers.Build.PushBackNamed(jsonrpc.BuildHandler) + svc.Handlers.Unmarshal.PushBackNamed(jsonrpc.UnmarshalHandler) + svc.Handlers.UnmarshalMeta.PushBackNamed(jsonrpc.UnmarshalMetaHandler) + svc.Handlers.UnmarshalError.PushBackNamed(jsonrpc.UnmarshalErrorHandler) + + // Run custom client initialization if present + if initClient != nil { + initClient(svc.Client) + } + + return svc +} + +// newRequest creates a new request for a WAFRegional operation and runs any +// custom request initialization. +func (c *WAFRegional) newRequest(op *request.Operation, params, data interface{}) *request.Request { + req := c.NewRequest(op, params, data) + + // Run custom request initialization if present + if initRequest != nil { + initRequest(req) + } + + return req +} diff --git a/vendor/github.com/denverdino/aliyungo/common/client.go b/vendor/github.com/denverdino/aliyungo/common/client.go index 69a9c3d1e..d186ebd82 100755 --- a/vendor/github.com/denverdino/aliyungo/common/client.go +++ b/vendor/github.com/denverdino/aliyungo/common/client.go @@ -13,6 +13,14 @@ import ( "github.com/denverdino/aliyungo/util" ) +// RemovalPolicy.N add index to array item +// RemovalPolicy=["a", "b"] => RemovalPolicy.1="a" RemovalPolicy.2="b" +type FlattenArray []string + +// string contains underline which will be replaced with dot +// SystemDisk_Category => SystemDisk.Category +type UnderlineString string + // A Client represents a client of ECS services type Client struct { AccessKeyId string //Access Key Id @@ -167,6 +175,75 @@ func (client *Client) Invoke(action string, args interface{}, response interface return nil } +// Invoke sends the raw HTTP request for ECS services +func (client *Client) InvokeByFlattenMethod(action string, args interface{}, response interface{}) error { + + request := Request{} + request.init(client.version, action, client.AccessKeyId) + + query := util.ConvertToQueryValues(request) + + util.SetQueryValueByFlattenMethod(args, &query) + + // Sign request + signature := util.CreateSignatureForRequest(ECSRequestMethod, &query, client.AccessKeySecret) + + // Generate the request URL + requestURL := client.endpoint + "?" + query.Encode() + "&Signature=" + url.QueryEscape(signature) + + httpReq, err := http.NewRequest(ECSRequestMethod, requestURL, nil) + + if err != nil { + return GetClientError(err) + } + + // TODO move to util and add build val flag + httpReq.Header.Set("X-SDK-Client", `AliyunGO/`+Version+client.businessInfo) + + t0 := time.Now() + httpResp, err := client.httpClient.Do(httpReq) + t1 := time.Now() + if err != nil { + return GetClientError(err) + } + statusCode := httpResp.StatusCode + + if client.debug { + log.Printf("Invoke %s %s %d (%v)", ECSRequestMethod, requestURL, statusCode, t1.Sub(t0)) + } + + defer httpResp.Body.Close() + body, err := ioutil.ReadAll(httpResp.Body) + + if err != nil { + return GetClientError(err) + } + + if client.debug { + var prettyJSON bytes.Buffer + err = json.Indent(&prettyJSON, body, "", " ") + log.Println(string(prettyJSON.Bytes())) + } + + if statusCode >= 400 && statusCode <= 599 { + errorResponse := ErrorResponse{} + err = json.Unmarshal(body, &errorResponse) + ecsError := &Error{ + ErrorResponse: errorResponse, + StatusCode: statusCode, + } + return ecsError + } + + err = json.Unmarshal(body, response) + //log.Printf("%++v", response) + if err != nil { + return GetClientError(err) + } + + return nil +} + // Invoke sends the raw HTTP request for ECS services //改进了一下上面那个方法,可以使用各种Http方法 //2017.1.30 增加了一个path参数,用来拓展访问的地址 diff --git a/vendor/github.com/denverdino/aliyungo/common/endpoints.xml b/vendor/github.com/denverdino/aliyungo/common/endpoints.xml index 8e781ac46..4079bcd2b 100644 --- a/vendor/github.com/denverdino/aliyungo/common/endpoints.xml +++ b/vendor/github.com/denverdino/aliyungo/common/endpoints.xml @@ -32,7 +32,6 @@ Smssms.aliyuncs.com Jaqjaq.aliyuncs.com HPChpc.aliyuncs.com - Kmskms.cn-hangzhou.aliyuncs.com Locationlocation.aliyuncs.com ChargingServicechargingservice.aliyuncs.com Msgmsg-inner.aliyuncs.com @@ -63,11 +62,9 @@ PTSpts.aliyuncs.com Qualitycheckqualitycheck.aliyuncs.com M-kvstorem-kvstore.aliyuncs.com - CloudAPIapigateway.cn-hangzhou.aliyuncs.com HighDDosyd-highddos-cn-hangzhou.aliyuncs.com CmsSiteMonitorsitemonitor.aliyuncs.com Rdsrds.aliyuncs.com - Mtsmts.cn-hangzhou.aliyuncs.com BatchComputebatchCompute.aliyuncs.com CFcf.aliyuncs.com Drdsdrds.aliyuncs.com @@ -127,7 +124,7 @@ Smssms.aliyuncs.com Jaqjaq.aliyuncs.com CScs.aliyuncs.com - Kmskms.cn-hangzhou.aliyuncs.com + Kmskms.cn-hongkong.aliyuncs.com Locationlocation.aliyuncs.com Msgmsg-inner.aliyuncs.com ChargingServicechargingservice.aliyuncs.com @@ -158,11 +155,11 @@ Qualitycheckqualitycheck.aliyuncs.com Bssbss.aliyuncs.com Ubsmsubsms.aliyuncs.com - CloudAPIapigateway.cn-hangzhou.aliyuncs.com + CloudAPIapigateway.cn-hongkong.aliyuncs.com Stssts.aliyuncs.com CmsSiteMonitorsitemonitor.aliyuncs.com Aceace.cn-hangzhou.aliyuncs.com - Mtsmts.cn-hangzhou.aliyuncs.com + Mtsmts.cn-hongkong.aliyuncs.com Location-innerlocation-inner.aliyuncs.com CFcf.aliyuncs.com Acsacs.aliyun-inc.com @@ -235,7 +232,6 @@ Smssms.aliyuncs.com Drdsdrds.aliyuncs.com HPChpc.aliyuncs.com - Kmskms.cn-hangzhou.aliyuncs.com Locationlocation.aliyuncs.com Msgmsg-inner.aliyuncs.com ChargingServicechargingservice.aliyuncs.com @@ -265,9 +261,8 @@ Qualitycheckqualitycheck.aliyuncs.com Bssbss.aliyuncs.com M-kvstorem-kvstore.aliyuncs.com - CloudAPIapigateway.cn-hangzhou.aliyuncs.com Aceace.cn-hangzhou.aliyuncs.com - Mtsmts.cn-hangzhou.aliyuncs.com + Mtsmts.cn-qingdao.aliyuncs.com CFcf.aliyuncs.com Httpdnshttpdns-api.aliyuncs.com Location-innerlocation-inner.aliyuncs.com @@ -330,6 +325,7 @@ cn-shanghai + ARMSarms.cn-shanghai.aliyuncs.com Riskrisk-cn-hangzhou.aliyuncs.com COScos.aliyuncs.com HPChpc.aliyuncs.com @@ -371,11 +367,11 @@ Qualitycheckqualitycheck.aliyuncs.com M-kvstorem-kvstore.aliyuncs.com Apigatewayapigateway.cn-shanghai.aliyuncs.com - CloudAPIapigateway.cn-hangzhou.aliyuncs.com + CloudAPIapigateway.cn-shanghai.aliyuncs.com Stssts.aliyuncs.com Vpcvpc.aliyuncs.com Aceace.cn-hangzhou.aliyuncs.com - Mtsmts.cn-hangzhou.aliyuncs.com + Mtsmts.cn-shanghai.aliyuncs.com Ddsmongodb.aliyuncs.com CFcf.aliyuncs.com Acsacs.aliyun-inc.com @@ -403,6 +399,7 @@ Essess.aliyuncs.com Ossoss-cn-shanghai.aliyuncs.com YundunDdosinner-yundun-ddos.cn-hangzhou.aliyuncs.com + vodvod.cn-shanghai.aliyuncs.com @@ -419,7 +416,6 @@ Smssms.aliyuncs.com Salessales.cn-hangzhou.aliyuncs.com HPChpc.aliyuncs.com - Kmskms.cn-hangzhou.aliyuncs.com Locationlocation.aliyuncs.com Msgmsg-inner.aliyuncs.com ChargingServicechargingservice.aliyuncs.com @@ -447,10 +443,9 @@ PTSpts.aliyuncs.com Qualitycheckqualitycheck.aliyuncs.com M-kvstorem-kvstore.aliyuncs.com - CloudAPIapigateway.cn-hangzhou.aliyuncs.com Stssts.aliyuncs.com Aceace.cn-hangzhou.aliyuncs.com - Mtsmts.cn-hangzhou.aliyuncs.com + Mtsmts.cn-shenzhen.aliyuncs.com CFcf.aliyuncs.com Httpdnshttpdns-api.aliyuncs.com Greengreen.aliyuncs.com @@ -504,7 +499,6 @@ Jaqjaq.aliyuncs.com Pushcloudpush.aliyuncs.com Alidnsalidns.aliyuncs.com - Kmskms.cn-hangzhou.aliyuncs.com Locationlocation.aliyuncs.com Msgmsg-inner.aliyuncs.com ChargingServicechargingservice.aliyuncs.com @@ -534,11 +528,10 @@ PTSpts.aliyuncs.com Qualitycheckqualitycheck.aliyuncs.com Ubsmsubsms.aliyuncs.com - CloudAPIapigateway.cn-hangzhou.aliyuncs.com HighDDosyd-highddos-cn-hangzhou.aliyuncs.com CmsSiteMonitorsitemonitor.aliyuncs.com Rdsrds.aliyuncs.com - Mtsmts.cn-hangzhou.aliyuncs.com + Mtsmts.us-west-1.aliyuncs.com CFcf.aliyuncs.com Acsacs.aliyun-inc.com Httpdnshttpdns-api.aliyuncs.com @@ -579,7 +572,6 @@ Smssms.aliyuncs.com Drdsdrds.aliyuncs.com HPChpc.aliyuncs.com - Kmskms.cn-hangzhou.aliyuncs.com Locationlocation.aliyuncs.com ChargingServicechargingservice.aliyuncs.com Msgmsg-inner.aliyuncs.com @@ -610,10 +602,9 @@ PTSpts.aliyuncs.com Qualitycheckqualitycheck.aliyuncs.com Ubsmsubsms.aliyuncs.com - CloudAPIapigateway.cn-hangzhou.aliyuncs.com HighDDosyd-highddos-cn-hangzhou.aliyuncs.com Rdsrds.aliyuncs.com - Mtsmts.cn-hangzhou.aliyuncs.com + Mtsmts.cn-shanghai.aliyuncs.com CFcf.aliyuncs.com Httpdnshttpdns-api.aliyuncs.com Location-innerlocation-inner.aliyuncs.com @@ -652,6 +643,7 @@ cn-hangzhou + ARMSarms.cn-hangzhou.aliyuncs.com CScs.aliyuncs.com COScos.aliyuncs.com Essess.aliyuncs.com @@ -743,7 +735,6 @@ Smssms.aliyuncs.com Drdsdrds.aliyuncs.com CScs.aliyuncs.com - Kmskms.cn-hangzhou.aliyuncs.com Locationlocation.aliyuncs.com ChargingServicechargingservice.aliyuncs.com Msgmsg-inner.aliyuncs.com @@ -774,10 +765,9 @@ PTSpts.aliyuncs.com Qualitycheckqualitycheck.aliyuncs.com Ubsmsubsms.aliyuncs.com - CloudAPIapigateway.cn-hangzhou.aliyuncs.com Stssts.aliyuncs.com Rdsrds.aliyuncs.com - Mtsmts.cn-hangzhou.aliyuncs.com + Mtsmts.cn-beijing.aliyuncs.com Location-innerlocation-inner.aliyuncs.com CFcf.aliyuncs.com Httpdnshttpdns-api.aliyuncs.com @@ -819,6 +809,7 @@ cn-shenzhen + ARMSarms.cn-shenzhen.aliyuncs.com CScs.aliyuncs.com COScos.aliyuncs.com Onsons.aliyuncs.com @@ -859,7 +850,7 @@ Stssts.aliyuncs.com Vpcvpc.aliyuncs.com Rdsrds.aliyuncs.com - Mtsmts.cn-hangzhou.aliyuncs.com + Mtsmts.cn-shenzhen.aliyuncs.com Oascn-shenzhen.oas.aliyuncs.com CFcf.aliyuncs.com Acsacs.aliyun-inc.com @@ -908,7 +899,6 @@ Smssms.aliyuncs.com Jaqjaq.aliyuncs.com Dtsdts.aliyuncs.com - Kmskms.cn-hangzhou.aliyuncs.com Locationlocation.aliyuncs.com Essess.aliyuncs.com R-kvstorer-kvstore-cn-hangzhou.aliyuncs.com @@ -937,7 +927,7 @@ CloudAPIapigateway.cn-qingdao.aliyuncs.com Stssts.aliyuncs.com Rdsrds.aliyuncs.com - Mtsmts.cn-hangzhou.aliyuncs.com + Mtsmts.cn-qingdao.aliyuncs.com Location-innerlocation-inner.aliyuncs.com CFcf.aliyuncs.com Acsacs.aliyun-inc.com @@ -1003,6 +993,7 @@ cn-beijing + ARMSarms.cn-beijing.aliyuncs.com CScs.aliyuncs.com COScos.aliyuncs.com Jaqjaq.aliyuncs.com @@ -1046,12 +1037,12 @@ PTSpts.aliyuncs.com M-kvstorem-kvstore.aliyuncs.com Apigatewayapigateway.cn-beijing.aliyuncs.com - CloudAPIapigateway.cn-hangzhou.aliyuncs.com + CloudAPIapigateway.cn-beijing.aliyuncs.com Kmskms.cn-beijing.aliyuncs.com HighDDosyd-highddos-cn-hangzhou.aliyuncs.com CmsSiteMonitorsitemonitor.aliyuncs.com Aceace.cn-hangzhou.aliyuncs.com - Mtsmts.cn-hangzhou.aliyuncs.com + Mtsmts.cn-beijing.aliyuncs.com CFcf.aliyuncs.com Acsacs.aliyun-inc.com Httpdnshttpdns-api.aliyuncs.com @@ -1077,6 +1068,7 @@ Yundunyundun-cn-hangzhou.aliyuncs.com Cdncdn.aliyuncs.com YundunDdosinner-yundun-ddos.cn-hangzhou.aliyuncs.com + vodvod.cn-beijing.aliyuncs.com @@ -1092,7 +1084,6 @@ Smssms.aliyuncs.com Salessales.cn-hangzhou.aliyuncs.com Dtsdts.aliyuncs.com - Kmskms.cn-hangzhou.aliyuncs.com Locationlocation.aliyuncs.com Msgmsg-inner.aliyuncs.com ChargingServicechargingservice.aliyuncs.com @@ -1122,7 +1113,6 @@ PTSpts.aliyuncs.com Qualitycheckqualitycheck.aliyuncs.com Ubsmsubsms.aliyuncs.com - CloudAPIapigateway.cn-hangzhou.aliyuncs.com Rdsrds.aliyuncs.com Mtsmts.cn-hangzhou.aliyuncs.com Location-innerlocation-inner.aliyuncs.com @@ -1180,7 +1170,6 @@ Smssms.aliyuncs.com Jaqjaq.aliyuncs.com Dtsdts.aliyuncs.com - Kmskms.cn-hangzhou.aliyuncs.com Locationlocation.aliyuncs.com Msgmsg-inner.aliyuncs.com ChargingServicechargingservice.aliyuncs.com @@ -1210,7 +1199,6 @@ PTSpts.aliyuncs.com Qualitycheckqualitycheck.aliyuncs.com M-kvstorem-kvstore.aliyuncs.com - CloudAPIapigateway.cn-hangzhou.aliyuncs.com Rdsrds.aliyuncs.com Mtsmts.cn-hangzhou.aliyuncs.com CFcf.aliyuncs.com @@ -1304,11 +1292,11 @@ Bssbss.aliyuncs.com Ubsmsubsms.aliyuncs.com Apigatewayapigateway.ap-southeast-1.aliyuncs.com - CloudAPIapigateway.cn-hangzhou.aliyuncs.com + CloudAPIapigateway.ap-southeast-1.aliyuncs.com Stssts.aliyuncs.com CmsSiteMonitorsitemonitor.aliyuncs.com Aceace.cn-hangzhou.aliyuncs.com - Mtsmts.cn-hangzhou.aliyuncs.com + Mtsmts.ap-southeast-1.aliyuncs.com CFcf.aliyuncs.com Crmcrm-cn-hangzhou.aliyuncs.com Location-innerlocation-inner.aliyuncs.com @@ -1348,4 +1336,14 @@ Slbslb.eu-central-1.aliyuncs.com - \ No newline at end of file + + cn-zhangjiakou + + Rdsrds.cn-zhangjiakou.aliyuncs.com + Ecsecs.cn-zhangjiakou.aliyuncs.com + Vpcvpc.cn-zhangjiakou.aliyuncs.com + Cmsmetrics.cn-hangzhou.aliyuncs.com + Slbslb.cn-zhangjiakou.aliyuncs.com + + + diff --git a/vendor/github.com/denverdino/aliyungo/ecs/forward_entry.go b/vendor/github.com/denverdino/aliyungo/ecs/forward_entry.go new file mode 100644 index 000000000..2a316e18e --- /dev/null +++ b/vendor/github.com/denverdino/aliyungo/ecs/forward_entry.go @@ -0,0 +1,104 @@ +package ecs + +import "github.com/denverdino/aliyungo/common" + +type CreateForwardEntryArgs struct { + RegionId common.Region + ForwardTableId string + ExternalIp string + ExternalPort string + IpProtocol string + InternalIp string + InternalPort string +} + +type CreateForwardEntryResponse struct { + common.Response + ForwardEntryId string +} + +type DescribeForwardTableEntriesArgs struct { + RegionId common.Region + ForwardTableId string + common.Pagination +} + +type ForwardTableEntrySetType struct { + RegionId common.Region + ExternalIp string + ExternalPort string + ForwardEntryId string + ForwardTableId string + InternalIp string + InternalPort string + IpProtocol string + Status string +} + +type DescribeForwardTableEntriesResponse struct { + common.Response + common.PaginationResult + ForwardTableEntries struct { + ForwardTableEntry []ForwardTableEntrySetType + } +} + +type ModifyForwardEntryArgs struct { + RegionId common.Region + ForwardTableId string + ForwardEntryId string + ExternalIp string + IpProtocol string + ExternalPort string + InternalIp string + InternalPort string +} + +type ModifyForwardEntryResponse struct { + common.Response +} + +type DeleteForwardEntryArgs struct { + RegionId common.Region + ForwardTableId string + ForwardEntryId string +} + +type DeleteForwardEntryResponse struct { + common.Response +} + +func (client *Client) CreateForwardEntry(args *CreateForwardEntryArgs) (resp *CreateForwardEntryResponse, err error) { + response := CreateForwardEntryResponse{} + err = client.Invoke("CreateForwardEntry", args, &response) + if err != nil { + return nil, err + } + return &response, err +} + +func (client *Client) DescribeForwardTableEntries(args *DescribeForwardTableEntriesArgs) (forwardTableEntries []ForwardTableEntrySetType, + pagination *common.PaginationResult, err error) { + + args.Validate() + response := DescribeForwardTableEntriesResponse{} + + err = client.Invoke("DescribeForwardTableEntries", args, &response) + + if err != nil { + return nil, nil, err + } + + return response.ForwardTableEntries.ForwardTableEntry, &response.PaginationResult, nil +} + +func (client *Client) ModifyForwardEntry(args *ModifyForwardEntryArgs) error { + response := ModifyForwardEntryResponse{} + return client.Invoke("ModifyForwardEntry", args, &response) +} + +func (client *Client) DeleteForwardEntry(args *DeleteForwardEntryArgs) error { + response := DeleteForwardEntryResponse{} + err := client.Invoke("DeleteForwardEntry", args, &response) + return err +} diff --git a/vendor/github.com/denverdino/aliyungo/ecs/vpcs.go b/vendor/github.com/denverdino/aliyungo/ecs/vpcs.go index 7a62857cd..80faf21ca 100644 --- a/vendor/github.com/denverdino/aliyungo/ecs/vpcs.go +++ b/vendor/github.com/denverdino/aliyungo/ecs/vpcs.go @@ -79,6 +79,7 @@ type VpcSetType struct { CidrBlock string VRouterId string Description string + IsDefault bool CreationTime util.ISO6801Time } diff --git a/vendor/github.com/denverdino/aliyungo/ecs/vswitches.go b/vendor/github.com/denverdino/aliyungo/ecs/vswitches.go index 8bf10394a..8a879ec80 100644 --- a/vendor/github.com/denverdino/aliyungo/ecs/vswitches.go +++ b/vendor/github.com/denverdino/aliyungo/ecs/vswitches.go @@ -77,6 +77,7 @@ type VSwitchSetType struct { AvailableIpAddressCount int Description string VSwitchName string + IsDefault bool CreationTime util.ISO6801Time } diff --git a/vendor/github.com/denverdino/aliyungo/ess/client.go b/vendor/github.com/denverdino/aliyungo/ess/client.go new file mode 100644 index 000000000..a2d486546 --- /dev/null +++ b/vendor/github.com/denverdino/aliyungo/ess/client.go @@ -0,0 +1,48 @@ +package ess + +import ( + "github.com/denverdino/aliyungo/common" + + "os" +) + +type Client struct { + common.Client +} + +const ( + // ESSDefaultEndpoint is the default API endpoint of ESS services + ESSDefaultEndpoint = "https://ess.aliyuncs.com" + ESSAPIVersion = "2014-08-28" + ESSServiceCode = "ess" +) + +// NewClient creates a new instance of RDS client +func NewClient(accessKeyId, accessKeySecret string) *Client { + endpoint := os.Getenv("ESS_ENDPOINT") + if endpoint == "" { + endpoint = ESSDefaultEndpoint + } + return NewClientWithEndpoint(endpoint, accessKeyId, accessKeySecret) +} + +func NewClientWithEndpoint(endpoint string, accessKeyId, accessKeySecret string) *Client { + client := &Client{} + client.Init(endpoint, ESSAPIVersion, accessKeyId, accessKeySecret) + return client +} + +func NewESSClient(accessKeyId, accessKeySecret string, regionID common.Region) *Client { + endpoint := os.Getenv("ESS_ENDPOINT") + if endpoint == "" { + endpoint = ESSDefaultEndpoint + } + + return NewClientWithRegion(endpoint, accessKeyId, accessKeySecret, regionID) +} + +func NewClientWithRegion(endpoint string, accessKeyId, accessKeySecret string, regionID common.Region) *Client { + client := &Client{} + client.NewInit(endpoint, ESSAPIVersion, accessKeyId, accessKeySecret, ESSServiceCode, regionID) + return client +} diff --git a/vendor/github.com/denverdino/aliyungo/ess/configuration.go b/vendor/github.com/denverdino/aliyungo/ess/configuration.go new file mode 100644 index 000000000..7fdcd187c --- /dev/null +++ b/vendor/github.com/denverdino/aliyungo/ess/configuration.go @@ -0,0 +1,127 @@ +package ess + +import ( + "github.com/denverdino/aliyungo/common" + "github.com/denverdino/aliyungo/ecs" +) + +type CreateScalingConfigurationArgs struct { + ScalingGroupId string + ImageId string + InstanceType string + IoOptimized ecs.IoOptimized + SecurityGroupId string + ScalingConfigurationName string + InternetChargeType common.InternetChargeType + InternetMaxBandwidthIn int + InternetMaxBandwidthOut int + SystemDisk_Category common.UnderlineString + SystemDisk_Size common.UnderlineString + DataDisk []DataDiskType +} + +type DataDiskType struct { + Category string + SnapshotId string + Device string + Size int +} + +type CreateScalingConfigurationResponse struct { + ScalingConfigurationId string + common.Response +} + +// CreateScalingConfiguration create scaling configuration +// +// You can read doc at https://help.aliyun.com/document_detail/25944.html?spm=5176.doc25942.6.625.KcE5ir +func (client *Client) CreateScalingConfiguration(args *CreateScalingConfigurationArgs) (resp *CreateScalingConfigurationResponse, err error) { + response := CreateScalingConfigurationResponse{} + err = client.InvokeByFlattenMethod("CreateScalingConfiguration", args, &response) + + if err != nil { + return nil, err + } + return &response, nil +} + +type DescribeScalingConfigurationsArgs struct { + RegionId common.Region + ScalingGroupId string + ScalingConfigurationId common.FlattenArray + ScalingConfigurationName common.FlattenArray + common.Pagination +} + +type DescribeScalingConfigurationsResponse struct { + common.Response + common.PaginationResult + ScalingConfigurations struct { + ScalingConfiguration []ScalingConfigurationItemType + } +} + +type ScalingConfigurationItemType struct { + ScalingConfigurationId string + ScalingConfigurationName string + ScalingGroupId string + ImageId string + InstanceType string + IoOptimized string + SecurityGroupId string + InternetChargeType string + LifecycleState LifecycleState + CreationTime string + InternetMaxBandwidthIn int + InternetMaxBandwidthOut int + SystemDiskCategory string + DataDisks struct { + DataDisk []DataDiskItemType + } +} + +type DataDiskItemType struct { + Size int + Category string + SnapshotId string + Device string +} + +// DescribeScalingConfigurations describes scaling configuration +// +// You can read doc at https://help.aliyun.com/document_detail/25945.html?spm=5176.doc25944.6.626.knG0zz +func (client *Client) DescribeScalingConfigurations(args *DescribeScalingConfigurationsArgs) (configs []ScalingConfigurationItemType, pagination *common.PaginationResult, err error) { + args.Validate() + response := DescribeScalingConfigurationsResponse{} + + err = client.InvokeByFlattenMethod("DescribeScalingConfigurations", args, &response) + + if err == nil { + return response.ScalingConfigurations.ScalingConfiguration, &response.PaginationResult, nil + } + + return nil, nil, err +} + +type DeleteScalingConfigurationArgs struct { + ScalingConfigurationId string + ScalingGroupId string + ImageId string +} + +type DeleteScalingConfigurationResponse struct { + common.Response +} + +// DeleteScalingConfiguration delete scaling configuration +// +// You can read doc at https://help.aliyun.com/document_detail/25946.html?spm=5176.doc25944.6.627.MjkuuL +func (client *Client) DeleteScalingConfiguration(args *DeleteScalingConfigurationArgs) (resp *DeleteScalingConfigurationResponse, err error) { + response := DeleteScalingConfigurationResponse{} + err = client.InvokeByFlattenMethod("DeleteScalingConfiguration", args, &response) + + if err != nil { + return nil, err + } + return &response, nil +} diff --git a/vendor/github.com/denverdino/aliyungo/ess/group.go b/vendor/github.com/denverdino/aliyungo/ess/group.go new file mode 100644 index 000000000..c24e074fd --- /dev/null +++ b/vendor/github.com/denverdino/aliyungo/ess/group.go @@ -0,0 +1,242 @@ +package ess + +import "github.com/denverdino/aliyungo/common" + +type LifecycleState string + +const ( + Active = LifecycleState("Active") + Inacitve = LifecycleState("Inacitve") + Deleting = LifecycleState("Deleting") + InService = LifecycleState("InService") + Pending = LifecycleState("Pending") + Removing = LifecycleState("Removing") +) + +type CreateScalingGroupArgs struct { + RegionId common.Region + ScalingGroupName string + LoadBalancerId string + VpcId string + VSwitchId string + MaxSize int + MinSize int + DefaultCooldown int + RemovalPolicy common.FlattenArray + DBInstanceId common.FlattenArray +} + +type CreateScalingGroupResponse struct { + common.Response + ScalingGroupId string +} + +// CreateScalingGroup create scaling group +// +// You can read doc at https://help.aliyun.com/document_detail/25936.html?spm=5176.doc25940.6.617.vm6LXF +func (client *Client) CreateScalingGroup(args *CreateScalingGroupArgs) (resp *CreateScalingGroupResponse, err error) { + response := CreateScalingGroupResponse{} + err = client.InvokeByFlattenMethod("CreateScalingGroup", args, &response) + + if err != nil { + return nil, err + } + return &response, nil +} + +type ModifyScalingGroupArgs struct { + ScalingGroupId string + ScalingGroupName string + ActiveScalingConfigurationId string + MinSize int + MaxSize int + DefaultCooldown int + RemovalPolicy common.FlattenArray +} + +type ModifyScalingGroupResponse struct { + common.Response +} + +// ModifyScalingGroup modify scaling group +// +// You can read doc at https://help.aliyun.com/document_detail/25937.html?spm=5176.doc25936.6.618.iwDcXT +func (client *Client) ModifyScalingGroup(args *ModifyScalingGroupArgs) (resp *ModifyScalingGroupResponse, err error) { + response := ModifyScalingGroupResponse{} + err = client.InvokeByFlattenMethod("ModifyScalingGroup", args, &response) + + if err != nil { + return nil, err + } + return &response, nil +} + +type DescribeScalingGroupsArgs struct { + RegionId common.Region + ScalingGroupId common.FlattenArray + ScalingGroupName common.FlattenArray + common.Pagination +} + +type DescribeInstancesResponse struct { + common.Response + common.PaginationResult + ScalingGroups struct { + ScalingGroup []ScalingGroupItemType + } +} + +type ScalingGroupItemType struct { + ScalingGroupId string + ScalingGroupName string + ActiveScalingConfigurationId string + RegionId string + LoadBalancerId string + VSwitchId string + CreationTime string + LifecycleState LifecycleState + MinSize int + MaxSize int + DefaultCooldown int + TotalCapacity int + ActiveCapacity int + PendingCapacity int + RemovingCapacity int + RemovalPolicies RemovalPolicySetType + DBInstanceIds DBInstanceIdSetType +} + +type RemovalPolicySetType struct { + RemovalPolicy []string +} + +type DBInstanceIdSetType struct { + DBInstanceId []string +} + +// DescribeScalingGroups describes scaling groups +// +// You can read doc at https://help.aliyun.com/document_detail/25938.html?spm=5176.doc25937.6.619.sUUOT7 +func (client *Client) DescribeScalingGroups(args *DescribeScalingGroupsArgs) (groups []ScalingGroupItemType, pagination *common.PaginationResult, err error) { + args.Validate() + response := DescribeInstancesResponse{} + + err = client.InvokeByFlattenMethod("DescribeScalingGroups", args, &response) + + if err == nil { + return response.ScalingGroups.ScalingGroup, &response.PaginationResult, nil + } + + return nil, nil, err +} + +type DescribeScalingInstancesArgs struct { + RegionId common.Region + ScalingGroupId string + ScalingConfigurationId string + HealthStatus string + CreationType string + LifecycleState LifecycleState + InstanceId common.FlattenArray + common.Pagination +} + +type DescribeScalingInstancesResponse struct { + common.Response + common.PaginationResult + ScalingInstances struct { + ScalingInstance []ScalingInstanceItemType + } +} + +type ScalingInstanceItemType struct { + InstanceId string + ScalingGroupId string + ScalingConfigurationId string + HealthStatus string + CreationTime string + CreationType string + LifecycleState LifecycleState +} + +// DescribeScalingInstances describes scaling instances +// +// You can read doc at https://help.aliyun.com/document_detail/25942.html?spm=5176.doc25941.6.623.2xA0Uj +func (client *Client) DescribeScalingInstances(args *DescribeScalingInstancesArgs) (instances []ScalingInstanceItemType, pagination *common.PaginationResult, err error) { + args.Validate() + response := DescribeScalingInstancesResponse{} + + err = client.InvokeByFlattenMethod("DescribeScalingInstances", args, &response) + + if err == nil { + return response.ScalingInstances.ScalingInstance, &response.PaginationResult, nil + } + + return nil, nil, err +} + +type EnableScalingGroupArgs struct { + ScalingGroupId string + ActiveScalingConfigurationId string + InstanceId common.FlattenArray +} + +type EnableScalingGroupResponse struct { + common.Response +} + +// EnableScalingGroup enable scaling group +// +// You can read doc at https://help.aliyun.com/document_detail/25939.html?spm=5176.doc25938.6.620.JiJhkx +func (client *Client) EnableScalingGroup(args *EnableScalingGroupArgs) (resp *EnableScalingGroupResponse, err error) { + response := EnableScalingGroupResponse{} + err = client.InvokeByFlattenMethod("EnableScalingGroup", args, &response) + + if err != nil { + return nil, err + } + return &response, nil +} + +type DisableScalingGroupArgs struct { + ScalingGroupId string +} + +type DisableScalingGroupResponse struct { + common.Response +} + +// DisableScalingGroup disable scaling group +// +// You can read doc at https://help.aliyun.com/document_detail/25940.html?spm=5176.doc25939.6.621.M8GuuY +func (client *Client) DisableScalingGroup(args *DisableScalingGroupArgs) (resp *DisableScalingGroupResponse, err error) { + response := DisableScalingGroupResponse{} + err = client.InvokeByFlattenMethod("DisableScalingGroup", args, &response) + + if err != nil { + return nil, err + } + return &response, nil +} + +type DeleteScalingGroupArgs struct { + ScalingGroupId string + ForceDelete bool +} + +type DeleteScalingGroupResponse struct { + common.Response +} + +// DeleteScalingGroup delete scaling group +// +// You can read doc at https://help.aliyun.com/document_detail/25941.html?spm=5176.doc25940.6.622.mRBCuw +func (client *Client) DeleteScalingGroup(args *DeleteScalingGroupArgs) (resp *DeleteScalingGroupResponse, err error) { + response := DeleteScalingGroupResponse{} + err = client.InvokeByFlattenMethod("DeleteScalingGroup", args, &response) + + if err != nil { + return nil, err + } + return &response, nil +} diff --git a/vendor/github.com/denverdino/aliyungo/ess/rule.go b/vendor/github.com/denverdino/aliyungo/ess/rule.go new file mode 100644 index 000000000..b6ce29002 --- /dev/null +++ b/vendor/github.com/denverdino/aliyungo/ess/rule.go @@ -0,0 +1,130 @@ +package ess + +import "github.com/denverdino/aliyungo/common" + +type AdjustmentType string + +const ( + QuantityChangeInCapacity = AdjustmentType("QuantityChangeInCapacity") + PercentChangeInCapacity = AdjustmentType("PercentChangeInCapacity") + TotalCapacity = AdjustmentType("TotalCapacity") +) + +type CreateScalingRuleArgs struct { + RegionId common.Region + ScalingGroupId string + AdjustmentType AdjustmentType + AdjustmentValue int + Cooldown int + ScalingRuleName string +} + +type CreateScalingRuleResponse struct { + common.Response + ScalingRuleId string + ScalingRuleAri string +} + +// CreateScalingRule create scaling rule +// +// You can read doc at https://help.aliyun.com/document_detail/25948.html?spm=5176.doc25944.6.629.FLkNnj +func (client *Client) CreateScalingRule(args *CreateScalingRuleArgs) (resp *CreateScalingRuleResponse, err error) { + response := CreateScalingRuleResponse{} + err = client.Invoke("CreateScalingRule", args, &response) + + if err != nil { + return nil, err + } + return &response, nil +} + +type ModifyScalingRuleArgs struct { + RegionId common.Region + ScalingRuleId string + AdjustmentType AdjustmentType + AdjustmentValue int + Cooldown int + ScalingRuleName string +} + +type ModifyScalingRuleResponse struct { + common.Response +} + +// ModifyScalingRule modify scaling rule +// +// You can read doc at https://help.aliyun.com/document_detail/25949.html?spm=5176.doc25948.6.630.HGN1va +func (client *Client) ModifyScalingRule(args *ModifyScalingRuleArgs) (resp *ModifyScalingRuleResponse, err error) { + response := ModifyScalingRuleResponse{} + err = client.Invoke("ModifyScalingRule", args, &response) + + if err != nil { + return nil, err + } + return &response, nil +} + +type DescribeScalingRulesArgs struct { + common.Pagination + RegionId common.Region + ScalingGroupId string + ScalingRuleId common.FlattenArray + ScalingRuleName common.FlattenArray + ScalingRuleAri common.FlattenArray +} + +type DescribeScalingRulesResponse struct { + common.Response + common.PaginationResult + ScalingRules struct { + ScalingRule []ScalingRuleItemType + } +} + +type ScalingRuleItemType struct { + ScalingRuleId string + ScalingGroupId string + ScalingRuleName string + AdjustmentType string + ScalingRuleAri string + Cooldown int + AdjustmentValue int +} + +// DescribeScalingRules describes scaling rules +// +// You can read doc at https://help.aliyun.com/document_detail/25950.html?spm=5176.doc25949.6.631.RwPguo +func (client *Client) DescribeScalingRules(args *DescribeScalingRulesArgs) (configs []ScalingRuleItemType, pagination *common.PaginationResult, err error) { + args.Validate() + response := DescribeScalingRulesResponse{} + + err = client.InvokeByFlattenMethod("DescribeScalingRules", args, &response) + + if err == nil { + return response.ScalingRules.ScalingRule, &response.PaginationResult, nil + } + + return nil, nil, err +} + +type DeleteScalingRuleArgs struct { + RegionId common.Region + ScalingRuleId string +} + +type DeleteScalingRuleResponse struct { + common.Response +} + +// DeleteScalingRule delete scaling rule +// +// You can read doc at https://help.aliyun.com/document_detail/25951.html?spm=5176.doc25950.6.632.HbPLMZ +func (client *Client) DeleteScalingRule(args *DeleteScalingRuleArgs) (resp *DeleteScalingRuleResponse, err error) { + response := DeleteScalingRuleResponse{} + err = client.InvokeByFlattenMethod("DeleteScalingRule", args, &response) + + if err != nil { + return nil, err + } + return &response, nil +} diff --git a/vendor/github.com/denverdino/aliyungo/ess/schedule.go b/vendor/github.com/denverdino/aliyungo/ess/schedule.go new file mode 100644 index 000000000..9da5a86e0 --- /dev/null +++ b/vendor/github.com/denverdino/aliyungo/ess/schedule.go @@ -0,0 +1,140 @@ +package ess + +import "github.com/denverdino/aliyungo/common" + +type RecurrenceType string + +const ( + Daily = RecurrenceType("Daily") + Weekly = RecurrenceType("Weekly") + Monthly = RecurrenceType("Monthly") +) + +type CreateScheduledTaskArgs struct { + RegionId common.Region + ScheduledAction string + LaunchTime string + ScheduledTaskName string + Description string + LaunchExpirationTime int + RecurrenceType RecurrenceType + RecurrenceValue string + RecurrenceEndTime string + TaskEnabled bool +} + +type CreateScheduledTaskResponse struct { + common.Response + ScheduledTaskId string +} + +// CreateScheduledTask create schedule task +// +// You can read doc at https://help.aliyun.com/document_detail/25957.html?spm=5176.doc25950.6.638.FfQ0BR +func (client *Client) CreateScheduledTask(args *CreateScheduledTaskArgs) (resp *CreateScheduledTaskResponse, err error) { + response := CreateScheduledTaskResponse{} + err = client.Invoke("CreateScheduledTask", args, &response) + + if err != nil { + return nil, err + } + return &response, nil +} + +type ModifyScheduledTaskArgs struct { + RegionId common.Region + ScheduledTaskId string + ScheduledAction string + LaunchTime string + ScheduledTaskName string + Description string + LaunchExpirationTime int + RecurrenceType RecurrenceType + RecurrenceValue string + RecurrenceEndTime string + TaskEnabled bool +} + +type ModifyScheduledTaskResponse struct { + common.Response +} + +// ModifyScheduledTask modify schedule task +// +// You can read doc at https://help.aliyun.com/document_detail/25958.html?spm=5176.doc25957.6.639.rgxQ1c +func (client *Client) ModifyScheduledTask(args *ModifyScheduledTaskArgs) (resp *ModifyScheduledTaskResponse, err error) { + response := ModifyScheduledTaskResponse{} + err = client.Invoke("ModifyScheduledTask", args, &response) + + if err != nil { + return nil, err + } + return &response, nil +} + +type DescribeScheduledTasksArgs struct { + RegionId common.Region + ScheduledTaskId common.FlattenArray + ScheduledTaskName common.FlattenArray + ScheduledAction common.FlattenArray + common.Pagination +} + +type DescribeScheduledTasksResponse struct { + common.Response + common.PaginationResult + ScheduledTasks struct { + ScheduledTask []ScheduledTaskItemType + } +} + +type ScheduledTaskItemType struct { + ScheduledTaskId string + ScheduledTaskName string + Description string + ScheduledAction string + LaunchTime string + RecurrenceType string + RecurrenceValue string + RecurrenceEndTime string + LaunchExpirationTime int + TaskEnabled bool +} + +// DescribeScheduledTasks describes scaling tasks +// +// You can read doc at https://help.aliyun.com/document_detail/25959.html?spm=5176.doc25958.6.640.cLccdR +func (client *Client) DescribeScheduledTasks(args *DescribeScheduledTasksArgs) (tasks []ScheduledTaskItemType, pagination *common.PaginationResult, err error) { + args.Validate() + response := DescribeScheduledTasksResponse{} + + err = client.InvokeByFlattenMethod("DescribeScheduledTasks", args, &response) + + if err == nil { + return response.ScheduledTasks.ScheduledTask, &response.PaginationResult, nil + } + + return nil, nil, err +} + +type DeleteScheduledTaskArgs struct { + RegionId common.Region + ScheduledTaskId string +} + +type DeleteScheduledTaskResponse struct { + common.Response +} + +// DeleteScheduledTask delete schedule task +// +// You can read doc at https://help.aliyun.com/document_detail/25960.html?spm=5176.doc25959.6.641.aGdNuW +func (client *Client) DeleteScheduledTask(args *DeleteScheduledTaskArgs) (resp *DeleteScheduledTaskResponse, err error) { + response := DeleteScheduledTaskResponse{} + err = client.Invoke("DeleteScheduledTask", args, &response) + + if err != nil { + return nil, err + } + return &response, nil +} diff --git a/vendor/github.com/denverdino/aliyungo/util/encoding.go b/vendor/github.com/denverdino/aliyungo/util/encoding.go index e545e069d..8cb588288 100644 --- a/vendor/github.com/denverdino/aliyungo/util/encoding.go +++ b/vendor/github.com/denverdino/aliyungo/util/encoding.go @@ -7,9 +7,26 @@ import ( "net/url" "reflect" "strconv" + "strings" "time" ) +// change instance=["a", "b"] +// to instance.1="a" instance.2="b" +func FlattenFn(fieldName string, field reflect.Value, values *url.Values) { + l := field.Len() + if l > 0 { + for i := 0; i < l; i++ { + str := field.Index(i).String() + values.Set(fieldName+"."+strconv.Itoa(i+1), str) + } + } +} + +func Underline2Dot(name string) string { + return strings.Replace(name, "_", ".", -1) +} + //ConvertToQueryValues converts the struct to url.Values func ConvertToQueryValues(ifc interface{}) url.Values { values := url.Values{} @@ -22,6 +39,10 @@ func SetQueryValues(ifc interface{}, values *url.Values) { setQueryValues(ifc, values, "") } +func SetQueryValueByFlattenMethod(ifc interface{}, values *url.Values) { + setQueryValuesByFlattenMethod(ifc, values, "") +} + func setQueryValues(i interface{}, values *url.Values, prefix string) { // add to support url.Values mapValues, ok := i.(url.Values) @@ -150,3 +171,144 @@ func setQueryValues(i interface{}, values *url.Values, prefix string) { } } } + +func setQueryValuesByFlattenMethod(i interface{}, values *url.Values, prefix string) { + // add to support url.Values + mapValues, ok := i.(url.Values) + if ok { + for k, _ := range mapValues { + values.Set(k, mapValues.Get(k)) + } + return + } + + elem := reflect.ValueOf(i) + if elem.Kind() == reflect.Ptr { + elem = elem.Elem() + } + elemType := elem.Type() + for i := 0; i < elem.NumField(); i++ { + + fieldName := elemType.Field(i).Name + anonymous := elemType.Field(i).Anonymous + field := elem.Field(i) + + // TODO Use Tag for validation + // tag := typ.Field(i).Tag.Get("tagname") + kind := field.Kind() + + if (kind == reflect.Ptr || kind == reflect.Array || kind == reflect.Slice || kind == reflect.Map || kind == reflect.Chan) && field.IsNil() { + continue + } + if kind == reflect.Ptr { + field = field.Elem() + kind = field.Kind() + } + + var value string + //switch field.Interface().(type) { + switch kind { + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + i := field.Int() + if i != 0 { + value = strconv.FormatInt(i, 10) + } + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: + i := field.Uint() + if i != 0 { + value = strconv.FormatUint(i, 10) + } + case reflect.Float32: + value = strconv.FormatFloat(field.Float(), 'f', 4, 32) + case reflect.Float64: + value = strconv.FormatFloat(field.Float(), 'f', 4, 64) + case reflect.Bool: + value = strconv.FormatBool(field.Bool()) + case reflect.String: + value = field.String() + case reflect.Map: + ifc := field.Interface() + m := ifc.(map[string]string) + if m != nil { + j := 0 + for k, v := range m { + j++ + keyName := fmt.Sprintf("%s.%d.Key", fieldName, j) + values.Set(keyName, k) + valueName := fmt.Sprintf("%s.%d.Value", fieldName, j) + values.Set(valueName, v) + } + } + case reflect.Slice: + if field.Type().Name() == "FlattenArray" { + FlattenFn(fieldName, field, values) + } else { + switch field.Type().Elem().Kind() { + case reflect.Uint8: + value = string(field.Bytes()) + case reflect.String: + l := field.Len() + if l > 0 { + strArray := make([]string, l) + for i := 0; i < l; i++ { + strArray[i] = field.Index(i).String() + } + bytes, err := json.Marshal(strArray) + if err == nil { + value = string(bytes) + } else { + log.Printf("Failed to convert JSON: %v", err) + } + } + default: + l := field.Len() + for j := 0; j < l; j++ { + prefixName := fmt.Sprintf("%s.%d.", fieldName, (j + 1)) + ifc := field.Index(j).Interface() + //log.Printf("%s : %v", prefixName, ifc) + if ifc != nil { + setQueryValuesByFlattenMethod(ifc, values, prefixName) + } + } + continue + } + } + + default: + switch field.Interface().(type) { + case ISO6801Time: + t := field.Interface().(ISO6801Time) + value = t.String() + case time.Time: + t := field.Interface().(time.Time) + value = GetISO8601TimeStamp(t) + default: + + ifc := field.Interface() + if ifc != nil { + if anonymous { + SetQueryValues(ifc, values) + } else { + prefixName := fieldName + "." + setQueryValuesByFlattenMethod(ifc, values, prefixName) + } + continue + } + } + } + if value != "" { + name := elemType.Field(i).Tag.Get("ArgName") + if name == "" { + name = fieldName + } + if prefix != "" { + name = prefix + name + } + // NOTE: here we will change name to underline style when the type is UnderlineString + if field.Type().Name() == "UnderlineString" { + name = Underline2Dot(name) + } + values.Set(name, value) + } + } +} diff --git a/vendor/github.com/gophercloud/gophercloud/openstack/networking/v2/extensions/security/rules/requests.go b/vendor/github.com/gophercloud/gophercloud/openstack/networking/v2/extensions/security/rules/requests.go index 77f7e37a4..59ba721d6 100644 --- a/vendor/github.com/gophercloud/gophercloud/openstack/networking/v2/extensions/security/rules/requests.go +++ b/vendor/github.com/gophercloud/gophercloud/openstack/networking/v2/extensions/security/rules/requests.go @@ -47,13 +47,31 @@ type RuleEtherType string // Constants useful for CreateOpts const ( - DirIngress RuleDirection = "ingress" - DirEgress RuleDirection = "egress" - ProtocolTCP RuleProtocol = "tcp" - ProtocolUDP RuleProtocol = "udp" - ProtocolICMP RuleProtocol = "icmp" - EtherType4 RuleEtherType = "IPv4" - EtherType6 RuleEtherType = "IPv6" + DirIngress RuleDirection = "ingress" + DirEgress RuleDirection = "egress" + EtherType4 RuleEtherType = "IPv4" + EtherType6 RuleEtherType = "IPv6" + ProtocolAH RuleProtocol = "ah" + ProtocolDCCP RuleProtocol = "dccp" + ProtocolEGP RuleProtocol = "egp" + ProtocolESP RuleProtocol = "esp" + ProtocolGRE RuleProtocol = "gre" + ProtocolICMP RuleProtocol = "icmp" + ProtocolIGMP RuleProtocol = "igmp" + ProtocolIPv6Encap RuleProtocol = "ipv6-encap" + ProtocolIPv6Frag RuleProtocol = "ipv6-frag" + ProtocolIPv6ICMP RuleProtocol = "ipv6-icmp" + ProtocolIPv6NoNxt RuleProtocol = "ipv6-nonxt" + ProtocolIPv6Opts RuleProtocol = "ipv6-opts" + ProtocolIPv6Route RuleProtocol = "ipv6-route" + ProtocolOSPF RuleProtocol = "ospf" + ProtocolPGM RuleProtocol = "pgm" + ProtocolRSVP RuleProtocol = "rsvp" + ProtocolSCTP RuleProtocol = "sctp" + ProtocolTCP RuleProtocol = "tcp" + ProtocolUDP RuleProtocol = "udp" + ProtocolUDPLite RuleProtocol = "udplite" + ProtocolVRRP RuleProtocol = "vrrp" ) // CreateOptsBuilder is what types must satisfy to be used as Create diff --git a/vendor/github.com/hashicorp/go-oracle-terraform/LICENSE b/vendor/github.com/hashicorp/go-oracle-terraform/LICENSE new file mode 100644 index 000000000..a612ad981 --- /dev/null +++ b/vendor/github.com/hashicorp/go-oracle-terraform/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/go-oracle-terraform/compute/acl.go b/vendor/github.com/hashicorp/go-oracle-terraform/compute/acl.go new file mode 100644 index 000000000..5543c4046 --- /dev/null +++ b/vendor/github.com/hashicorp/go-oracle-terraform/compute/acl.go @@ -0,0 +1,138 @@ +package compute + +// ACLsClient is a client for the ACLs functions of the Compute API. +type ACLsClient struct { + ResourceClient +} + +const ( + ACLDescription = "acl" + ACLContainerPath = "/network/v1/acl/" + ACLResourcePath = "/network/v1/acl" +) + +// ACLs obtains a ACLsClient which can be used to access to the +// ACLs functions of the Compute API +func (c *Client) ACLs() *ACLsClient { + return &ACLsClient{ + ResourceClient: ResourceClient{ + Client: c, + ResourceDescription: ACLDescription, + ContainerPath: ACLContainerPath, + ResourceRootPath: ACLResourcePath, + }} +} + +// ACLInfo describes an existing ACL. +type ACLInfo struct { + // Description of the ACL + Description string `json:"description"` + // Indicates whether the ACL is enabled + Enabled bool `json:"enabledFlag"` + // The name of the ACL + Name string `json:"name"` + // Tags associated with the ACL + Tags []string `json:"tags"` + // Uniform Resource Identifier for the ACL + URI string `json:"uri"` +} + +// CreateACLInput defines a ACL to be created. +type CreateACLInput struct { + // Description of the ACL + // Optional + Description string `json:"description"` + + // Enables or disables the ACL. Set to true by default. + //Set this to false to disable the ACL. + // Optional + Enabled bool `json:"enabledFlag"` + + // The name of the ACL to create. Object names can only contain alphanumeric, + // underscore, dash, and period characters. Names are case-sensitive. + // Required + Name string `json:"name"` + + // Strings that you can use to tag the ACL. + // Optional + Tags []string `json:"tags"` +} + +// CreateACL creates a new ACL. +func (c *ACLsClient) CreateACL(createInput *CreateACLInput) (*ACLInfo, error) { + createInput.Name = c.getQualifiedName(createInput.Name) + + var aclInfo ACLInfo + if err := c.createResource(createInput, &aclInfo); err != nil { + return nil, err + } + + return c.success(&aclInfo) +} + +// GetACLInput describes the ACL to get +type GetACLInput struct { + // The name of the ACL to query for + // Required + Name string `json:"name"` +} + +// GetACL retrieves the ACL with the given name. +func (c *ACLsClient) GetACL(getInput *GetACLInput) (*ACLInfo, error) { + var aclInfo ACLInfo + if err := c.getResource(getInput.Name, &aclInfo); err != nil { + return nil, err + } + + return c.success(&aclInfo) +} + +// UpdateACLInput describes a secruity rule to update +type UpdateACLInput struct { + // Description of the ACL + // Optional + Description string `json:"description"` + + // Enables or disables the ACL. Set to true by default. + //Set this to false to disable the ACL. + // Optional + Enabled bool `json:"enabledFlag"` + + // The name of the ACL to create. Object names can only contain alphanumeric, + // underscore, dash, and period characters. Names are case-sensitive. + // Required + Name string `json:"name"` + + // Strings that you can use to tag the ACL. + // Optional + Tags []string `json:"tags"` +} + +// UpdateACL modifies the properties of the ACL with the given name. +func (c *ACLsClient) UpdateACL(updateInput *UpdateACLInput) (*ACLInfo, error) { + updateInput.Name = c.getQualifiedName(updateInput.Name) + + var aclInfo ACLInfo + if err := c.updateResource(updateInput.Name, updateInput, &aclInfo); err != nil { + return nil, err + } + + return c.success(&aclInfo) +} + +// DeleteACLInput describes the ACL to delete +type DeleteACLInput struct { + // The name of the ACL to delete. + // Required + Name string `json:"name"` +} + +// DeleteACL deletes the ACL with the given name. +func (c *ACLsClient) DeleteACL(deleteInput *DeleteACLInput) error { + return c.deleteResource(deleteInput.Name) +} + +func (c *ACLsClient) success(aclInfo *ACLInfo) (*ACLInfo, error) { + aclInfo.Name = c.getUnqualifiedName(aclInfo.Name) + return aclInfo, nil +} diff --git a/vendor/github.com/hashicorp/go-oracle-terraform/compute/authentication.go b/vendor/github.com/hashicorp/go-oracle-terraform/compute/authentication.go new file mode 100644 index 000000000..d1b355087 --- /dev/null +++ b/vendor/github.com/hashicorp/go-oracle-terraform/compute/authentication.go @@ -0,0 +1,34 @@ +package compute + +import ( + "fmt" + "time" +) + +// AuthenticationReq represents the body of an authentication request. +type AuthenticationReq struct { + User string `json:"user"` + Password string `json:"password"` +} + +// Get a new auth cookie for the compute client +func (c *Client) getAuthenticationCookie() error { + req := AuthenticationReq{ + User: c.getUserName(), + Password: *c.password, + } + + rsp, err := c.executeRequest("POST", "/authenticate/", req) + if err != nil { + return err + } + + if len(rsp.Cookies()) == 0 { + return fmt.Errorf("No authentication cookie found in response %#v", rsp) + } + + c.debugLogString("Successfully authenticated to OPC") + c.authCookie = rsp.Cookies()[0] + c.cookieIssued = time.Now() + return nil +} diff --git a/vendor/github.com/hashicorp/go-oracle-terraform/compute/client.go b/vendor/github.com/hashicorp/go-oracle-terraform/compute/client.go new file mode 100644 index 000000000..5b2ee0473 --- /dev/null +++ b/vendor/github.com/hashicorp/go-oracle-terraform/compute/client.go @@ -0,0 +1,240 @@ +package compute + +import ( + "bytes" + "encoding/json" + "fmt" + "io" + "net/http" + "net/url" + "regexp" + "strings" + "time" + + "github.com/hashicorp/go-oracle-terraform/opc" +) + +const CMP_USERNAME = "/Compute-%s/%s" +const CMP_QUALIFIED_NAME = "%s/%s" + +// Client represents an authenticated compute client, with compute credentials and an api client. +type Client struct { + identityDomain *string + userName *string + password *string + apiEndpoint *url.URL + httpClient *http.Client + authCookie *http.Cookie + cookieIssued time.Time + logger opc.Logger + loglevel opc.LogLevelType +} + +func NewComputeClient(c *opc.Config) (*Client, error) { + // First create a client + client := &Client{ + identityDomain: c.IdentityDomain, + userName: c.Username, + password: c.Password, + apiEndpoint: c.APIEndpoint, + httpClient: c.HTTPClient, + loglevel: c.LogLevel, + } + + // Setup logger; defaults to stdout + if c.Logger == nil { + client.logger = opc.NewDefaultLogger() + } else { + client.logger = c.Logger + } + + // If LogLevel was not set to something different, + // double check for env var + if c.LogLevel == 0 { + client.loglevel = opc.LogLevel() + } + + if err := client.getAuthenticationCookie(); err != nil { + return nil, err + } + + return client, nil +} + +func (c *Client) executeRequest(method, path string, body interface{}) (*http.Response, error) { + // Parse URL Path + urlPath, err := url.Parse(path) + if err != nil { + return nil, err + } + + // Marshall request body + var requestBody io.ReadSeeker + var marshaled []byte + if body != nil { + marshaled, err = json.Marshal(body) + if err != nil { + return nil, err + } + requestBody = bytes.NewReader(marshaled) + } + + // Create request + req, err := http.NewRequest(method, c.formatURL(urlPath), requestBody) + if err != nil { + return nil, err + } + + debugReqString := fmt.Sprintf("HTTP %s Req (%s)", method, path) + if body != nil { + req.Header.Set("Content-Type", "application/oracle-compute-v3+json") + // Don't leak creds in STDERR + if path != "/authenticate/" { + debugReqString = fmt.Sprintf("%s:\n %s", debugReqString, string(marshaled)) + } + } + + // Log the request before the authentication cookie, so as not to leak credentials + c.debugLogString(debugReqString) + + // If we have an authentication cookie, let's authenticate, refreshing cookie if need be + if c.authCookie != nil { + if time.Since(c.cookieIssued).Minutes() > 25 { + if err := c.getAuthenticationCookie(); err != nil { + return nil, err + } + } + req.AddCookie(c.authCookie) + } + + // Execute request with supplied client + resp, err := c.httpClient.Do(req) + if err != nil { + return nil, err + } + + if resp.StatusCode >= http.StatusOK && resp.StatusCode < http.StatusMultipleChoices { + return resp, nil + } + + oracleErr := &opc.OracleError{ + StatusCode: resp.StatusCode, + } + + // Even though the returned body will be in json form, it's undocumented what + // fields are actually returned. Once we get documentation of the actual + // error fields that are possible to be returned we can have stricter error types. + if resp.Body != nil { + buf := new(bytes.Buffer) + buf.ReadFrom(resp.Body) + oracleErr.Message = buf.String() + } + + return nil, oracleErr +} + +func (c *Client) formatURL(path *url.URL) string { + return c.apiEndpoint.ResolveReference(path).String() +} + +func (c *Client) getUserName() string { + return fmt.Sprintf(CMP_USERNAME, *c.identityDomain, *c.userName) +} + +// From compute_client +// GetObjectName returns the fully-qualified name of an OPC object, e.g. /identity-domain/user@email/{name} +func (c *Client) getQualifiedName(name string) string { + if name == "" { + return "" + } + if strings.HasPrefix(name, "/oracle") || strings.HasPrefix(name, "/Compute-") { + return name + } + return fmt.Sprintf(CMP_QUALIFIED_NAME, c.getUserName(), name) +} + +func (c *Client) getObjectPath(root, name string) string { + return fmt.Sprintf("%s%s", root, c.getQualifiedName(name)) +} + +// GetUnqualifiedName returns the unqualified name of an OPC object, e.g. the {name} part of /identity-domain/user@email/{name} +func (c *Client) getUnqualifiedName(name string) string { + if name == "" { + return name + } + if strings.HasPrefix(name, "/oracle") { + return name + } + if !strings.Contains(name, "/") { + return name + } + + nameParts := strings.Split(name, "/") + return strings.Join(nameParts[3:], "/") +} + +func (c *Client) unqualify(names ...*string) { + for _, name := range names { + *name = c.getUnqualifiedName(*name) + } +} + +func (c *Client) unqualifyUrl(url *string) { + var validID = regexp.MustCompile(`(\/(Compute[^\/\s]+))(\/[^\/\s]+)(\/[^\/\s]+)`) + name := validID.FindString(*url) + *url = c.getUnqualifiedName(name) +} + +func (c *Client) getQualifiedList(list []string) []string { + for i, name := range list { + list[i] = c.getQualifiedName(name) + } + return list +} + +func (c *Client) getUnqualifiedList(list []string) []string { + for i, name := range list { + list[i] = c.getUnqualifiedName(name) + } + return list +} + +func (c *Client) getQualifiedListName(name string) string { + nameParts := strings.Split(name, ":") + listType := nameParts[0] + listName := nameParts[1] + return fmt.Sprintf("%s:%s", listType, c.getQualifiedName(listName)) +} + +func (c *Client) unqualifyListName(qualifiedName string) string { + nameParts := strings.Split(qualifiedName, ":") + listType := nameParts[0] + listName := nameParts[1] + return fmt.Sprintf("%s:%s", listType, c.getUnqualifiedName(listName)) +} + +// Retry function +func (c *Client) waitFor(description string, timeoutSeconds int, test func() (bool, error)) error { + tick := time.Tick(1 * time.Second) + + for i := 0; i < timeoutSeconds; i++ { + select { + case <-tick: + completed, err := test() + c.debugLogString(fmt.Sprintf("Waiting for %s (%d/%ds)", description, i, timeoutSeconds)) + if err != nil || completed { + return err + } + } + } + return fmt.Errorf("Timeout waiting for %s", description) +} + +// Used to determine if the checked resource was found or not. +func WasNotFoundError(e error) bool { + err, ok := e.(*opc.OracleError) + if ok { + return err.StatusCode == 404 + } + return false +} diff --git a/vendor/github.com/hashicorp/go-oracle-terraform/compute/image_list.go b/vendor/github.com/hashicorp/go-oracle-terraform/compute/image_list.go new file mode 100644 index 000000000..229b75195 --- /dev/null +++ b/vendor/github.com/hashicorp/go-oracle-terraform/compute/image_list.go @@ -0,0 +1,154 @@ +package compute + +const ( + ImageListDescription = "Image List" + ImageListContainerPath = "/imagelist/" + ImageListResourcePath = "/imagelist" +) + +// ImageListClient is a client for the Image List functions of the Compute API. +type ImageListClient struct { + ResourceClient +} + +// ImageList obtains an ImageListClient which can be used to access to the +// Image List functions of the Compute API +func (c *Client) ImageList() *ImageListClient { + return &ImageListClient{ + ResourceClient: ResourceClient{ + Client: c, + ResourceDescription: ImageListDescription, + ContainerPath: ImageListContainerPath, + ResourceRootPath: ImageListResourcePath, + }} +} + +type ImageListEntry struct { + // User-defined parameters, in JSON format, that can be passed to an instance of this machine image when it is launched. + Attributes map[string]interface{} `json:"attributes"` + + // Name of the Image List. + ImageList string `json:"imagelist"` + + // A list of machine images. + MachineImages []string `json:"machineimages"` + + // Uniform Resource Identifier. + URI string `json:"uri"` + + // Version number of these Machine Images in the Image List. + Version int `json:"version"` +} + +// ImageList describes an existing Image List. +type ImageList struct { + // The image list entry to be used, by default, when launching instances using this image list + Default int `json:"default"` + + // A description of this image list. + Description string `json:"description"` + + // Each machine image in an image list is identified by an image list entry. + Entries []ImageListEntry `json:"entries"` + + // The name of the Image List + Name string `json:"name"` + + // Uniform Resource Identifier + URI string `json:"uri"` +} + +// CreateImageListInput defines an Image List to be created. +type CreateImageListInput struct { + // The image list entry to be used, by default, when launching instances using this image list. + // If you don't specify this value, it is set to 1. + // Optional + Default int `json:"default"` + + // A description of this image list. + // Required + Description string `json:"description"` + + // The name of the Image List + // Object names can contain only alphanumeric characters, hyphens, underscores, and periods. Object names are case-sensitive. + // Required + Name string `json:"name"` +} + +// CreateImageList creates a new Image List with the given name, key and enabled flag. +func (c *ImageListClient) CreateImageList(createInput *CreateImageListInput) (*ImageList, error) { + var imageList ImageList + createInput.Name = c.getQualifiedName(createInput.Name) + if err := c.createResource(&createInput, &imageList); err != nil { + return nil, err + } + + return c.success(&imageList) +} + +// DeleteKeyInput describes the image list to delete +type DeleteImageListInput struct { + // The name of the Image List + Name string `json:name` +} + +// DeleteImageList deletes the Image List with the given name. +func (c *ImageListClient) DeleteImageList(deleteInput *DeleteImageListInput) error { + deleteInput.Name = c.getQualifiedName(deleteInput.Name) + return c.deleteResource(deleteInput.Name) +} + +// GetImageListInput describes the image list to get +type GetImageListInput struct { + // The name of the Image List + Name string `json:name` +} + +// GetImageList retrieves the Image List with the given name. +func (c *ImageListClient) GetImageList(getInput *GetImageListInput) (*ImageList, error) { + getInput.Name = c.getQualifiedName(getInput.Name) + + var imageList ImageList + if err := c.getResource(getInput.Name, &imageList); err != nil { + return nil, err + } + + return c.success(&imageList) +} + +// UpdateImageListInput defines an Image List to be updated +type UpdateImageListInput struct { + // The image list entry to be used, by default, when launching instances using this image list. + // If you don't specify this value, it is set to 1. + // Optional + Default int `json:"default"` + + // A description of this image list. + // Required + Description string `json:"description"` + + // The name of the Image List + // Object names can contain only alphanumeric characters, hyphens, underscores, and periods. Object names are case-sensitive. + // Required + Name string `json:"name"` +} + +// UpdateImageList updates the key and enabled flag of the Image List with the given name. +func (c *ImageListClient) UpdateImageList(updateInput *UpdateImageListInput) (*ImageList, error) { + var imageList ImageList + updateInput.Name = c.getQualifiedName(updateInput.Name) + if err := c.updateResource(updateInput.Name, updateInput, &imageList); err != nil { + return nil, err + } + return c.success(&imageList) +} + +func (c *ImageListClient) success(imageList *ImageList) (*ImageList, error) { + c.unqualify(&imageList.Name) + + for _, v := range imageList.Entries { + v.MachineImages = c.getUnqualifiedList(v.MachineImages) + } + + return imageList, nil +} diff --git a/vendor/github.com/hashicorp/go-oracle-terraform/compute/image_list_entries.go b/vendor/github.com/hashicorp/go-oracle-terraform/compute/image_list_entries.go new file mode 100644 index 000000000..bcc45b8f4 --- /dev/null +++ b/vendor/github.com/hashicorp/go-oracle-terraform/compute/image_list_entries.go @@ -0,0 +1,122 @@ +package compute + +import "fmt" + +const ( + ImageListEntryDescription = "image list entry" + ImageListEntryContainerPath = "/imagelist" + ImageListEntryResourcePath = "/imagelist" +) + +type ImageListEntriesClient struct { + ResourceClient +} + +// ImageListEntries() returns an ImageListEntriesClient that can be used to access the +// necessary CRUD functions for Image List Entry's. +func (c *Client) ImageListEntries() *ImageListEntriesClient { + return &ImageListEntriesClient{ + ResourceClient: ResourceClient{ + Client: c, + ResourceDescription: ImageListEntryDescription, + ContainerPath: ImageListEntryContainerPath, + ResourceRootPath: ImageListEntryResourcePath, + }, + } +} + +// ImageListEntryInfo contains the exported fields necessary to hold all the information about an +// Image List Entry +type ImageListEntryInfo struct { + // User-defined parameters, in JSON format, that can be passed to an instance of this machine + // image when it is launched. This field can be used, for example, to specify the location of + // a database server and login details. Instance metadata, including user-defined data is available + // at http://192.0.0.192/ within an instance. See Retrieving User-Defined Instance Attributes in Using + // Oracle Compute Cloud Service (IaaS). + Attributes map[string]interface{} `json:"attributes"` + // Name of the imagelist. + Name string `json:"imagelist"` + // A list of machine images. + MachineImages []string `json:"machineimages"` + // Uniform Resource Identifier for the Image List Entry + Uri string `json:"uri"` + // Version number of these machineImages in the imagelist. + Version int `json:"version"` +} + +type CreateImageListEntryInput struct { + // The name of the Image List + Name string + // User-defined parameters, in JSON format, that can be passed to an instance of this machine + // image when it is launched. This field can be used, for example, to specify the location of + // a database server and login details. Instance metadata, including user-defined data is + //available at http://192.0.0.192/ within an instance. See Retrieving User-Defined Instance + //Attributes in Using Oracle Compute Cloud Service (IaaS). + // Optional + Attributes map[string]interface{} `json:"attributes"` + // A list of machine images. + // Required + MachineImages []string `json:"machineimages"` + // The unique version of the entry in the image list. + // Required + Version int `json:"version"` +} + +// Create a new Image List Entry from an ImageListEntriesClient and an input struct. +// Returns a populated Info struct for the Image List Entry, and any errors +func (c *ImageListEntriesClient) CreateImageListEntry(input *CreateImageListEntryInput) (*ImageListEntryInfo, error) { + c.updateClientPaths(input.Name, -1) + var imageListEntryInfo ImageListEntryInfo + if err := c.createResource(&input, &imageListEntryInfo); err != nil { + return nil, err + } + return c.success(&imageListEntryInfo) +} + +type GetImageListEntryInput struct { + // The name of the Image List + Name string + // Version number of these machineImages in the imagelist. + Version int +} + +// Returns a populated ImageListEntryInfo struct from an input struct +func (c *ImageListEntriesClient) GetImageListEntry(input *GetImageListEntryInput) (*ImageListEntryInfo, error) { + c.updateClientPaths(input.Name, input.Version) + var imageListEntryInfo ImageListEntryInfo + if err := c.getResource("", &imageListEntryInfo); err != nil { + return nil, err + } + return c.success(&imageListEntryInfo) +} + +type DeleteImageListEntryInput struct { + // The name of the Image List + Name string + // Version number of these machineImages in the imagelist. + Version int +} + +func (c *ImageListEntriesClient) DeleteImageListEntry(input *DeleteImageListEntryInput) error { + c.updateClientPaths(input.Name, input.Version) + return c.deleteResource("") +} + +func (c *ImageListEntriesClient) updateClientPaths(name string, version int) { + var containerPath, resourcePath string + name = c.getQualifiedName(name) + containerPath = ImageListEntryContainerPath + name + "/entry/" + resourcePath = ImageListEntryContainerPath + name + "/entry" + if version != -1 { + containerPath = fmt.Sprintf("%s%d", containerPath, version) + resourcePath = fmt.Sprintf("%s/%d", resourcePath, version) + } + c.ContainerPath = containerPath + c.ResourceRootPath = resourcePath +} + +// Unqualifies any qualified fields in the IPNetworkInfo struct +func (c *ImageListEntriesClient) success(info *ImageListEntryInfo) (*ImageListEntryInfo, error) { + c.unqualifyUrl(&info.Uri) + return info, nil +} diff --git a/vendor/github.com/hashicorp/go-oracle-terraform/compute/instances.go b/vendor/github.com/hashicorp/go-oracle-terraform/compute/instances.go new file mode 100644 index 000000000..3c27db611 --- /dev/null +++ b/vendor/github.com/hashicorp/go-oracle-terraform/compute/instances.go @@ -0,0 +1,564 @@ +package compute + +import ( + "errors" + "fmt" + "strings" +) + +const WaitForInstanceReadyTimeout = 600 +const WaitForInstanceDeleteTimeout = 600 + +// InstancesClient is a client for the Instance functions of the Compute API. +type InstancesClient struct { + ResourceClient +} + +// Instances obtains an InstancesClient which can be used to access to the +// Instance functions of the Compute API +func (c *Client) Instances() *InstancesClient { + return &InstancesClient{ + ResourceClient: ResourceClient{ + Client: c, + ResourceDescription: "instance", + ContainerPath: "/launchplan/", + ResourceRootPath: "/instance", + }} +} + +type InstanceState string + +const ( + InstanceRunning InstanceState = "running" + InstanceInitializing InstanceState = "initializing" + InstancePreparing InstanceState = "preparing" + InstanceStopping InstanceState = "stopping" + InstanceQueued InstanceState = "queued" + InstanceError InstanceState = "error" +) + +// InstanceInfo represents the Compute API's view of the state of an instance. +type InstanceInfo struct { + // The ID for the instance. Set by the SDK based on the request - not the API. + ID string + + // A dictionary of attributes to be made available to the instance. + // A value with the key "userdata" will be made available in an EC2-compatible manner. + Attributes map[string]interface{} `json:"attributes"` + + // The availability domain for the instance + AvailabilityDomain string `json:"availability_domain"` + + // Boot order list. + BootOrder []int `json:"boot_order"` + + // The default domain to use for the hostname and DNS lookups + Domain string `json:"domain"` + + // Optional ImageListEntry number. Default will be used if not specified + Entry int `json:"entry"` + + // The reason for the instance going to error state, if available. + ErrorReason string `json:"error_reason"` + + // SSH Server Fingerprint presented by the instance + Fingerprint string `json:"fingerprint"` + + // The hostname for the instance + Hostname string `json:"hostname"` + + // The format of the image + ImageFormat string `json:"image_format"` + + // Name of imagelist to be launched. + ImageList string `json:"imagelist"` + + // IP address of the instance. + IPAddress string `json:"ip"` + + // A label assigned by the user, specifically for defining inter-instance relationships. + Label string `json:"label"` + + // Name of this instance, generated by the server. + Name string `json:"name"` + + // Mapping of to network specifiers for virtual NICs to be attached to this instance. + Networking map[string]NetworkingInfo `json:"networking"` + + // A list of strings specifying arbitrary tags on nodes to be matched on placement. + PlacementRequirements []string `json:"placement_requirements"` + + // The OS platform for the instance. + Platform string `json:"platform"` + + // The priority at which this instance will be run + Priority string `json:"priority"` + + // Reference to the QuotaReservation, to be destroyed with the instance + QuotaReservation string `json:"quota_reservation"` + + // Array of relationship specifications to be satisfied on this instance's placement + Relationships []string `json:"relationships"` + + // Resolvers to use instead of the default resolvers + Resolvers []string `json:"resolvers"` + + // Add PTR records for the hostname + ReverseDNS bool `json:"reverse_dns"` + + // Type of instance, as defined on site configuration. + Shape string `json:"shape"` + + // Site to run on + Site string `json:"site"` + + // ID's of SSH keys that will be exposed to the instance. + SSHKeys []string `json:"sshkeys"` + + // The start time of the instance + StartTime string `json:"start_time"` + + // State of the instance. + State InstanceState `json:"state"` + + // The Storage Attachment information. + Storage []StorageAttachment `json:"storage_attachments"` + + // Array of tags associated with the instance. + Tags []string `json:"tags"` + + // vCable for this instance. + VCableID string `json:"vcable_id"` + + // Specify if the devices created for the instance are virtio devices. If not specified, the default + // will come from the cluster configuration file + Virtio bool `json:"virtio,omitempty"` + + // IP Address and port of the VNC console for the instance + VNC string `json:"vnc"` +} + +type StorageAttachment struct { + // The index number for the volume. + Index int `json:"index"` + + // The three-part name (/Compute-identity_domain/user/object) of the storage attachment. + Name string `json:"name"` + + // The three-part name (/Compute-identity_domain/user/object) of the storage volume attached to the instance. + StorageVolumeName string `json:"storage_volume_name"` +} + +func (i *InstanceInfo) getInstanceName() string { + return fmt.Sprintf(CMP_QUALIFIED_NAME, i.Name, i.ID) +} + +type CreateInstanceInput struct { + // A dictionary of user-defined attributes to be made available to the instance. + // Optional + Attributes map[string]interface{} `json:"attributes"` + // Boot order list + // Optional + BootOrder []int `json:"boot_order"` + // The host name assigned to the instance. On an Oracle Linux instance, + // this host name is displayed in response to the hostname command. + // Only relative DNS is supported. The domain name is suffixed to the host name + // that you specify. The host name must not end with a period. If you don't specify a + // host name, then a name is generated automatically. + // Optional + Hostname string `json:"hostname"` + // Name of imagelist to be launched. + // Optional + ImageList string `json:"imagelist"` + // A label assigned by the user, specifically for defining inter-instance relationships. + // Optional + Label string `json:"label"` + // Name of this instance, generated by the server. + // Optional + Name string `json:"name"` + // Networking information. + // Optional + Networking map[string]NetworkingInfo `json:"networking"` + // If set to true (default), then reverse DNS records are created. + // If set to false, no reverse DNS records are created. + // Optional + ReverseDNS bool `json:"reverse_dns,omitempty"` + // Type of instance, as defined on site configuration. + // Required + Shape string `json:"shape"` + // A list of the Storage Attachments you want to associate with the instance. + // Optional + Storage []StorageAttachmentInput `json:"storage_attachments"` + // A list of the SSH public keys that you want to associate with the instance. + // Optional + SSHKeys []string `json:"sshkeys"` + // A list of tags to be supplied to the instance + // Optional + Tags []string `json:"tags"` +} + +type StorageAttachmentInput struct { + // The index number for the volume. The allowed range is 1 to 10. + // If you want to use a storage volume as the boot disk for an instance, you must specify the index number for that volume as 1. + // The index determines the device name by which the volume is exposed to the instance. + Index int `json:"index"` + // The three-part name (/Compute-identity_domain/user/object) of the storage volume that you want to attach to the instance. + // Note that volumes attached to an instance at launch time can't be detached. + Volume string `json:"volume"` +} + +const ReservationPrefix = "ipreservation" +const ReservationIPPrefix = "network/v1/ipreservation" + +type NICModel string + +const ( + NICDefaultModel NICModel = "e1000" +) + +// Struct of Networking info from a populated instance, or to be used as input to create an instance +type NetworkingInfo struct { + // The DNS name for the Shared network (Required) + // DNS A Record for an IP Network (Optional) + DNS []string `json:"dns,omitempty"` + // IP Network only. + // If you want to associate a static private IP Address, + // specify that here within the range of the supplied IPNetwork attribute. + // Optional + IPAddress string `json:"ip,omitempty"` + // IP Network only. + // The name of the IP Network you want to add the instance to. + // Required + IPNetwork string `json:"ipnetwork,omitempty"` + // IP Network only. + // The hexadecimal MAC Address of the interface + // Optional + MACAddress string `json:"address,omitempty"` + // Shared Network only. + // The type of NIC used. Must be set to 'e1000' + // Required + Model NICModel `json:"model,omitempty"` + // IP Network and Shared Network + // The name servers that are sent through DHCP as option 6. + // You can specify a maximum of eight name server IP addresses per interface. + // Optional + NameServers []string `json:"name_servers,omitempty"` + // The names of an IP Reservation to associate in an IP Network (Optional) + // Indicates whether a temporary or permanent public IP Address should be assigned + // in a Shared Network (Required) + Nat []string `json:"nat,omitempty"` + // IP Network and Shared Network + // The search domains that should be sent through DHCP as option 119. + // You can enter a maximum of eight search domain zones per interface. + // Optional + SearchDomains []string `json:"search_domains,omitempty"` + // Shared Network only. + // The security lists that you want to add the instance to + // Required + SecLists []string `json:"seclists,omitempty"` + // IP Network Only + // The name of the vNIC + // Optional + Vnic string `json:"vnic,omitempty"` + // IP Network only. + // The names of the vNICSets you want to add the interface to. + // Optional + VnicSets []string `json:"vnicsets,omitempty"` +} + +// LaunchPlan defines a launch plan, used to launch instances with the supplied InstanceSpec(s) +type LaunchPlanInput struct { + // Describes an array of instances which should be launched + Instances []CreateInstanceInput `json:"instances"` +} + +type LaunchPlanResponse struct { + // An array of instances which have been launched + Instances []InstanceInfo `json:"instances"` +} + +// LaunchInstance creates and submits a LaunchPlan to launch a new instance. +func (c *InstancesClient) CreateInstance(input *CreateInstanceInput) (*InstanceInfo, error) { + qualifiedSSHKeys := []string{} + for _, key := range input.SSHKeys { + qualifiedSSHKeys = append(qualifiedSSHKeys, c.getQualifiedName(key)) + } + + input.SSHKeys = qualifiedSSHKeys + + qualifiedStorageAttachments := []StorageAttachmentInput{} + for _, attachment := range input.Storage { + qualifiedStorageAttachments = append(qualifiedStorageAttachments, StorageAttachmentInput{ + Index: attachment.Index, + Volume: c.getQualifiedName(attachment.Volume), + }) + } + input.Storage = qualifiedStorageAttachments + + input.Networking = c.qualifyNetworking(input.Networking) + + input.Name = fmt.Sprintf(CMP_QUALIFIED_NAME, c.getUserName(), input.Name) + + plan := LaunchPlanInput{Instances: []CreateInstanceInput{*input}} + + var responseBody LaunchPlanResponse + if err := c.createResource(&plan, &responseBody); err != nil { + return nil, err + } + + if len(responseBody.Instances) == 0 { + return nil, fmt.Errorf("No instance information returned: %#v", responseBody) + } + + // Call wait for instance ready now, as creating the instance is an eventually consistent operation + getInput := &GetInstanceInput{ + Name: input.Name, + ID: responseBody.Instances[0].ID, + } + + // Wait for instance to be ready and return the result + // Don't have to unqualify any objects, as the GetInstance method will handle that + return c.WaitForInstanceRunning(getInput, WaitForInstanceReadyTimeout) +} + +// Both of these fields are required. If they're not provided, things go wrong in +// incredibly amazing ways. +type GetInstanceInput struct { + // The Unqualified Name of this Instance + Name string + // The Unqualified ID of this Instance + ID string +} + +func (g *GetInstanceInput) String() string { + return fmt.Sprintf(CMP_QUALIFIED_NAME, g.Name, g.ID) +} + +// GetInstance retrieves information about an instance. +func (c *InstancesClient) GetInstance(input *GetInstanceInput) (*InstanceInfo, error) { + if input.ID == "" || input.Name == "" { + return nil, errors.New("Both instance name and ID need to be specified") + } + + var responseBody InstanceInfo + if err := c.getResource(input.String(), &responseBody); err != nil { + return nil, err + } + + if responseBody.Name == "" { + return nil, fmt.Errorf("Empty response body when requesting instance %s", input.Name) + } + + // The returned 'Name' attribute is the fully qualified instance name + "/" + ID + // Split these out to accurately populate the fields + nID := strings.Split(c.getUnqualifiedName(responseBody.Name), "/") + responseBody.Name = nID[0] + responseBody.ID = nID[1] + + c.unqualify(&responseBody.VCableID) + + // Unqualify SSH Key names + sshKeyNames := []string{} + for _, sshKeyRef := range responseBody.SSHKeys { + sshKeyNames = append(sshKeyNames, c.getUnqualifiedName(sshKeyRef)) + } + responseBody.SSHKeys = sshKeyNames + + var networkingErr error + responseBody.Networking, networkingErr = c.unqualifyNetworking(responseBody.Networking) + if networkingErr != nil { + return nil, networkingErr + } + responseBody.Storage = c.unqualifyStorage(responseBody.Storage) + + return &responseBody, nil +} + +type DeleteInstanceInput struct { + // The Unqualified Name of this Instance + Name string + // The Unqualified ID of this Instance + ID string +} + +func (d *DeleteInstanceInput) String() string { + return fmt.Sprintf(CMP_QUALIFIED_NAME, d.Name, d.ID) +} + +// DeleteInstance deletes an instance. +func (c *InstancesClient) DeleteInstance(input *DeleteInstanceInput) error { + // Call to delete the instance + if err := c.deleteResource(input.String()); err != nil { + return err + } + // Wait for instance to be deleted + return c.WaitForInstanceDeleted(input, WaitForInstanceDeleteTimeout) +} + +// WaitForInstanceRunning waits for an instance to be completely initialized and available. +func (c *InstancesClient) WaitForInstanceRunning(input *GetInstanceInput, timeoutSeconds int) (*InstanceInfo, error) { + var info *InstanceInfo + var getErr error + err := c.waitFor("instance to be ready", timeoutSeconds, func() (bool, error) { + info, getErr = c.GetInstance(input) + if getErr != nil { + return false, getErr + } + switch s := info.State; s { + case InstanceError: + return false, fmt.Errorf("Error initializing instance: %s", info.ErrorReason) + case InstanceRunning: + c.debugLogString("Instance Running") + return true, nil + case InstanceQueued: + c.debugLogString("Instance Queuing") + return false, nil + case InstanceInitializing: + c.debugLogString("Instance Initializing") + return false, nil + case InstancePreparing: + c.debugLogString("Instance Preparing") + return false, nil + default: + c.debugLogString(fmt.Sprintf("Unknown instance state: %s, waiting", s)) + return false, nil + } + }) + return info, err +} + +// WaitForInstanceDeleted waits for an instance to be fully deleted. +func (c *InstancesClient) WaitForInstanceDeleted(input *DeleteInstanceInput, timeoutSeconds int) error { + return c.waitFor("instance to be deleted", timeoutSeconds, func() (bool, error) { + var info InstanceInfo + if err := c.getResource(input.String(), &info); err != nil { + if WasNotFoundError(err) { + // Instance could not be found, thus deleted + return true, nil + } + // Some other error occurred trying to get instance, exit + return false, err + } + switch s := info.State; s { + case InstanceError: + return false, fmt.Errorf("Error stopping instance: %s", info.ErrorReason) + case InstanceStopping: + c.debugLogString("Instance stopping") + return false, nil + default: + c.debugLogString(fmt.Sprintf("Unknown instance state: %s, waiting", s)) + return false, nil + } + }) +} + +func (c *InstancesClient) qualifyNetworking(info map[string]NetworkingInfo) map[string]NetworkingInfo { + qualifiedNetworks := map[string]NetworkingInfo{} + for k, v := range info { + qfd := v + sharedNetwork := false + if v.IPNetwork != "" { + // Network interface is for an IP Network + qfd.IPNetwork = c.getQualifiedName(v.IPNetwork) + sharedNetwork = true + } + if v.Vnic != "" { + qfd.Vnic = c.getQualifiedName(v.Vnic) + } + if v.Nat != nil { + qfd.Nat = c.qualifyNat(v.Nat, sharedNetwork) + } + if v.VnicSets != nil { + qfd.VnicSets = c.getQualifiedList(v.VnicSets) + } + if v.SecLists != nil { + // Network interface is for the shared network + secLists := []string{} + for _, v := range v.SecLists { + secLists = append(secLists, c.getQualifiedName(v)) + } + qfd.SecLists = secLists + } + + qualifiedNetworks[k] = qfd + } + return qualifiedNetworks +} + +func (c *InstancesClient) unqualifyNetworking(info map[string]NetworkingInfo) (map[string]NetworkingInfo, error) { + // Unqualify ip network + var err error + unqualifiedNetworks := map[string]NetworkingInfo{} + for k, v := range info { + unq := v + if v.IPNetwork != "" { + unq.IPNetwork = c.getUnqualifiedName(v.IPNetwork) + } + if v.Vnic != "" { + unq.Vnic = c.getUnqualifiedName(v.Vnic) + } + if v.Nat != nil { + unq.Nat, err = c.unqualifyNat(v.Nat) + if err != nil { + return nil, err + } + } + if v.VnicSets != nil { + unq.VnicSets = c.getUnqualifiedList(v.VnicSets) + } + if v.SecLists != nil { + secLists := []string{} + for _, v := range v.SecLists { + secLists = append(secLists, c.getUnqualifiedName(v)) + } + v.SecLists = secLists + } + unqualifiedNetworks[k] = unq + } + return unqualifiedNetworks, nil +} + +func (c *InstancesClient) qualifyNat(nat []string, shared bool) []string { + qualifiedNats := []string{} + for _, v := range nat { + if strings.HasPrefix(v, "ippool:/oracle") { + qualifiedNats = append(qualifiedNats, v) + continue + } + prefix := ReservationPrefix + if shared { + prefix = ReservationIPPrefix + } + qualifiedNats = append(qualifiedNats, fmt.Sprintf("%s:%s", prefix, c.getQualifiedName(v))) + } + return qualifiedNats +} + +func (c *InstancesClient) unqualifyNat(nat []string) ([]string, error) { + unQualifiedNats := []string{} + for _, v := range nat { + if strings.HasPrefix(v, "ippool:/oracle") { + unQualifiedNats = append(unQualifiedNats, v) + continue + } + n := strings.Split(v, ":") + if len(n) < 1 { + return nil, fmt.Errorf("Error unqualifying NAT: %s", v) + } + u := n[1] + unQualifiedNats = append(unQualifiedNats, c.getUnqualifiedName(u)) + } + return unQualifiedNats, nil +} + +func (c *InstancesClient) unqualifyStorage(attachments []StorageAttachment) []StorageAttachment { + unqAttachments := []StorageAttachment{} + for _, v := range attachments { + if v.StorageVolumeName != "" { + v.StorageVolumeName = c.getUnqualifiedName(v.StorageVolumeName) + } + unqAttachments = append(unqAttachments, v) + } + + return unqAttachments +} diff --git a/vendor/github.com/hashicorp/go-oracle-terraform/compute/ip_address_associations.go b/vendor/github.com/hashicorp/go-oracle-terraform/compute/ip_address_associations.go new file mode 100644 index 000000000..335ada558 --- /dev/null +++ b/vendor/github.com/hashicorp/go-oracle-terraform/compute/ip_address_associations.go @@ -0,0 +1,152 @@ +package compute + +const ( + IPAddressAssociationDescription = "ip address association" + IPAddressAssociationContainerPath = "/network/v1/ipassociation/" + IPAddressAssociationResourcePath = "/network/v1/ipassociation" +) + +type IPAddressAssociationsClient struct { + ResourceClient +} + +// IPAddressAssociations() returns an IPAddressAssociationsClient that can be used to access the +// necessary CRUD functions for IP Address Associations. +func (c *Client) IPAddressAssociations() *IPAddressAssociationsClient { + return &IPAddressAssociationsClient{ + ResourceClient: ResourceClient{ + Client: c, + ResourceDescription: IPAddressAssociationDescription, + ContainerPath: IPAddressAssociationContainerPath, + ResourceRootPath: IPAddressAssociationResourcePath, + }, + } +} + +// IPAddressAssociationInfo contains the exported fields necessary to hold all the information about an +// IP Address Association +type IPAddressAssociationInfo struct { + // The name of the NAT IP address reservation. + IPAddressReservation string `json:"ipAddressReservation"` + // Name of the virtual NIC associated with this NAT IP reservation. + Vnic string `json:"vnic"` + // The name of the IP Address Association + Name string `json:"name"` + // Description of the IP Address Association + Description string `json:"description"` + // Slice of tags associated with the IP Address Association + Tags []string `json:"tags"` + // Uniform Resource Identifier for the IP Address Association + Uri string `json:"uri"` +} + +type CreateIPAddressAssociationInput struct { + // The name of the IP Address Association to create. Object names can only contain alphanumeric, + // underscore, dash, and period characters. Names are case-sensitive. + // Required + Name string `json:"name"` + + // The name of the NAT IP address reservation. + // Optional + IPAddressReservation string `json:"ipAddressReservation,omitempty"` + + // Name of the virtual NIC associated with this NAT IP reservation. + // Optional + Vnic string `json:"vnic,omitempty"` + + // Description of the IPAddressAssociation + // Optional + Description string `json:"description"` + + // String slice of tags to apply to the IP Address Association object + // Optional + Tags []string `json:"tags"` +} + +// Create a new IP Address Association from an IPAddressAssociationsClient and an input struct. +// Returns a populated Info struct for the IP Address Association, and any errors +func (c *IPAddressAssociationsClient) CreateIPAddressAssociation(input *CreateIPAddressAssociationInput) (*IPAddressAssociationInfo, error) { + input.Name = c.getQualifiedName(input.Name) + input.IPAddressReservation = c.getQualifiedName(input.IPAddressReservation) + input.Vnic = c.getQualifiedName(input.Vnic) + + var ipInfo IPAddressAssociationInfo + if err := c.createResource(&input, &ipInfo); err != nil { + return nil, err + } + + return c.success(&ipInfo) +} + +type GetIPAddressAssociationInput struct { + // The name of the IP Address Association to query for. Case-sensitive + // Required + Name string `json:"name"` +} + +// Returns a populated IPAddressAssociationInfo struct from an input struct +func (c *IPAddressAssociationsClient) GetIPAddressAssociation(input *GetIPAddressAssociationInput) (*IPAddressAssociationInfo, error) { + input.Name = c.getQualifiedName(input.Name) + + var ipInfo IPAddressAssociationInfo + if err := c.getResource(input.Name, &ipInfo); err != nil { + return nil, err + } + + return c.success(&ipInfo) +} + +// UpdateIPAddressAssociationInput defines what to update in a ip address association +type UpdateIPAddressAssociationInput struct { + // The name of the IP Address Association to create. Object names can only contain alphanumeric, + // underscore, dash, and period characters. Names are case-sensitive. + // Required + Name string `json:"name"` + + // The name of the NAT IP address reservation. + // Optional + IPAddressReservation string `json:"ipAddressReservation,omitempty"` + + // Name of the virtual NIC associated with this NAT IP reservation. + // Optional + Vnic string `json:"vnic,omitempty"` + + // Description of the IPAddressAssociation + // Optional + Description string `json:"description"` + + // String slice of tags to apply to the IP Address Association object + // Optional + Tags []string `json:"tags"` +} + +// UpdateIPAddressAssociation update the ip address association +func (c *IPAddressAssociationsClient) UpdateIPAddressAssociation(updateInput *UpdateIPAddressAssociationInput) (*IPAddressAssociationInfo, error) { + updateInput.Name = c.getQualifiedName(updateInput.Name) + updateInput.IPAddressReservation = c.getQualifiedName(updateInput.IPAddressReservation) + updateInput.Vnic = c.getQualifiedName(updateInput.Vnic) + var ipInfo IPAddressAssociationInfo + if err := c.updateResource(updateInput.Name, updateInput, &ipInfo); err != nil { + return nil, err + } + + return c.success(&ipInfo) +} + +type DeleteIPAddressAssociationInput struct { + // The name of the IP Address Association to query for. Case-sensitive + // Required + Name string `json:"name"` +} + +func (c *IPAddressAssociationsClient) DeleteIPAddressAssociation(input *DeleteIPAddressAssociationInput) error { + return c.deleteResource(input.Name) +} + +// Unqualifies any qualified fields in the IPAddressAssociationInfo struct +func (c *IPAddressAssociationsClient) success(info *IPAddressAssociationInfo) (*IPAddressAssociationInfo, error) { + c.unqualify(&info.Name) + c.unqualify(&info.Vnic) + c.unqualify(&info.IPAddressReservation) + return info, nil +} diff --git a/vendor/github.com/hashicorp/go-oracle-terraform/compute/ip_address_prefix_set.go b/vendor/github.com/hashicorp/go-oracle-terraform/compute/ip_address_prefix_set.go new file mode 100644 index 000000000..f685fa2d5 --- /dev/null +++ b/vendor/github.com/hashicorp/go-oracle-terraform/compute/ip_address_prefix_set.go @@ -0,0 +1,135 @@ +package compute + +const ( + IPAddressPrefixSetDescription = "ip address prefix set" + IPAddressPrefixSetContainerPath = "/network/v1/ipaddressprefixset/" + IPAddressPrefixSetResourcePath = "/network/v1/ipaddressprefixset" +) + +type IPAddressPrefixSetsClient struct { + ResourceClient +} + +// IPAddressPrefixSets() returns an IPAddressPrefixSetsClient that can be used to access the +// necessary CRUD functions for IP Address Prefix Sets. +func (c *Client) IPAddressPrefixSets() *IPAddressPrefixSetsClient { + return &IPAddressPrefixSetsClient{ + ResourceClient: ResourceClient{ + Client: c, + ResourceDescription: IPAddressPrefixSetDescription, + ContainerPath: IPAddressPrefixSetContainerPath, + ResourceRootPath: IPAddressPrefixSetResourcePath, + }, + } +} + +// IPAddressPrefixSetInfo contains the exported fields necessary to hold all the information about an +// IP Address Prefix Set +type IPAddressPrefixSetInfo struct { + // The name of the IP Address Prefix Set + Name string `json:"name"` + // Description of the IP Address Prefix Set + Description string `json:"description"` + // List of CIDR IPv4 prefixes assigned in the virtual network. + IPAddressPrefixes []string `json:"ipAddressPrefixes"` + // Slice of tags associated with the IP Address Prefix Set + Tags []string `json:"tags"` + // Uniform Resource Identifier for the IP Address Prefix Set + Uri string `json:"uri"` +} + +type CreateIPAddressPrefixSetInput struct { + // The name of the IP Address Prefix Set to create. Object names can only contain alphanumeric, + // underscore, dash, and period characters. Names are case-sensitive. + // Required + Name string `json:"name"` + + // Description of the IPAddressPrefixSet + // Optional + Description string `json:"description"` + + // List of CIDR IPv4 prefixes assigned in the virtual network. + // Optional + IPAddressPrefixes []string `json:"ipAddressPrefixes"` + + // String slice of tags to apply to the IP Address Prefix Set object + // Optional + Tags []string `json:"tags"` +} + +// Create a new IP Address Prefix Set from an IPAddressPrefixSetsClient and an input struct. +// Returns a populated Info struct for the IP Address Prefix Set, and any errors +func (c *IPAddressPrefixSetsClient) CreateIPAddressPrefixSet(input *CreateIPAddressPrefixSetInput) (*IPAddressPrefixSetInfo, error) { + input.Name = c.getQualifiedName(input.Name) + + var ipInfo IPAddressPrefixSetInfo + if err := c.createResource(&input, &ipInfo); err != nil { + return nil, err + } + + return c.success(&ipInfo) +} + +type GetIPAddressPrefixSetInput struct { + // The name of the IP Address Prefix Set to query for. Case-sensitive + // Required + Name string `json:"name"` +} + +// Returns a populated IPAddressPrefixSetInfo struct from an input struct +func (c *IPAddressPrefixSetsClient) GetIPAddressPrefixSet(input *GetIPAddressPrefixSetInput) (*IPAddressPrefixSetInfo, error) { + input.Name = c.getQualifiedName(input.Name) + + var ipInfo IPAddressPrefixSetInfo + if err := c.getResource(input.Name, &ipInfo); err != nil { + return nil, err + } + + return c.success(&ipInfo) +} + +// UpdateIPAddressPrefixSetInput defines what to update in a ip address prefix set +type UpdateIPAddressPrefixSetInput struct { + // The name of the IP Address Prefix Set to create. Object names can only contain alphanumeric, + // underscore, dash, and period characters. Names are case-sensitive. + // Required + Name string `json:"name"` + + // Description of the IPAddressPrefixSet + // Optional + Description string `json:"description"` + + // List of CIDR IPv4 prefixes assigned in the virtual network. + IPAddressPrefixes []string `json:"ipAddressPrefixes"` + + // String slice of tags to apply to the IP Address Prefix Set object + // Optional + Tags []string `json:"tags"` +} + +// UpdateIPAddressPrefixSet update the ip address prefix set +func (c *IPAddressPrefixSetsClient) UpdateIPAddressPrefixSet(updateInput *UpdateIPAddressPrefixSetInput) (*IPAddressPrefixSetInfo, error) { + updateInput.Name = c.getQualifiedName(updateInput.Name) + var ipInfo IPAddressPrefixSetInfo + if err := c.updateResource(updateInput.Name, updateInput, &ipInfo); err != nil { + return nil, err + } + + return c.success(&ipInfo) +} + +type DeleteIPAddressPrefixSetInput struct { + // The name of the IP Address Prefix Set to query for. Case-sensitive + // Required + Name string `json:"name"` +} + +func (c *IPAddressPrefixSetsClient) DeleteIPAddressPrefixSet(input *DeleteIPAddressPrefixSetInput) error { + return c.deleteResource(input.Name) +} + +// Unqualifies any qualified fields in the IPAddressPrefixSetInfo struct +func (c *IPAddressPrefixSetsClient) success(info *IPAddressPrefixSetInfo) (*IPAddressPrefixSetInfo, error) { + c.unqualify(&info.Name) + return info, nil +} diff --git a/vendor/github.com/hashicorp/go-oracle-terraform/compute/ip_address_reservations.go b/vendor/github.com/hashicorp/go-oracle-terraform/compute/ip_address_reservations.go new file mode 100644 index 000000000..67e92d4ed --- /dev/null +++ b/vendor/github.com/hashicorp/go-oracle-terraform/compute/ip_address_reservations.go @@ -0,0 +1,190 @@ +package compute + +import ( + "fmt" + "path/filepath" +) + +// IPAddressReservationsClient is a client to manage ip address reservation resources +type IPAddressReservationsClient struct { + *ResourceClient +} + +const ( + IPAddressReservationDescription = "IP Address Reservation" + IPAddressReservationContainerPath = "/network/v1/ipreservation/" + IPAddressReservationResourcePath = "/network/v1/ipreservation" + IPAddressReservationQualifier = "/oracle/public" +) + +// IPAddressReservations returns an IPAddressReservationsClient to manage IP address reservation +// resources +func (c *Client) IPAddressReservations() *IPAddressReservationsClient { + return &IPAddressReservationsClient{ + ResourceClient: &ResourceClient{ + Client: c, + ResourceDescription: IPAddressReservationDescription, + ContainerPath: IPAddressReservationContainerPath, + ResourceRootPath: IPAddressReservationResourcePath, + }, + } +} + +// IPAddressReservation describes an IP Address reservation +type IPAddressReservation struct { + // Description of the IP Address Reservation + Description string `json:"description"` + + // Reserved NAT IPv4 address from the IP Address Pool + IPAddress string `json:"ipAddress"` + + // Name of the IP Address pool to reserve the NAT IP from + IPAddressPool string `json:"ipAddressPool"` + + // Name of the reservation + Name string `json:"name"` + + // Tags associated with the object + Tags []string `json:"tags"` + + // Uniform Resource Identified for the reservation + Uri string `json:"uri"` +} + +const ( + PublicIPAddressPool = "public-ippool" + PrivateIPAddressPool = "cloud-ippool" +) + +// CreateIPAddressReservationInput defines input parameters to create an ip address reservation +type CreateIPAddressReservationInput struct { + // Description of the IP Address Reservation + // Optional + Description string `json:"description"` + + // IP Address pool from which to reserve an IP Address. + // Can be one of the following: + // + // 'public-ippool' - When you attach an IP Address from this pool to an instance, you enable + // access between the public Internet and the instance + // 'cloud-ippool' - When you attach an IP Address from this pool to an instance, the instance + // can communicate privately with other Oracle Cloud Services + // Optional + IPAddressPool string `json:"ipAddressPool"` + + // The name of the reservation to create + // Required + Name string `json:"name"` + + // Tags to associate with the IP Reservation + // Optional + Tags []string `json:"tags"` +} + +// Takes an input struct, creates an IP Address reservation, and returns the info struct and any errors +func (c *IPAddressReservationsClient) CreateIPAddressReservation(input *CreateIPAddressReservationInput) (*IPAddressReservation, error) { + var ipAddrRes IPAddressReservation + // Qualify supplied name + input.Name = c.getQualifiedName(input.Name) + // Qualify supplied address pool if not nil + if input.IPAddressPool != "" { + input.IPAddressPool = c.qualifyIPAddressPool(input.IPAddressPool) + } + + if err := c.createResource(input, &ipAddrRes); err != nil { + return nil, err + } + + return c.success(&ipAddrRes) +} + +// Parameters to retrieve information on an ip address reservation +type GetIPAddressReservationInput struct { + // Name of the IP Reservation + // Required + Name string `json:"name"` +} + +// Returns an IP Address Reservation and any errors +func (c *IPAddressReservationsClient) GetIPAddressReservation(input *GetIPAddressReservationInput) (*IPAddressReservation, error) { + var ipAddrRes IPAddressReservation + + input.Name = c.getQualifiedName(input.Name) + if err := c.getResource(input.Name, &ipAddrRes); err != nil { + return nil, err + } + + return c.success(&ipAddrRes) +} + +// Parameters to update an IP Address reservation +type UpdateIPAddressReservationInput struct { + // Description of the IP Address Reservation + // Optional + Description string `json:"description"` + + // IP Address pool from which to reserve an IP Address. + // Can be one of the following: + // + // 'public-ippool' - When you attach an IP Address from this pool to an instance, you enable + // access between the public Internet and the instance + // 'cloud-ippool' - When you attach an IP Address from this pool to an instance, the instance + // can communicate privately with other Oracle Cloud Services + // Optional + IPAddressPool string `json:"ipAddressPool"` + + // The name of the reservation to create + // Required + Name string `json:"name"` + + // Tags to associate with the IP Reservation + // Optional + Tags []string `json:"tags"` +} + +func (c *IPAddressReservationsClient) UpdateIPAddressReservation(input *UpdateIPAddressReservationInput) (*IPAddressReservation, error) { + var ipAddrRes IPAddressReservation + + // Qualify supplied name + input.Name = c.getQualifiedName(input.Name) + // Qualify supplied address pool if not nil + if input.IPAddressPool != "" { + input.IPAddressPool = c.qualifyIPAddressPool(input.IPAddressPool) + } + + if err := c.updateResource(input.Name, input, &ipAddrRes); err != nil { + return nil, err + } + + return c.success(&ipAddrRes) +} + +// Parameters to delete an IP Address Reservation +type DeleteIPAddressReservationInput struct { + // The name of the reservation to delete + Name string `json:"name"` +} + +func (c *IPAddressReservationsClient) DeleteIPAddressReservation(input *DeleteIPAddressReservationInput) error { + input.Name = c.getQualifiedName(input.Name) + return c.deleteResource(input.Name) +} + +func (c *IPAddressReservationsClient) success(result *IPAddressReservation) (*IPAddressReservation, error) { + c.unqualify(&result.Name) + if result.IPAddressPool != "" { + result.IPAddressPool = c.unqualifyIPAddressPool(result.IPAddressPool) + } + + return result, nil +} + +func (c *IPAddressReservationsClient) qualifyIPAddressPool(input string) string { + // Add '/oracle/public/' + return fmt.Sprintf("%s/%s", IPAddressReservationQualifier, input) +} + +func (c *IPAddressReservationsClient) unqualifyIPAddressPool(input string) string { + // Remove '/oracle/public/' + return filepath.Base(input) +} diff --git a/vendor/github.com/hashicorp/go-oracle-terraform/compute/ip_associations.go b/vendor/github.com/hashicorp/go-oracle-terraform/compute/ip_associations.go new file mode 100644 index 000000000..0bfdcbc9d --- /dev/null +++ b/vendor/github.com/hashicorp/go-oracle-terraform/compute/ip_associations.go @@ -0,0 +1,118 @@ +package compute + +import ( + "fmt" + "strings" +) + +// IPAssociationsClient is a client for the IP Association functions of the Compute API. +type IPAssociationsClient struct { + *ResourceClient +} + +// IPAssociations obtains a IPAssociationsClient which can be used to access to the +// IP Association functions of the Compute API +func (c *Client) IPAssociations() *IPAssociationsClient { + return &IPAssociationsClient{ + ResourceClient: &ResourceClient{ + Client: c, + ResourceDescription: "ip association", + ContainerPath: "/ip/association/", + ResourceRootPath: "/ip/association", + }} +} + +// IPAssociationInfo describes an existing IP association. +type IPAssociationInfo struct { + // TODO: it'd probably make sense to expose the `ip` field here too? + + // The three-part name of the object (/Compute-identity_domain/user/object). + Name string `json:"name"` + + // The three-part name of the IP reservation object in the format (/Compute-identity_domain/user/object). + // An IP reservation is a public IP address which is attached to an Oracle Compute Cloud Service instance that requires access to or from the Internet. + Reservation string `json:"reservation"` + + // The type of IP Address to associate with this instance + // for a Dynamic IP address specify `ippool:/oracle/public/ippool`. + // for a Static IP address specify the three part name of the existing IP reservation + ParentPool string `json:"parentpool"` + + // Uniform Resource Identifier for the IP Association + URI string `json:"uri"` + + // The three-part name of a vcable ID of an instance that is associated with the IP reservation. + VCable string `json:"vcable"` +} + +type CreateIPAssociationInput struct { + // The type of IP Address to associate with this instance + // for a Dynamic IP address specify `ippool:/oracle/public/ippool`. + // for a Static IP address specify the three part name of the existing IP reservation + // Required + ParentPool string `json:"parentpool"` + + // The three-part name of the vcable ID of the instance that you want to associate with an IP address. The three-part name is in the format: /Compute-identity_domain/user/object. + // Required + VCable string `json:"vcable"` +} + +// CreateIPAssociation creates a new IP association with the supplied vcable and parentpool. +func (c *IPAssociationsClient) CreateIPAssociation(input *CreateIPAssociationInput) (*IPAssociationInfo, error) { + input.VCable = c.getQualifiedName(input.VCable) + input.ParentPool = c.getQualifiedParentPoolName(input.ParentPool) + var assocInfo IPAssociationInfo + if err := c.createResource(input, &assocInfo); err != nil { + return nil, err + } + + return c.success(&assocInfo) +} + +type GetIPAssociationInput struct { + // The three-part name of the IP Association + // Required. + Name string `json:"name"` +} + +// GetIPAssociation retrieves the IP association with the given name. +func (c *IPAssociationsClient) GetIPAssociation(input *GetIPAssociationInput) (*IPAssociationInfo, error) { + var assocInfo IPAssociationInfo + if err := c.getResource(input.Name, &assocInfo); err != nil { + return nil, err + } + + return c.success(&assocInfo) +} + +type DeleteIPAssociationInput struct { + // The three-part name of the IP Association + // Required. + Name string `json:"name"` +} + +// DeleteIPAssociation deletes the IP association with the given name. +func (c *IPAssociationsClient) DeleteIPAssociation(input *DeleteIPAssociationInput) error { + return c.deleteResource(input.Name) +} + +func (c *IPAssociationsClient) getQualifiedParentPoolName(parentpool string) string { + parts := strings.Split(parentpool, ":") + pooltype := parts[0] + name := parts[1] + return fmt.Sprintf("%s:%s", pooltype, c.getQualifiedName(name)) +} + +func (c *IPAssociationsClient) unqualifyParentPoolName(parentpool *string) { + parts := strings.Split(*parentpool, ":") + pooltype := parts[0] + name := parts[1] + *parentpool = fmt.Sprintf("%s:%s", pooltype, c.getUnqualifiedName(name)) +} + +// Unqualifies identifiers +func (c *IPAssociationsClient) success(assocInfo *IPAssociationInfo) (*IPAssociationInfo, error) { + c.unqualify(&assocInfo.Name, &assocInfo.VCable) + c.unqualifyParentPoolName(&assocInfo.ParentPool) + return assocInfo, nil +} diff --git a/vendor/github.com/hashicorp/go-oracle-terraform/compute/ip_network_exchange.go b/vendor/github.com/hashicorp/go-oracle-terraform/compute/ip_network_exchange.go new file mode 100644 index 000000000..9a20380f8 --- /dev/null +++ b/vendor/github.com/hashicorp/go-oracle-terraform/compute/ip_network_exchange.go @@ -0,0 +1,99 @@ +package compute + +const ( + IPNetworkExchangeDescription = "ip network exchange" + IPNetworkExchangeContainerPath = "/network/v1/ipnetworkexchange/" + IPNetworkExchangeResourcePath = "/network/v1/ipnetworkexchange" +) + +type IPNetworkExchangesClient struct { + ResourceClient +} + +// IPNetworkExchanges() returns an IPNetworkExchangesClient that can be used to access the +// necessary CRUD functions for IP Network Exchanges. +func (c *Client) IPNetworkExchanges() *IPNetworkExchangesClient { + return &IPNetworkExchangesClient{ + ResourceClient: ResourceClient{ + Client: c, + ResourceDescription: IPNetworkExchangeDescription, + ContainerPath: IPNetworkExchangeContainerPath, + ResourceRootPath: IPNetworkExchangeResourcePath, + }, + } +} + +// IPNetworkExchangeInfo contains the exported fields necessary to hold all the information about an +// IP Network Exchange +type IPNetworkExchangeInfo struct { + // The name of the IP Network Exchange + Name string `json:"name"` + // Description of the IP Network Exchange + Description string `json:"description"` + // Slice of tags associated with the IP Network Exchange + Tags []string `json:"tags"` + // Uniform Resource Identifier for the IP Network Exchange + Uri string `json:"uri"` +} + +type CreateIPNetworkExchangeInput struct { + // The name of the IP Network Exchange to create. Object names can only contain alphanumeric, + // underscore, dash, and period characters. Names are case-sensitive. + // Required + Name string `json:"name"` + + // Description of the IPNetworkExchange + // Optional + Description string `json:"description"` + + // String slice of tags to apply to the IP Network Exchange object + // Optional + Tags []string `json:"tags"` +} + +// Create a new IP Network Exchange from an IPNetworkExchangesClient and an input struct. +// Returns a populated Info struct for the IP Network Exchange, and any errors +func (c *IPNetworkExchangesClient) CreateIPNetworkExchange(input *CreateIPNetworkExchangeInput) (*IPNetworkExchangeInfo, error) { + input.Name = c.getQualifiedName(input.Name) + + var ipInfo IPNetworkExchangeInfo + if err := c.createResource(&input, &ipInfo); err != nil { + return nil, err + } + + return c.success(&ipInfo) +} + +type GetIPNetworkExchangeInput struct { + // The name of the IP Network Exchange to query for. Case-sensitive + // Required + Name string `json:"name"` +} + +// Returns a populated IPNetworkExchangeInfo struct from an input struct +func (c *IPNetworkExchangesClient) GetIPNetworkExchange(input *GetIPNetworkExchangeInput) (*IPNetworkExchangeInfo, error) { + input.Name = c.getQualifiedName(input.Name) + + var ipInfo IPNetworkExchangeInfo + if err := c.getResource(input.Name, &ipInfo); err != nil { + return nil, err + } + + return c.success(&ipInfo) +} + +type DeleteIPNetworkExchangeInput struct { + // The name of the IP Network Exchange to query for. Case-sensitive + // Required + Name string `json:"name"` +} + +func (c *IPNetworkExchangesClient) DeleteIPNetworkExchange(input *DeleteIPNetworkExchangeInput) error { + return c.deleteResource(input.Name) +} + +// Unqualifies any qualified fields in the IPNetworkExchangeInfo struct +func (c *IPNetworkExchangesClient) success(info *IPNetworkExchangeInfo) (*IPNetworkExchangeInfo, error) { + c.unqualify(&info.Name) + return info, nil +} diff --git a/vendor/github.com/hashicorp/go-oracle-terraform/compute/ip_networks.go b/vendor/github.com/hashicorp/go-oracle-terraform/compute/ip_networks.go new file mode 100644 index 000000000..3705eef29 --- /dev/null +++ b/vendor/github.com/hashicorp/go-oracle-terraform/compute/ip_networks.go @@ -0,0 +1,186 @@ +package compute + +const ( + IPNetworkDescription = "ip network" + IPNetworkContainerPath = "/network/v1/ipnetwork/" + IPNetworkResourcePath = "/network/v1/ipnetwork" +) + +type IPNetworksClient struct { + ResourceClient +} + +// IPNetworks() returns an IPNetworksClient that can be used to access the +// necessary CRUD functions for IP Networks. +func (c *Client) IPNetworks() *IPNetworksClient { + return &IPNetworksClient{ + ResourceClient: ResourceClient{ + Client: c, + ResourceDescription: IPNetworkDescription, + ContainerPath: IPNetworkContainerPath, + ResourceRootPath: IPNetworkResourcePath, + }, + } +} + +// IPNetworkInfo contains the exported fields necessary to hold all the information about an +// IP Network +type IPNetworkInfo struct { + // The name of the IP Network + Name string `json:"name"` + // The CIDR IPv4 prefix associated with the IP Network + IPAddressPrefix string `json:"ipAddressPrefix"` + // Name of the IP Network Exchange associated with the IP Network + IPNetworkExchange string `json:"ipNetworkExchange,omitempty"` + // Description of the IP Network + Description string `json:"description"` + // Whether public internet access was enabled using NAPT for VNICs without any public IP reservation + PublicNaptEnabled bool `json:"publicNaptEnabledFlag"` + // Slice of tags associated with the IP Network + Tags []string `json:"tags"` + // Uniform Resource Identifier for the IP Network + Uri string `json:"uri"` +} + +type CreateIPNetworkInput struct { + // The name of the IP Network to create. Object names can only contain alphanumeric, + // underscore, dash, and period characters. Names are case-sensitive. + // Required + Name string `json:"name"` + + // Specify the size of the IP Subnet. It is a range of IPv4 addresses assigned in the virtual + // network, in CIDR address prefix format. + // While specifying the IP address prefix take care of the following points: + // + //* These IP addresses aren't part of the common pool of Oracle-provided IP addresses used by the shared network. + // + //* There's no conflict with the range of IP addresses used in another IP network, the IP addresses used your on-premises network, or with the range of private IP addresses used in the shared network. If IP networks with overlapping IP subnets are linked to an IP exchange, packets going to and from those IP networks are dropped. + // + //* The upper limit of the CIDR block size for an IP network is /16. + // + //Note: The first IP address of any IP network is reserved for the default gateway, the DHCP server, and the DNS server of that IP network. + // Required + IPAddressPrefix string `json:"ipAddressPrefix"` + + //Specify the IP network exchange to which the IP network belongs. + //You can add an IP network to only one IP network exchange, but an IP network exchange + //can include multiple IP networks. An IP network exchange enables access between IP networks + //that have non-overlapping addresses, so that instances on these networks can exchange packets + //with each other without NAT. + // Optional + IPNetworkExchange string `json:"ipNetworkExchange,omitempty"` + + // Description of the IPNetwork + // Optional + Description string `json:"description"` + + // Enable public internet access using NAPT for VNICs without any public IP reservation + // Optional + PublicNaptEnabled bool `json:"publicNaptEnabledFlag"` + + // String slice of tags to apply to the IP Network object + // Optional + Tags []string `json:"tags"` +} + +// Create a new IP Network from an IPNetworksClient and an input struct. +// Returns a populated Info struct for the IP Network, and any errors +func (c *IPNetworksClient) CreateIPNetwork(input *CreateIPNetworkInput) (*IPNetworkInfo, error) { + input.Name = c.getQualifiedName(input.Name) + input.IPNetworkExchange = c.getQualifiedName(input.IPNetworkExchange) + + var ipInfo IPNetworkInfo + if err := c.createResource(&input, &ipInfo); err != nil { + return nil, err + } + + return c.success(&ipInfo) +} + +type GetIPNetworkInput struct { + // The name of the IP Network to query for. Case-sensitive + // Required + Name string `json:"name"` +} + +// Returns a populated IPNetworkInfo struct from an input struct +func (c *IPNetworksClient) GetIPNetwork(input *GetIPNetworkInput) (*IPNetworkInfo, error) { + input.Name = c.getQualifiedName(input.Name) + + var ipInfo IPNetworkInfo + if err := c.getResource(input.Name, &ipInfo); err != nil { + return nil, err + } + + return c.success(&ipInfo) +} + +type UpdateIPNetworkInput struct { + // The name of the IP Network to update. Object names can only contain alphanumeric, + // underscore, dash, and period characters. Names are case-sensitive. + // Required + Name string `json:"name"` + + // Specify the size of the IP Subnet. It is a range of IPv4 addresses assigned in the virtual + // network, in CIDR address prefix format. + // While specifying the IP address prefix take care of the following points: + // + //* These IP addresses aren't part of the common pool of Oracle-provided IP addresses used by the shared network. + // + //* There's no conflict with the range of IP addresses used in another IP network, the IP addresses used your on-premises network, or with the range of private IP addresses used in the shared network. If IP networks with overlapping IP subnets are linked to an IP exchange, packets going to and from those IP networks are dropped. + // + //* The upper limit of the CIDR block size for an IP network is /16. + // + //Note: The first IP address of any IP network is reserved for the default gateway, the DHCP server, and the DNS server of that IP network. + // Required + IPAddressPrefix string `json:"ipAddressPrefix"` + + //Specify the IP network exchange to which the IP network belongs. + //You can add an IP network to only one IP network exchange, but an IP network exchange + //can include multiple IP networks. An IP network exchange enables access between IP networks + //that have non-overlapping addresses, so that instances on these networks can exchange packets + //with each other without NAT. + // Optional + IPNetworkExchange string `json:"ipNetworkExchange,omitempty"` + + // Description of the IPNetwork + // Optional + Description string `json:"description"` + + // Enable public internet access using NAPT for VNICs without any public IP reservation + // Optional + PublicNaptEnabled bool `json:"publicNaptEnabledFlag"` + + // String slice of tags to apply to the IP Network object + // Optional + Tags []string `json:"tags"` +} + +func (c *IPNetworksClient) UpdateIPNetwork(input *UpdateIPNetworkInput) (*IPNetworkInfo, error) { + input.Name = c.getQualifiedName(input.Name) + input.IPNetworkExchange = c.getQualifiedName(input.IPNetworkExchange) + + var ipInfo IPNetworkInfo + if err := c.updateResource(input.Name, &input, &ipInfo); err != nil { + return nil, err + } + + return c.success(&ipInfo) +} + +type DeleteIPNetworkInput struct { + // The name of the IP Network to query for. Case-sensitive + // Required + Name string `json:"name"` +} + +func (c *IPNetworksClient) DeleteIPNetwork(input *DeleteIPNetworkInput) error { + return c.deleteResource(input.Name) +} + +// Unqualifies any qualified fields in the IPNetworkInfo struct +func (c *IPNetworksClient) success(info *IPNetworkInfo) (*IPNetworkInfo, error) { + c.unqualify(&info.Name) + c.unqualify(&info.IPNetworkExchange) + return info, nil +} diff --git a/vendor/github.com/hashicorp/go-oracle-terraform/compute/ip_reservations.go b/vendor/github.com/hashicorp/go-oracle-terraform/compute/ip_reservations.go new file mode 100644 index 000000000..30cb47cd6 --- /dev/null +++ b/vendor/github.com/hashicorp/go-oracle-terraform/compute/ip_reservations.go @@ -0,0 +1,147 @@ +package compute + +// IPReservationsClient is a client for the IP Reservations functions of the Compute API. +type IPReservationsClient struct { + *ResourceClient +} + +const ( + IPReservationDesc = "ip reservation" + IPReservationContainerPath = "/ip/reservation/" + IPReservataionResourcePath = "/ip/reservation" +) + +// IPReservations obtains an IPReservationsClient which can be used to access to the +// IP Reservations functions of the Compute API +func (c *Client) IPReservations() *IPReservationsClient { + return &IPReservationsClient{ + ResourceClient: &ResourceClient{ + Client: c, + ResourceDescription: IPReservationDesc, + ContainerPath: IPReservationContainerPath, + ResourceRootPath: IPReservataionResourcePath, + }} +} + +type IPReservationPool string + +const ( + PublicReservationPool IPReservationPool = "/oracle/public/ippool" +) + +// IPReservationInput describes an existing IP reservation. +type IPReservation struct { + // Shows the default account for your identity domain. + Account string `json:"account"` + // Public IP address. + IP string `json:"ip"` + // The three-part name of the IP Reservation (/Compute-identity_domain/user/object). + Name string `json:"name"` + // Pool of public IP addresses + ParentPool IPReservationPool `json:"parentpool"` + // Is the IP Reservation Persistent (i.e. static) or not (i.e. Dynamic)? + Permanent bool `json:"permanent"` + // A comma-separated list of strings which helps you to identify IP reservation. + Tags []string `json:"tags"` + // Uniform Resource Identifier + Uri string `json:"uri"` + // Is the IP reservation associated with an instance? + Used bool `json:"used"` +} + +// CreateIPReservationInput defines an IP reservation to be created. +type CreateIPReservationInput struct { + // The name of the object + // If you don't specify a name for this object, then the name is generated automatically. + // Object names can contain only alphanumeric characters, hyphens, underscores, and periods. + // Object names are case-sensitive. + // Optional + Name string `json:"name"` + // Pool of public IP addresses. This must be set to `ippool` + // Required + ParentPool IPReservationPool `json:"parentpool"` + // Is the IP Reservation Persistent (i.e. static) or not (i.e. Dynamic)? + // Required + Permanent bool `json:"permanent"` + // A comma-separated list of strings which helps you to identify IP reservations. + // Optional + Tags []string `json:"tags"` +} + +// CreateIPReservation creates a new IP reservation with the given parentpool, tags and permanent flag. +func (c *IPReservationsClient) CreateIPReservation(input *CreateIPReservationInput) (*IPReservation, error) { + var ipInput IPReservation + + input.Name = c.getQualifiedName(input.Name) + if err := c.createResource(input, &ipInput); err != nil { + return nil, err + } + + return c.success(&ipInput) +} + +// GetIPReservationInput defines an IP Reservation to get +type GetIPReservationInput struct { + // The name of the IP Reservation + // Required + Name string +} + +// GetIPReservation retrieves the IP reservation with the given name. +func (c *IPReservationsClient) GetIPReservation(input *GetIPReservationInput) (*IPReservation, error) { + var ipInput IPReservation + + input.Name = c.getQualifiedName(input.Name) + if err := c.getResource(input.Name, &ipInput); err != nil { + return nil, err + } + + return c.success(&ipInput) +} + +// UpdateIPReservationInput defines an IP Reservation to be updated +type UpdateIPReservationInput struct { + // The name of the object + // If you don't specify a name for this object, then the name is generated automatically. + // Object names can contain only alphanumeric characters, hyphens, underscores, and periods. + // Object names are case-sensitive. + // Required + Name string `json:"name"` + // Pool of public IP addresses. + // Required + ParentPool IPReservationPool `json:"parentpool"` + // Is the IP Reservation Persistent (i.e. static) or not (i.e. Dynamic)? + // Required + Permanent bool `json:"permanent"` + // A comma-separated list of strings which helps you to identify IP reservations. + // Optional + Tags []string `json:"tags"` +} + +// UpdateIPReservation updates the IP reservation. +func (c *IPReservationsClient) UpdateIPReservation(input *UpdateIPReservationInput) (*IPReservation, error) { + var updateOutput IPReservation + input.Name = c.getQualifiedName(input.Name) + if err := c.updateResource(input.Name, input, &updateOutput); err != nil { + return nil, err + } + return c.success(&updateOutput) +} + +// DeleteIPReservationInput defines an IP Reservation to delete +type DeleteIPReservationInput struct { + // The name of the IP Reservation + // Required + Name string +} + +// DeleteIPReservation deletes the IP reservation with the given name. +func (c *IPReservationsClient) DeleteIPReservation(input *DeleteIPReservationInput) error { + input.Name = c.getQualifiedName(input.Name) + return c.deleteResource(input.Name) +} + +func (c *IPReservationsClient) success(result *IPReservation) (*IPReservation, error) { + c.unqualify(&result.Name) + return result, nil +} diff --git a/vendor/github.com/hashicorp/go-oracle-terraform/compute/logging.go b/vendor/github.com/hashicorp/go-oracle-terraform/compute/logging.go new file mode 100644 index 000000000..5ce8ac23b --- /dev/null +++ b/vendor/github.com/hashicorp/go-oracle-terraform/compute/logging.go @@ -0,0 +1,28 @@ +package compute + +import ( + "bytes" + "fmt" + "net/http" + + "github.com/hashicorp/go-oracle-terraform/opc" +) + +// Log a string if debug logs are on +func (c *Client) debugLogString(str string) { + if c.loglevel != opc.LogDebug { + return + } + c.logger.Log(str) +} + +func (c *Client) debugLogReq(req *http.Request) { + // Don't need to log this if not debugging + if c.loglevel != opc.LogDebug { + return + } + buf := new(bytes.Buffer) + buf.ReadFrom(req.Body) + c.logger.Log(fmt.Sprintf("DEBUG: HTTP %s Req %s: %s", + req.Method, req.URL.String(), buf.String())) +} diff --git a/vendor/github.com/hashicorp/go-oracle-terraform/compute/resource_client.go b/vendor/github.com/hashicorp/go-oracle-terraform/compute/resource_client.go new file mode 100644 index 000000000..7b133c634 --- /dev/null +++ b/vendor/github.com/hashicorp/go-oracle-terraform/compute/resource_client.go @@ -0,0 +1,94 @@ +package compute + +import ( + "bytes" + "encoding/json" + "fmt" + "net/http" + + "github.com/mitchellh/mapstructure" +) + +// ResourceClient is an AuthenticatedClient with some additional information about the resources to be addressed. +type ResourceClient struct { + *Client + ResourceDescription string + ContainerPath string + ResourceRootPath string +} + +func (c *ResourceClient) createResource(requestBody interface{}, responseBody interface{}) error { + resp, err := c.executeRequest("POST", c.ContainerPath, requestBody) + if err != nil { + return err + } + + return c.unmarshalResponseBody(resp, responseBody) +} + +func (c *ResourceClient) updateResource(name string, requestBody interface{}, responseBody interface{}) error { + resp, err := c.executeRequest("PUT", c.getObjectPath(c.ResourceRootPath, name), requestBody) + if err != nil { + return err + } + + return c.unmarshalResponseBody(resp, responseBody) +} + +func (c *ResourceClient) getResource(name string, responseBody interface{}) error { + var objectPath string + if name != "" { + objectPath = c.getObjectPath(c.ResourceRootPath, name) + } else { + objectPath = c.ResourceRootPath + } + resp, err := c.executeRequest("GET", objectPath, nil) + if err != nil { + return err + } + + return c.unmarshalResponseBody(resp, responseBody) +} + +func (c *ResourceClient) deleteResource(name string) error { + var objectPath string + if name != "" { + objectPath = c.getObjectPath(c.ResourceRootPath, name) + } else { + objectPath = c.ResourceRootPath + } + _, err := c.executeRequest("DELETE", objectPath, nil) + if err != nil { + return err + } + + // No errors and no response body to write + return nil +} + +func (c *ResourceClient) unmarshalResponseBody(resp *http.Response, iface interface{}) error { + buf := new(bytes.Buffer) + buf.ReadFrom(resp.Body) + c.debugLogString(fmt.Sprintf("HTTP Resp (%d): %s", resp.StatusCode, buf.String())) + // JSON decode response into interface + var tmp interface{} + dcd := json.NewDecoder(buf) + if err := dcd.Decode(&tmp); err != nil { + return err + } + + // Use mapstructure to weakly decode into the resulting interface + msdcd, err := mapstructure.NewDecoder(&mapstructure.DecoderConfig{ + WeaklyTypedInput: true, + Result: iface, + TagName: "json", + }) + if err != nil { + return err + } + + if err := msdcd.Decode(tmp); err != nil { + return err + } + return nil +} diff --git a/vendor/github.com/hashicorp/go-oracle-terraform/compute/routes.go b/vendor/github.com/hashicorp/go-oracle-terraform/compute/routes.go new file mode 100644 index 000000000..c15303fd7 --- /dev/null +++ b/vendor/github.com/hashicorp/go-oracle-terraform/compute/routes.go @@ -0,0 +1,153 @@ +package compute + +const ( + RoutesDescription = "IP Network Route" + RoutesContainerPath = "/network/v1/route/" + RoutesResourcePath = "/network/v1/route" +) + +type RoutesClient struct { + ResourceClient +} + +func (c *Client) Routes() *RoutesClient { + return &RoutesClient{ + ResourceClient: ResourceClient{ + Client: c, + ResourceDescription: RoutesDescription, + ContainerPath: RoutesContainerPath, + ResourceRootPath: RoutesResourcePath, + }, + } +} + +type RouteInfo struct { + // Admin distance associated with this route + AdminDistance int `json:"adminDistance"` + // Description of the route + Description string `json:"description"` + // CIDR IPv4 Prefix associated with this route + IPAddressPrefix string `json:"ipAddressPrefix"` + // Name of the route + Name string `json:"name"` + // Name of the VNIC set associated with the route + NextHopVnicSet string `json:"nextHopVnicSet"` + // Slice of Tags associated with the route + Tags []string `json:"tags,omitempty"` + // Uniform resource identifier associated with the route + Uri string `json:"uri"` +} + +type CreateRouteInput struct { + // Specify 0,1, or 2 as the route's administrative distance. + // If you do not specify a value, the default value is 0. + // The same prefix can be used in multiple routes. In this case, packets are routed over all the matching + // routes with the lowest administrative distance. + // In the case multiple routes with the same lowest administrative distance match, + // routing occurs over all these routes using ECMP. + // Optional + AdminDistance int `json:"adminDistance"` + // Description of the route + // Optional + Description string `json:"description"` + // The IPv4 address prefix in CIDR format, of the external network (external to the vNIC set) + // from which you want to route traffic + // Required + IPAddressPrefix string `json:"ipAddressPrefix"` + // Name of the route. + // Names can only contain alphanumeric, underscore, dash, and period characters. Case-sensitive + // Required + Name string `json:"name"` + // Name of the virtual NIC set to route matching packets to. + // Routed flows are load-balanced among all the virtual NICs in the virtual NIC set + // Required + NextHopVnicSet string `json:"nextHopVnicSet"` + // Slice of tags to be associated with the route + // Optional + Tags []string `json:"tags,omitempty"` +} + +func (c *RoutesClient) CreateRoute(input *CreateRouteInput) (*RouteInfo, error) { + input.Name = c.getQualifiedName(input.Name) + input.NextHopVnicSet = c.getQualifiedName(input.NextHopVnicSet) + + var routeInfo RouteInfo + if err := c.createResource(&input, &routeInfo); err != nil { + return nil, err + } + + return c.success(&routeInfo) +} + +type GetRouteInput struct { + // Name of the Route to query for. Case-sensitive + // Required + Name string `json:"name"` +} + +func (c *RoutesClient) GetRoute(input *GetRouteInput) (*RouteInfo, error) { + input.Name = c.getQualifiedName(input.Name) + + var routeInfo RouteInfo + if err := c.getResource(input.Name, &routeInfo); err != nil { + return nil, err + } + return c.success(&routeInfo) +} + +type UpdateRouteInput struct { + // Specify 0,1, or 2 as the route's administrative distance. + // If you do not specify a value, the default value is 0. + // The same prefix can be used in multiple routes. In this case, packets are routed over all the matching + // routes with the lowest administrative distance. + // In the case multiple routes with the same lowest administrative distance match, + // routing occurs over all these routes using ECMP. + // Optional + AdminDistance int `json:"adminDistance"` + // Description of the route + // Optional + Description string `json:"description"` + // The IPv4 address prefix in CIDR format, of the external network (external to the vNIC set) + // from which you want to route traffic + // Required + IPAddressPrefix string `json:"ipAddressPrefix"` + // Name of the route. + // Names can only contain alphanumeric, underscore, dash, and period characters. Case-sensitive + // Required + Name string `json:"name"` + // Name of the virtual NIC set to route matching packets to. + // Routed flows are load-balanced among all the virtual NICs in the virtual NIC set + // Required + NextHopVnicSet string `json:"nextHopVnicSet"` + // Slice of tags to be associated with the route + // Optional + Tags []string `json:"tags"` +} + +func (c *RoutesClient) UpdateRoute(input *UpdateRouteInput) (*RouteInfo, error) { + input.Name = c.getQualifiedName(input.Name) + input.NextHopVnicSet = c.getQualifiedName(input.NextHopVnicSet) + + var routeInfo RouteInfo + if err := c.updateResource(input.Name, &input, &routeInfo); err != nil { + return nil, err + } + + return c.success(&routeInfo) +} + +type DeleteRouteInput struct { + // Name of the Route to delete. Case-sensitive + // Required + Name string `json:"name"` +} + +func (c *RoutesClient) DeleteRoute(input *DeleteRouteInput) error { + return c.deleteResource(input.Name) +} + +func (c *RoutesClient) success(info *RouteInfo) (*RouteInfo, error) { + c.unqualify(&info.Name) + c.unqualify(&info.NextHopVnicSet) + return info, nil +} diff --git a/vendor/github.com/hashicorp/go-oracle-terraform/compute/sec_rules.go b/vendor/github.com/hashicorp/go-oracle-terraform/compute/sec_rules.go new file mode 100644 index 000000000..c16e9d78b --- /dev/null +++ b/vendor/github.com/hashicorp/go-oracle-terraform/compute/sec_rules.go @@ -0,0 +1,193 @@ +package compute + +// SecRulesClient is a client for the Sec Rules functions of the Compute API. +type SecRulesClient struct { + ResourceClient +} + +// SecRules obtains a SecRulesClient which can be used to access to the +// Sec Rules functions of the Compute API +func (c *Client) SecRules() *SecRulesClient { + return &SecRulesClient{ + ResourceClient: ResourceClient{ + Client: c, + ResourceDescription: "security ip list", + ContainerPath: "/secrule/", + ResourceRootPath: "/secrule", + }} +} + +// SecRuleInfo describes an existing sec rule. +type SecRuleInfo struct { + // Set this parameter to PERMIT. + Action string `json:"action"` + // The name of the security application + Application string `json:"application"` + // A description of the sec rule + Description string `json:"description"` + // Indicates whether the security rule is enabled + Disabled bool `json:"disabled"` + // The name of the destination security list or security IP list. + DestinationList string `json:"dst_list"` + // The name of the sec rule + Name string `json:"name"` + // The name of the source security list or security IP list. + SourceList string `json:"src_list"` + // Uniform Resource Identifier for the sec rule + URI string `json:"uri"` +} + +// CreateSecRuleInput defines a sec rule to be created. +type CreateSecRuleInput struct { + // Set this parameter to PERMIT. + // Required + Action string `json:"action"` + + // The name of the security application for user-defined or predefined security applications. + // Required + Application string `json:"application"` + + // Description of the IP Network + // Optional + Description string `json:"description"` + + // Indicates whether the sec rule is enabled (set to false) or disabled (true). + // The default setting is false. + // Optional + Disabled bool `json:"disabled"` + + // The name of the destination security list or security IP list. + // + // You must use the prefix seclist: or seciplist: to identify the list type. + // + // You can specify a security IP list as the destination in a secrule, + // provided src_list is a security list that has DENY as its outbound policy. + // + // You cannot specify any of the security IP lists in the /oracle/public container + // as a destination in a secrule. + // Required + DestinationList string `json:"dst_list"` + + // The name of the Sec Rule to create. Object names can only contain alphanumeric, + // underscore, dash, and period characters. Names are case-sensitive. + // Required + Name string `json:"name"` + + // The name of the source security list or security IP list. + // + // You must use the prefix seclist: or seciplist: to identify the list type. + // + // Required + SourceList string `json:"src_list"` +} + +// CreateSecRule creates a new sec rule. +func (c *SecRulesClient) CreateSecRule(createInput *CreateSecRuleInput) (*SecRuleInfo, error) { + createInput.Name = c.getQualifiedName(createInput.Name) + createInput.SourceList = c.getQualifiedListName(createInput.SourceList) + createInput.DestinationList = c.getQualifiedListName(createInput.DestinationList) + createInput.Application = c.getQualifiedName(createInput.Application) + + var ruleInfo SecRuleInfo + if err := c.createResource(createInput, &ruleInfo); err != nil { + return nil, err + } + + return c.success(&ruleInfo) +} + +// GetSecRuleInput describes the Sec Rule to get +type GetSecRuleInput struct { + // The name of the Sec Rule to query for + // Required + Name string `json:"name"` +} + +// GetSecRule retrieves the sec rule with the given name. +func (c *SecRulesClient) GetSecRule(getInput *GetSecRuleInput) (*SecRuleInfo, error) { + var ruleInfo SecRuleInfo + if err := c.getResource(getInput.Name, &ruleInfo); err != nil { + return nil, err + } + + return c.success(&ruleInfo) +} + +// UpdateSecRuleInput describes a secruity rule to update +type UpdateSecRuleInput struct { + // Set this parameter to PERMIT. + // Required + Action string `json:"action"` + + // The name of the security application for user-defined or predefined security applications. + // Required + Application string `json:"application"` + + // Description of the IP Network + // Optional + Description string `json:"description"` + + // Indicates whether the sec rule is enabled (set to false) or disabled (true). + // The default setting is false. + // Optional + Disabled bool `json:"disabled"` + + // The name of the destination security list or security IP list. + // + // You must use the prefix seclist: or seciplist: to identify the list type. + // + // You can specify a security IP list as the destination in a secrule, + // provided src_list is a security list that has DENY as its outbound policy. + // + // You cannot specify any of the security IP lists in the /oracle/public container + // as a destination in a secrule. + // Required + DestinationList string `json:"dst_list"` + + // The name of the Sec Rule to create. Object names can only contain alphanumeric, + // underscore, dash, and period characters. Names are case-sensitive. + // Required + Name string `json:"name"` + + // The name of the source security list or security IP list. + // + // You must use the prefix seclist: or seciplist: to identify the list type. + // + // Required + SourceList string `json:"src_list"` +} + +// UpdateSecRule modifies the properties of the sec rule with the given name. +func (c *SecRulesClient) UpdateSecRule(updateInput *UpdateSecRuleInput) (*SecRuleInfo, error) { + updateInput.Name = c.getQualifiedName(updateInput.Name) + updateInput.SourceList = c.getQualifiedListName(updateInput.SourceList) + updateInput.DestinationList = c.getQualifiedListName(updateInput.DestinationList) + updateInput.Application = c.getQualifiedName(updateInput.Application) + + var ruleInfo SecRuleInfo + if err := c.updateResource(updateInput.Name, updateInput, &ruleInfo); err != nil { + return nil, err + } + + return c.success(&ruleInfo) +} + +// DeleteSecRuleInput describes the sec rule to delete +type DeleteSecRuleInput struct { + // The name of the Sec Rule to delete. + // Required + Name string `json:"name"` +} + +// DeleteSecRule deletes the sec rule with the given name. +func (c *SecRulesClient) DeleteSecRule(deleteInput *DeleteSecRuleInput) error { + return c.deleteResource(deleteInput.Name) +} + +func (c *SecRulesClient) success(ruleInfo *SecRuleInfo) (*SecRuleInfo, error) { + ruleInfo.Name = c.getUnqualifiedName(ruleInfo.Name) + ruleInfo.SourceList = c.unqualifyListName(ruleInfo.SourceList) + ruleInfo.DestinationList = c.unqualifyListName(ruleInfo.DestinationList) + ruleInfo.Application = c.getUnqualifiedName(ruleInfo.Application) + return ruleInfo, nil +} diff --git a/vendor/github.com/hashicorp/go-oracle-terraform/compute/security_applications.go b/vendor/github.com/hashicorp/go-oracle-terraform/compute/security_applications.go new file mode 100644 index 000000000..007e234da --- /dev/null +++ b/vendor/github.com/hashicorp/go-oracle-terraform/compute/security_applications.go @@ -0,0 +1,150 @@ +package compute + +// SecurityApplicationsClient is a client for the Security Application functions of the Compute API. +type SecurityApplicationsClient struct { + ResourceClient +} + +// SecurityApplications obtains a SecurityApplicationsClient which can be used to access to the +// Security Application functions of the Compute API +func (c *Client) SecurityApplications() *SecurityApplicationsClient { + return &SecurityApplicationsClient{ + ResourceClient: ResourceClient{ + Client: c, + ResourceDescription: "security application", + ContainerPath: "/secapplication/", + ResourceRootPath: "/secapplication", + }} +} + +// SecurityApplicationInfo describes an existing security application. +type SecurityApplicationInfo struct { + // A description of the security application. + Description string `json:"description"` + // The TCP or UDP destination port number. This can be a port range, such as 5900-5999 for TCP. + DPort string `json:"dport"` + // The ICMP code. + ICMPCode SecurityApplicationICMPCode `json:"icmpcode"` + // The ICMP type. + ICMPType SecurityApplicationICMPType `json:"icmptype"` + // The three-part name of the Security Application (/Compute-identity_domain/user/object). + Name string `json:"name"` + // The protocol to use. + Protocol SecurityApplicationProtocol `json:"protocol"` + // The Uniform Resource Identifier + URI string `json:"uri"` +} + +type SecurityApplicationProtocol string + +const ( + All SecurityApplicationProtocol = "all" + AH SecurityApplicationProtocol = "ah" + ESP SecurityApplicationProtocol = "esp" + ICMP SecurityApplicationProtocol = "icmp" + ICMPV6 SecurityApplicationProtocol = "icmpv6" + IGMP SecurityApplicationProtocol = "igmp" + IPIP SecurityApplicationProtocol = "ipip" + GRE SecurityApplicationProtocol = "gre" + MPLSIP SecurityApplicationProtocol = "mplsip" + OSPF SecurityApplicationProtocol = "ospf" + PIM SecurityApplicationProtocol = "pim" + RDP SecurityApplicationProtocol = "rdp" + SCTP SecurityApplicationProtocol = "sctp" + TCP SecurityApplicationProtocol = "tcp" + UDP SecurityApplicationProtocol = "udp" +) + +type SecurityApplicationICMPCode string + +const ( + Admin SecurityApplicationICMPCode = "admin" + Df SecurityApplicationICMPCode = "df" + Host SecurityApplicationICMPCode = "host" + Network SecurityApplicationICMPCode = "network" + Port SecurityApplicationICMPCode = "port" + Protocol SecurityApplicationICMPCode = "protocol" +) + +type SecurityApplicationICMPType string + +const ( + Echo SecurityApplicationICMPType = "echo" + Reply SecurityApplicationICMPType = "reply" + TTL SecurityApplicationICMPType = "ttl" + TraceRoute SecurityApplicationICMPType = "traceroute" + Unreachable SecurityApplicationICMPType = "unreachable" +) + +func (c *SecurityApplicationsClient) success(result *SecurityApplicationInfo) (*SecurityApplicationInfo, error) { + c.unqualify(&result.Name) + return result, nil +} + +// CreateSecurityApplicationInput describes the Security Application to create +type CreateSecurityApplicationInput struct { + // A description of the security application. + // Optional + Description string `json:"description"` + // The TCP or UDP destination port number. + // You can also specify a port range, such as 5900-5999 for TCP. + // This parameter isn't relevant to the icmp protocol. + // Required if the Protocol is TCP or UDP + DPort string `json:"dport"` + // The ICMP code. This parameter is relevant only if you specify ICMP as the protocol. + // If you specify icmp as the protocol and don't specify icmptype or icmpcode, then all ICMP packets are matched. + // Optional + ICMPCode SecurityApplicationICMPCode `json:"icmpcode,omitempty"` + // This parameter is relevant only if you specify ICMP as the protocol. + // If you specify icmp as the protocol and don't specify icmptype or icmpcode, then all ICMP packets are matched. + // Optional + ICMPType SecurityApplicationICMPType `json:"icmptype,omitempty"` + // The three-part name of the Security Application (/Compute-identity_domain/user/object). + // Object names can contain only alphanumeric characters, hyphens, underscores, and periods. Object names are case-sensitive. + // Required + Name string `json:"name"` + // The protocol to use. + // Required + Protocol SecurityApplicationProtocol `json:"protocol"` +} + +// CreateSecurityApplication creates a new security application. +func (c *SecurityApplicationsClient) CreateSecurityApplication(input *CreateSecurityApplicationInput) (*SecurityApplicationInfo, error) { + input.Name = c.getQualifiedName(input.Name) + + var appInfo SecurityApplicationInfo + if err := c.createResource(&input, &appInfo); err != nil { + return nil, err + } + + return c.success(&appInfo) +} + +// GetSecurityApplicationInput describes the Security Application to obtain +type GetSecurityApplicationInput struct { + // The three-part name of the Security Application (/Compute-identity_domain/user/object). + // Required + Name string `json:"name"` +} + +// GetSecurityApplication retrieves the security application with the given name. +func (c *SecurityApplicationsClient) GetSecurityApplication(input *GetSecurityApplicationInput) (*SecurityApplicationInfo, error) { + var appInfo SecurityApplicationInfo + if err := c.getResource(input.Name, &appInfo); err != nil { + return nil, err + } + + return c.success(&appInfo) +} + +// DeleteSecurityApplicationInput describes the Security Application to delete +type DeleteSecurityApplicationInput struct { + // The three-part name of the Security Application (/Compute-identity_domain/user/object). + // Required + Name string `json:"name"` +} + +// DeleteSecurityApplication deletes the security application with the given name. +func (c *SecurityApplicationsClient) DeleteSecurityApplication(input *DeleteSecurityApplicationInput) error { + return c.deleteResource(input.Name) +} diff --git a/vendor/github.com/hashicorp/go-oracle-terraform/compute/security_associations.go b/vendor/github.com/hashicorp/go-oracle-terraform/compute/security_associations.go new file mode 100644 index 000000000..ea30d7813 --- /dev/null +++ b/vendor/github.com/hashicorp/go-oracle-terraform/compute/security_associations.go @@ -0,0 +1,95 @@ +package compute + +// SecurityAssociationsClient is a client for the Security Association functions of the Compute API. +type SecurityAssociationsClient struct { + ResourceClient +} + +// SecurityAssociations obtains a SecurityAssociationsClient which can be used to access to the +// Security Association functions of the Compute API +func (c *Client) SecurityAssociations() *SecurityAssociationsClient { + return &SecurityAssociationsClient{ + ResourceClient: ResourceClient{ + Client: c, + ResourceDescription: "security association", + ContainerPath: "/secassociation/", + ResourceRootPath: "/secassociation", + }} +} + +// SecurityAssociationInfo describes an existing security association. +type SecurityAssociationInfo struct { + // The three-part name of the Security Association (/Compute-identity_domain/user/object). + Name string `json:"name"` + // The name of the Security List that you want to associate with the instance. + SecList string `json:"seclist"` + // vCable of the instance that you want to associate with the security list. + VCable string `json:"vcable"` + // Uniform Resource Identifier + URI string `json:"uri"` +} + +// CreateSecurityAssociationInput defines a security association to be created. +type CreateSecurityAssociationInput struct { + // The three-part name of the Security Association (/Compute-identity_domain/user/object). + // If you don't specify a name for this object, then the name is generated automatically. + // Object names can contain only alphanumeric characters, hyphens, underscores, and periods. Object names are case-sensitive. + // Optional + Name string `json:"name"` + // The name of the Security list that you want to associate with the instance. + // Required + SecList string `json:"seclist"` + // The name of the vCable of the instance that you want to associate with the security list. + // Required + VCable string `json:"vcable"` +} + +// CreateSecurityAssociation creates a security association between the given VCable and security list. +func (c *SecurityAssociationsClient) CreateSecurityAssociation(createInput *CreateSecurityAssociationInput) (*SecurityAssociationInfo, error) { + if createInput.Name != "" { + createInput.Name = c.getQualifiedName(createInput.Name) + } + createInput.VCable = c.getQualifiedName(createInput.VCable) + createInput.SecList = c.getQualifiedName(createInput.SecList) + + var assocInfo SecurityAssociationInfo + if err := c.createResource(&createInput, &assocInfo); err != nil { + return nil, err + } + + return c.success(&assocInfo) +} + +// GetSecurityAssociationInput describes the security association to get +type GetSecurityAssociationInput struct { + // The three-part name of the Security Association (/Compute-identity_domain/user/object). + // Required + Name string `json:"name"` +} + +// GetSecurityAssociation retrieves the security association with the given name. +func (c *SecurityAssociationsClient) GetSecurityAssociation(getInput *GetSecurityAssociationInput) (*SecurityAssociationInfo, error) { + var assocInfo SecurityAssociationInfo + if err := c.getResource(getInput.Name, &assocInfo); err != nil { + return nil, err + } + + return c.success(&assocInfo) +} + +// DeleteSecurityAssociationInput describes the security association to delete +type DeleteSecurityAssociationInput struct { + // The three-part name of the Security Association (/Compute-identity_domain/user/object). + // Required + Name string `json:"name"` +} + +// DeleteSecurityAssociation deletes the security association with the given name. +func (c *SecurityAssociationsClient) DeleteSecurityAssociation(deleteInput *DeleteSecurityAssociationInput) error { + return c.deleteResource(deleteInput.Name) +} + +func (c *SecurityAssociationsClient) success(assocInfo *SecurityAssociationInfo) (*SecurityAssociationInfo, error) { + c.unqualify(&assocInfo.Name, &assocInfo.SecList, &assocInfo.VCable) + return assocInfo, nil +} diff --git a/vendor/github.com/hashicorp/go-oracle-terraform/compute/security_ip_lists.go b/vendor/github.com/hashicorp/go-oracle-terraform/compute/security_ip_lists.go new file mode 100644 index 000000000..08314cd12 --- /dev/null +++ b/vendor/github.com/hashicorp/go-oracle-terraform/compute/security_ip_lists.go @@ -0,0 +1,113 @@ +package compute + +// SecurityIPListsClient is a client for the Security IP List functions of the Compute API. +type SecurityIPListsClient struct { + ResourceClient +} + +// SecurityIPLists obtains a SecurityIPListsClient which can be used to access to the +// Security IP List functions of the Compute API +func (c *Client) SecurityIPLists() *SecurityIPListsClient { + return &SecurityIPListsClient{ + ResourceClient: ResourceClient{ + Client: c, + ResourceDescription: "security ip list", + ContainerPath: "/seciplist/", + ResourceRootPath: "/seciplist", + }} +} + +// SecurityIPListInfo describes an existing security IP list. +type SecurityIPListInfo struct { + // A description of the security IP list. + Description string `json:"description"` + // The three-part name of the object (/Compute-identity_domain/user/object). + Name string `json:"name"` + // A comma-separated list of the subnets (in CIDR format) or IPv4 addresses for which you want to create this security IP list. + SecIPEntries []string `json:"secipentries"` + // Uniform Resource Identifier + URI string `json:"uri"` +} + +// CreateSecurityIPListInput defines a security IP list to be created. +type CreateSecurityIPListInput struct { + // A description of the security IP list. + // Optional + Description string `json:"description"` + // The three-part name of the object (/Compute-identity_domain/user/object). + // Object names can contain only alphanumeric characters, hyphens, underscores, and periods. Object names are case-sensitive. + // Required + Name string `json:"name"` + // A comma-separated list of the subnets (in CIDR format) or IPv4 addresses for which you want to create this security IP list. + // Required + SecIPEntries []string `json:"secipentries"` +} + +// CreateSecurityIPList creates a security IP list with the given name and entries. +func (c *SecurityIPListsClient) CreateSecurityIPList(createInput *CreateSecurityIPListInput) (*SecurityIPListInfo, error) { + createInput.Name = c.getQualifiedName(createInput.Name) + var listInfo SecurityIPListInfo + if err := c.createResource(createInput, &listInfo); err != nil { + return nil, err + } + + return c.success(&listInfo) +} + +// GetSecurityIPListInput describes the Security IP List to obtain +type GetSecurityIPListInput struct { + // The three-part name of the object (/Compute-identity_domain/user/object). + // Required + Name string `json:"name"` +} + +// GetSecurityIPList gets the security IP list with the given name. +func (c *SecurityIPListsClient) GetSecurityIPList(getInput *GetSecurityIPListInput) (*SecurityIPListInfo, error) { + var listInfo SecurityIPListInfo + if err := c.getResource(getInput.Name, &listInfo); err != nil { + return nil, err + } + + return c.success(&listInfo) +} + +// UpdateSecurityIPListInput describes the security ip list to update +type UpdateSecurityIPListInput struct { + // A description of the security IP list. + // Optional + Description string `json:"description"` + // The three-part name of the object (/Compute-identity_domain/user/object). + // Required + Name string `json:"name"` + // A comma-separated list of the subnets (in CIDR format) or IPv4 addresses for which you want to create this security IP list. + // Required + SecIPEntries []string `json:"secipentries"` +} + +// UpdateSecurityIPList modifies the entries in the security IP list with the given name. +func (c *SecurityIPListsClient) UpdateSecurityIPList(updateInput *UpdateSecurityIPListInput) (*SecurityIPListInfo, error) { + updateInput.Name = c.getQualifiedName(updateInput.Name) + var listInfo SecurityIPListInfo + if err := c.updateResource(updateInput.Name, updateInput, &listInfo); err != nil { + return nil, err + } + + return c.success(&listInfo) +} + +// DeleteSecurityIPListInput describes the security ip list to delete. +type DeleteSecurityIPListInput struct { + // The three-part name of the object (/Compute-identity_domain/user/object). + // Required + Name string `json:"name"` +} + +// DeleteSecurityIPList deletes the security IP list with the given name. +func (c *SecurityIPListsClient) DeleteSecurityIPList(deleteInput *DeleteSecurityIPListInput) error { + return c.deleteResource(deleteInput.Name) +} + +func (c *SecurityIPListsClient) success(listInfo *SecurityIPListInfo) (*SecurityIPListInfo, error) { + c.unqualify(&listInfo.Name) + return listInfo, nil +} diff --git a/vendor/github.com/hashicorp/go-oracle-terraform/compute/security_lists.go b/vendor/github.com/hashicorp/go-oracle-terraform/compute/security_lists.go new file mode 100644 index 000000000..fd654fac6 --- /dev/null +++ b/vendor/github.com/hashicorp/go-oracle-terraform/compute/security_lists.go @@ -0,0 +1,131 @@ +package compute + +// SecurityListsClient is a client for the Security List functions of the Compute API. +type SecurityListsClient struct { + ResourceClient +} + +// SecurityLists obtains a SecurityListsClient which can be used to access to the +// Security List functions of the Compute API +func (c *Client) SecurityLists() *SecurityListsClient { + return &SecurityListsClient{ + ResourceClient: ResourceClient{ + Client: c, + ResourceDescription: "security list", + ContainerPath: "/seclist/", + ResourceRootPath: "/seclist", + }} +} + +type SecurityListPolicy string + +const ( + SecurityListPolicyDeny SecurityListPolicy = "deny" + SecurityListPolicyReject SecurityListPolicy = "reject" + SecurityListPolicyPermit SecurityListPolicy = "permit" +) + +// SecurityListInfo describes an existing security list. +type SecurityListInfo struct { + // Shows the default account for your identity domain. + Account string `json:"account"` + // A description of the security list. + Description string `json:description` + // The three-part name of the security list (/Compute-identity_domain/user/object). + Name string `json:"name"` + // The policy for outbound traffic from the security list. + OutboundCIDRPolicy SecurityListPolicy `json:"outbound_cidr_policy"` + // The policy for inbound traffic to the security list + Policy SecurityListPolicy `json:"policy"` + // Uniform Resource Identifier + URI string `json:"uri"` +} + +// CreateSecurityListInput defines a security list to be created. +type CreateSecurityListInput struct { + // A description of the security list. + // Optional + Description string `json:"description"` + // The three-part name of the Security List (/Compute-identity_domain/user/object). + // Object names can contain only alphanumeric characters, hyphens, underscores, and periods. Object names are case-sensitive. + // Required + Name string `json:"name"` + // The policy for outbound traffic from the security list. + // Optional (defaults to `permit`) + OutboundCIDRPolicy SecurityListPolicy `json:"outbound_cidr_policy"` + // The policy for inbound traffic to the security list. + // Optional (defaults to `deny`) + Policy SecurityListPolicy `json:"policy"` +} + +// CreateSecurityList creates a new security list with the given name, policy and outbound CIDR policy. +func (c *SecurityListsClient) CreateSecurityList(createInput *CreateSecurityListInput) (*SecurityListInfo, error) { + createInput.Name = c.getQualifiedName(createInput.Name) + var listInfo SecurityListInfo + if err := c.createResource(createInput, &listInfo); err != nil { + return nil, err + } + + return c.success(&listInfo) +} + +// GetSecurityListInput describes the security list you want to get +type GetSecurityListInput struct { + // The three-part name of the Security List (/Compute-identity_domain/user/object). + // Required + Name string `json:name` +} + +// GetSecurityList retrieves the security list with the given name. +func (c *SecurityListsClient) GetSecurityList(getInput *GetSecurityListInput) (*SecurityListInfo, error) { + var listInfo SecurityListInfo + if err := c.getResource(getInput.Name, &listInfo); err != nil { + return nil, err + } + + return c.success(&listInfo) +} + +// UpdateSecurityListInput defines what to update in a security list +type UpdateSecurityListInput struct { + // A description of the security list. + // Optional + Description string `json:description` + // The three-part name of the Security List (/Compute-identity_domain/user/object). + // Required + Name string `json:"name"` + // The policy for outbound traffic from the security list. + // Optional (defaults to `permit`) + OutboundCIDRPolicy SecurityListPolicy `json:"outbound_cidr_policy"` + // The policy for inbound traffic to the security list. + // Optional (defaults to `deny`) + Policy SecurityListPolicy `json:"policy"` +} + +// UpdateSecurityList updates the policy and outbound CIDR pol +func (c *SecurityListsClient) UpdateSecurityList(updateInput *UpdateSecurityListInput) (*SecurityListInfo, error) { + updateInput.Name = c.getQualifiedName(updateInput.Name) + var listInfo SecurityListInfo + if err := c.updateResource(updateInput.Name, updateInput, &listInfo); err != nil { + return nil, err + } + + return c.success(&listInfo) +} + +// DeleteSecurityListInput describes the security list to destroy +type DeleteSecurityListInput struct { + // The three-part name of the Security List (/Compute-identity_domain/user/object). + // Required + Name string `json:name` +} + +// DeleteSecurityList deletes the security list with the given name. +func (c *SecurityListsClient) DeleteSecurityList(deleteInput *DeleteSecurityListInput) error { + return c.deleteResource(deleteInput.Name) +} + +func (c *SecurityListsClient) success(listInfo *SecurityListInfo) (*SecurityListInfo, error) { + c.unqualify(&listInfo.Name) + return listInfo, nil +} diff --git a/vendor/github.com/hashicorp/go-oracle-terraform/compute/security_protocols.go b/vendor/github.com/hashicorp/go-oracle-terraform/compute/security_protocols.go new file mode 100644 index 000000000..e54aeef89 --- /dev/null +++ b/vendor/github.com/hashicorp/go-oracle-terraform/compute/security_protocols.go @@ -0,0 +1,187 @@ +package compute + +const ( + SecurityProtocolDescription = "security protocol" + SecurityProtocolContainerPath = "/network/v1/secprotocol/" + SecurityProtocolResourcePath = "/network/v1/secprotocol" +) + +type SecurityProtocolsClient struct { + ResourceClient +} + +// SecurityProtocols() returns an SecurityProtocolsClient that can be used to access the +// necessary CRUD functions for Security Protocols. +func (c *Client) SecurityProtocols() *SecurityProtocolsClient { + return &SecurityProtocolsClient{ + ResourceClient: ResourceClient{ + Client: c, + ResourceDescription: SecurityProtocolDescription, + ContainerPath: SecurityProtocolContainerPath, + ResourceRootPath: SecurityProtocolResourcePath, + }, + } +} + +// SecurityProtocolInfo contains the exported fields necessary to hold all the information about an +// Security Protocol +type SecurityProtocolInfo struct { + // List of port numbers or port range strings to match the packet's destination port. + DstPortSet []string `json:"dstPortSet"` + // Protocol used in the data portion of the IP datagram. + IPProtocol string `json:"ipProtocol"` + // List of port numbers or port range strings to match the packet's source port. + SrcPortSet []string `json:"srcPortSet"` + // The name of the Security Protocol + Name string `json:"name"` + // Description of the Security Protocol + Description string `json:"description"` + // Slice of tags associated with the Security Protocol + Tags []string `json:"tags"` + // Uniform Resource Identifier for the Security Protocol + Uri string `json:"uri"` +} + +type CreateSecurityProtocolInput struct { + // The name of the Security Protocol to create. Object names can only contain alphanumeric, + // underscore, dash, and period characters. Names are case-sensitive. + // Required + Name string `json:"name"` + + // Description of the SecurityProtocol + // Optional + Description string `json:"description"` + + // Enter a list of port numbers or port range strings. + //Traffic is enabled by a security rule when a packet's destination port matches the + // ports specified here. + // For TCP, SCTP, and UDP, each port is a destination transport port, between 0 and 65535, + // inclusive. For ICMP, each port is an ICMP type, between 0 and 255, inclusive. + // If no destination ports are specified, all destination ports or ICMP types are allowed. + // Optional + DstPortSet []string `json:"dstPortSet"` + + // The protocol used in the data portion of the IP datagram. + // Specify one of the permitted values or enter a number in the range 0–254 to + // represent the protocol that you want to specify. See Assigned Internet Protocol Numbers. + // Permitted values are: tcp, udp, icmp, igmp, ipip, rdp, esp, ah, gre, icmpv6, ospf, pim, sctp, + // mplsip, all. + // Traffic is enabled by a security rule when the protocol in the packet matches the + // protocol specified here. If no protocol is specified, all protocols are allowed. + // Optional + IPProtocol string `json:"ipProtocol"` + + // Enter a list of port numbers or port range strings. + // Traffic is enabled by a security rule when a packet's source port matches the + // ports specified here. + // For TCP, SCTP, and UDP, each port is a source transport port, + // between 0 and 65535, inclusive. + // For ICMP, each port is an ICMP type, between 0 and 255, inclusive. + // If no source ports are specified, all source ports or ICMP types are allowed. + // Optional + SrcPortSet []string `json:"srcPortSet"` + + // String slice of tags to apply to the Security Protocol object + // Optional + Tags []string `json:"tags"` +} + +// Create a new Security Protocol from an SecurityProtocolsClient and an input struct. +// Returns a populated Info struct for the Security Protocol, and any errors +func (c *SecurityProtocolsClient) CreateSecurityProtocol(input *CreateSecurityProtocolInput) (*SecurityProtocolInfo, error) { + input.Name = c.getQualifiedName(input.Name) + + var ipInfo SecurityProtocolInfo + if err := c.createResource(&input, &ipInfo); err != nil { + return nil, err + } + + return c.success(&ipInfo) +} + +type GetSecurityProtocolInput struct { + // The name of the Security Protocol to query for. Case-sensitive + // Required + Name string `json:"name"` +} + +// Returns a populated SecurityProtocolInfo struct from an input struct +func (c *SecurityProtocolsClient) GetSecurityProtocol(input *GetSecurityProtocolInput) (*SecurityProtocolInfo, error) { + input.Name = c.getQualifiedName(input.Name) + + var ipInfo SecurityProtocolInfo + if err := c.getResource(input.Name, &ipInfo); err != nil { + return nil, err + } + + return c.success(&ipInfo) +} + +// UpdateSecurityProtocolInput defines what to update in a security protocol +type UpdateSecurityProtocolInput struct { + // The name of the Security Protocol to create. Object names can only contain alphanumeric, + // underscore, dash, and period characters. Names are case-sensitive. + // Required + Name string `json:"name"` + + // Description of the SecurityProtocol + // Optional + Description string `json:"description"` + + // Enter a list of port numbers or port range strings. + //Traffic is enabled by a security rule when a packet's destination port matches the + // ports specified here. + // For TCP, SCTP, and UDP, each port is a destination transport port, between 0 and 65535, + // inclusive. For ICMP, each port is an ICMP type, between 0 and 255, inclusive. + // If no destination ports are specified, all destination ports or ICMP types are allowed. + DstPortSet []string `json:"dstPortSet"` + + // The protocol used in the data portion of the IP datagram. + // Specify one of the permitted values or enter a number in the range 0–254 to + // represent the protocol that you want to specify. See Assigned Internet Protocol Numbers. + // Permitted values are: tcp, udp, icmp, igmp, ipip, rdp, esp, ah, gre, icmpv6, ospf, pim, sctp, + // mplsip, all. + // Traffic is enabled by a security rule when the protocol in the packet matches the + // protocol specified here. If no protocol is specified, all protocols are allowed. + IPProtocol string `json:"ipProtocol"` + + // Enter a list of port numbers or port range strings. + // Traffic is enabled by a security rule when a packet's source port matches the + // ports specified here. + // For TCP, SCTP, and UDP, each port is a source transport port, + // between 0 and 65535, inclusive. + // For ICMP, each port is an ICMP type, between 0 and 255, inclusive. + // If no source ports are specified, all source ports or ICMP types are allowed. + SrcPortSet []string `json:"srcPortSet"` + + // String slice of tags to apply to the Security Protocol object + // Optional + Tags []string `json:"tags"` +} + +// UpdateSecurityProtocol update the security protocol +func (c *SecurityProtocolsClient) UpdateSecurityProtocol(updateInput *UpdateSecurityProtocolInput) (*SecurityProtocolInfo, error) { + updateInput.Name = c.getQualifiedName(updateInput.Name) + var ipInfo SecurityProtocolInfo + if err := c.updateResource(updateInput.Name, updateInput, &ipInfo); err != nil { + return nil, err + } + + return c.success(&ipInfo) +} + +type DeleteSecurityProtocolInput struct { + // The name of the Security Protocol to query for. Case-sensitive + // Required + Name string `json:"name"` +} + +func (c *SecurityProtocolsClient) DeleteSecurityProtocol(input *DeleteSecurityProtocolInput) error { + return c.deleteResource(input.Name) +} + +// Unqualifies any qualified fields in the SecurityProtocolInfo struct +func (c *SecurityProtocolsClient) success(info *SecurityProtocolInfo) (*SecurityProtocolInfo, error) { + c.unqualify(&info.Name) + return info, nil +} diff --git a/vendor/github.com/hashicorp/go-oracle-terraform/compute/security_rules.go b/vendor/github.com/hashicorp/go-oracle-terraform/compute/security_rules.go new file mode 100644 index 000000000..025a3465a --- /dev/null +++ b/vendor/github.com/hashicorp/go-oracle-terraform/compute/security_rules.go @@ -0,0 +1,266 @@ +package compute + +const ( + SecurityRuleDescription = "security rules" + SecurityRuleContainerPath = "/network/v1/secrule/" + SecurityRuleResourcePath = "/network/v1/secrule" +) + +type SecurityRuleClient struct { + ResourceClient +} + +// SecurityRules() returns an SecurityRulesClient that can be used to access the +// necessary CRUD functions for Security Rules. +func (c *Client) SecurityRules() *SecurityRuleClient { + return &SecurityRuleClient{ + ResourceClient: ResourceClient{ + Client: c, + ResourceDescription: SecurityRuleDescription, + ContainerPath: SecurityRuleContainerPath, + ResourceRootPath: SecurityRuleResourcePath, + }, + } +} + +// SecurityRuleInfo contains the exported fields necessary to hold all the information about a +// Security Rule +type SecurityRuleInfo struct { + // Name of the ACL that contains this rule. + ACL string `json:"acl"` + // Description of the Security Rule + Description string `json:"description"` + // List of IP address prefix set names to match the packet's destination IP address. + DstIpAddressPrefixSets []string `json:"dstIpAddressPrefixSets"` + // Name of virtual NIC set containing the packet's destination virtual NIC. + DstVnicSet string `json:"dstVnicSet"` + // Allows the security rule to be disabled. + Enabled bool `json:"enabledFlag"` + // Direction of the flow; Can be "egress" or "ingress". + FlowDirection string `json:"FlowDirection"` + // The name of the Security Rule + Name string `json:"name"` + // List of security protocol names to match the packet's protocol and port. + SecProtocols []string `json:"secProtocols"` + // List of multipart names of IP address prefix set to match the packet's source IP address. + SrcIpAddressPrefixSets []string `json:"srcIpAddressPrefixSets"` + // Name of virtual NIC set containing the packet's source virtual NIC. + SrcVnicSet string `json:"srcVnicSet"` + // Slice of tags associated with the Security Rule + Tags []string `json:"tags"` + // Uniform Resource Identifier for the Security Rule + Uri string `json:"uri"` +} + +type CreateSecurityRuleInput struct { + //Select the name of the access control list (ACL) that you want to add this + // security rule to. Security rules are applied to vNIC sets by using ACLs. + // Optional + ACL string `json:"acl,omitempty"` + + // Description of the Security Rule + // Optional + Description string `json:"description"` + + // A list of IP address prefix sets to which you want to permit traffic. + // Only packets to IP addresses in the specified IP address prefix sets are permitted. + // When no destination IP address prefix sets are specified, traffic to any + // IP address is permitted. + // Optional + DstIpAddressPrefixSets []string `json:"dstIpAddressPrefixSets"` + + // The vNICset to which you want to permit traffic. Only packets to vNICs in the + // specified vNICset are permitted. When no destination vNICset is specified, traffic + // to any vNIC is permitted. + // Optional + DstVnicSet string `json:"dstVnicSet,omitempty"` + + // Allows the security rule to be enabled or disabled. This parameter is set to + // true by default. Specify false to disable the security rule. + // Optional + Enabled bool `json:"enabledFlag"` + + // Specify the direction of flow of traffic, which is relative to the instances, + // for this security rule. Allowed values are ingress or egress. + // An ingress packet is a packet received by a virtual NIC, for example from + // another virtual NIC or from the public Internet. + // An egress packet is a packet sent by a virtual NIC, for example to another + // virtual NIC or to the public Internet. + // Required + FlowDirection string `json:"flowDirection"` + + // The name of the Security Rule + // Object names can contain only alphanumeric characters, hyphens, underscores, and periods. + // Object names are case-sensitive. When you specify the object name, ensure that an object + // of the same type and with the same name doesn't already exist. + // If such an object already exists, another object of the same type and with the same name won't + // be created and the existing object won't be updated. + // Required + Name string `json:"name"` + + // A list of security protocols for which you want to permit traffic. Only packets that + // match the specified protocols and ports are permitted. When no security protocols are + // specified, traffic using any protocol over any port is permitted. + // Optional + SecProtocols []string `json:"secProtocols"` + + // A list of IP address prefix sets from which you want to permit traffic. Only packets + // from IP addresses in the specified IP address prefix sets are permitted. When no source + // IP address prefix sets are specified, traffic from any IP address is permitted. + // Optional + SrcIpAddressPrefixSets []string `json:"srcIpAddressPrefixSets"` + + // The vNICset from which you want to permit traffic. Only packets from vNICs in the + // specified vNICset are permitted. When no source vNICset is specified, traffic from any + // vNIC is permitted. + // Optional + SrcVnicSet string `json:"srcVnicSet,omitempty"` + + // Strings that you can use to tag the security rule. + // Optional + Tags []string `json:"tags"` +} + +// Create a new Security Rule from an SecurityRuleClient and an input struct. +// Returns a populated Info struct for the Security Rule, and any errors +func (c *SecurityRuleClient) CreateSecurityRule(input *CreateSecurityRuleInput) (*SecurityRuleInfo, error) { + input.Name = c.getQualifiedName(input.Name) + input.ACL = c.getQualifiedName(input.ACL) + input.SrcVnicSet = c.getQualifiedName(input.SrcVnicSet) + input.DstVnicSet = c.getQualifiedName(input.DstVnicSet) + input.SrcIpAddressPrefixSets = c.getQualifiedList(input.SrcIpAddressPrefixSets) + input.DstIpAddressPrefixSets = c.getQualifiedList(input.DstIpAddressPrefixSets) + input.SecProtocols = c.getQualifiedList(input.SecProtocols) + + var securityRuleInfo SecurityRuleInfo + if err := c.createResource(&input, &securityRuleInfo); err != nil { + return nil, err + } + + return c.success(&securityRuleInfo) +} + +type GetSecurityRuleInput struct { + // The name of the Security Rule to query for. Case-sensitive + // Required + Name string `json:"name"` +} + +// Returns a populated SecurityRuleInfo struct from an input struct +func (c *SecurityRuleClient) GetSecurityRule(input *GetSecurityRuleInput) (*SecurityRuleInfo, error) { + input.Name = c.getQualifiedName(input.Name) + + var securityRuleInfo SecurityRuleInfo + if err := c.getResource(input.Name, &securityRuleInfo); err != nil { + return nil, err + } + + return c.success(&securityRuleInfo) +} + +// UpdateSecurityRuleInput describes a secruity rule to update +type UpdateSecurityRuleInput struct { + //Select the name of the access control list (ACL) that you want to add this + // security rule to. Security rules are applied to vNIC sets by using ACLs. + // Optional + ACL string `json:"acl,omitempty"` + + // Description of the Security Rule + // Optional + Description string `json:"description"` + + // A list of IP address prefix sets to which you want to permit traffic. + // Only packets to IP addresses in the specified IP address prefix sets are permitted. + // When no destination IP address prefix sets are specified, traffic to any + // IP address is permitted. + // Optional + DstIpAddressPrefixSets []string `json:"dstIpAddressPrefixSets"` + + // The vNICset to which you want to permit traffic. Only packets to vNICs in the + // specified vNICset are permitted. When no destination vNICset is specified, traffic + // to any vNIC is permitted. + // Optional + DstVnicSet string `json:"dstVnicSet,omitempty"` + + // Allows the security rule to be enabled or disabled. This parameter is set to + // true by default. Specify false to disable the security rule. + // Optional + Enabled bool `json:"enabledFlag"` + + // Specify the direction of flow of traffic, which is relative to the instances, + // for this security rule. Allowed values are ingress or egress. + // An ingress packet is a packet received by a virtual NIC, for example from + // another virtual NIC or from the public Internet. + // An egress packet is a packet sent by a virtual NIC, for example to another + // virtual NIC or to the public Internet. + // Required + FlowDirection string `json:"flowDirection"` + + // The name of the Security Rule + // Object names can contain only alphanumeric characters, hyphens, underscores, and periods. + // Object names are case-sensitive. When you specify the object name, ensure that an object + // of the same type and with the same name doesn't already exist. + // If such an object already exists, another object of the same type and with the same name won't + // be created and the existing object won't be updated. + // Required + Name string `json:"name"` + + // A list of security protocols for which you want to permit traffic. Only packets that + // match the specified protocols and ports are permitted. When no security protocols are + // specified, traffic using any protocol over any port is permitted. + // Optional + SecProtocols []string `json:"secProtocols"` + + // A list of IP address prefix sets from which you want to permit traffic. Only packets + // from IP addresses in the specified IP address prefix sets are permitted. When no source + // IP address prefix sets are specified, traffic from any IP address is permitted. + // Optional + SrcIpAddressPrefixSets []string `json:"srcIpAddressPrefixSets"` + + // The vNICset from which you want to permit traffic. Only packets from vNICs in the + // specified vNICset are permitted. When no source vNICset is specified, traffic from any + // vNIC is permitted. + // Optional + SrcVnicSet string `json:"srcVnicSet,omitempty"` + + // Strings that you can use to tag the security rule. + // Optional + Tags []string `json:"tags"` +} + +// UpdateSecRule modifies the properties of the sec rule with the given name. +func (c *SecurityRuleClient) UpdateSecurityRule(updateInput *UpdateSecurityRuleInput) (*SecurityRuleInfo, error) { + updateInput.Name = c.getQualifiedName(updateInput.Name) + updateInput.ACL = c.getQualifiedName(updateInput.ACL) + updateInput.SrcVnicSet = c.getQualifiedName(updateInput.SrcVnicSet) + updateInput.DstVnicSet = c.getQualifiedName(updateInput.DstVnicSet) + updateInput.SrcIpAddressPrefixSets = c.getQualifiedList(updateInput.SrcIpAddressPrefixSets) + updateInput.DstIpAddressPrefixSets = c.getQualifiedList(updateInput.DstIpAddressPrefixSets) + updateInput.SecProtocols = c.getQualifiedList(updateInput.SecProtocols) + + var securityRuleInfo SecurityRuleInfo + if err := c.updateResource(updateInput.Name, updateInput, &securityRuleInfo); err != nil { + return nil, err + } + + return c.success(&securityRuleInfo) +} + +type DeleteSecurityRuleInput struct { + // The name of the Security Rule to query for. Case-sensitive + // Required + Name string `json:"name"` +} + +func (c *SecurityRuleClient) DeleteSecurityRule(input *DeleteSecurityRuleInput) error { + return c.deleteResource(input.Name) +} + +// Unqualifies any qualified fields in the IPNetworkExchangeInfo struct +func (c *SecurityRuleClient) success(info *SecurityRuleInfo) (*SecurityRuleInfo, error) { + c.unqualify(&info.Name, &info.ACL, &info.SrcVnicSet, &info.DstVnicSet) + info.SrcIpAddressPrefixSets = c.getUnqualifiedList(info.SrcIpAddressPrefixSets) + info.DstIpAddressPrefixSets = c.getUnqualifiedList(info.DstIpAddressPrefixSets) + info.SecProtocols = c.getUnqualifiedList(info.SecProtocols) + return info, nil +} diff --git a/vendor/github.com/hashicorp/go-oracle-terraform/compute/ssh_keys.go b/vendor/github.com/hashicorp/go-oracle-terraform/compute/ssh_keys.go new file mode 100644 index 000000000..4ad000a43 --- /dev/null +++ b/vendor/github.com/hashicorp/go-oracle-terraform/compute/ssh_keys.go @@ -0,0 +1,124 @@ +package compute + +// SSHKeysClient is a client for the SSH key functions of the Compute API. +type SSHKeysClient struct { + ResourceClient +} + +// SSHKeys obtains an SSHKeysClient which can be used to access to the +// SSH key functions of the Compute API +func (c *Client) SSHKeys() *SSHKeysClient { + return &SSHKeysClient{ + ResourceClient: ResourceClient{ + Client: c, + ResourceDescription: "SSH key", + ContainerPath: "/sshkey/", + ResourceRootPath: "/sshkey", + }} +} + +// SSHKeyInfo describes an existing SSH key. +type SSHKey struct { + // Indicates whether the key is enabled (true) or disabled. + Enabled bool `json:"enabled"` + // The SSH public key value. + Key string `json:"key"` + // The three-part name of the SSH Key (/Compute-identity_domain/user/object). + Name string `json:"name"` + // Unique Resource Identifier + URI string `json:"uri"` +} + +// CreateSSHKeyInput defines an SSH key to be created. +type CreateSSHKeyInput struct { + // The three-part name of the SSH Key (/Compute-identity_domain/user/object). + // Object names can contain only alphanumeric characters, hyphens, underscores, and periods. Object names are case-sensitive. + // Required + Name string `json:"name"` + // The SSH public key value. + // Required + Key string `json:"key"` + // Indicates whether the key must be enabled (default) or disabled. Note that disabled keys cannot be associated with instances. + // To explicitly enable the key, specify true. To disable the key, specify false. + // Optional + Enabled bool `json:"enabled"` +} + +// CreateSSHKey creates a new SSH key with the given name, key and enabled flag. +func (c *SSHKeysClient) CreateSSHKey(createInput *CreateSSHKeyInput) (*SSHKey, error) { + var keyInfo SSHKey + // We have to update after create to get the full ssh key into opc + updateSSHKeyInput := UpdateSSHKeyInput{ + Name: createInput.Name, + Key: createInput.Key, + Enabled: createInput.Enabled, + } + + createInput.Name = c.getQualifiedName(createInput.Name) + if err := c.createResource(&createInput, &keyInfo); err != nil { + return nil, err + } + + _, err := c.UpdateSSHKey(&updateSSHKeyInput) + if err != nil { + return nil, err + } + + return c.success(&keyInfo) +} + +// GetSSHKeyInput describes the ssh key to get +type GetSSHKeyInput struct { + // The three-part name of the SSH Key (/Compute-identity_domain/user/object). + Name string `json:name` +} + +// GetSSHKey retrieves the SSH key with the given name. +func (c *SSHKeysClient) GetSSHKey(getInput *GetSSHKeyInput) (*SSHKey, error) { + var keyInfo SSHKey + if err := c.getResource(getInput.Name, &keyInfo); err != nil { + return nil, err + } + + return c.success(&keyInfo) +} + +// UpdateSSHKeyInput defines an SSH key to be updated +type UpdateSSHKeyInput struct { + // The three-part name of the object (/Compute-identity_domain/user/object). + Name string `json:"name"` + // The SSH public key value. + // Required + Key string `json:"key"` + // Indicates whether the key must be enabled (default) or disabled. Note that disabled keys cannot be associated with instances. + // To explicitly enable the key, specify true. To disable the key, specify false. + // Optional + // TODO/NOTE: isn't this required? + Enabled bool `json:"enabled"` +} + +// UpdateSSHKey updates the key and enabled flag of the SSH key with the given name. +func (c *SSHKeysClient) UpdateSSHKey(updateInput *UpdateSSHKeyInput) (*SSHKey, error) { + var keyInfo SSHKey + updateInput.Name = c.getQualifiedName(updateInput.Name) + if err := c.updateResource(updateInput.Name, updateInput, &keyInfo); err != nil { + return nil, err + } + return c.success(&keyInfo) +} + +// DeleteKeyInput describes the ssh key to delete +type DeleteSSHKeyInput struct { + // The three-part name of the SSH Key (/Compute-identity_domain/user/object). + Name string `json:name` +} + +// DeleteSSHKey deletes the SSH key with the given name. +func (c *SSHKeysClient) DeleteSSHKey(deleteInput *DeleteSSHKeyInput) error { + return c.deleteResource(deleteInput.Name) +} + +func (c *SSHKeysClient) success(keyInfo *SSHKey) (*SSHKey, error) { + c.unqualify(&keyInfo.Name) + return keyInfo, nil +} diff --git a/vendor/github.com/hashicorp/go-oracle-terraform/compute/storage_volume_attachments.go b/vendor/github.com/hashicorp/go-oracle-terraform/compute/storage_volume_attachments.go new file mode 100644 index 000000000..c24cf0cc9 --- /dev/null +++ b/vendor/github.com/hashicorp/go-oracle-terraform/compute/storage_volume_attachments.go @@ -0,0 +1,158 @@ +package compute + +const WaitForVolumeAttachmentDeleteTimeout = 30 +const WaitForVolumeAttachmentReadyTimeout = 30 + +// StorageAttachmentsClient is a client for the Storage Attachment functions of the Compute API. +type StorageAttachmentsClient struct { + ResourceClient +} + +// StorageAttachments obtains a StorageAttachmentsClient which can be used to access to the +// Storage Attachment functions of the Compute API +func (c *Client) StorageAttachments() *StorageAttachmentsClient { + return &StorageAttachmentsClient{ + ResourceClient: ResourceClient{ + Client: c, + ResourceDescription: "storage volume attachment", + ContainerPath: "/storage/attachment/", + ResourceRootPath: "/storage/attachment", + }} +} + +type StorageAttachmentState string + +const ( + Attaching StorageAttachmentState = "attaching" + Attached StorageAttachmentState = "attached" + Detaching StorageAttachmentState = "detaching" + Unavailable StorageAttachmentState = "unavailable" + Unknown StorageAttachmentState = "unknown" +) + +// StorageAttachmentInfo describes an existing storage attachment. +type StorageAttachmentInfo struct { + // Name of this attachment, generated by the server. + Name string `json:"name"` + + // Index number for the volume. The allowed range is 1-10 + // An attachment with index 1 is exposed to the instance as /dev/xvdb, an attachment with index 2 is exposed as /dev/xvdc, and so on. + Index int `json:"index"` + + // Multipart name of the instance attached to the storage volume. + InstanceName string `json:"instance_name"` + + // Multipart name of the volume attached to the instance. + StorageVolumeName string `json:"storage_volume_name"` + + // The State of the Storage Attachment + State StorageAttachmentState `json:"state"` +} + +func (c *StorageAttachmentsClient) success(attachmentInfo *StorageAttachmentInfo) (*StorageAttachmentInfo, error) { + c.unqualify(&attachmentInfo.Name, &attachmentInfo.InstanceName, &attachmentInfo.StorageVolumeName) + return attachmentInfo, nil +} + +type CreateStorageAttachmentInput struct { + // Index number for the volume. The allowed range is 1-10 + // An attachment with index 1 is exposed to the instance as /dev/xvdb, an attachment with index 2 is exposed as /dev/xvdc, and so on. + // Required. + Index int `json:"index"` + + // Multipart name of the instance to which you want to attach the volume. + // Required. + InstanceName string `json:"instance_name"` + + // Multipart name of the volume that you want to attach. + // Required. + StorageVolumeName string `json:"storage_volume_name"` +} + +// CreateStorageAttachment creates a storage attachment attaching the given volume to the given instance at the given index. +func (c *StorageAttachmentsClient) CreateStorageAttachment(input *CreateStorageAttachmentInput) (*StorageAttachmentInfo, error) { + input.InstanceName = c.getQualifiedName(input.InstanceName) + + var attachmentInfo *StorageAttachmentInfo + if err := c.createResource(&input, &attachmentInfo); err != nil { + return nil, err + } + + return c.waitForStorageAttachmentToFullyAttach(attachmentInfo.Name, WaitForVolumeAttachmentReadyTimeout) +} + +// DeleteStorageAttachmentInput represents the body of an API request to delete a Storage Attachment. +type DeleteStorageAttachmentInput struct { + // The three-part name of the Storage Attachment (/Compute-identity_domain/user/object). + // Required + Name string `json:"name"` +} + +// DeleteStorageAttachment deletes the storage attachment with the given name. +func (c *StorageAttachmentsClient) DeleteStorageAttachment(input *DeleteStorageAttachmentInput) error { + if err := c.deleteResource(input.Name); err != nil { + return err + } + + return c.waitForStorageAttachmentToBeDeleted(input.Name, WaitForVolumeAttachmentDeleteTimeout) +} + +// GetStorageAttachmentInput represents the body of an API request to obtain a Storage Attachment. +type GetStorageAttachmentInput struct { + // The three-part name of the Storage Attachment (/Compute-identity_domain/user/object). + // Required + Name string `json:"name"` +} + +// GetStorageAttachment retrieves the storage attachment with the given name. +func (c *StorageAttachmentsClient) GetStorageAttachment(input *GetStorageAttachmentInput) (*StorageAttachmentInfo, error) { + var attachmentInfo *StorageAttachmentInfo + if err := c.getResource(input.Name, &attachmentInfo); err != nil { + return nil, err + } + + return c.success(attachmentInfo) +} + +// waitForStorageAttachmentToFullyAttach waits for the storage attachment with the given name to be fully attached, or times out. +func (c *StorageAttachmentsClient) waitForStorageAttachmentToFullyAttach(name string, timeoutSeconds int) (*StorageAttachmentInfo, error) { + var waitResult *StorageAttachmentInfo + + err := c.waitFor("storage attachment to be attached", timeoutSeconds, func() (bool, error) { + input := &GetStorageAttachmentInput{ + Name: name, + } + info, err := c.GetStorageAttachment(input) + if err != nil { + return false, err + } + + if info != nil { + if info.State == Attached { + waitResult = info + return true, nil + } + } + + return false, nil + }) + + return waitResult, err +} + +// waitForStorageAttachmentToBeDeleted waits for the storage attachment with the given name to be fully deleted, or times out. +func (c *StorageAttachmentsClient) waitForStorageAttachmentToBeDeleted(name string, timeoutSeconds int) error { + return c.waitFor("storage attachment to be deleted", timeoutSeconds, func() (bool, error) { + input := &GetStorageAttachmentInput{ + Name: name, + } + _, err := c.GetStorageAttachment(input) + if err != nil { + if WasNotFoundError(err) { + return true, nil + } + return false, err + } + return false, nil + }) +} diff --git a/vendor/github.com/hashicorp/go-oracle-terraform/compute/storage_volume_snapshots.go b/vendor/github.com/hashicorp/go-oracle-terraform/compute/storage_volume_snapshots.go new file mode 100644 index 000000000..f958d2107 --- /dev/null +++ b/vendor/github.com/hashicorp/go-oracle-terraform/compute/storage_volume_snapshots.go @@ -0,0 +1,250 @@ +package compute + +import ( + "fmt" + "strings" +) + +const ( + StorageVolumeSnapshotDescription = "storage volume snapshot" + StorageVolumeSnapshotContainerPath = "/storage/snapshot/" + StorageVolumeSnapshotResourcePath = "/storage/snapshot" + + WaitForSnapshotCreateTimeout = 1200 + WaitForSnapshotDeleteTimeout = 1500 + + // Collocated Snapshot Property + SnapshotPropertyCollocated = "/oracle/private/storage/snapshot/collocated" +) + +// StorageVolumeSnapshotClient is a client for the Storage Volume Snapshot functions of the Compute API. +type StorageVolumeSnapshotClient struct { + ResourceClient +} + +func (c *Client) StorageVolumeSnapshots() *StorageVolumeSnapshotClient { + return &StorageVolumeSnapshotClient{ + ResourceClient: ResourceClient{ + Client: c, + ResourceDescription: StorageVolumeSnapshotDescription, + ContainerPath: StorageVolumeSnapshotContainerPath, + ResourceRootPath: StorageVolumeSnapshotResourcePath, + }, + } +} + +// StorageVolumeSnapshotInfo represents the information retrieved from the service about a storage volume snapshot +type StorageVolumeSnapshotInfo struct { + // Account to use for snapshots + Account string `json:"account"` + + // Description of the snapshot + Description string `json:"description"` + + // The name of the machine image that's used in the boot volume from which this snapshot is taken + MachineImageName string `json:"machineimage_name"` + + // Name of the snapshot + Name string `json:"name"` + + // String indicating whether the parent volume is bootable or not + ParentVolumeBootable string `json:"parent_volume_bootable"` + + // Platform the snapshot is compatible with + Platform string `json:"platform"` + + // String determining whether the snapshot is remote or collocated + Property string `json:"property"` + + // The size of the snapshot in GB + Size string `json:"size"` + + // The ID of the snapshot. Generated by the server + SnapshotID string `json:"snapshot_id"` + + // The timestamp of the storage snapshot + SnapshotTimestamp string `json:"snapshot_timestamp"` + + // Timestamp for when the operation started + StartTimestamp string `json:"start_timestamp"` + + // Status of the snapshot + Status string `json:"status"` + + // Status Detail of the storage snapshot + StatusDetail string `json:"status_detail"` + + // Indicates the time that the current view of the storage volume snapshot was generated. + StatusTimestamp string `json:"status_timestamp"` + + // Array of tags for the snapshot + Tags []string `json:"tags,omitempty"` + + // Uniform Resource Identifier + URI string `json:"uri"` + + // Name of the parent storage volume for the snapshot + Volume string `json:"volume"` +} + +// CreateStorageVolumeSnapshotInput represents the body of an API request to create a new storage volume snapshot +type CreateStorageVolumeSnapshotInput struct { + // Description of the snapshot + // Optional + Description string `json:"description,omitempty"` + + // Name of the snapshot + // Optional, will be generated if not specified + Name string `json:"name,omitempty"` + + // Whether or not the parent volume is bootable + // Optional + ParentVolumeBootable string `json:"parent_volume_bootable,omitempty"` + + // Whether collocated or remote + // Optional, will be remote if unspecified + Property string `json:"property,omitempty"` + + // Array of tags for the snapshot + // Optional + Tags []string `json:"tags,omitempty"` + + // Name of the volume to create the snapshot from + // Required + Volume string `json:"volume"` + + // Timeout (in seconds) to wait for snapshot to be completed. Will use default if unspecified + Timeout int +} + +// CreateStorageVolumeSnapshot creates a snapshot based on the supplied information struct +func (c *StorageVolumeSnapshotClient) CreateStorageVolumeSnapshot(input *CreateStorageVolumeSnapshotInput) (*StorageVolumeSnapshotInfo, error) { + if input.Name != "" { + input.Name = c.getQualifiedName(input.Name) + } + input.Volume = c.getQualifiedName(input.Volume) + + var storageSnapshotInfo StorageVolumeSnapshotInfo + if err := c.createResource(&input, &storageSnapshotInfo); err != nil { + return nil, err + } + + timeout := WaitForSnapshotCreateTimeout + if input.Timeout != 0 { + timeout = input.Timeout + } + + // The name of the snapshot could have been generated. Use the response name as input + return c.waitForStorageSnapshotAvailable(storageSnapshotInfo.Name, timeout) +} + +// GetStorageVolumeSnapshotInput represents the body of an API request to get information on a storage volume snapshot +type GetStorageVolumeSnapshotInput struct { + // Name of the snapshot + Name string `json:"name"` +} + +// GetStorageVolumeSnapshot makes an API request to populate information on a storage volume snapshot +func (c *StorageVolumeSnapshotClient) GetStorageVolumeSnapshot(input *GetStorageVolumeSnapshotInput) (*StorageVolumeSnapshotInfo, error) { + var storageSnapshot StorageVolumeSnapshotInfo + input.Name = c.getQualifiedName(input.Name) + if err := c.getResource(input.Name, &storageSnapshot); err != nil { + if WasNotFoundError(err) { + return nil, nil + } + + return nil, err + } + return c.success(&storageSnapshot) +} + +// DeleteStorageVolumeSnapshotInput represents the body of an API request to delete a storage volume snapshot +type DeleteStorageVolumeSnapshotInput struct { + // Name of the snapshot to delete + Name string `json:"name"` + + // Timeout in seconds to wait for deletion, will use default if unspecified + Timeout int +} + +// DeleteStoragevolumeSnapshot makes an API request to delete a storage volume snapshot +func (c *StorageVolumeSnapshotClient) DeleteStorageVolumeSnapshot(input *DeleteStorageVolumeSnapshotInput) error { + input.Name = c.getQualifiedName(input.Name) + + if err := c.deleteResource(input.Name); err != nil { + return err + } + + timeout := WaitForSnapshotDeleteTimeout + if input.Timeout != 0 { + timeout = input.Timeout + } + + return c.waitForStorageSnapshotDeleted(input.Name, timeout) +} + +func (c *StorageVolumeSnapshotClient) success(result *StorageVolumeSnapshotInfo) (*StorageVolumeSnapshotInfo, error) { + c.unqualify(&result.Name) + c.unqualify(&result.Volume) + + sizeInGigaBytes, err := sizeInGigaBytes(result.Size) + if err != nil { + return nil, err + } + result.Size = sizeInGigaBytes + + return result, nil +} + +// Waits for a storage snapshot to become available +func (c *StorageVolumeSnapshotClient) waitForStorageSnapshotAvailable(name string, timeout int) (*StorageVolumeSnapshotInfo, error) { + var result *StorageVolumeSnapshotInfo + + err := c.waitFor( + fmt.Sprintf("storage volume snapshot %s to become available", c.getQualifiedName(name)), + timeout, + func() (bool, error) { + req := &GetStorageVolumeSnapshotInput{ + Name: name, + } + res, err := c.GetStorageVolumeSnapshot(req) + if err != nil { + return false, err + } + + if res != nil { + result = res + if strings.ToLower(result.Status) == "completed" { + return true, nil + } else if strings.ToLower(result.Status) == "error" { + return false, fmt.Errorf("Snapshot '%s' failed to create successfully. Status: %s Status Detail: %s", result.Name, result.Status, result.StatusDetail) + } + } + + return false, nil + }) + + return result, err +} + +// Waits for a storage snapshot to be deleted +func (c *StorageVolumeSnapshotClient) waitForStorageSnapshotDeleted(name string, timeout int) error { + return c.waitFor( + fmt.Sprintf("storage volume snapshot %s to be deleted", c.getQualifiedName(name)), + timeout, + func() (bool, error) { + req := &GetStorageVolumeSnapshotInput{ + Name: name, + } + res, err := c.GetStorageVolumeSnapshot(req) + if res == nil { + return true, nil + } + + if err != nil { + return false, err + } + + return res == nil, nil + }) +} diff --git a/vendor/github.com/hashicorp/go-oracle-terraform/compute/storage_volumes.go b/vendor/github.com/hashicorp/go-oracle-terraform/compute/storage_volumes.go new file mode 100644 index 000000000..da2ce8e0d --- /dev/null +++ b/vendor/github.com/hashicorp/go-oracle-terraform/compute/storage_volumes.go @@ -0,0 +1,347 @@ +package compute + +import ( + "fmt" + "strconv" + "strings" +) + +const WaitForVolumeReadyTimeout = 600 +const WaitForVolumeDeleteTimeout = 600 + +// StorageVolumeClient is a client for the Storage Volume functions of the Compute API. +type StorageVolumeClient struct { + ResourceClient +} + +// StorageVolumes obtains a StorageVolumeClient which can be used to access to the +// Storage Volume functions of the Compute API +func (c *Client) StorageVolumes() *StorageVolumeClient { + return &StorageVolumeClient{ + ResourceClient: ResourceClient{ + Client: c, + ResourceDescription: "storage volume", + ContainerPath: "/storage/volume/", + ResourceRootPath: "/storage/volume", + }} + +} + +type StorageVolumeKind string + +const ( + StorageVolumeKindDefault StorageVolumeKind = "/oracle/public/storage/default" + StorageVolumeKindLatency StorageVolumeKind = "/oracle/public/storage/latency" +) + +// StorageVolumeInfo represents information retrieved from the service about a Storage Volume. +type StorageVolumeInfo struct { + // Shows the default account for your identity domain. + Account string `json:"account,omitempty"` + + // true indicates that the storage volume can also be used as a boot disk for an instance. + // If you set the value to true, then you must specify values for the `ImageList` and `ImageListEntry` fields. + Bootable bool `json:"bootable,omitempty"` + + // The description of the storage volume. + Description string `json:"description,omitempty"` + + // The hypervisor that this volume is compatible with. + Hypervisor string `json:"hypervisor,omitempty"` + + // Name of machine image to extract onto this volume when created. This information is provided only for bootable storage volumes. + ImageList string `json:"imagelist,omitempty"` + + // Specific imagelist entry version to extract. + ImageListEntry int `json:"imagelist_entry,omitempty"` + + // Three-part name of the machine image. This information is available if the volume is a bootable storage volume. + MachineImage string `json:"machineimage_name,omitempty"` + + // All volumes are managed volumes. Default value is true. + Managed bool `json:"managed,omitempty"` + + // The three-part name of the object (/Compute-identity_domain/user/object). + Name string `json:"name"` + + // The OS platform this volume is compatible with. + Platform string `json:"platform,omitempty` + + // The storage-pool property: /oracle/public/storage/latency or /oracle/public/storage/default. + Properties []string `json:"properties,omitempty"` + + // Boolean field indicating whether this volume can be attached as readonly. If set to False the volume will be attached as read-write. + ReadOnly bool `json:"readonly,omitempty"` + + // The size of this storage volume in GB. + Size string `json:"size"` + + // Name of the parent snapshot from which the storage volume is restored or cloned. + Snapshot string `json:"snapshot,omitempty"` + + // Account of the parent snapshot from which the storage volume is restored. + SnapshotAccount string `json:"snapshot_account,omitempty"` + + // Id of the parent snapshot from which the storage volume is restored or cloned. + SnapshotID string `json:"snapshot_id,omitempty"` + + // TODO: this should become a Constant, if/when we have the values + // The current state of the storage volume. + Status string `json:"status,omitempty"` + + // Details about the latest state of the storage volume. + StatusDetail string `json:"status_detail,omitempty"` + + // It indicates the time that the current view of the storage volume was generated. + StatusTimestamp string `json:"status_timestamp,omitempty"` + + // The storage pool from which this volume is allocated. + StoragePool string `json:"storage_pool,omitempty"` + + // Comma-separated strings that tag the storage volume. + Tags []string `json:"tags,omitempty"` + + // Uniform Resource Identifier + URI string `json:"uri,omitempty"` +} + +func (c *StorageVolumeClient) getStorageVolumePath(name string) string { + return c.getObjectPath("/storage/volume", name) +} + +// CreateStorageVolumeInput represents the body of an API request to create a new Storage Volume. +type CreateStorageVolumeInput struct { + // true indicates that the storage volume can also be used as a boot disk for an instance. + // If you set the value to true, then you must specify values for the `ImageList` and `ImageListEntry` fields. + Bootable bool `json:"bootable,omitempty"` + + // The description of the storage volume. + Description string `json:"description,omitempty"` + + // Name of machine image to extract onto this volume when created. This information is provided only for bootable storage volumes. + ImageList string `json:"imagelist,omitempty"` + + // Specific imagelist entry version to extract. + ImageListEntry int `json:"imagelist_entry,omitempty"` + + // The three-part name of the object (/Compute-identity_domain/user/object). + Name string `json:"name"` + + // The storage-pool property: /oracle/public/storage/latency or /oracle/public/storage/default. + Properties []string `json:"properties,omitempty"` + + // The size of this storage volume in GB. + Size string `json:"size"` + + // Name of the parent snapshot from which the storage volume is restored or cloned. + Snapshot string `json:"snapshot,omitempty"` + + // Account of the parent snapshot from which the storage volume is restored. + SnapshotAccount string `json:"snapshot_account,omitempty"` + + // Id of the parent snapshot from which the storage volume is restored or cloned. + SnapshotID string `json:"snapshot_id,omitempty"` + + // Comma-separated strings that tag the storage volume. + Tags []string `json:"tags,omitempty"` +} + +// CreateStorageVolume uses the given CreateStorageVolumeInput to create a new Storage Volume. +func (c *StorageVolumeClient) CreateStorageVolume(input *CreateStorageVolumeInput) (*StorageVolumeInfo, error) { + input.Name = c.getQualifiedName(input.Name) + input.ImageList = c.getQualifiedName(input.ImageList) + + sizeInBytes, err := sizeInBytes(input.Size) + if err != nil { + return nil, err + } + input.Size = sizeInBytes + + var storageInfo StorageVolumeInfo + if err := c.createResource(&input, &storageInfo); err != nil { + return nil, err + } + + return c.waitForStorageVolumeToBecomeAvailable(input.Name, WaitForVolumeReadyTimeout) +} + +// DeleteStorageVolumeInput represents the body of an API request to delete a Storage Volume. +type DeleteStorageVolumeInput struct { + // The three-part name of the object (/Compute-identity_domain/user/object). + Name string `json:"name"` +} + +// DeleteStorageVolume deletes the specified storage volume. +func (c *StorageVolumeClient) DeleteStorageVolume(input *DeleteStorageVolumeInput) error { + if err := c.deleteResource(input.Name); err != nil { + return err + } + + return c.waitForStorageVolumeToBeDeleted(input.Name, WaitForVolumeDeleteTimeout) +} + +// GetStorageVolumeInput represents the body of an API request to obtain a Storage Volume. +type GetStorageVolumeInput struct { + // The three-part name of the object (/Compute-identity_domain/user/object). + Name string `json:"name"` +} + +func (c *StorageVolumeClient) success(result *StorageVolumeInfo) (*StorageVolumeInfo, error) { + c.unqualify(&result.ImageList) + c.unqualify(&result.Name) + c.unqualify(&result.Snapshot) + + sizeInMegaBytes, err := sizeInGigaBytes(result.Size) + if err != nil { + return nil, err + } + result.Size = sizeInMegaBytes + + return result, nil +} + +// GetStorageVolume gets Storage Volume information for the specified storage volume. +func (c *StorageVolumeClient) GetStorageVolume(input *GetStorageVolumeInput) (*StorageVolumeInfo, error) { + var storageVolume StorageVolumeInfo + if err := c.getResource(input.Name, &storageVolume); err != nil { + if WasNotFoundError(err) { + return nil, nil + } + + return nil, err + } + + return c.success(&storageVolume) +} + +// UpdateStorageVolumeInput represents the body of an API request to update a Storage Volume. +type UpdateStorageVolumeInput struct { + // The description of the storage volume. + Description string `json:"description,omitempty"` + + // Name of machine image to extract onto this volume when created. This information is provided only for bootable storage volumes. + ImageList string `json:"imagelist,omitempty"` + + // Specific imagelist entry version to extract. + ImageListEntry int `json:"imagelist_entry,omitempty"` + + // The three-part name of the object (/Compute-identity_domain/user/object). + Name string `json:"name"` + + // The storage-pool property: /oracle/public/storage/latency or /oracle/public/storage/default. + Properties []string `json:"properties,omitempty"` + + // The size of this storage volume in GB. + Size string `json:"size"` + + // Name of the parent snapshot from which the storage volume is restored or cloned. + Snapshot string `json:"snapshot,omitempty"` + + // Account of the parent snapshot from which the storage volume is restored. + SnapshotAccount string `json:"snapshot_account,omitempty"` + + // Id of the parent snapshot from which the storage volume is restored or cloned. + SnapshotID string `json:"snapshot_id,omitempty"` + + // Comma-separated strings that tag the storage volume. + Tags []string `json:"tags,omitempty"` +} + +// UpdateStorageVolume updates the specified storage volume, optionally modifying size, description and tags. +func (c *StorageVolumeClient) UpdateStorageVolume(input *UpdateStorageVolumeInput) (*StorageVolumeInfo, error) { + input.Name = c.getQualifiedName(input.Name) + input.ImageList = c.getQualifiedName(input.ImageList) + + sizeInBytes, err := sizeInBytes(input.Size) + if err != nil { + return nil, err + } + input.Size = sizeInBytes + + path := c.getStorageVolumePath(input.Name) + _, err = c.executeRequest("PUT", path, input) + if err != nil { + return nil, err + } + + instanceInfo, err := c.waitForStorageVolumeToBecomeAvailable(input.Name, WaitForVolumeReadyTimeout) + if err != nil { + return nil, err + } + + return instanceInfo, nil +} + +// waitForStorageVolumeToBecomeAvailable waits until a new Storage Volume is available (i.e. has finished initialising or updating). +func (c *StorageVolumeClient) waitForStorageVolumeToBecomeAvailable(name string, timeoutInSeconds int) (*StorageVolumeInfo, error) { + var waitResult *StorageVolumeInfo + + err := c.waitFor( + fmt.Sprintf("storage volume %s to become available", c.getQualifiedName(name)), + timeoutInSeconds, + func() (bool, error) { + getRequest := &GetStorageVolumeInput{ + Name: name, + } + result, err := c.GetStorageVolume(getRequest) + + if err != nil { + return false, err + } + + if result != nil { + waitResult = result + if strings.ToLower(waitResult.Status) == "online" { + return true, nil + } + } + + return false, nil + }) + + return waitResult, err +} + +// waitForStorageVolumeToBeDeleted waits until the specified storage volume has been deleted. +func (c *StorageVolumeClient) waitForStorageVolumeToBeDeleted(name string, timeoutInSeconds int) error { + return c.waitFor( + fmt.Sprintf("storage volume %s to be deleted", c.getQualifiedName(name)), + timeoutInSeconds, + func() (bool, error) { + getRequest := &GetStorageVolumeInput{ + Name: name, + } + result, err := c.GetStorageVolume(getRequest) + if result == nil { + return true, nil + } + + if err != nil { + return false, err + } + + return result == nil, nil + }) +} + +func sizeInGigaBytes(input string) (string, error) { + sizeInBytes, err := strconv.Atoi(input) + if err != nil { + return "", err + } + sizeInKB := sizeInBytes / 1024 + sizeInMB := sizeInKB / 1024 + sizeInGb := sizeInMB / 1024 + return strconv.Itoa(sizeInGb), nil +} + +func sizeInBytes(input string) (string, error) { + sizeInGB, err := strconv.Atoi(input) + if err != nil { + return "", err + } + sizeInMB := sizeInGB * 1024 + sizeInKB := sizeInMB * 1024 + sizeInBytes := sizeInKB * 1024 + return strconv.Itoa(sizeInBytes), nil +} diff --git a/vendor/github.com/hashicorp/go-oracle-terraform/compute/test_utils.go b/vendor/github.com/hashicorp/go-oracle-terraform/compute/test_utils.go new file mode 100644 index 000000000..82b6047ff --- /dev/null +++ b/vendor/github.com/hashicorp/go-oracle-terraform/compute/test_utils.go @@ -0,0 +1,121 @@ +package compute + +import ( + "bytes" + "encoding/json" + "net/http" + "net/http/httptest" + "net/url" + "os" + "testing" + + "time" + + "log" + + "github.com/hashicorp/go-oracle-terraform/opc" +) + +const ( + _ClientTestUser = "test-user" + _ClientTestDomain = "test-domain" +) + +func newAuthenticatingServer(handler func(w http.ResponseWriter, r *http.Request)) *httptest.Server { + return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if os.Getenv("ORACLE_LOG") != "" { + log.Printf("[DEBUG] Received request: %s, %s\n", r.Method, r.URL) + } + + if r.URL.Path == "/authenticate/" { + http.SetCookie(w, &http.Cookie{Name: "testAuthCookie", Value: "cookie value"}) + // w.WriteHeader(200) + } else { + handler(w, r) + } + })) +} + +func getTestClient(c *opc.Config) (*Client, error) { + // Build up config with default values if omitted + if c.APIEndpoint == nil { + if os.Getenv("OPC_ENDPOINT") == "" { + panic("OPC_ENDPOINT not set in environment") + } + endpoint, err := url.Parse(os.Getenv("OPC_ENDPOINT")) + if err != nil { + return nil, err + } + c.APIEndpoint = endpoint + } + + if c.IdentityDomain == nil { + domain := os.Getenv("OPC_IDENTITY_DOMAIN") + c.IdentityDomain = &domain + } + + if c.Username == nil { + username := os.Getenv("OPC_USERNAME") + c.Username = &username + } + + if c.Password == nil { + password := os.Getenv("OPC_PASSWORD") + c.Password = &password + } + + if c.HTTPClient == nil { + c.HTTPClient = &http.Client{ + Transport: &http.Transport{ + Proxy: http.ProxyFromEnvironment, + TLSHandshakeTimeout: 120 * time.Second}, + } + } + + return NewComputeClient(c) +} + +func getBlankTestClient() (*Client, *httptest.Server, error) { + server := newAuthenticatingServer(func(w http.ResponseWriter, r *http.Request) { + }) + + endpoint, err := url.Parse(server.URL) + if err != nil { + server.Close() + return nil, nil, err + } + + client, err := getTestClient(&opc.Config{ + IdentityDomain: opc.String(_ClientTestDomain), + Username: opc.String(_ClientTestUser), + APIEndpoint: endpoint, + }) + if err != nil { + server.Close() + return nil, nil, err + } + return client, server, nil +} + +// Returns a stub client with default values, and a custom API Endpoint +func getStubClient(endpoint *url.URL) (*Client, error) { + domain := "test" + username := "test" + password := "test" + config := &opc.Config{ + IdentityDomain: &domain, + Username: &username, + Password: &password, + APIEndpoint: endpoint, + } + return getTestClient(config) +} + +func unmarshalRequestBody(t *testing.T, r *http.Request, target interface{}) { + buf := new(bytes.Buffer) + buf.ReadFrom(r.Body) + err := json.Unmarshal(buf.Bytes(), target) + if err != nil { + t.Fatalf("Error marshalling request: %s", err) + } +} diff --git a/vendor/github.com/hashicorp/go-oracle-terraform/compute/virtual_nic.go b/vendor/github.com/hashicorp/go-oracle-terraform/compute/virtual_nic.go new file mode 100644 index 000000000..825bb8fe8 --- /dev/null +++ b/vendor/github.com/hashicorp/go-oracle-terraform/compute/virtual_nic.go @@ -0,0 +1,52 @@ +package compute + +type VirtNICsClient struct { + ResourceClient +} + +func (c *Client) VirtNICs() *VirtNICsClient { + return &VirtNICsClient{ + ResourceClient: ResourceClient{ + Client: c, + ResourceDescription: "Virtual NIC", + ContainerPath: "/network/v1/vnic/", + ResourceRootPath: "/network/v1/vnic", + }, + } +} + +type VirtualNIC struct { + // Description of the object. + Description string `json:"description"` + // MAC address of this VNIC. + MACAddress string `json:"macAddress"` + // The three-part name (/Compute-identity_domain/user/object) of the Virtual NIC. + Name string `json:"name"` + // Tags associated with the object. + Tags []string `json:"tags"` + // True if the VNIC is of type "transit". + TransitFlag bool `json:"transitFlag"` + // Uniform Resource Identifier + Uri string `json:"uri"` +} + +// Can only GET a virtual NIC, not update, create, or delete +type GetVirtualNICInput struct { + // The three-part name (/Compute-identity_domain/user/object) of the Virtual NIC. + // Required + Name string `json:"name"` +} + +func (c *VirtNICsClient) GetVirtualNIC(input *GetVirtualNICInput) (*VirtualNIC, error) { + var virtNIC VirtualNIC + input.Name = c.getQualifiedName(input.Name) + if err := c.getResource(input.Name, &virtNIC); err != nil { + return nil, err + } + return c.success(&virtNIC) +} + +func (c *VirtNICsClient) success(info *VirtualNIC) (*VirtualNIC, error) { + c.unqualify(&info.Name) + return info, nil +} diff --git a/vendor/github.com/hashicorp/go-oracle-terraform/compute/virtual_nic_sets.go b/vendor/github.com/hashicorp/go-oracle-terraform/compute/virtual_nic_sets.go new file mode 100644 index 000000000..ef9035f26 --- /dev/null +++ b/vendor/github.com/hashicorp/go-oracle-terraform/compute/virtual_nic_sets.go @@ -0,0 +1,154 @@ +package compute + +type VirtNICSetsClient struct { + ResourceClient +} + +func (c *Client) VirtNICSets() *VirtNICSetsClient { + return &VirtNICSetsClient{ + ResourceClient: ResourceClient{ + Client: c, + ResourceDescription: "Virtual NIC Set", + ContainerPath: "/network/v1/vnicset/", + ResourceRootPath: "/network/v1/vnicset", + }, + } +} + +// Describes an existing virtual nic set +type VirtualNICSet struct { + // List of ACLs applied to the VNICs in the set. + AppliedACLs []string `json:"appliedAcls"` + // Description of the VNIC Set. + Description string `json:"description"` + // Name of the VNIC set. + Name string `json:"name"` + // The three-part name (/Compute-identity_domain/user/object) of the virtual NIC set. + Tags []string `json:"tags"` + // Uniform Resource Identifier + Uri string `json:"uri"` + // List of VNICs associated with this VNIC set. + VirtualNICs []string `json:"vnics"` +} + +type CreateVirtualNICSetInput struct { + // List of ACLs applied to the VNICs in the set. + // Optional + AppliedACLs []string `json:"appliedAcls"` + // Description of the object. + // Optional + Description string `json:"description"` + // The three-part name (/Compute-identity_domain/user/object) of the virtual NIC set. + // Object names can contain only alphanumeric, underscore (_), dash (-), and period (.) characters. Object names are case-sensitive. + // Required + Name string `json:"name"` + // Tags associated with this VNIC set. + // Optional + Tags []string `json:"tags"` + // List of VNICs associated with this VNIC set. + // Optional + VirtualNICs []string `json:"vnics"` +} + +func (c *VirtNICSetsClient) CreateVirtualNICSet(input *CreateVirtualNICSetInput) (*VirtualNICSet, error) { + input.Name = c.getQualifiedName(input.Name) + input.AppliedACLs = c.getQualifiedAcls(input.AppliedACLs) + qualifiedNics := c.getQualifiedList(input.VirtualNICs) + if len(qualifiedNics) != 0 { + input.VirtualNICs = qualifiedNics + } + + var virtNicSet VirtualNICSet + if err := c.createResource(input, &virtNicSet); err != nil { + return nil, err + } + + return c.success(&virtNicSet) +} + +type GetVirtualNICSetInput struct { + // The three-part name (/Compute-identity_domain/user/object) of the virtual NIC set. + // Required + Name string `json:"name"` +} + +func (c *VirtNICSetsClient) GetVirtualNICSet(input *GetVirtualNICSetInput) (*VirtualNICSet, error) { + var virtNicSet VirtualNICSet + // Qualify Name + input.Name = c.getQualifiedName(input.Name) + if err := c.getResource(input.Name, &virtNicSet); err != nil { + return nil, err + } + + return c.success(&virtNicSet) +} + +type UpdateVirtualNICSetInput struct { + // List of ACLs applied to the VNICs in the set. + // Optional + AppliedACLs []string `json:"appliedAcls"` + // Description of the object. + // Optional + Description string `json:"description"` + // The three-part name (/Compute-identity_domain/user/object) of the virtual NIC set. + // Object names can contain only alphanumeric, underscore (_), dash (-), and period (.) characters. Object names are case-sensitive. + // Required + Name string `json:"name"` + // Tags associated with this VNIC set. + // Optional + Tags []string `json:"tags"` + // List of VNICs associated with this VNIC set. + // Optional + VirtualNICs []string `json:"vnics"` +} + +func (c *VirtNICSetsClient) UpdateVirtualNICSet(input *UpdateVirtualNICSetInput) (*VirtualNICSet, error) { + input.Name = c.getQualifiedName(input.Name) + input.AppliedACLs = c.getQualifiedAcls(input.AppliedACLs) + // Qualify VirtualNICs + qualifiedVNICs := c.getQualifiedList(input.VirtualNICs) + if len(qualifiedVNICs) != 0 { + input.VirtualNICs = qualifiedVNICs + } + + var virtNICSet VirtualNICSet + if err := c.updateResource(input.Name, input, &virtNICSet); err != nil { + return nil, err + } + + return c.success(&virtNICSet) +} + +type DeleteVirtualNICSetInput struct { + // The name of the virtual NIC set. + // Required + Name string `json:"name"` +} + +func (c *VirtNICSetsClient) DeleteVirtualNICSet(input *DeleteVirtualNICSetInput) error { + input.Name = c.getQualifiedName(input.Name) + return c.deleteResource(input.Name) +} + +func (c *VirtNICSetsClient) getQualifiedAcls(acls []string) []string { + qualifiedAcls := []string{} + for _, acl := range acls { + qualifiedAcls = append(qualifiedAcls, c.getQualifiedName(acl)) + } + return qualifiedAcls +} + +func (c *VirtNICSetsClient) unqualifyAcls(acls []string) []string { + unqualifiedAcls := []string{} + for _, acl := range acls { + unqualifiedAcls = append(unqualifiedAcls, c.getUnqualifiedName(acl)) + } + return unqualifiedAcls +} + +func (c *VirtNICSetsClient) success(info *VirtualNICSet) (*VirtualNICSet, error) { + c.unqualify(&info.Name) + info.AppliedACLs = c.unqualifyAcls(info.AppliedACLs) + info.VirtualNICs = c.getUnqualifiedList(info.VirtualNICs) + return info, nil +} diff --git a/vendor/github.com/hashicorp/go-oracle-terraform/helper/testing.go b/vendor/github.com/hashicorp/go-oracle-terraform/helper/testing.go new file mode 100644 index 000000000..eccbdeeb2 --- /dev/null +++ b/vendor/github.com/hashicorp/go-oracle-terraform/helper/testing.go @@ -0,0 +1,44 @@ +package helper + +import ( + "fmt" + "log" + "math/rand" + "os" + "time" + + "github.com/hashicorp/go-oracle-terraform/opc" +) + +const TestEnvVar = "ORACLE_ACC" + +// Test suite helpers + +type TestCase struct { + // Fields to test stuff with +} + +func Test(t TestT, c TestCase) { + if os.Getenv(TestEnvVar) == "" { + t.Skip(fmt.Sprintf("Acceptance tests skipped unless env '%s' is set", TestEnvVar)) + return + } + + // Setup logging Output + logWriter, err := opc.LogOutput() + if err != nil { + t.Error(fmt.Sprintf("Error setting up log writer: %s", err)) + } + log.SetOutput(logWriter) +} + +type TestT interface { + Error(args ...interface{}) + Fatal(args ...interface{}) + Skip(args ...interface{}) +} + +func RInt() int { + rand.Seed(time.Now().UTC().UnixNano()) + return rand.Int() +} diff --git a/vendor/github.com/hashicorp/go-oracle-terraform/opc/config.go b/vendor/github.com/hashicorp/go-oracle-terraform/opc/config.go new file mode 100644 index 000000000..0ac83ec88 --- /dev/null +++ b/vendor/github.com/hashicorp/go-oracle-terraform/opc/config.go @@ -0,0 +1,21 @@ +package opc + +import ( + "net/http" + "net/url" +) + +type Config struct { + Username *string + Password *string + IdentityDomain *string + APIEndpoint *url.URL + MaxRetries *int + LogLevel LogLevelType + Logger Logger + HTTPClient *http.Client +} + +func NewConfig() *Config { + return &Config{} +} diff --git a/vendor/github.com/hashicorp/go-oracle-terraform/opc/convert.go b/vendor/github.com/hashicorp/go-oracle-terraform/opc/convert.go new file mode 100644 index 000000000..3fa365c1c --- /dev/null +++ b/vendor/github.com/hashicorp/go-oracle-terraform/opc/convert.go @@ -0,0 +1,5 @@ +package opc + +func String(v string) *string { + return &v +} diff --git a/vendor/github.com/hashicorp/go-oracle-terraform/opc/errors.go b/vendor/github.com/hashicorp/go-oracle-terraform/opc/errors.go new file mode 100644 index 000000000..6b12c10d9 --- /dev/null +++ b/vendor/github.com/hashicorp/go-oracle-terraform/opc/errors.go @@ -0,0 +1,12 @@ +package opc + +import "fmt" + +type OracleError struct { + StatusCode int + Message string +} + +func (e OracleError) Error() string { + return fmt.Sprintf("%d: %s", e.StatusCode, e.Message) +} diff --git a/vendor/github.com/hashicorp/go-oracle-terraform/opc/logger.go b/vendor/github.com/hashicorp/go-oracle-terraform/opc/logger.go new file mode 100644 index 000000000..f9714a7a8 --- /dev/null +++ b/vendor/github.com/hashicorp/go-oracle-terraform/opc/logger.go @@ -0,0 +1,70 @@ +package opc + +import ( + "io" + "io/ioutil" + "log" + "os" +) + +const ( + LogOff LogLevelType = 0 + LogDebug LogLevelType = 1 +) + +type LogLevelType uint + +// Logger interface. Should be satisfied by Terraform's logger as well as the Default logger +type Logger interface { + Log(...interface{}) +} + +type LoggerFunc func(...interface{}) + +func (f LoggerFunc) Log(args ...interface{}) { + f(args...) +} + +// Returns a default logger if one isn't specified during configuration +func NewDefaultLogger() Logger { + logWriter, err := LogOutput() + if err != nil { + log.Fatalf("Error setting up log writer: %s", err) + } + return &defaultLogger{ + logger: log.New(logWriter, "", log.LstdFlags), + } +} + +// Default logger to satisfy the logger interface +type defaultLogger struct { + logger *log.Logger +} + +func (l defaultLogger) Log(args ...interface{}) { + l.logger.Println(args...) +} + +func LogOutput() (logOutput io.Writer, err error) { + // Default to nil + logOutput = ioutil.Discard + + logLevel := LogLevel() + if logLevel == LogOff { + return + } + + // Logging is on, set output to STDERR + logOutput = os.Stderr + return +} + +// Gets current Log Level from the ORACLE_LOG env var +func LogLevel() LogLevelType { + envLevel := os.Getenv("ORACLE_LOG") + if envLevel == "" { + return LogOff + } else { + return LogDebug + } +} diff --git a/vendor/github.com/hashicorp/go-retryablehttp/client.go b/vendor/github.com/hashicorp/go-retryablehttp/client.go index d0ec6b2ab..198779bdf 100644 --- a/vendor/github.com/hashicorp/go-retryablehttp/client.go +++ b/vendor/github.com/hashicorp/go-retryablehttp/client.go @@ -32,8 +32,8 @@ import ( var ( // Default retry configuration defaultRetryWaitMin = 1 * time.Second - defaultRetryWaitMax = 5 * time.Minute - defaultRetryMax = 32 + defaultRetryWaitMax = 30 * time.Second + defaultRetryMax = 4 // defaultClient is used for performing requests without explicitly making // a new client. It is purposely private to avoid modifications. diff --git a/vendor/github.com/hashicorp/hcl/appveyor.yml b/vendor/github.com/hashicorp/hcl/appveyor.yml index 3c8cdf8e9..4db0b7112 100644 --- a/vendor/github.com/hashicorp/hcl/appveyor.yml +++ b/vendor/github.com/hashicorp/hcl/appveyor.yml @@ -4,7 +4,7 @@ clone_folder: c:\gopath\src\github.com\hashicorp\hcl environment: GOPATH: c:\gopath init: - - git config --global core.autocrlf true + - git config --global core.autocrlf false install: - cmd: >- echo %Path% diff --git a/vendor/github.com/hashicorp/hcl/hcl/parser/parser.go b/vendor/github.com/hashicorp/hcl/hcl/parser/parser.go index 6e54bed97..b4881806e 100644 --- a/vendor/github.com/hashicorp/hcl/hcl/parser/parser.go +++ b/vendor/github.com/hashicorp/hcl/hcl/parser/parser.go @@ -3,6 +3,7 @@ package parser import ( + "bytes" "errors" "fmt" "strings" @@ -36,6 +37,11 @@ func newParser(src []byte) *Parser { // Parse returns the fully parsed source and returns the abstract syntax tree. func Parse(src []byte) (*ast.File, error) { + // normalize all line endings + // since the scanner and output only work with "\n" line endings, we may + // end up with dangling "\r" characters in the parsed data. + src = bytes.Replace(src, []byte("\r\n"), []byte("\n"), -1) + p := newParser(src) return p.Parse() } diff --git a/vendor/github.com/hashicorp/hcl/hcl/printer/printer.go b/vendor/github.com/hashicorp/hcl/hcl/printer/printer.go index a296fc851..6617ab8e7 100644 --- a/vendor/github.com/hashicorp/hcl/hcl/printer/printer.go +++ b/vendor/github.com/hashicorp/hcl/hcl/printer/printer.go @@ -62,6 +62,5 @@ func Format(src []byte) ([]byte, error) { // Add trailing newline to result buf.WriteString("\n") - return buf.Bytes(), nil } diff --git a/vendor/github.com/hashicorp/hcl/json/parser/parser.go b/vendor/github.com/hashicorp/hcl/json/parser/parser.go index 6f4608530..125a5f072 100644 --- a/vendor/github.com/hashicorp/hcl/json/parser/parser.go +++ b/vendor/github.com/hashicorp/hcl/json/parser/parser.go @@ -147,7 +147,7 @@ func (p *Parser) objectKey() ([]*ast.ObjectKey, error) { // Done return keys, nil case token.ILLEGAL: - fmt.Println("illegal") + return nil, errors.New("illegal") default: return nil, fmt.Errorf("expected: STRING got: %s", p.tok.Type) } diff --git a/vendor/github.com/hashicorp/hil/ast/literal.go b/vendor/github.com/hashicorp/hil/ast/literal.go index 8149d495d..da6014fee 100644 --- a/vendor/github.com/hashicorp/hil/ast/literal.go +++ b/vendor/github.com/hashicorp/hil/ast/literal.go @@ -77,3 +77,12 @@ func (n *LiteralNode) String() string { func (n *LiteralNode) Type(Scope) (Type, error) { return n.Typex, nil } + +// IsUnknown returns true either if the node's value is itself unknown +// of if it is a collection containing any unknown elements, deeply. +func (n *LiteralNode) IsUnknown() bool { + return IsUnknown(Variable{ + Type: n.Typex, + Value: n.Value, + }) +} diff --git a/vendor/github.com/hashicorp/hil/ast/variables_helper.go b/vendor/github.com/hashicorp/hil/ast/variables_helper.go index 40aa534cf..06bd18de2 100644 --- a/vendor/github.com/hashicorp/hil/ast/variables_helper.go +++ b/vendor/github.com/hashicorp/hil/ast/variables_helper.go @@ -3,54 +3,61 @@ package ast import "fmt" func VariableListElementTypesAreHomogenous(variableName string, list []Variable) (Type, error) { - listTypes := make(map[Type]struct{}) + if len(list) == 0 { + return TypeInvalid, fmt.Errorf("list %q does not have any elements so cannot determine type.", variableName) + } + + elemType := TypeUnknown for _, v := range list { - // Allow unknown if v.Type == TypeUnknown { continue } - if _, ok := listTypes[v.Type]; ok { + if elemType == TypeUnknown { + elemType = v.Type continue } - listTypes[v.Type] = struct{}{} + + if v.Type != elemType { + return TypeInvalid, fmt.Errorf( + "list %q does not have homogenous types. found %s and then %s", + variableName, + elemType, v.Type, + ) + } + + elemType = v.Type } - if len(listTypes) != 1 && len(list) != 0 { - return TypeInvalid, fmt.Errorf("list %q does not have homogenous types. found %s", variableName, reportTypes(listTypes)) - } - - if len(list) > 0 { - return list[0].Type, nil - } - - return TypeInvalid, fmt.Errorf("list %q does not have any elements so cannot determine type.", variableName) + return elemType, nil } func VariableMapValueTypesAreHomogenous(variableName string, vmap map[string]Variable) (Type, error) { - valueTypes := make(map[Type]struct{}) + if len(vmap) == 0 { + return TypeInvalid, fmt.Errorf("map %q does not have any elements so cannot determine type.", variableName) + } + + elemType := TypeUnknown for _, v := range vmap { - // Allow unknown if v.Type == TypeUnknown { continue } - if _, ok := valueTypes[v.Type]; ok { + if elemType == TypeUnknown { + elemType = v.Type continue } - valueTypes[v.Type] = struct{}{} + if v.Type != elemType { + return TypeInvalid, fmt.Errorf( + "map %q does not have homogenous types. found %s and then %s", + variableName, + elemType, v.Type, + ) + } + + elemType = v.Type } - if len(valueTypes) != 1 && len(vmap) != 0 { - return TypeInvalid, fmt.Errorf("map %q does not have homogenous value types. found %s", variableName, reportTypes(valueTypes)) - } - - // For loop here is an easy way to get a single key, we return immediately. - for _, v := range vmap { - return v.Type, nil - } - - // This means the map is empty - return TypeInvalid, fmt.Errorf("map %q does not have any elements so cannot determine type.", variableName) + return elemType, nil } diff --git a/vendor/github.com/hashicorp/hil/check_types.go b/vendor/github.com/hashicorp/hil/check_types.go index a8ca44e06..f16da3918 100644 --- a/vendor/github.com/hashicorp/hil/check_types.go +++ b/vendor/github.com/hashicorp/hil/check_types.go @@ -98,10 +98,6 @@ func (v *TypeCheck) visit(raw ast.Node) ast.Node { pos.Column, pos.Line, err) } - if v.StackPeek() == ast.TypeUnknown { - v.err = errExitUnknown - } - return result } @@ -116,6 +112,14 @@ func (tc *typeCheckArithmetic) TypeCheck(v *TypeCheck) (ast.Node, error) { exprs[len(tc.n.Exprs)-1-i] = v.StackPop() } + // If any operand is unknown then our result is automatically unknown + for _, ty := range exprs { + if ty == ast.TypeUnknown { + v.StackPush(ast.TypeUnknown) + return tc.n, nil + } + } + switch tc.n.Op { case ast.ArithmeticOpLogicalAnd, ast.ArithmeticOpLogicalOr: return tc.checkLogical(v, exprs) @@ -333,6 +337,11 @@ func (tc *typeCheckCall) TypeCheck(v *TypeCheck) (ast.Node, error) { continue } + if args[i] == ast.TypeUnknown { + v.StackPush(ast.TypeUnknown) + return tc.n, nil + } + if args[i] != expected { cn := v.ImplicitConversion(args[i], expected, tc.n.Args[i]) if cn != nil { @@ -350,6 +359,11 @@ func (tc *typeCheckCall) TypeCheck(v *TypeCheck) (ast.Node, error) { if function.Variadic && function.VariadicType != ast.TypeAny { args = args[len(function.ArgTypes):] for i, t := range args { + if t == ast.TypeUnknown { + v.StackPush(ast.TypeUnknown) + return tc.n, nil + } + if t != function.VariadicType { realI := i + len(function.ArgTypes) cn := v.ImplicitConversion( @@ -384,6 +398,11 @@ func (tc *typeCheckConditional) TypeCheck(v *TypeCheck) (ast.Node, error) { trueType := v.StackPop() condType := v.StackPop() + if condType == ast.TypeUnknown { + v.StackPush(ast.TypeUnknown) + return tc.n, nil + } + if condType != ast.TypeBool { cn := v.ImplicitConversion(condType, ast.TypeBool, tc.n.CondExpr) if cn == nil { @@ -395,7 +414,7 @@ func (tc *typeCheckConditional) TypeCheck(v *TypeCheck) (ast.Node, error) { } // The types of the true and false expression must match - if trueType != falseType { + if trueType != falseType && trueType != ast.TypeUnknown && falseType != ast.TypeUnknown { // Since passing around stringified versions of other types is // common, we pragmatically allow the false expression to dictate @@ -441,7 +460,13 @@ func (tc *typeCheckConditional) TypeCheck(v *TypeCheck) (ast.Node, error) { } // Result type (guaranteed to also match falseType due to the above) - v.StackPush(trueType) + if trueType == ast.TypeUnknown { + // falseType may also be unknown, but that's okay because two + // unknowns means our result is unknown anyway. + v.StackPush(falseType) + } else { + v.StackPush(trueType) + } return tc.n, nil } @@ -457,6 +482,13 @@ func (tc *typeCheckOutput) TypeCheck(v *TypeCheck) (ast.Node, error) { types[len(n.Exprs)-1-i] = v.StackPop() } + for _, ty := range types { + if ty == ast.TypeUnknown { + v.StackPush(ast.TypeUnknown) + return tc.n, nil + } + } + // If there is only one argument and it is a list, we evaluate to a list if len(types) == 1 { switch t := types[0]; t { @@ -469,7 +501,14 @@ func (tc *typeCheckOutput) TypeCheck(v *TypeCheck) (ast.Node, error) { } // Otherwise, all concat args must be strings, so validate that + resultType := ast.TypeString for i, t := range types { + + if t == ast.TypeUnknown { + resultType = ast.TypeUnknown + continue + } + if t != ast.TypeString { cn := v.ImplicitConversion(t, ast.TypeString, n.Exprs[i]) if cn != nil { @@ -482,8 +521,8 @@ func (tc *typeCheckOutput) TypeCheck(v *TypeCheck) (ast.Node, error) { } } - // This always results in type string - v.StackPush(ast.TypeString) + // This always results in type string, unless there are unknowns + v.StackPush(resultType) return n, nil } @@ -509,13 +548,6 @@ func (tc *typeCheckVariableAccess) TypeCheck(v *TypeCheck) (ast.Node, error) { "unknown variable accessed: %s", tc.n.Name) } - // Check if the variable contains any unknown types. If so, then - // mark it as unknown. - if ast.IsUnknown(variable) { - v.StackPush(ast.TypeUnknown) - return tc.n, nil - } - // Add the type to the stack v.StackPush(variable.Type) @@ -530,6 +562,11 @@ func (tc *typeCheckIndex) TypeCheck(v *TypeCheck) (ast.Node, error) { keyType := v.StackPop() targetType := v.StackPop() + if keyType == ast.TypeUnknown || targetType == ast.TypeUnknown { + v.StackPush(ast.TypeUnknown) + return tc.n, nil + } + // Ensure we have a VariableAccess as the target varAccessNode, ok := tc.n.Target.(*ast.VariableAccess) if !ok { diff --git a/vendor/github.com/hashicorp/hil/eval.go b/vendor/github.com/hashicorp/hil/eval.go index 5c7afb024..27820769e 100644 --- a/vendor/github.com/hashicorp/hil/eval.go +++ b/vendor/github.com/hashicorp/hil/eval.go @@ -54,6 +54,14 @@ func Eval(root ast.Node, config *EvalConfig) (EvaluationResult, error) { return InvalidResult, err } + // If the result contains any nested unknowns then the result as a whole + // is unknown, so that callers only have to deal with "entirely known" + // or "entirely unknown" as outcomes. + if ast.IsUnknown(ast.Variable{Type: outputType, Value: output}) { + outputType = ast.TypeUnknown + output = UnknownValue + } + switch outputType { case ast.TypeList: val, err := VariableToInterface(ast.Variable{ @@ -264,6 +272,10 @@ func (v *evalCall) Eval(s ast.Scope, stack *ast.Stack) (interface{}, ast.Type, e args := make([]interface{}, len(v.Args)) for i, _ := range v.Args { node := stack.Pop().(*ast.LiteralNode) + if node.IsUnknown() { + // If any arguments are unknown then the result is automatically unknown + return UnknownValue, ast.TypeUnknown, nil + } args[len(v.Args)-1-i] = node.Value } @@ -286,6 +298,11 @@ func (v *evalConditional) Eval(s ast.Scope, stack *ast.Stack) (interface{}, ast. trueLit := stack.Pop().(*ast.LiteralNode) condLit := stack.Pop().(*ast.LiteralNode) + if condLit.IsUnknown() { + // If our conditional is unknown then our result is also unknown + return UnknownValue, ast.TypeUnknown, nil + } + if condLit.Value.(bool) { return trueLit.Value, trueLit.Typex, nil } else { @@ -301,6 +318,17 @@ func (v *evalIndex) Eval(scope ast.Scope, stack *ast.Stack) (interface{}, ast.Ty variableName := v.Index.Target.(*ast.VariableAccess).Name + if key.IsUnknown() { + // If our key is unknown then our result is also unknown + return UnknownValue, ast.TypeUnknown, nil + } + + // For target, we'll accept collections containing unknown values but + // we still need to catch when the collection itself is unknown, shallowly. + if target.Typex == ast.TypeUnknown { + return UnknownValue, ast.TypeUnknown, nil + } + switch target.Typex { case ast.TypeList: return v.evalListIndex(variableName, target.Value, key.Value) @@ -377,8 +405,22 @@ func (v *evalOutput) Eval(s ast.Scope, stack *ast.Stack) (interface{}, ast.Type, // The expressions should all be on the stack in reverse // order. So pop them off, reverse their order, and concatenate. nodes := make([]*ast.LiteralNode, 0, len(v.Exprs)) + haveUnknown := false for range v.Exprs { - nodes = append(nodes, stack.Pop().(*ast.LiteralNode)) + n := stack.Pop().(*ast.LiteralNode) + nodes = append(nodes, n) + + // If we have any unknowns then the whole result is unknown + // (we must deal with this first, because the type checker can + // skip type conversions in the presence of unknowns, and thus + // any of our other nodes may be incorrectly typed.) + if n.IsUnknown() { + haveUnknown = true + } + } + + if haveUnknown { + return UnknownValue, ast.TypeUnknown, nil } // Special case the single list and map @@ -396,6 +438,14 @@ func (v *evalOutput) Eval(s ast.Scope, stack *ast.Stack) (interface{}, ast.Type, // Otherwise concatenate the strings var buf bytes.Buffer for i := len(nodes) - 1; i >= 0; i-- { + if nodes[i].Typex != ast.TypeString { + return nil, ast.TypeInvalid, fmt.Errorf( + "invalid output with %s value at index %d: %#v", + nodes[i].Typex, + i, + nodes[i].Value, + ) + } buf.WriteString(nodes[i].Value.(string)) } @@ -418,11 +468,5 @@ func (v *evalVariableAccess) Eval(scope ast.Scope, _ *ast.Stack) (interface{}, a "unknown variable accessed: %s", v.Name) } - // Check if the variable contains any unknown types. If so, then - // mark it as unknown and return that type. - if ast.IsUnknown(variable) { - return nil, ast.TypeUnknown, nil - } - return variable.Value, variable.Type, nil } diff --git a/vendor/github.com/hashicorp/terraform-provider-opc/LICENSE b/vendor/github.com/hashicorp/terraform-provider-opc/LICENSE new file mode 100644 index 000000000..a612ad981 --- /dev/null +++ b/vendor/github.com/hashicorp/terraform-provider-opc/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/terraform-provider-opc/opc/config.go b/vendor/github.com/hashicorp/terraform-provider-opc/opc/config.go new file mode 100644 index 000000000..b82594cca --- /dev/null +++ b/vendor/github.com/hashicorp/terraform-provider-opc/opc/config.go @@ -0,0 +1,60 @@ +package opc + +import ( + "fmt" + "log" + "net/url" + "strings" + + "github.com/hashicorp/go-cleanhttp" + "github.com/hashicorp/go-oracle-terraform/compute" + "github.com/hashicorp/go-oracle-terraform/opc" + "github.com/hashicorp/terraform/helper/logging" +) + +type Config struct { + User string + Password string + IdentityDomain string + Endpoint string + MaxRetryTimeout int +} + +type OPCClient struct { + Client *compute.Client + MaxRetryTimeout int +} + +func (c *Config) Client() (*compute.Client, error) { + u, err := url.ParseRequestURI(c.Endpoint) + if err != nil { + return nil, fmt.Errorf("Invalid endpoint URI: %s", err) + } + + config := opc.Config{ + IdentityDomain: &c.IdentityDomain, + Username: &c.User, + Password: &c.Password, + APIEndpoint: u, + HTTPClient: cleanhttp.DefaultClient(), + } + + if logging.IsDebugOrHigher() { + config.LogLevel = opc.LogDebug + config.Logger = opcLogger{} + } + + return compute.NewComputeClient(&config) +} + +type opcLogger struct{} + +func (l opcLogger) 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] [go-oracle-terraform]: %s", strings.Join(tokens, " ")) +} diff --git a/vendor/github.com/hashicorp/terraform-provider-opc/opc/data_source_network_interface.go b/vendor/github.com/hashicorp/terraform-provider-opc/opc/data_source_network_interface.go new file mode 100644 index 000000000..5a5b8fa78 --- /dev/null +++ b/vendor/github.com/hashicorp/terraform-provider-opc/opc/data_source_network_interface.go @@ -0,0 +1,176 @@ +package opc + +import ( + "fmt" + "log" + + "github.com/hashicorp/go-oracle-terraform/compute" + "github.com/hashicorp/terraform/helper/schema" +) + +func dataSourceNetworkInterface() *schema.Resource { + return &schema.Resource{ + Read: dataSourceNetworkInterfaceRead, + + Schema: map[string]*schema.Schema{ + "instance_id": { + Type: schema.TypeString, + Required: true, + }, + + "instance_name": { + Type: schema.TypeString, + Required: true, + }, + + "interface": { + Type: schema.TypeString, + Required: true, + }, + + // Computed Values returned from the data source lookup + "dns": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{Type: schema.TypeString}, + }, + + "ip_address": { + Type: schema.TypeString, + Computed: true, + }, + + "ip_network": { + Type: schema.TypeString, + Computed: true, + }, + + "mac_address": { + Type: schema.TypeString, + Computed: true, + }, + + "model": { + Type: schema.TypeString, + Computed: true, + }, + + "name_servers": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{Type: schema.TypeString}, + }, + + "nat": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{Type: schema.TypeString}, + }, + + "search_domains": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{Type: schema.TypeString}, + }, + + "sec_lists": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{Type: schema.TypeString}, + }, + + "shared_network": { + Type: schema.TypeBool, + Computed: true, + }, + + "vnic": { + Type: schema.TypeString, + Computed: true, + }, + + "vnic_sets": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{Type: schema.TypeString}, + }, + }, + } +} + +func dataSourceNetworkInterfaceRead(d *schema.ResourceData, meta interface{}) error { + client := meta.(*compute.Client).Instances() + + // Get required attributes + instance_name := d.Get("instance_name").(string) + instance_id := d.Get("instance_id").(string) + targetInterface := d.Get("interface").(string) + + // Get instance + input := &compute.GetInstanceInput{ + Name: instance_name, + ID: instance_id, + } + + instance, err := client.GetInstance(input) + if err != nil { + if compute.WasNotFoundError(err) { + d.SetId("") + return nil + } + return fmt.Errorf("Error reading instance %q: %v", instance_name, err) + } + + result := compute.NetworkingInfo{} + + // If the target instance has no network interfaces, return + if instance.Networking == nil { + d.SetId("") + return nil + } + + // Set the computed fields + result = instance.Networking[targetInterface] + + // Check if the target interface exists or not + if &result == nil { + log.Printf("[WARN] %q networking interface not found on instance %q", targetInterface, instance_name) + } + + d.SetId(fmt.Sprintf("%s-%s", instance_name, targetInterface)) + + // vNIC is a required field for an IP Network interface, and can only be set if the network + // interface is inside an IP Network. Use this key to determine shared_network status + if result.Vnic != "" { + d.Set("shared_network", false) + } else { + d.Set("shared_network", true) + } + + d.Set("ip_address", result.IPAddress) + d.Set("ip_network", result.IPNetwork) + d.Set("mac_address", result.MACAddress) + d.Set("model", result.Model) + d.Set("vnic", result.Vnic) + + if err := setStringList(d, "dns", result.DNS); err != nil { + return err + } + if err := setStringList(d, "name_servers", result.NameServers); err != nil { + return err + } + if err := setStringList(d, "nat", result.Nat); err != nil { + return err + } + if err := setStringList(d, "search_domains", result.SearchDomains); err != nil { + return err + } + if err := setStringList(d, "sec_lists", result.SecLists); err != nil { + return err + } + if err := setStringList(d, "vnic_sets", result.VnicSets); err != nil { + return err + } + + return nil +} diff --git a/vendor/github.com/hashicorp/terraform-provider-opc/opc/data_source_virtual_nic.go b/vendor/github.com/hashicorp/terraform-provider-opc/opc/data_source_virtual_nic.go new file mode 100644 index 000000000..2878cf489 --- /dev/null +++ b/vendor/github.com/hashicorp/terraform-provider-opc/opc/data_source_virtual_nic.go @@ -0,0 +1,72 @@ +package opc + +import ( + "fmt" + + "github.com/hashicorp/go-oracle-terraform/compute" + "github.com/hashicorp/terraform/helper/schema" +) + +func dataSourceVNIC() *schema.Resource { + return &schema.Resource{ + Read: dataSourceVNICRead, + + Schema: map[string]*schema.Schema{ + "name": { + Type: schema.TypeString, + Required: true, + }, + + "description": { + Type: schema.TypeString, + Computed: true, + }, + + "mac_address": { + Type: schema.TypeString, + Computed: true, + }, + + "tags": tagsComputedSchema(), + + "transit_flag": { + Type: schema.TypeBool, + Computed: true, + }, + + "uri": { + Type: schema.TypeString, + Computed: true, + }, + }, + } +} + +func dataSourceVNICRead(d *schema.ResourceData, meta interface{}) error { + client := meta.(*compute.Client).VirtNICs() + + name := d.Get("name").(string) + + input := &compute.GetVirtualNICInput{ + Name: name, + } + + vnic, err := client.GetVirtualNIC(input) + if err != nil { + if compute.WasNotFoundError(err) { + d.SetId("") + return nil + } + return fmt.Errorf("Error reading vnic %s: %s", name, err) + } + + d.SetId(name) + d.Set("description", vnic.Description) + d.Set("mac_address", vnic.MACAddress) + d.Set("transit_flag", vnic.TransitFlag) + d.Set("uri", vnic.Uri) + if err := setStringList(d, "tags", vnic.Tags); err != nil { + return err + } + return nil +} diff --git a/vendor/github.com/hashicorp/terraform-provider-opc/opc/helpers.go b/vendor/github.com/hashicorp/terraform-provider-opc/opc/helpers.go new file mode 100644 index 000000000..ea0123c96 --- /dev/null +++ b/vendor/github.com/hashicorp/terraform-provider-opc/opc/helpers.go @@ -0,0 +1,47 @@ +package opc + +import ( + "sort" + + "github.com/hashicorp/terraform/helper/schema" +) + +// Helper function to get a string list from the schema, and alpha-sort it +func getStringList(d *schema.ResourceData, key string) []string { + if _, ok := d.GetOk(key); !ok { + return nil + } + l := d.Get(key).([]interface{}) + res := make([]string, len(l)) + for i, v := range l { + res[i] = v.(string) + } + sort.Strings(res) + return res +} + +// Helper function to set a string list in the schema, in an alpha-sorted order. +func setStringList(d *schema.ResourceData, key string, value []string) error { + sort.Strings(value) + return d.Set(key, value) +} + +// Helper function to get an int list from the schema, and numerically sort it +func getIntList(d *schema.ResourceData, key string) []int { + if _, ok := d.GetOk(key); !ok { + return nil + } + + l := d.Get(key).([]interface{}) + res := make([]int, len(l)) + for i, v := range l { + res[i] = v.(int) + } + sort.Ints(res) + return res +} + +func setIntList(d *schema.ResourceData, key string, value []int) error { + sort.Ints(value) + return d.Set(key, value) +} diff --git a/vendor/github.com/hashicorp/terraform-provider-opc/opc/provider.go b/vendor/github.com/hashicorp/terraform-provider-opc/opc/provider.go new file mode 100644 index 000000000..8f52bd874 --- /dev/null +++ b/vendor/github.com/hashicorp/terraform-provider-opc/opc/provider.go @@ -0,0 +1,93 @@ +package opc + +import ( + "github.com/hashicorp/terraform/helper/schema" + "github.com/hashicorp/terraform/terraform" +) + +func Provider() terraform.ResourceProvider { + return &schema.Provider{ + Schema: map[string]*schema.Schema{ + "user": { + Type: schema.TypeString, + Required: true, + DefaultFunc: schema.EnvDefaultFunc("OPC_USERNAME", nil), + Description: "The user name for OPC API operations.", + }, + + "password": { + Type: schema.TypeString, + Required: true, + DefaultFunc: schema.EnvDefaultFunc("OPC_PASSWORD", nil), + Description: "The user password for OPC API operations.", + }, + + "identity_domain": { + Type: schema.TypeString, + Required: true, + DefaultFunc: schema.EnvDefaultFunc("OPC_IDENTITY_DOMAIN", nil), + Description: "The OPC identity domain for API operations", + }, + + "endpoint": { + Type: schema.TypeString, + Required: true, + DefaultFunc: schema.EnvDefaultFunc("OPC_ENDPOINT", nil), + Description: "The HTTP endpoint for OPC API operations.", + }, + + // TODO Actually implement this + "max_retry_timeout": { + Type: schema.TypeInt, + Optional: true, + DefaultFunc: schema.EnvDefaultFunc("OPC_MAX_RETRY_TIMEOUT", 3000), + Description: "Max num seconds to wait for successful response when operating on resources within OPC (defaults to 3000)", + }, + }, + + DataSourcesMap: map[string]*schema.Resource{ + "opc_compute_network_interface": dataSourceNetworkInterface(), + "opc_compute_vnic": dataSourceVNIC(), + }, + + ResourcesMap: map[string]*schema.Resource{ + "opc_compute_ip_network": resourceOPCIPNetwork(), + "opc_compute_acl": resourceOPCACL(), + "opc_compute_image_list": resourceOPCImageList(), + "opc_compute_image_list_entry": resourceOPCImageListEntry(), + "opc_compute_instance": resourceInstance(), + "opc_compute_ip_address_reservation": resourceOPCIPAddressReservation(), + "opc_compute_ip_association": resourceOPCIPAssociation(), + "opc_compute_ip_network_exchange": resourceOPCIPNetworkExchange(), + "opc_compute_ip_reservation": resourceOPCIPReservation(), + "opc_compute_route": resourceOPCRoute(), + "opc_compute_security_application": resourceOPCSecurityApplication(), + "opc_compute_security_association": resourceOPCSecurityAssociation(), + "opc_compute_security_ip_list": resourceOPCSecurityIPList(), + "opc_compute_security_list": resourceOPCSecurityList(), + "opc_compute_security_rule": resourceOPCSecurityRule(), + "opc_compute_sec_rule": resourceOPCSecRule(), + "opc_compute_ssh_key": resourceOPCSSHKey(), + "opc_compute_storage_volume": resourceOPCStorageVolume(), + "opc_compute_storage_volume_snapshot": resourceOPCStorageVolumeSnapshot(), + "opc_compute_vnic_set": resourceOPCVNICSet(), + "opc_compute_security_protocol": resourceOPCSecurityProtocol(), + "opc_compute_ip_address_prefix_set": resourceOPCIPAddressPrefixSet(), + "opc_compute_ip_address_association": resourceOPCIPAddressAssociation(), + }, + + ConfigureFunc: providerConfigure, + } +} + +func providerConfigure(d *schema.ResourceData) (interface{}, error) { + config := Config{ + User: d.Get("user").(string), + Password: d.Get("password").(string), + IdentityDomain: d.Get("identity_domain").(string), + Endpoint: d.Get("endpoint").(string), + MaxRetryTimeout: d.Get("max_retry_timeout").(int), + } + + return config.Client() +} diff --git a/vendor/github.com/hashicorp/terraform-provider-opc/opc/resource_acl.go b/vendor/github.com/hashicorp/terraform-provider-opc/opc/resource_acl.go new file mode 100644 index 000000000..55558b7fa --- /dev/null +++ b/vendor/github.com/hashicorp/terraform-provider-opc/opc/resource_acl.go @@ -0,0 +1,151 @@ +package opc + +import ( + "fmt" + "log" + + "github.com/hashicorp/go-oracle-terraform/compute" + "github.com/hashicorp/terraform/helper/schema" +) + +func resourceOPCACL() *schema.Resource { + return &schema.Resource{ + Create: resourceOPCACLCreate, + Read: resourceOPCACLRead, + Update: resourceOPCACLUpdate, + Delete: resourceOPCACLDelete, + Importer: &schema.ResourceImporter{ + State: schema.ImportStatePassthrough, + }, + + Schema: map[string]*schema.Schema{ + "name": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + "description": { + Type: schema.TypeString, + Optional: true, + }, + "enabled": { + Type: schema.TypeBool, + Optional: true, + Default: true, + }, + "tags": { + Type: schema.TypeList, + Optional: true, + Elem: &schema.Schema{Type: schema.TypeString}, + ForceNew: true, + }, + "uri": { + Type: schema.TypeString, + Computed: true, + }, + }, + } +} + +func resourceOPCACLCreate(d *schema.ResourceData, meta interface{}) error { + log.Printf("[DEBUG] Resource state: %#v", d.State()) + + log.Print("[DEBUG] Creating acl") + + client := meta.(*compute.Client).ACLs() + input := compute.CreateACLInput{ + Name: d.Get("name").(string), + Enabled: d.Get("enabled").(bool), + } + + tags := getStringList(d, "tags") + if len(tags) != 0 { + input.Tags = tags + } + + if description, ok := d.GetOk("description"); ok { + input.Description = description.(string) + } + + info, err := client.CreateACL(&input) + if err != nil { + return fmt.Errorf("Error creating ACL: %s", err) + } + + d.SetId(info.Name) + return resourceOPCACLRead(d, meta) +} + +func resourceOPCACLRead(d *schema.ResourceData, meta interface{}) error { + log.Printf("[DEBUG] Resource state: %#v", d.State()) + client := meta.(*compute.Client).ACLs() + + log.Printf("[DEBUG] Reading state of ip reservation %s", d.Id()) + getInput := compute.GetACLInput{ + Name: d.Id(), + } + result, err := client.GetACL(&getInput) + if err != nil { + // ACL does not exist + if compute.WasNotFoundError(err) { + d.SetId("") + return nil + } + return fmt.Errorf("Error reading acl %s: %s", d.Id(), err) + } + + log.Printf("[DEBUG] Read state of acl %s: %#v", d.Id(), result) + d.Set("name", result.Name) + d.Set("enabled", result.Enabled) + d.Set("description", result.Description) + d.Set("uri", result.URI) + if err := setStringList(d, "tags", result.Tags); err != nil { + return err + } + return nil +} + +func resourceOPCACLUpdate(d *schema.ResourceData, meta interface{}) error { + log.Printf("[DEBUG] Resource state: %#v", d.State()) + + log.Print("[DEBUG] Updating acl") + + client := meta.(*compute.Client).ACLs() + input := compute.UpdateACLInput{ + Name: d.Get("name").(string), + Enabled: d.Get("enabled").(bool), + } + + tags := getStringList(d, "tags") + if len(tags) != 0 { + input.Tags = tags + } + + if description, ok := d.GetOk("description"); ok { + input.Description = description.(string) + } + + info, err := client.UpdateACL(&input) + if err != nil { + return fmt.Errorf("Error updating ACL: %s", err) + } + + d.SetId(info.Name) + return resourceOPCACLRead(d, meta) +} + +func resourceOPCACLDelete(d *schema.ResourceData, meta interface{}) error { + log.Printf("[DEBUG] Resource state: %#v", d.State()) + client := meta.(*compute.Client).ACLs() + name := d.Id() + + log.Printf("[DEBUG] Deleting ACL: %v", name) + + input := compute.DeleteACLInput{ + Name: name, + } + if err := client.DeleteACL(&input); err != nil { + return fmt.Errorf("Error deleting ACL") + } + return nil +} diff --git a/vendor/github.com/hashicorp/terraform-provider-opc/opc/resource_image_list.go b/vendor/github.com/hashicorp/terraform-provider-opc/opc/resource_image_list.go new file mode 100644 index 000000000..79038f7bc --- /dev/null +++ b/vendor/github.com/hashicorp/terraform-provider-opc/opc/resource_image_list.go @@ -0,0 +1,107 @@ +package opc + +import ( + "github.com/hashicorp/go-oracle-terraform/compute" + "github.com/hashicorp/terraform/helper/schema" +) + +func resourceOPCImageList() *schema.Resource { + return &schema.Resource{ + Create: resourceOPCImageListCreate, + Read: resourceOPCImageListRead, + Update: resourceOPCImageListUpdate, + Delete: resourceOPCImageListDelete, + Importer: &schema.ResourceImporter{ + State: schema.ImportStatePassthrough, + }, + + Schema: map[string]*schema.Schema{ + "name": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + "description": { + Type: schema.TypeString, + Required: true, + }, + "default": { + Type: schema.TypeInt, + Optional: true, + Default: 1, + }, + }, + } +} + +func resourceOPCImageListCreate(d *schema.ResourceData, meta interface{}) error { + client := meta.(*compute.Client).ImageList() + + name := d.Get("name").(string) + + createInput := &compute.CreateImageListInput{ + Name: name, + Description: d.Get("description").(string), + Default: d.Get("default").(int), + } + + createResult, err := client.CreateImageList(createInput) + if err != nil { + return err + } + + d.SetId(createResult.Name) + + return resourceOPCImageListRead(d, meta) +} + +func resourceOPCImageListUpdate(d *schema.ResourceData, meta interface{}) error { + client := meta.(*compute.Client).ImageList() + + name := d.Id() + + updateInput := &compute.UpdateImageListInput{ + Name: name, + Description: d.Get("description").(string), + Default: d.Get("default").(int), + } + + _, err := client.UpdateImageList(updateInput) + if err != nil { + return err + } + + return resourceOPCImageListRead(d, meta) +} + +func resourceOPCImageListRead(d *schema.ResourceData, meta interface{}) error { + client := meta.(*compute.Client).ImageList() + + getInput := &compute.GetImageListInput{ + Name: d.Id(), + } + getResult, err := client.GetImageList(getInput) + if err != nil { + return err + } + + d.Set("name", getResult.Name) + d.Set("description", getResult.Description) + d.Set("default", getResult.Default) + + return nil +} + +func resourceOPCImageListDelete(d *schema.ResourceData, meta interface{}) error { + client := meta.(*compute.Client).ImageList() + + deleteInput := &compute.DeleteImageListInput{ + Name: d.Id(), + } + err := client.DeleteImageList(deleteInput) + if err != nil { + return err + } + + return nil +} diff --git a/vendor/github.com/hashicorp/terraform-provider-opc/opc/resource_image_list_entry.go b/vendor/github.com/hashicorp/terraform-provider-opc/opc/resource_image_list_entry.go new file mode 100644 index 000000000..8262657b5 --- /dev/null +++ b/vendor/github.com/hashicorp/terraform-provider-opc/opc/resource_image_list_entry.go @@ -0,0 +1,160 @@ +package opc + +import ( + "fmt" + "strconv" + "strings" + + "github.com/hashicorp/go-oracle-terraform/compute" + "github.com/hashicorp/terraform/helper/schema" + "github.com/hashicorp/terraform/helper/structure" + "github.com/hashicorp/terraform/helper/validation" +) + +func resourceOPCImageListEntry() *schema.Resource { + return &schema.Resource{ + Create: resourceOPCImageListEntryCreate, + Read: resourceOPCImageListEntryRead, + Delete: resourceOPCImageListEntryDelete, + Importer: &schema.ResourceImporter{ + State: schema.ImportStatePassthrough, + }, + + Schema: map[string]*schema.Schema{ + "name": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + "machine_images": { + Type: schema.TypeList, + Required: true, + ForceNew: true, + Elem: &schema.Schema{Type: schema.TypeString}, + }, + "version": { + Type: schema.TypeInt, + ForceNew: true, + Required: true, + }, + "attributes": { + Type: schema.TypeString, + ForceNew: true, + Optional: true, + ValidateFunc: validation.ValidateJsonString, + DiffSuppressFunc: structure.SuppressJsonDiff, + }, + "uri": { + Type: schema.TypeString, + Computed: true, + }, + }, + } +} + +func resourceOPCImageListEntryCreate(d *schema.ResourceData, meta interface{}) error { + client := meta.(*compute.Client).ImageListEntries() + + name := d.Get("name").(string) + machineImages := expandOPCImageListEntryMachineImages(d) + version := d.Get("version").(int) + + createInput := &compute.CreateImageListEntryInput{ + Name: name, + MachineImages: machineImages, + Version: version, + } + + if v, ok := d.GetOk("attributes"); ok { + attributesString := v.(string) + attributes, err := structure.ExpandJsonFromString(attributesString) + if err != nil { + return err + } + + createInput.Attributes = attributes + } + + _, err := client.CreateImageListEntry(createInput) + if err != nil { + return err + } + + id := generateOPCImageListEntryID(name, version) + d.SetId(id) + return resourceOPCImageListEntryRead(d, meta) +} + +func resourceOPCImageListEntryRead(d *schema.ResourceData, meta interface{}) error { + client := meta.(*compute.Client).ImageListEntries() + + name, version, err := parseOPCImageListEntryID(d.Id()) + if err != nil { + return err + } + + getInput := compute.GetImageListEntryInput{ + Name: *name, + Version: *version, + } + getResult, err := client.GetImageListEntry(&getInput) + if err != nil { + return err + } + + attrs, err := structure.FlattenJsonToString(getResult.Attributes) + if err != nil { + return err + } + + d.Set("name", name) + d.Set("machine_images", getResult.MachineImages) + d.Set("version", getResult.Version) + d.Set("attributes", attrs) + d.Set("uri", getResult.Uri) + + return nil +} + +func resourceOPCImageListEntryDelete(d *schema.ResourceData, meta interface{}) error { + client := meta.(*compute.Client).ImageListEntries() + + name, version, err := parseOPCImageListEntryID(d.Id()) + if err != nil { + return err + } + + deleteInput := &compute.DeleteImageListEntryInput{ + Name: *name, + Version: *version, + } + err = client.DeleteImageListEntry(deleteInput) + if err != nil { + return err + } + + return nil +} + +func parseOPCImageListEntryID(id string) (*string, *int, error) { + s := strings.Split(id, "|") + name, versionString := s[0], s[1] + version, err := strconv.Atoi(versionString) + if err != nil { + return nil, nil, err + } + + return &name, &version, nil +} + +func expandOPCImageListEntryMachineImages(d *schema.ResourceData) []string { + machineImages := []string{} + for _, i := range d.Get("machine_images").([]interface{}) { + machineImages = append(machineImages, i.(string)) + } + return machineImages +} + +func generateOPCImageListEntryID(name string, version int) string { + return fmt.Sprintf("%s|%d", name, version) +} diff --git a/vendor/github.com/hashicorp/terraform-provider-opc/opc/resource_instance.go b/vendor/github.com/hashicorp/terraform-provider-opc/opc/resource_instance.go new file mode 100644 index 000000000..7e413b13f --- /dev/null +++ b/vendor/github.com/hashicorp/terraform-provider-opc/opc/resource_instance.go @@ -0,0 +1,898 @@ +package opc + +import ( + "bytes" + "encoding/json" + "fmt" + "log" + "strconv" + "strings" + + "github.com/hashicorp/go-oracle-terraform/compute" + "github.com/hashicorp/terraform/helper/hashcode" + "github.com/hashicorp/terraform/helper/schema" + "github.com/hashicorp/terraform/helper/validation" +) + +func resourceInstance() *schema.Resource { + return &schema.Resource{ + Create: resourceInstanceCreate, + Read: resourceInstanceRead, + Delete: resourceInstanceDelete, + Importer: &schema.ResourceImporter{ + State: func(d *schema.ResourceData, meta interface{}) ([]*schema.ResourceData, error) { + combined := strings.Split(d.Id(), "/") + if len(combined) != 2 { + return nil, fmt.Errorf("Invalid ID specified. Must be in the form of instance_name/instance_id. Got: %s", d.Id()) + } + d.Set("name", combined[0]) + d.SetId(combined[1]) + return []*schema.ResourceData{d}, nil + }, + }, + + Schema: map[string]*schema.Schema{ + ///////////////////////// + // Required Attributes // + ///////////////////////// + "name": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + + "shape": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + + ///////////////////////// + // Optional Attributes // + ///////////////////////// + "instance_attributes": { + Type: schema.TypeString, + Optional: true, + ForceNew: true, + ValidateFunc: validation.ValidateJsonString, + }, + + "boot_order": { + Type: schema.TypeList, + Optional: true, + ForceNew: true, + Elem: &schema.Schema{Type: schema.TypeInt}, + }, + + "hostname": { + Type: schema.TypeString, + Optional: true, + Computed: true, + ForceNew: true, + }, + + "image_list": { + Type: schema.TypeString, + Optional: true, + ForceNew: true, + }, + + "label": { + Type: schema.TypeString, + Optional: true, + Computed: true, + ForceNew: true, + }, + + "networking_info": { + Type: schema.TypeSet, + Optional: true, + Computed: true, + ForceNew: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "dns": { + // Required for Shared Network Interface, will default if unspecified, however + // Optional for IP Network Interface + Type: schema.TypeList, + Optional: true, + Computed: true, + ForceNew: true, + Elem: &schema.Schema{Type: schema.TypeString}, + }, + + "index": { + Type: schema.TypeInt, + ForceNew: true, + Required: true, + }, + + "ip_address": { + // Optional, IP Network only + Type: schema.TypeString, + ForceNew: true, + Optional: true, + }, + + "ip_network": { + // Required for an IP Network Interface + Type: schema.TypeString, + ForceNew: true, + Optional: true, + }, + + "mac_address": { + // Optional, IP Network Only + Type: schema.TypeString, + ForceNew: true, + Computed: true, + Optional: true, + }, + + "name_servers": { + // Optional, IP Network + Shared Network + Type: schema.TypeList, + Optional: true, + ForceNew: true, + Elem: &schema.Schema{Type: schema.TypeString}, + }, + + "nat": { + // Optional for IP Network + // Required for Shared Network + Type: schema.TypeList, + Optional: true, + ForceNew: true, + Elem: &schema.Schema{Type: schema.TypeString}, + }, + + "search_domains": { + // Optional, IP Network + Shared Network + Type: schema.TypeList, + Optional: true, + ForceNew: true, + Elem: &schema.Schema{Type: schema.TypeString}, + }, + + "sec_lists": { + // Required, Shared Network only. Will default if unspecified however + Type: schema.TypeList, + Optional: true, + Computed: true, + ForceNew: true, + Elem: &schema.Schema{Type: schema.TypeString}, + }, + + "shared_network": { + Type: schema.TypeBool, + Optional: true, + ForceNew: true, + Default: false, + }, + + "vnic": { + // Optional, IP Network only. + Type: schema.TypeString, + ForceNew: true, + Optional: true, + }, + + "vnic_sets": { + // Optional, IP Network only. + Type: schema.TypeList, + Optional: true, + ForceNew: true, + Elem: &schema.Schema{Type: schema.TypeString}, + }, + }, + }, + Set: func(v interface{}) int { + var buf bytes.Buffer + m := v.(map[string]interface{}) + buf.WriteString(fmt.Sprintf("%d-", m["index"].(int))) + buf.WriteString(fmt.Sprintf("%s-", m["vnic"].(string))) + buf.WriteString(fmt.Sprintf("%s-", m["nat"])) + return hashcode.String(buf.String()) + }, + }, + + "reverse_dns": { + Type: schema.TypeBool, + Optional: true, + Default: true, + ForceNew: true, + }, + + "ssh_keys": { + Type: schema.TypeList, + Optional: true, + ForceNew: true, + Elem: &schema.Schema{Type: schema.TypeString}, + }, + + "storage": { + Type: schema.TypeSet, + Optional: true, + ForceNew: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "index": { + Type: schema.TypeInt, + Required: true, + ForceNew: true, + ValidateFunc: validation.IntBetween(1, 10), + }, + "volume": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + "name": { + Type: schema.TypeString, + Computed: true, + }, + }, + }, + }, + + "tags": tagsForceNewSchema(), + + ///////////////////////// + // Computed Attributes // + ///////////////////////// + "attributes": { + Type: schema.TypeString, + Computed: true, + }, + + "availability_domain": { + Type: schema.TypeString, + Computed: true, + }, + + "domain": { + Type: schema.TypeString, + Computed: true, + }, + + "entry": { + Type: schema.TypeInt, + Computed: true, + }, + + "fingerprint": { + Type: schema.TypeString, + Computed: true, + }, + + "image_format": { + Type: schema.TypeString, + Computed: true, + }, + + "ip_address": { + Type: schema.TypeString, + Computed: true, + }, + + "placement_requirements": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{Type: schema.TypeString}, + }, + + "platform": { + Type: schema.TypeString, + Computed: true, + }, + + "priority": { + Type: schema.TypeString, + Computed: true, + }, + + "quota_reservation": { + Type: schema.TypeString, + Computed: true, + }, + + "relationships": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{Type: schema.TypeString}, + }, + + "resolvers": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{Type: schema.TypeString}, + }, + + "site": { + Type: schema.TypeString, + Computed: true, + }, + + "start_time": { + Type: schema.TypeString, + Computed: true, + }, + + "state": { + Type: schema.TypeString, + Computed: true, + }, + + "vcable": { + Type: schema.TypeString, + Computed: true, + }, + + "virtio": { + Type: schema.TypeBool, + Computed: true, + }, + + "vnc_address": { + Type: schema.TypeString, + Computed: true, + }, + }, + } +} + +func resourceInstanceCreate(d *schema.ResourceData, meta interface{}) error { + client := meta.(*compute.Client).Instances() + + // Get Required Attributes + input := &compute.CreateInstanceInput{ + Name: d.Get("name").(string), + Shape: d.Get("shape").(string), + } + + // Get optional instance attributes + attributes, attrErr := getInstanceAttributes(d) + if attrErr != nil { + return attrErr + } + + if attributes != nil { + input.Attributes = attributes + } + + if bootOrder := getIntList(d, "boot_order"); len(bootOrder) > 0 { + input.BootOrder = bootOrder + } + + if v, ok := d.GetOk("hostname"); ok { + input.Hostname = v.(string) + } + + if v, ok := d.GetOk("image_list"); ok { + input.ImageList = v.(string) + } + + if v, ok := d.GetOk("label"); ok { + input.Label = v.(string) + } + + interfaces, err := readNetworkInterfacesFromConfig(d) + if err != nil { + return err + } + if interfaces != nil { + input.Networking = interfaces + } + + if v, ok := d.GetOk("reverse_dns"); ok { + input.ReverseDNS = v.(bool) + } + + if sshKeys := getStringList(d, "ssh_keys"); len(sshKeys) > 0 { + input.SSHKeys = sshKeys + } + + storage := getStorageAttachments(d) + if len(storage) > 0 { + input.Storage = storage + } + + if tags := getStringList(d, "tags"); len(tags) > 0 { + input.Tags = tags + } + + result, err := client.CreateInstance(input) + if err != nil { + return fmt.Errorf("Error creating instance %s: %s", input.Name, err) + } + + log.Printf("[DEBUG] Created instance %s: %#v", input.Name, result.ID) + + d.SetId(result.ID) + + return resourceInstanceRead(d, meta) +} + +func resourceInstanceRead(d *schema.ResourceData, meta interface{}) error { + client := meta.(*compute.Client).Instances() + + name := d.Get("name").(string) + + input := &compute.GetInstanceInput{ + ID: d.Id(), + Name: name, + } + + log.Printf("[DEBUG] Reading state of instance %s", name) + result, err := client.GetInstance(input) + if err != nil { + // Instance doesn't exist + if compute.WasNotFoundError(err) { + log.Printf("[DEBUG] Instance %s not found", name) + d.SetId("") + return nil + } + return fmt.Errorf("Error reading instance %s: %s", name, err) + } + + log.Printf("[DEBUG] Instance '%s' found", name) + + // Update attributes + return updateInstanceAttributes(d, result) +} + +func updateInstanceAttributes(d *schema.ResourceData, instance *compute.InstanceInfo) error { + d.Set("name", instance.Name) + d.Set("shape", instance.Shape) + + if err := setInstanceAttributes(d, instance.Attributes); err != nil { + return err + } + + if attrs, ok := d.GetOk("instance_attributes"); ok && attrs != nil { + d.Set("instance_attributes", attrs.(string)) + } + + if err := setIntList(d, "boot_order", instance.BootOrder); err != nil { + return err + } + d.Set("hostname", instance.Hostname) + d.Set("image_list", instance.ImageList) + d.Set("label", instance.Label) + + if err := readNetworkInterfaces(d, instance.Networking); err != nil { + return err + } + + d.Set("reverse_dns", instance.ReverseDNS) + if err := setStringList(d, "ssh_keys", instance.SSHKeys); err != nil { + return err + } + + if err := readStorageAttachments(d, instance.Storage); err != nil { + return err + } + + if err := setStringList(d, "tags", instance.Tags); err != nil { + return err + } + d.Set("availability_domain", instance.AvailabilityDomain) + d.Set("domain", instance.Domain) + d.Set("entry", instance.Entry) + d.Set("fingerprint", instance.Fingerprint) + d.Set("image_format", instance.ImageFormat) + d.Set("ip_address", instance.IPAddress) + + if err := setStringList(d, "placement_requirements", instance.PlacementRequirements); err != nil { + return err + } + + d.Set("platform", instance.Platform) + d.Set("priority", instance.Priority) + d.Set("quota_reservation", instance.QuotaReservation) + + if err := setStringList(d, "relationships", instance.Relationships); err != nil { + return err + } + + if err := setStringList(d, "resolvers", instance.Resolvers); err != nil { + return err + } + + d.Set("site", instance.Site) + d.Set("start_time", instance.StartTime) + d.Set("state", instance.State) + + if err := setStringList(d, "tags", instance.Tags); err != nil { + return err + } + + d.Set("vcable", instance.VCableID) + d.Set("virtio", instance.Virtio) + d.Set("vnc_address", instance.VNC) + + return nil +} + +func resourceInstanceDelete(d *schema.ResourceData, meta interface{}) error { + client := meta.(*compute.Client).Instances() + + name := d.Get("name").(string) + + input := &compute.DeleteInstanceInput{ + ID: d.Id(), + Name: name, + } + log.Printf("[DEBUG] Deleting instance %s", name) + + if err := client.DeleteInstance(input); err != nil { + return fmt.Errorf("Error deleting instance %s: %s", name, err) + } + + return nil +} + +func getStorageAttachments(d *schema.ResourceData) []compute.StorageAttachmentInput { + storageAttachments := []compute.StorageAttachmentInput{} + storage := d.Get("storage").(*schema.Set) + for _, i := range storage.List() { + attrs := i.(map[string]interface{}) + storageAttachments = append(storageAttachments, compute.StorageAttachmentInput{ + Index: attrs["index"].(int), + Volume: attrs["volume"].(string), + }) + } + return storageAttachments +} + +// Parses instance_attributes from a string to a map[string]interface and returns any errors. +func getInstanceAttributes(d *schema.ResourceData) (map[string]interface{}, error) { + var attrs map[string]interface{} + + // Empty instance attributes + attributes, ok := d.GetOk("instance_attributes") + if !ok { + return attrs, nil + } + + if err := json.Unmarshal([]byte(attributes.(string)), &attrs); err != nil { + return attrs, fmt.Errorf("Cannot parse attributes as json: %s", err) + } + + return attrs, nil +} + +// Reads attributes from the returned instance object, and sets the computed attributes string +// as JSON +func setInstanceAttributes(d *schema.ResourceData, attributes map[string]interface{}) error { + // Shouldn't ever get nil attributes on an instance, but protect against the case either way + if attributes == nil { + return nil + } + + b, err := json.Marshal(attributes) + if err != nil { + return fmt.Errorf("Error marshalling returned attributes: %s", err) + } + return d.Set("attributes", string(b)) +} + +// Populates and validates shared network and ip network interfaces to return the of map +// objects needed to create/update an instance's networking_info +func readNetworkInterfacesFromConfig(d *schema.ResourceData) (map[string]compute.NetworkingInfo, error) { + interfaces := make(map[string]compute.NetworkingInfo) + + if v, ok := d.GetOk("networking_info"); ok { + vL := v.(*schema.Set).List() + for _, v := range vL { + ni := v.(map[string]interface{}) + index, ok := ni["index"].(int) + if !ok { + return nil, fmt.Errorf("Index not specified for network interface: %v", ni) + } + + deviceIndex := fmt.Sprintf("eth%d", index) + + // Verify that the network interface doesn't already exist + if _, ok := interfaces[deviceIndex]; ok { + return nil, fmt.Errorf("Duplicate Network interface at eth%d already specified", index) + } + + // Determine if we're creating a shared network interface or an IP Network interface + info := compute.NetworkingInfo{} + var err error + if ni["shared_network"].(bool) { + // Populate shared network parameters + info, err = readSharedNetworkFromConfig(ni) + // Set 'model' since we're configuring a shared network interface + info.Model = compute.NICDefaultModel + } else { + // Populate IP Network Parameters + info, err = readIPNetworkFromConfig(ni) + } + if err != nil { + return nil, err + } + // And you may find yourself in a beautiful house, with a beautiful wife + // And you may ask yourself, well, how did I get here? + interfaces[deviceIndex] = info + } + } + + return interfaces, nil +} + +// Reads a networking_info config block as a shared network interface +func readSharedNetworkFromConfig(ni map[string]interface{}) (compute.NetworkingInfo, error) { + info := compute.NetworkingInfo{} + // Validate the shared network + if err := validateSharedNetwork(ni); err != nil { + return info, err + } + // Populate shared network fields; checking type casting + dns := []string{} + if v, ok := ni["dns"]; ok && v != nil { + for _, d := range v.([]interface{}) { + dns = append(dns, d.(string)) + } + if len(dns) > 0 { + info.DNS = dns + } + } + + if v, ok := ni["model"].(string); ok && v != "" { + info.Model = compute.NICModel(v) + } + + nats := []string{} + if v, ok := ni["nat"]; ok && v != nil { + for _, nat := range v.([]interface{}) { + nats = append(nats, nat.(string)) + } + if len(nats) > 0 { + info.Nat = nats + } + } + + slists := []string{} + if v, ok := ni["sec_lists"]; ok && v != nil { + for _, slist := range v.([]interface{}) { + slists = append(slists, slist.(string)) + } + if len(slists) > 0 { + info.SecLists = slists + } + } + + nservers := []string{} + if v, ok := ni["name_servers"]; ok && v != nil { + for _, nserver := range v.([]interface{}) { + nservers = append(nservers, nserver.(string)) + } + if len(nservers) > 0 { + info.NameServers = nservers + } + } + + sdomains := []string{} + if v, ok := ni["search_domains"]; ok && v != nil { + for _, sdomain := range v.([]interface{}) { + sdomains = append(sdomains, sdomain.(string)) + } + if len(sdomains) > 0 { + info.SearchDomains = sdomains + } + } + + return info, nil +} + +// Unfortunately this cannot take place during plan-phase, because we currently cannot have a validation +// function based off of multiple fields in the supplied schema. +func validateSharedNetwork(ni map[string]interface{}) error { + // A Shared Networking Interface MUST have the following attributes set: + // - "nat" + // The following attributes _cannot_ be set for a shared network: + // - "ip_address" + // - "ip_network" + // - "mac_address" + // - "vnic" + // - "vnic_sets" + + if _, ok := ni["nat"]; !ok { + return fmt.Errorf("'nat' field needs to be set for a Shared Networking Interface") + } + + // Strings only + nilAttrs := []string{ + "ip_address", + "ip_network", + "mac_address", + "vnic", + } + + for _, v := range nilAttrs { + if d, ok := ni[v]; ok && d.(string) != "" { + return fmt.Errorf("%q field cannot be set in a Shared Networking Interface", v) + } + } + if _, ok := ni["vnic_sets"].([]string); ok { + return fmt.Errorf("%q field cannot be set in a Shared Networking Interface", "vnic_sets") + } + + return nil +} + +// Populates fields for an IP Network +func readIPNetworkFromConfig(ni map[string]interface{}) (compute.NetworkingInfo, error) { + info := compute.NetworkingInfo{} + // Validate the IP Network + if err := validateIPNetwork(ni); err != nil { + return info, err + } + // Populate fields + if v, ok := ni["ip_network"].(string); ok && v != "" { + info.IPNetwork = v + } + + dns := []string{} + if v, ok := ni["dns"]; ok && v != nil { + for _, d := range v.([]interface{}) { + dns = append(dns, d.(string)) + } + if len(dns) > 0 { + info.DNS = dns + } + } + + if v, ok := ni["ip_address"].(string); ok && v != "" { + info.IPAddress = v + } + + if v, ok := ni["mac_address"].(string); ok && v != "" { + info.MACAddress = v + } + + nservers := []string{} + if v, ok := ni["name_servers"]; ok && v != nil { + for _, nserver := range v.([]interface{}) { + nservers = append(nservers, nserver.(string)) + } + if len(nservers) > 0 { + info.NameServers = nservers + } + } + + nats := []string{} + if v, ok := ni["nat"]; ok && v != nil { + for _, nat := range v.([]interface{}) { + nats = append(nats, nat.(string)) + } + if len(nats) > 0 { + info.Nat = nats + } + } + + sdomains := []string{} + if v, ok := ni["search_domains"]; ok && v != nil { + for _, sdomain := range v.([]interface{}) { + sdomains = append(sdomains, sdomain.(string)) + } + if len(sdomains) > 0 { + info.SearchDomains = sdomains + } + } + + if v, ok := ni["vnic"].(string); ok && v != "" { + info.Vnic = v + } + + vnicSets := []string{} + if v, ok := ni["vnic_sets"]; ok && v != nil { + for _, vnic := range v.([]interface{}) { + vnicSets = append(vnicSets, vnic.(string)) + } + if len(vnicSets) > 0 { + info.VnicSets = vnicSets + } + } + + return info, nil +} + +// Validates an IP Network config block +func validateIPNetwork(ni map[string]interface{}) error { + // An IP Networking Interface MUST have the following attributes set: + // - "ip_network" + + // Required to be set + if d, ok := ni["ip_network"]; !ok || d.(string) == "" { + return fmt.Errorf("'ip_network' field is required for an IP Network interface") + } + + return nil +} + +// Reads network interfaces from the config +func readNetworkInterfaces(d *schema.ResourceData, ifaces map[string]compute.NetworkingInfo) error { + result := make([]map[string]interface{}, 0) + + // Nil check for import case + if ifaces == nil { + return d.Set("networking_info", result) + } + + for index, iface := range ifaces { + res := make(map[string]interface{}) + // The index returned from the SDK holds the full device_index from the instance. + // For users convenience, we simply allow them to specify the integer equivalent of the device_index + // so a user could implement several network interfaces via `count`. + // Convert the full device_index `ethN` to `N` as an integer. + index := strings.TrimPrefix(index, "eth") + indexInt, err := strconv.Atoi(index) + if err != nil { + return err + } + res["index"] = indexInt + + // Set the proper attributes for this specific network interface + if iface.DNS != nil { + res["dns"] = iface.DNS + } + if iface.IPAddress != "" { + res["ip_address"] = iface.IPAddress + } + if iface.IPNetwork != "" { + res["ip_network"] = iface.IPNetwork + } + if iface.MACAddress != "" { + res["mac_address"] = iface.MACAddress + } + if iface.Model != "" { + // Model can only be set on Shared networks + res["shared_network"] = true + } + if iface.NameServers != nil { + res["name_servers"] = iface.NameServers + } + if iface.Nat != nil { + res["nat"] = iface.Nat + } + if iface.SearchDomains != nil { + res["search_domains"] = iface.SearchDomains + } + if iface.SecLists != nil { + res["sec_lists"] = iface.SecLists + } + if iface.Vnic != "" { + res["vnic"] = iface.Vnic + // VNIC can only be set on an IP Network + res["shared_network"] = false + } + if iface.VnicSets != nil { + res["vnic_sets"] = iface.VnicSets + } + + result = append(result, res) + } + + return d.Set("networking_info", result) +} + +// Flattens the returned slice of storage attachments to a map +func readStorageAttachments(d *schema.ResourceData, attachments []compute.StorageAttachment) error { + result := make([]map[string]interface{}, 0) + + if attachments == nil || len(attachments) == 0 { + return d.Set("storage", nil) + } + + for _, attachment := range attachments { + res := make(map[string]interface{}) + res["index"] = attachment.Index + res["volume"] = attachment.StorageVolumeName + res["name"] = attachment.Name + result = append(result, res) + } + return d.Set("storage", result) +} diff --git a/vendor/github.com/hashicorp/terraform-provider-opc/opc/resource_ip_address_association.go b/vendor/github.com/hashicorp/terraform-provider-opc/opc/resource_ip_address_association.go new file mode 100644 index 000000000..59fcde858 --- /dev/null +++ b/vendor/github.com/hashicorp/terraform-provider-opc/opc/resource_ip_address_association.go @@ -0,0 +1,156 @@ +package opc + +import ( + "fmt" + + "github.com/hashicorp/go-oracle-terraform/compute" + "github.com/hashicorp/terraform/helper/schema" +) + +func resourceOPCIPAddressAssociation() *schema.Resource { + return &schema.Resource{ + Create: resourceOPCIPAddressAssociationCreate, + Read: resourceOPCIPAddressAssociationRead, + Update: resourceOPCIPAddressAssociationUpdate, + Delete: resourceOPCIPAddressAssociationDelete, + Importer: &schema.ResourceImporter{ + State: schema.ImportStatePassthrough, + }, + + Schema: map[string]*schema.Schema{ + "name": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + "ip_address_reservation": { + Type: schema.TypeString, + Optional: true, + }, + "vnic": { + Type: schema.TypeString, + Optional: true, + }, + "description": { + Type: schema.TypeString, + Optional: true, + }, + "tags": tagsOptionalSchema(), + "uri": { + Type: schema.TypeString, + Computed: true, + }, + }, + } +} + +func resourceOPCIPAddressAssociationCreate(d *schema.ResourceData, meta interface{}) error { + client := meta.(*compute.Client).IPAddressAssociations() + + input := compute.CreateIPAddressAssociationInput{ + Name: d.Get("name").(string), + } + + if ipAddressReservation, ok := d.GetOk("ip_address_reservation"); ok { + input.IPAddressReservation = ipAddressReservation.(string) + } + + if vnic, ok := d.GetOk("vnic"); ok { + input.Vnic = vnic.(string) + } + + tags := getStringList(d, "tags") + if len(tags) != 0 { + input.Tags = tags + } + + if description, ok := d.GetOk("description"); ok { + input.Description = description.(string) + } + + info, err := client.CreateIPAddressAssociation(&input) + if err != nil { + return fmt.Errorf("Error creating IP Address Association: %s", err) + } + + d.SetId(info.Name) + return resourceOPCIPAddressAssociationRead(d, meta) +} + +func resourceOPCIPAddressAssociationRead(d *schema.ResourceData, meta interface{}) error { + client := meta.(*compute.Client).IPAddressAssociations() + name := d.Id() + + getInput := compute.GetIPAddressAssociationInput{ + Name: name, + } + result, err := client.GetIPAddressAssociation(&getInput) + if err != nil { + // IP Address Association does not exist + if compute.WasNotFoundError(err) { + d.SetId("") + return nil + } + return fmt.Errorf("Error reading IP Address Association %s: %s", name, err) + } + if result == nil { + d.SetId("") + return fmt.Errorf("Error reading IP Address Association %s: %s", name, err) + } + + d.Set("name", result.Name) + d.Set("ip_address_reservation", result.IPAddressReservation) + d.Set("vnic", result.Vnic) + d.Set("description", result.Description) + d.Set("uri", result.Uri) + if err := setStringList(d, "tags", result.Tags); err != nil { + return err + } + return nil +} + +func resourceOPCIPAddressAssociationUpdate(d *schema.ResourceData, meta interface{}) error { + client := meta.(*compute.Client).IPAddressAssociations() + + input := compute.UpdateIPAddressAssociationInput{ + Name: d.Get("name").(string), + } + + if ipAddressReservation, ok := d.GetOk("ip_address_reservation"); ok { + input.IPAddressReservation = ipAddressReservation.(string) + } + + if vnic, ok := d.GetOk("vnic"); ok { + input.Vnic = vnic.(string) + } + + tags := getStringList(d, "tags") + if len(tags) != 0 { + input.Tags = tags + } + + if description, ok := d.GetOk("description"); ok { + input.Description = description.(string) + } + + info, err := client.UpdateIPAddressAssociation(&input) + if err != nil { + return fmt.Errorf("Error updating IP Address Association: %s", err) + } + + d.SetId(info.Name) + return resourceOPCIPAddressAssociationRead(d, meta) +} + +func resourceOPCIPAddressAssociationDelete(d *schema.ResourceData, meta interface{}) error { + client := meta.(*compute.Client).IPAddressAssociations() + name := d.Id() + + input := compute.DeleteIPAddressAssociationInput{ + Name: name, + } + if err := client.DeleteIPAddressAssociation(&input); err != nil { + return fmt.Errorf("Error deleting IP Address Association: %s", err) + } + return nil +} diff --git a/vendor/github.com/hashicorp/terraform-provider-opc/opc/resource_ip_address_prefix_set.go b/vendor/github.com/hashicorp/terraform-provider-opc/opc/resource_ip_address_prefix_set.go new file mode 100644 index 000000000..ab40be7a7 --- /dev/null +++ b/vendor/github.com/hashicorp/terraform-provider-opc/opc/resource_ip_address_prefix_set.go @@ -0,0 +1,147 @@ +package opc + +import ( + "fmt" + + "github.com/hashicorp/go-oracle-terraform/compute" + "github.com/hashicorp/terraform/helper/schema" +) + +func resourceOPCIPAddressPrefixSet() *schema.Resource { + return &schema.Resource{ + Create: resourceOPCIPAddressPrefixSetCreate, + Read: resourceOPCIPAddressPrefixSetRead, + Update: resourceOPCIPAddressPrefixSetUpdate, + Delete: resourceOPCIPAddressPrefixSetDelete, + Importer: &schema.ResourceImporter{ + State: schema.ImportStatePassthrough, + }, + + Schema: map[string]*schema.Schema{ + "name": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + "prefixes": { + Type: schema.TypeList, + Optional: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + ValidateFunc: validateIPPrefixCIDR, + }, + }, + "description": { + Type: schema.TypeString, + Optional: true, + ForceNew: true, + }, + "tags": tagsOptionalSchema(), + "uri": { + Type: schema.TypeString, + Computed: true, + }, + }, + } +} + +func resourceOPCIPAddressPrefixSetCreate(d *schema.ResourceData, meta interface{}) error { + client := meta.(*compute.Client).IPAddressPrefixSets() + + input := compute.CreateIPAddressPrefixSetInput{ + Name: d.Get("name").(string), + } + + prefixes := getStringList(d, "prefixes") + if len(prefixes) != 0 { + input.IPAddressPrefixes = prefixes + } + + tags := getStringList(d, "tags") + if len(tags) != 0 { + input.Tags = tags + } + + if description, ok := d.GetOk("description"); ok { + input.Description = description.(string) + } + + info, err := client.CreateIPAddressPrefixSet(&input) + if err != nil { + return fmt.Errorf("Error creating IP Address Prefix Set: %s", err) + } + + d.SetId(info.Name) + return resourceOPCIPAddressPrefixSetRead(d, meta) +} + +func resourceOPCIPAddressPrefixSetRead(d *schema.ResourceData, meta interface{}) error { + client := meta.(*compute.Client).IPAddressPrefixSets() + + getInput := compute.GetIPAddressPrefixSetInput{ + Name: d.Id(), + } + result, err := client.GetIPAddressPrefixSet(&getInput) + if err != nil { + // IP Address Prefix Set does not exist + if compute.WasNotFoundError(err) { + d.SetId("") + return nil + } + return fmt.Errorf("Error reading IP Address Prefix Set %s: %s", d.Id(), err) + } + + d.Set("name", result.Name) + d.Set("description", result.Description) + d.Set("uri", result.Uri) + if err := setStringList(d, "prefixes", result.IPAddressPrefixes); err != nil { + return err + } + if err := setStringList(d, "tags", result.Tags); err != nil { + return err + } + return nil +} + +func resourceOPCIPAddressPrefixSetUpdate(d *schema.ResourceData, meta interface{}) error { + client := meta.(*compute.Client).IPAddressPrefixSets() + + input := compute.UpdateIPAddressPrefixSetInput{ + Name: d.Get("name").(string), + } + + prefixes := getStringList(d, "prefixes") + if len(prefixes) != 0 { + input.IPAddressPrefixes = prefixes + } + + tags := getStringList(d, "tags") + if len(tags) != 0 { + input.Tags = tags + } + + if description, ok := d.GetOk("description"); ok { + input.Description = description.(string) + } + + info, err := client.UpdateIPAddressPrefixSet(&input) + if err != nil { + return fmt.Errorf("Error updating IP Address Prefix Set: %s", err) + } + + d.SetId(info.Name) + return resourceOPCIPAddressPrefixSetRead(d, meta) +} + +func resourceOPCIPAddressPrefixSetDelete(d *schema.ResourceData, meta interface{}) error { + client := meta.(*compute.Client).IPAddressPrefixSets() + name := d.Id() + + input := compute.DeleteIPAddressPrefixSetInput{ + Name: name, + } + if err := client.DeleteIPAddressPrefixSet(&input); err != nil { + return fmt.Errorf("Error deleting IP Address Prefix Set: %s", err) + } + return nil +} diff --git a/vendor/github.com/hashicorp/terraform-provider-opc/opc/resource_ip_address_reservation.go b/vendor/github.com/hashicorp/terraform-provider-opc/opc/resource_ip_address_reservation.go new file mode 100644 index 000000000..0e47ff906 --- /dev/null +++ b/vendor/github.com/hashicorp/terraform-provider-opc/opc/resource_ip_address_reservation.go @@ -0,0 +1,137 @@ +package opc + +import ( + "fmt" + + "github.com/hashicorp/go-oracle-terraform/compute" + "github.com/hashicorp/terraform/helper/schema" + "github.com/hashicorp/terraform/helper/validation" +) + +func resourceOPCIPAddressReservation() *schema.Resource { + return &schema.Resource{ + Create: resourceOPCIPAddressReservationCreate, + Read: resourceOPCIPAddressReservationRead, + Update: resourceOPCIPAddressReservationUpdate, + Delete: resourceOPCIPAddressReservationDelete, + Importer: &schema.ResourceImporter{ + State: schema.ImportStatePassthrough, + }, + + Schema: map[string]*schema.Schema{ + "name": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + "ip_address_pool": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + ValidateFunc: validation.StringInSlice([]string{ + string(compute.PublicIPAddressPool), + string(compute.PrivateIPAddressPool), + }, true), + }, + "description": { + Type: schema.TypeString, + Optional: true, + }, + "tags": tagsOptionalSchema(), + "ip_address": { + Type: schema.TypeString, + Computed: true, + }, + "uri": { + Type: schema.TypeString, + Computed: true, + }, + }, + } +} + +func resourceOPCIPAddressReservationCreate(d *schema.ResourceData, meta interface{}) error { + client := meta.(*compute.Client).IPAddressReservations() + + input := compute.CreateIPAddressReservationInput{ + Name: d.Get("name").(string), + IPAddressPool: d.Get("ip_address_pool").(string), + } + tags := getStringList(d, "tags") + if len(tags) != 0 { + input.Tags = tags + } + if description, ok := d.GetOk("description"); ok { + input.Description = description.(string) + } + + info, err := client.CreateIPAddressReservation(&input) + if err != nil { + return fmt.Errorf("Error creating IP Address Reservation: %s", err) + } + d.SetId(info.Name) + return resourceOPCIPAddressReservationRead(d, meta) +} + +func resourceOPCIPAddressReservationRead(d *schema.ResourceData, meta interface{}) error { + client := meta.(*compute.Client).IPAddressReservations() + + getInput := compute.GetIPAddressReservationInput{ + Name: d.Id(), + } + result, err := client.GetIPAddressReservation(&getInput) + if err != nil { + // IP Address Reservation does not exist + if compute.WasNotFoundError(err) { + d.SetId("") + return nil + } + return fmt.Errorf("Error reading ip address reservation %s: %s", d.Id(), err) + } + + d.Set("name", result.Name) + d.Set("description", result.Description) + d.Set("ip_address_pool", result.IPAddressPool) + d.Set("uri", result.Uri) + + if err := setStringList(d, "tags", result.Tags); err != nil { + return err + } + return nil +} + +func resourceOPCIPAddressReservationUpdate(d *schema.ResourceData, meta interface{}) error { + client := meta.(*compute.Client).IPAddressReservations() + + input := compute.UpdateIPAddressReservationInput{ + Name: d.Get("name").(string), + IPAddressPool: d.Get("ip_address_pool").(string), + } + tags := getStringList(d, "tags") + if len(tags) != 0 { + input.Tags = tags + } + if description, ok := d.GetOk("description"); ok { + input.Description = description.(string) + } + + info, err := client.UpdateIPAddressReservation(&input) + if err != nil { + return fmt.Errorf("Error updating IP Address Reservation: %s", err) + } + d.SetId(info.Name) + return resourceOPCIPAddressReservationRead(d, meta) +} + +func resourceOPCIPAddressReservationDelete(d *schema.ResourceData, meta interface{}) error { + client := meta.(*compute.Client).IPAddressReservations() + name := d.Id() + + input := compute.DeleteIPAddressReservationInput{ + Name: name, + } + if err := client.DeleteIPAddressReservation(&input); err != nil { + return fmt.Errorf("Error deleting IP Address Reservation: %+v", err) + } + return nil +} diff --git a/vendor/github.com/hashicorp/terraform-provider-opc/opc/resource_ip_association.go b/vendor/github.com/hashicorp/terraform-provider-opc/opc/resource_ip_association.go new file mode 100644 index 000000000..2e90e99ee --- /dev/null +++ b/vendor/github.com/hashicorp/terraform-provider-opc/opc/resource_ip_association.go @@ -0,0 +1,96 @@ +package opc + +import ( + "fmt" + + "github.com/hashicorp/go-oracle-terraform/compute" + "github.com/hashicorp/terraform/helper/schema" +) + +func resourceOPCIPAssociation() *schema.Resource { + return &schema.Resource{ + Create: resourceOPCIPAssociationCreate, + Read: resourceOPCIPAssociationRead, + Delete: resourceOPCIPAssociationDelete, + Importer: &schema.ResourceImporter{ + State: schema.ImportStatePassthrough, + }, + + Schema: map[string]*schema.Schema{ + "name": { + Type: schema.TypeString, + Optional: true, + Computed: true, + }, + + "vcable": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + + "parent_pool": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + }, + } +} + +func resourceOPCIPAssociationCreate(d *schema.ResourceData, meta interface{}) error { + vCable := d.Get("vcable").(string) + parentPool := d.Get("parent_pool").(string) + + client := meta.(*compute.Client).IPAssociations() + input := compute.CreateIPAssociationInput{ + ParentPool: parentPool, + VCable: vCable, + } + info, err := client.CreateIPAssociation(&input) + if err != nil { + return fmt.Errorf("Error creating ip association between vcable %s and parent pool %s: %s", vCable, parentPool, err) + } + + d.SetId(info.Name) + + return resourceOPCIPAssociationRead(d, meta) +} + +func resourceOPCIPAssociationRead(d *schema.ResourceData, meta interface{}) error { + client := meta.(*compute.Client).IPAssociations() + + name := d.Id() + input := compute.GetIPAssociationInput{ + Name: name, + } + result, err := client.GetIPAssociation(&input) + if err != nil { + // IP Association does not exist + if compute.WasNotFoundError(err) { + d.SetId("") + return nil + } + return fmt.Errorf("Error reading ip association '%s': %s", name, err) + } + + d.Set("name", result.Name) + d.Set("parent_pool", result.ParentPool) + d.Set("vcable", result.VCable) + + return nil +} + +func resourceOPCIPAssociationDelete(d *schema.ResourceData, meta interface{}) error { + client := meta.(*compute.Client).IPAssociations() + + name := d.Id() + input := compute.DeleteIPAssociationInput{ + Name: name, + } + if err := client.DeleteIPAssociation(&input); err != nil { + return fmt.Errorf("Error deleting ip association '%s': %s", name, err) + } + + return nil +} diff --git a/vendor/github.com/hashicorp/terraform-provider-opc/opc/resource_ip_network.go b/vendor/github.com/hashicorp/terraform-provider-opc/opc/resource_ip_network.go new file mode 100644 index 000000000..ddb0e65c3 --- /dev/null +++ b/vendor/github.com/hashicorp/terraform-provider-opc/opc/resource_ip_network.go @@ -0,0 +1,179 @@ +package opc + +import ( + "fmt" + + "github.com/hashicorp/go-oracle-terraform/compute" + "github.com/hashicorp/terraform/helper/schema" +) + +func resourceOPCIPNetwork() *schema.Resource { + return &schema.Resource{ + Create: resourceOPCIPNetworkCreate, + Read: resourceOPCIPNetworkRead, + Update: resourceOPCIPNetworkUpdate, + Delete: resourceOPCIPNetworkDelete, + Importer: &schema.ResourceImporter{ + State: schema.ImportStatePassthrough, + }, + + Schema: map[string]*schema.Schema{ + "name": { + Type: schema.TypeString, + Required: true, + }, + + "ip_address_prefix": { + Type: schema.TypeString, + Required: true, + ValidateFunc: validateIPPrefixCIDR, + }, + + "ip_network_exchange": { + Type: schema.TypeString, + Optional: true, + }, + + "description": { + Type: schema.TypeString, + Optional: true, + }, + + "public_napt_enabled": { + Type: schema.TypeBool, + Optional: true, + Default: false, + }, + + "uri": { + Type: schema.TypeString, + Computed: true, + }, + + "tags": tagsOptionalSchema(), + }, + } +} + +func resourceOPCIPNetworkCreate(d *schema.ResourceData, meta interface{}) error { + client := meta.(*compute.Client).IPNetworks() + + // Get required attributes + name := d.Get("name").(string) + ipPrefix := d.Get("ip_address_prefix").(string) + // public_napt_enabled is not required, but bool type allows it to be unspecified + naptEnabled := d.Get("public_napt_enabled").(bool) + + input := &compute.CreateIPNetworkInput{ + Name: name, + IPAddressPrefix: ipPrefix, + PublicNaptEnabled: naptEnabled, + } + + // Get Optional attributes + if desc, ok := d.GetOk("description"); ok && desc != nil { + input.Description = desc.(string) + } + + if ipEx, ok := d.GetOk("ip_network_exchange"); ok && ipEx != nil { + input.IPNetworkExchange = ipEx.(string) + } + + tags := getStringList(d, "tags") + if len(tags) != 0 { + input.Tags = tags + } + + info, err := client.CreateIPNetwork(input) + if err != nil { + return fmt.Errorf("Error creating IP Network '%s': %v", name, err) + } + + d.SetId(info.Name) + + return resourceOPCIPNetworkRead(d, meta) +} + +func resourceOPCIPNetworkRead(d *schema.ResourceData, meta interface{}) error { + client := meta.(*compute.Client).IPNetworks() + + name := d.Id() + input := &compute.GetIPNetworkInput{ + Name: name, + } + + res, err := client.GetIPNetwork(input) + if err != nil { + if compute.WasNotFoundError(err) { + d.SetId("") + return nil + } + return fmt.Errorf("Error reading IP Network '%s': %v", name, err) + } + + d.Set("name", res.Name) + d.Set("ip_address_prefix", res.IPAddressPrefix) + d.Set("ip_network_exchanged", res.IPNetworkExchange) + d.Set("description", res.Description) + d.Set("public_napt_enabled", res.PublicNaptEnabled) + d.Set("uri", res.Uri) + if err := setStringList(d, "tags", res.Tags); err != nil { + return err + } + return nil +} + +func resourceOPCIPNetworkUpdate(d *schema.ResourceData, meta interface{}) error { + client := meta.(*compute.Client).IPNetworks() + + // Get required attributes + name := d.Get("name").(string) + ipPrefix := d.Get("ip_address_prefix").(string) + // public_napt_enabled is not required, but bool type allows it to be unspecified + naptEnabled := d.Get("public_napt_enabled").(bool) + + input := &compute.UpdateIPNetworkInput{ + Name: name, + IPAddressPrefix: ipPrefix, + PublicNaptEnabled: naptEnabled, + } + + // Get Optional attributes + desc, descOk := d.GetOk("description") + if descOk { + input.Description = desc.(string) + } + + ipEx, ipExOk := d.GetOk("ip_network_exchange") + if ipExOk { + input.IPNetworkExchange = ipEx.(string) + } + + tags := getStringList(d, "tags") + if len(tags) != 0 { + input.Tags = tags + } + + info, err := client.UpdateIPNetwork(input) + if err != nil { + return fmt.Errorf("Error updating IP Network '%s': %v", name, err) + } + + d.SetId(info.Name) + + return resourceOPCIPNetworkRead(d, meta) +} + +func resourceOPCIPNetworkDelete(d *schema.ResourceData, meta interface{}) error { + client := meta.(*compute.Client).IPNetworks() + + name := d.Id() + input := &compute.DeleteIPNetworkInput{ + Name: name, + } + + if err := client.DeleteIPNetwork(input); err != nil { + return fmt.Errorf("Error deleting IP Network '%s': %v", name, err) + } + return nil +} diff --git a/vendor/github.com/hashicorp/terraform-provider-opc/opc/resource_ip_network_exchange.go b/vendor/github.com/hashicorp/terraform-provider-opc/opc/resource_ip_network_exchange.go new file mode 100644 index 000000000..938f12e40 --- /dev/null +++ b/vendor/github.com/hashicorp/terraform-provider-opc/opc/resource_ip_network_exchange.go @@ -0,0 +1,105 @@ +package opc + +import ( + "fmt" + "log" + + "github.com/hashicorp/go-oracle-terraform/compute" + "github.com/hashicorp/terraform/helper/schema" +) + +func resourceOPCIPNetworkExchange() *schema.Resource { + return &schema.Resource{ + Create: resourceOPCIPNetworkExchangeCreate, + Read: resourceOPCIPNetworkExchangeRead, + Delete: resourceOPCIPNetworkExchangeDelete, + Importer: &schema.ResourceImporter{ + State: schema.ImportStatePassthrough, + }, + + Schema: map[string]*schema.Schema{ + "name": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + "description": { + Type: schema.TypeString, + Optional: true, + ForceNew: true, + }, + "tags": tagsForceNewSchema(), + "uri": { + Type: schema.TypeString, + Computed: true, + }, + }, + } +} + +func resourceOPCIPNetworkExchangeCreate(d *schema.ResourceData, meta interface{}) error { + client := meta.(*compute.Client).IPNetworkExchanges() + input := compute.CreateIPNetworkExchangeInput{ + Name: d.Get("name").(string), + } + + log.Printf("[DEBUG] Creating ip network exchange '%s'", input.Name) + tags := getStringList(d, "tags") + if len(tags) != 0 { + input.Tags = tags + } + + if description, ok := d.GetOk("description"); ok { + input.Description = description.(string) + } + + info, err := client.CreateIPNetworkExchange(&input) + if err != nil { + return fmt.Errorf("Error creating IP Network Exchange: %s", err) + } + + d.SetId(info.Name) + return resourceOPCIPNetworkExchangeRead(d, meta) +} + +func resourceOPCIPNetworkExchangeRead(d *schema.ResourceData, meta interface{}) error { + client := meta.(*compute.Client).IPNetworkExchanges() + + log.Printf("[DEBUG] Reading state of IP Network Exchange %s", d.Id()) + getInput := compute.GetIPNetworkExchangeInput{ + Name: d.Id(), + } + result, err := client.GetIPNetworkExchange(&getInput) + if err != nil { + // IP NetworkExchange does not exist + if compute.WasNotFoundError(err) { + d.SetId("") + return nil + } + return fmt.Errorf("Error reading ip network exchange %s: %s", d.Id(), err) + } + + d.Set("name", result.Name) + d.Set("description", result.Description) + d.Set("uri", result.Uri) + + if err := setStringList(d, "tags", result.Tags); err != nil { + return err + } + + return nil +} + +func resourceOPCIPNetworkExchangeDelete(d *schema.ResourceData, meta interface{}) error { + client := meta.(*compute.Client).IPNetworkExchanges() + name := d.Id() + + log.Printf("[DEBUG] Deleting IP Network Exchange '%s'", name) + input := compute.DeleteIPNetworkExchangeInput{ + Name: name, + } + if err := client.DeleteIPNetworkExchange(&input); err != nil { + return fmt.Errorf("Error deleting IP Network Exchange '%s': %+v", name, err) + } + return nil +} diff --git a/vendor/github.com/hashicorp/terraform-provider-opc/opc/resource_ip_reservation.go b/vendor/github.com/hashicorp/terraform-provider-opc/opc/resource_ip_reservation.go new file mode 100644 index 000000000..2a7ea08bd --- /dev/null +++ b/vendor/github.com/hashicorp/terraform-provider-opc/opc/resource_ip_reservation.go @@ -0,0 +1,117 @@ +package opc + +import ( + "fmt" + "log" + + "github.com/hashicorp/go-oracle-terraform/compute" + "github.com/hashicorp/terraform/helper/schema" +) + +func resourceOPCIPReservation() *schema.Resource { + return &schema.Resource{ + Create: resourceOPCIPReservationCreate, + Read: resourceOPCIPReservationRead, + Delete: resourceOPCIPReservationDelete, + Importer: &schema.ResourceImporter{ + State: schema.ImportStatePassthrough, + }, + + Schema: map[string]*schema.Schema{ + "name": { + Type: schema.TypeString, + Optional: true, + Computed: true, + }, + "permanent": { + Type: schema.TypeBool, + Required: true, + ForceNew: true, + }, + "parent_pool": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + "tags": tagsForceNewSchema(), + "ip": { + Type: schema.TypeString, + Computed: true, + }, + }, + } +} + +func resourceOPCIPReservationCreate(d *schema.ResourceData, meta interface{}) error { + log.Printf("[DEBUG] Resource state: %#v", d.State()) + + reservation := compute.CreateIPReservationInput{ + Name: d.Get("name").(string), + ParentPool: compute.IPReservationPool(d.Get("parent_pool").(string)), + Permanent: d.Get("permanent").(bool), + } + + tags := getStringList(d, "tags") + if len(tags) != 0 { + reservation.Tags = tags + } + + log.Printf("[DEBUG] Creating ip reservation from parent_pool %s with tags=%s", + reservation.ParentPool, reservation.Tags) + + client := meta.(*compute.Client).IPReservations() + info, err := client.CreateIPReservation(&reservation) + if err != nil { + return fmt.Errorf("Error creating ip reservation from parent_pool %s with tags=%s: %s", + reservation.ParentPool, reservation.Tags, err) + } + + d.SetId(info.Name) + return resourceOPCIPReservationRead(d, meta) +} + +func resourceOPCIPReservationRead(d *schema.ResourceData, meta interface{}) error { + log.Printf("[DEBUG] Resource state: %#v", d.State()) + client := meta.(*compute.Client).IPReservations() + + log.Printf("[DEBUG] Reading state of ip reservation %s", d.Id()) + getInput := compute.GetIPReservationInput{ + Name: d.Id(), + } + result, err := client.GetIPReservation(&getInput) + if err != nil { + // IP Reservation does not exist + if compute.WasNotFoundError(err) { + d.SetId("") + return nil + } + return fmt.Errorf("Error reading ip reservation %s: %s", d.Id(), err) + } + + log.Printf("[DEBUG] Read state of ip reservation %s: %#v", d.Id(), result) + d.Set("name", result.Name) + d.Set("parent_pool", result.ParentPool) + d.Set("permanent", result.Permanent) + + if err := setStringList(d, "tags", result.Tags); err != nil { + return err + } + + d.Set("ip", result.IP) + return nil +} + +func resourceOPCIPReservationDelete(d *schema.ResourceData, meta interface{}) error { + log.Printf("[DEBUG] Resource state: %#v", d.State()) + client := meta.(*compute.Client).IPReservations() + + log.Printf("[DEBUG] Deleting ip reservation %s", d.Id()) + + input := compute.DeleteIPReservationInput{ + Name: d.Id(), + } + if err := client.DeleteIPReservation(&input); err != nil { + return fmt.Errorf("Error deleting ip reservation %s", d.Id()) + } + return nil +} diff --git a/vendor/github.com/hashicorp/terraform-provider-opc/opc/resource_route.go b/vendor/github.com/hashicorp/terraform-provider-opc/opc/resource_route.go new file mode 100644 index 000000000..b09ccee38 --- /dev/null +++ b/vendor/github.com/hashicorp/terraform-provider-opc/opc/resource_route.go @@ -0,0 +1,176 @@ +package opc + +import ( + "fmt" + + "github.com/hashicorp/go-oracle-terraform/compute" + "github.com/hashicorp/terraform/helper/schema" +) + +func resourceOPCRoute() *schema.Resource { + return &schema.Resource{ + Create: resourceOPCRouteCreate, + Read: resourceOPCRouteRead, + Update: resourceOPCRouteUpdate, + Delete: resourceOPCRouteDelete, + Importer: &schema.ResourceImporter{ + State: schema.ImportStatePassthrough, + }, + + Schema: map[string]*schema.Schema{ + "name": { + Type: schema.TypeString, + Required: true, + }, + + "description": { + Type: schema.TypeString, + Optional: true, + }, + + "admin_distance": { + Type: schema.TypeInt, + Optional: true, + ValidateFunc: validateAdminDistance, + }, + + "ip_address_prefix": { + Type: schema.TypeString, + Required: true, + ValidateFunc: validateIPPrefixCIDR, + }, + + "next_hop_vnic_set": { + Type: schema.TypeString, + Required: true, + }, + + "tags": tagsOptionalSchema(), + }, + } +} + +func resourceOPCRouteCreate(d *schema.ResourceData, meta interface{}) error { + client := meta.(*compute.Client).Routes() + + // Get Required attributes + name := d.Get("name").(string) + ipPrefix := d.Get("ip_address_prefix").(string) + nextHop := d.Get("next_hop_vnic_set").(string) + + // Start populating input struct + input := &compute.CreateRouteInput{ + Name: name, + IPAddressPrefix: ipPrefix, + NextHopVnicSet: nextHop, + } + + // Get Optional Attributes + desc, descOk := d.GetOk("description") + if descOk { + input.Description = desc.(string) + } + + dist, distOk := d.GetOk("admin_distance") + if distOk { + input.AdminDistance = dist.(int) + } + + tags := getStringList(d, "tags") + if len(tags) != 0 { + input.Tags = tags + } + + // Create Route + info, err := client.CreateRoute(input) + if err != nil { + return fmt.Errorf("Error creating route '%s': %v", name, err) + } + + d.SetId(info.Name) + + return resourceOPCRouteRead(d, meta) +} + +func resourceOPCRouteRead(d *schema.ResourceData, meta interface{}) error { + client := meta.(*compute.Client).Routes() + + name := d.Id() + input := &compute.GetRouteInput{ + Name: name, + } + + res, err := client.GetRoute(input) + if err != nil { + if compute.WasNotFoundError(err) { + d.SetId("") + return nil + } + return fmt.Errorf("Error reading route '%s': %v", name, err) + } + + d.Set("name", res.Name) + d.Set("admin_distance", res.AdminDistance) + d.Set("ip_address_prefix", res.IPAddressPrefix) + d.Set("next_hop_vnic_set", res.NextHopVnicSet) + d.Set("description", res.Description) + if err := setStringList(d, "tags", res.Tags); err != nil { + return err + } + return nil +} + +func resourceOPCRouteUpdate(d *schema.ResourceData, meta interface{}) error { + client := meta.(*compute.Client).Routes() + + // Get Required attributes + name := d.Get("name").(string) + ipPrefix := d.Get("ip_address_prefix").(string) + nextHop := d.Get("next_hop_vnic_set").(string) + + // Start populating input struct + input := &compute.UpdateRouteInput{ + Name: name, + IPAddressPrefix: ipPrefix, + NextHopVnicSet: nextHop, + } + + // Get Optional Attributes + desc, descOk := d.GetOk("description") + if descOk { + input.Description = desc.(string) + } + + dist, distOk := d.GetOk("admin_distance") + if distOk { + input.AdminDistance = dist.(int) + } + + tags := getStringList(d, "tags") + if len(tags) != 0 { + input.Tags = tags + } + + // Create Route + info, err := client.UpdateRoute(input) + if err != nil { + return fmt.Errorf("Error creating route '%s': %v", name, err) + } + + d.SetId(info.Name) + + return resourceOPCRouteRead(d, meta) +} + +func resourceOPCRouteDelete(d *schema.ResourceData, meta interface{}) error { + client := meta.(*compute.Client).Routes() + + name := d.Id() + input := &compute.DeleteRouteInput{ + Name: name, + } + if err := client.DeleteRoute(input); err != nil { + return fmt.Errorf("Error deleting route '%s': %v", name, err) + } + return nil +} diff --git a/vendor/github.com/hashicorp/terraform-provider-opc/opc/resource_sec_rule.go b/vendor/github.com/hashicorp/terraform-provider-opc/opc/resource_sec_rule.go new file mode 100644 index 000000000..d3d0f01d9 --- /dev/null +++ b/vendor/github.com/hashicorp/terraform-provider-opc/opc/resource_sec_rule.go @@ -0,0 +1,163 @@ +package opc + +import ( + "fmt" + + "github.com/hashicorp/go-oracle-terraform/compute" + "github.com/hashicorp/terraform/helper/schema" +) + +func resourceOPCSecRule() *schema.Resource { + return &schema.Resource{ + Create: resourceOPCSecRuleCreate, + Read: resourceOPCSecRuleRead, + Update: resourceOPCSecRuleUpdate, + Delete: resourceOPCSecRuleDelete, + Importer: &schema.ResourceImporter{ + State: schema.ImportStatePassthrough, + }, + + Schema: map[string]*schema.Schema{ + "name": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + "description": { + Type: schema.TypeString, + Optional: true, + }, + "source_list": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + "destination_list": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + "application": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + "action": { + Type: schema.TypeString, + Required: true, + }, + "disabled": { + Type: schema.TypeBool, + Optional: true, + Default: false, + }, + }, + } +} + +func resourceOPCSecRuleCreate(d *schema.ResourceData, meta interface{}) error { + client := meta.(*compute.Client).SecRules() + + name := d.Get("name").(string) + sourceList := d.Get("source_list").(string) + destinationList := d.Get("destination_list").(string) + application := d.Get("application").(string) + action := d.Get("action").(string) + disabled := d.Get("disabled").(bool) + + input := compute.CreateSecRuleInput{ + Name: name, + Action: action, + SourceList: sourceList, + DestinationList: destinationList, + Disabled: disabled, + Application: application, + } + desc, descOk := d.GetOk("description") + if descOk { + input.Description = desc.(string) + } + + info, err := client.CreateSecRule(&input) + if err != nil { + return fmt.Errorf("Error creating sec rule %s: %s", name, err) + } + + d.SetId(info.Name) + + return resourceOPCSecRuleRead(d, meta) +} + +func resourceOPCSecRuleRead(d *schema.ResourceData, meta interface{}) error { + client := meta.(*compute.Client).SecRules() + + name := d.Id() + + input := compute.GetSecRuleInput{ + Name: name, + } + result, err := client.GetSecRule(&input) + if err != nil { + // Sec Rule does not exist + if compute.WasNotFoundError(err) { + d.SetId("") + return nil + } + return fmt.Errorf("Error reading sec list %s: %s", name, err) + } + + d.Set("name", result.Name) + d.Set("description", result.Description) + d.Set("source_list", result.SourceList) + d.Set("destination_list", result.DestinationList) + d.Set("application", result.Application) + d.Set("action", result.Action) + d.Set("disabled", result.Disabled) + + return nil +} + +func resourceOPCSecRuleUpdate(d *schema.ResourceData, meta interface{}) error { + client := meta.(*compute.Client).SecRules() + + name := d.Get("name").(string) + sourceList := d.Get("source_list").(string) + destinationList := d.Get("destination_list").(string) + application := d.Get("application").(string) + action := d.Get("action").(string) + disabled := d.Get("disabled").(bool) + + input := compute.UpdateSecRuleInput{ + Action: action, + Application: application, + DestinationList: destinationList, + Disabled: disabled, + Name: name, + SourceList: sourceList, + } + desc, descOk := d.GetOk("description") + if descOk { + input.Description = desc.(string) + } + + _, err := client.UpdateSecRule(&input) + if err != nil { + return fmt.Errorf("Error updating sec rule %s: %s", name, err) + } + + return resourceOPCSecRuleRead(d, meta) +} + +func resourceOPCSecRuleDelete(d *schema.ResourceData, meta interface{}) error { + client := meta.(*compute.Client).SecRules() + name := d.Id() + + input := compute.DeleteSecRuleInput{ + Name: name, + } + if err := client.DeleteSecRule(&input); err != nil { + return fmt.Errorf("Error deleting sec rule %s: %s", name, err) + } + + return nil +} diff --git a/vendor/github.com/hashicorp/terraform-provider-opc/opc/resource_security_application.go b/vendor/github.com/hashicorp/terraform-provider-opc/opc/resource_security_application.go new file mode 100644 index 000000000..26b095330 --- /dev/null +++ b/vendor/github.com/hashicorp/terraform-provider-opc/opc/resource_security_application.go @@ -0,0 +1,140 @@ +package opc + +import ( + "fmt" + + "github.com/hashicorp/go-oracle-terraform/compute" + "github.com/hashicorp/terraform/helper/schema" + "github.com/hashicorp/terraform/helper/validation" +) + +func resourceOPCSecurityApplication() *schema.Resource { + return &schema.Resource{ + Create: resourceOPCSecurityApplicationCreate, + Read: resourceOPCSecurityApplicationRead, + Delete: resourceOPCSecurityApplicationDelete, + Importer: &schema.ResourceImporter{ + State: schema.ImportStatePassthrough, + }, + + Schema: map[string]*schema.Schema{ + "name": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + + "description": { + Type: schema.TypeString, + Optional: true, + ForceNew: true, + }, + + "protocol": { + Type: schema.TypeString, + Required: true, + ValidateFunc: validateIPProtocol, + ForceNew: true, + }, + + "dport": { + Type: schema.TypeString, + Optional: true, + ForceNew: true, + }, + + "icmptype": { + Type: schema.TypeString, + Optional: true, + ValidateFunc: validation.StringInSlice([]string{ + string(compute.Echo), + string(compute.Reply), + string(compute.TTL), + string(compute.TraceRoute), + string(compute.Unreachable), + }, true), + ForceNew: true, + }, + + "icmpcode": { + Type: schema.TypeString, + Optional: true, + ValidateFunc: validation.StringInSlice([]string{ + string(compute.Admin), + string(compute.Df), + string(compute.Host), + string(compute.Network), + string(compute.Port), + string(compute.Protocol), + }, true), + ForceNew: true, + }, + }, + } +} + +func resourceOPCSecurityApplicationCreate(d *schema.ResourceData, meta interface{}) error { + name := d.Get("name").(string) + protocol := d.Get("protocol").(string) + dport := d.Get("dport").(string) + icmptype := d.Get("icmptype").(string) + icmpcode := d.Get("icmpcode").(string) + description := d.Get("description").(string) + + client := meta.(*compute.Client).SecurityApplications() + input := compute.CreateSecurityApplicationInput{ + Name: name, + Description: description, + Protocol: compute.SecurityApplicationProtocol(protocol), + DPort: dport, + ICMPCode: compute.SecurityApplicationICMPCode(icmpcode), + ICMPType: compute.SecurityApplicationICMPType(icmptype), + } + info, err := client.CreateSecurityApplication(&input) + if err != nil { + return fmt.Errorf("Error creating security application %s: %s", name, err) + } + + d.SetId(info.Name) + + return resourceOPCSecurityApplicationRead(d, meta) +} + +func resourceOPCSecurityApplicationRead(d *schema.ResourceData, meta interface{}) error { + client := meta.(*compute.Client).SecurityApplications() + name := d.Id() + + input := compute.GetSecurityApplicationInput{ + Name: name, + } + result, err := client.GetSecurityApplication(&input) + if err != nil { + if compute.WasNotFoundError(err) { + d.SetId("") + return nil + } + return fmt.Errorf("Error reading security application %s: %s", name, err) + } + + d.Set("name", result.Name) + d.Set("protocol", result.Protocol) + d.Set("dport", result.DPort) + d.Set("icmptype", result.ICMPType) + d.Set("icmpcode", result.ICMPCode) + d.Set("description", result.Description) + + return nil +} + +func resourceOPCSecurityApplicationDelete(d *schema.ResourceData, meta interface{}) error { + client := meta.(*compute.Client).SecurityApplications() + name := d.Id() + + input := compute.DeleteSecurityApplicationInput{ + Name: name, + } + if err := client.DeleteSecurityApplication(&input); err != nil { + return fmt.Errorf("Error deleting security application '%s': %s", name, err) + } + return nil +} diff --git a/vendor/github.com/hashicorp/terraform-provider-opc/opc/resource_security_association.go b/vendor/github.com/hashicorp/terraform-provider-opc/opc/resource_security_association.go new file mode 100644 index 000000000..5e6d4277b --- /dev/null +++ b/vendor/github.com/hashicorp/terraform-provider-opc/opc/resource_security_association.go @@ -0,0 +1,101 @@ +package opc + +import ( + "fmt" + + "github.com/hashicorp/go-oracle-terraform/compute" + "github.com/hashicorp/terraform/helper/schema" +) + +func resourceOPCSecurityAssociation() *schema.Resource { + return &schema.Resource{ + Create: resourceOPCSecurityAssociationCreate, + Read: resourceOPCSecurityAssociationRead, + Delete: resourceOPCSecurityAssociationDelete, + Importer: &schema.ResourceImporter{ + State: schema.ImportStatePassthrough, + }, + + Schema: map[string]*schema.Schema{ + "name": { + Type: schema.TypeString, + Optional: true, + Computed: true, + ForceNew: true, + }, + + "vcable": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + + "seclist": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + }, + } +} + +func resourceOPCSecurityAssociationCreate(d *schema.ResourceData, meta interface{}) error { + client := meta.(*compute.Client).SecurityAssociations() + + name := d.Get("name").(string) + vcable := d.Get("vcable").(string) + seclist := d.Get("seclist").(string) + + input := compute.CreateSecurityAssociationInput{ + Name: name, + SecList: seclist, + VCable: vcable, + } + info, err := client.CreateSecurityAssociation(&input) + if err != nil { + return fmt.Errorf("Error creating security association between vcable %s and security list %s: %s", vcable, seclist, err) + } + + d.SetId(info.Name) + + return resourceOPCSecurityAssociationRead(d, meta) +} + +func resourceOPCSecurityAssociationRead(d *schema.ResourceData, meta interface{}) error { + client := meta.(*compute.Client).SecurityAssociations() + + name := d.Id() + + input := compute.GetSecurityAssociationInput{ + Name: name, + } + result, err := client.GetSecurityAssociation(&input) + if err != nil { + // Security Association does not exist + if compute.WasNotFoundError(err) { + d.SetId("") + return nil + } + return fmt.Errorf("Error reading security association %s: %s", name, err) + } + + d.Set("name", result.Name) + d.Set("seclist", result.SecList) + d.Set("vcable", result.VCable) + + return nil +} + +func resourceOPCSecurityAssociationDelete(d *schema.ResourceData, meta interface{}) error { + client := meta.(*compute.Client).SecurityAssociations() + + name := d.Id() + + input := compute.DeleteSecurityAssociationInput{ + Name: name, + } + if err := client.DeleteSecurityAssociation(&input); err != nil { + return fmt.Errorf("Error deleting Security Association '%s': %v", name, err) + } + return nil +} diff --git a/vendor/github.com/hashicorp/terraform-provider-opc/opc/resource_security_ip_list.go b/vendor/github.com/hashicorp/terraform-provider-opc/opc/resource_security_ip_list.go new file mode 100644 index 000000000..041f378a1 --- /dev/null +++ b/vendor/github.com/hashicorp/terraform-provider-opc/opc/resource_security_ip_list.go @@ -0,0 +1,135 @@ +package opc + +import ( + "fmt" + "log" + + "github.com/hashicorp/go-oracle-terraform/compute" + "github.com/hashicorp/terraform/helper/schema" +) + +func resourceOPCSecurityIPList() *schema.Resource { + return &schema.Resource{ + Create: resourceOPCSecurityIPListCreate, + Read: resourceOPCSecurityIPListRead, + Update: resourceOPCSecurityIPListUpdate, + Delete: resourceOPCSecurityIPListDelete, + Importer: &schema.ResourceImporter{ + State: schema.ImportStatePassthrough, + }, + + Schema: map[string]*schema.Schema{ + "name": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + "ip_entries": { + Type: schema.TypeList, + Required: true, + Elem: &schema.Schema{Type: schema.TypeString}, + }, + "description": { + Type: schema.TypeString, + Optional: true, + }, + }, + } +} + +func resourceOPCSecurityIPListCreate(d *schema.ResourceData, meta interface{}) error { + log.Printf("[DEBUG] Resource state: %#v", d.State()) + client := meta.(*compute.Client).SecurityIPLists() + + ipEntries := d.Get("ip_entries").([]interface{}) + ipEntryStrings := []string{} + for _, entry := range ipEntries { + ipEntryStrings = append(ipEntryStrings, entry.(string)) + } + + input := compute.CreateSecurityIPListInput{ + Name: d.Get("name").(string), + SecIPEntries: ipEntryStrings, + } + if description, ok := d.GetOk("description"); ok { + input.Description = description.(string) + } + + log.Printf("[DEBUG] Creating security IP list with %+v", input) + info, err := client.CreateSecurityIPList(&input) + if err != nil { + return fmt.Errorf("Error creating security IP list %s: %s", input.Name, err) + } + + d.SetId(info.Name) + return resourceOPCSecurityIPListRead(d, meta) +} + +func resourceOPCSecurityIPListRead(d *schema.ResourceData, meta interface{}) error { + log.Printf("[DEBUG] Resource state: %#v", d.State()) + client := meta.(*compute.Client).SecurityIPLists() + name := d.Id() + + log.Printf("[DEBUG] Reading state of security IP list %s", name) + input := compute.GetSecurityIPListInput{ + Name: name, + } + result, err := client.GetSecurityIPList(&input) + if err != nil { + // Security IP List does not exist + if compute.WasNotFoundError(err) { + d.SetId("") + return nil + } + return fmt.Errorf("Error reading security IP list %s: %s", name, err) + } + + log.Printf("[DEBUG] Read state of security IP list %s: %#v", name, result) + d.Set("name", result.Name) + d.Set("ip_entries", result.SecIPEntries) + d.Set("description", result.Description) + return nil +} + +func resourceOPCSecurityIPListUpdate(d *schema.ResourceData, meta interface{}) error { + log.Printf("[DEBUG] Resource state: %#v", d.State()) + + client := meta.(*compute.Client).SecurityIPLists() + + ipEntries := d.Get("ip_entries").([]interface{}) + ipEntryStrings := []string{} + for _, entry := range ipEntries { + ipEntryStrings = append(ipEntryStrings, entry.(string)) + } + input := compute.UpdateSecurityIPListInput{ + Name: d.Get("name").(string), + SecIPEntries: ipEntryStrings, + } + if description, ok := d.GetOk("description"); ok { + input.Description = description.(string) + } + + log.Printf("[DEBUG] Updating security IP list with %+v", input) + info, err := client.UpdateSecurityIPList(&input) + if err != nil { + return fmt.Errorf("Error updating security IP list %s: %s", input.Name, err) + } + d.SetId(info.Name) + + return resourceOPCSecurityIPListRead(d, meta) +} + +func resourceOPCSecurityIPListDelete(d *schema.ResourceData, meta interface{}) error { + log.Printf("[DEBUG] Resource state: %#v", d.State()) + client := meta.(*compute.Client).SecurityIPLists() + name := d.Id() + + log.Printf("[DEBUG] Deleting security IP list %s", name) + input := compute.DeleteSecurityIPListInput{ + Name: name, + } + if err := client.DeleteSecurityIPList(&input); err != nil { + return fmt.Errorf("Error deleting security IP list %s: %s", name, err) + } + return nil +} diff --git a/vendor/github.com/hashicorp/terraform-provider-opc/opc/resource_security_list.go b/vendor/github.com/hashicorp/terraform-provider-opc/opc/resource_security_list.go new file mode 100644 index 000000000..964c50210 --- /dev/null +++ b/vendor/github.com/hashicorp/terraform-provider-opc/opc/resource_security_list.go @@ -0,0 +1,141 @@ +package opc + +import ( + "fmt" + + "github.com/hashicorp/go-oracle-terraform/compute" + "github.com/hashicorp/terraform/helper/schema" + "github.com/hashicorp/terraform/helper/validation" +) + +func resourceOPCSecurityList() *schema.Resource { + return &schema.Resource{ + Create: resourceOPCSecurityListCreate, + Read: resourceOPCSecurityListRead, + Update: resourceOPCSecurityListUpdate, + Delete: resourceOPCSecurityListDelete, + Importer: &schema.ResourceImporter{ + State: schema.ImportStatePassthrough, + }, + + Schema: map[string]*schema.Schema{ + "name": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + + "description": { + Type: schema.TypeString, + Optional: true, + }, + + "policy": { + Type: schema.TypeString, + Optional: true, + Default: "deny", + ValidateFunc: validation.StringInSlice([]string{ + string(compute.SecurityListPolicyDeny), + string(compute.SecurityListPolicyPermit), + string(compute.SecurityListPolicyReject), + }, true), + }, + + "outbound_cidr_policy": { + Type: schema.TypeString, + Optional: true, + Default: "permit", + ValidateFunc: validation.StringInSlice([]string{ + string(compute.SecurityListPolicyDeny), + string(compute.SecurityListPolicyPermit), + string(compute.SecurityListPolicyReject), + }, true), + }, + }, + } +} + +func resourceOPCSecurityListCreate(d *schema.ResourceData, meta interface{}) error { + name := d.Get("name").(string) + description := d.Get("description").(string) + policy := d.Get("policy").(string) + outboundCIDRPolicy := d.Get("outbound_cidr_policy").(string) + + client := meta.(*compute.Client).SecurityLists() + input := compute.CreateSecurityListInput{ + Name: name, + Description: description, + Policy: compute.SecurityListPolicy(policy), + OutboundCIDRPolicy: compute.SecurityListPolicy(outboundCIDRPolicy), + } + info, err := client.CreateSecurityList(&input) + if err != nil { + return fmt.Errorf("Error creating security list %s: %s", name, err) + } + + d.SetId(info.Name) + + return resourceOPCSecurityListRead(d, meta) +} + +func resourceOPCSecurityListUpdate(d *schema.ResourceData, meta interface{}) error { + client := meta.(*compute.Client).SecurityLists() + + name := d.Get("name").(string) + description := d.Get("description").(string) + policy := d.Get("policy").(string) + outboundCIDRPolicy := d.Get("outbound_cidr_policy").(string) + + input := compute.UpdateSecurityListInput{ + Name: name, + Description: description, + Policy: compute.SecurityListPolicy(policy), + OutboundCIDRPolicy: compute.SecurityListPolicy(outboundCIDRPolicy), + } + _, err := client.UpdateSecurityList(&input) + if err != nil { + return fmt.Errorf("Error updating security list %s: %s", name, err) + } + + return resourceOPCSecurityListRead(d, meta) +} + +func resourceOPCSecurityListRead(d *schema.ResourceData, meta interface{}) error { + client := meta.(*compute.Client).SecurityLists() + + name := d.Id() + + input := compute.GetSecurityListInput{ + Name: name, + } + result, err := client.GetSecurityList(&input) + if err != nil { + // Security List does not exist + if compute.WasNotFoundError(err) { + d.SetId("") + return nil + } + return fmt.Errorf("Error reading security list %s: %s", name, err) + } + + d.Set("name", result.Name) + d.Set("description", result.Description) + d.Set("policy", string(result.Policy)) + d.Set("outbound_cidr_policy", string(result.OutboundCIDRPolicy)) + + return nil +} + +func resourceOPCSecurityListDelete(d *schema.ResourceData, meta interface{}) error { + client := meta.(*compute.Client).SecurityLists() + + name := d.Id() + input := compute.DeleteSecurityListInput{ + Name: name, + } + if err := client.DeleteSecurityList(&input); err != nil { + return fmt.Errorf("Error deleting security list %s: %s", name, err) + } + + return nil +} diff --git a/vendor/github.com/hashicorp/terraform-provider-opc/opc/resource_security_protocol.go b/vendor/github.com/hashicorp/terraform-provider-opc/opc/resource_security_protocol.go new file mode 100644 index 000000000..ed3b7b3fc --- /dev/null +++ b/vendor/github.com/hashicorp/terraform-provider-opc/opc/resource_security_protocol.go @@ -0,0 +1,160 @@ +package opc + +import ( + "fmt" + + "github.com/hashicorp/go-oracle-terraform/compute" + "github.com/hashicorp/terraform/helper/schema" +) + +func resourceOPCSecurityProtocol() *schema.Resource { + return &schema.Resource{ + Create: resourceOPCSecurityProtocolCreate, + Read: resourceOPCSecurityProtocolRead, + Update: resourceOPCSecurityProtocolUpdate, + Delete: resourceOPCSecurityProtocolDelete, + Importer: &schema.ResourceImporter{ + State: schema.ImportStatePassthrough, + }, + + Schema: map[string]*schema.Schema{ + "name": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + "dst_ports": { + Type: schema.TypeList, + Optional: true, + Elem: &schema.Schema{Type: schema.TypeString}, + }, + "description": { + Type: schema.TypeString, + Optional: true, + ForceNew: true, + }, + "ip_protocol": { + Type: schema.TypeString, + Optional: true, + Default: string(compute.All), + ValidateFunc: validateIPProtocol, + }, + "src_ports": { + Type: schema.TypeList, + Optional: true, + Elem: &schema.Schema{Type: schema.TypeString}, + }, + "tags": tagsForceNewSchema(), + "uri": { + Type: schema.TypeString, + Computed: true, + }, + }, + } +} + +func resourceOPCSecurityProtocolCreate(d *schema.ResourceData, meta interface{}) error { + client := meta.(*compute.Client).SecurityProtocols() + input := compute.CreateSecurityProtocolInput{ + Name: d.Get("name").(string), + IPProtocol: d.Get("ip_protocol").(string), + } + dstPorts := getStringList(d, "dst_ports") + if len(dstPorts) != 0 { + input.DstPortSet = dstPorts + } + srcPorts := getStringList(d, "src_ports") + if len(srcPorts) != 0 { + input.SrcPortSet = srcPorts + } + tags := getStringList(d, "tags") + if len(tags) != 0 { + input.Tags = tags + } + + if description, ok := d.GetOk("description"); ok { + input.Description = description.(string) + } + + info, err := client.CreateSecurityProtocol(&input) + if err != nil { + return fmt.Errorf("Error creating Security Protocol: %s", err) + } + + d.SetId(info.Name) + return resourceOPCSecurityProtocolRead(d, meta) +} + +func resourceOPCSecurityProtocolRead(d *schema.ResourceData, meta interface{}) error { + client := meta.(*compute.Client).SecurityProtocols() + getInput := compute.GetSecurityProtocolInput{ + Name: d.Id(), + } + result, err := client.GetSecurityProtocol(&getInput) + if err != nil { + // Security Protocol does not exist + if compute.WasNotFoundError(err) { + d.SetId("") + return nil + } + return fmt.Errorf("Error reading security protocol %s: %s", d.Id(), err) + } + + d.Set("name", result.Name) + d.Set("ip_protocol", result.IPProtocol) + d.Set("description", result.Description) + if err := setStringList(d, "dst_ports", result.DstPortSet); err != nil { + return err + } + if err := setStringList(d, "src_ports", result.SrcPortSet); err != nil { + return err + } + if err := setStringList(d, "tags", result.Tags); err != nil { + return err + } + return nil +} + +func resourceOPCSecurityProtocolUpdate(d *schema.ResourceData, meta interface{}) error { + client := meta.(*compute.Client).SecurityProtocols() + input := compute.UpdateSecurityProtocolInput{ + Name: d.Get("name").(string), + IPProtocol: d.Get("ip_protocol").(string), + } + dstPorts := getStringList(d, "dst_ports") + if len(dstPorts) != 0 { + input.DstPortSet = dstPorts + } + srcPorts := getStringList(d, "src_ports") + if len(srcPorts) != 0 { + input.SrcPortSet = srcPorts + } + tags := getStringList(d, "tags") + if len(tags) != 0 { + input.Tags = tags + } + if description, ok := d.GetOk("description"); ok { + input.Description = description.(string) + } + + info, err := client.UpdateSecurityProtocol(&input) + if err != nil { + return fmt.Errorf("Error updating Security Protocol: %s", err) + } + + d.SetId(info.Name) + return resourceOPCSecurityProtocolRead(d, meta) +} + +func resourceOPCSecurityProtocolDelete(d *schema.ResourceData, meta interface{}) error { + client := meta.(*compute.Client).SecurityProtocols() + name := d.Id() + + input := compute.DeleteSecurityProtocolInput{ + Name: name, + } + if err := client.DeleteSecurityProtocol(&input); err != nil { + return fmt.Errorf("Error deleting Security Protocol: %s", err) + } + return nil +} diff --git a/vendor/github.com/hashicorp/terraform-provider-opc/opc/resource_security_rule.go b/vendor/github.com/hashicorp/terraform-provider-opc/opc/resource_security_rule.go new file mode 100644 index 000000000..cfb49b974 --- /dev/null +++ b/vendor/github.com/hashicorp/terraform-provider-opc/opc/resource_security_rule.go @@ -0,0 +1,231 @@ +package opc + +import ( + "fmt" + + "github.com/hashicorp/go-oracle-terraform/compute" + "github.com/hashicorp/terraform/helper/schema" +) + +func resourceOPCSecurityRule() *schema.Resource { + return &schema.Resource{ + Create: resourceOPCSecurityRuleCreate, + Read: resourceOPCSecurityRuleRead, + Update: resourceOPCSecurityRuleUpdate, + Delete: resourceOPCSecurityRuleDelete, + Importer: &schema.ResourceImporter{ + State: schema.ImportStatePassthrough, + }, + + Schema: map[string]*schema.Schema{ + "name": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + "flow_direction": { + Type: schema.TypeString, + Required: true, + }, + "acl": { + Type: schema.TypeString, + Optional: true, + }, + "dst_ip_address_prefixes": { + Type: schema.TypeList, + Optional: true, + Elem: &schema.Schema{Type: schema.TypeString}, + }, + "src_ip_address_prefixes": { + Type: schema.TypeList, + Optional: true, + Elem: &schema.Schema{Type: schema.TypeString}, + }, + "security_protocols": { + Type: schema.TypeList, + Optional: true, + Elem: &schema.Schema{Type: schema.TypeString}, + }, + "dst_vnic_set": { + Type: schema.TypeString, + Optional: true, + }, + "src_vnic_set": { + Type: schema.TypeString, + Optional: true, + }, + "enabled": { + Type: schema.TypeBool, + Optional: true, + Default: true, + }, + "description": { + Type: schema.TypeString, + Optional: true, + }, + "tags": tagsOptionalSchema(), + "uri": { + Type: schema.TypeString, + Computed: true, + }, + }, + } +} + +func resourceOPCSecurityRuleCreate(d *schema.ResourceData, meta interface{}) error { + client := meta.(*compute.Client).SecurityRules() + input := compute.CreateSecurityRuleInput{ + Name: d.Get("name").(string), + FlowDirection: d.Get("flow_direction").(string), + Enabled: d.Get("enabled").(bool), + } + + if acl, ok := d.GetOk("acl"); ok { + input.ACL = acl.(string) + } + + if srcVNicSet, ok := d.GetOk("src_vnic_set"); ok { + input.SrcVnicSet = srcVNicSet.(string) + } + + if dstVNicSet, ok := d.GetOk("dst_vnic_set"); ok { + input.DstVnicSet = dstVNicSet.(string) + } + + securityProtocols := getStringList(d, "security_protocols") + if len(securityProtocols) != 0 { + input.SecProtocols = securityProtocols + } + + srcIPAdressPrefixes := getStringList(d, "src_ip_address_prefixes") + if len(srcIPAdressPrefixes) != 0 { + input.SrcIpAddressPrefixSets = srcIPAdressPrefixes + } + + dstIPAdressPrefixes := getStringList(d, "dst_ip_address_prefixes") + if len(dstIPAdressPrefixes) != 0 { + input.DstIpAddressPrefixSets = dstIPAdressPrefixes + } + + tags := getStringList(d, "tags") + if len(tags) != 0 { + input.Tags = tags + } + + if description, ok := d.GetOk("description"); ok { + input.Description = description.(string) + } + + info, err := client.CreateSecurityRule(&input) + if err != nil { + return fmt.Errorf("Error creating Security Rule: %s", err) + } + + d.SetId(info.Name) + return resourceOPCSecurityRuleRead(d, meta) +} + +func resourceOPCSecurityRuleRead(d *schema.ResourceData, meta interface{}) error { + client := meta.(*compute.Client).SecurityRules() + + getInput := compute.GetSecurityRuleInput{ + Name: d.Id(), + } + result, err := client.GetSecurityRule(&getInput) + if err != nil { + // SecurityRule does not exist + if compute.WasNotFoundError(err) { + d.SetId("") + return nil + } + return fmt.Errorf("Error reading security rule %s: %s", d.Id(), err) + } + + d.Set("name", result.Name) + d.Set("flow_direction", result.FlowDirection) + d.Set("enabled", result.Enabled) + d.Set("acl", result.ACL) + d.Set("src_vnic_set", result.SrcVnicSet) + d.Set("dst_vnic_set", result.DstVnicSet) + d.Set("description", result.Description) + d.Set("uri", result.Uri) + + if err := setStringList(d, "security_protocols", result.SecProtocols); err != nil { + return err + } + if err := setStringList(d, "dst_ip_address_prefixes", result.DstIpAddressPrefixSets); err != nil { + return err + } + if err := setStringList(d, "src_ip_address_prefixes", result.SrcIpAddressPrefixSets); err != nil { + return err + } + if err := setStringList(d, "tags", result.Tags); err != nil { + return err + } + return nil +} + +func resourceOPCSecurityRuleUpdate(d *schema.ResourceData, meta interface{}) error { + client := meta.(*compute.Client).SecurityRules() + input := compute.UpdateSecurityRuleInput{ + Name: d.Get("name").(string), + FlowDirection: d.Get("flow_direction").(string), + Enabled: d.Get("enabled").(bool), + } + + if acl, ok := d.GetOk("acl"); ok { + input.ACL = acl.(string) + } + + if srcVNicSet, ok := d.GetOk("src_vnic_set"); ok { + input.SrcVnicSet = srcVNicSet.(string) + } + + if dstVNicSet, ok := d.GetOk("dst_vnic_set"); ok { + input.DstVnicSet = dstVNicSet.(string) + } + + securityProtocols := getStringList(d, "security_protocols") + if len(securityProtocols) != 0 { + input.SecProtocols = securityProtocols + } + + srcIPAdressPrefixes := getStringList(d, "src_ip_address_prefixes") + if len(srcIPAdressPrefixes) != 0 { + input.SrcIpAddressPrefixSets = srcIPAdressPrefixes + } + + dstIPAdressPrefixes := getStringList(d, "dst_ip_address_prefixes") + if len(dstIPAdressPrefixes) != 0 { + input.DstIpAddressPrefixSets = dstIPAdressPrefixes + } + + tags := getStringList(d, "tags") + if len(tags) != 0 { + input.Tags = tags + } + + if description, ok := d.GetOk("description"); ok { + input.Description = description.(string) + } + info, err := client.UpdateSecurityRule(&input) + if err != nil { + return fmt.Errorf("Error updating Security Rule: %s", err) + } + + d.SetId(info.Name) + return resourceOPCSecurityRuleRead(d, meta) +} + +func resourceOPCSecurityRuleDelete(d *schema.ResourceData, meta interface{}) error { + client := meta.(*compute.Client).SecurityRules() + name := d.Id() + + input := compute.DeleteSecurityRuleInput{ + Name: name, + } + if err := client.DeleteSecurityRule(&input); err != nil { + return fmt.Errorf("Error deleting Security Rule: %s", err) + } + return nil +} diff --git a/vendor/github.com/hashicorp/terraform-provider-opc/opc/resource_ssh_key.go b/vendor/github.com/hashicorp/terraform-provider-opc/opc/resource_ssh_key.go new file mode 100644 index 000000000..40bcb8393 --- /dev/null +++ b/vendor/github.com/hashicorp/terraform-provider-opc/opc/resource_ssh_key.go @@ -0,0 +1,118 @@ +package opc + +import ( + "fmt" + + "github.com/hashicorp/go-oracle-terraform/compute" + "github.com/hashicorp/terraform/helper/schema" +) + +func resourceOPCSSHKey() *schema.Resource { + return &schema.Resource{ + Create: resourceOPCSSHKeyCreate, + Read: resourceOPCSSHKeyRead, + Update: resourceOPCSSHKeyUpdate, + Delete: resourceOPCSSHKeyDelete, + Importer: &schema.ResourceImporter{ + State: schema.ImportStatePassthrough, + }, + + Schema: map[string]*schema.Schema{ + "name": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + + "key": { + Type: schema.TypeString, + Required: true, + }, + + "enabled": { + Type: schema.TypeBool, + Optional: true, + Default: true, + }, + }, + } +} + +func resourceOPCSSHKeyCreate(d *schema.ResourceData, meta interface{}) error { + client := meta.(*compute.Client).SSHKeys() + + name := d.Get("name").(string) + key := d.Get("key").(string) + enabled := d.Get("enabled").(bool) + + input := compute.CreateSSHKeyInput{ + Name: name, + Key: key, + Enabled: enabled, + } + info, err := client.CreateSSHKey(&input) + if err != nil { + return fmt.Errorf("Error creating ssh key %s: %s", name, err) + } + + d.SetId(info.Name) + + return resourceOPCSSHKeyRead(d, meta) +} + +func resourceOPCSSHKeyUpdate(d *schema.ResourceData, meta interface{}) error { + client := meta.(*compute.Client).SSHKeys() + + name := d.Get("name").(string) + key := d.Get("key").(string) + enabled := d.Get("enabled").(bool) + + input := compute.UpdateSSHKeyInput{ + Name: name, + Key: key, + Enabled: enabled, + } + _, err := client.UpdateSSHKey(&input) + if err != nil { + return fmt.Errorf("Error updating ssh key %s: %s", name, err) + } + + return resourceOPCSSHKeyRead(d, meta) +} + +func resourceOPCSSHKeyRead(d *schema.ResourceData, meta interface{}) error { + client := meta.(*compute.Client).SSHKeys() + name := d.Id() + + input := compute.GetSSHKeyInput{ + Name: name, + } + result, err := client.GetSSHKey(&input) + if err != nil { + if compute.WasNotFoundError(err) { + d.SetId("") + return nil + } + return fmt.Errorf("Error reading ssh key %s: %s", name, err) + } + + d.Set("name", result.Name) + d.Set("key", result.Key) + d.Set("enabled", result.Enabled) + + return nil +} + +func resourceOPCSSHKeyDelete(d *schema.ResourceData, meta interface{}) error { + client := meta.(*compute.Client).SSHKeys() + name := d.Id() + + input := compute.DeleteSSHKeyInput{ + Name: name, + } + if err := client.DeleteSSHKey(&input); err != nil { + return fmt.Errorf("Error deleting ssh key %s: %s", name, err) + } + + return nil +} diff --git a/vendor/github.com/hashicorp/terraform-provider-opc/opc/resource_storage_volume.go b/vendor/github.com/hashicorp/terraform-provider-opc/opc/resource_storage_volume.go new file mode 100644 index 000000000..72a2b969c --- /dev/null +++ b/vendor/github.com/hashicorp/terraform-provider-opc/opc/resource_storage_volume.go @@ -0,0 +1,285 @@ +package opc + +import ( + "fmt" + "strconv" + + "github.com/hashicorp/go-oracle-terraform/compute" + "github.com/hashicorp/terraform/helper/schema" + "github.com/hashicorp/terraform/helper/validation" +) + +func resourceOPCStorageVolume() *schema.Resource { + return &schema.Resource{ + Create: resourceOPCStorageVolumeCreate, + Read: resourceOPCStorageVolumeRead, + Update: resourceOPCStorageVolumeUpdate, + Delete: resourceOPCStorageVolumeDelete, + Importer: &schema.ResourceImporter{ + State: schema.ImportStatePassthrough, + }, + + Schema: map[string]*schema.Schema{ + "name": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + "description": { + Type: schema.TypeString, + Optional: true, + }, + "size": { + Type: schema.TypeInt, + Required: true, + ValidateFunc: validation.IntBetween(1, 2048), + }, + "storage_type": { + Type: schema.TypeString, + Optional: true, + ForceNew: true, + Default: compute.StorageVolumeKindDefault, + ValidateFunc: validation.StringInSlice([]string{ + string(compute.StorageVolumeKindDefault), + string(compute.StorageVolumeKindLatency), + }, true), + }, + + "snapshot": { + Type: schema.TypeString, + Optional: true, + ForceNew: true, + Computed: true, + }, + + "snapshot_id": { + Type: schema.TypeString, + Optional: true, + Computed: true, + ForceNew: true, + }, + + "snapshot_account": { + Type: schema.TypeString, + Optional: true, + ForceNew: true, + }, + + "bootable": { + Type: schema.TypeBool, + Optional: true, + Default: false, + ForceNew: true, + }, + + "image_list": { + Type: schema.TypeString, + Optional: true, + ForceNew: true, + }, + + "image_list_entry": { + Type: schema.TypeInt, + Optional: true, + ForceNew: true, + Default: -1, + }, + + "tags": tagsOptionalSchema(), + + // Computed fields + "hypervisor": { + Type: schema.TypeString, + Optional: true, + Computed: true, + }, + "machine_image": { + Type: schema.TypeString, + Optional: true, + Computed: true, + }, + "managed": { + Type: schema.TypeBool, + Optional: true, + Computed: true, + }, + "platform": { + Type: schema.TypeString, + Optional: true, + Computed: true, + }, + "readonly": { + Type: schema.TypeBool, + Optional: true, + Computed: true, + }, + "status": { + Type: schema.TypeString, + Optional: true, + Computed: true, + }, + "storage_pool": { + Type: schema.TypeString, + Optional: true, + Computed: true, + }, + "uri": { + Type: schema.TypeString, + Optional: true, + Computed: true, + }, + }, + } +} + +func resourceOPCStorageVolumeCreate(d *schema.ResourceData, meta interface{}) error { + client := meta.(*compute.Client).StorageVolumes() + + name := d.Get("name").(string) + description := d.Get("description").(string) + size := d.Get("size").(int) + storageType := d.Get("storage_type").(string) + bootable := d.Get("bootable").(bool) + imageList := d.Get("image_list").(string) + imageListEntry := d.Get("image_list_entry").(int) + + if bootable == true { + if imageList == "" { + return fmt.Errorf("Error: A Bootable Volume must have an Image List!") + } + + if imageListEntry == -1 { + return fmt.Errorf("Error: A Bootable Volume must have an Image List Entry!") + } + } + + input := compute.CreateStorageVolumeInput{ + Name: name, + Description: description, + Size: strconv.Itoa(size), + Properties: []string{storageType}, + Bootable: bootable, + ImageList: imageList, + ImageListEntry: imageListEntry, + Tags: getStringList(d, "tags"), + } + + if v, ok := d.GetOk("snapshot"); ok { + input.Snapshot = v.(string) + } + if v, ok := d.GetOk("snapshot_account"); ok { + input.SnapshotAccount = v.(string) + } + if v, ok := d.GetOk("snapshot_id"); ok { + input.SnapshotID = v.(string) + } + + info, err := client.CreateStorageVolume(&input) + if err != nil { + return fmt.Errorf("Error creating storage volume %s: %s", name, err) + } + + d.SetId(info.Name) + return resourceOPCStorageVolumeRead(d, meta) +} + +func resourceOPCStorageVolumeUpdate(d *schema.ResourceData, meta interface{}) error { + client := meta.(*compute.Client).StorageVolumes() + + name := d.Id() + description := d.Get("description").(string) + size := d.Get("size").(int) + storageType := d.Get("storage_type").(string) + imageList := d.Get("image_list").(string) + imageListEntry := d.Get("image_list_entry").(int) + + input := compute.UpdateStorageVolumeInput{ + Name: name, + Description: description, + Size: strconv.Itoa(size), + Properties: []string{storageType}, + ImageList: imageList, + ImageListEntry: imageListEntry, + Tags: getStringList(d, "tags"), + } + _, err := client.UpdateStorageVolume(&input) + if err != nil { + return fmt.Errorf("Error updating storage volume %s: %s", name, err) + } + + return resourceOPCStorageVolumeRead(d, meta) +} + +func resourceOPCStorageVolumeRead(d *schema.ResourceData, meta interface{}) error { + sv := meta.(*compute.Client).StorageVolumes() + + name := d.Id() + input := compute.GetStorageVolumeInput{ + Name: name, + } + result, err := sv.GetStorageVolume(&input) + if err != nil { + // Volume doesn't exist + if compute.WasNotFoundError(err) { + d.SetId("") + return nil + } + return fmt.Errorf("Error reading storage volume %s: %s", name, err) + } + + if result == nil { + // Volume doesn't exist + d.SetId("") + return nil + } + + d.Set("name", result.Name) + d.Set("description", result.Description) + d.Set("storage_type", result.Properties[0]) + size, err := strconv.Atoi(result.Size) + if err != nil { + return err + } + d.Set("size", size) + d.Set("bootable", result.Bootable) + d.Set("image_list", result.ImageList) + d.Set("image_list_entry", result.ImageListEntry) + + d.Set("snapshot", result.Snapshot) + d.Set("snapshot_id", result.SnapshotID) + d.Set("snapshot_account", result.SnapshotAccount) + + if err := setStringList(d, "tags", result.Tags); err != nil { + return err + } + + flattenOPCStorageVolumeComputedFields(d, result) + + return nil +} + +func resourceOPCStorageVolumeDelete(d *schema.ResourceData, meta interface{}) error { + client := meta.(*compute.Client).StorageVolumes() + name := d.Id() + + input := compute.DeleteStorageVolumeInput{ + Name: name, + } + err := client.DeleteStorageVolume(&input) + if err != nil { + return fmt.Errorf("Error deleting storage volume %s: %s", name, err) + } + + return nil +} + +func flattenOPCStorageVolumeComputedFields(d *schema.ResourceData, result *compute.StorageVolumeInfo) { + d.Set("hypervisor", result.Hypervisor) + d.Set("machine_image", result.MachineImage) + d.Set("managed", result.Managed) + d.Set("platform", result.Platform) + d.Set("readonly", result.ReadOnly) + d.Set("status", result.Status) + d.Set("storage_pool", result.StoragePool) + d.Set("uri", result.URI) +} diff --git a/vendor/github.com/hashicorp/terraform-provider-opc/opc/resource_storage_volume_snapshot.go b/vendor/github.com/hashicorp/terraform-provider-opc/opc/resource_storage_volume_snapshot.go new file mode 100644 index 000000000..4612c9f95 --- /dev/null +++ b/vendor/github.com/hashicorp/terraform-provider-opc/opc/resource_storage_volume_snapshot.go @@ -0,0 +1,230 @@ +package opc + +import ( + "fmt" + "strconv" + + "github.com/hashicorp/go-oracle-terraform/compute" + "github.com/hashicorp/terraform/helper/schema" +) + +func resourceOPCStorageVolumeSnapshot() *schema.Resource { + return &schema.Resource{ + Create: resourceOPCStorageVolumeSnapshotCreate, + Read: resourceOPCStorageVolumeSnapshotRead, + Delete: resourceOPCStorageVolumeSnapshotDelete, + Importer: &schema.ResourceImporter{ + State: schema.ImportStatePassthrough, + }, + + Schema: map[string]*schema.Schema{ + // Required Attributes + "volume_name": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + + // Optional Attributes + "description": { + Type: schema.TypeString, + Optional: true, + ForceNew: true, + }, + + // Optional, but also computed if unspecified + "name": { + Type: schema.TypeString, + Optional: true, + Computed: true, + ForceNew: true, + }, + + "parent_volume_bootable": { + Type: schema.TypeBool, + Optional: true, + ForceNew: true, + Default: false, + }, + + "collocated": { + Type: schema.TypeBool, + Optional: true, + Default: false, + ForceNew: true, + }, + + "tags": tagsForceNewSchema(), + + // Computed Attributes + "account": { + Type: schema.TypeString, + Computed: true, + }, + + "machine_image_name": { + Type: schema.TypeString, + Computed: true, + }, + + "size": { + Type: schema.TypeString, + Computed: true, + }, + + "property": { + Type: schema.TypeString, + Computed: true, + }, + + "platform": { + Type: schema.TypeString, + Computed: true, + }, + + "snapshot_timestamp": { + Type: schema.TypeString, + Computed: true, + }, + + "snapshot_id": { + Type: schema.TypeString, + Computed: true, + }, + + "start_timestamp": { + Type: schema.TypeString, + Computed: true, + }, + + "status": { + Type: schema.TypeString, + Computed: true, + }, + + "status_detail": { + Type: schema.TypeString, + Computed: true, + }, + + "status_timestamp": { + Type: schema.TypeString, + Computed: true, + }, + + "uri": { + Type: schema.TypeString, + Computed: true, + }, + }, + } +} + +func resourceOPCStorageVolumeSnapshotCreate(d *schema.ResourceData, meta interface{}) error { + client := meta.(*compute.Client).StorageVolumeSnapshots() + + // Get required attribute + input := &compute.CreateStorageVolumeSnapshotInput{ + Volume: d.Get("volume_name").(string), + } + + if v, ok := d.GetOk("description"); ok { + input.Description = v.(string) + } + + if v, ok := d.GetOk("name"); ok { + input.Name = v.(string) + } + + // Convert parent_volume_bootable to string + bootable := d.Get("parent_volume_bootable").(bool) + if bootable { + input.ParentVolumeBootable = "true" + } + + collocated := d.Get("collocated").(bool) + if collocated { + input.Property = compute.SnapshotPropertyCollocated + } + + tags := getStringList(d, "tags") + if len(tags) > 0 { + input.Tags = tags + } + + info, err := client.CreateStorageVolumeSnapshot(input) + if err != nil { + return fmt.Errorf("Error creating snapshot '%s': %v", input.Name, err) + } + + d.SetId(info.Name) + return resourceOPCStorageVolumeSnapshotRead(d, meta) +} + +func resourceOPCStorageVolumeSnapshotRead(d *schema.ResourceData, meta interface{}) error { + client := meta.(*compute.Client).StorageVolumeSnapshots() + + name := d.Id() + input := &compute.GetStorageVolumeSnapshotInput{ + Name: name, + } + + result, err := client.GetStorageVolumeSnapshot(input) + if err != nil { + if compute.WasNotFoundError(err) { + d.SetId("") + return nil + } + return fmt.Errorf("Error reading storage volume snapshot '%s': %v", name, err) + } + + d.Set("volume_name", result.Volume) + d.Set("description", result.Description) + d.Set("name", result.Name) + d.Set("property", result.Property) + d.Set("platform", result.Platform) + d.Set("account", result.Account) + d.Set("machine_image_name", result.MachineImageName) + d.Set("size", result.Size) + d.Set("snapshot_timestamp", result.SnapshotTimestamp) + d.Set("snapshot_id", result.SnapshotID) + d.Set("start_timestamp", result.StartTimestamp) + d.Set("status", result.Status) + d.Set("status_detail", result.StatusDetail) + d.Set("status_timestamp", result.StatusTimestamp) + d.Set("uri", result.URI) + + bootable, err := strconv.ParseBool(result.ParentVolumeBootable) + if err != nil { + return fmt.Errorf("Error converting parent volume to boolean: %v", err) + } + d.Set("parent_volume_bootable", bootable) + + if result.Property != compute.SnapshotPropertyCollocated { + d.Set("collocated", false) + } else { + d.Set("collocated", true) + } + + if err := setStringList(d, "tags", result.Tags); err != nil { + return err + } + + return nil +} + +func resourceOPCStorageVolumeSnapshotDelete(d *schema.ResourceData, meta interface{}) error { + client := meta.(*compute.Client).StorageVolumeSnapshots() + + name := d.Id() + + input := &compute.DeleteStorageVolumeSnapshotInput{ + Name: name, + } + + if err := client.DeleteStorageVolumeSnapshot(input); err != nil { + return fmt.Errorf("Error deleting storage volume snapshot '%s': %v", name, err) + } + + return nil +} diff --git a/vendor/github.com/hashicorp/terraform-provider-opc/opc/resource_vnic_set.go b/vendor/github.com/hashicorp/terraform-provider-opc/opc/resource_vnic_set.go new file mode 100644 index 000000000..6ca4a53be --- /dev/null +++ b/vendor/github.com/hashicorp/terraform-provider-opc/opc/resource_vnic_set.go @@ -0,0 +1,169 @@ +package opc + +import ( + "fmt" + + "github.com/hashicorp/go-oracle-terraform/compute" + "github.com/hashicorp/terraform/helper/schema" +) + +func resourceOPCVNICSet() *schema.Resource { + return &schema.Resource{ + Create: resourceOPCVNICSetCreate, + Read: resourceOPCVNICSetRead, + Update: resourceOPCVNICSetUpdate, + Delete: resourceOPCVNICSetDelete, + Importer: &schema.ResourceImporter{ + State: schema.ImportStatePassthrough, + }, + + Schema: map[string]*schema.Schema{ + "name": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + "description": { + Type: schema.TypeString, + Optional: true, + }, + "applied_acls": { + Type: schema.TypeList, + Optional: true, + Elem: &schema.Schema{Type: schema.TypeString}, + }, + "virtual_nics": { + Type: schema.TypeList, + Optional: true, + Elem: &schema.Schema{Type: schema.TypeString}, + }, + "tags": { + Type: schema.TypeList, + Optional: true, + Elem: &schema.Schema{Type: schema.TypeString}, + }, + }, + } +} + +func resourceOPCVNICSetCreate(d *schema.ResourceData, meta interface{}) error { + client := meta.(*compute.Client).VirtNICSets() + + name := d.Get("name").(string) + desc, descOk := d.GetOk("description") + + input := &compute.CreateVirtualNICSetInput{ + Name: name, + } + + if descOk { + input.Description = desc.(string) + } + + acls := getStringList(d, "applied_acls") + if len(acls) != 0 { + input.AppliedACLs = acls + } + + vnics := getStringList(d, "virtual_nics") + if len(vnics) != 0 { + input.VirtualNICs = vnics + } + + tags := getStringList(d, "tags") + if len(tags) != 0 { + input.Tags = tags + } + + vnicSet, err := client.CreateVirtualNICSet(input) + if err != nil { + return fmt.Errorf("Error creating Virtual NIC Set: %s", err) + } + + d.SetId(vnicSet.Name) + + return resourceOPCVNICSetRead(d, meta) +} + +func resourceOPCVNICSetRead(d *schema.ResourceData, meta interface{}) error { + client := meta.(*compute.Client).VirtNICSets() + + name := d.Id() + input := &compute.GetVirtualNICSetInput{ + Name: name, + } + + res, err := client.GetVirtualNICSet(input) + if err != nil { + if compute.WasNotFoundError(err) { + d.SetId("") + return nil + } + return fmt.Errorf("Error reading Virtual NIC Set '%s': %s", name, err) + } + + d.Set("name", res.Name) + d.Set("description", res.Description) + if err := setStringList(d, "applied_acls", res.AppliedACLs); err != nil { + return err + } + if err := setStringList(d, "virtual_nics", res.VirtualNICs); err != nil { + return err + } + if err := setStringList(d, "tags", res.Tags); err != nil { + return err + } + return nil +} + +func resourceOPCVNICSetUpdate(d *schema.ResourceData, meta interface{}) error { + client := meta.(*compute.Client).VirtNICSets() + + name := d.Id() + desc, descOk := d.GetOk("description") + + input := &compute.UpdateVirtualNICSetInput{ + Name: name, + } + + if descOk { + input.Description = desc.(string) + } + + acls := getStringList(d, "applied_acls") + if len(acls) != 0 { + input.AppliedACLs = acls + } + + vnics := getStringList(d, "virtual_nics") + if len(vnics) != 0 { + input.VirtualNICs = vnics + } + + tags := getStringList(d, "tags") + if len(tags) != 0 { + input.Tags = tags + } + + info, err := client.UpdateVirtualNICSet(input) + if err != nil { + return fmt.Errorf("Error updating Virtual NIC Set: %s", err) + } + + d.SetId(info.Name) + return resourceOPCVNICSetRead(d, meta) +} + +func resourceOPCVNICSetDelete(d *schema.ResourceData, meta interface{}) error { + client := meta.(*compute.Client).VirtNICSets() + + name := d.Id() + input := &compute.DeleteVirtualNICSetInput{ + Name: name, + } + + if err := client.DeleteVirtualNICSet(input); err != nil { + return fmt.Errorf("Error deleting Virtual NIC Set '%s': %s", name, err) + } + return nil +} diff --git a/vendor/github.com/hashicorp/terraform-provider-opc/opc/tags.go b/vendor/github.com/hashicorp/terraform-provider-opc/opc/tags.go new file mode 100644 index 000000000..593752ba0 --- /dev/null +++ b/vendor/github.com/hashicorp/terraform-provider-opc/opc/tags.go @@ -0,0 +1,28 @@ +package opc + +import "github.com/hashicorp/terraform/helper/schema" + +func tagsOptionalSchema() *schema.Schema { + return &schema.Schema{ + Type: schema.TypeList, + Optional: true, + Elem: &schema.Schema{Type: schema.TypeString}, + } +} + +func tagsForceNewSchema() *schema.Schema { + return &schema.Schema{ + Type: schema.TypeList, + Optional: true, + ForceNew: true, + Elem: &schema.Schema{Type: schema.TypeString}, + } +} + +func tagsComputedSchema() *schema.Schema { + return &schema.Schema{ + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{Type: schema.TypeString}, + } +} diff --git a/vendor/github.com/hashicorp/terraform-provider-opc/opc/validators.go b/vendor/github.com/hashicorp/terraform-provider-opc/opc/validators.go new file mode 100644 index 000000000..776ee53e5 --- /dev/null +++ b/vendor/github.com/hashicorp/terraform-provider-opc/opc/validators.go @@ -0,0 +1,67 @@ +package opc + +import ( + "fmt" + "net" + + "github.com/hashicorp/go-oracle-terraform/compute" +) + +// Validate whether an IP Prefix CIDR is correct or not +func validateIPPrefixCIDR(v interface{}, k string) (ws []string, errors []error) { + value := v.(string) + + _, ipnet, err := net.ParseCIDR(value) + if err != nil { + errors = append(errors, fmt.Errorf( + "%q must contain a valid CIDR, got error while parsing: %s", k, err)) + return + } + + if ipnet == nil || value != ipnet.String() { + errors = append(errors, fmt.Errorf( + "%q must contain a valid network CIDR, expected %q, got %q", k, ipnet, value)) + return + } + return +} + +// Admin distance can either be a 0, 1, or a 2. Defaults to 0. +func validateAdminDistance(v interface{}, k string) (ws []string, errors []error) { + value := v.(int) + + if value < 0 || value > 2 { + errors = append(errors, fmt.Errorf( + "%q can only be an interger between 0-2. Got: %d", k, value)) + } + return +} + +// Admin distance can either be a 0, 1, or a 2. Defaults to 0. +func validateIPProtocol(v interface{}, k string) (ws []string, errors []error) { + validProtocols := map[string]struct{}{ + string(compute.All): {}, + string(compute.AH): {}, + string(compute.ESP): {}, + string(compute.ICMP): {}, + string(compute.ICMPV6): {}, + string(compute.IGMP): {}, + string(compute.IPIP): {}, + string(compute.GRE): {}, + string(compute.MPLSIP): {}, + string(compute.OSPF): {}, + string(compute.PIM): {}, + string(compute.RDP): {}, + string(compute.SCTP): {}, + string(compute.TCP): {}, + string(compute.UDP): {}, + } + + value := v.(string) + if _, ok := validProtocols[value]; !ok { + errors = append(errors, fmt.Errorf( + `%q must contain a valid Image owner , expected ["all", "ah", "esp", "icmp", "icmpv6", "igmp", "ipip", "gre", "mplsip", "ospf", "pim", "rdp", "sctp", "tcp", "udp"] got %q`, + k, value)) + } + return +} diff --git a/vendor/github.com/joyent/gosdc/cloudapi/cloudapi.go b/vendor/github.com/joyent/gosdc/cloudapi/cloudapi.go deleted file mode 100644 index 2f7c406ac..000000000 --- a/vendor/github.com/joyent/gosdc/cloudapi/cloudapi.go +++ /dev/null @@ -1,127 +0,0 @@ -/* -Package cloudapi interacts with the Cloud API (http://apidocs.joyent.com/cloudapi/). - -Licensed under the Mozilla Public License version 2.0 - -Copyright (c) Joyent Inc. -*/ -package cloudapi - -import ( - "net/http" - "net/url" - "path" - - "github.com/joyent/gocommon/client" - jh "github.com/joyent/gocommon/http" -) - -const ( - // DefaultAPIVersion defines the default version of the Cloud API to use - DefaultAPIVersion = "~7.3" - - // CloudAPI URL parts - apiKeys = "keys" - apiPackages = "packages" - apiImages = "images" - apiDatacenters = "datacenters" - apiMachines = "machines" - apiMetadata = "metadata" - apiSnapshots = "snapshots" - apiTags = "tags" - apiAnalytics = "analytics" - apiInstrumentations = "instrumentations" - apiInstrumentationsValue = "value" - apiInstrumentationsRaw = "raw" - apiInstrumentationsHeatmap = "heatmap" - apiInstrumentationsImage = "image" - apiInstrumentationsDetails = "details" - apiUsage = "usage" - apiAudit = "audit" - apiFirewallRules = "fwrules" - apiFirewallRulesEnable = "enable" - apiFirewallRulesDisable = "disable" - apiNetworks = "networks" - apiFabricVLANs = "fabrics/default/vlans" - apiFabricNetworks = "networks" - apiNICs = "nics" - apiServices = "services" - - // CloudAPI actions - actionExport = "export" - actionStop = "stop" - actionStart = "start" - actionReboot = "reboot" - actionResize = "resize" - actionRename = "rename" - actionEnableFw = "enable_firewall" - actionDisableFw = "disable_firewall" -) - -// Client provides a means to access the Joyent CloudAPI -type Client struct { - client client.Client -} - -// New creates a new Client. -func New(client client.Client) *Client { - return &Client{client} -} - -// Filter represents a filter that can be applied to an API request. -type Filter struct { - v url.Values -} - -// NewFilter creates a new Filter. -func NewFilter() *Filter { - return &Filter{make(url.Values)} -} - -// Set a value for the specified filter. -func (f *Filter) Set(filter, value string) { - f.v.Set(filter, value) -} - -// Add a value for the specified filter. -func (f *Filter) Add(filter, value string) { - f.v.Add(filter, value) -} - -// request represents an API request -type request struct { - method string - url string - filter *Filter - reqValue interface{} - reqHeader http.Header - resp interface{} - respHeader *http.Header - expectedStatus int -} - -// Helper method to send an API request -func (c *Client) sendRequest(req request) (*jh.ResponseData, error) { - request := jh.RequestData{ - ReqValue: req.reqValue, - ReqHeaders: req.reqHeader, - } - if req.filter != nil { - request.Params = &req.filter.v - } - if req.expectedStatus == 0 { - req.expectedStatus = http.StatusOK - } - respData := jh.ResponseData{ - RespValue: req.resp, - RespHeaders: req.respHeader, - ExpectedStatus: []int{req.expectedStatus}, - } - err := c.client.SendRequest(req.method, req.url, "", &request, &respData) - return &respData, err -} - -// Helper method to create the API URL -func makeURL(parts ...string) string { - return path.Join(parts...) -} diff --git a/vendor/github.com/joyent/gosdc/cloudapi/datacenters.go b/vendor/github.com/joyent/gosdc/cloudapi/datacenters.go deleted file mode 100644 index e2bddf954..000000000 --- a/vendor/github.com/joyent/gosdc/cloudapi/datacenters.go +++ /dev/null @@ -1,41 +0,0 @@ -package cloudapi - -import ( - "net/http" - - "github.com/joyent/gocommon/client" - "github.com/joyent/gocommon/errors" -) - -// ListDatacenters provides a list of all datacenters this cloud is aware of. -// See API docs: http://apidocs.joyent.com/cloudapi/#ListDatacenters -func (c *Client) ListDatacenters() (map[string]interface{}, error) { - var resp map[string]interface{} - req := request{ - method: client.GET, - url: apiDatacenters, - resp: &resp, - } - if _, err := c.sendRequest(req); err != nil { - return nil, errors.Newf(err, "failed to get list of datcenters") - } - return resp, nil -} - -// GetDatacenter gets an individual datacenter by name. Returns an HTTP redirect -// to your client, the datacenter URL is in the Location header. -// See API docs: http://apidocs.joyent.com/cloudapi/#GetDatacenter -func (c *Client) GetDatacenter(datacenterName string) (string, error) { - var respHeader http.Header - req := request{ - method: client.GET, - url: makeURL(apiDatacenters, datacenterName), - respHeader: &respHeader, - expectedStatus: http.StatusFound, - } - respData, err := c.sendRequest(req) - if err != nil { - return "", errors.Newf(err, "failed to get datacenter with name: %s", datacenterName) - } - return respData.RespHeaders.Get("Location"), nil -} diff --git a/vendor/github.com/joyent/gosdc/cloudapi/fabrics.go b/vendor/github.com/joyent/gosdc/cloudapi/fabrics.go deleted file mode 100644 index cc36a7b3d..000000000 --- a/vendor/github.com/joyent/gosdc/cloudapi/fabrics.go +++ /dev/null @@ -1,182 +0,0 @@ -package cloudapi - -import ( - "net/http" - "strconv" - - "github.com/joyent/gocommon/client" - "github.com/joyent/gocommon/errors" -) - -type FabricVLAN struct { - Id int16 `json:"vlan_id"` // Number between 0-4095 indicating VLAN Id - Name string `json:"name"` // Unique name to identify VLAN - Description string `json:"description,omitempty"` // Optional description of the VLAN -} - -type FabricNetwork struct { - Id string `json:"id"` // Unique identifier for network - Name string `json:"name"` // Network name - Public bool `json:"public"` // Whether or not this is an RFC1918 network - Fabric bool `json:"fabric"` // Whether this network is on a fabric - Description string `json:"description"` // Optional description of network - Subnet string `json:"subnet"` // CIDR formatted string describing network - ProvisionStartIp string `json:"provision_start_ip"` // First IP on the network that can be assigned - ProvisionEndIp string `json:"provision_end_ip"` // Last assignable IP on the network - Gateway string `json:"gateway"` // Optional Gateway IP - Resolvers []string `json:"resolvers,omitempty"` // Array of IP addresses for resolvers - Routes map[string]string `json:"routes,omitempty"` // Map of CIDR block to Gateway IP Address - InternetNAT bool `json:"internet_nat"` // If a NAT zone is provisioned at Gateway IP Address - VLANId int16 `json:"vlan_id"` // VLAN network is on -} - -type CreateFabricNetworkOpts struct { - Name string `json:"name"` // Network name - Description string `json:"description,omitempty"` // Optional description of network - Subnet string `json:"subnet"` // CIDR formatted string describing network - ProvisionStartIp string `json:"provision_start_ip"` // First IP on the network that can be assigned - ProvisionEndIp string `json:"provision_end_ip"` // Last assignable IP on the network - Gateway string `json:"gateway,omitempty"` // Optional Gateway IP - Resolvers []string `json:"resolvers,omitempty"` // Array of IP addresses for resolvers - Routes map[string]string `json:"routes,omitempty"` // Map of CIDR block to Gateway IP Address - InternetNAT bool `json:"internet_nat"` // If a NAT zone is provisioned at Gateway IP Address -} - -// ListFabricVLANs lists VLANs -// See API docs: https://apidocs.joyent.com/cloudapi/#ListFabricVLANs -func (c *Client) ListFabricVLANs() ([]FabricVLAN, error) { - var resp []FabricVLAN - req := request{ - method: client.GET, - url: apiFabricVLANs, - resp: &resp, - } - if _, err := c.sendRequest(req); err != nil { - return nil, errors.Newf(err, "failed to get list of fabric VLANs") - } - return resp, nil -} - -// GetFabricLAN retrieves a single VLAN by ID -// See API docs: https://apidocs.joyent.com/cloudapi/#GetFabricVLAN -func (c *Client) GetFabricVLAN(vlanID int16) (*FabricVLAN, error) { - var resp FabricVLAN - req := request{ - method: client.GET, - url: makeURL(apiFabricVLANs, strconv.Itoa(int(vlanID))), - resp: &resp, - } - if _, err := c.sendRequest(req); err != nil { - return nil, errors.Newf(err, "failed to get fabric VLAN with id %d", vlanID) - } - return &resp, nil -} - -// CreateFabricVLAN creates a new VLAN with the specified options -// See API docs: https://apidocs.joyent.com/cloudapi/#CreateFabricVLAN -func (c *Client) CreateFabricVLAN(vlan FabricVLAN) (*FabricVLAN, error) { - var resp FabricVLAN - req := request{ - method: client.POST, - url: apiFabricVLANs, - reqValue: vlan, - resp: &resp, - expectedStatus: http.StatusCreated, - } - if _, err := c.sendRequest(req); err != nil { - return nil, errors.Newf(err, "failed to create fabric VLAN: %d - %s", vlan.Id, vlan.Name) - } - return &resp, nil -} - -// UpdateFabricVLAN updates a given VLAN with new fields -// See API docs: https://apidocs.joyent.com/cloudapi/#UpdateFabricVLAN -func (c *Client) UpdateFabricVLAN(vlan FabricVLAN) (*FabricVLAN, error) { - var resp FabricVLAN - req := request{ - method: client.PUT, - url: makeURL(apiFabricVLANs, strconv.Itoa(int(vlan.Id))), - reqValue: vlan, - resp: &resp, - expectedStatus: http.StatusAccepted, - } - if _, err := c.sendRequest(req); err != nil { - return nil, errors.Newf(err, "failed to update fabric VLAN with id %d to %s - %s", vlan.Id, vlan.Name, vlan.Description) - } - return &resp, nil -} - -// DeleteFabricVLAN delets a given VLAN as specified by ID -// See API docs: https://apidocs.joyent.com/cloudapi/#DeleteFabricVLAN -func (c *Client) DeleteFabricVLAN(vlanID int16) error { - req := request{ - method: client.DELETE, - url: makeURL(apiFabricVLANs, strconv.Itoa(int(vlanID))), - expectedStatus: http.StatusNoContent, - } - if _, err := c.sendRequest(req); err != nil { - return errors.Newf(err, "failed to delete fabric VLAN with id %d", vlanID) - } - return nil -} - -// ListFabricNetworks lists the networks inside the given VLAN -// See API docs: https://apidocs.joyent.com/cloudapi/#ListFabricNetworks -func (c *Client) ListFabricNetworks(vlanID int16) ([]FabricNetwork, error) { - var resp []FabricNetwork - req := request{ - method: client.GET, - url: makeURL(apiFabricVLANs, strconv.Itoa(int(vlanID)), apiFabricNetworks), - resp: &resp, - } - if _, err := c.sendRequest(req); err != nil { - return nil, errors.Newf(err, "failed to get list of networks on fabric %d", vlanID) - } - return resp, nil -} - -// GetFabricNetwork gets a single network by VLAN and Network IDs -// See API docs: https://apidocs.joyent.com/cloudapi/#GetFabricNetwork -func (c *Client) GetFabricNetwork(vlanID int16, networkID string) (*FabricNetwork, error) { - var resp FabricNetwork - req := request{ - method: client.GET, - url: makeURL(apiFabricVLANs, strconv.Itoa(int(vlanID)), apiFabricNetworks, networkID), - resp: &resp, - } - if _, err := c.sendRequest(req); err != nil { - return nil, errors.Newf(err, "failed to get fabric network %s on vlan %d", networkID, vlanID) - } - return &resp, nil -} - -// CreateFabricNetwork creates a new fabric network -// See API docs: https://apidocs.joyent.com/cloudapi/#CreateFabricNetwork -func (c *Client) CreateFabricNetwork(vlanID int16, opts CreateFabricNetworkOpts) (*FabricNetwork, error) { - var resp FabricNetwork - req := request{ - method: client.POST, - url: makeURL(apiFabricVLANs, strconv.Itoa(int(vlanID)), apiFabricNetworks), - reqValue: opts, - resp: &resp, - expectedStatus: http.StatusCreated, - } - if _, err := c.sendRequest(req); err != nil { - return nil, errors.Newf(err, "failed to create fabric network %s on vlan %d", opts.Name, vlanID) - } - return &resp, nil -} - -// DeleteFabricNetwork deletes an existing fabric network -// See API docs: https://apidocs.joyent.com/cloudapi/#DeleteFabricNetwork -func (c *Client) DeleteFabricNetwork(vlanID int16, networkID string) error { - req := request{ - method: client.DELETE, - url: makeURL(apiFabricVLANs, strconv.Itoa(int(vlanID)), apiFabricNetworks, networkID), - expectedStatus: http.StatusNoContent, - } - if _, err := c.sendRequest(req); err != nil { - return errors.Newf(err, "failed to delete fabric network %s on vlan %d", networkID, vlanID) - } - return nil -} diff --git a/vendor/github.com/joyent/gosdc/cloudapi/firewalls.go b/vendor/github.com/joyent/gosdc/cloudapi/firewalls.go deleted file mode 100644 index a7763a668..000000000 --- a/vendor/github.com/joyent/gosdc/cloudapi/firewalls.go +++ /dev/null @@ -1,144 +0,0 @@ -package cloudapi - -import ( - "net/http" - - "github.com/joyent/gocommon/client" - "github.com/joyent/gocommon/errors" -) - -// FirewallRule represent a firewall rule that can be specifed for a machine. -type FirewallRule struct { - Id string // Unique identifier for the rule - Enabled bool // Whether the rule is enabled or not - Rule string // Firewall rule in the form 'FROM TO ' -} - -// CreateFwRuleOpts represent the option that can be specified -// when creating a new firewall rule. -type CreateFwRuleOpts struct { - Enabled bool `json:"enabled"` // Whether to enable the rule or not - Rule string `json:"rule"` // Firewall rule in the form 'FROM TO ' -} - -// ListFirewallRules lists all the firewall rules on record for a specified account. -// See API docs: http://apidocs.joyent.com/cloudapi/#ListFirewallRules -func (c *Client) ListFirewallRules() ([]FirewallRule, error) { - var resp []FirewallRule - req := request{ - method: client.GET, - url: apiFirewallRules, - resp: &resp, - } - if _, err := c.sendRequest(req); err != nil { - return nil, errors.Newf(err, "failed to get list of firewall rules") - } - return resp, nil -} - -// GetFirewallRule returns the specified firewall rule. -// See API docs: http://apidocs.joyent.com/cloudapi/#GetFirewallRule -func (c *Client) GetFirewallRule(fwRuleID string) (*FirewallRule, error) { - var resp FirewallRule - req := request{ - method: client.GET, - url: makeURL(apiFirewallRules, fwRuleID), - resp: &resp, - } - if _, err := c.sendRequest(req); err != nil { - return nil, errors.Newf(err, "failed to get firewall rule with id %s", fwRuleID) - } - return &resp, nil -} - -// CreateFirewallRule creates the firewall rule with the specified options. -// See API docs: http://apidocs.joyent.com/cloudapi/#CreateFirewallRule -func (c *Client) CreateFirewallRule(opts CreateFwRuleOpts) (*FirewallRule, error) { - var resp FirewallRule - req := request{ - method: client.POST, - url: apiFirewallRules, - reqValue: opts, - resp: &resp, - expectedStatus: http.StatusCreated, - } - if _, err := c.sendRequest(req); err != nil { - return nil, errors.Newf(err, "failed to create firewall rule: %s", opts.Rule) - } - return &resp, nil -} - -// UpdateFirewallRule updates the specified firewall rule. -// See API docs: http://apidocs.joyent.com/cloudapi/#UpdateFirewallRule -func (c *Client) UpdateFirewallRule(fwRuleID string, opts CreateFwRuleOpts) (*FirewallRule, error) { - var resp FirewallRule - req := request{ - method: client.POST, - url: makeURL(apiFirewallRules, fwRuleID), - reqValue: opts, - resp: &resp, - } - if _, err := c.sendRequest(req); err != nil { - return nil, errors.Newf(err, "failed to update firewall rule with id %s to %s", fwRuleID, opts.Rule) - } - return &resp, nil -} - -// EnableFirewallRule enables the given firewall rule record if it is disabled. -// See API docs: http://apidocs.joyent.com/cloudapi/#EnableFirewallRule -func (c *Client) EnableFirewallRule(fwRuleID string) (*FirewallRule, error) { - var resp FirewallRule - req := request{ - method: client.POST, - url: makeURL(apiFirewallRules, fwRuleID, apiFirewallRulesEnable), - resp: &resp, - } - if _, err := c.sendRequest(req); err != nil { - return nil, errors.Newf(err, "failed to enable firewall rule with id %s", fwRuleID) - } - return &resp, nil -} - -// DisableFirewallRule disables the given firewall rule record if it is enabled. -// See API docs: http://apidocs.joyent.com/cloudapi/#DisableFirewallRule -func (c *Client) DisableFirewallRule(fwRuleID string) (*FirewallRule, error) { - var resp FirewallRule - req := request{ - method: client.POST, - url: makeURL(apiFirewallRules, fwRuleID, apiFirewallRulesDisable), - resp: &resp, - } - if _, err := c.sendRequest(req); err != nil { - return nil, errors.Newf(err, "failed to disable firewall rule with id %s", fwRuleID) - } - return &resp, nil -} - -// DeleteFirewallRule removes the given firewall rule record from all the required account machines. -// See API docs: http://apidocs.joyent.com/cloudapi/#DeleteFirewallRule -func (c *Client) DeleteFirewallRule(fwRuleID string) error { - req := request{ - method: client.DELETE, - url: makeURL(apiFirewallRules, fwRuleID), - expectedStatus: http.StatusNoContent, - } - if _, err := c.sendRequest(req); err != nil { - return errors.Newf(err, "failed to delete firewall rule with id %s", fwRuleID) - } - return nil -} - -// ListFirewallRuleMachines return the list of machines affected by the given firewall rule. -// See API docs: http://apidocs.joyent.com/cloudapi/#ListFirewallRuleMachines -func (c *Client) ListFirewallRuleMachines(fwRuleID string) ([]Machine, error) { - var resp []Machine - req := request{ - method: client.GET, - url: makeURL(apiFirewallRules, fwRuleID, apiMachines), - resp: &resp, - } - if _, err := c.sendRequest(req); err != nil { - return nil, errors.Newf(err, "failed to get list of machines affected by firewall rule wit id %s", fwRuleID) - } - return resp, nil -} diff --git a/vendor/github.com/joyent/gosdc/cloudapi/images.go b/vendor/github.com/joyent/gosdc/cloudapi/images.go deleted file mode 100644 index c7f9a2fe3..000000000 --- a/vendor/github.com/joyent/gosdc/cloudapi/images.go +++ /dev/null @@ -1,133 +0,0 @@ -package cloudapi - -import ( - "fmt" - "net/http" - - "github.com/joyent/gocommon/client" - "github.com/joyent/gocommon/errors" -) - -// Image represent the software packages that will be available on newly provisioned machines -type Image struct { - Id string // Unique identifier for the image - Name string // Image friendly name - OS string // Underlying operating system - Version string // Image version - Type string // Image type, one of 'smartmachine' or 'virtualmachine' - Description string // Image description - Requirements map[string]interface{} // Minimum requirements for provisioning a machine with this image, e.g. 'password' indicates that a password must be provided - Homepage string // URL for a web page including detailed information for this image (new in API version 7.0) - PublishedAt string `json:"published_at"` // Time this image has been made publicly available (new in API version 7.0) - Public bool // Indicates if the image is publicly available (new in API version 7.1) - State string // Current image state. One of 'active', 'unactivated', 'disabled', 'creating', 'failed' (new in API version 7.1) - Tags map[string]string // A map of key/value pairs that allows clients to categorize images by any given criteria (new in API version 7.1) - EULA string // URL of the End User License Agreement (EULA) for the image (new in API version 7.1) - ACL []string // An array of account UUIDs given access to a private image. The field is only relevant to private images (new in API version 7.1) - Owner string // The UUID of the user owning the image -} - -// ExportImageOpts represent the option that can be specified -// when exporting an image. -type ExportImageOpts struct { - MantaPath string `json:"manta_path"` // The Manta path prefix to use when exporting the image -} - -// MantaLocation represent the properties that allow a user -// to retrieve the image file and manifest from Manta -type MantaLocation struct { - MantaURL string `json:"manta_url"` // Manta datacenter URL - ImagePath string `json:"image_path"` // Path to the image - ManifestPath string `json:"manifest_path"` // Path to the image manifest -} - -// CreateImageFromMachineOpts represent the option that can be specified -// when creating a new image from an existing machine. -type CreateImageFromMachineOpts struct { - Machine string `json:"machine"` // The machine UUID from which the image is to be created - Name string `json:"name"` // Image name - Version string `json:"version"` // Image version - Description string `json:"description,omitempty"` // Image description - Homepage string `json:"homepage,omitempty"` // URL for a web page including detailed information for this image - EULA string `json:"eula,omitempty"` // URL of the End User License Agreement (EULA) for the image - ACL []string `json:"acl,omitempty"` // An array of account UUIDs given access to a private image. The field is only relevant to private images - Tags map[string]string `json:"tags,omitempty"` // A map of key/value pairs that allows clients to categorize images by any given criteria -} - -// ListImages provides a list of images available in the datacenter. -// See API docs: http://apidocs.joyent.com/cloudapi/#ListImages -func (c *Client) ListImages(filter *Filter) ([]Image, error) { - var resp []Image - req := request{ - method: client.GET, - url: apiImages, - filter: filter, - resp: &resp, - } - if _, err := c.sendRequest(req); err != nil { - return nil, errors.Newf(err, "failed to get list of images") - } - return resp, nil -} - -// GetImage returns the image specified by imageId. -// See API docs: http://apidocs.joyent.com/cloudapi/#GetImage -func (c *Client) GetImage(imageID string) (*Image, error) { - var resp Image - req := request{ - method: client.GET, - url: makeURL(apiImages, imageID), - resp: &resp, - } - if _, err := c.sendRequest(req); err != nil { - return nil, errors.Newf(err, "failed to get image with id: %s", imageID) - } - return &resp, nil -} - -// DeleteImage (Beta) Delete the image specified by imageId. Must be image owner to do so. -// See API docs: http://apidocs.joyent.com/cloudapi/#DeleteImage -func (c *Client) DeleteImage(imageID string) error { - req := request{ - method: client.DELETE, - url: makeURL(apiImages, imageID), - expectedStatus: http.StatusNoContent, - } - if _, err := c.sendRequest(req); err != nil { - return errors.Newf(err, "failed to delete image with id: %s", imageID) - } - return nil -} - -// ExportImage (Beta) Exports an image to the specified Manta path. -// See API docs: http://apidocs.joyent.com/cloudapi/#ListImages -func (c *Client) ExportImage(imageID string, opts ExportImageOpts) (*MantaLocation, error) { - var resp MantaLocation - req := request{ - method: client.POST, - url: fmt.Sprintf("%s/%s?action=%s", apiImages, imageID, actionExport), - reqValue: opts, - resp: &resp, - } - if _, err := c.sendRequest(req); err != nil { - return nil, errors.Newf(err, "failed to export image %s to %s", imageID, opts.MantaPath) - } - return &resp, nil -} - -// CreateImageFromMachine (Beta) Create a new custom image from a machine. -// See API docs: http://apidocs.joyent.com/cloudapi/#ListImages -func (c *Client) CreateImageFromMachine(opts CreateImageFromMachineOpts) (*Image, error) { - var resp Image - req := request{ - method: client.POST, - url: apiImages, - reqValue: opts, - resp: &resp, - expectedStatus: http.StatusCreated, - } - if _, err := c.sendRequest(req); err != nil { - return nil, errors.Newf(err, "failed to create image from machine %s", opts.Machine) - } - return &resp, nil -} diff --git a/vendor/github.com/joyent/gosdc/cloudapi/instrumentations.go b/vendor/github.com/joyent/gosdc/cloudapi/instrumentations.go deleted file mode 100644 index 1dcd32777..000000000 --- a/vendor/github.com/joyent/gosdc/cloudapi/instrumentations.go +++ /dev/null @@ -1,216 +0,0 @@ -package cloudapi - -import ( - "net/http" - - "github.com/joyent/gocommon/client" - "github.com/joyent/gocommon/errors" -) - -// Analytics represents the available analytics -type Analytics struct { - Modules map[string]interface{} // Namespace to organize metrics - Fields map[string]interface{} // Fields represent metadata by which data points can be filtered or decomposed - Types map[string]interface{} // Types are used with both metrics and fields for two purposes: to hint to clients at how to best label values, and to distinguish between numeric and discrete quantities. - Metrics map[string]interface{} // Metrics describe quantities which can be measured by the system - Transformations map[string]interface{} // Transformations are post-processing functions that can be applied to data when it's retrieved. -} - -// Instrumentation specify which metric to collect, how frequently to aggregate data (e.g., every second, every hour, etc.) -// how much data to keep (e.g., 10 minutes' worth, 6 months' worth, etc.) and other configuration options -type Instrumentation struct { - Module string `json:"module"` - Stat string `json:"stat"` - Predicate string `json:"predicate"` - Decomposition []string `json:"decomposition"` - ValueDimension int `json:"value-dimenstion"` - ValueArity string `json:"value-arity"` - RetentionTime int `json:"retention-time"` - Granularity int `json:"granularitiy"` - IdleMax int `json:"idle-max"` - Transformations []string `json:"transformations"` - PersistData bool `json:"persist-data"` - Crtime int `json:"crtime"` - ValueScope string `json:"value-scope"` - Id string `json:"id"` - Uris []Uri `json:"uris"` -} - -// Uri represents a Universal Resource Identifier -type Uri struct { - Uri string // Resource identifier - Name string // URI name -} - -// InstrumentationValue represents the data associated to an instrumentation for a point in time -type InstrumentationValue struct { - Value interface{} - Transformations map[string]interface{} - StartTime int - Duration int -} - -// HeatmapOpts represent the option that can be specified -// when retrieving an instrumentation.'s heatmap -type HeatmapOpts struct { - Height int `json:"height"` // Height of the image in pixels - Width int `json:"width"` // Width of the image in pixels - Ymin int `json:"ymin"` // Y-Axis value for the bottom of the image (default: 0) - Ymax int `json:"ymax"` // Y-Axis value for the top of the image (default: auto) - Nbuckets int `json:"nbuckets"` // Number of buckets in the vertical dimension - Selected []string `json:"selected"` // Array of field values to highlight, isolate or exclude - Isolate bool `json:"isolate"` // If true, only draw selected values - Exclude bool `json:"exclude"` // If true, don't draw selected values at all - Hues []string `json:"hues"` // Array of colors for highlighting selected field values - DecomposeAll bool `json:"decompose_all"` // Highlight all field values - X int `json:"x"` - Y int `json:"y"` -} - -// Heatmap represents an instrumentation's heatmap -type Heatmap struct { - BucketTime int `json:"bucket_time"` // Time corresponding to the bucket (Unix seconds) - BucketYmin int `json:"bucket_ymin"` // Minimum y-axis value for the bucket - BucketYmax int `json:"bucket_ymax"` // Maximum y-axis value for the bucket - Present map[string]interface{} `json:"present"` // If the instrumentation defines a discrete decomposition, this property's value is an object whose keys are values of that field and whose values are the number of data points in that bucket for that key - Total int `json:"total"` // The total number of data points in the bucket -} - -// CreateInstrumentationOpts represent the option that can be specified -// when creating a new instrumentation. -type CreateInstrumentationOpts struct { - Clone int `json:"clone"` // An existing instrumentation ID to be cloned - Module string `json:"module"` // Analytics module - Stat string `json:"stat"` // Analytics stat - Predicate string `json:"predicate"` // Instrumentation predicate, must be JSON string - Decomposition string `json:"decomposition"` - Granularity int `json:"granularity"` // Number of seconds between data points (default is 1) - RetentionTime int `json:"retention-time"` // How long to keep this instrumentation data for - PersistData bool `json:"persist-data"` // Whether or not to store this for historical analysis - IdleMax int `json:"idle-max"` // Number of seconds after which if the instrumentation or its data has not been accessed via the API the service may delete the instrumentation and its data -} - -// DescribeAnalytics retrieves the "schema" for instrumentations that can be created. -// See API docs: http://apidocs.joyent.com/cloudapi/#DescribeAnalytics -func (c *Client) DescribeAnalytics() (*Analytics, error) { - var resp Analytics - req := request{ - method: client.GET, - url: apiAnalytics, - resp: &resp, - } - if _, err := c.sendRequest(req); err != nil { - return nil, errors.Newf(err, "failed to get analytics") - } - return &resp, nil -} - -// ListInstrumentations retrieves all currently created instrumentations. -// See API docs: http://apidocs.joyent.com/cloudapi/#ListInstrumentations -func (c *Client) ListInstrumentations() ([]Instrumentation, error) { - var resp []Instrumentation - req := request{ - method: client.GET, - url: makeURL(apiAnalytics, apiInstrumentations), - resp: &resp, - } - if _, err := c.sendRequest(req); err != nil { - return nil, errors.Newf(err, "failed to get instrumentations") - } - return resp, nil -} - -// GetInstrumentation retrieves the configuration for the specified instrumentation. -// See API docs: http://apidocs.joyent.com/cloudapi/#GetInstrumentation -func (c *Client) GetInstrumentation(instrumentationID string) (*Instrumentation, error) { - var resp Instrumentation - req := request{ - method: client.GET, - url: makeURL(apiAnalytics, apiInstrumentations, instrumentationID), - resp: &resp, - } - if _, err := c.sendRequest(req); err != nil { - return nil, errors.Newf(err, "failed to get instrumentation with id %s", instrumentationID) - } - return &resp, nil -} - -// GetInstrumentationValue retrieves the data associated to an instrumentation -// for a point in time. -// See API docs: http://apidocs.joyent.com/cloudapi/#GetInstrumentationValue -func (c *Client) GetInstrumentationValue(instrumentationID string) (*InstrumentationValue, error) { - var resp InstrumentationValue - req := request{ - method: client.GET, - url: makeURL(apiAnalytics, apiInstrumentations, instrumentationID, apiInstrumentationsValue, apiInstrumentationsRaw), - resp: &resp, - } - if _, err := c.sendRequest(req); err != nil { - return nil, errors.Newf(err, "failed to get value for instrumentation with id %s", instrumentationID) - } - return &resp, nil -} - -// GetInstrumentationHeatmap retrieves the specified instrumentation's heatmap. -// See API docs: http://apidocs.joyent.com/cloudapi/#GetInstrumentationHeatmap -func (c *Client) GetInstrumentationHeatmap(instrumentationID string) (*Heatmap, error) { - var resp Heatmap - req := request{ - method: client.GET, - url: makeURL(apiAnalytics, apiInstrumentations, instrumentationID, apiInstrumentationsValue, apiInstrumentationsHeatmap, apiInstrumentationsImage), - resp: &resp, - } - if _, err := c.sendRequest(req); err != nil { - return nil, errors.Newf(err, "failed to get heatmap image for instrumentation with id %s", instrumentationID) - } - return &resp, nil -} - -// GetInstrumentationHeatmapDetails allows you to retrieve the bucket details -// for a heatmap. -// See API docs: http://apidocs.joyent.com/cloudapi/#GetInstrumentationHeatmapDetails -func (c *Client) GetInstrumentationHeatmapDetails(instrumentationID string) (*Heatmap, error) { - var resp Heatmap - req := request{ - method: client.GET, - url: makeURL(apiAnalytics, apiInstrumentations, instrumentationID, apiInstrumentationsValue, apiInstrumentationsHeatmap, apiInstrumentationsDetails), - resp: &resp, - } - if _, err := c.sendRequest(req); err != nil { - return nil, errors.Newf(err, "failed to get heatmap details for instrumentation with id %s", instrumentationID) - } - return &resp, nil -} - -// CreateInstrumentation Creates an instrumentation. You can clone an existing -// instrumentation by passing in the parameter clone, which should be a numeric id -// of an existing instrumentation. -// See API docs: http://apidocs.joyent.com/cloudapi/#CreateInstrumentation -func (c *Client) CreateInstrumentation(opts CreateInstrumentationOpts) (*Instrumentation, error) { - var resp Instrumentation - req := request{ - method: client.POST, - url: makeURL(apiAnalytics, apiInstrumentations), - reqValue: opts, - resp: &resp, - expectedStatus: http.StatusCreated, - } - if _, err := c.sendRequest(req); err != nil { - return nil, errors.Newf(err, "failed to create instrumentation") - } - return &resp, nil -} - -// DeleteInstrumentation destroys an instrumentation. -// See API docs: http://apidocs.joyent.com/cloudapi/#DeleteInstrumentation -func (c *Client) DeleteInstrumentation(instrumentationID string) error { - req := request{ - method: client.DELETE, - url: makeURL(apiAnalytics, apiInstrumentations, instrumentationID), - expectedStatus: http.StatusNoContent, - } - if _, err := c.sendRequest(req); err != nil { - return errors.Newf(err, "failed to delete instrumentation with id %s", instrumentationID) - } - return nil -} diff --git a/vendor/github.com/joyent/gosdc/cloudapi/keys.go b/vendor/github.com/joyent/gosdc/cloudapi/keys.go deleted file mode 100644 index fd9fd91b3..000000000 --- a/vendor/github.com/joyent/gosdc/cloudapi/keys.go +++ /dev/null @@ -1,90 +0,0 @@ -package cloudapi - -import ( - "net/http" - - "github.com/joyent/gocommon/client" - "github.com/joyent/gocommon/errors" -) - -// Key represent a public key -type Key struct { - Name string // Name for the key - Fingerprint string // Key Fingerprint - Key string // OpenSSH formatted public key -} - -/*func (k Key) Equals(other Key) bool { - if k.Name == other.Name && k.Fingerprint == other.Fingerprint && k.Key == other.Key { - return true - } - return false -}*/ - -// CreateKeyOpts represent the option that can be specified -// when creating a new key. -type CreateKeyOpts struct { - Name string `json:"name"` // Name for the key, optional - Key string `json:"key"` // OpenSSH formatted public key -} - -// ListKeys returns a list of public keys registered with a specific account. -// See API docs: http://apidocs.joyent.com/cloudapi/#ListKeys -func (c *Client) ListKeys() ([]Key, error) { - var resp []Key - req := request{ - method: client.GET, - url: apiKeys, - resp: &resp, - } - if _, err := c.sendRequest(req); err != nil { - return nil, errors.Newf(err, "failed to get list of keys") - } - return resp, nil -} - -// GetKey returns the key identified by keyName. -// See API docs: http://apidocs.joyent.com/cloudapi/#GetKey -func (c *Client) GetKey(keyName string) (*Key, error) { - var resp Key - req := request{ - method: client.GET, - url: makeURL(apiKeys, keyName), - resp: &resp, - } - if _, err := c.sendRequest(req); err != nil { - return nil, errors.Newf(err, "failed to get key with name: %s", keyName) - } - return &resp, nil -} - -// CreateKey creates a new key with the specified options. -// See API docs: http://apidocs.joyent.com/cloudapi/#CreateKey -func (c *Client) CreateKey(opts CreateKeyOpts) (*Key, error) { - var resp Key - req := request{ - method: client.POST, - url: apiKeys, - reqValue: opts, - resp: &resp, - expectedStatus: http.StatusCreated, - } - if _, err := c.sendRequest(req); err != nil { - return nil, errors.Newf(err, "failed to create key with name: %s", opts.Name) - } - return &resp, nil -} - -// DeleteKey deletes the key identified by keyName. -// See API docs: http://apidocs.joyent.com/cloudapi/#DeleteKey -func (c *Client) DeleteKey(keyName string) error { - req := request{ - method: client.DELETE, - url: makeURL(apiKeys, keyName), - expectedStatus: http.StatusNoContent, - } - if _, err := c.sendRequest(req); err != nil { - return errors.Newf(err, "failed to delete key with name: %s", keyName) - } - return nil -} diff --git a/vendor/github.com/joyent/gosdc/cloudapi/machine_firewall.go b/vendor/github.com/joyent/gosdc/cloudapi/machine_firewall.go deleted file mode 100644 index 60471e72e..000000000 --- a/vendor/github.com/joyent/gosdc/cloudapi/machine_firewall.go +++ /dev/null @@ -1,52 +0,0 @@ -package cloudapi - -import ( - "fmt" - "net/http" - - "github.com/joyent/gocommon/client" - "github.com/joyent/gocommon/errors" -) - -// ListMachineFirewallRules lists all the firewall rules for the specified machine. -// See API docs: http://apidocs.joyent.com/cloudapi/#ListMachineFirewallRules -func (c *Client) ListMachineFirewallRules(machineID string) ([]FirewallRule, error) { - var resp []FirewallRule - req := request{ - method: client.GET, - url: makeURL(apiMachines, machineID, apiFirewallRules), - resp: &resp, - } - if _, err := c.sendRequest(req); err != nil { - return nil, errors.Newf(err, "failed to get list of firewall rules for machine with id %s", machineID) - } - return resp, nil -} - -// EnableFirewallMachine enables the firewall for the specified machine. -// See API docs: http://apidocs.joyent.com/cloudapi/#EnableMachineFirewall -func (c *Client) EnableFirewallMachine(machineID string) error { - req := request{ - method: client.POST, - url: fmt.Sprintf("%s/%s?action=%s", apiMachines, machineID, actionEnableFw), - expectedStatus: http.StatusAccepted, - } - if _, err := c.sendRequest(req); err != nil { - return errors.Newf(err, "failed to enable firewall on machine with id: %s", machineID) - } - return nil -} - -// DisableFirewallMachine disables the firewall for the specified machine. -// See API docs: http://apidocs.joyent.com/cloudapi/#DisableMachineFirewall -func (c *Client) DisableFirewallMachine(machineID string) error { - req := request{ - method: client.POST, - url: fmt.Sprintf("%s/%s?action=%s", apiMachines, machineID, actionDisableFw), - expectedStatus: http.StatusAccepted, - } - if _, err := c.sendRequest(req); err != nil { - return errors.Newf(err, "failed to disable firewall on machine with id: %s", machineID) - } - return nil -} diff --git a/vendor/github.com/joyent/gosdc/cloudapi/machine_metadata.go b/vendor/github.com/joyent/gosdc/cloudapi/machine_metadata.go deleted file mode 100644 index ca8d83ca9..000000000 --- a/vendor/github.com/joyent/gosdc/cloudapi/machine_metadata.go +++ /dev/null @@ -1,70 +0,0 @@ -package cloudapi - -import ( - "net/http" - - "github.com/joyent/gocommon/client" - "github.com/joyent/gocommon/errors" -) - -// UpdateMachineMetadata updates the metadata for a given machine. -// Any metadata keys passed in here are created if they do not exist, and -// overwritten if they do. -// See API docs: http://apidocs.joyent.com/cloudapi/#UpdateMachineMetadata -func (c *Client) UpdateMachineMetadata(machineID string, metadata map[string]string) (map[string]interface{}, error) { - var resp map[string]interface{} - req := request{ - method: client.POST, - url: makeURL(apiMachines, machineID, apiMetadata), - reqValue: metadata, - resp: &resp, - } - if _, err := c.sendRequest(req); err != nil { - return nil, errors.Newf(err, "failed to update metadata for machine with id %s", machineID) - } - return resp, nil -} - -// GetMachineMetadata returns the complete set of metadata associated with the -// specified machine. -// See API docs: http://apidocs.joyent.com/cloudapi/#GetMachineMetadata -func (c *Client) GetMachineMetadata(machineID string) (map[string]interface{}, error) { - var resp map[string]interface{} - req := request{ - method: client.GET, - url: makeURL(apiMachines, machineID, apiMetadata), - resp: &resp, - } - if _, err := c.sendRequest(req); err != nil { - return nil, errors.Newf(err, "failed to get list of metadata for machine with id %s", machineID) - } - return resp, nil -} - -// DeleteMachineMetadata deletes a single metadata key from the specified machine. -// See API docs: http://apidocs.joyent.com/cloudapi/#DeleteMachineMetadata -func (c *Client) DeleteMachineMetadata(machineID, metadataKey string) error { - req := request{ - method: client.DELETE, - url: makeURL(apiMachines, machineID, apiMetadata, metadataKey), - expectedStatus: http.StatusNoContent, - } - if _, err := c.sendRequest(req); err != nil { - return errors.Newf(err, "failed to delete metadata with key %s for machine with id %s", metadataKey, machineID) - } - return nil -} - -// DeleteAllMachineMetadata deletes all metadata keys from the specified machine. -// See API docs: http://apidocs.joyent.com/cloudapi/#DeleteAllMachineMetadata -func (c *Client) DeleteAllMachineMetadata(machineID string) error { - req := request{ - method: client.DELETE, - url: makeURL(apiMachines, machineID, apiMetadata), - expectedStatus: http.StatusNoContent, - } - if _, err := c.sendRequest(req); err != nil { - return errors.Newf(err, "failed to delete metadata for machine with id %s", machineID) - } - return nil -} diff --git a/vendor/github.com/joyent/gosdc/cloudapi/machine_nics.go b/vendor/github.com/joyent/gosdc/cloudapi/machine_nics.go deleted file mode 100644 index 4a137e4d9..000000000 --- a/vendor/github.com/joyent/gosdc/cloudapi/machine_nics.go +++ /dev/null @@ -1,95 +0,0 @@ -package cloudapi - -import ( - "net/http" - - "github.com/joyent/gocommon/client" - "github.com/joyent/gocommon/errors" -) - -// NICState represents the state of a NIC -type NICState string - -var ( - NICStateProvisioning NICState = "provisioning" - NICStateRunning NICState = "running" - NICStateStopped NICState = "stopped" -) - -// NIC represents a NIC on a machine -type NIC struct { - IP string `json:"ip"` // NIC's IPv4 Address - MAC string `json:"mac"` // NIC's MAC address - Primary bool `json:"primary"` // Whether this is the machine's primary NIC - Netmask string `json:"netmask"` // IPv4 netmask - Gateway string `json:"gateway"` // IPv4 gateway - State NICState `json:"state"` // Describes the state of the NIC (e.g. provisioning, running, or stopped) - Network string `json:"network"` // Network ID this NIC is attached to -} - -type addNICOptions struct { - Network string `json:"network"` // UUID of network this NIC should attach to -} - -// ListNICs lists all the NICs on a machine belonging to a given account -// See API docs: https://apidocs.joyent.com/cloudapi/#ListNics -func (c *Client) ListNICs(machineID string) ([]NIC, error) { - var resp []NIC - req := request{ - method: client.GET, - url: makeURL(apiMachines, machineID, apiNICs), - resp: &resp, - } - if _, err := c.sendRequest(req); err != nil { - return nil, errors.Newf(err, "failed to list NICs") - } - return resp, nil -} - -// GetNIC gets a specific NIC on a machine belonging to a given account -// See API docs: https://apidocs.joyent.com/cloudapi/#GetNic -func (c *Client) GetNIC(machineID, MAC string) (*NIC, error) { - resp := new(NIC) - req := request{ - method: client.GET, - url: makeURL(apiMachines, machineID, apiNICs, MAC), - resp: resp, - } - if _, err := c.sendRequest(req); err != nil { - return nil, errors.Newf(err, "failed to get NIC with MAC: %s", MAC) - } - return resp, nil -} - -// AddNIC creates a new NIC on a machine belonging to a given account. -// *WARNING*: this causes the machine to reboot while adding the NIC. -// See API docs: https://apidocs.joyent.com/cloudapi/#AddNic -func (c *Client) AddNIC(machineID, networkID string) (*NIC, error) { - resp := new(NIC) - req := request{ - method: client.POST, - url: makeURL(apiMachines, machineID, apiNICs), - reqValue: addNICOptions{networkID}, - resp: resp, - expectedStatus: http.StatusCreated, - } - if _, err := c.sendRequest(req); err != nil { - return nil, errors.Newf(err, "failed to add NIC to machine %s on network: %s", machineID, networkID) - } - return resp, nil -} - -// RemoveNIC removes a NIC on a machine belonging to a given account. -// *WARNING*: this causes the machine to reboot while removing the NIC. -// See API docs: https://apidocs.joyent.com/cloudapi/#RemoveNic -func (c *Client) RemoveNIC(machineID, MAC string) error { - req := request{ - method: client.DELETE, - url: makeURL(apiMachines, machineID, apiNICs, MAC), - expectedStatus: http.StatusNoContent, - } - if _, err := c.sendRequest(req); err != nil { - return errors.Newf(err, "failed to remove NIC: %s", MAC) - } - return nil -} diff --git a/vendor/github.com/joyent/gosdc/cloudapi/machine_snapshots.go b/vendor/github.com/joyent/gosdc/cloudapi/machine_snapshots.go deleted file mode 100644 index 0497a0fe5..000000000 --- a/vendor/github.com/joyent/gosdc/cloudapi/machine_snapshots.go +++ /dev/null @@ -1,96 +0,0 @@ -package cloudapi - -import ( - "net/http" - - "github.com/joyent/gocommon/client" - "github.com/joyent/gocommon/errors" -) - -// Snapshot represent a point in time state of a machine. -type Snapshot struct { - Name string // Snapshot name - State string // Snapshot state -} - -// SnapshotOpts represent the option that can be specified -// when creating a new machine snapshot. -type SnapshotOpts struct { - Name string `json:"name"` // Snapshot name -} - -// CreateMachineSnapshot creates a new snapshot for the machine with the options specified. -// See API docs: http://apidocs.joyent.com/cloudapi/#CreateMachineSnapshot -func (c *Client) CreateMachineSnapshot(machineID string, opts SnapshotOpts) (*Snapshot, error) { - var resp Snapshot - req := request{ - method: client.POST, - url: makeURL(apiMachines, machineID, apiSnapshots), - reqValue: opts, - resp: &resp, - expectedStatus: http.StatusCreated, - } - if _, err := c.sendRequest(req); err != nil { - return nil, errors.Newf(err, "failed to create snapshot %s from machine with id %s", opts.Name, machineID) - } - return &resp, nil -} - -// StartMachineFromSnapshot starts the machine from the specified snapshot. -// Machine must be in 'stopped' state. -// See API docs: http://apidocs.joyent.com/cloudapi/#StartMachineFromSnapshot -func (c *Client) StartMachineFromSnapshot(machineID, snapshotName string) error { - req := request{ - method: client.POST, - url: makeURL(apiMachines, machineID, apiSnapshots, snapshotName), - expectedStatus: http.StatusAccepted, - } - if _, err := c.sendRequest(req); err != nil { - return errors.Newf(err, "failed to start machine with id %s from snapshot %s", machineID, snapshotName) - } - return nil -} - -// ListMachineSnapshots lists all snapshots for the specified machine. -// See API docs: http://apidocs.joyent.com/cloudapi/#ListMachineSnapshots -func (c *Client) ListMachineSnapshots(machineID string) ([]Snapshot, error) { - var resp []Snapshot - req := request{ - method: client.GET, - url: makeURL(apiMachines, machineID, apiSnapshots), - resp: &resp, - } - if _, err := c.sendRequest(req); err != nil { - return nil, errors.Newf(err, "failed to get list of snapshots for machine with id %s", machineID) - } - return resp, nil -} - -// GetMachineSnapshot returns the state of the specified snapshot. -// See API docs: http://apidocs.joyent.com/cloudapi/#GetMachineSnapshot -func (c *Client) GetMachineSnapshot(machineID, snapshotName string) (*Snapshot, error) { - var resp Snapshot - req := request{ - method: client.GET, - url: makeURL(apiMachines, machineID, apiSnapshots, snapshotName), - resp: &resp, - } - if _, err := c.sendRequest(req); err != nil { - return nil, errors.Newf(err, "failed to get snapshot %s for machine with id %s", snapshotName, machineID) - } - return &resp, nil -} - -// DeleteMachineSnapshot deletes the specified snapshot. -// See API docs: http://apidocs.joyent.com/cloudapi/#DeleteMachineSnapshot -func (c *Client) DeleteMachineSnapshot(machineID, snapshotName string) error { - req := request{ - method: client.DELETE, - url: makeURL(apiMachines, machineID, apiSnapshots, snapshotName), - expectedStatus: http.StatusNoContent, - } - if _, err := c.sendRequest(req); err != nil { - return errors.Newf(err, "failed to delete snapshot %s for machine with id %s", snapshotName, machineID) - } - return nil -} diff --git a/vendor/github.com/joyent/gosdc/cloudapi/machine_tags.go b/vendor/github.com/joyent/gosdc/cloudapi/machine_tags.go deleted file mode 100644 index 9a5242bdb..000000000 --- a/vendor/github.com/joyent/gosdc/cloudapi/machine_tags.go +++ /dev/null @@ -1,103 +0,0 @@ -package cloudapi - -import ( - "net/http" - - "github.com/joyent/gocommon/client" - "github.com/joyent/gocommon/errors" -) - -// AddMachineTags adds additional tags to the specified machine. -// This API lets you append new tags, not overwrite existing tags. -// See API docs: http://apidocs.joyent.com/cloudapi/#AddMachineTags -func (c *Client) AddMachineTags(machineID string, tags map[string]string) (map[string]string, error) { - var resp map[string]string - req := request{ - method: client.POST, - url: makeURL(apiMachines, machineID, apiTags), - reqValue: tags, - resp: &resp, - } - if _, err := c.sendRequest(req); err != nil { - return nil, errors.Newf(err, "failed to add tags for machine with id %s", machineID) - } - return resp, nil -} - -// ReplaceMachineTags replaces existing tags for the specified machine. -// This API lets you overwrite existing tags, not append to existing tags. -// See API docs: http://apidocs.joyent.com/cloudapi/#ReplaceMachineTags -func (c *Client) ReplaceMachineTags(machineID string, tags map[string]string) (map[string]string, error) { - var resp map[string]string - req := request{ - method: client.PUT, - url: makeURL(apiMachines, machineID, apiTags), - reqValue: tags, - resp: &resp, - } - if _, err := c.sendRequest(req); err != nil { - return nil, errors.Newf(err, "failed to replace tags for machine with id %s", machineID) - } - return resp, nil -} - -// ListMachineTags returns the complete set of tags associated with the specified machine. -// See API docs: http://apidocs.joyent.com/cloudapi/#ListMachineTags -func (c *Client) ListMachineTags(machineID string) (map[string]string, error) { - var resp map[string]string - req := request{ - method: client.GET, - url: makeURL(apiMachines, machineID, apiTags), - resp: &resp, - } - if _, err := c.sendRequest(req); err != nil { - return nil, errors.Newf(err, "failed to get list of tags for machine with id %s", machineID) - } - return resp, nil -} - -// GetMachineTag returns the value for a single tag on the specified machine. -// See API docs: http://apidocs.joyent.com/cloudapi/#GetMachineTag -func (c *Client) GetMachineTag(machineID, tagKey string) (string, error) { - var resp []byte - requestHeaders := make(http.Header) - requestHeaders.Set("Accept", "text/plain") - req := request{ - method: client.GET, - url: makeURL(apiMachines, machineID, apiTags, tagKey), - resp: &resp, - reqHeader: requestHeaders, - } - if _, err := c.sendRequest(req); err != nil { - return "", errors.Newf(err, "failed to get tag %s for machine with id %s", tagKey, machineID) - } - return string(resp), nil -} - -// DeleteMachineTag deletes a single tag from the specified machine. -// See API docs: http://apidocs.joyent.com/cloudapi/#DeleteMachineTag -func (c *Client) DeleteMachineTag(machineID, tagKey string) error { - req := request{ - method: client.DELETE, - url: makeURL(apiMachines, machineID, apiTags, tagKey), - expectedStatus: http.StatusNoContent, - } - if _, err := c.sendRequest(req); err != nil { - return errors.Newf(err, "failed to delete tag with key %s for machine with id %s", tagKey, machineID) - } - return nil -} - -// DeleteMachineTags deletes all tags from the specified machine. -// See API docs: http://apidocs.joyent.com/cloudapi/#DeleteMachineTags -func (c *Client) DeleteMachineTags(machineID string) error { - req := request{ - method: client.DELETE, - url: makeURL(apiMachines, machineID, apiTags), - expectedStatus: http.StatusNoContent, - } - if _, err := c.sendRequest(req); err != nil { - return errors.Newf(err, "failed to delete tags for machine with id %s", machineID) - } - return nil -} diff --git a/vendor/github.com/joyent/gosdc/cloudapi/machines.go b/vendor/github.com/joyent/gosdc/cloudapi/machines.go deleted file mode 100644 index 32a3ccf65..000000000 --- a/vendor/github.com/joyent/gosdc/cloudapi/machines.go +++ /dev/null @@ -1,307 +0,0 @@ -package cloudapi - -import ( - "encoding/json" - "fmt" - "net/http" - - "strings" - - "github.com/joyent/gocommon/client" - "github.com/joyent/gocommon/errors" -) - -// Machine represent a provisioned virtual machines -type Machine struct { - Id string // Unique identifier for the image - Name string // Machine friendly name - Type string // Machine type, one of 'smartmachine' or 'virtualmachine' - State string // Current state of the machine - Dataset string // The dataset URN the machine was provisioned with. For new images/datasets this value will be the dataset id, i.e, same value than the image attribute - Memory int // The amount of memory the machine has (in Mb) - Disk int // The amount of disk the machine has (in Gb) - IPs []string // The IP addresses the machine has - Metadata map[string]string // Map of the machine metadata, e.g. authorized-keys - Tags map[string]string // Map of the machine tags - Created string // When the machine was created - Updated string // When the machine was updated - Package string // The name of the package used to create the machine - Image string // The image id the machine was provisioned with - PrimaryIP string // The primary (public) IP address for the machine - Networks []string // The network IDs for the machine - FirewallEnabled bool `json:"firewall_enabled"` // whether or not the firewall is enabled - DomainNames []string `json:"dns_names"` // The domain names of this machine -} - -// Equals compares two machines. Ignores state and timestamps. -func (m Machine) Equals(other Machine) bool { - if m.Id == other.Id && m.Name == other.Name && m.Type == other.Type && m.Dataset == other.Dataset && - m.Memory == other.Memory && m.Disk == other.Disk && m.Package == other.Package && m.Image == other.Image && - m.compareIPs(other) && m.compareMetadata(other) { - return true - } - return false -} - -// Helper method to compare two machines IPs -func (m Machine) compareIPs(other Machine) bool { - if len(m.IPs) != len(other.IPs) { - return false - } - for i, v := range m.IPs { - if v != other.IPs[i] { - return false - } - } - return true -} - -// Helper method to compare two machines metadata -func (m Machine) compareMetadata(other Machine) bool { - if len(m.Metadata) != len(other.Metadata) { - return false - } - for k, v := range m.Metadata { - if v != other.Metadata[k] { - return false - } - } - return true -} - -// CreateMachineOpts represent the option that can be specified -// when creating a new machine. -type CreateMachineOpts struct { - Name string `json:"name"` // Machine friendly name, default is a randomly generated name - Package string `json:"package"` // Name of the package to use on provisioning - Image string `json:"image"` // The image UUID - Networks []string `json:"networks"` // Desired networks IDs - Metadata map[string]string `json:"-"` // An arbitrary set of metadata key/value pairs can be set at provision time - Tags map[string]string `json:"-"` // An arbitrary set of tags can be set at provision time - FirewallEnabled bool `json:"firewall_enabled"` // Completely enable or disable firewall for this machine (new in API version 7.0) -} - -// AuditAction represents an action/event accomplished by a machine. -type AuditAction struct { - Action string // Action name - Parameters map[string]interface{} // Original set of parameters sent when the action was requested - Time string // When the action finished - Success string // Either 'yes' or 'no', depending on the action successfulness - Caller Caller // Account requesting the action -} - -// Caller represents an account requesting an action. -type Caller struct { - Type string // Authentication type for the action request. One of 'basic', 'operator', 'signature' or 'token' - User string // When the authentication type is 'basic', this member will be present and include user login - IP string // The IP addresses this from which the action was requested. Not present if type is 'operator' - KeyId string // When authentication type is either 'signature' or 'token', SSH key identifier -} - -// appendJSON marshals the given attribute value and appends it as an encoded value to the given json data. -// The newly encode (attr, value) is inserted just before the closing "}" in the json data. -func appendJSON(data []byte, attr string, value interface{}) ([]byte, error) { - newData, err := json.Marshal(&value) - if err != nil { - return nil, err - } - strData := string(data) - result := fmt.Sprintf(`%s, "%s":%s}`, strData[:len(strData)-1], attr, string(newData)) - return []byte(result), nil -} - -type jsonOpts CreateMachineOpts - -// MarshalJSON turns the given CreateMachineOpts into JSON -func (opts CreateMachineOpts) MarshalJSON() ([]byte, error) { - jo := jsonOpts(opts) - data, err := json.Marshal(&jo) - if err != nil { - return nil, err - } - for k, v := range opts.Tags { - if !strings.HasPrefix(k, "tag.") { - k = "tag." + k - } - data, err = appendJSON(data, k, v) - if err != nil { - return nil, err - } - } - for k, v := range opts.Metadata { - if !strings.HasPrefix(k, "metadata.") { - k = "metadata." + k - } - data, err = appendJSON(data, k, v) - if err != nil { - return nil, err - } - } - return data, nil -} - -// ListMachines lists all machines on record for an account. -// You can paginate this API by passing in offset, and limit -// See API docs: http://apidocs.joyent.com/cloudapi/#ListMachines -func (c *Client) ListMachines(filter *Filter) ([]Machine, error) { - var resp []Machine - req := request{ - method: client.GET, - url: apiMachines, - filter: filter, - resp: &resp, - } - if _, err := c.sendRequest(req); err != nil { - return nil, errors.Newf(err, "failed to get list of machines") - } - return resp, nil -} - -// CountMachines returns the number of machines on record for an account. -// See API docs: http://apidocs.joyent.com/cloudapi/#ListMachines -func (c *Client) CountMachines() (int, error) { - var resp int - req := request{ - method: client.HEAD, - url: apiMachines, - resp: &resp, - } - if _, err := c.sendRequest(req); err != nil { - return -1, errors.Newf(err, "failed to get count of machines") - } - return resp, nil -} - -// GetMachine returns the machine specified by machineId. -// See API docs: http://apidocs.joyent.com/cloudapi/#GetMachine -func (c *Client) GetMachine(machineID string) (*Machine, error) { - var resp Machine - req := request{ - method: client.GET, - url: makeURL(apiMachines, machineID), - resp: &resp, - } - if _, err := c.sendRequest(req); err != nil { - return nil, errors.Newf(err, "failed to get machine with id: %s", machineID) - } - return &resp, nil -} - -// CreateMachine creates a new machine with the options specified. -// See API docs: http://apidocs.joyent.com/cloudapi/#CreateMachine -func (c *Client) CreateMachine(opts CreateMachineOpts) (*Machine, error) { - var resp Machine - req := request{ - method: client.POST, - url: apiMachines, - reqValue: opts, - resp: &resp, - expectedStatus: http.StatusCreated, - } - if _, err := c.sendRequest(req); err != nil { - return nil, errors.Newf(err, "failed to create machine with name: %s", opts.Name) - } - return &resp, nil -} - -// StopMachine stops a running machine. -// See API docs: http://apidocs.joyent.com/cloudapi/#StopMachine -func (c *Client) StopMachine(machineID string) error { - req := request{ - method: client.POST, - url: fmt.Sprintf("%s/%s?action=%s", apiMachines, machineID, actionStop), - expectedStatus: http.StatusAccepted, - } - if _, err := c.sendRequest(req); err != nil { - return errors.Newf(err, "failed to stop machine with id: %s", machineID) - } - return nil -} - -// StartMachine starts a stopped machine. -// See API docs: http://apidocs.joyent.com/cloudapi/#StartMachine -func (c *Client) StartMachine(machineID string) error { - req := request{ - method: client.POST, - url: fmt.Sprintf("%s/%s?action=%s", apiMachines, machineID, actionStart), - expectedStatus: http.StatusAccepted, - } - if _, err := c.sendRequest(req); err != nil { - return errors.Newf(err, "failed to start machine with id: %s", machineID) - } - return nil -} - -// RebootMachine reboots (stop followed by a start) a machine. -// See API docs: http://apidocs.joyent.com/cloudapi/#RebootMachine -func (c *Client) RebootMachine(machineID string) error { - req := request{ - method: client.POST, - url: fmt.Sprintf("%s/%s?action=%s", apiMachines, machineID, actionReboot), - expectedStatus: http.StatusAccepted, - } - if _, err := c.sendRequest(req); err != nil { - return errors.Newf(err, "failed to reboot machine with id: %s", machineID) - } - return nil -} - -// ResizeMachine allows you to resize a SmartMachine. Virtual machines can also -// be resized, but only resizing virtual machines to a higher capacity package -// is supported. -// See API docs: http://apidocs.joyent.com/cloudapi/#ResizeMachine -func (c *Client) ResizeMachine(machineID, packageName string) error { - req := request{ - method: client.POST, - url: fmt.Sprintf("%s/%s?action=%s&package=%s", apiMachines, machineID, actionResize, packageName), - expectedStatus: http.StatusAccepted, - } - if _, err := c.sendRequest(req); err != nil { - return errors.Newf(err, "failed to resize machine with id: %s", machineID) - } - return nil -} - -// RenameMachine renames an existing machine. -// See API docs: http://apidocs.joyent.com/cloudapi/#RenameMachine -func (c *Client) RenameMachine(machineID, machineName string) error { - req := request{ - method: client.POST, - url: fmt.Sprintf("%s/%s?action=%s&name=%s", apiMachines, machineID, actionRename, machineName), - expectedStatus: http.StatusAccepted, - } - if _, err := c.sendRequest(req); err != nil { - return errors.Newf(err, "failed to rename machine with id: %s", machineID) - } - return nil -} - -// DeleteMachine allows you to completely destroy a machine. Machine must be in the 'stopped' state. -// See API docs: http://apidocs.joyent.com/cloudapi/#DeleteMachine -func (c *Client) DeleteMachine(machineID string) error { - req := request{ - method: client.DELETE, - url: makeURL(apiMachines, machineID), - expectedStatus: http.StatusNoContent, - } - if _, err := c.sendRequest(req); err != nil { - return errors.Newf(err, "failed to delete machine with id %s", machineID) - } - return nil -} - -// MachineAudit provides a list of machine's accomplished actions, (sorted from -// latest to older one). -// See API docs: http://apidocs.joyent.com/cloudapi/#MachineAudit -func (c *Client) MachineAudit(machineID string) ([]AuditAction, error) { - var resp []AuditAction - req := request{ - method: client.GET, - url: makeURL(apiMachines, machineID, apiAudit), - resp: &resp, - } - if _, err := c.sendRequest(req); err != nil { - return nil, errors.Newf(err, "failed to get actions for machine with id %s", machineID) - } - return resp, nil -} diff --git a/vendor/github.com/joyent/gosdc/cloudapi/networks.go b/vendor/github.com/joyent/gosdc/cloudapi/networks.go deleted file mode 100644 index 18d828999..000000000 --- a/vendor/github.com/joyent/gosdc/cloudapi/networks.go +++ /dev/null @@ -1,44 +0,0 @@ -package cloudapi - -import ( - "github.com/joyent/gocommon/client" - "github.com/joyent/gocommon/errors" -) - -// Network represents a network available to a given account -type Network struct { - Id string // Unique identifier for the network - Name string // Network name - Public bool // Whether this a public or private (rfc1918) network - Description string // Optional description for this network, when name is not enough -} - -// ListNetworks lists all the networks which can be used by the given account. -// See API docs: http://apidocs.joyent.com/cloudapi/#ListNetworks -func (c *Client) ListNetworks() ([]Network, error) { - var resp []Network - req := request{ - method: client.GET, - url: apiNetworks, - resp: &resp, - } - if _, err := c.sendRequest(req); err != nil { - return nil, errors.Newf(err, "failed to get list of networks") - } - return resp, nil -} - -// GetNetwork retrieves an individual network record. -// See API docs: http://apidocs.joyent.com/cloudapi/#GetNetwork -func (c *Client) GetNetwork(networkID string) (*Network, error) { - var resp Network - req := request{ - method: client.GET, - url: makeURL(apiNetworks, networkID), - resp: &resp, - } - if _, err := c.sendRequest(req); err != nil { - return nil, errors.Newf(err, "failed to get network with id %s", networkID) - } - return &resp, nil -} diff --git a/vendor/github.com/joyent/gosdc/cloudapi/packages.go b/vendor/github.com/joyent/gosdc/cloudapi/packages.go deleted file mode 100644 index 9b3399916..000000000 --- a/vendor/github.com/joyent/gosdc/cloudapi/packages.go +++ /dev/null @@ -1,53 +0,0 @@ -package cloudapi - -import ( - "github.com/joyent/gocommon/client" - "github.com/joyent/gocommon/errors" -) - -// Package represents a named collections of resources that are used to describe the 'sizes' -// of either a smart machine or a virtual machine. -type Package struct { - Name string // Name for the package - Memory int // Memory available (in Mb) - Disk int // Disk space available (in Gb) - Swap int // Swap memory available (in Mb) - VCPUs int // Number of VCPUs for the package - Default bool // Indicates whether this is the default package in the datacenter - Id string // Unique identifier for the package - Version string // Version for the package - Group string // Group this package belongs to - Description string // Human friendly description for the package -} - -// ListPackages provides a list of packages available in the datacenter. -// See API docs: http://apidocs.joyent.com/cloudapi/#ListPackages -func (c *Client) ListPackages(filter *Filter) ([]Package, error) { - var resp []Package - req := request{ - method: client.GET, - url: apiPackages, - filter: filter, - resp: &resp, - } - if _, err := c.sendRequest(req); err != nil { - return nil, errors.Newf(err, "failed to get list of packages") - } - return resp, nil -} - -// GetPackage returns the package specified by packageName. NOTE: packageName can -// specify either the package name or package ID. -// See API docs: http://apidocs.joyent.com/cloudapi/#GetPackage -func (c *Client) GetPackage(packageName string) (*Package, error) { - var resp Package - req := request{ - method: client.GET, - url: makeURL(apiPackages, packageName), - resp: &resp, - } - if _, err := c.sendRequest(req); err != nil { - return nil, errors.Newf(err, "failed to get package with name: %s", packageName) - } - return &resp, nil -} diff --git a/vendor/github.com/joyent/gosdc/cloudapi/services.go b/vendor/github.com/joyent/gosdc/cloudapi/services.go deleted file mode 100644 index 634b69ff3..000000000 --- a/vendor/github.com/joyent/gosdc/cloudapi/services.go +++ /dev/null @@ -1,20 +0,0 @@ -package cloudapi - -import ( - "github.com/joyent/gocommon/client" - "github.com/joyent/gocommon/errors" -) - -// list available services -func (c *Client) ListServices() (map[string]string, error) { - var resp map[string]string - req := request{ - method: client.GET, - url: apiServices, - resp: &resp, - } - if _, err := c.sendRequest(req); err != nil { - return nil, errors.Newf(err, "failed to get list of services") - } - return resp, nil -} diff --git a/vendor/github.com/joyent/gosdc/LICENSE b/vendor/github.com/joyent/triton-go/LICENSE similarity index 100% rename from vendor/github.com/joyent/gosdc/LICENSE rename to vendor/github.com/joyent/triton-go/LICENSE diff --git a/vendor/github.com/joyent/triton-go/README.md b/vendor/github.com/joyent/triton-go/README.md new file mode 100644 index 000000000..6546ba373 --- /dev/null +++ b/vendor/github.com/joyent/triton-go/README.md @@ -0,0 +1,216 @@ +# triton-go + +`go-triton` is an idiomatic library exposing a client SDK for Go applications using the Joyent Triton API. + +## Usage + +Triton uses [HTTP Signature][4] to sign the Date header in each HTTP request made to the Triton API. Currently, requests can be signed using either a private key file loaded from disk (using an [`authentication.PrivateKeySigner`][5]), or using a key stored with the local SSH Agent (using an [`SSHAgentSigner`][6]. + +To construct a Signer, use the `New*` range of methods in the `authentication` package. In the case of `authentication.NewSSHAgentSigner`, the parameters are the fingerprint of the key with which to sign, and the account name (normally stored in the `SDC_ACCOUNT` environment variable). For example: + +``` +const fingerprint := "a4:c6:f3:75:80:27:e0:03:a9:98:79:ef:c5:0a:06:11" +sshKeySigner, err := authentication.NewSSHAgentSigner(fingerprint, "AccountName") +if err != nil { + log.Fatalf("NewSSHAgentSigner: %s", err) +} +``` + +An appropriate key fingerprint can be generated using `ssh-keygen`: + +``` +ssh-keygen -Emd5 -lf ~/.ssh/id_rsa.pub | cut -d " " -f 2 | sed 's/MD5://' +``` + +To construct a Client, use the `NewClient` function, passing in the endpoint, account name and constructed signer: + +```go +client, err := triton.NewClient("https://us-sw-1.api.joyent.com/", "AccountName", sshKeySigner) +if err != nil { + log.Fatalf("NewClient: %s", err) +} +``` + +Having constructed a `triton.Client`, use the methods available to access functionality by functional grouping. For example, for access to operations on SSH keys, use the `Keys()` method to obtain a client which has access to the `CreateKey`, `ListKeys` and `DeleteKey` operations. For access to operations on Machines, use the `Machines()` method to obtain a client which has access to the `RenameMachine`, `GetMachineMetadata`, `GetMachineTag`, and other operations. + +Operation methods take their formal parameters via a struct named `OperationInput` - for example when creating an SSH key, the `CreateKeyInput` struct is used with the `func CreateKey(*CreateKeyInput) (*Key, error)` method. This allows specification of named parameters: + +``` +client := state.Client().Keys() + +key, err := client.CreateKey(&CreateKeyInput{ + Name: "tempKey", + Key: "ssh-rsa .....", +}) +if err != nil { + panic(err) +} + +// Key contains the return value. +``` + +## Error Handling + +If an error is returned by the HTTP API, the `error` returned from the function will contain an instance of `triton.TritonError` in the chain. Error wrapping is performed using the [errwrap][7] library from HashiCorp. + +## Completeness + +The following list is updated as new functionality is added. The complete list of operations is taken from the [CloudAPI documentation](https://apidocs.joyent.com/cloudapi). + +- Accounts + - [x] GetAccount + - [x] UpdateAccount +- Keys + - [x] ListKeys + - [x] GetKey + - [x] CreateKey + - [x] DeleteKey +- Users + - [ ] ListUsers + - [ ] GetUser + - [ ] CreateUser + - [ ] UpdateUser + - [ ] ChangeUserPassword + - [ ] DeleteUser +- Roles + - [x] ListRoles + - [x] GetRole + - [x] CreateRole + - [x] UpdateRole + - [x] DeleteRole +- Role Tags + - [ ] SetRoleTags +- Policies + - [ ] ListPolicies + - [ ] GetPolicy + - [ ] CreatePolicy + - [ ] UpdatePolicy + - [ ] DeletePolicy +- User SSH Keys + - [x] ListUserKeys + - [x] GetUserKey + - [x] CreateUserKey + - [x] DeleteUserKey +- Config + - [x] GetConfig + - [x] UpdateConfig +- Datacenters + - [x] ListDatacenters + - [x] GetDatacenter +- Services + - [x] ListServices +- Images + - [x] ListImages + - [x] GetImage + - [x] DeleteImage + - [x] ExportImage + - [x] CreateImageFromMachine + - [x] UpdateImage +- Packages + - [x] ListPackages + - [x] GetPackage +- Instances + - [ ] ListMachines + - [x] GetMachine + - [x] CreateMachine + - [ ] StopMachine + - [ ] StartMachine + - [ ] RebootMachine + - [x] ResizeMachine + - [x] RenameMachine + - [x] EnableMachineFirewall + - [x] DisableMachineFirewall + - [ ] CreateMachineSnapshot + - [ ] StartMachineFromSnapshot + - [ ] ListMachineSnapshots + - [ ] GetMachineSnapshot + - [ ] DeleteMachineSnapshot + - [x] UpdateMachineMetadata + - [ ] ListMachineMetadata + - [ ] GetMachineMetadata + - [ ] DeleteMachineMetadata + - [ ] DeleteAllMachineMetadata + - [x] AddMachineTags + - [x] ReplaceMachineTags + - [x] ListMachineTags + - [x] GetMachineTag + - [x] DeleteMachineTag + - [x] DeleteMachineTags + - [x] DeleteMachine + - [ ] MachineAudit +- Analytics + - [ ] DescribeAnalytics + - [ ] ListInstrumentations + - [ ] GetInstrumentation + - [ ] GetInstrumentationValue + - [ ] GetInstrumentationHeatmap + - [ ] GetInstrumentationHeatmapDetails + - [ ] CreateInstrumentation + - [ ] DeleteInstrumentation +- Firewall Rules + - [x] ListFirewallRules + - [x] GetFirewallRule + - [x] CreateFirewallRule + - [x] UpdateFirewallRule + - [x] EnableFirewallRule + - [x] DisableFirewallRule + - [x] DeleteFirewallRule + - [ ] ListMachineFirewallRules + - [x] ListFirewallRuleMachines +- Fabrics + - [x] ListFabricVLANs + - [x] CreateFabricVLAN + - [x] GetFabricVLAN + - [x] UpdateFabricVLAN + - [x] DeleteFabricVLAN + - [x] ListFabricNetworks + - [x] CreateFabricNetwork + - [x] GetFabricNetwork + - [x] DeleteFabricNetwork +- Networks + - [x] ListNetworks + - [x] GetNetwork +- Nics + - [ ] ListNics + - [ ] GetNic + - [x] AddNic + - [x] RemoveNic + +## Running Acceptance Tests + +Acceptance Tests run directly against the Triton API, so you will need either a local installation or Triton or an account with Joyent in order to run them. The tests create real resources (and thus cost real money!) + +In order to run acceptance tests, the following environment variables must be set: + +- `TRITON_TEST` - must be set to any value in order to indicate desire to create resources +- `SDC_URL` - the base endpoint for the Triton API +- `SDC_ACCOUNT` - the account name for the Triton API +- `SDC_KEY_ID` - the fingerprint of the SSH key identifying the key + +Additionally, you may set `SDC_KEY_MATERIAL` to the contents of an unencrypted private key. If this is set, the PrivateKeySigner (see above) will be used - if not the SSHAgentSigner will be used. + +### Example Run + +The verbose output has been removed for brevity here. + +``` +$ HTTP_PROXY=http://localhost:8888 \ + TRITON_TEST=1 \ + SDC_URL=https://us-sw-1.api.joyent.com \ + SDC_ACCOUNT=AccountName \ + SDC_KEY_ID=a4:c6:f3:75:80:27:e0:03:a9:98:79:ef:c5:0a:06:11 \ + go test -v -run "TestAccKey" +=== RUN TestAccKey_Create +--- PASS: TestAccKey_Create (12.46s) +=== RUN TestAccKey_Get +--- PASS: TestAccKey_Get (4.30s) +=== RUN TestAccKey_Delete +--- PASS: TestAccKey_Delete (15.08s) +PASS +ok github.com/jen20/triton-go 31.861s +``` + +[4]: https://github.com/joyent/node-http-signature/blob/master/http_signing.md +[5]: https://godoc.org/github.com/joyent/go-triton/authentication +[6]: https://godoc.org/github.com/joyent/go-triton/authentication +[7]: https://github.com/hashicorp/go-errwrap diff --git a/vendor/github.com/joyent/triton-go/accounts.go b/vendor/github.com/joyent/triton-go/accounts.go new file mode 100644 index 000000000..88e7bbf12 --- /dev/null +++ b/vendor/github.com/joyent/triton-go/accounts.go @@ -0,0 +1,95 @@ +package triton + +import ( + "context" + "encoding/json" + "fmt" + "net/http" + "time" + + "github.com/hashicorp/errwrap" +) + +type AccountsClient struct { + *Client +} + +// Accounts returns a c used for accessing functions pertaining +// to Account functionality in the Triton API. +func (c *Client) Accounts() *AccountsClient { + return &AccountsClient{c} +} + +type Account struct { + ID string `json:"id"` + Login string `json:"login"` + Email string `json:"email"` + CompanyName string `json:"companyName"` + FirstName string `json:"firstName"` + LastName string `json:"lastName"` + Address string `json:"address"` + PostalCode string `json:"postalCode"` + City string `json:"city"` + State string `json:"state"` + Country string `json:"country"` + Phone string `json:"phone"` + Created time.Time `json:"created"` + Updated time.Time `json:"updated"` + TritonCNSEnabled bool `json:"triton_cns_enabled"` +} + +type GetAccountInput struct{} + +func (client *AccountsClient) GetAccount(ctx context.Context, input *GetAccountInput) (*Account, error) { + path := fmt.Sprintf("/%s", client.accountName) + respReader, err := client.executeRequest(ctx, http.MethodGet, path, nil) + if respReader != nil { + defer respReader.Close() + } + if err != nil { + return nil, errwrap.Wrapf("Error executing GetAccount request: {{err}}", err) + } + + var result *Account + decoder := json.NewDecoder(respReader) + if err = decoder.Decode(&result); err != nil { + return nil, errwrap.Wrapf("Error decoding GetAccount response: {{err}}", err) + } + + return result, nil +} + +type UpdateAccountInput struct { + Email string `json:"email,omitempty"` + CompanyName string `json:"companyName,omitempty"` + FirstName string `json:"firstName,omitempty"` + LastName string `json:"lastName,omitempty"` + Address string `json:"address,omitempty"` + PostalCode string `json:"postalCode,omitempty"` + City string `json:"city,omitempty"` + State string `json:"state,omitempty"` + Country string `json:"country,omitempty"` + Phone string `json:"phone,omitempty"` + TritonCNSEnabled bool `json:"triton_cns_enabled,omitempty"` +} + +// UpdateAccount updates your account details with the given parameters. +// TODO(jen20) Work out a safe way to test this +func (client *AccountsClient) UpdateAccount(ctx context.Context, input *UpdateAccountInput) (*Account, error) { + path := fmt.Sprintf("/%s", client.accountName) + respReader, err := client.executeRequest(ctx, http.MethodPost, path, input) + if respReader != nil { + defer respReader.Close() + } + if err != nil { + return nil, errwrap.Wrapf("Error executing UpdateAccount request: {{err}}", err) + } + + var result *Account + decoder := json.NewDecoder(respReader) + if err = decoder.Decode(&result); err != nil { + return nil, errwrap.Wrapf("Error decoding UpdateAccount response: {{err}}", err) + } + + return result, nil +} diff --git a/vendor/github.com/joyent/triton-go/authentication/ecdsa_signature.go b/vendor/github.com/joyent/triton-go/authentication/ecdsa_signature.go new file mode 100644 index 000000000..8aaba97a5 --- /dev/null +++ b/vendor/github.com/joyent/triton-go/authentication/ecdsa_signature.go @@ -0,0 +1,66 @@ +package authentication + +import ( + "encoding/asn1" + "encoding/base64" + "fmt" + "math/big" + + "github.com/hashicorp/errwrap" + "golang.org/x/crypto/ssh" +) + +type ecdsaSignature struct { + hashAlgorithm string + R *big.Int + S *big.Int +} + +func (s *ecdsaSignature) SignatureType() string { + return fmt.Sprintf("ecdsa-%s", s.hashAlgorithm) +} + +func (s *ecdsaSignature) String() string { + toEncode := struct { + R *big.Int + S *big.Int + }{ + R: s.R, + S: s.S, + } + + signatureBytes, err := asn1.Marshal(toEncode) + if err != nil { + panic(fmt.Sprintf("Error marshaling signature: %s", err)) + } + + return base64.StdEncoding.EncodeToString(signatureBytes) +} + +func newECDSASignature(signatureBlob []byte) (*ecdsaSignature, error) { + var ecSig struct { + R *big.Int + S *big.Int + } + + if err := ssh.Unmarshal(signatureBlob, &ecSig); err != nil { + return nil, errwrap.Wrapf("Error unmarshaling signature: {{err}}", err) + } + + rValue := ecSig.R.Bytes() + var hashAlgorithm string + switch len(rValue) { + case 31, 32: + hashAlgorithm = "sha256" + case 65, 66: + hashAlgorithm = "sha512" + default: + return nil, fmt.Errorf("Unsupported key length: %d", len(rValue)) + } + + return &ecdsaSignature{ + hashAlgorithm: hashAlgorithm, + R: ecSig.R, + S: ecSig.S, + }, nil +} diff --git a/vendor/github.com/joyent/triton-go/authentication/private_key_signer.go b/vendor/github.com/joyent/triton-go/authentication/private_key_signer.go new file mode 100644 index 000000000..20dc6bfed --- /dev/null +++ b/vendor/github.com/joyent/triton-go/authentication/private_key_signer.go @@ -0,0 +1,76 @@ +package authentication + +import ( + "crypto" + "crypto/rand" + "crypto/rsa" + "crypto/x509" + "encoding/base64" + "encoding/pem" + "errors" + "fmt" + "strings" + + "github.com/hashicorp/errwrap" + "golang.org/x/crypto/ssh" +) + +type PrivateKeySigner struct { + formattedKeyFingerprint string + keyFingerprint string + accountName string + hashFunc crypto.Hash + + privateKey *rsa.PrivateKey +} + +func NewPrivateKeySigner(keyFingerprint string, privateKeyMaterial []byte, accountName string) (*PrivateKeySigner, error) { + keyFingerprintMD5 := strings.Replace(keyFingerprint, ":", "", -1) + + block, _ := pem.Decode(privateKeyMaterial) + if block == nil { + return nil, errors.New("Error PEM-decoding private key material: nil block received") + } + + rsakey, err := x509.ParsePKCS1PrivateKey(block.Bytes) + if err != nil { + return nil, errwrap.Wrapf("Error parsing private key: {{err}}", err) + } + + sshPublicKey, err := ssh.NewPublicKey(rsakey.Public()) + if err != nil { + return nil, errwrap.Wrapf("Error parsing SSH key from private key: {{err}}", err) + } + + matchKeyFingerprint := formatPublicKeyFingerprint(sshPublicKey, false) + displayKeyFingerprint := formatPublicKeyFingerprint(sshPublicKey, true) + if matchKeyFingerprint != keyFingerprintMD5 { + return nil, errors.New("Private key file does not match public key fingerprint") + } + + return &PrivateKeySigner{ + formattedKeyFingerprint: displayKeyFingerprint, + keyFingerprint: keyFingerprint, + accountName: accountName, + + hashFunc: crypto.SHA1, + privateKey: rsakey, + }, nil +} + +func (s *PrivateKeySigner) Sign(dateHeader string) (string, error) { + const headerName = "date" + + hash := s.hashFunc.New() + hash.Write([]byte(fmt.Sprintf("%s: %s", headerName, dateHeader))) + digest := hash.Sum(nil) + + signed, err := rsa.SignPKCS1v15(rand.Reader, s.privateKey, s.hashFunc, digest) + if err != nil { + return "", errwrap.Wrapf("Error signing date header: {{err}}", err) + } + signedBase64 := base64.StdEncoding.EncodeToString(signed) + + keyID := fmt.Sprintf("/%s/keys/%s", s.accountName, s.formattedKeyFingerprint) + return fmt.Sprintf(authorizationHeaderFormat, keyID, "rsa-sha1", headerName, signedBase64), nil +} diff --git a/vendor/github.com/joyent/triton-go/authentication/rsa_signature.go b/vendor/github.com/joyent/triton-go/authentication/rsa_signature.go new file mode 100644 index 000000000..8d513f6c4 --- /dev/null +++ b/vendor/github.com/joyent/triton-go/authentication/rsa_signature.go @@ -0,0 +1,25 @@ +package authentication + +import ( + "encoding/base64" +) + +type rsaSignature struct { + hashAlgorithm string + signature []byte +} + +func (s *rsaSignature) SignatureType() string { + return s.hashAlgorithm +} + +func (s *rsaSignature) String() string { + return base64.StdEncoding.EncodeToString(s.signature) +} + +func newRSASignature(signatureBlob []byte) (*rsaSignature, error) { + return &rsaSignature{ + hashAlgorithm: "rsa-sha1", + signature: signatureBlob, + }, nil +} diff --git a/vendor/github.com/joyent/triton-go/authentication/signature.go b/vendor/github.com/joyent/triton-go/authentication/signature.go new file mode 100644 index 000000000..e6a52df30 --- /dev/null +++ b/vendor/github.com/joyent/triton-go/authentication/signature.go @@ -0,0 +1,27 @@ +package authentication + +import ( + "regexp" + "fmt" +) + +type httpAuthSignature interface { + SignatureType() string + String() string +} + +func keyFormatToKeyType(keyFormat string) (string, error) { + if keyFormat == "ssh-rsa" { + return "rsa", nil + } + + if keyFormat == "ssh-ed25519" { + return "ed25519", nil + } + + if regexp.MustCompile("^ecdsa-sha2-*").Match([]byte(keyFormat)) { + return "ecdsa", nil + } + + return "", fmt.Errorf("Unknown key format: %s", keyFormat) +} diff --git a/vendor/github.com/joyent/triton-go/authentication/signer.go b/vendor/github.com/joyent/triton-go/authentication/signer.go new file mode 100644 index 000000000..dfc89ad44 --- /dev/null +++ b/vendor/github.com/joyent/triton-go/authentication/signer.go @@ -0,0 +1,7 @@ +package authentication + +const authorizationHeaderFormat = `Signature keyId="%s",algorithm="%s",headers="%s",signature="%s"` + +type Signer interface { + Sign(dateHeader string) (string, error) +} diff --git a/vendor/github.com/joyent/triton-go/authentication/ssh_agent_signer.go b/vendor/github.com/joyent/triton-go/authentication/ssh_agent_signer.go new file mode 100644 index 000000000..028743159 --- /dev/null +++ b/vendor/github.com/joyent/triton-go/authentication/ssh_agent_signer.go @@ -0,0 +1,104 @@ +package authentication + +import ( + "crypto/md5" + "errors" + "fmt" + "net" + "os" + "strings" + + "github.com/hashicorp/errwrap" + "golang.org/x/crypto/ssh" + "golang.org/x/crypto/ssh/agent" +) + +type SSHAgentSigner struct { + formattedKeyFingerprint string + keyFingerprint string + accountName string + keyIdentifier string + + agent agent.Agent + key ssh.PublicKey +} + +func NewSSHAgentSigner(keyFingerprint, accountName string) (*SSHAgentSigner, error) { + sshAgentAddress := os.Getenv("SSH_AUTH_SOCK") + if sshAgentAddress == "" { + return nil, errors.New("SSH_AUTH_SOCK is not set") + } + + conn, err := net.Dial("unix", sshAgentAddress) + if err != nil { + return nil, errwrap.Wrapf("Error dialing SSH agent: {{err}}", err) + } + + ag := agent.NewClient(conn) + + keys, err := ag.List() + if err != nil { + return nil, errwrap.Wrapf("Error listing keys in SSH Agent: %s", err) + } + + keyFingerprintMD5 := strings.Replace(keyFingerprint, ":", "", -1) + + var matchingKey ssh.PublicKey + for _, key := range keys { + h := md5.New() + h.Write(key.Marshal()) + fp := fmt.Sprintf("%x", h.Sum(nil)) + + if fp == keyFingerprintMD5 { + matchingKey = key + } + } + + if matchingKey == nil { + return nil, fmt.Errorf("No key in the SSH Agent matches fingerprint: %s", keyFingerprint) + } + + formattedKeyFingerprint := formatPublicKeyFingerprint(matchingKey, true) + + return &SSHAgentSigner{ + formattedKeyFingerprint: formattedKeyFingerprint, + keyFingerprint: keyFingerprint, + accountName: accountName, + agent: ag, + key: matchingKey, + keyIdentifier: fmt.Sprintf("/%s/keys/%s", accountName, formattedKeyFingerprint), + }, nil +} + +func (s *SSHAgentSigner) Sign(dateHeader string) (string, error) { + const headerName = "date" + + signature, err := s.agent.Sign(s.key, []byte(fmt.Sprintf("%s: %s", headerName, dateHeader))) + if err != nil { + return "", errwrap.Wrapf("Error signing date header: {{err}}", err) + } + + keyFormat, err := keyFormatToKeyType(signature.Format) + if err != nil { + return "", errwrap.Wrapf("Error reading signature: {{err}}", err) + } + + var authSignature httpAuthSignature + switch keyFormat { + case "rsa": + authSignature, err = newRSASignature(signature.Blob) + if err != nil { + return "", errwrap.Wrapf("Error reading signature: {{err}}", err) + } + case "ecdsa": + authSignature, err = newECDSASignature(signature.Blob) + if err != nil { + return "", errwrap.Wrapf("Error reading signature: {{err}}", err) + } + default: + return "", fmt.Errorf("Unsupported algorithm from SSH agent: %s", signature.Format) + } + + return fmt.Sprintf(authorizationHeaderFormat, s.keyIdentifier, + authSignature.SignatureType(), headerName, authSignature.String()), nil +} diff --git a/vendor/github.com/joyent/triton-go/authentication/util.go b/vendor/github.com/joyent/triton-go/authentication/util.go new file mode 100644 index 000000000..7c298b68c --- /dev/null +++ b/vendor/github.com/joyent/triton-go/authentication/util.go @@ -0,0 +1,29 @@ +package authentication + +import ( + "crypto/md5" + "fmt" + "strings" + + "golang.org/x/crypto/ssh" +) + +// formatPublicKeyFingerprint produces the MD5 fingerprint of the given SSH +// public key. If display is true, the fingerprint is formatted with colons +// between each byte, as per the output of OpenSSL. +func formatPublicKeyFingerprint(key ssh.PublicKey, display bool) string { + publicKeyFingerprint := md5.New() + publicKeyFingerprint.Write(key.Marshal()) + publicKeyFingerprintString := fmt.Sprintf("%x", publicKeyFingerprint.Sum(nil)) + + if !display { + return publicKeyFingerprintString + } + + formatted := "" + for i := 0; i < len(publicKeyFingerprintString); i = i + 2 { + formatted = fmt.Sprintf("%s%s:", formatted, publicKeyFingerprintString[i:i+2]) + } + + return strings.TrimSuffix(formatted, ":") +} diff --git a/vendor/github.com/joyent/triton-go/client.go b/vendor/github.com/joyent/triton-go/client.go new file mode 100644 index 000000000..c0ecc5fd0 --- /dev/null +++ b/vendor/github.com/joyent/triton-go/client.go @@ -0,0 +1,195 @@ +package triton + +import ( + "bytes" + "context" + "crypto/tls" + "encoding/json" + "errors" + "io" + "net" + "net/http" + "net/url" + "time" + + "github.com/hashicorp/errwrap" + "github.com/joyent/triton-go/authentication" +) + +const nilContext = "nil context" + +// Client represents a connection to the Triton API. +type Client struct { + client *http.Client + authorizer []authentication.Signer + apiURL url.URL + accountName string +} + +// NewClient is used to construct a Client in order to make API +// requests to the Triton API. +// +// At least one signer must be provided - example signers include +// authentication.PrivateKeySigner and authentication.SSHAgentSigner. +func NewClient(endpoint string, accountName string, signers ...authentication.Signer) (*Client, error) { + apiURL, err := url.Parse(endpoint) + if err != nil { + return nil, errwrap.Wrapf("invalid endpoint: {{err}}", err) + } + + if accountName == "" { + return nil, errors.New("account name can not be empty") + } + + httpClient := &http.Client{ + Transport: httpTransport(false), + CheckRedirect: doNotFollowRedirects, + } + + return &Client{ + client: httpClient, + authorizer: signers, + apiURL: *apiURL, + accountName: accountName, + }, nil +} + +// InsecureSkipTLSVerify turns off TLS verification for the client connection. This +// allows connection to an endpoint with a certificate which was signed by a non- +// trusted CA, such as self-signed certificates. This can be useful when connecting +// to temporary Triton installations such as Triton Cloud-On-A-Laptop. +func (c *Client) InsecureSkipTLSVerify() { + if c.client == nil { + return + } + + c.client.Transport = httpTransport(true) +} + +func httpTransport(insecureSkipTLSVerify bool) *http.Transport { + return &http.Transport{ + Proxy: http.ProxyFromEnvironment, + Dial: (&net.Dialer{ + Timeout: 30 * time.Second, + KeepAlive: 30 * time.Second, + }).Dial, + TLSHandshakeTimeout: 10 * time.Second, + DisableKeepAlives: true, + MaxIdleConnsPerHost: -1, + TLSClientConfig: &tls.Config{ + InsecureSkipVerify: insecureSkipTLSVerify, + }, + } +} + +func doNotFollowRedirects(*http.Request, []*http.Request) error { + return http.ErrUseLastResponse +} + +func (c *Client) executeRequestURIParams(ctx context.Context, method, path string, body interface{}, query *url.Values) (io.ReadCloser, error) { + var requestBody io.ReadSeeker + if body != nil { + marshaled, err := json.MarshalIndent(body, "", " ") + if err != nil { + return nil, err + } + requestBody = bytes.NewReader(marshaled) + } + + endpoint := c.apiURL + endpoint.Path = path + if query != nil { + endpoint.RawQuery = query.Encode() + } + + req, err := http.NewRequest(method, endpoint.String(), requestBody) + if err != nil { + return nil, errwrap.Wrapf("Error constructing HTTP request: {{err}}", err) + } + + dateHeader := time.Now().UTC().Format(time.RFC1123) + req.Header.Set("date", dateHeader) + + authHeader, err := c.authorizer[0].Sign(dateHeader) + if err != nil { + return nil, errwrap.Wrapf("Error signing HTTP request: {{err}}", err) + } + req.Header.Set("Authorization", authHeader) + req.Header.Set("Accept", "application/json") + req.Header.Set("Accept-Version", "8") + req.Header.Set("User-Agent", "triton-go Client API") + + if body != nil { + req.Header.Set("Content-Type", "application/json") + } + + resp, err := c.client.Do(req.WithContext(ctx)) + if err != nil { + return nil, errwrap.Wrapf("Error executing HTTP request: {{err}}", err) + } + + if resp.StatusCode >= http.StatusOK && resp.StatusCode < http.StatusMultipleChoices { + return resp.Body, nil + } + + return nil, c.decodeError(resp.StatusCode, resp.Body) +} + +func (c *Client) decodeError(statusCode int, body io.Reader) error { + err := &TritonError{ + StatusCode: statusCode, + } + + errorDecoder := json.NewDecoder(body) + if err := errorDecoder.Decode(err); err != nil { + return errwrap.Wrapf("Error decoding error response: {{err}}", err) + } + + return err +} + +func (c *Client) executeRequest(ctx context.Context, method, path string, body interface{}) (io.ReadCloser, error) { + return c.executeRequestURIParams(ctx, method, path, body, nil) +} + +func (c *Client) executeRequestRaw(ctx context.Context, method, path string, body interface{}) (*http.Response, error) { + var requestBody io.ReadSeeker + if body != nil { + marshaled, err := json.MarshalIndent(body, "", " ") + if err != nil { + return nil, err + } + requestBody = bytes.NewReader(marshaled) + } + + endpoint := c.apiURL + endpoint.Path = path + + req, err := http.NewRequest(method, endpoint.String(), requestBody) + if err != nil { + return nil, errwrap.Wrapf("Error constructing HTTP request: {{err}}", err) + } + + dateHeader := time.Now().UTC().Format(time.RFC1123) + req.Header.Set("date", dateHeader) + + authHeader, err := c.authorizer[0].Sign(dateHeader) + if err != nil { + return nil, errwrap.Wrapf("Error signing HTTP request: {{err}}", err) + } + req.Header.Set("Authorization", authHeader) + req.Header.Set("Accept", "application/json") + req.Header.Set("Accept-Version", "8") + req.Header.Set("User-Agent", "triton-go c API") + + if body != nil { + req.Header.Set("Content-Type", "application/json") + } + + resp, err := c.client.Do(req.WithContext(ctx)) + if err != nil { + return nil, errwrap.Wrapf("Error executing HTTP request: {{err}}", err) + } + + return resp, nil +} diff --git a/vendor/github.com/joyent/triton-go/config.go b/vendor/github.com/joyent/triton-go/config.go new file mode 100644 index 000000000..b4f20e0a8 --- /dev/null +++ b/vendor/github.com/joyent/triton-go/config.go @@ -0,0 +1,73 @@ +package triton + +import ( + "context" + "encoding/json" + "fmt" + "net/http" + + "github.com/hashicorp/errwrap" +) + +type ConfigClient struct { + *Client +} + +// Config returns a c used for accessing functions pertaining +// to Config functionality in the Triton API. +func (c *Client) Config() *ConfigClient { + return &ConfigClient{c} +} + +// Config represents configuration for your account. +type Config struct { + // DefaultNetwork is the network that docker containers are provisioned on. + DefaultNetwork string `json:"default_network"` +} + +type GetConfigInput struct{} + +// GetConfig outputs configuration for your account. +func (client *ConfigClient) GetConfig(ctx context.Context, input *GetConfigInput) (*Config, error) { + path := fmt.Sprintf("/%s/config", client.accountName) + respReader, err := client.executeRequest(ctx, http.MethodGet, path, nil) + if respReader != nil { + defer respReader.Close() + } + if err != nil { + return nil, errwrap.Wrapf("Error executing GetConfig request: {{err}}", err) + } + + var result *Config + decoder := json.NewDecoder(respReader) + if err = decoder.Decode(&result); err != nil { + return nil, errwrap.Wrapf("Error decoding GetConfig response: {{err}}", err) + } + + return result, nil +} + +type UpdateConfigInput struct { + // DefaultNetwork is the network that docker containers are provisioned on. + DefaultNetwork string `json:"default_network"` +} + +// UpdateConfig updates configuration values for your account. +func (client *ConfigClient) UpdateConfig(ctx context.Context, input *UpdateConfigInput) (*Config, error) { + path := fmt.Sprintf("/%s/config", client.accountName) + respReader, err := client.executeRequest(ctx, http.MethodPut, path, input) + if respReader != nil { + defer respReader.Close() + } + if err != nil { + return nil, errwrap.Wrapf("Error executing UpdateConfig request: {{err}}", err) + } + + var result *Config + decoder := json.NewDecoder(respReader) + if err = decoder.Decode(&result); err != nil { + return nil, errwrap.Wrapf("Error decoding UpdateConfig response: {{err}}", err) + } + + return result, nil +} diff --git a/vendor/github.com/joyent/triton-go/datacenters.go b/vendor/github.com/joyent/triton-go/datacenters.go new file mode 100644 index 000000000..2834f77c2 --- /dev/null +++ b/vendor/github.com/joyent/triton-go/datacenters.go @@ -0,0 +1,93 @@ +package triton + +import ( + "encoding/json" + "errors" + "fmt" + "net/http" + "sort" + + "context" + "github.com/hashicorp/errwrap" +) + +type DataCentersClient struct { + *Client +} + +// DataCenters returns a c used for accessing functions pertaining +// to Datacenter functionality in the Triton API. +func (c *Client) Datacenters() *DataCentersClient { + return &DataCentersClient{c} +} + +type DataCenter struct { + Name string `json:"name"` + URL string `json:"url"` +} + +type ListDataCentersInput struct{} + +func (client *DataCentersClient) ListDataCenters(ctx context.Context, _ *ListDataCentersInput) ([]*DataCenter, error) { + path := fmt.Sprintf("/%s/datacenters", client.accountName) + respReader, err := client.executeRequest(ctx, http.MethodGet, path, nil) + if respReader != nil { + defer respReader.Close() + } + if err != nil { + return nil, errwrap.Wrapf("Error executing ListDatacenters request: {{err}}", err) + } + + var intermediate map[string]string + decoder := json.NewDecoder(respReader) + if err = decoder.Decode(&intermediate); err != nil { + return nil, errwrap.Wrapf("Error decoding ListDatacenters response: {{err}}", err) + } + + keys := make([]string, len(intermediate)) + i := 0 + for k := range intermediate { + keys[i] = k + i++ + } + sort.Strings(keys) + + result := make([]*DataCenter, len(intermediate)) + i = 0 + for _, key := range keys { + result[i] = &DataCenter{ + Name: key, + URL: intermediate[key], + } + i++ + } + + return result, nil +} + +type GetDataCenterInput struct { + Name string +} + +func (client *DataCentersClient) GetDataCenter(ctx context.Context, input *GetDataCenterInput) (*DataCenter, error) { + path := fmt.Sprintf("/%s/datacenters/%s", client.accountName, input.Name) + resp, err := client.executeRequestRaw(ctx, http.MethodGet, path, nil) + if err != nil { + return nil, errwrap.Wrapf("Error executing GetDatacenter request: {{err}}", err) + } + + if resp.StatusCode != http.StatusFound { + return nil, fmt.Errorf("Error executing GetDatacenter request: expected status code 302, got %s", + resp.StatusCode) + } + + location := resp.Header.Get("Location") + if location == "" { + return nil, errors.New("Error decoding GetDatacenter response: no Location header") + } + + return &DataCenter{ + Name: input.Name, + URL: location, + }, nil +} diff --git a/vendor/github.com/joyent/triton-go/errors.go b/vendor/github.com/joyent/triton-go/errors.go new file mode 100644 index 000000000..76d4a6254 --- /dev/null +++ b/vendor/github.com/joyent/triton-go/errors.go @@ -0,0 +1,126 @@ +package triton + +import ( + "fmt" + + "github.com/hashicorp/errwrap" +) + +// TritonError represents an error code and message along with +// the status code of the HTTP request which resulted in the error +// message. Error codes used by the Triton API are listed at +// https://apidocs.joyent.com/cloudapi/#cloudapi-http-responses +type TritonError struct { + StatusCode int + Code string `json:"code"` + Message string `json:"message"` +} + +// Error implements interface Error on the TritonError type. +func (e TritonError) Error() string { + return fmt.Sprintf("%s: %s", e.Code, e.Message) +} + +// IsBadRequest tests whether err wraps a TritonError with +// code BadRequest +func IsBadRequest(err error) bool { + return isSpecificError(err, "BadRequest") +} + +// IsInternalError tests whether err wraps a TritonError with +// code InternalError +func IsInternalError(err error) bool { + return isSpecificError(err, "InternalError") +} + +// IsInUseError tests whether err wraps a TritonError with +// code InUseError +func IsInUseError(err error) bool { + return isSpecificError(err, "InUseError") +} + +// IsInvalidArgument tests whether err wraps a TritonError with +// code InvalidArgument +func IsInvalidArgument(err error) bool { + return isSpecificError(err, "InvalidArgument") +} + +// IsInvalidCredentials tests whether err wraps a TritonError with +// code InvalidCredentials +func IsInvalidCredentials(err error) bool { + return isSpecificError(err, "InvalidCredentials") +} + +// IsInvalidHeader tests whether err wraps a TritonError with +// code InvalidHeader +func IsInvalidHeader(err error) bool { + return isSpecificError(err, "InvalidHeader") +} + +// IsInvalidVersion tests whether err wraps a TritonError with +// code InvalidVersion +func IsInvalidVersion(err error) bool { + return isSpecificError(err, "InvalidVersion") +} + +// IsMissingParameter tests whether err wraps a TritonError with +// code MissingParameter +func IsMissingParameter(err error) bool { + return isSpecificError(err, "MissingParameter") +} + +// IsNotAuthorized tests whether err wraps a TritonError with +// code NotAuthorized +func IsNotAuthorized(err error) bool { + return isSpecificError(err, "NotAuthorized") +} + +// IsRequestThrottled tests whether err wraps a TritonError with +// code RequestThrottled +func IsRequestThrottled(err error) bool { + return isSpecificError(err, "RequestThrottled") +} + +// IsRequestTooLarge tests whether err wraps a TritonError with +// code RequestTooLarge +func IsRequestTooLarge(err error) bool { + return isSpecificError(err, "RequestTooLarge") +} + +// IsRequestMoved tests whether err wraps a TritonError with +// code RequestMoved +func IsRequestMoved(err error) bool { + return isSpecificError(err, "RequestMoved") +} + +// IsResourceNotFound tests whether err wraps a TritonError with +// code ResourceNotFound +func IsResourceNotFound(err error) bool { + return isSpecificError(err, "ResourceNotFound") +} + +// IsUnknownError tests whether err wraps a TritonError with +// code UnknownError +func IsUnknownError(err error) bool { + return isSpecificError(err, "UnknownError") +} + +// isSpecificError checks whether the error represented by err wraps +// an underlying TritonError with code errorCode. +func isSpecificError(err error, errorCode string) bool { + if err == nil { + return false + } + + tritonErrorInterface := errwrap.GetType(err.(error), &TritonError{}) + if tritonErrorInterface == nil { + return false + } + + tritonErr := tritonErrorInterface.(*TritonError) + if tritonErr.Code == errorCode { + return true + } + + return false +} diff --git a/vendor/github.com/joyent/triton-go/fabrics.go b/vendor/github.com/joyent/triton-go/fabrics.go new file mode 100644 index 000000000..1d32b83ba --- /dev/null +++ b/vendor/github.com/joyent/triton-go/fabrics.go @@ -0,0 +1,234 @@ +package triton + +import ( + "encoding/json" + "fmt" + "net/http" + + "context" + "github.com/hashicorp/errwrap" +) + +type FabricsClient struct { + *Client +} + +// Fabrics returns a client used for accessing functions pertaining to +// Fabric functionality in the Triton API. +func (c *Client) Fabrics() *FabricsClient { + return &FabricsClient{c} +} + +type FabricVLAN struct { + Name string `json:"name"` + ID int `json:"vlan_id"` + Description string `json:"description"` +} + +type ListFabricVLANsInput struct{} + +func (client *FabricsClient) ListFabricVLANs(ctx context.Context, _ *ListFabricVLANsInput) ([]*FabricVLAN, error) { + path := fmt.Sprintf("/%s/fabrics/default/vlans", client.accountName) + respReader, err := client.executeRequest(ctx, http.MethodGet, path, nil) + if respReader != nil { + defer respReader.Close() + } + if err != nil { + return nil, errwrap.Wrapf("Error executing ListFabricVLANs request: {{err}}", err) + } + + var result []*FabricVLAN + decoder := json.NewDecoder(respReader) + if err = decoder.Decode(&result); err != nil { + return nil, errwrap.Wrapf("Error decoding ListFabricVLANs response: {{err}}", err) + } + + return result, nil +} + +type CreateFabricVLANInput struct { + Name string `json:"name"` + ID int `json:"vlan_id"` + Description string `json:"description"` +} + +func (client *FabricsClient) CreateFabricVLAN(ctx context.Context, input *CreateFabricVLANInput) (*FabricVLAN, error) { + path := fmt.Sprintf("/%s/fabrics/default/vlans", client.accountName) + respReader, err := client.executeRequest(ctx, http.MethodPost, path, input) + if respReader != nil { + defer respReader.Close() + } + if err != nil { + return nil, errwrap.Wrapf("Error executing CreateFabricVLAN request: {{err}}", err) + } + + var result *FabricVLAN + decoder := json.NewDecoder(respReader) + if err = decoder.Decode(&result); err != nil { + return nil, errwrap.Wrapf("Error decoding CreateFabricVLAN response: {{err}}", err) + } + + return result, nil +} + +type UpdateFabricVLANInput struct { + ID int `json:"-"` + Name string `json:"name"` + Description string `json:"description"` +} + +func (client *FabricsClient) UpdateFabricVLAN(ctx context.Context, input *UpdateFabricVLANInput) (*FabricVLAN, error) { + path := fmt.Sprintf("/%s/fabrics/default/vlans/%d", client.accountName, input.ID) + respReader, err := client.executeRequest(ctx, http.MethodPut, path, input) + if respReader != nil { + defer respReader.Close() + } + if err != nil { + return nil, errwrap.Wrapf("Error executing UpdateFabricVLAN request: {{err}}", err) + } + + var result *FabricVLAN + decoder := json.NewDecoder(respReader) + if err = decoder.Decode(&result); err != nil { + return nil, errwrap.Wrapf("Error decoding UpdateFabricVLAN response: {{err}}", err) + } + + return result, nil +} + +type GetFabricVLANInput struct { + ID int `json:"-"` +} + +func (client *FabricsClient) GetFabricVLAN(ctx context.Context, input *GetFabricVLANInput) (*FabricVLAN, error) { + path := fmt.Sprintf("/%s/fabrics/default/vlans/%d", client.accountName, input.ID) + respReader, err := client.executeRequest(ctx, http.MethodGet, path, nil) + if respReader != nil { + defer respReader.Close() + } + if err != nil { + return nil, errwrap.Wrapf("Error executing GetFabricVLAN request: {{err}}", err) + } + + var result *FabricVLAN + decoder := json.NewDecoder(respReader) + if err = decoder.Decode(&result); err != nil { + return nil, errwrap.Wrapf("Error decoding GetFabricVLAN response: {{err}}", err) + } + + return result, nil +} + +type DeleteFabricVLANInput struct { + ID int `json:"-"` +} + +func (client *FabricsClient) DeleteFabricVLAN(ctx context.Context, input *DeleteFabricVLANInput) error { + path := fmt.Sprintf("/%s/fabrics/default/vlans/%d", client.accountName, input.ID) + respReader, err := client.executeRequest(ctx, http.MethodDelete, path, nil) + if respReader != nil { + defer respReader.Close() + } + if err != nil { + return errwrap.Wrapf("Error executing DeleteFabricVLAN request: {{err}}", err) + } + + return nil +} + +type ListFabricNetworksInput struct { + FabricVLANID int `json:"-"` +} + +func (client *FabricsClient) ListFabricNetworks(ctx context.Context, input *ListFabricNetworksInput) ([]*Network, error) { + path := fmt.Sprintf("/%s/fabrics/default/vlans/%d/networks", client.accountName, input.FabricVLANID) + respReader, err := client.executeRequest(ctx, http.MethodGet, path, nil) + if respReader != nil { + defer respReader.Close() + } + if err != nil { + return nil, errwrap.Wrapf("Error executing ListFabricNetworks request: {{err}}", err) + } + + var result []*Network + decoder := json.NewDecoder(respReader) + if err = decoder.Decode(&result); err != nil { + return nil, errwrap.Wrapf("Error decoding ListFabricNetworks response: {{err}}", err) + } + + return result, nil +} + +type CreateFabricNetworkInput struct { + FabricVLANID int `json:"-"` + Name string `json:"name"` + Description string `json:"description"` + Subnet string `json:"subnet"` + ProvisionStartIP string `json:"provision_start_ip"` + ProvisionEndIP string `json:"provision_end_ip"` + Gateway string `json:"gateway"` + Resolvers []string `json:"resolvers"` + Routes map[string]string `json:"routes"` + InternetNAT bool `json:"internet_nat"` +} + +func (client *FabricsClient) CreateFabricNetwork(ctx context.Context, input *CreateFabricNetworkInput) (*Network, error) { + path := fmt.Sprintf("/%s/fabrics/default/vlans/%d/networks", client.accountName, input.FabricVLANID) + respReader, err := client.executeRequest(ctx, http.MethodPost, path, input) + if respReader != nil { + defer respReader.Close() + } + if err != nil { + return nil, errwrap.Wrapf("Error executing CreateFabricNetwork request: {{err}}", err) + } + + var result *Network + decoder := json.NewDecoder(respReader) + if err = decoder.Decode(&result); err != nil { + return nil, errwrap.Wrapf("Error decoding CreateFabricNetwork response: {{err}}", err) + } + + return result, nil +} + +type GetFabricNetworkInput struct { + FabricVLANID int `json:"-"` + NetworkID string `json:"-"` +} + +func (client *FabricsClient) GetFabricNetwork(ctx context.Context, input *GetFabricNetworkInput) (*Network, error) { + path := fmt.Sprintf("/%s/fabrics/default/vlans/%d/networks/%s", client.accountName, input.FabricVLANID, input.NetworkID) + respReader, err := client.executeRequest(ctx, http.MethodGet, path, nil) + if respReader != nil { + defer respReader.Close() + } + if err != nil { + return nil, errwrap.Wrapf("Error executing GetFabricNetwork request: {{err}}", err) + } + + var result *Network + decoder := json.NewDecoder(respReader) + if err = decoder.Decode(&result); err != nil { + return nil, errwrap.Wrapf("Error decoding GetFabricNetwork response: {{err}}", err) + } + + return result, nil +} + +type DeleteFabricNetworkInput struct { + FabricVLANID int `json:"-"` + NetworkID string `json:"-"` +} + +func (client *FabricsClient) DeleteFabricNetwork(ctx context.Context, input *DeleteFabricNetworkInput) error { + path := fmt.Sprintf("/%s/fabrics/default/vlans/%d/networks/%s", client.accountName, input.FabricVLANID, input.NetworkID) + respReader, err := client.executeRequest(ctx, http.MethodDelete, path, nil) + if respReader != nil { + defer respReader.Close() + } + if err != nil { + return errwrap.Wrapf("Error executing DeleteFabricNetwork request: {{err}}", err) + } + + return nil +} diff --git a/vendor/github.com/joyent/triton-go/firewall.go b/vendor/github.com/joyent/triton-go/firewall.go new file mode 100644 index 000000000..a3de9ccf6 --- /dev/null +++ b/vendor/github.com/joyent/triton-go/firewall.go @@ -0,0 +1,219 @@ +package triton + +import ( + "context" + "encoding/json" + "fmt" + "net/http" + + "github.com/hashicorp/errwrap" +) + +type FirewallClient struct { + *Client +} + +// Firewall returns a client used for accessing functions pertaining to +// firewall functionality in the Triton API. +func (c *Client) Firewall() *FirewallClient { + return &FirewallClient{c} +} + +// FirewallRule represents a firewall rule +type FirewallRule struct { + // ID is a unique identifier for this rule + ID string `json:"id"` + + // Enabled indicates if the rule is enabled + Enabled bool `json:"enabled"` + + // Rule is the firewall rule text + Rule string `json:"rule"` + + // Global indicates if the rule is global. Optional. + Global bool `json:"global"` + + // Description is a human-readable description for the rule. Optional + Description string `json:"description"` +} + +type ListFirewallRulesInput struct{} + +func (client *FirewallClient) ListFirewallRules(ctx context.Context, _ *ListFirewallRulesInput) ([]*FirewallRule, error) { + path := fmt.Sprintf("/%s/fwrules", client.accountName) + respReader, err := client.executeRequest(ctx, http.MethodGet, path, nil) + if respReader != nil { + defer respReader.Close() + } + if err != nil { + return nil, errwrap.Wrapf("Error executing ListFirewallRules request: {{err}}", err) + } + + var result []*FirewallRule + decoder := json.NewDecoder(respReader) + if err = decoder.Decode(&result); err != nil { + return nil, errwrap.Wrapf("Error decoding ListFirewallRules response: {{err}}", err) + } + + return result, nil +} + +type GetFirewallRuleInput struct { + ID string +} + +func (client *FirewallClient) GetFirewallRule(ctx context.Context, input *GetFirewallRuleInput) (*FirewallRule, error) { + path := fmt.Sprintf("/%s/fwrules/%s", client.accountName, input.ID) + respReader, err := client.executeRequest(ctx, http.MethodGet, path, nil) + if respReader != nil { + defer respReader.Close() + } + if err != nil { + return nil, errwrap.Wrapf("Error executing GetFirewallRule request: {{err}}", err) + } + + var result *FirewallRule + decoder := json.NewDecoder(respReader) + if err = decoder.Decode(&result); err != nil { + return nil, errwrap.Wrapf("Error decoding GetFirewallRule response: {{err}}", err) + } + + return result, nil +} + +type CreateFirewallRuleInput struct { + Enabled bool `json:"enabled"` + Rule string `json:"rule"` + Description string `json:"description"` +} + +func (client *FirewallClient) CreateFirewallRule(ctx context.Context, input *CreateFirewallRuleInput) (*FirewallRule, error) { + path := fmt.Sprintf("/%s/fwrules", client.accountName) + respReader, err := client.executeRequest(ctx, http.MethodPost, path, input) + if respReader != nil { + defer respReader.Close() + } + if err != nil { + return nil, errwrap.Wrapf("Error executing CreateFirewallRule request: {{err}}", err) + } + + var result *FirewallRule + decoder := json.NewDecoder(respReader) + if err = decoder.Decode(&result); err != nil { + return nil, errwrap.Wrapf("Error decoding CreateFirewallRule response: {{err}}", err) + } + + return result, nil +} + +type UpdateFirewallRuleInput struct { + ID string `json:"-"` + Enabled bool `json:"enabled"` + Rule string `json:"rule"` + Description string `json:"description"` +} + +func (client *FirewallClient) UpdateFirewallRule(ctx context.Context, input *UpdateFirewallRuleInput) (*FirewallRule, error) { + path := fmt.Sprintf("/%s/fwrules/%s", client.accountName, input.ID) + respReader, err := client.executeRequest(ctx, http.MethodPost, path, input) + if respReader != nil { + defer respReader.Close() + } + if err != nil { + return nil, errwrap.Wrapf("Error executing UpdateFirewallRule request: {{err}}", err) + } + + var result *FirewallRule + decoder := json.NewDecoder(respReader) + if err = decoder.Decode(&result); err != nil { + return nil, errwrap.Wrapf("Error decoding UpdateFirewallRule response: {{err}}", err) + } + + return result, nil +} + +type EnableFirewallRuleInput struct { + ID string `json:"-"` +} + +func (client *FirewallClient) EnableFirewallRule(ctx context.Context, input *EnableFirewallRuleInput) (*FirewallRule, error) { + path := fmt.Sprintf("/%s/fwrules/%s/enable", client.accountName, input.ID) + respReader, err := client.executeRequest(ctx, http.MethodPost, path, input) + if respReader != nil { + defer respReader.Close() + } + if err != nil { + return nil, errwrap.Wrapf("Error executing EnableFirewallRule request: {{err}}", err) + } + + var result *FirewallRule + decoder := json.NewDecoder(respReader) + if err = decoder.Decode(&result); err != nil { + return nil, errwrap.Wrapf("Error decoding EnableFirewallRule response: {{err}}", err) + } + + return result, nil +} + +type DisableFirewallRuleInput struct { + ID string `json:"-"` +} + +func (client *FirewallClient) DisableFirewallRule(ctx context.Context, input *DisableFirewallRuleInput) (*FirewallRule, error) { + path := fmt.Sprintf("/%s/fwrules/%s/disable", client.accountName, input.ID) + respReader, err := client.executeRequest(ctx, http.MethodPost, path, input) + if respReader != nil { + defer respReader.Close() + } + if err != nil { + return nil, errwrap.Wrapf("Error executing DisableFirewallRule request: {{err}}", err) + } + + var result *FirewallRule + decoder := json.NewDecoder(respReader) + if err = decoder.Decode(&result); err != nil { + return nil, errwrap.Wrapf("Error decoding DisableFirewallRule response: {{err}}", err) + } + + return result, nil +} + +type DeleteFirewallRuleInput struct { + ID string +} + +func (client *FirewallClient) DeleteFirewallRule(ctx context.Context, input *DeleteFirewallRuleInput) error { + path := fmt.Sprintf("/%s/fwrules/%s", client.accountName, input.ID) + respReader, err := client.executeRequest(ctx, http.MethodDelete, path, nil) + if respReader != nil { + defer respReader.Close() + } + if err != nil { + return errwrap.Wrapf("Error executing DeleteFirewallRule request: {{err}}", err) + } + + return nil +} + +type ListMachineFirewallRulesInput struct { + MachineID string +} + +func (client *FirewallClient) ListMachineFirewallRules(ctx context.Context, input *ListMachineFirewallRulesInput) ([]*FirewallRule, error) { + path := fmt.Sprintf("/%s/machines/%s/firewallrules", client.accountName, input.MachineID) + respReader, err := client.executeRequest(ctx, http.MethodGet, path, nil) + if respReader != nil { + defer respReader.Close() + } + if err != nil { + return nil, errwrap.Wrapf("Error executing ListMachineFirewallRules request: {{err}}", err) + } + + var result []*FirewallRule + decoder := json.NewDecoder(respReader) + if err = decoder.Decode(&result); err != nil { + return nil, errwrap.Wrapf("Error decoding ListFirewallRules response: {{err}}", err) + } + + return result, nil +} diff --git a/vendor/github.com/joyent/triton-go/images.go b/vendor/github.com/joyent/triton-go/images.go new file mode 100644 index 000000000..f6ab1fce9 --- /dev/null +++ b/vendor/github.com/joyent/triton-go/images.go @@ -0,0 +1,206 @@ +package triton + +import ( + "context" + "encoding/json" + "fmt" + "net/http" + "net/url" + "time" + + "github.com/hashicorp/errwrap" +) + +type ImagesClient struct { + *Client +} + +// Images returns a c used for accessing functions pertaining to +// Images functionality in the Triton API. +func (c *Client) Images() *ImagesClient { + return &ImagesClient{c} +} + +type ImageFile struct { + Compression string `json:"compression"` + SHA1 string `json:"sha1"` + Size int64 `json:"size"` +} + +type Image struct { + ID string `json:"id"` + Name string `json:"name"` + OS string `json:"os"` + Description string `json:"description"` + Version string `json:"version"` + Type string `json:"type"` + Requirements map[string]interface{} `json:"requirements"` + Homepage string `json:"homepage"` + Files []*ImageFile `json:"files"` + PublishedAt time.Time `json:"published_at"` + Owner string `json:"owner"` + Public bool `json:"public"` + State string `json:"state"` + Tags map[string]string `json:"tags"` + EULA string `json:"eula"` + ACL []string `json:"acl"` + Error TritonError `json:"error"` +} + +type ListImagesInput struct{} + +func (client *ImagesClient) ListImages(ctx context.Context, _ *ListImagesInput) ([]*Image, error) { + path := fmt.Sprintf("/%s/images", client.accountName) + respReader, err := client.executeRequest(ctx, http.MethodGet, path, nil) + if respReader != nil { + defer respReader.Close() + } + if err != nil { + return nil, errwrap.Wrapf("Error executing ListImages request: {{err}}", err) + } + + var result []*Image + decoder := json.NewDecoder(respReader) + if err = decoder.Decode(&result); err != nil { + return nil, errwrap.Wrapf("Error decoding ListImages response: {{err}}", err) + } + + return result, nil +} + +type GetImageInput struct { + ImageID string +} + +func (client *ImagesClient) GetImage(ctx context.Context, input *GetImageInput) (*Image, error) { + path := fmt.Sprintf("/%s/images/%s", client.accountName, input.ImageID) + respReader, err := client.executeRequest(ctx, http.MethodGet, path, nil) + if respReader != nil { + defer respReader.Close() + } + if err != nil { + return nil, errwrap.Wrapf("Error executing GetImage request: {{err}}", err) + } + + var result *Image + decoder := json.NewDecoder(respReader) + if err = decoder.Decode(&result); err != nil { + return nil, errwrap.Wrapf("Error decoding GetImage response: {{err}}", err) + } + + return result, nil +} + +type DeleteImageInput struct { + ImageID string +} + +func (client *ImagesClient) DeleteImage(ctx context.Context, input *DeleteImageInput) error { + path := fmt.Sprintf("/%s/images/%s", client.accountName, input.ImageID) + respReader, err := client.executeRequest(ctx, http.MethodDelete, path, nil) + if respReader != nil { + defer respReader.Close() + } + if err != nil { + return errwrap.Wrapf("Error executing DeleteKey request: {{err}}", err) + } + + return nil +} + +type ExportImageInput struct { + ImageID string + MantaPath string +} + +type MantaLocation struct { + MantaURL string `json:"manta_url"` + ImagePath string `json:"image_path"` + ManifestPath string `json:"manifest_path"` +} + +func (client *ImagesClient) ExportImage(ctx context.Context, input *ExportImageInput) (*MantaLocation, error) { + path := fmt.Sprintf("/%s/images/%s", client.accountName, input.ImageID) + query := &url.Values{} + query.Set("action", "export") + query.Set("manta_path", input.MantaPath) + + respReader, err := client.executeRequestURIParams(ctx, http.MethodGet, path, nil, query) + if respReader != nil { + defer respReader.Close() + } + if err != nil { + return nil, errwrap.Wrapf("Error executing GetImage request: {{err}}", err) + } + + var result *MantaLocation + decoder := json.NewDecoder(respReader) + if err = decoder.Decode(&result); err != nil { + return nil, errwrap.Wrapf("Error decoding GetImage response: {{err}}", err) + } + + return result, nil +} + +type CreateImageFromMachineInput struct { + MachineID string `json:"machine"` + Name string `json:"name"` + Version string `json:"version,omitempty"` + Description string `json:"description,omitempty"` + HomePage string `json:"homepage,omitempty"` + EULA string `json:"eula,omitempty"` + ACL []string `json:"acl,omitempty"` + Tags map[string]string `json:"tags,omitempty"` +} + +func (client *ImagesClient) CreateImageFromMachine(ctx context.Context, input *CreateImageFromMachineInput) (*Image, error) { + path := fmt.Sprintf("/%s/images", client.accountName) + respReader, err := client.executeRequest(ctx, http.MethodPost, path, input) + if respReader != nil { + defer respReader.Close() + } + if err != nil { + return nil, errwrap.Wrapf("Error executing CreateImageFromMachine request: {{err}}", err) + } + + var result *Image + decoder := json.NewDecoder(respReader) + if err = decoder.Decode(&result); err != nil { + return nil, errwrap.Wrapf("Error decoding CreateImageFromMachine response: {{err}}", err) + } + + return result, nil +} + +type UpdateImageInput struct { + ImageID string `json:"-"` + Name string `json:"name"` + Version string `json:"version,omitempty"` + Description string `json:"description,omitempty"` + HomePage string `json:"homepage,omitempty"` + EULA string `json:"eula,omitempty"` + ACL []string `json:"acl,omitempty"` + Tags map[string]string `json:"tags,omitempty"` +} + +func (client *ImagesClient) UpdateImage(ctx context.Context, input *UpdateImageInput) (*Image, error) { + path := fmt.Sprintf("/%s/images/%s", client.accountName, input.ImageID) + query := &url.Values{} + query.Set("action", "update") + + respReader, err := client.executeRequestURIParams(ctx, http.MethodPost, path, input, query) + if respReader != nil { + defer respReader.Close() + } + if err != nil { + return nil, errwrap.Wrapf("Error executing UpdateImage request: {{err}}", err) + } + + var result *Image + decoder := json.NewDecoder(respReader) + if err = decoder.Decode(&result); err != nil { + return nil, errwrap.Wrapf("Error decoding UpdateImage response: {{err}}", err) + } + + return result, nil +} diff --git a/vendor/github.com/joyent/triton-go/keys.go b/vendor/github.com/joyent/triton-go/keys.go new file mode 100644 index 000000000..001f020ee --- /dev/null +++ b/vendor/github.com/joyent/triton-go/keys.go @@ -0,0 +1,125 @@ +package triton + +import ( + "context" + "encoding/json" + "fmt" + "net/http" + + "github.com/hashicorp/errwrap" +) + +type KeysClient struct { + *Client +} + +// Keys returns a c used for accessing functions pertaining to +// SSH key functionality in the Triton API. +func (c *Client) Keys() *KeysClient { + return &KeysClient{c} +} + +// Key represents a public key +type Key struct { + // Name of the key + Name string `json:"name"` + + // Key fingerprint + Fingerprint string `json:"fingerprint"` + + // OpenSSH-formatted public key + Key string `json:"key"` +} + +type ListKeysInput struct{} + +// ListKeys lists all public keys we have on record for the specified +// account. +func (client *KeysClient) ListKeys(ctx context.Context, _ *ListKeysInput) ([]*Key, error) { + path := fmt.Sprintf("/%s/keys", client.accountName) + respReader, err := client.executeRequest(ctx, http.MethodGet, path, nil) + if respReader != nil { + defer respReader.Close() + } + if err != nil { + return nil, errwrap.Wrapf("Error executing ListKeys request: {{err}}", err) + } + + var result []*Key + decoder := json.NewDecoder(respReader) + if err = decoder.Decode(&result); err != nil { + return nil, errwrap.Wrapf("Error decoding ListKeys response: {{err}}", err) + } + + return result, nil +} + +type GetKeyInput struct { + KeyName string +} + +func (client *KeysClient) GetKey(ctx context.Context, input *GetKeyInput) (*Key, error) { + path := fmt.Sprintf("/%s/keys/%s", client.accountName, input.KeyName) + respReader, err := client.executeRequest(ctx, http.MethodGet, path, nil) + if respReader != nil { + defer respReader.Close() + } + if err != nil { + return nil, errwrap.Wrapf("Error executing GetKey request: {{err}}", err) + } + + var result *Key + decoder := json.NewDecoder(respReader) + if err = decoder.Decode(&result); err != nil { + return nil, errwrap.Wrapf("Error decoding GetKey response: {{err}}", err) + } + + return result, nil +} + +type DeleteKeyInput struct { + KeyName string +} + +func (client *KeysClient) DeleteKey(ctx context.Context, input *DeleteKeyInput) error { + path := fmt.Sprintf("/%s/keys/%s", client.accountName, input.KeyName) + respReader, err := client.executeRequest(ctx, http.MethodDelete, path, nil) + if respReader != nil { + defer respReader.Close() + } + if err != nil { + return errwrap.Wrapf("Error executing DeleteKey request: {{err}}", err) + } + + return nil +} + +// CreateKeyInput represents the option that can be specified +// when creating a new key. +type CreateKeyInput struct { + // Name of the key. Optional. + Name string `json:"name,omitempty"` + + // OpenSSH-formatted public key. + Key string `json:"key"` +} + +// CreateKey uploads a new OpenSSH key to Triton for use in HTTP signing and SSH. +func (client *KeysClient) CreateKey(ctx context.Context, input *CreateKeyInput) (*Key, error) { + path := fmt.Sprintf("/%s/keys", client.accountName) + respReader, err := client.executeRequest(ctx, http.MethodPost, path, input) + if respReader != nil { + defer respReader.Close() + } + if err != nil { + return nil, errwrap.Wrapf("Error executing CreateKey request: {{err}}", err) + } + + var result *Key + decoder := json.NewDecoder(respReader) + if err = decoder.Decode(&result); err != nil { + return nil, errwrap.Wrapf("Error decoding CreateKey response: {{err}}", err) + } + + return result, nil +} diff --git a/vendor/github.com/joyent/triton-go/machines.go b/vendor/github.com/joyent/triton-go/machines.go new file mode 100644 index 000000000..aba5a984a --- /dev/null +++ b/vendor/github.com/joyent/triton-go/machines.go @@ -0,0 +1,667 @@ +package triton + +import ( + "context" + "encoding/json" + "fmt" + "net/http" + "net/url" + "strings" + "time" + + "github.com/hashicorp/errwrap" +) + +type MachinesClient struct { + *Client +} + +// Machines returns a client used for accessing functions pertaining to +// machine functionality in the Triton API. +func (c *Client) Machines() *MachinesClient { + return &MachinesClient{c} +} + +const ( + machineCNSTagDisable = "triton.cns.disable" + machineCNSTagReversePTR = "triton.cns.reverse_ptr" + machineCNSTagServices = "triton.cns.services" +) + +// MachineCNS is a container for the CNS-specific attributes. In the API these +// values are embedded within a Machine's Tags attribute, however they are +// exposed to the caller as their native types. +type MachineCNS struct { + Disable *bool + ReversePTR *string + Services []string +} + +type Machine struct { + ID string `json:"id"` + Name string `json:"name"` + Type string `json:"type"` + Brand string `json:"brand"` + State string `json:"state"` + Image string `json:"image"` + Memory int `json:"memory"` + Disk int `json:"disk"` + Metadata map[string]string `json:"metadata"` + Tags map[string]string `json:"tags"` + Created time.Time `json:"created"` + Updated time.Time `json:"updated"` + Docker bool `json:"docker"` + IPs []string `json:"ips"` + Networks []string `json:"networks"` + PrimaryIP string `json:"primaryIp"` + FirewallEnabled bool `json:"firewall_enabled"` + ComputeNode string `json:"compute_node"` + Package string `json:"package"` + DomainNames []string `json:"dns_names"` + CNS MachineCNS +} + +// _Machine is a private facade over Machine that handles the necessary API +// overrides from VMAPI's machine endpoint(s). +type _Machine struct { + Machine + Tags map[string]interface{} `json:"tags"` +} + +type NIC struct { + IP string `json:"ip"` + MAC string `json:"mac"` + Primary bool `json:"primary"` + Netmask string `json:"netmask"` + Gateway string `json:"gateway"` + State string `json:"state"` + Network string `json:"network"` +} + +type GetMachineInput struct { + ID string +} + +func (gmi *GetMachineInput) Validate() error { + if gmi.ID == "" { + return fmt.Errorf("machine ID can not be empty") + } + + return nil +} + +func (client *MachinesClient) GetMachine(ctx context.Context, input *GetMachineInput) (*Machine, error) { + if err := input.Validate(); err != nil { + return nil, errwrap.Wrapf("unable to get machine: {{err}}", err) + } + + path := fmt.Sprintf("/%s/machines/%s", client.accountName, input.ID) + response, err := client.executeRequestRaw(ctx, http.MethodGet, path, nil) + if response != nil { + defer response.Body.Close() + } + if response.StatusCode == http.StatusNotFound || response.StatusCode == http.StatusGone { + return nil, &TritonError{ + StatusCode: response.StatusCode, + Code: "ResourceNotFound", + } + } + if err != nil { + return nil, errwrap.Wrapf("Error executing GetMachine request: {{err}}", + client.decodeError(response.StatusCode, response.Body)) + } + + var result *_Machine + decoder := json.NewDecoder(response.Body) + if err = decoder.Decode(&result); err != nil { + return nil, errwrap.Wrapf("Error decoding GetMachine response: {{err}}", err) + } + + native, err := result.toNative() + if err != nil { + return nil, errwrap.Wrapf("unable to convert API response for machines to native type: {{err}}", err) + } + + return native, nil +} + +type ListMachinesInput struct{} + +func (client *MachinesClient) ListMachines(ctx context.Context, _ *ListMachinesInput) ([]*Machine, error) { + path := fmt.Sprintf("/%s/machines", client.accountName) + response, err := client.executeRequestRaw(ctx, http.MethodGet, path, nil) + if response != nil { + defer response.Body.Close() + } + if response.StatusCode == http.StatusNotFound { + return nil, &TritonError{ + StatusCode: response.StatusCode, + Code: "ResourceNotFound", + } + } + if err != nil { + return nil, errwrap.Wrapf("Error executing ListMachines request: {{err}}", + client.decodeError(response.StatusCode, response.Body)) + } + + var results []*_Machine + decoder := json.NewDecoder(response.Body) + if err = decoder.Decode(&results); err != nil { + return nil, errwrap.Wrapf("Error decoding ListMachines response: {{err}}", err) + } + + machines := make([]*Machine, 0, len(results)) + for _, machineAPI := range results { + native, err := machineAPI.toNative() + if err != nil { + return nil, errwrap.Wrapf("unable to convert API response for machines to native type: {{err}}", err) + } + machines = append(machines, native) + } + return machines, nil +} + +type CreateMachineInput struct { + Name string + Package string + Image string + Networks []string + LocalityStrict bool + LocalityNear []string + LocalityFar []string + Metadata map[string]string + Tags map[string]string + FirewallEnabled bool + CNS MachineCNS +} + +func (input *CreateMachineInput) toAPI() map[string]interface{} { + const numExtraParams = 8 + result := make(map[string]interface{}, numExtraParams+len(input.Metadata)+len(input.Tags)) + + result["firewall_enabled"] = input.FirewallEnabled + + if input.Name != "" { + result["name"] = input.Name + } + + if input.Package != "" { + result["package"] = input.Package + } + + if input.Image != "" { + result["image"] = input.Image + } + + if len(input.Networks) > 0 { + result["networks"] = input.Networks + } + + locality := struct { + Strict bool `json:"strict"` + Near []string `json:"near,omitempty"` + Far []string `json:"far,omitempty"` + }{ + Strict: input.LocalityStrict, + Near: input.LocalityNear, + Far: input.LocalityFar, + } + result["locality"] = locality + for key, value := range input.Tags { + result[fmt.Sprintf("tag.%s", key)] = value + } + + // Deliberately clobber any user-specified Tags with the attributes from the + // CNS struct. + input.CNS.toTags(result) + + for key, value := range input.Metadata { + result[fmt.Sprintf("metadata.%s", key)] = value + } + + return result +} + +func (client *MachinesClient) CreateMachine(ctx context.Context, input *CreateMachineInput) (*Machine, error) { + path := fmt.Sprintf("/%s/machines", client.accountName) + respReader, err := client.executeRequest(ctx, http.MethodPost, path, input.toAPI()) + if respReader != nil { + defer respReader.Close() + } + if err != nil { + return nil, errwrap.Wrapf("Error executing CreateMachine request: {{err}}", err) + } + + var result *Machine + decoder := json.NewDecoder(respReader) + if err = decoder.Decode(&result); err != nil { + return nil, errwrap.Wrapf("Error decoding CreateMachine response: {{err}}", err) + } + + return result, nil +} + +type DeleteMachineInput struct { + ID string +} + +func (client *MachinesClient) DeleteMachine(ctx context.Context, input *DeleteMachineInput) error { + path := fmt.Sprintf("/%s/machines/%s", client.accountName, input.ID) + response, err := client.executeRequestRaw(ctx, http.MethodDelete, path, nil) + if response.Body != nil { + defer response.Body.Close() + } + if response.StatusCode == http.StatusNotFound || response.StatusCode == http.StatusGone { + return nil + } + if err != nil { + return errwrap.Wrapf("Error executing DeleteMachine request: {{err}}", + client.decodeError(response.StatusCode, response.Body)) + } + + return nil +} + +type DeleteMachineTagsInput struct { + ID string +} + +func (client *MachinesClient) DeleteMachineTags(ctx context.Context, input *DeleteMachineTagsInput) error { + path := fmt.Sprintf("/%s/machines/%s/tags", client.accountName, input.ID) + response, err := client.executeRequestRaw(ctx, http.MethodDelete, path, nil) + if response.Body != nil { + defer response.Body.Close() + } + if response.StatusCode == http.StatusNotFound { + return nil + } + if err != nil { + return errwrap.Wrapf("Error executing DeleteMachineTags request: {{err}}", + client.decodeError(response.StatusCode, response.Body)) + } + + return nil +} + +type DeleteMachineTagInput struct { + ID string + Key string +} + +func (client *MachinesClient) DeleteMachineTag(ctx context.Context, input *DeleteMachineTagInput) error { + path := fmt.Sprintf("/%s/machines/%s/tags/%s", client.accountName, input.ID, input.Key) + response, err := client.executeRequestRaw(ctx, http.MethodDelete, path, nil) + if response.Body != nil { + defer response.Body.Close() + } + if response.StatusCode == http.StatusNotFound { + return nil + } + if err != nil { + return errwrap.Wrapf("Error executing DeleteMachineTag request: {{err}}", + client.decodeError(response.StatusCode, response.Body)) + } + + return nil +} + +type RenameMachineInput struct { + ID string + Name string +} + +func (client *MachinesClient) RenameMachine(ctx context.Context, input *RenameMachineInput) error { + path := fmt.Sprintf("/%s/machines/%s", client.accountName, input.ID) + + params := &url.Values{} + params.Set("action", "rename") + params.Set("name", input.Name) + + respReader, err := client.executeRequestURIParams(ctx, http.MethodPost, path, nil, params) + if respReader != nil { + defer respReader.Close() + } + if err != nil { + return errwrap.Wrapf("Error executing RenameMachine request: {{err}}", err) + } + + return nil +} + +type ReplaceMachineTagsInput struct { + ID string + Tags map[string]string +} + +func (client *MachinesClient) ReplaceMachineTags(ctx context.Context, input *ReplaceMachineTagsInput) error { + path := fmt.Sprintf("/%s/machines/%s/tags", client.accountName, input.ID) + respReader, err := client.executeRequest(ctx, http.MethodPut, path, input.Tags) + if respReader != nil { + defer respReader.Close() + } + if err != nil { + return errwrap.Wrapf("Error executing ReplaceMachineTags request: {{err}}", err) + } + + return nil +} + +type AddMachineTagsInput struct { + ID string + Tags map[string]string +} + +func (client *MachinesClient) AddMachineTags(ctx context.Context, input *AddMachineTagsInput) error { + path := fmt.Sprintf("/%s/machines/%s/tags", client.accountName, input.ID) + respReader, err := client.executeRequest(ctx, http.MethodPost, path, input.Tags) + if respReader != nil { + defer respReader.Close() + } + if err != nil { + return errwrap.Wrapf("Error executing AddMachineTags request: {{err}}", err) + } + + return nil +} + +type GetMachineTagInput struct { + ID string + Key string +} + +func (client *MachinesClient) GetMachineTag(ctx context.Context, input *GetMachineTagInput) (string, error) { + path := fmt.Sprintf("/%s/machines/%s/tags/%s", client.accountName, input.ID, input.Key) + respReader, err := client.executeRequest(ctx, http.MethodGet, path, nil) + if respReader != nil { + defer respReader.Close() + } + if err != nil { + return "", errwrap.Wrapf("Error executing GetMachineTag request: {{err}}", err) + } + + var result string + decoder := json.NewDecoder(respReader) + if err = decoder.Decode(&result); err != nil { + return "", errwrap.Wrapf("Error decoding GetMachineTag response: {{err}}", err) + } + + return result, nil +} + +type ListMachineTagsInput struct { + ID string +} + +func (client *MachinesClient) ListMachineTags(ctx context.Context, input *ListMachineTagsInput) (map[string]string, error) { + path := fmt.Sprintf("/%s/machines/%s/tags", client.accountName, input.ID) + respReader, err := client.executeRequest(ctx, http.MethodGet, path, nil) + if respReader != nil { + defer respReader.Close() + } + if err != nil { + return nil, errwrap.Wrapf("Error executing ListMachineTags request: {{err}}", err) + } + + var result map[string]interface{} + decoder := json.NewDecoder(respReader) + if err = decoder.Decode(&result); err != nil { + return nil, errwrap.Wrapf("Error decoding ListMachineTags response: {{err}}", err) + } + + _, tags := machineTagsExtractMeta(result) + return tags, nil +} + +type UpdateMachineMetadataInput struct { + ID string + Metadata map[string]string +} + +func (client *MachinesClient) UpdateMachineMetadata(ctx context.Context, input *UpdateMachineMetadataInput) (map[string]string, error) { + path := fmt.Sprintf("/%s/machines/%s/tags", client.accountName, input.ID) + respReader, err := client.executeRequest(ctx, http.MethodPost, path, input.Metadata) + if respReader != nil { + defer respReader.Close() + } + if err != nil { + return nil, errwrap.Wrapf("Error executing UpdateMachineMetadata request: {{err}}", err) + } + + var result map[string]string + decoder := json.NewDecoder(respReader) + if err = decoder.Decode(&result); err != nil { + return nil, errwrap.Wrapf("Error decoding UpdateMachineMetadata response: {{err}}", err) + } + + return result, nil +} + +type ResizeMachineInput struct { + ID string + Package string +} + +func (client *MachinesClient) ResizeMachine(ctx context.Context, input *ResizeMachineInput) error { + path := fmt.Sprintf("/%s/machines/%s", client.accountName, input.ID) + + params := &url.Values{} + params.Set("action", "resize") + params.Set("package", input.Package) + + respReader, err := client.executeRequestURIParams(ctx, http.MethodPost, path, nil, params) + if respReader != nil { + defer respReader.Close() + } + if err != nil { + return errwrap.Wrapf("Error executing ResizeMachine request: {{err}}", err) + } + + return nil +} + +type EnableMachineFirewallInput struct { + ID string +} + +func (client *MachinesClient) EnableMachineFirewall(ctx context.Context, input *EnableMachineFirewallInput) error { + path := fmt.Sprintf("/%s/machines/%s", client.accountName, input.ID) + + params := &url.Values{} + params.Set("action", "enable_firewall") + + respReader, err := client.executeRequestURIParams(ctx, http.MethodPost, path, nil, params) + if respReader != nil { + defer respReader.Close() + } + if err != nil { + return errwrap.Wrapf("Error executing EnableMachineFirewall request: {{err}}", err) + } + + return nil +} + +type DisableMachineFirewallInput struct { + ID string +} + +func (client *MachinesClient) DisableMachineFirewall(ctx context.Context, input *DisableMachineFirewallInput) error { + path := fmt.Sprintf("/%s/machines/%s", client.accountName, input.ID) + + params := &url.Values{} + params.Set("action", "disable_firewall") + + respReader, err := client.executeRequestURIParams(ctx, http.MethodPost, path, nil, params) + if respReader != nil { + defer respReader.Close() + } + if err != nil { + return errwrap.Wrapf("Error executing DisableMachineFirewall request: {{err}}", err) + } + + return nil +} + +type ListNICsInput struct { + MachineID string +} + +func (client *MachinesClient) ListNICs(ctx context.Context, input *ListNICsInput) ([]*NIC, error) { + path := fmt.Sprintf("/%s/machines/%s/nics", client.accountName, input.MachineID) + respReader, err := client.executeRequest(ctx, http.MethodGet, path, nil) + if respReader != nil { + defer respReader.Close() + } + if err != nil { + return nil, errwrap.Wrapf("Error executing ListNICs request: {{err}}", err) + } + + var result []*NIC + decoder := json.NewDecoder(respReader) + if err = decoder.Decode(&result); err != nil { + return nil, errwrap.Wrapf("Error decoding ListNICs response: {{err}}", err) + } + + return result, nil +} + +type AddNICInput struct { + MachineID string `json:"-"` + Network string `json:"network"` +} + +func (client *MachinesClient) AddNIC(ctx context.Context, input *AddNICInput) (*NIC, error) { + path := fmt.Sprintf("/%s/machines/%s/nics", client.accountName, input.MachineID) + respReader, err := client.executeRequest(ctx, http.MethodPost, path, input) + if respReader != nil { + defer respReader.Close() + } + if err != nil { + return nil, errwrap.Wrapf("Error executing AddNIC request: {{err}}", err) + } + + var result *NIC + decoder := json.NewDecoder(respReader) + if err = decoder.Decode(&result); err != nil { + return nil, errwrap.Wrapf("Error decoding AddNIC response: {{err}}", err) + } + + return result, nil +} + +type RemoveNICInput struct { + MachineID string + MAC string +} + +func (client *MachinesClient) RemoveNIC(ctx context.Context, input *RemoveNICInput) error { + path := fmt.Sprintf("/%s/machines/%s/nics/%s", client.accountName, input.MachineID, input.MAC) + respReader, err := client.executeRequest(ctx, http.MethodDelete, path, nil) + if respReader != nil { + defer respReader.Close() + } + if err != nil { + return errwrap.Wrapf("Error executing RemoveNIC request: {{err}}", err) + } + + return nil +} + +type StopMachineInput struct { + MachineID string +} + +func (client *MachinesClient) StopMachine(ctx context.Context, input *StopMachineInput) error { + path := fmt.Sprintf("/%s/machines/%s", client.accountName, input.MachineID) + + params := &url.Values{} + params.Set("action", "stop") + + respReader, err := client.executeRequestURIParams(ctx, http.MethodPost, path, nil, params) + if respReader != nil { + defer respReader.Close() + } + if err != nil { + return errwrap.Wrapf("Error executing StopMachine request: {{err}}", err) + } + + return nil +} + +type StartMachineInput struct { + MachineID string +} + +func (client *MachinesClient) StartMachine(ctx context.Context, input *StartMachineInput) error { + path := fmt.Sprintf("/%s/machines/%s", client.accountName, input.MachineID) + + params := &url.Values{} + params.Set("action", "start") + + respReader, err := client.executeRequestURIParams(ctx, http.MethodPost, path, nil, params) + if respReader != nil { + defer respReader.Close() + } + if err != nil { + return errwrap.Wrapf("Error executing StartMachine request: {{err}}", err) + } + + return nil +} + +var reservedMachineCNSTags = map[string]struct{}{ + machineCNSTagDisable: {}, + machineCNSTagReversePTR: {}, + machineCNSTagServices: {}, +} + +// machineTagsExtractMeta() extracts all of the misc parameters from Tags and +// returns a clean CNS and Tags struct. +func machineTagsExtractMeta(tags map[string]interface{}) (MachineCNS, map[string]string) { + nativeCNS := MachineCNS{} + nativeTags := make(map[string]string, len(tags)) + for k, raw := range tags { + if _, found := reservedMachineCNSTags[k]; found { + switch k { + case machineCNSTagDisable: + b := raw.(bool) + nativeCNS.Disable = &b + case machineCNSTagReversePTR: + s := raw.(string) + nativeCNS.ReversePTR = &s + case machineCNSTagServices: + nativeCNS.Services = strings.Split(raw.(string), ",") + default: + // TODO(seanc@): should assert, logic fail + } + } else { + nativeTags[k] = raw.(string) + } + } + + return nativeCNS, nativeTags +} + +// toNative() exports a given _Machine (API representation) to its native object +// format. +func (api *_Machine) toNative() (*Machine, error) { + m := Machine(api.Machine) + m.CNS, m.Tags = machineTagsExtractMeta(api.Tags) + return &m, nil +} + +// toTags() injects its state information into a Tags map suitable for use to +// submit an API call to the vmapi machine endpoint +func (mcns *MachineCNS) toTags(m map[string]interface{}) { + if mcns.Disable != nil { + s := fmt.Sprintf("%t", mcns.Disable) + m[machineCNSTagDisable] = &s + } + + if mcns.ReversePTR != nil { + m[machineCNSTagReversePTR] = &mcns.ReversePTR + } + + if len(mcns.Services) > 0 { + m[machineCNSTagServices] = strings.Join(mcns.Services, ",") + } +} diff --git a/vendor/github.com/joyent/triton-go/networks.go b/vendor/github.com/joyent/triton-go/networks.go new file mode 100644 index 000000000..585a65e7c --- /dev/null +++ b/vendor/github.com/joyent/triton-go/networks.go @@ -0,0 +1,79 @@ +package triton + +import ( + "encoding/json" + "fmt" + "net/http" + + "context" + "github.com/hashicorp/errwrap" +) + +type NetworksClient struct { + *Client +} + +// Networks returns a c used for accessing functions pertaining to +// Network functionality in the Triton API. +func (c *Client) Networks() *NetworksClient { + return &NetworksClient{c} +} + +type Network struct { + Id string `json:"id"` + Name string `json:"name"` + Public bool `json:"public"` + Fabric bool `json:"fabric"` + Description string `json:"description"` + Subnet string `json:"subnet"` + ProvisioningStartIP string `json:"provision_start_ip"` + ProvisioningEndIP string `json:"provision_end_ip"` + Gateway string `json:"gateway"` + Resolvers []string `json:"resolvers"` + Routes map[string]string `json:"routes"` + InternetNAT bool `json:"internet_nat"` +} + +type ListNetworksInput struct{} + +func (client *NetworksClient) ListNetworks(ctx context.Context, _ *ListNetworksInput) ([]*Network, error) { + path := fmt.Sprintf("/%s/networks", client.accountName) + respReader, err := client.executeRequest(ctx, http.MethodGet, path, nil) + if respReader != nil { + defer respReader.Close() + } + if err != nil { + return nil, errwrap.Wrapf("Error executing ListNetworks request: {{err}}", err) + } + + var result []*Network + decoder := json.NewDecoder(respReader) + if err = decoder.Decode(&result); err != nil { + return nil, errwrap.Wrapf("Error decoding ListNetworks response: {{err}}", err) + } + + return result, nil +} + +type GetNetworkInput struct { + ID string +} + +func (client *NetworksClient) GetNetwork(ctx context.Context, input *GetNetworkInput) (*Network, error) { + path := fmt.Sprintf("/%s/networks/%s", client.accountName, input.ID) + respReader, err := client.executeRequest(ctx, http.MethodGet, path, nil) + if respReader != nil { + defer respReader.Close() + } + if err != nil { + return nil, errwrap.Wrapf("Error executing GetNetwork request: {{err}}", err) + } + + var result *Network + decoder := json.NewDecoder(respReader) + if err = decoder.Decode(&result); err != nil { + return nil, errwrap.Wrapf("Error decoding GetNetwork response: {{err}}", err) + } + + return result, nil +} diff --git a/vendor/github.com/joyent/triton-go/packages.go b/vendor/github.com/joyent/triton-go/packages.go new file mode 100644 index 000000000..e8a4adbbe --- /dev/null +++ b/vendor/github.com/joyent/triton-go/packages.go @@ -0,0 +1,87 @@ +package triton + +import ( + "context" + "encoding/json" + "fmt" + "net/http" + + "github.com/hashicorp/errwrap" +) + +type PackagesClient struct { + *Client +} + +// Packages returns a c used for accessing functions pertaining +// to Packages functionality in the Triton API. +func (c *Client) Packages() *PackagesClient { + return &PackagesClient{c} +} + +type Package struct { + ID string `json:"id"` + Name string `json:"name"` + Memory int64 `json:"memory"` + Disk int64 `json:"disk"` + Swap int64 `json:"swap"` + LWPs int64 `json:"lwps"` + VCPUs int64 `json:"vcpus"` + Version string `json:"version"` + Group string `json:"group"` + Description string `json:"description"` + Default bool `json:"default"` +} + +type ListPackagesInput struct { + Name string `json:"name"` + Memory int64 `json:"memory"` + Disk int64 `json:"disk"` + Swap int64 `json:"swap"` + LWPs int64 `json:"lwps"` + VCPUs int64 `json:"vcpus"` + Version string `json:"version"` + Group string `json:"group"` +} + +func (client *PackagesClient) ListPackages(ctx context.Context, input *ListPackagesInput) ([]*Package, error) { + path := fmt.Sprintf("/%s/packages", client.accountName) + respReader, err := client.executeRequest(ctx, http.MethodGet, path, input) + if respReader != nil { + defer respReader.Close() + } + if err != nil { + return nil, errwrap.Wrapf("Error executing ListPackages request: {{err}}", err) + } + + var result []*Package + decoder := json.NewDecoder(respReader) + if err = decoder.Decode(&result); err != nil { + return nil, errwrap.Wrapf("Error decoding ListPackages response: {{err}}", err) + } + + return result, nil +} + +type GetPackageInput struct { + ID string +} + +func (client *PackagesClient) GetPackage(ctx context.Context, input *GetPackageInput) (*Package, error) { + path := fmt.Sprintf("/%s/packages/%s", client.accountName, input.ID) + respReader, err := client.executeRequest(ctx, http.MethodGet, path, nil) + if respReader != nil { + defer respReader.Close() + } + if err != nil { + return nil, errwrap.Wrapf("Error executing GetPackage request: {{err}}", err) + } + + var result *Package + decoder := json.NewDecoder(respReader) + if err = decoder.Decode(&result); err != nil { + return nil, errwrap.Wrapf("Error decoding GetPackage response: {{err}}", err) + } + + return result, nil +} diff --git a/vendor/github.com/joyent/triton-go/roles.go b/vendor/github.com/joyent/triton-go/roles.go new file mode 100644 index 000000000..a01fba6a9 --- /dev/null +++ b/vendor/github.com/joyent/triton-go/roles.go @@ -0,0 +1,164 @@ +package triton + +import ( + "context" + "encoding/json" + "fmt" + "net/http" + + "github.com/hashicorp/errwrap" +) + +type RolesClient struct { + *Client +} + +// Roles returns a c used for accessing functions pertaining +// to Role functionality in the Triton API. +func (c *Client) Roles() *RolesClient { + return &RolesClient{c} +} + +type Role struct { + ID string `json:"id"` + Name string `json:"name"` + Policies []string `json:"policies"` + Members []string `json:"policies"` + DefaultMembers []string `json:"default_members"` +} + +type ListRolesInput struct{} + +func (client *RolesClient) ListRoles(ctx context.Context, _ *ListRolesInput) ([]*Role, error) { + path := fmt.Sprintf("/%s/roles", client.accountName) + respReader, err := client.executeRequest(ctx, http.MethodGet, path, nil) + if respReader != nil { + defer respReader.Close() + } + if err != nil { + return nil, errwrap.Wrapf("Error executing ListRoles request: {{err}}", err) + } + + var result []*Role + decoder := json.NewDecoder(respReader) + if err = decoder.Decode(&result); err != nil { + return nil, errwrap.Wrapf("Error decoding ListRoles response: {{err}}", err) + } + + return result, nil +} + +type GetRoleInput struct { + RoleID string +} + +func (client *RolesClient) GetRole(ctx context.Context, input *GetRoleInput) (*Role, error) { + path := fmt.Sprintf("/%s/roles/%s", client.accountName, input.RoleID) + respReader, err := client.executeRequest(ctx, http.MethodGet, path, nil) + if respReader != nil { + defer respReader.Close() + } + if err != nil { + return nil, errwrap.Wrapf("Error executing GetRole request: {{err}}", err) + } + + var result *Role + decoder := json.NewDecoder(respReader) + if err = decoder.Decode(&result); err != nil { + return nil, errwrap.Wrapf("Error decoding GetRole response: {{err}}", err) + } + + return result, nil +} + +// CreateRoleInput represents the options that can be specified +// when creating a new role. +type CreateRoleInput struct { + // Name of the role. Required. + Name string `json:"name"` + + // This account's policies to be given to this role. Optional. + Policies []string `json:"policies,omitempty"` + + // This account's user logins to be added to this role. Optional. + Members []string `json:"members,omitempty"` + + // This account's user logins to be added to this role and have + // it enabled by default. Optional. + DefaultMembers []string `json:"default_members,omitempty"` +} + +func (client *RolesClient) CreateRole(ctx context.Context, input *CreateRoleInput) (*Role, error) { + path := fmt.Sprintf("/%s/roles", client.accountName) + respReader, err := client.executeRequest(ctx, http.MethodPost, path, input) + if respReader != nil { + defer respReader.Close() + } + if err != nil { + return nil, errwrap.Wrapf("Error executing CreateRole request: {{err}}", err) + } + + var result *Role + decoder := json.NewDecoder(respReader) + if err = decoder.Decode(&result); err != nil { + return nil, errwrap.Wrapf("Error decoding CreateRole response: {{err}}", err) + } + + return result, nil +} + +// UpdateRoleInput represents the options that can be specified +// when updating a role. Anything but ID can be modified. +type UpdateRoleInput struct { + // ID of the role to modify. Required. + RoleID string `json:"id"` + + // Name of the role. Required. + Name string `json:"name"` + + // This account's policies to be given to this role. Optional. + Policies []string `json:"policies,omitempty"` + + // This account's user logins to be added to this role. Optional. + Members []string `json:"members,omitempty"` + + // This account's user logins to be added to this role and have + // it enabled by default. Optional. + DefaultMembers []string `json:"default_members,omitempty"` +} + +func (client *RolesClient) UpdateRole(ctx context.Context, input *UpdateRoleInput) (*Role, error) { + path := fmt.Sprintf("/%s/roles/%s", client.accountName, input.RoleID) + respReader, err := client.executeRequest(ctx, http.MethodPost, path, input) + if respReader != nil { + defer respReader.Close() + } + if err != nil { + return nil, errwrap.Wrapf("Error executing UpdateRole request: {{err}}", err) + } + + var result *Role + decoder := json.NewDecoder(respReader) + if err = decoder.Decode(&result); err != nil { + return nil, errwrap.Wrapf("Error decoding UpdateRole response: {{err}}", err) + } + + return result, nil +} + +type DeleteRoleInput struct { + RoleID string +} + +func (client *RolesClient) DeleteRoles(ctx context.Context, input *DeleteRoleInput) error { + path := fmt.Sprintf("/%s/roles/%s", client.accountName, input.RoleID) + respReader, err := client.executeRequest(ctx, http.MethodDelete, path, nil) + if respReader != nil { + defer respReader.Close() + } + if err != nil { + return errwrap.Wrapf("Error executing DeleteRole request: {{err}}", err) + } + + return nil +} diff --git a/vendor/github.com/joyent/triton-go/services.go b/vendor/github.com/joyent/triton-go/services.go new file mode 100644 index 000000000..e220b2699 --- /dev/null +++ b/vendor/github.com/joyent/triton-go/services.go @@ -0,0 +1,65 @@ +package triton + +import ( + "context" + "encoding/json" + "fmt" + "net/http" + "sort" + + "github.com/hashicorp/errwrap" +) + +type ServicesClient struct { + *Client +} + +// Services returns a c used for accessing functions pertaining +// to Services functionality in the Triton API. +func (c *Client) Services() *ServicesClient { + return &ServicesClient{c} +} + +type Service struct { + Name string + Endpoint string +} + +type ListServicesInput struct{} + +func (client *ServicesClient) ListServices(ctx context.Context, _ *ListServicesInput) ([]*Service, error) { + path := fmt.Sprintf("/%s/services", client.accountName) + respReader, err := client.executeRequest(ctx, http.MethodGet, path, nil) + if respReader != nil { + defer respReader.Close() + } + if err != nil { + return nil, errwrap.Wrapf("Error executing ListServices request: {{err}}", err) + } + + var intermediate map[string]string + decoder := json.NewDecoder(respReader) + if err = decoder.Decode(&intermediate); err != nil { + return nil, errwrap.Wrapf("Error decoding ListServices response: {{err}}", err) + } + + keys := make([]string, len(intermediate)) + i := 0 + for k := range intermediate { + keys[i] = k + i++ + } + sort.Strings(keys) + + result := make([]*Service, len(intermediate)) + i = 0 + for _, key := range keys { + result[i] = &Service{ + Name: key, + Endpoint: intermediate[key], + } + i++ + } + + return result, nil +} diff --git a/vendor/github.com/mitchellh/mapstructure/decode_hooks.go b/vendor/github.com/mitchellh/mapstructure/decode_hooks.go index aa91f76ce..115ae67c1 100644 --- a/vendor/github.com/mitchellh/mapstructure/decode_hooks.go +++ b/vendor/github.com/mitchellh/mapstructure/decode_hooks.go @@ -72,7 +72,10 @@ func ComposeDecodeHookFunc(fs ...DecodeHookFunc) DecodeHookFunc { } // Modify the from kind to be correct with the new data - f = reflect.ValueOf(data).Type() + f = nil + if val := reflect.ValueOf(data); val.IsValid() { + f = val.Type() + } } return data, nil diff --git a/vendor/github.com/mitchellh/mapstructure/mapstructure.go b/vendor/github.com/mitchellh/mapstructure/mapstructure.go index 40be5116d..6dee0ef0a 100644 --- a/vendor/github.com/mitchellh/mapstructure/mapstructure.go +++ b/vendor/github.com/mitchellh/mapstructure/mapstructure.go @@ -1,5 +1,5 @@ // The mapstructure package exposes functionality to convert an -// abitrary map[string]interface{} into a native Go structure. +// arbitrary map[string]interface{} into a native Go structure. // // The Go structure can be arbitrarily complex, containing slices, // other structs, etc. and the decoder will properly decode nested @@ -8,6 +8,7 @@ package mapstructure import ( + "encoding/json" "errors" "fmt" "reflect" @@ -67,6 +68,10 @@ type DecoderConfig struct { // FALSE, false, False. Anything else is an error) // - empty array = empty map and vice versa // - negative numbers to overflowed uint values (base 10) + // - slice of maps to a merged map + // - single values are converted to slices if required. Each + // element is weakly decoded. For example: "4" can become []int{4} + // if the target type is an int slice. // WeaklyTypedInput bool @@ -200,7 +205,7 @@ func (d *Decoder) decode(name string, data interface{}, val reflect.Value) error d.config.DecodeHook, dataVal.Type(), val.Type(), data) if err != nil { - return err + return fmt.Errorf("error decoding '%s': %s", name, err) } } @@ -227,6 +232,8 @@ func (d *Decoder) decode(name string, data interface{}, val reflect.Value) error err = d.decodePtr(name, data, val) case reflect.Slice: err = d.decodeSlice(name, data, val) + case reflect.Func: + err = d.decodeFunc(name, data, val) default: // If we reached this point then we weren't able to decode it return fmt.Errorf("%s: unsupported type: %s", name, dataKind) @@ -245,6 +252,10 @@ func (d *Decoder) decode(name string, data interface{}, val reflect.Value) error // value to "data" of that type. func (d *Decoder) decodeBasic(name string, data interface{}, val reflect.Value) error { dataVal := reflect.ValueOf(data) + if !dataVal.IsValid() { + dataVal = reflect.Zero(val.Type()) + } + dataValType := dataVal.Type() if !dataValType.AssignableTo(val.Type()) { return fmt.Errorf( @@ -301,6 +312,7 @@ func (d *Decoder) decodeString(name string, data interface{}, val reflect.Value) func (d *Decoder) decodeInt(name string, data interface{}, val reflect.Value) error { dataVal := reflect.ValueOf(data) dataKind := getKind(dataVal) + dataType := dataVal.Type() switch { case dataKind == reflect.Int: @@ -322,6 +334,14 @@ func (d *Decoder) decodeInt(name string, data interface{}, val reflect.Value) er } else { return fmt.Errorf("cannot parse '%s' as int: %s", name, err) } + case dataType.PkgPath() == "encoding/json" && dataType.Name() == "Number": + jn := data.(json.Number) + i, err := jn.Int64() + if err != nil { + return fmt.Errorf( + "error decoding json.Number into %s: %s", name, err) + } + val.SetInt(i) default: return fmt.Errorf( "'%s' expected type '%s', got unconvertible type '%s'", @@ -408,6 +428,7 @@ func (d *Decoder) decodeBool(name string, data interface{}, val reflect.Value) e func (d *Decoder) decodeFloat(name string, data interface{}, val reflect.Value) error { dataVal := reflect.ValueOf(data) dataKind := getKind(dataVal) + dataType := dataVal.Type() switch { case dataKind == reflect.Int: @@ -429,6 +450,14 @@ func (d *Decoder) decodeFloat(name string, data interface{}, val reflect.Value) } else { return fmt.Errorf("cannot parse '%s' as float: %s", name, err) } + case dataType.PkgPath() == "encoding/json" && dataType.Name() == "Number": + jn := data.(json.Number) + i, err := jn.Float64() + if err != nil { + return fmt.Errorf( + "error decoding json.Number into %s: %s", name, err) + } + val.SetFloat(i) default: return fmt.Errorf( "'%s' expected type '%s', got unconvertible type '%s'", @@ -456,15 +485,30 @@ func (d *Decoder) decodeMap(name string, data interface{}, val reflect.Value) er // Check input type dataVal := reflect.Indirect(reflect.ValueOf(data)) if dataVal.Kind() != reflect.Map { - // Accept empty array/slice instead of an empty map in weakly typed mode - if d.config.WeaklyTypedInput && - (dataVal.Kind() == reflect.Slice || dataVal.Kind() == reflect.Array) && - dataVal.Len() == 0 { - val.Set(valMap) - return nil - } else { - return fmt.Errorf("'%s' expected a map, got '%s'", name, dataVal.Kind()) + // In weak mode, we accept a slice of maps as an input... + if d.config.WeaklyTypedInput { + switch dataVal.Kind() { + case reflect.Array, reflect.Slice: + // Special case for BC reasons (covered by tests) + if dataVal.Len() == 0 { + val.Set(valMap) + return nil + } + + for i := 0; i < dataVal.Len(); i++ { + err := d.decode( + fmt.Sprintf("%s[%d]", name, i), + dataVal.Index(i).Interface(), val) + if err != nil { + return err + } + } + + return nil + } } + + return fmt.Errorf("'%s' expected a map, got '%s'", name, dataVal.Kind()) } // Accumulate errors @@ -507,7 +551,12 @@ func (d *Decoder) decodePtr(name string, data interface{}, val reflect.Value) er // into that. Then set the value of the pointer to this type. valType := val.Type() valElemType := valType.Elem() - realVal := reflect.New(valElemType) + + realVal := val + if realVal.IsNil() || d.config.ZeroFields { + realVal = reflect.New(valElemType) + } + if err := d.decode(name, data, reflect.Indirect(realVal)); err != nil { return err } @@ -516,6 +565,19 @@ func (d *Decoder) decodePtr(name string, data interface{}, val reflect.Value) er return nil } +func (d *Decoder) decodeFunc(name string, data interface{}, val reflect.Value) error { + // Create an element of the concrete (non pointer) type and decode + // into that. Then set the value of the pointer to this type. + dataVal := reflect.Indirect(reflect.ValueOf(data)) + if val.Type() != dataVal.Type() { + return fmt.Errorf( + "'%s' expected type '%s', got unconvertible type '%s'", + name, val.Type(), dataVal.Type()) + } + val.Set(dataVal) + return nil +} + func (d *Decoder) decodeSlice(name string, data interface{}, val reflect.Value) error { dataVal := reflect.Indirect(reflect.ValueOf(data)) dataValKind := dataVal.Kind() @@ -523,26 +585,44 @@ func (d *Decoder) decodeSlice(name string, data interface{}, val reflect.Value) valElemType := valType.Elem() sliceType := reflect.SliceOf(valElemType) - // Check input type - if dataValKind != reflect.Array && dataValKind != reflect.Slice { - // Accept empty map instead of array/slice in weakly typed mode - if d.config.WeaklyTypedInput && dataVal.Kind() == reflect.Map && dataVal.Len() == 0 { - val.Set(reflect.MakeSlice(sliceType, 0, 0)) - return nil - } else { + valSlice := val + if valSlice.IsNil() || d.config.ZeroFields { + // Check input type + if dataValKind != reflect.Array && dataValKind != reflect.Slice { + if d.config.WeaklyTypedInput { + switch { + // Empty maps turn into empty slices + case dataValKind == reflect.Map: + if dataVal.Len() == 0 { + val.Set(reflect.MakeSlice(sliceType, 0, 0)) + return nil + } + + // All other types we try to convert to the slice type + // and "lift" it into it. i.e. a string becomes a string slice. + default: + // Just re-try this function with data as a slice. + return d.decodeSlice(name, []interface{}{data}, val) + } + } + return fmt.Errorf( "'%s': source data must be an array or slice, got %s", name, dataValKind) - } - } - // Make a new slice to hold our result, same size as the original data. - valSlice := reflect.MakeSlice(sliceType, dataVal.Len(), dataVal.Len()) + } + + // Make a new slice to hold our result, same size as the original data. + valSlice = reflect.MakeSlice(sliceType, dataVal.Len(), dataVal.Len()) + } // Accumulate any errors errors := make([]string, 0) for i := 0; i < dataVal.Len(); i++ { currentData := dataVal.Index(i).Interface() + for valSlice.Len() <= i { + valSlice = reflect.Append(valSlice, reflect.Zero(valElemType)) + } currentField := valSlice.Index(i) fieldName := fmt.Sprintf("%s[%d]", name, i) @@ -607,17 +687,10 @@ func (d *Decoder) decodeStruct(name string, data interface{}, val reflect.Value) structs = structs[1:] structType := structVal.Type() + for i := 0; i < structType.NumField(); i++ { fieldType := structType.Field(i) - - if fieldType.Anonymous { - fieldKind := fieldType.Type.Kind() - if fieldKind != reflect.Struct { - errors = appendErrors(errors, - fmt.Errorf("%s: unsupported type: %s", fieldType.Name, fieldKind)) - continue - } - } + fieldKind := fieldType.Type.Kind() // If "squash" is specified in the tag, we squash the field down. squash := false @@ -630,7 +703,12 @@ func (d *Decoder) decodeStruct(name string, data interface{}, val reflect.Value) } if squash { - structs = append(structs, val.FieldByName(fieldType.Name)) + if fieldKind != reflect.Struct { + errors = appendErrors(errors, + fmt.Errorf("%s: unsupported type for squash: %s", fieldType.Name, fieldKind)) + } else { + structs = append(structs, val.FieldByName(fieldType.Name)) + } continue } @@ -653,7 +731,7 @@ func (d *Decoder) decodeStruct(name string, data interface{}, val reflect.Value) if !rawMapVal.IsValid() { // Do a slower search by iterating over each key and // doing case-insensitive search. - for dataValKey, _ := range dataValKeys { + for dataValKey := range dataValKeys { mK, ok := dataValKey.Interface().(string) if !ok { // Not a string key @@ -701,7 +779,7 @@ func (d *Decoder) decodeStruct(name string, data interface{}, val reflect.Value) if d.config.ErrorUnused && len(dataValKeysUnused) > 0 { keys := make([]string, 0, len(dataValKeysUnused)) - for rawKey, _ := range dataValKeysUnused { + for rawKey := range dataValKeysUnused { keys = append(keys, rawKey.(string)) } sort.Strings(keys) @@ -716,7 +794,7 @@ func (d *Decoder) decodeStruct(name string, data interface{}, val reflect.Value) // Add the unused keys to the list of unused keys if we're tracking metadata if d.config.Metadata != nil { - for rawKey, _ := range dataValKeysUnused { + for rawKey := range dataValKeysUnused { key := rawKey.(string) if name != "" { key = fmt.Sprintf("%s.%s", name, key) diff --git a/vendor/github.com/ovh/go-ovh/LICENSE b/vendor/github.com/ovh/go-ovh/LICENSE new file mode 100644 index 000000000..d847c8afb --- /dev/null +++ b/vendor/github.com/ovh/go-ovh/LICENSE @@ -0,0 +1,26 @@ +Copyright (c) 2015-2017, OVH SAS. +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. + * Neither the name of OVH SAS nor the + names of its contributors may be used to endorse or promote products + derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY OVH SAS 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 OVH SAS AND 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/ovh/go-ovh/ovh/configuration.go b/vendor/github.com/ovh/go-ovh/ovh/configuration.go new file mode 100644 index 000000000..e7dbb7c69 --- /dev/null +++ b/vendor/github.com/ovh/go-ovh/ovh/configuration.go @@ -0,0 +1,123 @@ +package ovh + +import ( + "fmt" + "os" + "os/user" + "path/filepath" + "strings" + + "gopkg.in/ini.v1" +) + +// Use variables for easier test overload +var ( + systemConfigPath = "/etc/ovh.conf" + userConfigPath = "/.ovh.conf" // prefixed with homeDir + localConfigPath = "./ovh.conf" +) + +// currentUserHome attempts to get current user's home directory +func currentUserHome() (string, error) { + usr, err := user.Current() + if err != nil { + return "", err + } + return usr.HomeDir, nil +} + +// appendConfigurationFile only if it exists. We need to do this because +// ini package will fail to load configuration at all if a configuration +// file is missing. This is racy, but better than always failing. +func appendConfigurationFile(cfg *ini.File, path string) { + if file, err := os.Open(path); err == nil { + file.Close() + cfg.Append(path) + } +} + +// loadConfig loads client configuration from params, environments or configuration +// files (by order of decreasing precedence). +// +// loadConfig will check OVH_CONSUMER_KEY, OVH_APPLICATION_KEY, OVH_APPLICATION_SECRET +// and OVH_ENDPOINT environment variables. If any is present, it will take precedence +// over any configuration from file. +// +// Configuration files are ini files. They share the same format as python-ovh, +// node-ovh, php-ovh and all other wrappers. If any wrapper is configured, all +// can re-use the same configuration. loadConfig will check for configuration in: +// +// - ./ovh.conf +// - $HOME/.ovh.conf +// - /etc/ovh.conf +// +func (c *Client) loadConfig(endpointName string) error { + // Load configuration files by order of increasing priority. All configuration + // files are optional. Only load file from user home if home could be resolve + cfg := ini.Empty() + appendConfigurationFile(cfg, systemConfigPath) + if home, err := currentUserHome(); err == nil { + userConfigFullPath := filepath.Join(home, userConfigPath) + appendConfigurationFile(cfg, userConfigFullPath) + } + appendConfigurationFile(cfg, localConfigPath) + + // Canonicalize configuration + if endpointName == "" { + endpointName = getConfigValue(cfg, "default", "endpoint", "ovh-eu") + } + + if c.AppKey == "" { + c.AppKey = getConfigValue(cfg, endpointName, "application_key", "") + } + + if c.AppSecret == "" { + c.AppSecret = getConfigValue(cfg, endpointName, "application_secret", "") + } + + if c.ConsumerKey == "" { + c.ConsumerKey = getConfigValue(cfg, endpointName, "consumer_key", "") + } + + // Load real endpoint URL by name. If endpoint contains a '/', consider it as a URL + if strings.Contains(endpointName, "/") { + c.endpoint = endpointName + } else { + c.endpoint = Endpoints[endpointName] + } + + // If we still have no valid endpoint, AppKey or AppSecret, return an error + if c.endpoint == "" { + return fmt.Errorf("Unknown endpoint '%s'. Consider checking 'Endpoints' list of using an URL.", endpointName) + } + if c.AppKey == "" { + return fmt.Errorf("Missing application key. Please check your configuration or consult the documentation to create one.") + } + if c.AppSecret == "" { + return fmt.Errorf("Missing application secret. Please check your configuration or consult the documentation to create one.") + } + + return nil +} + +// getConfigValue returns the value of OVH_ or ``name`` value from ``section``. If +// the value could not be read from either env or any configuration files, return 'def' +func getConfigValue(cfg *ini.File, section, name, def string) string { + // Attempt to load from environment + fromEnv := os.Getenv("OVH_" + strings.ToUpper(name)) + if len(fromEnv) > 0 { + return fromEnv + } + + // Attempt to load from configuration + fromSection := cfg.Section(section) + if fromSection == nil { + return def + } + + fromSectionKey := fromSection.Key(name) + if fromSectionKey == nil { + return def + } + return fromSectionKey.String() +} diff --git a/vendor/github.com/ovh/go-ovh/ovh/consumer_key.go b/vendor/github.com/ovh/go-ovh/ovh/consumer_key.go new file mode 100644 index 000000000..716375511 --- /dev/null +++ b/vendor/github.com/ovh/go-ovh/ovh/consumer_key.go @@ -0,0 +1,113 @@ +package ovh + +import ( + "fmt" + "strings" +) + +// Map user friendly access level names to corresponding HTTP verbs +var ( + ReadOnly = []string{"GET"} + ReadWrite = []string{"GET", "POST", "PUT", "DELETE"} + ReadWriteSafe = []string{"GET", "POST", "PUT"} +) + +// AccessRule represents a method allowed for a path +type AccessRule struct { + // Allowed HTTP Method for the requested AccessRule. + // Can be set to GET/POST/PUT/DELETE. + Method string `json:"method"` + // Allowed path. + // Can be an exact string or a string with '*' char. + // Example : + // /me : only /me is authorized + // /* : all calls are authorized + Path string `json:"path"` +} + +// CkValidationState represents the response when asking a new consumerKey. +type CkValidationState struct { + // Consumer key, which need to be validated by customer. + ConsumerKey string `json:"consumerKey"` + // Current status, should be always "pendingValidation". + State string `json:"state"` + // URL to redirect user in order to log in. + ValidationURL string `json:"validationUrl"` +} + +// CkRequest represents the parameters to fill in order to ask a new +// consumerKey. +type CkRequest struct { + client *Client + AccessRules []AccessRule `json:"accessRules"` + Redirection string `json:"redirection,omitempty"` +} + +func (ck *CkValidationState) String() string { + return fmt.Sprintf("CK: %q\nStatus: %q\nValidation URL: %q\n", + ck.ConsumerKey, + ck.State, + ck.ValidationURL, + ) +} + +// NewCkRequest helps create a new ck request +func (c *Client) NewCkRequest() *CkRequest { + return &CkRequest{ + client: c, + AccessRules: []AccessRule{}, + } +} + +// NewCkRequestWithRedirection helps create a new ck request with a redirect URL +func (c *Client) NewCkRequestWithRedirection(redirection string) *CkRequest { + return &CkRequest{ + client: c, + AccessRules: []AccessRule{}, + Redirection: redirection, + } +} + +// AddRule adds a new rule to the ckRequest +func (ck *CkRequest) AddRule(method, path string) { + ck.AccessRules = append(ck.AccessRules, AccessRule{ + Method: method, + Path: path, + }) +} + +// AddRules adds grant requests on "path" for all methods. "ReadOnly", +// "ReadWrite" and "ReadWriteSafe" should be used for "methods" unless +// specific access are required. +func (ck *CkRequest) AddRules(methods []string, path string) { + for _, method := range methods { + ck.AddRule(method, path) + } + +} + +// AddRecursiveRules adds grant requests on "path" and "path/*", for all +// methods "ReadOnly", "ReadWrite" and "ReadWriteSafe" should be used for +// "methods" unless specific access are required. +func (ck *CkRequest) AddRecursiveRules(methods []string, path string) { + path = strings.TrimRight(path, "/") + + // Add rules. Skip base rule when requesting access to "/" + if path != "" { + ck.AddRules(methods, path) + } + ck.AddRules(methods, path+"/*") +} + +// Do executes the request. On success, set the consumer key in the client +// and return the URL the user needs to visit to validate the key +func (ck *CkRequest) Do() (*CkValidationState, error) { + state := CkValidationState{} + err := ck.client.PostUnAuth("/auth/credential", ck, &state) + + if err == nil { + ck.client.ConsumerKey = state.ConsumerKey + } + + return &state, err +} diff --git a/vendor/github.com/ovh/go-ovh/ovh/error.go b/vendor/github.com/ovh/go-ovh/ovh/error.go new file mode 100644 index 000000000..35e3608e9 --- /dev/null +++ b/vendor/github.com/ovh/go-ovh/ovh/error.go @@ -0,0 +1,17 @@ +package ovh + +import "fmt" + +// APIError represents an error that can occurred while calling the API. +type APIError struct { + // Error message. + Message string + // HTTP code. + Code int + // ID of the request + QueryID string +} + +func (err *APIError) Error() string { + return fmt.Sprintf("Error %d: %q", err.Code, err.Message) +} diff --git a/vendor/github.com/ovh/go-ovh/ovh/ovh.go b/vendor/github.com/ovh/go-ovh/ovh/ovh.go new file mode 100644 index 000000000..737c94470 --- /dev/null +++ b/vendor/github.com/ovh/go-ovh/ovh/ovh.go @@ -0,0 +1,331 @@ +// Package ovh provides a HTTP wrapper for the OVH API. +package ovh + +import ( + "bytes" + "crypto/sha1" + "encoding/json" + "errors" + "fmt" + "io/ioutil" + "net/http" + "strconv" + "sync" + "time" +) + +// DefaultTimeout api requests after 180s +const DefaultTimeout = 180 * time.Second + +// Endpoints +const ( + OvhEU = "https://eu.api.ovh.com/1.0" + OvhCA = "https://ca.api.ovh.com/1.0" + KimsufiEU = "https://eu.api.kimsufi.com/1.0" + KimsufiCA = "https://ca.api.kimsufi.com/1.0" + SoyoustartEU = "https://eu.api.soyoustart.com/1.0" + SoyoustartCA = "https://ca.api.soyoustart.com/1.0" + RunaboveCA = "https://api.runabove.com/1.0" +) + +// Endpoints conveniently maps endpoints names to their URI for external configuration +var Endpoints = map[string]string{ + "ovh-eu": OvhEU, + "ovh-ca": OvhCA, + "kimsufi-eu": KimsufiEU, + "kimsufi-ca": KimsufiCA, + "soyoustart-eu": SoyoustartEU, + "soyoustart-ca": SoyoustartCA, + "runabove-ca": RunaboveCA, +} + +// Errors +var ( + ErrAPIDown = errors.New("go-vh: the OVH API is down, it does't respond to /time anymore") +) + +// Client represents a client to call the OVH API +type Client struct { + // Self generated tokens. Create one by visiting + // https://eu.api.ovh.com/createApp/ + // AppKey holds the Application key + AppKey string + + // AppSecret holds the Application secret key + AppSecret string + + // ConsumerKey holds the user/app specific token. It must have been validated before use. + ConsumerKey string + + // API endpoint + endpoint string + + // Client is the underlying HTTP client used to run the requests. It may be overloaded but a default one is instanciated in ``NewClient`` by default. + Client *http.Client + + // Ensures that the timeDelta function is only ran once + // sync.Once would consider init done, even in case of error + // hence a good old flag + timeDeltaMutex *sync.Mutex + timeDeltaDone bool + timeDelta time.Duration + Timeout time.Duration +} + +// NewClient represents a new client to call the API +func NewClient(endpoint, appKey, appSecret, consumerKey string) (*Client, error) { + client := Client{ + AppKey: appKey, + AppSecret: appSecret, + ConsumerKey: consumerKey, + Client: &http.Client{}, + timeDeltaMutex: &sync.Mutex{}, + timeDeltaDone: false, + Timeout: time.Duration(DefaultTimeout), + } + + // Get and check the configuration + if err := client.loadConfig(endpoint); err != nil { + return nil, err + } + return &client, nil +} + +// NewEndpointClient will create an API client for specified +// endpoint and load all credentials from environment or +// configuration files +func NewEndpointClient(endpoint string) (*Client, error) { + return NewClient(endpoint, "", "", "") +} + +// NewDefaultClient will load all it's parameter from environment +// or configuration files +func NewDefaultClient() (*Client, error) { + return NewClient("", "", "", "") +} + +// +// High level helpers +// + +// Ping performs a ping to OVH API. +// In fact, ping is just a /auth/time call, in order to check if API is up. +func (c *Client) Ping() error { + _, err := c.getTime() + return err +} + +// TimeDelta represents the delay between the machine that runs the code and the +// OVH API. The delay shouldn't change, let's do it only once. +func (c *Client) TimeDelta() (time.Duration, error) { + return c.getTimeDelta() +} + +// Time returns time from the OVH API, by asking GET /auth/time. +func (c *Client) Time() (*time.Time, error) { + return c.getTime() +} + +// +// Common request wrappers +// + +// Get is a wrapper for the GET method +func (c *Client) Get(url string, resType interface{}) error { + return c.CallAPI("GET", url, nil, resType, true) +} + +// GetUnAuth is a wrapper for the unauthenticated GET method +func (c *Client) GetUnAuth(url string, resType interface{}) error { + return c.CallAPI("GET", url, nil, resType, false) +} + +// Post is a wrapper for the POST method +func (c *Client) Post(url string, reqBody, resType interface{}) error { + return c.CallAPI("POST", url, reqBody, resType, true) +} + +// PostUnAuth is a wrapper for the unauthenticated POST method +func (c *Client) PostUnAuth(url string, reqBody, resType interface{}) error { + return c.CallAPI("POST", url, reqBody, resType, false) +} + +// Put is a wrapper for the PUT method +func (c *Client) Put(url string, reqBody, resType interface{}) error { + return c.CallAPI("PUT", url, reqBody, resType, true) +} + +// PutUnAuth is a wrapper for the unauthenticated PUT method +func (c *Client) PutUnAuth(url string, reqBody, resType interface{}) error { + return c.CallAPI("PUT", url, reqBody, resType, false) +} + +// Delete is a wrapper for the DELETE method +func (c *Client) Delete(url string, resType interface{}) error { + return c.CallAPI("DELETE", url, nil, resType, true) +} + +// DeleteUnAuth is a wrapper for the unauthenticated DELETE method +func (c *Client) DeleteUnAuth(url string, resType interface{}) error { + return c.CallAPI("DELETE", url, nil, resType, false) +} + +// +// Low level API access +// + +// getResult check the response and unmarshals it into the response type if needed. +// Helper function, called from CallAPI. +func (c *Client) getResponse(response *http.Response, resType interface{}) error { + // Read all the response body + defer response.Body.Close() + body, err := ioutil.ReadAll(response.Body) + if err != nil { + return err + } + + // < 200 && >= 300 : API error + if response.StatusCode < http.StatusOK || response.StatusCode >= http.StatusMultipleChoices { + apiError := &APIError{Code: response.StatusCode} + if err = json.Unmarshal(body, apiError); err != nil { + return err + } + apiError.QueryID = response.Header.Get("X-Ovh-QueryID") + return apiError + } + + // Nothing to unmarshal + if len(body) == 0 || resType == nil { + return nil + } + + return json.Unmarshal(body, &resType) +} + +// timeDelta returns the time delta between the host and the remote API +func (c *Client) getTimeDelta() (time.Duration, error) { + + if !c.timeDeltaDone { + // Ensure only one thread is updating + c.timeDeltaMutex.Lock() + + // Did we wait ? Maybe no more needed + if !c.timeDeltaDone { + ovhTime, err := c.getTime() + if err != nil { + return 0, err + } + + c.timeDelta = time.Since(*ovhTime) + c.timeDeltaDone = true + } + c.timeDeltaMutex.Unlock() + } + + return c.timeDelta, nil +} + +// getTime t returns time from for a given api client endpoint +func (c *Client) getTime() (*time.Time, error) { + var timestamp int64 + + err := c.GetUnAuth("/auth/time", ×tamp) + if err != nil { + return nil, err + } + + serverTime := time.Unix(timestamp, 0) + return &serverTime, nil +} + +// getLocalTime is a function to be overwritten during the tests, it return the time +// on the the local machine +var getLocalTime = func() time.Time { + return time.Now() +} + +// getEndpointForSignature is a function to be overwritten during the tests, it returns a +// the endpoint +var getEndpointForSignature = func(c *Client) string { + return c.endpoint +} + +// CallAPI is the lowest level call helper. If needAuth is true, +// inject authentication headers and sign the request. +// +// Request signature is a sha1 hash on following fields, joined by '+': +// - applicationSecret (from Client instance) +// - consumerKey (from Client instance) +// - capitalized method (from arguments) +// - full request url, including any query string argument +// - full serialized request body +// - server current time (takes time delta into account) +// +// Call will automatically assemble the target url from the endpoint +// configured in the client instance and the path argument. If the reqBody +// argument is not nil, it will also serialize it as json and inject +// the required Content-Type header. +// +// If everyrthing went fine, unmarshall response into resType and return nil +// otherwise, return the error +func (c *Client) CallAPI(method, path string, reqBody, resType interface{}, needAuth bool) error { + var body []byte + var err error + + if reqBody != nil { + body, err = json.Marshal(reqBody) + if err != nil { + return err + } + } + + target := fmt.Sprintf("%s%s", c.endpoint, path) + req, err := http.NewRequest(method, target, bytes.NewReader(body)) + if err != nil { + return err + } + + // Inject headers + if body != nil { + req.Header.Add("Content-Type", "application/json;charset=utf-8") + } + req.Header.Add("X-Ovh-Application", c.AppKey) + req.Header.Add("Accept", "application/json") + + // Inject signature. Some methods do not need authentication, especially /time, + // /auth and some /order methods are actually broken if authenticated. + if needAuth { + timeDelta, err := c.TimeDelta() + if err != nil { + return err + } + + timestamp := getLocalTime().Add(-timeDelta).Unix() + + req.Header.Add("X-Ovh-Timestamp", strconv.FormatInt(timestamp, 10)) + req.Header.Add("X-Ovh-Consumer", c.ConsumerKey) + + h := sha1.New() + h.Write([]byte(fmt.Sprintf("%s+%s+%s+%s%s+%s+%d", + c.AppSecret, + c.ConsumerKey, + method, + getEndpointForSignature(c), + path, + body, + timestamp, + ))) + req.Header.Add("X-Ovh-Signature", fmt.Sprintf("$1$%x", h.Sum(nil))) + } + + // Send the request with requested timeout + c.Client.Timeout = c.Timeout + response, err := c.Client.Do(req) + + if err != nil { + return err + } + + // Unmarshal the result into the resType if possible + return c.getResponse(response, resType) +} diff --git a/vendor/github.com/paultyng/go-newrelic/api/alert_channels.go b/vendor/github.com/paultyng/go-newrelic/api/alert_channels.go index edb078c28..c4e6b632a 100644 --- a/vendor/github.com/paultyng/go-newrelic/api/alert_channels.go +++ b/vendor/github.com/paultyng/go-newrelic/api/alert_channels.go @@ -52,6 +52,7 @@ func (c *Client) ListAlertChannels() ([]AlertChannel, error) { return c.queryAlertChannels() } +// CreateAlertChannel allows you to create an alert channel with the specified data and links. func (c *Client) CreateAlertChannel(channel AlertChannel) (*AlertChannel, error) { // TODO: support attaching policy ID's here? // qs := map[string]string{ @@ -59,7 +60,7 @@ func (c *Client) CreateAlertChannel(channel AlertChannel) (*AlertChannel, error) // } if len(channel.Links.PolicyIDs) > 0 { - return nil, fmt.Errorf("You cannot create an alert channel with policy IDs, you must attach polidy IDs after creation.") + return nil, fmt.Errorf("cannot create an alert channel with policy IDs, you must attach polidy IDs after creation") } req := struct { @@ -80,6 +81,7 @@ func (c *Client) CreateAlertChannel(channel AlertChannel) (*AlertChannel, error) return &resp.Channels[0], nil } +// DeleteAlertChannel deletes the alert channel with the specified ID. func (c *Client) DeleteAlertChannel(id int) error { u := &url.URL{Path: fmt.Sprintf("/alerts_channels/%v.json", id)} _, err := c.Do("DELETE", u.String(), nil, nil) diff --git a/vendor/github.com/paultyng/go-newrelic/api/alert_conditions.go b/vendor/github.com/paultyng/go-newrelic/api/alert_conditions.go index 45c5a9f89..6dd0ad15e 100644 --- a/vendor/github.com/paultyng/go-newrelic/api/alert_conditions.go +++ b/vendor/github.com/paultyng/go-newrelic/api/alert_conditions.go @@ -41,6 +41,7 @@ func (c *Client) queryAlertConditions(policyID int) ([]AlertCondition, error) { return conditions, nil } +// GetAlertCondition gets information about an alert condition given an ID and policy ID. func (c *Client) GetAlertCondition(policyID int, id int) (*AlertCondition, error) { conditions, err := c.queryAlertConditions(policyID) if err != nil { @@ -61,6 +62,7 @@ func (c *Client) ListAlertConditions(policyID int) ([]AlertCondition, error) { return c.queryAlertConditions(policyID) } +// CreateAlertCondition creates an alert condition given the passed configuration. func (c *Client) CreateAlertCondition(condition AlertCondition) (*AlertCondition, error) { policyID := condition.PolicyID @@ -85,6 +87,7 @@ func (c *Client) CreateAlertCondition(condition AlertCondition) (*AlertCondition return &resp.Condition, nil } +// UpdateAlertCondition updates an alert condition with the specified changes. func (c *Client) UpdateAlertCondition(condition AlertCondition) (*AlertCondition, error) { policyID := condition.PolicyID id := condition.ID @@ -110,6 +113,7 @@ func (c *Client) UpdateAlertCondition(condition AlertCondition) (*AlertCondition return &resp.Condition, nil } +// DeleteAlertCondition removes the alert condition given the specified ID and policy ID. func (c *Client) DeleteAlertCondition(policyID int, id int) error { u := &url.URL{Path: fmt.Sprintf("/alerts_conditions/%v.json", id)} _, err := c.Do("DELETE", u.String(), nil, nil) diff --git a/vendor/github.com/paultyng/go-newrelic/api/alert_policy_channels.go b/vendor/github.com/paultyng/go-newrelic/api/alert_policy_channels.go index 3c822131f..8a67e68e9 100644 --- a/vendor/github.com/paultyng/go-newrelic/api/alert_policy_channels.go +++ b/vendor/github.com/paultyng/go-newrelic/api/alert_policy_channels.go @@ -6,6 +6,7 @@ import ( "strconv" ) +// UpdateAlertPolicyChannels updates a policy by adding the specified notification channels. func (c *Client) UpdateAlertPolicyChannels(policyID int, channelIDs []int) error { channelIDStrings := make([]string, len(channelIDs)) @@ -30,6 +31,7 @@ func (c *Client) UpdateAlertPolicyChannels(policyID int, channelIDs []int) error return err } +// DeleteAlertPolicyChannel deletes a notification channel from an alert policy. func (c *Client) DeleteAlertPolicyChannel(policyID int, channelID int) error { reqURL, err := url.Parse("/alerts_policy_channels.json") if err != nil { diff --git a/vendor/github.com/paultyng/go-newrelic/api/applications.go b/vendor/github.com/paultyng/go-newrelic/api/applications.go index 54af0bda2..dc3bdf2e0 100644 --- a/vendor/github.com/paultyng/go-newrelic/api/applications.go +++ b/vendor/github.com/paultyng/go-newrelic/api/applications.go @@ -53,6 +53,7 @@ func (c *Client) queryApplications(filters applicationsFilters) ([]Application, return applications, nil } +// ListApplications lists all the applications you have access to. func (c *Client) ListApplications() ([]Application, error) { return c.queryApplications(applicationsFilters{}) } diff --git a/vendor/github.com/paultyng/go-newrelic/api/client.go b/vendor/github.com/paultyng/go-newrelic/api/client.go index e46d6823c..936ffef1a 100644 --- a/vendor/github.com/paultyng/go-newrelic/api/client.go +++ b/vendor/github.com/paultyng/go-newrelic/api/client.go @@ -13,6 +13,7 @@ type Client struct { RestyClient *resty.Client } +// ErrorResponse represents an error response from New Relic. type ErrorResponse struct { Detail *ErrorDetail `json:"error,omitempty"` } @@ -24,6 +25,7 @@ func (e *ErrorResponse) Error() string { return "Unknown error" } +// ErrorDetail represents the details of an ErrorResponse from New Relic. type ErrorDetail struct { Title string `json:"title,omitempty"` } diff --git a/vendor/github.com/paultyng/go-newrelic/api/component_metric_data.go b/vendor/github.com/paultyng/go-newrelic/api/component_metric_data.go new file mode 100644 index 000000000..a8d743e9b --- /dev/null +++ b/vendor/github.com/paultyng/go-newrelic/api/component_metric_data.go @@ -0,0 +1,45 @@ +package api + +import ( + "fmt" + "net/url" +) + +func (c *Client) queryComponentMetricData(componentID int, names []string) ([]Metric, error) { + data := []Metric{} + + reqURL, err := url.Parse(fmt.Sprintf("/components/%v/metrics/data.json", componentID)) + if err != nil { + return nil, err + } + + qs := reqURL.Query() + for _, name := range names { + qs.Add("names[]", name) + } + reqURL.RawQuery = qs.Encode() + + nextPath := reqURL.String() + + for nextPath != "" { + resp := struct { + MetricData struct { + Metrics []Metric `json:"metrics"` + } `json:"metric_data,omitempty"` + }{} + + nextPath, err = c.Do("GET", nextPath, nil, &resp) + if err != nil { + return nil, err + } + + data = append(data, resp.MetricData.Metrics...) + } + + return data, nil +} + +// ListComponentMetricData lists all the metric data for the specified component ID and metric names. +func (c *Client) ListComponentMetricData(componentID int, names []string) ([]Metric, error) { + return c.queryComponentMetricData(componentID, names) +} diff --git a/vendor/github.com/paultyng/go-newrelic/api/component_metrics.go b/vendor/github.com/paultyng/go-newrelic/api/component_metrics.go new file mode 100644 index 000000000..60b99ca9a --- /dev/null +++ b/vendor/github.com/paultyng/go-newrelic/api/component_metrics.go @@ -0,0 +1,40 @@ +package api + +import ( + "fmt" + "net/url" +) + +func (c *Client) queryComponentMetrics(componentID int) ([]ComponentMetric, error) { + metrics := []ComponentMetric{} + + reqURL, err := url.Parse(fmt.Sprintf("/components/%v/metrics.json", componentID)) + if err != nil { + return nil, err + } + + qs := reqURL.Query() + reqURL.RawQuery = qs.Encode() + + nextPath := reqURL.String() + + for nextPath != "" { + resp := struct { + Metrics []ComponentMetric `json:"metrics,omitempty"` + }{} + + nextPath, err = c.Do("GET", nextPath, nil, &resp) + if err != nil { + return nil, err + } + + metrics = append(metrics, resp.Metrics...) + } + + return metrics, nil +} + +// ListComponentMetrics lists all the component metrics for the specificed component ID. +func (c *Client) ListComponentMetrics(componentID int) ([]ComponentMetric, error) { + return c.queryComponentMetrics(componentID) +} diff --git a/vendor/github.com/paultyng/go-newrelic/api/components.go b/vendor/github.com/paultyng/go-newrelic/api/components.go new file mode 100644 index 000000000..a6acfc375 --- /dev/null +++ b/vendor/github.com/paultyng/go-newrelic/api/components.go @@ -0,0 +1,51 @@ +package api + +import ( + "net/url" + "strconv" +) + +type componentsFilters struct { + PluginID int + IDs []int +} + +func (c *Client) queryComponents(filters componentsFilters) ([]Component, error) { + components := []Component{} + + reqURL, err := url.Parse("/components.json") + if err != nil { + return nil, err + } + + qs := reqURL.Query() + qs.Set("filter[plugin_id]", strconv.Itoa(filters.PluginID)) + for _, id := range filters.IDs { + qs.Add("filter[ids]", strconv.Itoa(id)) + } + reqURL.RawQuery = qs.Encode() + + nextPath := reqURL.String() + + for nextPath != "" { + resp := struct { + Components []Component `json:"components,omitempty"` + }{} + + nextPath, err = c.Do("GET", nextPath, nil, &resp) + if err != nil { + return nil, err + } + + components = append(components, resp.Components...) + } + + return components, nil +} + +// ListComponents lists all the components for the specified plugin ID. +func (c *Client) ListComponents(pluginID int) ([]Component, error) { + return c.queryComponents(componentsFilters{ + PluginID: pluginID, + }) +} diff --git a/vendor/github.com/paultyng/go-newrelic/api/labels.go b/vendor/github.com/paultyng/go-newrelic/api/labels.go index 933fd9607..7db1f560c 100644 --- a/vendor/github.com/paultyng/go-newrelic/api/labels.go +++ b/vendor/github.com/paultyng/go-newrelic/api/labels.go @@ -31,6 +31,7 @@ func (c *Client) queryLabels() ([]Label, error) { return labels, nil } +// GetLabel gets the label for the specified key. func (c *Client) GetLabel(key string) (*Label, error) { labels, err := c.queryLabels() if err != nil { diff --git a/vendor/github.com/paultyng/go-newrelic/api/plugins.go b/vendor/github.com/paultyng/go-newrelic/api/plugins.go new file mode 100644 index 000000000..5cf917113 --- /dev/null +++ b/vendor/github.com/paultyng/go-newrelic/api/plugins.go @@ -0,0 +1,51 @@ +package api + +import ( + "net/url" + "strconv" +) + +type pluginsFilters struct { + GUID *string + IDs []int +} + +func (c *Client) queryPlugins(filters pluginsFilters) ([]Plugin, error) { + plugins := []Plugin{} + + reqURL, err := url.Parse("/plugins.json") + if err != nil { + return nil, err + } + + qs := reqURL.Query() + if filters.GUID != nil { + qs.Set("filter[guid]", *filters.GUID) + } + for _, id := range filters.IDs { + qs.Add("filter[ids]", strconv.Itoa(id)) + } + reqURL.RawQuery = qs.Encode() + + nextPath := reqURL.String() + + for nextPath != "" { + resp := struct { + Plugins []Plugin `json:"plugins,omitempty"` + }{} + + nextPath, err = c.Do("GET", nextPath, nil, &resp) + if err != nil { + return nil, err + } + + plugins = append(plugins, resp.Plugins...) + } + + return plugins, nil +} + +// ListPlugins lists all the plugins you have access to. +func (c *Client) ListPlugins() ([]Plugin, error) { + return c.queryPlugins(pluginsFilters{}) +} diff --git a/vendor/github.com/paultyng/go-newrelic/api/types.go b/vendor/github.com/paultyng/go-newrelic/api/types.go index df5f88773..cb7bbbf0a 100644 --- a/vendor/github.com/paultyng/go-newrelic/api/types.go +++ b/vendor/github.com/paultyng/go-newrelic/api/types.go @@ -3,6 +3,7 @@ package api import "errors" var ( + // ErrNotFound is returned when the resource was not found in New Relic. ErrNotFound = errors.New("newrelic: Resource not found") ) @@ -57,7 +58,8 @@ type AlertCondition struct { Metric string `json:"metric,omitempty"` RunbookURL string `json:"runbook_url,omitempty"` Terms []AlertConditionTerm `json:"terms,omitempty"` - UserDefined AlertConditionUserDefined `json:"uder_defined,omitempty"` + UserDefined AlertConditionUserDefined `json:"user_defined,omitempty"` + Scope string `json:"condition_scope,omitempty"` } // AlertChannelLinks represent the links between policies and alert channels @@ -74,6 +76,7 @@ type AlertChannel struct { Links AlertChannelLinks `json:"links,omitempty"` } +// ApplicationSummary represents performance information about a New Relic application. type ApplicationSummary struct { ResponseTime float64 `json:"response_time"` Throughput float64 `json:"throughput"` @@ -85,6 +88,7 @@ type ApplicationSummary struct { ConcurrentInstanceCount int `json:"concurrent_instance_count"` } +// ApplicationEndUserSummary represents performance information about a New Relic application. type ApplicationEndUserSummary struct { ResponseTime float64 `json:"response_time"` Throughput float64 `json:"throughput"` @@ -92,6 +96,7 @@ type ApplicationEndUserSummary struct { ApdexScore float64 `json:"apdex_score"` } +// ApplicationSettings represents some of the settings of a New Relic application. type ApplicationSettings struct { AppApdexThreshold float64 `json:"app_apdex_threshold,omitempty"` EndUserApdexThreshold float64 `json:"end_user_apdex_threshold,omitempty"` @@ -99,6 +104,7 @@ type ApplicationSettings struct { UseServerSideConfig bool `json:"use_server_side_config,omitempty"` } +// ApplicationLinks represents all the links for a New Relic application. type ApplicationLinks struct { ServerIDs []int `json:"servers,omitempty"` HostIDs []int `json:"application_hosts,omitempty"` @@ -106,6 +112,7 @@ type ApplicationLinks struct { AlertPolicyID int `json:"alert_policy"` } +// Application represents information about a New Relic application. type Application struct { ID int `json:"id,omitempty"` Name string `json:"name,omitempty"` @@ -118,3 +125,83 @@ type Application struct { Settings ApplicationSettings `json:"settings,omitempty"` Links ApplicationLinks `json:"links,omitempty"` } + +// PluginDetails represents information about a New Relic plugin. +type PluginDetails struct { + Description int `json:"description"` + IsPublic string `json:"is_public"` + CreatedAt string `json:"created_at,omitempty"` + UpdatedAt string `json:"updated_at,omitempty"` + LastPublishedAt string `json:"last_published_at,omitempty"` + HasUnpublishedChanges bool `json:"has_unpublished_changes"` + BrandingImageURL string `json:"branding_image_url"` + UpgradedAt string `json:"upgraded_at,omitempty"` + ShortName string `json:"short_name"` + PublisherAboutURL string `json:"publisher_about_url"` + PublisherSupportURL string `json:"publisher_support_url"` + DownloadURL string `json:"download_url"` + FirstEditedAt string `json:"first_edited_at,omitempty"` + LastEditedAt string `json:"last_edited_at,omitempty"` + FirstPublishedAt string `json:"first_published_at,omitempty"` + PublishedVersion string `json:"published_version"` +} + +// MetricThreshold represents the different thresholds for a metric in an alert. +type MetricThreshold struct { + Caution float64 `json:"caution"` + Critical float64 `json:"critical"` +} + +// MetricValue represents the observed value of a metric. +type MetricValue struct { + Raw float64 `json:"raw"` + Formatted string `json:"formatted"` +} + +// MetricTimeslice represents the values of a metric over a given time. +type MetricTimeslice struct { + From string `json:"from,omitempty"` + To string `json:"to,omitempty"` + Values map[string]interface{} `json:"values,omitempty"` +} + +// Metric represents data for a specific metric. +type Metric struct { + Name string `json:"name"` + Timeslices []MetricTimeslice `json:"timeslices"` +} + +// SummaryMetric represents summary information for a specific metric. +type SummaryMetric struct { + ID int `json:"id"` + Name string `json:"name"` + Metric string `json:"metric"` + ValueFunction string `json:"value_function"` + Thresholds MetricThreshold `json:"thresholds"` + Values MetricValue `json:"values"` +} + +// Plugin represents information about a New Relic plugin. +type Plugin struct { + ID int `json:"id"` + Name string `json:"name,omitempty"` + GUID string `json:"guid,omitempty"` + Publisher string `json:"publisher,omitempty"` + ComponentAgentCount int `json:"component_agent_count"` + Details PluginDetails `json:"details"` + SummaryMetrics []SummaryMetric `json:"summary_metrics"` +} + +// Component represnets information about a New Relic component. +type Component struct { + ID int `json:"id"` + Name string `json:"name,omitempty"` + HealthStatus string `json:"health_status,omitempty"` + SummaryMetrics []SummaryMetric `json:"summary_metrics"` +} + +// ComponentMetric represents metric information for a specific component. +type ComponentMetric struct { + Name string `json:"name,omitempty"` + Values []string `json:"values"` +} diff --git a/vendor/github.com/profitbricks/profitbricks-sdk-go/nic.go b/vendor/github.com/profitbricks/profitbricks-sdk-go/nic.go index 1d082a64d..86571ad01 100644 --- a/vendor/github.com/profitbricks/profitbricks-sdk-go/nic.go +++ b/vendor/github.com/profitbricks/profitbricks-sdk-go/nic.go @@ -22,7 +22,7 @@ type NicProperties struct { Name string `json:"name,omitempty"` Mac string `json:"mac,omitempty"` Ips []string `json:"ips,omitempty"` - Dhcp bool `json:"dhcp,omitempty"` + Dhcp bool `json:"dhcp"` Lan int `json:"lan,omitempty"` FirewallActive bool `json:"firewallActive,omitempty"` Nat bool `json:"nat,omitempty"` diff --git a/vendor/github.com/profitbricks/profitbricks-sdk-go/request.go b/vendor/github.com/profitbricks/profitbricks-sdk-go/request.go index 023ae1a4a..98cbbffd9 100644 --- a/vendor/github.com/profitbricks/profitbricks-sdk-go/request.go +++ b/vendor/github.com/profitbricks/profitbricks-sdk-go/request.go @@ -3,6 +3,7 @@ package profitbricks import ( "encoding/json" "net/http" + "time" ) type RequestStatus struct { @@ -26,6 +27,55 @@ type RequestTarget struct { Status string `json:"status,omitempty"` } +type Requests struct { + Id string `json:"id,omitempty"` + Type_ string `json:"type,omitempty"` + Href string `json:"href,omitempty"` + Items []Request `json:"items,omitempty"` + Response string `json:"Response,omitempty"` + Headers *http.Header `json:"headers,omitempty"` + StatusCode int `json:"headers,omitempty"` +} + +type Request struct { + ID string `json:"id"` + Type string `json:"type"` + Href string `json:"href"` + Metadata struct { + CreatedDate time.Time `json:"createdDate"` + CreatedBy string `json:"createdBy"` + Etag string `json:"etag"` + RequestStatus struct { + ID string `json:"id"` + Type string `json:"type"` + Href string `json:"href"` + } `json:"requestStatus"` + } `json:"metadata"` + Properties struct { + Method string `json:"method"` + Headers interface{} `json:"headers"` + Body interface{} `json:"body"` + URL string `json:"url"` + } `json:"properties"` + Response string `json:"Response,omitempty"` + Headers *http.Header `json:"headers,omitempty"` + StatusCode int `json:"headers,omitempty"` +} + +func ListRequests() Requests { + url := mk_url("/requests") + `?depth=` + Depth + req, _ := http.NewRequest("GET", url, nil) + req.Header.Add("Content-Type", FullHeader) + return toRequests(do(req)) +} + +func GetRequest(req_id string) Request { + url := mk_url("/requests/" + req_id) + `?depth=` + Depth + req, _ := http.NewRequest("GET", url, nil) + req.Header.Add("Content-Type", FullHeader) + return toRequest(do(req)) +} + func GetRequestStatus(path string) RequestStatus { url := mk_url(path) + `?depth=` + Depth req, _ := http.NewRequest("GET", url, nil) @@ -41,3 +91,22 @@ func toRequestStatus(resp Resp) RequestStatus { server.StatusCode = resp.StatusCode return server } + +func toRequests(resp Resp) Requests { + var server Requests + json.Unmarshal(resp.Body, &server) + server.Response = string(resp.Body) + server.Headers = &resp.Headers + server.StatusCode = resp.StatusCode + return server +} + +func toRequest(resp Resp) Request { + var server Request + json.Unmarshal(resp.Body, &server) + server.Response = string(resp.Body) + server.Headers = &resp.Headers + server.StatusCode = resp.StatusCode + return server +} + diff --git a/vendor/github.com/sethvargo/go-fastly/Makefile b/vendor/github.com/sethvargo/go-fastly/Makefile index 2addc380e..14a75743c 100644 --- a/vendor/github.com/sethvargo/go-fastly/Makefile +++ b/vendor/github.com/sethvargo/go-fastly/Makefile @@ -1,42 +1,62 @@ -TEST?=./... -NAME?=$(shell basename "${CURDIR}") -EXTERNAL_TOOLS=\ - github.com/mitchellh/gox +# Metadata about this makefile and position +MKFILE_PATH := $(lastword $(MAKEFILE_LIST)) +CURRENT_DIR := $(dir $(realpath $(MKFILE_PATH))) +CURRENT_DIR := $(CURRENT_DIR:/=) -default: test +# Get the project metadata +GOVERSION := 1.8 +PROJECT := github.com/sethvargo/go-fastly +OWNER := $(dir $(PROJECT)) +OWNER := $(notdir $(OWNER:/=)) +NAME := $(notdir $(PROJECT)) +EXTERNAL_TOOLS = -# test runs the test suite and vets the code. -test: generate - @echo "==> Running tests..." - @go list $(TEST) \ - | grep -v "github.com/sethvargo/${NAME}/vendor" \ - | xargs -n1 go test -timeout=60s -parallel=10 ${TESTARGS} +# List of tests to run +TEST ?= ./... -# testrace runs the race checker -testrace: generate - @echo "==> Running tests (race)..." - @go list $(TEST) \ - | grep -v "github.com/sethvargo/${NAME}/vendor" \ - | xargs -n1 go test -timeout=60s -race ${TESTARGS} +# List all our actual files, excluding vendor +GOFILES = $(shell go list $(TEST) | grep -v /vendor/) -# updatedeps installs all the dependencies needed to run and build. -updatedeps: - @sh -c "'${CURDIR}/scripts/deps.sh' '${NAME}'" +# Tags specific for building +GOTAGS ?= -# generate runs `go generate` to build the dynamically generated source files. -generate: - @echo "==> Generating..." - @find . -type f -name '.DS_Store' -delete - @go list ./... \ - | grep -v "github.com/hashicorp/${NAME}/vendor" \ - | xargs -n1 go generate +# Number of procs to use +GOMAXPROCS ?= 4 -# bootstrap installs the necessary go tools for development/build. +# bootstrap installs the necessary go tools for development or build bootstrap: - @echo "==> Bootstrapping..." + @echo "==> Bootstrapping ${PROJECT}..." @for t in ${EXTERNAL_TOOLS}; do \ - echo "--> Installing "$$t"..." ; \ + echo "--> Installing $$t" ; \ go get -u "$$t"; \ done -.PHONY: default test testrace updatedeps generate bootstrap +# deps gets all the dependencies for this repository and vendors them. +deps: + @echo "==> Updating dependencies..." + @docker run \ + --interactive \ + --tty \ + --rm \ + --dns=8.8.8.8 \ + --env="GOMAXPROCS=${GOMAXPROCS}" \ + --workdir="/go/src/${PROJECT}" \ + --volume="${CURRENT_DIR}:/go/src/${PROJECT}" \ + "golang:${GOVERSION}" /usr/bin/env sh -c "scripts/deps.sh" + +# generate runs the code generator +generate: + @echo "==> Generating ${PROJECT}..." + @go generate ${GOFILES} + +# test runs the test suite +test: + @echo "==> Testing ${PROJECT}..." + @go test -timeout=60s -parallel=20 -tags="${GOTAGS}" ${GOFILES} ${TESTARGS} + +# test-race runs the race checker +test-race: + @echo "==> Testing ${PROJECT} (race)..." + @go test -timeout=60s -race -tags="${GOTAGS}" ${GOFILES} ${TESTARGS} + +.PHONY: bootstrap deps generate test test-race diff --git a/vendor/github.com/sethvargo/go-fastly/backend.go b/vendor/github.com/sethvargo/go-fastly/backend.go index 0d08445fa..0e2642ece 100644 --- a/vendor/github.com/sethvargo/go-fastly/backend.go +++ b/vendor/github.com/sethvargo/go-fastly/backend.go @@ -8,7 +8,7 @@ import ( // Backend represents a backend response from the Fastly API. type Backend struct { ServiceID string `mapstructure:"service_id"` - Version string `mapstructure:"version"` + Version int `mapstructure:"version"` Name string `mapstructure:"name"` Address string `mapstructure:"address"` @@ -53,7 +53,7 @@ type ListBackendsInput struct { Service string // Version is the specific configuration version (required). - Version string + Version int } // ListBackends returns the list of backends for the configuration version. @@ -62,11 +62,11 @@ func (c *Client) ListBackends(i *ListBackendsInput) ([]*Backend, error) { return nil, ErrMissingService } - if i.Version == "" { + if i.Version == 0 { return nil, ErrMissingVersion } - path := fmt.Sprintf("/service/%s/version/%s/backend", i.Service, i.Version) + path := fmt.Sprintf("/service/%s/version/%d/backend", i.Service, i.Version) resp, err := c.Get(path, nil) if err != nil { return nil, err @@ -85,7 +85,7 @@ type CreateBackendInput struct { // Service is the ID of the service. Version is the specific configuration // version. Both fields are required. Service string - Version string + Version int Name string `form:"name,omitempty"` Address string `form:"address,omitempty"` @@ -119,11 +119,11 @@ func (c *Client) CreateBackend(i *CreateBackendInput) (*Backend, error) { return nil, ErrMissingService } - if i.Version == "" { + if i.Version == 0 { return nil, ErrMissingVersion } - path := fmt.Sprintf("/service/%s/version/%s/backend", i.Service, i.Version) + path := fmt.Sprintf("/service/%s/version/%d/backend", i.Service, i.Version) resp, err := c.PostForm(path, i, nil) if err != nil { return nil, err @@ -141,7 +141,7 @@ type GetBackendInput struct { // Service is the ID of the service. Version is the specific configuration // version. Both fields are required. Service string - Version string + Version int // Name is the name of the backend to fetch. Name string @@ -153,7 +153,7 @@ func (c *Client) GetBackend(i *GetBackendInput) (*Backend, error) { return nil, ErrMissingService } - if i.Version == "" { + if i.Version == 0 { return nil, ErrMissingVersion } @@ -161,7 +161,7 @@ func (c *Client) GetBackend(i *GetBackendInput) (*Backend, error) { return nil, ErrMissingName } - path := fmt.Sprintf("/service/%s/version/%s/backend/%s", i.Service, i.Version, i.Name) + path := fmt.Sprintf("/service/%s/version/%d/backend/%s", i.Service, i.Version, i.Name) resp, err := c.Get(path, nil) if err != nil { return nil, err @@ -179,7 +179,7 @@ type UpdateBackendInput struct { // Service is the ID of the service. Version is the specific configuration // version. Both fields are required. Service string - Version string + Version int // Name is the name of the backend to update. Name string @@ -216,7 +216,7 @@ func (c *Client) UpdateBackend(i *UpdateBackendInput) (*Backend, error) { return nil, ErrMissingService } - if i.Version == "" { + if i.Version == 0 { return nil, ErrMissingVersion } @@ -224,7 +224,7 @@ func (c *Client) UpdateBackend(i *UpdateBackendInput) (*Backend, error) { return nil, ErrMissingName } - path := fmt.Sprintf("/service/%s/version/%s/backend/%s", i.Service, i.Version, i.Name) + path := fmt.Sprintf("/service/%s/version/%d/backend/%s", i.Service, i.Version, i.Name) resp, err := c.PutForm(path, i, nil) if err != nil { return nil, err @@ -242,7 +242,7 @@ type DeleteBackendInput struct { // Service is the ID of the service. Version is the specific configuration // version. Both fields are required. Service string - Version string + Version int // Name is the name of the backend to delete (required). Name string @@ -254,7 +254,7 @@ func (c *Client) DeleteBackend(i *DeleteBackendInput) error { return ErrMissingService } - if i.Version == "" { + if i.Version == 0 { return ErrMissingVersion } @@ -262,7 +262,7 @@ func (c *Client) DeleteBackend(i *DeleteBackendInput) error { return ErrMissingName } - path := fmt.Sprintf("/service/%s/version/%s/backend/%s", i.Service, i.Version, i.Name) + path := fmt.Sprintf("/service/%s/version/%d/backend/%s", i.Service, i.Version, i.Name) resp, err := c.Delete(path, nil) if err != nil { return err diff --git a/vendor/github.com/sethvargo/go-fastly/cache_setting.go b/vendor/github.com/sethvargo/go-fastly/cache_setting.go index 79ba5c64c..5a90f9b0e 100644 --- a/vendor/github.com/sethvargo/go-fastly/cache_setting.go +++ b/vendor/github.com/sethvargo/go-fastly/cache_setting.go @@ -22,7 +22,7 @@ type CacheSettingAction string // CacheSetting represents a response from Fastly's API for cache settings. type CacheSetting struct { ServiceID string `mapstructure:"service_id"` - Version string `mapstructure:"version"` + Version int `mapstructure:"version"` Name string `mapstructure:"name"` Action CacheSettingAction `mapstructure:"action"` @@ -47,7 +47,7 @@ type ListCacheSettingsInput struct { Service string // Version is the specific configuration version (required). - Version string + Version int } // ListCacheSettings returns the list of cache settings for the configuration @@ -57,11 +57,11 @@ func (c *Client) ListCacheSettings(i *ListCacheSettingsInput) ([]*CacheSetting, return nil, ErrMissingService } - if i.Version == "" { + if i.Version == 0 { return nil, ErrMissingVersion } - path := fmt.Sprintf("/service/%s/version/%s/cache_settings", i.Service, i.Version) + path := fmt.Sprintf("/service/%s/version/%d/cache_settings", i.Service, i.Version) resp, err := c.Get(path, nil) if err != nil { return nil, err @@ -80,7 +80,7 @@ type CreateCacheSettingInput struct { // Service is the ID of the service. Version is the specific configuration // version. Both fields are required. Service string - Version string + Version int Name string `form:"name,omitempty"` Action CacheSettingAction `form:"action,omitempty"` @@ -95,11 +95,11 @@ func (c *Client) CreateCacheSetting(i *CreateCacheSettingInput) (*CacheSetting, return nil, ErrMissingService } - if i.Version == "" { + if i.Version == 0 { return nil, ErrMissingVersion } - path := fmt.Sprintf("/service/%s/version/%s/cache_settings", i.Service, i.Version) + path := fmt.Sprintf("/service/%s/version/%d/cache_settings", i.Service, i.Version) resp, err := c.PostForm(path, i, nil) if err != nil { return nil, err @@ -117,7 +117,7 @@ type GetCacheSettingInput struct { // Service is the ID of the service. Version is the specific configuration // version. Both fields are required. Service string - Version string + Version int // Name is the name of the cache setting to fetch. Name string @@ -130,7 +130,7 @@ func (c *Client) GetCacheSetting(i *GetCacheSettingInput) (*CacheSetting, error) return nil, ErrMissingService } - if i.Version == "" { + if i.Version == 0 { return nil, ErrMissingVersion } @@ -138,7 +138,7 @@ func (c *Client) GetCacheSetting(i *GetCacheSettingInput) (*CacheSetting, error) return nil, ErrMissingName } - path := fmt.Sprintf("/service/%s/version/%s/cache_settings/%s", i.Service, i.Version, i.Name) + path := fmt.Sprintf("/service/%s/version/%d/cache_settings/%s", i.Service, i.Version, i.Name) resp, err := c.Get(path, nil) if err != nil { return nil, err @@ -156,7 +156,7 @@ type UpdateCacheSettingInput struct { // Service is the ID of the service. Version is the specific configuration // version. Both fields are required. Service string - Version string + Version int // Name is the name of the cache setting to update. Name string @@ -174,7 +174,7 @@ func (c *Client) UpdateCacheSetting(i *UpdateCacheSettingInput) (*CacheSetting, return nil, ErrMissingService } - if i.Version == "" { + if i.Version == 0 { return nil, ErrMissingVersion } @@ -182,7 +182,7 @@ func (c *Client) UpdateCacheSetting(i *UpdateCacheSettingInput) (*CacheSetting, return nil, ErrMissingName } - path := fmt.Sprintf("/service/%s/version/%s/cache_settings/%s", i.Service, i.Version, i.Name) + path := fmt.Sprintf("/service/%s/version/%d/cache_settings/%s", i.Service, i.Version, i.Name) resp, err := c.PutForm(path, i, nil) if err != nil { return nil, err @@ -200,7 +200,7 @@ type DeleteCacheSettingInput struct { // Service is the ID of the service. Version is the specific configuration // version. Both fields are required. Service string - Version string + Version int // Name is the name of the cache setting to delete (required). Name string @@ -212,7 +212,7 @@ func (c *Client) DeleteCacheSetting(i *DeleteCacheSettingInput) error { return ErrMissingService } - if i.Version == "" { + if i.Version == 0 { return ErrMissingVersion } @@ -220,7 +220,7 @@ func (c *Client) DeleteCacheSetting(i *DeleteCacheSettingInput) error { return ErrMissingName } - path := fmt.Sprintf("/service/%s/version/%s/cache_settings/%s", i.Service, i.Version, i.Name) + path := fmt.Sprintf("/service/%s/version/%d/cache_settings/%s", i.Service, i.Version, i.Name) resp, err := c.Delete(path, nil) if err != nil { return err diff --git a/vendor/github.com/sethvargo/go-fastly/client.go b/vendor/github.com/sethvargo/go-fastly/client.go index 4c670601f..30a54a09c 100644 --- a/vendor/github.com/sethvargo/go-fastly/client.go +++ b/vendor/github.com/sethvargo/go-fastly/client.go @@ -64,20 +64,24 @@ func DefaultClient() *Client { return client } -// NewClient creates a new API client with the given key. Because Fastly allows -// some requests without an API key, this function will not error if the API -// token is not supplied. Attempts to make a request that requires an API key -// will return a 403 response. +// NewClient creates a new API client with the given key and the default API +// endpoint. Because Fastly allows some requests without an API key, this +// function will not error if the API token is not supplied. Attempts to make a +// request that requires an API key will return a 403 response. func NewClient(key string) (*Client, error) { - client := &Client{apiKey: key} + return NewClientForEndpoint(key, DefaultEndpoint) +} + +// NewClientForEndpoint creates a new API client with the given key and API +// endpoint. Because Fastly allows some requests without an API key, this +// function will not error if the API token is not supplied. Attempts to make a +// request that requires an API key will return a 403 response. +func NewClientForEndpoint(key string, endpoint string) (*Client, error) { + client := &Client{apiKey: key, Address: endpoint} return client.init() } func (c *Client) init() (*Client, error) { - if len(c.Address) == 0 { - c.Address = DefaultEndpoint - } - u, err := url.Parse(c.Address) if err != nil { return nil, err @@ -155,7 +159,7 @@ func (c *Client) RequestForm(verb, p string, i interface{}, ro *RequestOptions) ro.Headers["Content-Type"] = "application/x-www-form-urlencoded" buf := new(bytes.Buffer) - if err := form.NewEncoder(buf).DelimitWith('|').Encode(i); err != nil { + if err := form.NewEncoder(buf).KeepZeros(true).DelimitWith('|').Encode(i); err != nil { return nil, err } body := buf.String() diff --git a/vendor/github.com/sethvargo/go-fastly/condition.go b/vendor/github.com/sethvargo/go-fastly/condition.go index b88b61ad0..43a7c70c2 100644 --- a/vendor/github.com/sethvargo/go-fastly/condition.go +++ b/vendor/github.com/sethvargo/go-fastly/condition.go @@ -8,7 +8,7 @@ import ( // Condition represents a condition response from the Fastly API. type Condition struct { ServiceID string `mapstructure:"service_id"` - Version string `mapstructure:"version"` + Version int `mapstructure:"version"` Name string `mapstructure:"name"` Statement string `mapstructure:"statement"` @@ -32,7 +32,7 @@ type ListConditionsInput struct { Service string // Version is the specific configuration version (required). - Version string + Version int } // ListConditions returns the list of conditions for the configuration version. @@ -41,11 +41,11 @@ func (c *Client) ListConditions(i *ListConditionsInput) ([]*Condition, error) { return nil, ErrMissingService } - if i.Version == "" { + if i.Version == 0 { return nil, ErrMissingVersion } - path := fmt.Sprintf("/service/%s/version/%s/condition", i.Service, i.Version) + path := fmt.Sprintf("/service/%s/version/%d/condition", i.Service, i.Version) resp, err := c.Get(path, nil) if err != nil { return nil, err @@ -64,7 +64,7 @@ type CreateConditionInput struct { // Service is the ID of the service. Version is the specific configuration // version. Both fields are required. Service string - Version string + Version int Name string `form:"name,omitempty"` Statement string `form:"statement,omitempty"` @@ -78,11 +78,11 @@ func (c *Client) CreateCondition(i *CreateConditionInput) (*Condition, error) { return nil, ErrMissingService } - if i.Version == "" { + if i.Version == 0 { return nil, ErrMissingVersion } - path := fmt.Sprintf("/service/%s/version/%s/condition", i.Service, i.Version) + path := fmt.Sprintf("/service/%s/version/%d/condition", i.Service, i.Version) resp, err := c.PostForm(path, i, nil) if err != nil { return nil, err @@ -100,7 +100,7 @@ type GetConditionInput struct { // Service is the ID of the service. Version is the specific configuration // version. Both fields are required. Service string - Version string + Version int // Name is the name of the condition to fetch. Name string @@ -112,7 +112,7 @@ func (c *Client) GetCondition(i *GetConditionInput) (*Condition, error) { return nil, ErrMissingService } - if i.Version == "" { + if i.Version == 0 { return nil, ErrMissingVersion } @@ -120,7 +120,7 @@ func (c *Client) GetCondition(i *GetConditionInput) (*Condition, error) { return nil, ErrMissingName } - path := fmt.Sprintf("/service/%s/version/%s/condition/%s", i.Service, i.Version, i.Name) + path := fmt.Sprintf("/service/%s/version/%d/condition/%s", i.Service, i.Version, i.Name) resp, err := c.Get(path, nil) if err != nil { return nil, err @@ -138,7 +138,7 @@ type UpdateConditionInput struct { // Service is the ID of the service. Version is the specific configuration // version. Both fields are required. Service string - Version string + Version int // Name is the name of the condition to update. Name string @@ -154,7 +154,7 @@ func (c *Client) UpdateCondition(i *UpdateConditionInput) (*Condition, error) { return nil, ErrMissingService } - if i.Version == "" { + if i.Version == 0 { return nil, ErrMissingVersion } @@ -162,7 +162,7 @@ func (c *Client) UpdateCondition(i *UpdateConditionInput) (*Condition, error) { return nil, ErrMissingName } - path := fmt.Sprintf("/service/%s/version/%s/condition/%s", i.Service, i.Version, i.Name) + path := fmt.Sprintf("/service/%s/version/%d/condition/%s", i.Service, i.Version, i.Name) resp, err := c.PutForm(path, i, nil) if err != nil { return nil, err @@ -180,7 +180,7 @@ type DeleteConditionInput struct { // Service is the ID of the service. Version is the specific configuration // version. Both fields are required. Service string - Version string + Version int // Name is the name of the condition to delete (required). Name string @@ -192,7 +192,7 @@ func (c *Client) DeleteCondition(i *DeleteConditionInput) error { return ErrMissingService } - if i.Version == "" { + if i.Version == 0 { return ErrMissingVersion } @@ -200,7 +200,7 @@ func (c *Client) DeleteCondition(i *DeleteConditionInput) error { return ErrMissingName } - path := fmt.Sprintf("/service/%s/version/%s/condition/%s", i.Service, i.Version, i.Name) + path := fmt.Sprintf("/service/%s/version/%d/condition/%s", i.Service, i.Version, i.Name) resp, err := c.Delete(path, nil) if err != nil { return err diff --git a/vendor/github.com/sethvargo/go-fastly/dictionary.go b/vendor/github.com/sethvargo/go-fastly/dictionary.go index c3d883802..2a1ae2518 100644 --- a/vendor/github.com/sethvargo/go-fastly/dictionary.go +++ b/vendor/github.com/sethvargo/go-fastly/dictionary.go @@ -8,7 +8,7 @@ import ( // Dictionary represents a dictionary response from the Fastly API. type Dictionary struct { ServiceID string `mapstructure:"service_id"` - Version string `mapstructure:"version"` + Version int `mapstructure:"version"` ID string `mapstructure:"id"` Name string `mapstructure:"name"` @@ -31,7 +31,7 @@ type ListDictionariesInput struct { Service string // Version is the specific configuration version (required). - Version string + Version int } // ListDictionaries returns the list of dictionaries for the configuration version. @@ -40,11 +40,11 @@ func (c *Client) ListDictionaries(i *ListDictionariesInput) ([]*Dictionary, erro return nil, ErrMissingService } - if i.Version == "" { + if i.Version == 0 { return nil, ErrMissingVersion } - path := fmt.Sprintf("/service/%s/version/%s/dictionary", i.Service, i.Version) + path := fmt.Sprintf("/service/%s/version/%d/dictionary", i.Service, i.Version) resp, err := c.Get(path, nil) if err != nil { return nil, err @@ -63,7 +63,7 @@ type CreateDictionaryInput struct { // Service is the ID of the service. Version is the specific configuration // version. Both fields are required. Service string - Version string + Version int Name string `form:"name,omitempty"` } @@ -74,11 +74,11 @@ func (c *Client) CreateDictionary(i *CreateDictionaryInput) (*Dictionary, error) return nil, ErrMissingService } - if i.Version == "" { + if i.Version == 0 { return nil, ErrMissingVersion } - path := fmt.Sprintf("/service/%s/version/%s/dictionary", i.Service, i.Version) + path := fmt.Sprintf("/service/%s/version/%d/dictionary", i.Service, i.Version) resp, err := c.PostForm(path, i, nil) if err != nil { return nil, err @@ -96,7 +96,7 @@ type GetDictionaryInput struct { // Service is the ID of the service. Version is the specific configuration // version. Both fields are required. Service string - Version string + Version int // Name is the name of the dictionary to fetch. Name string @@ -108,7 +108,7 @@ func (c *Client) GetDictionary(i *GetDictionaryInput) (*Dictionary, error) { return nil, ErrMissingService } - if i.Version == "" { + if i.Version == 0 { return nil, ErrMissingVersion } @@ -116,7 +116,7 @@ func (c *Client) GetDictionary(i *GetDictionaryInput) (*Dictionary, error) { return nil, ErrMissingName } - path := fmt.Sprintf("/service/%s/version/%s/dictionary/%s", i.Service, i.Version, i.Name) + path := fmt.Sprintf("/service/%s/version/%d/dictionary/%s", i.Service, i.Version, i.Name) resp, err := c.Get(path, nil) if err != nil { return nil, err @@ -134,7 +134,7 @@ type UpdateDictionaryInput struct { // Service is the ID of the service. Version is the specific configuration // version. Both fields are required. Service string - Version string + Version int // Name is the name of the dictionary to update. Name string @@ -148,7 +148,7 @@ func (c *Client) UpdateDictionary(i *UpdateDictionaryInput) (*Dictionary, error) return nil, ErrMissingService } - if i.Version == "" { + if i.Version == 0 { return nil, ErrMissingVersion } @@ -156,7 +156,7 @@ func (c *Client) UpdateDictionary(i *UpdateDictionaryInput) (*Dictionary, error) return nil, ErrMissingName } - path := fmt.Sprintf("/service/%s/version/%s/dictionary/%s", i.Service, i.Version, i.Name) + path := fmt.Sprintf("/service/%s/version/%d/dictionary/%s", i.Service, i.Version, i.Name) resp, err := c.PutForm(path, i, nil) if err != nil { return nil, err @@ -174,7 +174,7 @@ type DeleteDictionaryInput struct { // Service is the ID of the service. Version is the specific configuration // version. Both fields are required. Service string - Version string + Version int // Name is the name of the dictionary to delete (required). Name string @@ -186,7 +186,7 @@ func (c *Client) DeleteDictionary(i *DeleteDictionaryInput) error { return ErrMissingService } - if i.Version == "" { + if i.Version == 0 { return ErrMissingVersion } @@ -194,7 +194,7 @@ func (c *Client) DeleteDictionary(i *DeleteDictionaryInput) error { return ErrMissingName } - path := fmt.Sprintf("/service/%s/version/%s/dictionary/%s", i.Service, i.Version, i.Name) + path := fmt.Sprintf("/service/%s/version/%d/dictionary/%s", i.Service, i.Version, i.Name) resp, err := c.Delete(path, nil) if err != nil { return err diff --git a/vendor/github.com/sethvargo/go-fastly/diff.go b/vendor/github.com/sethvargo/go-fastly/diff.go index 3cb07b94b..63e798825 100644 --- a/vendor/github.com/sethvargo/go-fastly/diff.go +++ b/vendor/github.com/sethvargo/go-fastly/diff.go @@ -5,8 +5,8 @@ import "fmt" // Diff represents a diff of two versions as a response from the Fastly API. type Diff struct { Format string `mapstructure:"format"` - From string `mapstructure:"from"` - To string `mapstructure:"to"` + From int `mapstructure:"from"` + To int `mapstructure:"to"` Diff string `mapstructure:"diff"` } @@ -18,10 +18,10 @@ type GetDiffInput struct { // From is the version to diff from. This can either be a string indicating a // positive number (e.g. "1") or a negative number from "-1" down ("-1" is the // latest version). - From string + From int // To is the version to diff up to. The same rules for From apply. - To string + To int // Format is an optional field to specify the format with which the diff will // be returned. Acceptable values are "text" (default), "html", or @@ -35,15 +35,15 @@ func (c *Client) GetDiff(i *GetDiffInput) (*Diff, error) { return nil, ErrMissingService } - if i.From == "" { + if i.From == 0 { return nil, ErrMissingFrom } - if i.To == "" { + if i.To == 0 { return nil, ErrMissingTo } - path := fmt.Sprintf("service/%s/diff/from/%s/to/%s", i.Service, i.From, i.To) + path := fmt.Sprintf("service/%s/diff/from/%d/to/%d", i.Service, i.From, i.To) resp, err := c.Get(path, nil) if err != nil { return nil, err diff --git a/vendor/github.com/sethvargo/go-fastly/director.go b/vendor/github.com/sethvargo/go-fastly/director.go index d5c3dee63..418774c31 100644 --- a/vendor/github.com/sethvargo/go-fastly/director.go +++ b/vendor/github.com/sethvargo/go-fastly/director.go @@ -25,7 +25,7 @@ type DirectorType uint8 // Director represents a director response from the Fastly API. type Director struct { ServiceID string `mapstructure:"service_id"` - Version string `mapstructure:"version"` + Version int `mapstructure:"version"` Name string `mapstructure:"name"` Comment string `mapstructure:"comment"` @@ -51,7 +51,7 @@ type ListDirectorsInput struct { Service string // Version is the specific configuration version (required). - Version string + Version int } // ListDirectors returns the list of directors for the configuration version. @@ -60,11 +60,11 @@ func (c *Client) ListDirectors(i *ListDirectorsInput) ([]*Director, error) { return nil, ErrMissingService } - if i.Version == "" { + if i.Version == 0 { return nil, ErrMissingVersion } - path := fmt.Sprintf("/service/%s/version/%s/director", i.Service, i.Version) + path := fmt.Sprintf("/service/%s/version/%d/director", i.Service, i.Version) resp, err := c.Get(path, nil) if err != nil { return nil, err @@ -83,7 +83,7 @@ type CreateDirectorInput struct { // Service is the ID of the service. Version is the specific configuration // version. Both fields are required. Service string - Version string + Version int Name string `form:"name,omitempty"` Comment string `form:"comment,omitempty"` @@ -98,11 +98,11 @@ func (c *Client) CreateDirector(i *CreateDirectorInput) (*Director, error) { return nil, ErrMissingService } - if i.Version == "" { + if i.Version == 0 { return nil, ErrMissingVersion } - path := fmt.Sprintf("/service/%s/version/%s/director", i.Service, i.Version) + path := fmt.Sprintf("/service/%s/version/%d/director", i.Service, i.Version) resp, err := c.PostForm(path, i, nil) if err != nil { return nil, err @@ -120,7 +120,7 @@ type GetDirectorInput struct { // Service is the ID of the service. Version is the specific configuration // version. Both fields are required. Service string - Version string + Version int // Name is the name of the director to fetch. Name string @@ -132,7 +132,7 @@ func (c *Client) GetDirector(i *GetDirectorInput) (*Director, error) { return nil, ErrMissingService } - if i.Version == "" { + if i.Version == 0 { return nil, ErrMissingVersion } @@ -140,7 +140,7 @@ func (c *Client) GetDirector(i *GetDirectorInput) (*Director, error) { return nil, ErrMissingName } - path := fmt.Sprintf("/service/%s/version/%s/director/%s", i.Service, i.Version, i.Name) + path := fmt.Sprintf("/service/%s/version/%d/director/%s", i.Service, i.Version, i.Name) resp, err := c.Get(path, nil) if err != nil { return nil, err @@ -158,7 +158,7 @@ type UpdateDirectorInput struct { // Service is the ID of the service. Version is the specific configuration // version. Both fields are required. Service string - Version string + Version int // Name is the name of the director to update. Name string @@ -175,7 +175,7 @@ func (c *Client) UpdateDirector(i *UpdateDirectorInput) (*Director, error) { return nil, ErrMissingService } - if i.Version == "" { + if i.Version == 0 { return nil, ErrMissingVersion } @@ -183,7 +183,7 @@ func (c *Client) UpdateDirector(i *UpdateDirectorInput) (*Director, error) { return nil, ErrMissingName } - path := fmt.Sprintf("/service/%s/version/%s/director/%s", i.Service, i.Version, i.Name) + path := fmt.Sprintf("/service/%s/version/%d/director/%s", i.Service, i.Version, i.Name) resp, err := c.PutForm(path, i, nil) if err != nil { return nil, err @@ -201,7 +201,7 @@ type DeleteDirectorInput struct { // Service is the ID of the service. Version is the specific configuration // version. Both fields are required. Service string - Version string + Version int // Name is the name of the director to delete (required). Name string @@ -213,7 +213,7 @@ func (c *Client) DeleteDirector(i *DeleteDirectorInput) error { return ErrMissingService } - if i.Version == "" { + if i.Version == 0 { return ErrMissingVersion } @@ -221,7 +221,7 @@ func (c *Client) DeleteDirector(i *DeleteDirectorInput) error { return ErrMissingName } - path := fmt.Sprintf("/service/%s/version/%s/director/%s", i.Service, i.Version, i.Name) + path := fmt.Sprintf("/service/%s/version/%d/director/%s", i.Service, i.Version, i.Name) resp, err := c.Delete(path, nil) if err != nil { return err diff --git a/vendor/github.com/sethvargo/go-fastly/director_backend.go b/vendor/github.com/sethvargo/go-fastly/director_backend.go index 5cbde76b2..7ca6bcdda 100644 --- a/vendor/github.com/sethvargo/go-fastly/director_backend.go +++ b/vendor/github.com/sethvargo/go-fastly/director_backend.go @@ -9,7 +9,7 @@ import ( // Fastly API. type DirectorBackend struct { ServiceID string `mapstructure:"service_id"` - Version string `mapstructure:"version"` + Version int `mapstructure:"version"` Director string `mapstructure:"director_name"` Backend string `mapstructure:"backend_name"` @@ -24,7 +24,7 @@ type CreateDirectorBackendInput struct { // Service is the ID of the service. Version is the specific configuration // version. Both fields are required. Service string - Version string + Version int // Director is the name of the director (required). Director string @@ -39,7 +39,7 @@ func (c *Client) CreateDirectorBackend(i *CreateDirectorBackendInput) (*Director return nil, ErrMissingService } - if i.Version == "" { + if i.Version == 0 { return nil, ErrMissingVersion } @@ -51,7 +51,7 @@ func (c *Client) CreateDirectorBackend(i *CreateDirectorBackendInput) (*Director return nil, ErrMissingBackend } - path := fmt.Sprintf("/service/%s/version/%s/director/%s/backend/%s", + path := fmt.Sprintf("/service/%s/version/%d/director/%s/backend/%s", i.Service, i.Version, i.Director, i.Backend) resp, err := c.PostForm(path, i, nil) if err != nil { @@ -70,7 +70,7 @@ type GetDirectorBackendInput struct { // Service is the ID of the service. Version is the specific configuration // version. Both fields are required. Service string - Version string + Version int // Director is the name of the director (required). Director string @@ -85,7 +85,7 @@ func (c *Client) GetDirectorBackend(i *GetDirectorBackendInput) (*DirectorBacken return nil, ErrMissingService } - if i.Version == "" { + if i.Version == 0 { return nil, ErrMissingVersion } @@ -97,7 +97,7 @@ func (c *Client) GetDirectorBackend(i *GetDirectorBackendInput) (*DirectorBacken return nil, ErrMissingBackend } - path := fmt.Sprintf("/service/%s/version/%s/director/%s/backend/%s", + path := fmt.Sprintf("/service/%s/version/%d/director/%s/backend/%s", i.Service, i.Version, i.Director, i.Backend) resp, err := c.Get(path, nil) if err != nil { @@ -116,7 +116,7 @@ type DeleteDirectorBackendInput struct { // Service is the ID of the service. Version is the specific configuration // version. Both fields are required. Service string - Version string + Version int // Director is the name of the director (required). Director string @@ -131,7 +131,7 @@ func (c *Client) DeleteDirectorBackend(i *DeleteDirectorBackendInput) error { return ErrMissingService } - if i.Version == "" { + if i.Version == 0 { return ErrMissingVersion } @@ -143,7 +143,7 @@ func (c *Client) DeleteDirectorBackend(i *DeleteDirectorBackendInput) error { return ErrMissingBackend } - path := fmt.Sprintf("/service/%s/version/%s/director/%s/backend/%s", + path := fmt.Sprintf("/service/%s/version/%d/director/%s/backend/%s", i.Service, i.Version, i.Director, i.Backend) resp, err := c.Delete(path, nil) if err != nil { diff --git a/vendor/github.com/sethvargo/go-fastly/domain.go b/vendor/github.com/sethvargo/go-fastly/domain.go index 56356f8eb..b41c2262f 100644 --- a/vendor/github.com/sethvargo/go-fastly/domain.go +++ b/vendor/github.com/sethvargo/go-fastly/domain.go @@ -8,7 +8,7 @@ import ( // Domain represents the the domain name Fastly will serve content for. type Domain struct { ServiceID string `mapstructure:"service_id"` - Version string `mapstructure:"version"` + Version int `mapstructure:"version"` Name string `mapstructure:"name"` Comment string `mapstructure:"comment"` @@ -30,7 +30,7 @@ type ListDomainsInput struct { // Service is the ID of the service. Version is the specific configuration // version. Both fields are required. Service string - Version string + Version int } // ListDomains returns the list of domains for this Service. @@ -39,11 +39,11 @@ func (c *Client) ListDomains(i *ListDomainsInput) ([]*Domain, error) { return nil, ErrMissingService } - if i.Version == "" { + if i.Version == 0 { return nil, ErrMissingVersion } - path := fmt.Sprintf("/service/%s/version/%s/domain", i.Service, i.Version) + path := fmt.Sprintf("/service/%s/version/%d/domain", i.Service, i.Version) resp, err := c.Get(path, nil) if err != nil { return nil, err @@ -62,7 +62,7 @@ type CreateDomainInput struct { // Service is the ID of the service. Version is the specific configuration // version. Both fields are required. Service string - Version string + Version int // Name is the name of the domain that the service will respond to (required). Name string `form:"name"` @@ -77,11 +77,11 @@ func (c *Client) CreateDomain(i *CreateDomainInput) (*Domain, error) { return nil, ErrMissingService } - if i.Version == "" { + if i.Version == 0 { return nil, ErrMissingVersion } - path := fmt.Sprintf("/service/%s/version/%s/domain", i.Service, i.Version) + path := fmt.Sprintf("/service/%s/version/%d/domain", i.Service, i.Version) resp, err := c.PostForm(path, i, nil) if err != nil { return nil, err @@ -99,7 +99,7 @@ type GetDomainInput struct { // Service is the ID of the service. Version is the specific configuration // version. Both fields are required. Service string - Version string + Version int // Name is the name of the domain to fetch. Name string `form:"name"` @@ -111,7 +111,7 @@ func (c *Client) GetDomain(i *GetDomainInput) (*Domain, error) { return nil, ErrMissingService } - if i.Version == "" { + if i.Version == 0 { return nil, ErrMissingVersion } @@ -119,7 +119,7 @@ func (c *Client) GetDomain(i *GetDomainInput) (*Domain, error) { return nil, ErrMissingName } - path := fmt.Sprintf("/service/%s/version/%s/domain/%s", i.Service, i.Version, i.Name) + path := fmt.Sprintf("/service/%s/version/%d/domain/%s", i.Service, i.Version, i.Name) resp, err := c.Get(path, nil) if err != nil { return nil, err @@ -137,7 +137,7 @@ type UpdateDomainInput struct { // Service is the ID of the service. Version is the specific configuration // version. Both fields are required. Service string - Version string + Version int // Name is the name of the domain that the service will respond to (required). Name string @@ -156,7 +156,7 @@ func (c *Client) UpdateDomain(i *UpdateDomainInput) (*Domain, error) { return nil, ErrMissingService } - if i.Version == "" { + if i.Version == 0 { return nil, ErrMissingVersion } @@ -164,7 +164,7 @@ func (c *Client) UpdateDomain(i *UpdateDomainInput) (*Domain, error) { return nil, ErrMissingName } - path := fmt.Sprintf("/service/%s/version/%s/domain/%s", i.Service, i.Version, i.Name) + path := fmt.Sprintf("/service/%s/version/%d/domain/%s", i.Service, i.Version, i.Name) resp, err := c.PutForm(path, i, nil) if err != nil { return nil, err @@ -182,7 +182,7 @@ type DeleteDomainInput struct { // Service is the ID of the service. Version is the specific configuration // version. Both fields are required. Service string - Version string + Version int // Name is the name of the domain that the service will respond to (required). Name string `form:"name"` @@ -194,7 +194,7 @@ func (c *Client) DeleteDomain(i *DeleteDomainInput) error { return ErrMissingService } - if i.Version == "" { + if i.Version == 0 { return ErrMissingVersion } @@ -202,7 +202,7 @@ func (c *Client) DeleteDomain(i *DeleteDomainInput) error { return ErrMissingName } - path := fmt.Sprintf("/service/%s/version/%s/domain/%s", i.Service, i.Version, i.Name) + path := fmt.Sprintf("/service/%s/version/%d/domain/%s", i.Service, i.Version, i.Name) _, err := c.Delete(path, nil) if err != nil { return err diff --git a/vendor/github.com/sethvargo/go-fastly/ftp.go b/vendor/github.com/sethvargo/go-fastly/ftp.go index 95cdf828e..5bdc10119 100644 --- a/vendor/github.com/sethvargo/go-fastly/ftp.go +++ b/vendor/github.com/sethvargo/go-fastly/ftp.go @@ -9,7 +9,7 @@ import ( // FTP represents an FTP logging response from the Fastly API. type FTP struct { ServiceID string `mapstructure:"service_id"` - Version string `mapstructure:"version"` + Version int `mapstructure:"version"` Name string `mapstructure:"name"` Address string `mapstructure:"address"` @@ -43,7 +43,7 @@ type ListFTPsInput struct { Service string // Version is the specific configuration version (required). - Version string + Version int } // ListFTPs returns the list of ftps for the configuration version. @@ -52,11 +52,11 @@ func (c *Client) ListFTPs(i *ListFTPsInput) ([]*FTP, error) { return nil, ErrMissingService } - if i.Version == "" { + if i.Version == 0 { return nil, ErrMissingVersion } - path := fmt.Sprintf("/service/%s/version/%s/logging/ftp", i.Service, i.Version) + path := fmt.Sprintf("/service/%s/version/%d/logging/ftp", i.Service, i.Version) resp, err := c.Get(path, nil) if err != nil { return nil, err @@ -75,7 +75,7 @@ type CreateFTPInput struct { // Service is the ID of the service. Version is the specific configuration // version. Both fields are required. Service string - Version string + Version int Name string `form:"name,omitempty"` Address string `form:"address,omitempty"` @@ -96,11 +96,11 @@ func (c *Client) CreateFTP(i *CreateFTPInput) (*FTP, error) { return nil, ErrMissingService } - if i.Version == "" { + if i.Version == 0 { return nil, ErrMissingVersion } - path := fmt.Sprintf("/service/%s/version/%s/logging/ftp", i.Service, i.Version) + path := fmt.Sprintf("/service/%s/version/%d/logging/ftp", i.Service, i.Version) resp, err := c.PostForm(path, i, nil) if err != nil { return nil, err @@ -118,7 +118,7 @@ type GetFTPInput struct { // Service is the ID of the service. Version is the specific configuration // version. Both fields are required. Service string - Version string + Version int // Name is the name of the FTP to fetch. Name string @@ -130,7 +130,7 @@ func (c *Client) GetFTP(i *GetFTPInput) (*FTP, error) { return nil, ErrMissingService } - if i.Version == "" { + if i.Version == 0 { return nil, ErrMissingVersion } @@ -138,7 +138,7 @@ func (c *Client) GetFTP(i *GetFTPInput) (*FTP, error) { return nil, ErrMissingName } - path := fmt.Sprintf("/service/%s/version/%s/logging/ftp/%s", i.Service, i.Version, i.Name) + path := fmt.Sprintf("/service/%s/version/%d/logging/ftp/%s", i.Service, i.Version, i.Name) resp, err := c.Get(path, nil) if err != nil { return nil, err @@ -156,7 +156,7 @@ type UpdateFTPInput struct { // Service is the ID of the service. Version is the specific configuration // version. Both fields are required. Service string - Version string + Version int // Name is the name of the FTP to update. Name string @@ -180,7 +180,7 @@ func (c *Client) UpdateFTP(i *UpdateFTPInput) (*FTP, error) { return nil, ErrMissingService } - if i.Version == "" { + if i.Version == 0 { return nil, ErrMissingVersion } @@ -188,7 +188,7 @@ func (c *Client) UpdateFTP(i *UpdateFTPInput) (*FTP, error) { return nil, ErrMissingName } - path := fmt.Sprintf("/service/%s/version/%s/logging/ftp/%s", i.Service, i.Version, i.Name) + path := fmt.Sprintf("/service/%s/version/%d/logging/ftp/%s", i.Service, i.Version, i.Name) resp, err := c.PutForm(path, i, nil) if err != nil { return nil, err @@ -206,7 +206,7 @@ type DeleteFTPInput struct { // Service is the ID of the service. Version is the specific configuration // version. Both fields are required. Service string - Version string + Version int // Name is the name of the FTP to delete (required). Name string @@ -218,7 +218,7 @@ func (c *Client) DeleteFTP(i *DeleteFTPInput) error { return ErrMissingService } - if i.Version == "" { + if i.Version == 0 { return ErrMissingVersion } @@ -226,7 +226,7 @@ func (c *Client) DeleteFTP(i *DeleteFTPInput) error { return ErrMissingName } - path := fmt.Sprintf("/service/%s/version/%s/logging/ftp/%s", i.Service, i.Version, i.Name) + path := fmt.Sprintf("/service/%s/version/%d/logging/ftp/%s", i.Service, i.Version, i.Name) resp, err := c.Delete(path, nil) if err != nil { return err diff --git a/vendor/github.com/sethvargo/go-fastly/gcs.go b/vendor/github.com/sethvargo/go-fastly/gcs.go index ef813ac51..950fa7e7f 100644 --- a/vendor/github.com/sethvargo/go-fastly/gcs.go +++ b/vendor/github.com/sethvargo/go-fastly/gcs.go @@ -8,7 +8,7 @@ import ( // GCS represents an GCS logging response from the Fastly API. type GCS struct { ServiceID string `mapstructure:"service_id"` - Version string `mapstructure:"version"` + Version int `mapstructure:"version"` Name string `mapstructure:"name"` Bucket string `mapstructure:"bucket_name"` @@ -38,7 +38,7 @@ type ListGCSsInput struct { Service string // Version is the specific configuration version (required). - Version string + Version int } // ListGCSs returns the list of gcses for the configuration version. @@ -47,11 +47,11 @@ func (c *Client) ListGCSs(i *ListGCSsInput) ([]*GCS, error) { return nil, ErrMissingService } - if i.Version == "" { + if i.Version == 0 { return nil, ErrMissingVersion } - path := fmt.Sprintf("/service/%s/version/%s/logging/gcs", i.Service, i.Version) + path := fmt.Sprintf("/service/%s/version/%d/logging/gcs", i.Service, i.Version) resp, err := c.Get(path, nil) if err != nil { return nil, err @@ -70,7 +70,7 @@ type CreateGCSInput struct { // Service is the ID of the service. Version is the specific configuration // version. Both fields are required. Service string - Version string + Version int Name string `form:"name,omitempty"` Bucket string `form:"bucket_name,omitempty"` @@ -90,11 +90,11 @@ func (c *Client) CreateGCS(i *CreateGCSInput) (*GCS, error) { return nil, ErrMissingService } - if i.Version == "" { + if i.Version == 0 { return nil, ErrMissingVersion } - path := fmt.Sprintf("/service/%s/version/%s/logging/gcs", i.Service, i.Version) + path := fmt.Sprintf("/service/%s/version/%d/logging/gcs", i.Service, i.Version) resp, err := c.PostForm(path, i, nil) if err != nil { return nil, err @@ -112,7 +112,7 @@ type GetGCSInput struct { // Service is the ID of the service. Version is the specific configuration // version. Both fields are required. Service string - Version string + Version int // Name is the name of the GCS to fetch. Name string @@ -124,7 +124,7 @@ func (c *Client) GetGCS(i *GetGCSInput) (*GCS, error) { return nil, ErrMissingService } - if i.Version == "" { + if i.Version == 0 { return nil, ErrMissingVersion } @@ -132,7 +132,7 @@ func (c *Client) GetGCS(i *GetGCSInput) (*GCS, error) { return nil, ErrMissingName } - path := fmt.Sprintf("/service/%s/version/%s/logging/gcs/%s", i.Service, i.Version, i.Name) + path := fmt.Sprintf("/service/%s/version/%d/logging/gcs/%s", i.Service, i.Version, i.Name) resp, err := c.Get(path, nil) if err != nil { return nil, err @@ -150,7 +150,7 @@ type UpdateGCSInput struct { // Service is the ID of the service. Version is the specific configuration // version. Both fields are required. Service string - Version string + Version int // Name is the name of the GCS to update. Name string @@ -173,7 +173,7 @@ func (c *Client) UpdateGCS(i *UpdateGCSInput) (*GCS, error) { return nil, ErrMissingService } - if i.Version == "" { + if i.Version == 0 { return nil, ErrMissingVersion } @@ -181,7 +181,7 @@ func (c *Client) UpdateGCS(i *UpdateGCSInput) (*GCS, error) { return nil, ErrMissingName } - path := fmt.Sprintf("/service/%s/version/%s/logging/gcs/%s", i.Service, i.Version, i.Name) + path := fmt.Sprintf("/service/%s/version/%d/logging/gcs/%s", i.Service, i.Version, i.Name) resp, err := c.PutForm(path, i, nil) if err != nil { return nil, err @@ -199,7 +199,7 @@ type DeleteGCSInput struct { // Service is the ID of the service. Version is the specific configuration // version. Both fields are required. Service string - Version string + Version int // Name is the name of the GCS to delete (required). Name string @@ -211,7 +211,7 @@ func (c *Client) DeleteGCS(i *DeleteGCSInput) error { return ErrMissingService } - if i.Version == "" { + if i.Version == 0 { return ErrMissingVersion } @@ -219,7 +219,7 @@ func (c *Client) DeleteGCS(i *DeleteGCSInput) error { return ErrMissingName } - path := fmt.Sprintf("/service/%s/version/%s/logging/gcs/%s", i.Service, i.Version, i.Name) + path := fmt.Sprintf("/service/%s/version/%d/logging/gcs/%s", i.Service, i.Version, i.Name) resp, err := c.Delete(path, nil) if err != nil { return err diff --git a/vendor/github.com/sethvargo/go-fastly/gzip.go b/vendor/github.com/sethvargo/go-fastly/gzip.go index 2b9f6d80b..002d454dc 100644 --- a/vendor/github.com/sethvargo/go-fastly/gzip.go +++ b/vendor/github.com/sethvargo/go-fastly/gzip.go @@ -8,7 +8,7 @@ import ( // Gzip represents an Gzip logging response from the Fastly API. type Gzip struct { ServiceID string `mapstructure:"service_id"` - Version string `mapstructure:"version"` + Version int `mapstructure:"version"` Name string `mapstructure:"name"` ContentTypes string `mapstructure:"content_types"` @@ -32,7 +32,7 @@ type ListGzipsInput struct { Service string // Version is the specific configuration version (required). - Version string + Version int } // ListGzips returns the list of gzips for the configuration version. @@ -41,11 +41,11 @@ func (c *Client) ListGzips(i *ListGzipsInput) ([]*Gzip, error) { return nil, ErrMissingService } - if i.Version == "" { + if i.Version == 0 { return nil, ErrMissingVersion } - path := fmt.Sprintf("/service/%s/version/%s/gzip", i.Service, i.Version) + path := fmt.Sprintf("/service/%s/version/%d/gzip", i.Service, i.Version) resp, err := c.Get(path, nil) if err != nil { return nil, err @@ -64,7 +64,7 @@ type CreateGzipInput struct { // Service is the ID of the service. Version is the specific configuration // version. Both fields are required. Service string - Version string + Version int Name string `form:"name,omitempty"` ContentTypes string `form:"content_types"` @@ -78,11 +78,11 @@ func (c *Client) CreateGzip(i *CreateGzipInput) (*Gzip, error) { return nil, ErrMissingService } - if i.Version == "" { + if i.Version == 0 { return nil, ErrMissingVersion } - path := fmt.Sprintf("/service/%s/version/%s/gzip", i.Service, i.Version) + path := fmt.Sprintf("/service/%s/version/%d/gzip", i.Service, i.Version) resp, err := c.PostForm(path, i, nil) if err != nil { return nil, err @@ -100,7 +100,7 @@ type GetGzipInput struct { // Service is the ID of the service. Version is the specific configuration // version. Both fields are required. Service string - Version string + Version int // Name is the name of the Gzip to fetch. Name string @@ -112,7 +112,7 @@ func (c *Client) GetGzip(i *GetGzipInput) (*Gzip, error) { return nil, ErrMissingService } - if i.Version == "" { + if i.Version == 0 { return nil, ErrMissingVersion } @@ -120,7 +120,7 @@ func (c *Client) GetGzip(i *GetGzipInput) (*Gzip, error) { return nil, ErrMissingName } - path := fmt.Sprintf("/service/%s/version/%s/gzip/%s", i.Service, i.Version, i.Name) + path := fmt.Sprintf("/service/%s/version/%d/gzip/%s", i.Service, i.Version, i.Name) resp, err := c.Get(path, nil) if err != nil { return nil, err @@ -138,7 +138,7 @@ type UpdateGzipInput struct { // Service is the ID of the service. Version is the specific configuration // version. Both fields are required. Service string - Version string + Version int // Name is the name of the Gzip to update. Name string @@ -155,7 +155,7 @@ func (c *Client) UpdateGzip(i *UpdateGzipInput) (*Gzip, error) { return nil, ErrMissingService } - if i.Version == "" { + if i.Version == 0 { return nil, ErrMissingVersion } @@ -163,7 +163,7 @@ func (c *Client) UpdateGzip(i *UpdateGzipInput) (*Gzip, error) { return nil, ErrMissingName } - path := fmt.Sprintf("/service/%s/version/%s/gzip/%s", i.Service, i.Version, i.Name) + path := fmt.Sprintf("/service/%s/version/%d/gzip/%s", i.Service, i.Version, i.Name) resp, err := c.PutForm(path, i, nil) if err != nil { return nil, err @@ -181,7 +181,7 @@ type DeleteGzipInput struct { // Service is the ID of the service. Version is the specific configuration // version. Both fields are required. Service string - Version string + Version int // Name is the name of the Gzip to delete (required). Name string @@ -193,7 +193,7 @@ func (c *Client) DeleteGzip(i *DeleteGzipInput) error { return ErrMissingService } - if i.Version == "" { + if i.Version == 0 { return ErrMissingVersion } @@ -201,7 +201,7 @@ func (c *Client) DeleteGzip(i *DeleteGzipInput) error { return ErrMissingName } - path := fmt.Sprintf("/service/%s/version/%s/gzip/%s", i.Service, i.Version, i.Name) + path := fmt.Sprintf("/service/%s/version/%d/gzip/%s", i.Service, i.Version, i.Name) resp, err := c.Delete(path, nil) if err != nil { return err diff --git a/vendor/github.com/sethvargo/go-fastly/header.go b/vendor/github.com/sethvargo/go-fastly/header.go index 21bcc0cc1..d4af0d37a 100644 --- a/vendor/github.com/sethvargo/go-fastly/header.go +++ b/vendor/github.com/sethvargo/go-fastly/header.go @@ -51,7 +51,7 @@ type HeaderType string // Header represents a header response from the Fastly API. type Header struct { ServiceID string `mapstructure:"service_id"` - Version string `mapstructure:"version"` + Version int `mapstructure:"version"` Name string `mapstructure:"name"` Action HeaderAction `mapstructure:"action"` @@ -83,7 +83,7 @@ type ListHeadersInput struct { Service string // Version is the specific configuration version (required). - Version string + Version int } // ListHeaders returns the list of headers for the configuration version. @@ -92,11 +92,11 @@ func (c *Client) ListHeaders(i *ListHeadersInput) ([]*Header, error) { return nil, ErrMissingService } - if i.Version == "" { + if i.Version == 0 { return nil, ErrMissingVersion } - path := fmt.Sprintf("/service/%s/version/%s/header", i.Service, i.Version) + path := fmt.Sprintf("/service/%s/version/%d/header", i.Service, i.Version) resp, err := c.Get(path, nil) if err != nil { return nil, err @@ -115,7 +115,7 @@ type CreateHeaderInput struct { // Service is the ID of the service. Version is the specific configuration // version. Both fields are required. Service string - Version string + Version int Name string `form:"name,omitempty"` Action HeaderAction `form:"action,omitempty"` @@ -137,11 +137,11 @@ func (c *Client) CreateHeader(i *CreateHeaderInput) (*Header, error) { return nil, ErrMissingService } - if i.Version == "" { + if i.Version == 0 { return nil, ErrMissingVersion } - path := fmt.Sprintf("/service/%s/version/%s/header", i.Service, i.Version) + path := fmt.Sprintf("/service/%s/version/%d/header", i.Service, i.Version) resp, err := c.PostForm(path, i, nil) if err != nil { return nil, err @@ -159,7 +159,7 @@ type GetHeaderInput struct { // Service is the ID of the service. Version is the specific configuration // version. Both fields are required. Service string - Version string + Version int // Name is the name of the header to fetch. Name string @@ -171,7 +171,7 @@ func (c *Client) GetHeader(i *GetHeaderInput) (*Header, error) { return nil, ErrMissingService } - if i.Version == "" { + if i.Version == 0 { return nil, ErrMissingVersion } @@ -179,7 +179,7 @@ func (c *Client) GetHeader(i *GetHeaderInput) (*Header, error) { return nil, ErrMissingName } - path := fmt.Sprintf("/service/%s/version/%s/header/%s", i.Service, i.Version, i.Name) + path := fmt.Sprintf("/service/%s/version/%d/header/%s", i.Service, i.Version, i.Name) resp, err := c.Get(path, nil) if err != nil { return nil, err @@ -197,7 +197,7 @@ type UpdateHeaderInput struct { // Service is the ID of the service. Version is the specific configuration // version. Both fields are required. Service string - Version string + Version int // Name is the name of the header to update. Name string @@ -222,7 +222,7 @@ func (c *Client) UpdateHeader(i *UpdateHeaderInput) (*Header, error) { return nil, ErrMissingService } - if i.Version == "" { + if i.Version == 0 { return nil, ErrMissingVersion } @@ -230,7 +230,7 @@ func (c *Client) UpdateHeader(i *UpdateHeaderInput) (*Header, error) { return nil, ErrMissingName } - path := fmt.Sprintf("/service/%s/version/%s/header/%s", i.Service, i.Version, i.Name) + path := fmt.Sprintf("/service/%s/version/%d/header/%s", i.Service, i.Version, i.Name) resp, err := c.PutForm(path, i, nil) if err != nil { return nil, err @@ -248,7 +248,7 @@ type DeleteHeaderInput struct { // Service is the ID of the service. Version is the specific configuration // version. Both fields are required. Service string - Version string + Version int // Name is the name of the header to delete (required). Name string @@ -260,7 +260,7 @@ func (c *Client) DeleteHeader(i *DeleteHeaderInput) error { return ErrMissingService } - if i.Version == "" { + if i.Version == 0 { return ErrMissingVersion } @@ -268,7 +268,7 @@ func (c *Client) DeleteHeader(i *DeleteHeaderInput) error { return ErrMissingName } - path := fmt.Sprintf("/service/%s/version/%s/header/%s", i.Service, i.Version, i.Name) + path := fmt.Sprintf("/service/%s/version/%d/header/%s", i.Service, i.Version, i.Name) resp, err := c.Delete(path, nil) if err != nil { return err diff --git a/vendor/github.com/sethvargo/go-fastly/health_check.go b/vendor/github.com/sethvargo/go-fastly/health_check.go index 5a091d2c2..a264c3dd4 100644 --- a/vendor/github.com/sethvargo/go-fastly/health_check.go +++ b/vendor/github.com/sethvargo/go-fastly/health_check.go @@ -8,7 +8,7 @@ import ( // HealthCheck represents a health check response from the Fastly API. type HealthCheck struct { ServiceID string `mapstructure:"service_id"` - Version string `mapstructure:"version"` + Version int `mapstructure:"version"` Name string `mapstructure:"name"` Method string `mapstructure:"method"` @@ -39,7 +39,7 @@ type ListHealthChecksInput struct { Service string // Version is the specific configuration version (required). - Version string + Version int } // ListHealthChecks returns the list of health checks for the configuration @@ -49,11 +49,11 @@ func (c *Client) ListHealthChecks(i *ListHealthChecksInput) ([]*HealthCheck, err return nil, ErrMissingService } - if i.Version == "" { + if i.Version == 0 { return nil, ErrMissingVersion } - path := fmt.Sprintf("/service/%s/version/%s/healthcheck", i.Service, i.Version) + path := fmt.Sprintf("/service/%s/version/%d/healthcheck", i.Service, i.Version) resp, err := c.Get(path, nil) if err != nil { return nil, err @@ -72,7 +72,7 @@ type CreateHealthCheckInput struct { // Service is the ID of the service. Version is the specific configuration // version. Both fields are required. Service string - Version string + Version int Name string `form:"name,omitempty"` Method string `form:"method,omitempty"` @@ -93,11 +93,11 @@ func (c *Client) CreateHealthCheck(i *CreateHealthCheckInput) (*HealthCheck, err return nil, ErrMissingService } - if i.Version == "" { + if i.Version == 0 { return nil, ErrMissingVersion } - path := fmt.Sprintf("/service/%s/version/%s/healthcheck", i.Service, i.Version) + path := fmt.Sprintf("/service/%s/version/%d/healthcheck", i.Service, i.Version) resp, err := c.PostForm(path, i, nil) if err != nil { return nil, err @@ -115,7 +115,7 @@ type GetHealthCheckInput struct { // Service is the ID of the service. Version is the specific configuration // version. Both fields are required. Service string - Version string + Version int // Name is the name of the health check to fetch. Name string @@ -127,7 +127,7 @@ func (c *Client) GetHealthCheck(i *GetHealthCheckInput) (*HealthCheck, error) { return nil, ErrMissingService } - if i.Version == "" { + if i.Version == 0 { return nil, ErrMissingVersion } @@ -135,7 +135,7 @@ func (c *Client) GetHealthCheck(i *GetHealthCheckInput) (*HealthCheck, error) { return nil, ErrMissingName } - path := fmt.Sprintf("/service/%s/version/%s/healthcheck/%s", i.Service, i.Version, i.Name) + path := fmt.Sprintf("/service/%s/version/%d/healthcheck/%s", i.Service, i.Version, i.Name) resp, err := c.Get(path, nil) if err != nil { return nil, err @@ -153,7 +153,7 @@ type UpdateHealthCheckInput struct { // Service is the ID of the service. Version is the specific configuration // version. Both fields are required. Service string - Version string + Version int // Name is the name of the health check to update. Name string @@ -177,7 +177,7 @@ func (c *Client) UpdateHealthCheck(i *UpdateHealthCheckInput) (*HealthCheck, err return nil, ErrMissingService } - if i.Version == "" { + if i.Version == 0 { return nil, ErrMissingVersion } @@ -185,7 +185,7 @@ func (c *Client) UpdateHealthCheck(i *UpdateHealthCheckInput) (*HealthCheck, err return nil, ErrMissingName } - path := fmt.Sprintf("/service/%s/version/%s/healthcheck/%s", i.Service, i.Version, i.Name) + path := fmt.Sprintf("/service/%s/version/%d/healthcheck/%s", i.Service, i.Version, i.Name) resp, err := c.PutForm(path, i, nil) if err != nil { return nil, err @@ -203,7 +203,7 @@ type DeleteHealthCheckInput struct { // Service is the ID of the service. Version is the specific configuration // version. Both fields are required. Service string - Version string + Version int // Name is the name of the health check to delete (required). Name string @@ -215,7 +215,7 @@ func (c *Client) DeleteHealthCheck(i *DeleteHealthCheckInput) error { return ErrMissingService } - if i.Version == "" { + if i.Version == 0 { return ErrMissingVersion } @@ -223,7 +223,7 @@ func (c *Client) DeleteHealthCheck(i *DeleteHealthCheckInput) error { return ErrMissingName } - path := fmt.Sprintf("/service/%s/version/%s/healthcheck/%s", i.Service, i.Version, i.Name) + path := fmt.Sprintf("/service/%s/version/%d/healthcheck/%s", i.Service, i.Version, i.Name) resp, err := c.Delete(path, nil) if err != nil { return err diff --git a/vendor/github.com/sethvargo/go-fastly/logentries.go b/vendor/github.com/sethvargo/go-fastly/logentries.go index 4296cede3..1815eee0a 100644 --- a/vendor/github.com/sethvargo/go-fastly/logentries.go +++ b/vendor/github.com/sethvargo/go-fastly/logentries.go @@ -9,7 +9,7 @@ import ( // Logentries represents a logentries response from the Fastly API. type Logentries struct { ServiceID string `mapstructure:"service_id"` - Version string `mapstructure:"version"` + Version int `mapstructure:"version"` Name string `mapstructure:"name"` Port uint `mapstructure:"port"` @@ -38,7 +38,7 @@ type ListLogentriesInput struct { Service string // Version is the specific configuration version (required). - Version string + Version int } // ListLogentries returns the list of logentries for the configuration version. @@ -47,11 +47,11 @@ func (c *Client) ListLogentries(i *ListLogentriesInput) ([]*Logentries, error) { return nil, ErrMissingService } - if i.Version == "" { + if i.Version == 0 { return nil, ErrMissingVersion } - path := fmt.Sprintf("/service/%s/version/%s/logging/logentries", i.Service, i.Version) + path := fmt.Sprintf("/service/%s/version/%d/logging/logentries", i.Service, i.Version) resp, err := c.Get(path, nil) if err != nil { return nil, err @@ -70,7 +70,7 @@ type CreateLogentriesInput struct { // Service is the ID of the service. Version is the specific configuration // version. Both fields are required. Service string - Version string + Version int Name string `form:"name,omitempty"` Port uint `form:"port,omitempty"` @@ -86,11 +86,11 @@ func (c *Client) CreateLogentries(i *CreateLogentriesInput) (*Logentries, error) return nil, ErrMissingService } - if i.Version == "" { + if i.Version == 0 { return nil, ErrMissingVersion } - path := fmt.Sprintf("/service/%s/version/%s/logging/logentries", i.Service, i.Version) + path := fmt.Sprintf("/service/%s/version/%d/logging/logentries", i.Service, i.Version) resp, err := c.PostForm(path, i, nil) if err != nil { return nil, err @@ -108,7 +108,7 @@ type GetLogentriesInput struct { // Service is the ID of the service. Version is the specific configuration // version. Both fields are required. Service string - Version string + Version int // Name is the name of the logentries to fetch. Name string @@ -120,7 +120,7 @@ func (c *Client) GetLogentries(i *GetLogentriesInput) (*Logentries, error) { return nil, ErrMissingService } - if i.Version == "" { + if i.Version == 0 { return nil, ErrMissingVersion } @@ -128,7 +128,7 @@ func (c *Client) GetLogentries(i *GetLogentriesInput) (*Logentries, error) { return nil, ErrMissingName } - path := fmt.Sprintf("/service/%s/version/%s/logging/logentries/%s", i.Service, i.Version, i.Name) + path := fmt.Sprintf("/service/%s/version/%d/logging/logentries/%s", i.Service, i.Version, i.Name) resp, err := c.Get(path, nil) if err != nil { return nil, err @@ -146,7 +146,7 @@ type UpdateLogentriesInput struct { // Service is the ID of the service. Version is the specific configuration // version. Both fields are required. Service string - Version string + Version int // Name is the name of the logentries to update. Name string @@ -165,7 +165,7 @@ func (c *Client) UpdateLogentries(i *UpdateLogentriesInput) (*Logentries, error) return nil, ErrMissingService } - if i.Version == "" { + if i.Version == 0 { return nil, ErrMissingVersion } @@ -173,7 +173,7 @@ func (c *Client) UpdateLogentries(i *UpdateLogentriesInput) (*Logentries, error) return nil, ErrMissingName } - path := fmt.Sprintf("/service/%s/version/%s/logging/logentries/%s", i.Service, i.Version, i.Name) + path := fmt.Sprintf("/service/%s/version/%d/logging/logentries/%s", i.Service, i.Version, i.Name) resp, err := c.PutForm(path, i, nil) if err != nil { return nil, err @@ -191,7 +191,7 @@ type DeleteLogentriesInput struct { // Service is the ID of the service. Version is the specific configuration // version. Both fields are required. Service string - Version string + Version int // Name is the name of the logentries to delete (required). Name string @@ -203,7 +203,7 @@ func (c *Client) DeleteLogentries(i *DeleteLogentriesInput) error { return ErrMissingService } - if i.Version == "" { + if i.Version == 0 { return ErrMissingVersion } @@ -211,7 +211,7 @@ func (c *Client) DeleteLogentries(i *DeleteLogentriesInput) error { return ErrMissingName } - path := fmt.Sprintf("/service/%s/version/%s/logging/logentries/%s", i.Service, i.Version, i.Name) + path := fmt.Sprintf("/service/%s/version/%d/logging/logentries/%s", i.Service, i.Version, i.Name) resp, err := c.Delete(path, nil) if err != nil { return err diff --git a/vendor/github.com/sethvargo/go-fastly/papertrail.go b/vendor/github.com/sethvargo/go-fastly/papertrail.go index 294c5b1c1..3b7d85e27 100644 --- a/vendor/github.com/sethvargo/go-fastly/papertrail.go +++ b/vendor/github.com/sethvargo/go-fastly/papertrail.go @@ -9,7 +9,7 @@ import ( // Papertrail represents a papertrail response from the Fastly API. type Papertrail struct { ServiceID string `mapstructure:"service_id"` - Version string `mapstructure:"version"` + Version int `mapstructure:"version"` Name string `mapstructure:"name"` Address string `mapstructure:"address"` @@ -37,7 +37,7 @@ type ListPapertrailsInput struct { Service string // Version is the specific configuration version (required). - Version string + Version int } // ListPapertrails returns the list of papertrails for the configuration version. @@ -46,11 +46,11 @@ func (c *Client) ListPapertrails(i *ListPapertrailsInput) ([]*Papertrail, error) return nil, ErrMissingService } - if i.Version == "" { + if i.Version == 0 { return nil, ErrMissingVersion } - path := fmt.Sprintf("/service/%s/version/%s/logging/papertrail", i.Service, i.Version) + path := fmt.Sprintf("/service/%s/version/%d/logging/papertrail", i.Service, i.Version) resp, err := c.Get(path, nil) if err != nil { return nil, err @@ -69,7 +69,7 @@ type CreatePapertrailInput struct { // Service is the ID of the service. Version is the specific configuration // version. Both fields are required. Service string - Version string + Version int Name string `form:"name,omitempty"` Address string `form:"address,omitempty"` @@ -87,11 +87,11 @@ func (c *Client) CreatePapertrail(i *CreatePapertrailInput) (*Papertrail, error) return nil, ErrMissingService } - if i.Version == "" { + if i.Version == 0 { return nil, ErrMissingVersion } - path := fmt.Sprintf("/service/%s/version/%s/logging/papertrail", i.Service, i.Version) + path := fmt.Sprintf("/service/%s/version/%d/logging/papertrail", i.Service, i.Version) resp, err := c.PostForm(path, i, nil) if err != nil { return nil, err @@ -109,7 +109,7 @@ type GetPapertrailInput struct { // Service is the ID of the service. Version is the specific configuration // version. Both fields are required. Service string - Version string + Version int // Name is the name of the papertrail to fetch. Name string @@ -121,7 +121,7 @@ func (c *Client) GetPapertrail(i *GetPapertrailInput) (*Papertrail, error) { return nil, ErrMissingService } - if i.Version == "" { + if i.Version == 0 { return nil, ErrMissingVersion } @@ -129,7 +129,7 @@ func (c *Client) GetPapertrail(i *GetPapertrailInput) (*Papertrail, error) { return nil, ErrMissingName } - path := fmt.Sprintf("/service/%s/version/%s/logging/papertrail/%s", i.Service, i.Version, i.Name) + path := fmt.Sprintf("/service/%s/version/%d/logging/papertrail/%s", i.Service, i.Version, i.Name) resp, err := c.Get(path, nil) if err != nil { return nil, err @@ -147,7 +147,7 @@ type UpdatePapertrailInput struct { // Service is the ID of the service. Version is the specific configuration // version. Both fields are required. Service string - Version string + Version int // Name is the name of the papertrail to update. Name string @@ -168,7 +168,7 @@ func (c *Client) UpdatePapertrail(i *UpdatePapertrailInput) (*Papertrail, error) return nil, ErrMissingService } - if i.Version == "" { + if i.Version == 0 { return nil, ErrMissingVersion } @@ -176,7 +176,7 @@ func (c *Client) UpdatePapertrail(i *UpdatePapertrailInput) (*Papertrail, error) return nil, ErrMissingName } - path := fmt.Sprintf("/service/%s/version/%s/logging/papertrail/%s", i.Service, i.Version, i.Name) + path := fmt.Sprintf("/service/%s/version/%d/logging/papertrail/%s", i.Service, i.Version, i.Name) resp, err := c.PutForm(path, i, nil) if err != nil { return nil, err @@ -194,7 +194,7 @@ type DeletePapertrailInput struct { // Service is the ID of the service. Version is the specific configuration // version. Both fields are required. Service string - Version string + Version int // Name is the name of the papertrail to delete (required). Name string @@ -206,7 +206,7 @@ func (c *Client) DeletePapertrail(i *DeletePapertrailInput) error { return ErrMissingService } - if i.Version == "" { + if i.Version == 0 { return ErrMissingVersion } @@ -214,7 +214,7 @@ func (c *Client) DeletePapertrail(i *DeletePapertrailInput) error { return ErrMissingName } - path := fmt.Sprintf("/service/%s/version/%s/logging/papertrail/%s", i.Service, i.Version, i.Name) + path := fmt.Sprintf("/service/%s/version/%d/logging/papertrail/%s", i.Service, i.Version, i.Name) resp, err := c.Delete(path, nil) if err != nil { return err diff --git a/vendor/github.com/sethvargo/go-fastly/request.go b/vendor/github.com/sethvargo/go-fastly/request.go index 3e1de3a3b..5f2af4959 100644 --- a/vendor/github.com/sethvargo/go-fastly/request.go +++ b/vendor/github.com/sethvargo/go-fastly/request.go @@ -4,7 +4,7 @@ import ( "io" "net/http" "net/url" - "path" + "strings" ) // RequestOptions is the list of options to pass to the request. @@ -31,7 +31,7 @@ func (c *Client) RawRequest(verb, p string, ro *RequestOptions) (*http.Request, // Append the path to the URL. u := *c.url - u.Path = path.Join(c.url.Path, p) + u.Path = strings.TrimRight(c.url.Path, "/") + "/" + strings.TrimLeft(p, "/") // Add the token and other params. var params = make(url.Values) diff --git a/vendor/github.com/sethvargo/go-fastly/request_setting.go b/vendor/github.com/sethvargo/go-fastly/request_setting.go index 41fb9836d..eef9c2d14 100644 --- a/vendor/github.com/sethvargo/go-fastly/request_setting.go +++ b/vendor/github.com/sethvargo/go-fastly/request_setting.go @@ -40,7 +40,7 @@ type RequestSettingXFF string // RequestSetting represents a request setting response from the Fastly API. type RequestSetting struct { ServiceID string `mapstructure:"service_id"` - Version string `mapstructure:"version"` + Version int `mapstructure:"version"` Name string `mapstructure:"name"` ForceMiss bool `mapstructure:"force_miss"` @@ -73,7 +73,7 @@ type ListRequestSettingsInput struct { Service string // Version is the specific configuration version (required). - Version string + Version int } // ListRequestSettings returns the list of request settings for the @@ -83,11 +83,11 @@ func (c *Client) ListRequestSettings(i *ListRequestSettingsInput) ([]*RequestSet return nil, ErrMissingService } - if i.Version == "" { + if i.Version == 0 { return nil, ErrMissingVersion } - path := fmt.Sprintf("/service/%s/version/%s/request_settings", i.Service, i.Version) + path := fmt.Sprintf("/service/%s/version/%d/request_settings", i.Service, i.Version) resp, err := c.Get(path, nil) if err != nil { return nil, err @@ -107,7 +107,7 @@ type CreateRequestSettingInput struct { // Service is the ID of the service. Version is the specific configuration // version. Both fields are required. Service string - Version string + Version int Name string `form:"name,omitempty"` ForceMiss *Compatibool `form:"force_miss,omitempty"` @@ -129,11 +129,11 @@ func (c *Client) CreateRequestSetting(i *CreateRequestSettingInput) (*RequestSet return nil, ErrMissingService } - if i.Version == "" { + if i.Version == 0 { return nil, ErrMissingVersion } - path := fmt.Sprintf("/service/%s/version/%s/request_settings", i.Service, i.Version) + path := fmt.Sprintf("/service/%s/version/%d/request_settings", i.Service, i.Version) resp, err := c.PostForm(path, i, nil) if err != nil { return nil, err @@ -151,7 +151,7 @@ type GetRequestSettingInput struct { // Service is the ID of the service. Version is the specific configuration // version. Both fields are required. Service string - Version string + Version int // Name is the name of the request settings to fetch. Name string @@ -164,7 +164,7 @@ func (c *Client) GetRequestSetting(i *GetRequestSettingInput) (*RequestSetting, return nil, ErrMissingService } - if i.Version == "" { + if i.Version == 0 { return nil, ErrMissingVersion } @@ -172,7 +172,7 @@ func (c *Client) GetRequestSetting(i *GetRequestSettingInput) (*RequestSetting, return nil, ErrMissingName } - path := fmt.Sprintf("/service/%s/version/%s/request_settings/%s", i.Service, i.Version, i.Name) + path := fmt.Sprintf("/service/%s/version/%d/request_settings/%s", i.Service, i.Version, i.Name) resp, err := c.Get(path, nil) if err != nil { return nil, err @@ -191,7 +191,7 @@ type UpdateRequestSettingInput struct { // Service is the ID of the service. Version is the specific configuration // version. Both fields are required. Service string - Version string + Version int // Name is the name of the request settings to update. Name string @@ -216,7 +216,7 @@ func (c *Client) UpdateRequestSetting(i *UpdateRequestSettingInput) (*RequestSet return nil, ErrMissingService } - if i.Version == "" { + if i.Version == 0 { return nil, ErrMissingVersion } @@ -224,7 +224,7 @@ func (c *Client) UpdateRequestSetting(i *UpdateRequestSettingInput) (*RequestSet return nil, ErrMissingName } - path := fmt.Sprintf("/service/%s/version/%s/request_settings/%s", i.Service, i.Version, i.Name) + path := fmt.Sprintf("/service/%s/version/%d/request_settings/%s", i.Service, i.Version, i.Name) resp, err := c.PutForm(path, i, nil) if err != nil { return nil, err @@ -242,7 +242,7 @@ type DeleteRequestSettingInput struct { // Service is the ID of the service. Version is the specific configuration // version. Both fields are required. Service string - Version string + Version int // Name is the name of the request settings to delete (required). Name string @@ -254,7 +254,7 @@ func (c *Client) DeleteRequestSetting(i *DeleteRequestSettingInput) error { return ErrMissingService } - if i.Version == "" { + if i.Version == 0 { return ErrMissingVersion } @@ -262,7 +262,7 @@ func (c *Client) DeleteRequestSetting(i *DeleteRequestSettingInput) error { return ErrMissingName } - path := fmt.Sprintf("/service/%s/version/%s/request_settings/%s", i.Service, i.Version, i.Name) + path := fmt.Sprintf("/service/%s/version/%d/request_settings/%s", i.Service, i.Version, i.Name) resp, err := c.Delete(path, nil) if err != nil { return err diff --git a/vendor/github.com/sethvargo/go-fastly/response_object.go b/vendor/github.com/sethvargo/go-fastly/response_object.go index 1579d58c8..78bc581c5 100644 --- a/vendor/github.com/sethvargo/go-fastly/response_object.go +++ b/vendor/github.com/sethvargo/go-fastly/response_object.go @@ -8,7 +8,7 @@ import ( // ResponseObject represents a response object response from the Fastly API. type ResponseObject struct { ServiceID string `mapstructure:"service_id"` - Version string `mapstructure:"version"` + Version int `mapstructure:"version"` Name string `mapstructure:"name"` Status uint `mapstructure:"status"` @@ -36,7 +36,7 @@ type ListResponseObjectsInput struct { Service string // Version is the specific configuration version (required). - Version string + Version int } // ListResponseObjects returns the list of response objects for the @@ -46,11 +46,11 @@ func (c *Client) ListResponseObjects(i *ListResponseObjectsInput) ([]*ResponseOb return nil, ErrMissingService } - if i.Version == "" { + if i.Version == 0 { return nil, ErrMissingVersion } - path := fmt.Sprintf("/service/%s/version/%s/response_object", i.Service, i.Version) + path := fmt.Sprintf("/service/%s/version/%d/response_object", i.Service, i.Version) resp, err := c.Get(path, nil) if err != nil { return nil, err @@ -70,7 +70,7 @@ type CreateResponseObjectInput struct { // Service is the ID of the service. Version is the specific configuration // version. Both fields are required. Service string - Version string + Version int Name string `form:"name,omitempty"` Status uint `form:"status,omitempty"` @@ -87,11 +87,11 @@ func (c *Client) CreateResponseObject(i *CreateResponseObjectInput) (*ResponseOb return nil, ErrMissingService } - if i.Version == "" { + if i.Version == 0 { return nil, ErrMissingVersion } - path := fmt.Sprintf("/service/%s/version/%s/response_object", i.Service, i.Version) + path := fmt.Sprintf("/service/%s/version/%d/response_object", i.Service, i.Version) resp, err := c.PostForm(path, i, nil) if err != nil { return nil, err @@ -109,7 +109,7 @@ type GetResponseObjectInput struct { // Service is the ID of the service. Version is the specific configuration // version. Both fields are required. Service string - Version string + Version int // Name is the name of the response object to fetch. Name string @@ -122,7 +122,7 @@ func (c *Client) GetResponseObject(i *GetResponseObjectInput) (*ResponseObject, return nil, ErrMissingService } - if i.Version == "" { + if i.Version == 0 { return nil, ErrMissingVersion } @@ -130,7 +130,7 @@ func (c *Client) GetResponseObject(i *GetResponseObjectInput) (*ResponseObject, return nil, ErrMissingName } - path := fmt.Sprintf("/service/%s/version/%s/response_object/%s", i.Service, i.Version, i.Name) + path := fmt.Sprintf("/service/%s/version/%d/response_object/%s", i.Service, i.Version, i.Name) resp, err := c.Get(path, nil) if err != nil { return nil, err @@ -149,7 +149,7 @@ type UpdateResponseObjectInput struct { // Service is the ID of the service. Version is the specific configuration // version. Both fields are required. Service string - Version string + Version int // Name is the name of the response object to update. Name string @@ -169,7 +169,7 @@ func (c *Client) UpdateResponseObject(i *UpdateResponseObjectInput) (*ResponseOb return nil, ErrMissingService } - if i.Version == "" { + if i.Version == 0 { return nil, ErrMissingVersion } @@ -177,7 +177,7 @@ func (c *Client) UpdateResponseObject(i *UpdateResponseObjectInput) (*ResponseOb return nil, ErrMissingName } - path := fmt.Sprintf("/service/%s/version/%s/response_object/%s", i.Service, i.Version, i.Name) + path := fmt.Sprintf("/service/%s/version/%d/response_object/%s", i.Service, i.Version, i.Name) resp, err := c.PutForm(path, i, nil) if err != nil { return nil, err @@ -195,7 +195,7 @@ type DeleteResponseObjectInput struct { // Service is the ID of the service. Version is the specific configuration // version. Both fields are required. Service string - Version string + Version int // Name is the name of the response object to delete (required). Name string @@ -207,7 +207,7 @@ func (c *Client) DeleteResponseObject(i *DeleteResponseObjectInput) error { return ErrMissingService } - if i.Version == "" { + if i.Version == 0 { return ErrMissingVersion } @@ -215,7 +215,7 @@ func (c *Client) DeleteResponseObject(i *DeleteResponseObjectInput) error { return ErrMissingName } - path := fmt.Sprintf("/service/%s/version/%s/response_object/%s", i.Service, i.Version, i.Name) + path := fmt.Sprintf("/service/%s/version/%d/response_object/%s", i.Service, i.Version, i.Name) resp, err := c.Delete(path, nil) if err != nil { return err diff --git a/vendor/github.com/sethvargo/go-fastly/s3.go b/vendor/github.com/sethvargo/go-fastly/s3.go index ed20bf9ad..89fda06c6 100644 --- a/vendor/github.com/sethvargo/go-fastly/s3.go +++ b/vendor/github.com/sethvargo/go-fastly/s3.go @@ -16,7 +16,7 @@ const ( // S3 represents a S3 response from the Fastly API. type S3 struct { ServiceID string `mapstructure:"service_id"` - Version string `mapstructure:"version"` + Version int `mapstructure:"version"` Name string `mapstructure:"name"` BucketName string `mapstructure:"bucket_name"` @@ -52,7 +52,7 @@ type ListS3sInput struct { Service string // Version is the specific configuration version (required). - Version string + Version int } // ListS3s returns the list of S3s for the configuration version. @@ -61,11 +61,11 @@ func (c *Client) ListS3s(i *ListS3sInput) ([]*S3, error) { return nil, ErrMissingService } - if i.Version == "" { + if i.Version == 0 { return nil, ErrMissingVersion } - path := fmt.Sprintf("/service/%s/version/%s/logging/s3", i.Service, i.Version) + path := fmt.Sprintf("/service/%s/version/%d/logging/s3", i.Service, i.Version) resp, err := c.Get(path, nil) if err != nil { return nil, err @@ -84,7 +84,7 @@ type CreateS3Input struct { // Service is the ID of the service. Version is the specific configuration // version. Both fields are required. Service string - Version string + Version int Name string `form:"name,omitempty"` BucketName string `form:"bucket_name,omitempty"` @@ -107,11 +107,11 @@ func (c *Client) CreateS3(i *CreateS3Input) (*S3, error) { return nil, ErrMissingService } - if i.Version == "" { + if i.Version == 0 { return nil, ErrMissingVersion } - path := fmt.Sprintf("/service/%s/version/%s/logging/s3", i.Service, i.Version) + path := fmt.Sprintf("/service/%s/version/%d/logging/s3", i.Service, i.Version) resp, err := c.PostForm(path, i, nil) if err != nil { return nil, err @@ -129,7 +129,7 @@ type GetS3Input struct { // Service is the ID of the service. Version is the specific configuration // version. Both fields are required. Service string - Version string + Version int // Name is the name of the S3 to fetch. Name string @@ -141,7 +141,7 @@ func (c *Client) GetS3(i *GetS3Input) (*S3, error) { return nil, ErrMissingService } - if i.Version == "" { + if i.Version == 0 { return nil, ErrMissingVersion } @@ -149,7 +149,7 @@ func (c *Client) GetS3(i *GetS3Input) (*S3, error) { return nil, ErrMissingName } - path := fmt.Sprintf("/service/%s/version/%s/logging/s3/%s", i.Service, i.Version, i.Name) + path := fmt.Sprintf("/service/%s/version/%d/logging/s3/%s", i.Service, i.Version, i.Name) resp, err := c.Get(path, nil) if err != nil { return nil, err @@ -167,7 +167,7 @@ type UpdateS3Input struct { // Service is the ID of the service. Version is the specific configuration // version. Both fields are required. Service string - Version string + Version int // Name is the name of the S3 to update. Name string @@ -193,7 +193,7 @@ func (c *Client) UpdateS3(i *UpdateS3Input) (*S3, error) { return nil, ErrMissingService } - if i.Version == "" { + if i.Version == 0 { return nil, ErrMissingVersion } @@ -201,7 +201,7 @@ func (c *Client) UpdateS3(i *UpdateS3Input) (*S3, error) { return nil, ErrMissingName } - path := fmt.Sprintf("/service/%s/version/%s/logging/s3/%s", i.Service, i.Version, i.Name) + path := fmt.Sprintf("/service/%s/version/%d/logging/s3/%s", i.Service, i.Version, i.Name) resp, err := c.PutForm(path, i, nil) if err != nil { return nil, err @@ -219,7 +219,7 @@ type DeleteS3Input struct { // Service is the ID of the service. Version is the specific configuration // version. Both fields are required. Service string - Version string + Version int // Name is the name of the S3 to delete (required). Name string @@ -231,7 +231,7 @@ func (c *Client) DeleteS3(i *DeleteS3Input) error { return ErrMissingService } - if i.Version == "" { + if i.Version == 0 { return ErrMissingVersion } @@ -239,7 +239,7 @@ func (c *Client) DeleteS3(i *DeleteS3Input) error { return ErrMissingName } - path := fmt.Sprintf("/service/%s/version/%s/logging/s3/%s", i.Service, i.Version, i.Name) + path := fmt.Sprintf("/service/%s/version/%d/logging/s3/%s", i.Service, i.Version, i.Name) resp, err := c.Delete(path, nil) if err != nil { return err diff --git a/vendor/github.com/sethvargo/go-fastly/settings.go b/vendor/github.com/sethvargo/go-fastly/settings.go index 02ea6f234..8208acf15 100644 --- a/vendor/github.com/sethvargo/go-fastly/settings.go +++ b/vendor/github.com/sethvargo/go-fastly/settings.go @@ -5,7 +5,7 @@ import "fmt" // Settings represents a backend response from the Fastly API. type Settings struct { ServiceID string `mapstructure:"service_id"` - Version string `mapstructure:"version"` + Version int `mapstructure:"version"` DefaultTTL uint `mapstructure:"general.default_ttl"` DefaultHost string `mapstructure:"general.default_host"` @@ -16,7 +16,7 @@ type GetSettingsInput struct { // Service is the ID of the service. Version is the specific configuration // version. Both fields are required. Service string - Version string + Version int } // GetSettings gets the backend configuration with the given parameters. @@ -25,11 +25,11 @@ func (c *Client) GetSettings(i *GetSettingsInput) (*Settings, error) { return nil, ErrMissingService } - if i.Version == "" { + if i.Version == 0 { return nil, ErrMissingVersion } - path := fmt.Sprintf("/service/%s/version/%s/settings", i.Service, i.Version) + path := fmt.Sprintf("/service/%s/version/%d/settings", i.Service, i.Version) resp, err := c.Get(path, nil) if err != nil { return nil, err @@ -47,9 +47,9 @@ type UpdateSettingsInput struct { // Service is the ID of the service. Version is the specific configuration // version. Both fields are required. Service string - Version string + Version int - DefaultTTL uint `form:"general.default_ttl,omitempty"` + DefaultTTL uint `form:"general.default_ttl"` DefaultHost string `form:"general.default_host,omitempty"` } @@ -59,11 +59,11 @@ func (c *Client) UpdateSettings(i *UpdateSettingsInput) (*Settings, error) { return nil, ErrMissingService } - if i.Version == "" { + if i.Version == 0 { return nil, ErrMissingVersion } - path := fmt.Sprintf("/service/%s/version/%s/settings", i.Service, i.Version) + path := fmt.Sprintf("/service/%s/version/%d/settings", i.Service, i.Version) resp, err := c.PutForm(path, i, nil) if err != nil { return nil, err diff --git a/vendor/github.com/sethvargo/go-fastly/sumologic.go b/vendor/github.com/sethvargo/go-fastly/sumologic.go index 371e7a6e8..c94f98de7 100644 --- a/vendor/github.com/sethvargo/go-fastly/sumologic.go +++ b/vendor/github.com/sethvargo/go-fastly/sumologic.go @@ -9,13 +9,15 @@ import ( // Sumologic represents a sumologic response from the Fastly API. type Sumologic struct { ServiceID string `mapstructure:"service_id"` - Version string `mapstructure:"version"` + Version int `mapstructure:"version"` Name string `mapstructure:"name"` Address string `mapstructure:"address"` URL string `mapstructure:"url"` Format string `mapstructure:"format"` ResponseCondition string `mapstructure:"response_condition"` + MessageType string `mapstructure:"message_type"` + FormatVersion int `mapstructure:"format_version"` CreatedAt *time.Time `mapstructure:"created_at"` UpdatedAt *time.Time `mapstructure:"updated_at"` DeletedAt *time.Time `mapstructure:"deleted_at"` @@ -37,7 +39,7 @@ type ListSumologicsInput struct { Service string // Version is the specific configuration version (required). - Version string + Version int } // ListSumologics returns the list of sumologics for the configuration version. @@ -46,11 +48,11 @@ func (c *Client) ListSumologics(i *ListSumologicsInput) ([]*Sumologic, error) { return nil, ErrMissingService } - if i.Version == "" { + if i.Version == 0 { return nil, ErrMissingVersion } - path := fmt.Sprintf("/service/%s/version/%s/logging/sumologic", i.Service, i.Version) + path := fmt.Sprintf("/service/%s/version/%d/logging/sumologic", i.Service, i.Version) resp, err := c.Get(path, nil) if err != nil { return nil, err @@ -69,13 +71,15 @@ type CreateSumologicInput struct { // Service is the ID of the service. Version is the specific configuration // version. Both fields are required. Service string - Version string + Version int Name string `form:"name,omitempty"` Address string `form:"address,omitempty"` URL string `form:"url,omitempty"` Format string `form:"format,omitempty"` ResponseCondition string `form:"response_condition,omitempty"` + MessageType string `form:"message_type,omitempty"` + FormatVersion int `form:"format_version,omitempty"` } // CreateSumologic creates a new Fastly sumologic. @@ -84,11 +88,11 @@ func (c *Client) CreateSumologic(i *CreateSumologicInput) (*Sumologic, error) { return nil, ErrMissingService } - if i.Version == "" { + if i.Version == 0 { return nil, ErrMissingVersion } - path := fmt.Sprintf("/service/%s/version/%s/logging/sumologic", i.Service, i.Version) + path := fmt.Sprintf("/service/%s/version/%d/logging/sumologic", i.Service, i.Version) resp, err := c.PostForm(path, i, nil) if err != nil { return nil, err @@ -106,7 +110,7 @@ type GetSumologicInput struct { // Service is the ID of the service. Version is the specific configuration // version. Both fields are required. Service string - Version string + Version int // Name is the name of the sumologic to fetch. Name string @@ -118,7 +122,7 @@ func (c *Client) GetSumologic(i *GetSumologicInput) (*Sumologic, error) { return nil, ErrMissingService } - if i.Version == "" { + if i.Version == 0 { return nil, ErrMissingVersion } @@ -126,7 +130,7 @@ func (c *Client) GetSumologic(i *GetSumologicInput) (*Sumologic, error) { return nil, ErrMissingName } - path := fmt.Sprintf("/service/%s/version/%s/logging/sumologic/%s", i.Service, i.Version, i.Name) + path := fmt.Sprintf("/service/%s/version/%d/logging/sumologic/%s", i.Service, i.Version, i.Name) resp, err := c.Get(path, nil) if err != nil { return nil, err @@ -144,7 +148,7 @@ type UpdateSumologicInput struct { // Service is the ID of the service. Version is the specific configuration // version. Both fields are required. Service string - Version string + Version int // Name is the name of the sumologic to update. Name string @@ -154,6 +158,8 @@ type UpdateSumologicInput struct { URL string `form:"url,omitempty"` Format string `form:"format,omitempty"` ResponseCondition string `form:"response_condition,omitempty"` + MessageType string `form:"message_type,omitempty"` + FormatVersion int `form:"format_version,omitempty"` } // UpdateSumologic updates a specific sumologic. @@ -162,7 +168,7 @@ func (c *Client) UpdateSumologic(i *UpdateSumologicInput) (*Sumologic, error) { return nil, ErrMissingService } - if i.Version == "" { + if i.Version == 0 { return nil, ErrMissingVersion } @@ -170,7 +176,7 @@ func (c *Client) UpdateSumologic(i *UpdateSumologicInput) (*Sumologic, error) { return nil, ErrMissingName } - path := fmt.Sprintf("/service/%s/version/%s/logging/sumologic/%s", i.Service, i.Version, i.Name) + path := fmt.Sprintf("/service/%s/version/%d/logging/sumologic/%s", i.Service, i.Version, i.Name) resp, err := c.PutForm(path, i, nil) if err != nil { return nil, err @@ -188,7 +194,7 @@ type DeleteSumologicInput struct { // Service is the ID of the service. Version is the specific configuration // version. Both fields are required. Service string - Version string + Version int // Name is the name of the sumologic to delete (required). Name string @@ -200,7 +206,7 @@ func (c *Client) DeleteSumologic(i *DeleteSumologicInput) error { return ErrMissingService } - if i.Version == "" { + if i.Version == 0 { return ErrMissingVersion } @@ -208,7 +214,7 @@ func (c *Client) DeleteSumologic(i *DeleteSumologicInput) error { return ErrMissingName } - path := fmt.Sprintf("/service/%s/version/%s/logging/sumologic/%s", i.Service, i.Version, i.Name) + path := fmt.Sprintf("/service/%s/version/%d/logging/sumologic/%s", i.Service, i.Version, i.Name) resp, err := c.Delete(path, nil) if err != nil { return err diff --git a/vendor/github.com/sethvargo/go-fastly/syslog.go b/vendor/github.com/sethvargo/go-fastly/syslog.go index 5d2a08303..dc6c548f9 100644 --- a/vendor/github.com/sethvargo/go-fastly/syslog.go +++ b/vendor/github.com/sethvargo/go-fastly/syslog.go @@ -9,7 +9,7 @@ import ( // Syslog represents a syslog response from the Fastly API. type Syslog struct { ServiceID string `mapstructure:"service_id"` - Version string `mapstructure:"version"` + Version int `mapstructure:"version"` Name string `mapstructure:"name"` Address string `mapstructure:"address"` @@ -18,6 +18,7 @@ type Syslog struct { TLSCACert string `mapstructure:"tls_ca_cert"` Token string `mapstructure:"token"` Format string `mapstructure:"format"` + FormatVersion uint `mapstructure:"format_version"` ResponseCondition string `mapstructure:"response_condition"` CreatedAt *time.Time `mapstructure:"created_at"` UpdatedAt *time.Time `mapstructure:"updated_at"` @@ -40,7 +41,7 @@ type ListSyslogsInput struct { Service string // Version is the specific configuration version (required). - Version string + Version int } // ListSyslogs returns the list of syslogs for the configuration version. @@ -49,11 +50,11 @@ func (c *Client) ListSyslogs(i *ListSyslogsInput) ([]*Syslog, error) { return nil, ErrMissingService } - if i.Version == "" { + if i.Version == 0 { return nil, ErrMissingVersion } - path := fmt.Sprintf("/service/%s/version/%s/logging/syslog", i.Service, i.Version) + path := fmt.Sprintf("/service/%s/version/%d/logging/syslog", i.Service, i.Version) resp, err := c.Get(path, nil) if err != nil { return nil, err @@ -72,7 +73,7 @@ type CreateSyslogInput struct { // Service is the ID of the service. Version is the specific configuration // version. Both fields are required. Service string - Version string + Version int Name string `form:"name,omitempty"` Address string `form:"address,omitempty"` @@ -81,6 +82,7 @@ type CreateSyslogInput struct { TLSCACert string `form:"tls_ca_cert,omitempty"` Token string `form:"token,omitempty"` Format string `form:"format,omitempty"` + FormatVersion uint `form:"format_version,omitempty"` ResponseCondition string `form:"response_condition,omitempty"` } @@ -90,11 +92,11 @@ func (c *Client) CreateSyslog(i *CreateSyslogInput) (*Syslog, error) { return nil, ErrMissingService } - if i.Version == "" { + if i.Version == 0 { return nil, ErrMissingVersion } - path := fmt.Sprintf("/service/%s/version/%s/logging/syslog", i.Service, i.Version) + path := fmt.Sprintf("/service/%s/version/%d/logging/syslog", i.Service, i.Version) resp, err := c.PostForm(path, i, nil) if err != nil { return nil, err @@ -112,7 +114,7 @@ type GetSyslogInput struct { // Service is the ID of the service. Version is the specific configuration // version. Both fields are required. Service string - Version string + Version int // Name is the name of the syslog to fetch. Name string @@ -124,7 +126,7 @@ func (c *Client) GetSyslog(i *GetSyslogInput) (*Syslog, error) { return nil, ErrMissingService } - if i.Version == "" { + if i.Version == 0 { return nil, ErrMissingVersion } @@ -132,7 +134,7 @@ func (c *Client) GetSyslog(i *GetSyslogInput) (*Syslog, error) { return nil, ErrMissingName } - path := fmt.Sprintf("/service/%s/version/%s/logging/syslog/%s", i.Service, i.Version, i.Name) + path := fmt.Sprintf("/service/%s/version/%d/logging/syslog/%s", i.Service, i.Version, i.Name) resp, err := c.Get(path, nil) if err != nil { return nil, err @@ -150,7 +152,7 @@ type UpdateSyslogInput struct { // Service is the ID of the service. Version is the specific configuration // version. Both fields are required. Service string - Version string + Version int // Name is the name of the syslog to update. Name string @@ -162,6 +164,7 @@ type UpdateSyslogInput struct { TLSCACert string `form:"tls_ca_cert,omitempty"` Token string `form:"token,omitempty"` Format string `form:"format,omitempty"` + FormatVersion uint `form:"format_version,omitempty"` ResponseCondition string `form:"response_condition,omitempty"` } @@ -171,7 +174,7 @@ func (c *Client) UpdateSyslog(i *UpdateSyslogInput) (*Syslog, error) { return nil, ErrMissingService } - if i.Version == "" { + if i.Version == 0 { return nil, ErrMissingVersion } @@ -179,7 +182,7 @@ func (c *Client) UpdateSyslog(i *UpdateSyslogInput) (*Syslog, error) { return nil, ErrMissingName } - path := fmt.Sprintf("/service/%s/version/%s/logging/syslog/%s", i.Service, i.Version, i.Name) + path := fmt.Sprintf("/service/%s/version/%d/logging/syslog/%s", i.Service, i.Version, i.Name) resp, err := c.PutForm(path, i, nil) if err != nil { return nil, err @@ -197,7 +200,7 @@ type DeleteSyslogInput struct { // Service is the ID of the service. Version is the specific configuration // version. Both fields are required. Service string - Version string + Version int // Name is the name of the syslog to delete (required). Name string @@ -209,7 +212,7 @@ func (c *Client) DeleteSyslog(i *DeleteSyslogInput) error { return ErrMissingService } - if i.Version == "" { + if i.Version == 0 { return ErrMissingVersion } @@ -217,7 +220,7 @@ func (c *Client) DeleteSyslog(i *DeleteSyslogInput) error { return ErrMissingName } - path := fmt.Sprintf("/service/%s/version/%s/logging/syslog/%s", i.Service, i.Version, i.Name) + path := fmt.Sprintf("/service/%s/version/%d/logging/syslog/%s", i.Service, i.Version, i.Name) resp, err := c.Delete(path, nil) if err != nil { return err diff --git a/vendor/github.com/sethvargo/go-fastly/vcl.go b/vendor/github.com/sethvargo/go-fastly/vcl.go index 63be5a652..dda137be4 100644 --- a/vendor/github.com/sethvargo/go-fastly/vcl.go +++ b/vendor/github.com/sethvargo/go-fastly/vcl.go @@ -8,7 +8,7 @@ import ( // VCL represents a response about VCL from the Fastly API. type VCL struct { ServiceID string `mapstructure:"service_id"` - Version string `mapstructure:"version"` + Version int `mapstructure:"version"` Name string `mapstructure:"name"` Main bool `mapstructure:"main"` @@ -31,7 +31,7 @@ type ListVCLsInput struct { Service string // Version is the specific configuration version (required). - Version string + Version int } // ListVCLs returns the list of VCLs for the configuration version. @@ -40,11 +40,11 @@ func (c *Client) ListVCLs(i *ListVCLsInput) ([]*VCL, error) { return nil, ErrMissingService } - if i.Version == "" { + if i.Version == 0 { return nil, ErrMissingVersion } - path := fmt.Sprintf("/service/%s/version/%s/vcl", i.Service, i.Version) + path := fmt.Sprintf("/service/%s/version/%d/vcl", i.Service, i.Version) resp, err := c.Get(path, nil) if err != nil { return nil, err @@ -63,7 +63,7 @@ type GetVCLInput struct { // Service is the ID of the service. Version is the specific configuration // version. Both fields are required. Service string - Version string + Version int // Name is the name of the VCL to fetch. Name string @@ -75,7 +75,7 @@ func (c *Client) GetVCL(i *GetVCLInput) (*VCL, error) { return nil, ErrMissingService } - if i.Version == "" { + if i.Version == 0 { return nil, ErrMissingVersion } @@ -83,7 +83,7 @@ func (c *Client) GetVCL(i *GetVCLInput) (*VCL, error) { return nil, ErrMissingName } - path := fmt.Sprintf("/service/%s/version/%s/vcl/%s", i.Service, i.Version, i.Name) + path := fmt.Sprintf("/service/%s/version/%d/vcl/%s", i.Service, i.Version, i.Name) resp, err := c.Get(path, nil) if err != nil { return nil, err @@ -101,7 +101,7 @@ type GetGeneratedVCLInput struct { // Service is the ID of the service. Version is the specific configuration // version. Both fields are required. Service string - Version string + Version int } // GetGeneratedVCL gets the VCL configuration with the given parameters. @@ -110,11 +110,11 @@ func (c *Client) GetGeneratedVCL(i *GetGeneratedVCLInput) (*VCL, error) { return nil, ErrMissingService } - if i.Version == "" { + if i.Version == 0 { return nil, ErrMissingVersion } - path := fmt.Sprintf("/service/%s/version/%s/generated_vcl", i.Service, i.Version) + path := fmt.Sprintf("/service/%s/version/%d/generated_vcl", i.Service, i.Version) resp, err := c.Get(path, nil) if err != nil { return nil, err @@ -132,7 +132,7 @@ type CreateVCLInput struct { // Service is the ID of the service. Version is the specific configuration // version. Both fields are required. Service string - Version string + Version int Name string `form:"name,omitempty"` Content string `form:"content,omitempty"` @@ -144,11 +144,11 @@ func (c *Client) CreateVCL(i *CreateVCLInput) (*VCL, error) { return nil, ErrMissingService } - if i.Version == "" { + if i.Version == 0 { return nil, ErrMissingVersion } - path := fmt.Sprintf("/service/%s/version/%s/vcl", i.Service, i.Version) + path := fmt.Sprintf("/service/%s/version/%d/vcl", i.Service, i.Version) resp, err := c.PostForm(path, i, nil) if err != nil { return nil, err @@ -166,7 +166,7 @@ type UpdateVCLInput struct { // Service is the ID of the service. Version is the specific configuration // version. Both fields are required. Service string - Version string + Version int // Name is the name of the VCL to update (required). Name string @@ -181,7 +181,7 @@ func (c *Client) UpdateVCL(i *UpdateVCLInput) (*VCL, error) { return nil, ErrMissingService } - if i.Version == "" { + if i.Version == 0 { return nil, ErrMissingVersion } @@ -189,7 +189,7 @@ func (c *Client) UpdateVCL(i *UpdateVCLInput) (*VCL, error) { return nil, ErrMissingName } - path := fmt.Sprintf("/service/%s/version/%s/vcl/%s", i.Service, i.Version, i.Name) + path := fmt.Sprintf("/service/%s/version/%d/vcl/%s", i.Service, i.Version, i.Name) resp, err := c.PutForm(path, i, nil) if err != nil { return nil, err @@ -207,7 +207,7 @@ type ActivateVCLInput struct { // Service is the ID of the service. Version is the specific configuration // version. Both fields are required. Service string - Version string + Version int // Name is the name of the VCL to mark as main (required). Name string @@ -219,7 +219,7 @@ func (c *Client) ActivateVCL(i *ActivateVCLInput) (*VCL, error) { return nil, ErrMissingService } - if i.Version == "" { + if i.Version == 0 { return nil, ErrMissingVersion } @@ -227,7 +227,7 @@ func (c *Client) ActivateVCL(i *ActivateVCLInput) (*VCL, error) { return nil, ErrMissingName } - path := fmt.Sprintf("/service/%s/version/%s/vcl/%s/main", i.Service, i.Version, i.Name) + path := fmt.Sprintf("/service/%s/version/%d/vcl/%s/main", i.Service, i.Version, i.Name) resp, err := c.Put(path, nil) if err != nil { return nil, err @@ -245,7 +245,7 @@ type DeleteVCLInput struct { // Service is the ID of the service. Version is the specific configuration // version. Both fields are required. Service string - Version string + Version int // Name is the name of the VCL to delete (required). Name string @@ -257,7 +257,7 @@ func (c *Client) DeleteVCL(i *DeleteVCLInput) error { return ErrMissingService } - if i.Version == "" { + if i.Version == 0 { return ErrMissingVersion } @@ -265,7 +265,7 @@ func (c *Client) DeleteVCL(i *DeleteVCLInput) error { return ErrMissingName } - path := fmt.Sprintf("/service/%s/version/%s/vcl/%s", i.Service, i.Version, i.Name) + path := fmt.Sprintf("/service/%s/version/%d/vcl/%s", i.Service, i.Version, i.Name) resp, err := c.Delete(path, nil) if err != nil { return err diff --git a/vendor/github.com/sethvargo/go-fastly/version.go b/vendor/github.com/sethvargo/go-fastly/version.go index 8b54c9cee..f245eebfa 100644 --- a/vendor/github.com/sethvargo/go-fastly/version.go +++ b/vendor/github.com/sethvargo/go-fastly/version.go @@ -7,14 +7,14 @@ import ( // Version represents a distinct configuration version. type Version struct { - Number string `mapstructure:"number"` - Comment string `mapstructure:"comment"` - ServiceID string `mapstructure:"service_id"` - Active bool `mapstructure:"active"` - Locked bool `mapstructure:"locked"` - Deployed bool `mapstructure:"deployed"` - Staging bool `mapstructure:"staging"` - Testing bool `mapstructure:"testing"` + Number int `mapstructure:"number"` + Comment string `mapstructure:"comment"` + ServiceID string `mapstructure:"service_id"` + Active bool `mapstructure:"active"` + Locked bool `mapstructure:"locked"` + Deployed bool `mapstructure:"deployed"` + Staging bool `mapstructure:"staging"` + Testing bool `mapstructure:"testing"` } // versionsByNumber is a sortable list of versions. This is used by the version @@ -114,7 +114,7 @@ type GetVersionInput struct { Service string // Version is the version number to fetch (required). - Version string + Version int } // GetVersion fetches a version with the given information. @@ -123,11 +123,11 @@ func (c *Client) GetVersion(i *GetVersionInput) (*Version, error) { return nil, ErrMissingService } - if i.Version == "" { + if i.Version == 0 { return nil, ErrMissingVersion } - path := fmt.Sprintf("/service/%s/version/%s", i.Service, i.Version) + path := fmt.Sprintf("/service/%s/version/%d", i.Service, i.Version) resp, err := c.Get(path, nil) if err != nil { return nil, err @@ -145,7 +145,7 @@ type UpdateVersionInput struct { // Service is the ID of the service. Version is the specific configuration // version. Both fields are required. Service string - Version string + Version int Comment string `form:"comment,omitempty"` } @@ -156,11 +156,11 @@ func (c *Client) UpdateVersion(i *UpdateVersionInput) (*Version, error) { return nil, ErrMissingService } - if i.Version == "" { + if i.Version == 0 { return nil, ErrMissingVersion } - path := fmt.Sprintf("/service/%s/version/%s", i.Service, i.Version) + path := fmt.Sprintf("/service/%s/version/%d", i.Service, i.Version) resp, err := c.PutForm(path, i, nil) if err != nil { return nil, err @@ -178,7 +178,7 @@ type ActivateVersionInput struct { // Service is the ID of the service. Version is the specific configuration // version. Both fields are required. Service string - Version string + Version int } // ActivateVersion activates the given version. @@ -187,11 +187,11 @@ func (c *Client) ActivateVersion(i *ActivateVersionInput) (*Version, error) { return nil, ErrMissingService } - if i.Version == "" { + if i.Version == 0 { return nil, ErrMissingVersion } - path := fmt.Sprintf("/service/%s/version/%s/activate", i.Service, i.Version) + path := fmt.Sprintf("/service/%s/version/%d/activate", i.Service, i.Version) resp, err := c.Put(path, nil) if err != nil { return nil, err @@ -209,7 +209,7 @@ type DeactivateVersionInput struct { // Service is the ID of the service. Version is the specific configuration // version. Both fields are required. Service string - Version string + Version int } // DeactivateVersion deactivates the given version. @@ -218,11 +218,11 @@ func (c *Client) DeactivateVersion(i *DeactivateVersionInput) (*Version, error) return nil, ErrMissingService } - if i.Version == "" { + if i.Version == 0 { return nil, ErrMissingVersion } - path := fmt.Sprintf("/service/%s/version/%s/deactivate", i.Service, i.Version) + path := fmt.Sprintf("/service/%s/version/%d/deactivate", i.Service, i.Version) resp, err := c.Put(path, nil) if err != nil { return nil, err @@ -240,7 +240,7 @@ type CloneVersionInput struct { // Service is the ID of the service. Version is the specific configuration // version. Both fields are required. Service string - Version string + Version int } // CloneVersion creates a clone of the version with and returns a new @@ -251,11 +251,11 @@ func (c *Client) CloneVersion(i *CloneVersionInput) (*Version, error) { return nil, ErrMissingService } - if i.Version == "" { + if i.Version == 0 { return nil, ErrMissingVersion } - path := fmt.Sprintf("/service/%s/version/%s/clone", i.Service, i.Version) + path := fmt.Sprintf("/service/%s/version/%d/clone", i.Service, i.Version) resp, err := c.Put(path, nil) if err != nil { return nil, err @@ -273,7 +273,7 @@ type ValidateVersionInput struct { // Service is the ID of the service. Version is the specific configuration // version. Both fields are required. Service string - Version string + Version int } // ValidateVersion validates if the given version is okay. @@ -284,11 +284,11 @@ func (c *Client) ValidateVersion(i *ValidateVersionInput) (bool, string, error) return false, msg, ErrMissingService } - if i.Version == "" { + if i.Version == 0 { return false, msg, ErrMissingVersion } - path := fmt.Sprintf("/service/%s/version/%s/validate", i.Service, i.Version) + path := fmt.Sprintf("/service/%s/version/%d/validate", i.Service, i.Version) resp, err := c.Get(path, nil) if err != nil { return false, msg, err @@ -308,7 +308,7 @@ type LockVersionInput struct { // Service is the ID of the service. Version is the specific configuration // version. Both fields are required. Service string - Version string + Version int } // LockVersion locks the specified version. @@ -317,11 +317,11 @@ func (c *Client) LockVersion(i *LockVersionInput) (*Version, error) { return nil, ErrMissingService } - if i.Version == "" { + if i.Version == 0 { return nil, ErrMissingVersion } - path := fmt.Sprintf("/service/%s/version/%s/lock", i.Service, i.Version) + path := fmt.Sprintf("/service/%s/version/%d/lock", i.Service, i.Version) resp, err := c.Put(path, nil) if err != nil { return nil, err diff --git a/vendor/github.com/sethvargo/go-fastly/wordpress.go b/vendor/github.com/sethvargo/go-fastly/wordpress.go index 661d61348..c1e0a4efb 100644 --- a/vendor/github.com/sethvargo/go-fastly/wordpress.go +++ b/vendor/github.com/sethvargo/go-fastly/wordpress.go @@ -8,7 +8,7 @@ import ( // Wordpress represents a wordpress response from the Fastly API. type Wordpress struct { ServiceID string `mapstructure:"service_id"` - Version string `mapstructure:"version"` + Version int `mapstructure:"version"` Name string `mapstructure:"name"` Path string `mapstructure:"path"` @@ -30,7 +30,7 @@ type ListWordpressesInput struct { // Service is the ID of the service. Version is the specific configuration // version. Both fields are required. Service string - Version string + Version int } // ListWordpresses returns the list of wordpresses for the configuration version. @@ -39,11 +39,11 @@ func (c *Client) ListWordpresses(i *ListWordpressesInput) ([]*Wordpress, error) return nil, ErrMissingService } - if i.Version == "" { + if i.Version == 0 { return nil, ErrMissingVersion } - path := fmt.Sprintf("/service/%s/version/%s/wordpress", i.Service, i.Version) + path := fmt.Sprintf("/service/%s/version/%d/wordpress", i.Service, i.Version) resp, err := c.Get(path, nil) if err != nil { return nil, err @@ -62,7 +62,7 @@ type CreateWordpressInput struct { // Service is the ID of the service. Version is the specific configuration // version. Both fields are required. Service string - Version string + Version int Name string `form:"name,omitempty"` Path string `form:"path,omitempty"` @@ -75,11 +75,11 @@ func (c *Client) CreateWordpress(i *CreateWordpressInput) (*Wordpress, error) { return nil, ErrMissingService } - if i.Version == "" { + if i.Version == 0 { return nil, ErrMissingVersion } - path := fmt.Sprintf("/service/%s/version/%s/wordpress", i.Service, i.Version) + path := fmt.Sprintf("/service/%s/version/%d/wordpress", i.Service, i.Version) resp, err := c.PostForm(path, i, nil) if err != nil { return nil, err @@ -97,7 +97,7 @@ type GetWordpressInput struct { // Service is the ID of the service. Version is the specific configuration // version. Both fields are required. Service string - Version string + Version int // Name is the name of the wordpress to fetch. Name string @@ -109,7 +109,7 @@ func (c *Client) GetWordpress(i *GetWordpressInput) (*Wordpress, error) { return nil, ErrMissingService } - if i.Version == "" { + if i.Version == 0 { return nil, ErrMissingVersion } @@ -117,7 +117,7 @@ func (c *Client) GetWordpress(i *GetWordpressInput) (*Wordpress, error) { return nil, ErrMissingName } - path := fmt.Sprintf("/service/%s/version/%s/wordpress/%s", i.Service, i.Version, i.Name) + path := fmt.Sprintf("/service/%s/version/%d/wordpress/%s", i.Service, i.Version, i.Name) resp, err := c.Get(path, nil) if err != nil { return nil, err @@ -135,7 +135,7 @@ type UpdateWordpressInput struct { // Service is the ID of the service. Version is the specific configuration // version. Both fields are required. Service string - Version string + Version int // Name is the name of the wordpress to update. Name string @@ -151,7 +151,7 @@ func (c *Client) UpdateWordpress(i *UpdateWordpressInput) (*Wordpress, error) { return nil, ErrMissingService } - if i.Version == "" { + if i.Version == 0 { return nil, ErrMissingVersion } @@ -159,7 +159,7 @@ func (c *Client) UpdateWordpress(i *UpdateWordpressInput) (*Wordpress, error) { return nil, ErrMissingName } - path := fmt.Sprintf("/service/%s/version/%s/wordpress/%s", i.Service, i.Version, i.Name) + path := fmt.Sprintf("/service/%s/version/%d/wordpress/%s", i.Service, i.Version, i.Name) resp, err := c.PutForm(path, i, nil) if err != nil { return nil, err @@ -177,7 +177,7 @@ type DeleteWordpressInput struct { // Service is the ID of the service. Version is the specific configuration // version. Both fields are required. Service string - Version string + Version int // Name is the name of the wordpress to delete (required). Name string @@ -189,7 +189,7 @@ func (c *Client) DeleteWordpress(i *DeleteWordpressInput) error { return ErrMissingService } - if i.Version == "" { + if i.Version == 0 { return ErrMissingVersion } @@ -197,7 +197,7 @@ func (c *Client) DeleteWordpress(i *DeleteWordpressInput) error { return ErrMissingName } - path := fmt.Sprintf("/service/%s/version/%s/wordpress/%s", i.Service, i.Version, i.Name) + path := fmt.Sprintf("/service/%s/version/%d/wordpress/%s", i.Service, i.Version, i.Name) resp, err := c.Delete(path, nil) if err != nil { return err diff --git a/vendor/github.com/ukcloud/govcloudair/api_vcd.go b/vendor/github.com/ukcloud/govcloudair/api_vcd.go index 7938727de..dc6163a2e 100644 --- a/vendor/github.com/ukcloud/govcloudair/api_vcd.go +++ b/vendor/github.com/ukcloud/govcloudair/api_vcd.go @@ -141,7 +141,7 @@ func (c *VCDClient) vcdauthorize(user, pass, org string) error { func (c *VCDClient) RetrieveOrg(vcdname string) (Org, error) { req := c.Client.NewRequest(map[string]string{}, "GET", c.OrgHREF, nil) - req.Header.Add("Accept", "vnd.vmware.vcloud.org+xml;version=5.5") + req.Header.Add("Accept", "application/*+xml;version=5.5") // TODO: wrap into checkresp to parse error resp, err := checkResp(c.Client.Http.Do(req)) diff --git a/vendor/github.com/xanzy/go-cloudstack/cloudstack/APIDiscoveryService.go b/vendor/github.com/xanzy/go-cloudstack/cloudstack/APIDiscoveryService.go index 490d36d65..0b9029e6c 100644 --- a/vendor/github.com/xanzy/go-cloudstack/cloudstack/APIDiscoveryService.go +++ b/vendor/github.com/xanzy/go-cloudstack/cloudstack/APIDiscoveryService.go @@ -63,6 +63,7 @@ func (s *APIDiscoveryService) ListApis(p *ListApisParams) (*ListApisResponse, er if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } diff --git a/vendor/github.com/xanzy/go-cloudstack/cloudstack/AccountService.go b/vendor/github.com/xanzy/go-cloudstack/cloudstack/AccountService.go index 28b50b66a..3a2bf1c95 100644 --- a/vendor/github.com/xanzy/go-cloudstack/cloudstack/AccountService.go +++ b/vendor/github.com/xanzy/go-cloudstack/cloudstack/AccountService.go @@ -210,6 +210,7 @@ func (s *AccountService) CreateAccount(p *CreateAccountParams) (*CreateAccountRe if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -345,6 +346,7 @@ func (s *AccountService) DeleteAccount(p *DeleteAccountParams) (*DeleteAccountRe return nil, err } } + return &r, nil } @@ -457,6 +459,7 @@ func (s *AccountService) UpdateAccount(p *UpdateAccountParams) (*UpdateAccountRe if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -631,6 +634,7 @@ func (s *AccountService) DisableAccount(p *DisableAccountParams) (*DisableAccoun return nil, err } } + return &r, nil } @@ -773,6 +777,7 @@ func (s *AccountService) EnableAccount(p *EnableAccountParams) (*EnableAccountRe if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -905,6 +910,7 @@ func (s *AccountService) LockAccount(p *LockAccountParams) (*LockAccountResponse if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -1223,6 +1229,7 @@ func (s *AccountService) ListAccounts(p *ListAccountsParams) (*ListAccountsRespo if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -1392,6 +1399,7 @@ func (s *AccountService) MarkDefaultZoneForAccount(p *MarkDefaultZoneForAccountP return nil, err } } + return &r, nil } @@ -1550,6 +1558,7 @@ func (s *AccountService) AddAccountToProject(p *AddAccountToProjectParams) (*Add return nil, err } } + return &r, nil } @@ -1629,6 +1638,7 @@ func (s *AccountService) DeleteAccountFromProject(p *DeleteAccountFromProjectPar return nil, err } } + return &r, nil } @@ -1775,6 +1785,7 @@ func (s *AccountService) ListProjectAccounts(p *ListProjectAccountsParams) (*Lis if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -1895,6 +1906,7 @@ func (s *AccountService) GetSolidFireAccountId(p *GetSolidFireAccountIdParams) ( if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } diff --git a/vendor/github.com/xanzy/go-cloudstack/cloudstack/AddressService.go b/vendor/github.com/xanzy/go-cloudstack/cloudstack/AddressService.go index 9ffc6d9b8..698558218 100644 --- a/vendor/github.com/xanzy/go-cloudstack/cloudstack/AddressService.go +++ b/vendor/github.com/xanzy/go-cloudstack/cloudstack/AddressService.go @@ -177,6 +177,7 @@ func (s *AddressService) AssociateIpAddress(p *AssociateIpAddressParams) (*Assoc return nil, err } } + return &r, nil } @@ -283,6 +284,7 @@ func (s *AddressService) DisassociateIpAddress(p *DisassociateIpAddressParams) ( return nil, err } } + return &r, nil } @@ -624,6 +626,7 @@ func (s *AddressService) ListPublicIpAddresses(p *ListPublicIpAddressesParams) ( if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -762,6 +765,7 @@ func (s *AddressService) UpdateIpAddress(p *UpdateIpAddressParams) (*UpdateIpAdd return nil, err } } + return &r, nil } diff --git a/vendor/github.com/xanzy/go-cloudstack/cloudstack/AffinityGroupService.go b/vendor/github.com/xanzy/go-cloudstack/cloudstack/AffinityGroupService.go index 48f1b0f93..c62b40146 100644 --- a/vendor/github.com/xanzy/go-cloudstack/cloudstack/AffinityGroupService.go +++ b/vendor/github.com/xanzy/go-cloudstack/cloudstack/AffinityGroupService.go @@ -143,6 +143,7 @@ func (s *AffinityGroupService) CreateAffinityGroup(p *CreateAffinityGroupParams) return nil, err } } + return &r, nil } @@ -261,6 +262,7 @@ func (s *AffinityGroupService) DeleteAffinityGroup(p *DeleteAffinityGroupParams) return nil, err } } + return &r, nil } @@ -528,6 +530,7 @@ func (s *AffinityGroupService) ListAffinityGroups(p *ListAffinityGroupsParams) ( if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -636,6 +639,7 @@ func (s *AffinityGroupService) UpdateVMAffinityGroup(p *UpdateVMAffinityGroupPar return nil, err } } + return &r, nil } @@ -882,6 +886,7 @@ func (s *AffinityGroupService) ListAffinityGroupTypes(p *ListAffinityGroupTypesP if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } diff --git a/vendor/github.com/xanzy/go-cloudstack/cloudstack/AlertService.go b/vendor/github.com/xanzy/go-cloudstack/cloudstack/AlertService.go index dc73a2177..df6d5bfdc 100644 --- a/vendor/github.com/xanzy/go-cloudstack/cloudstack/AlertService.go +++ b/vendor/github.com/xanzy/go-cloudstack/cloudstack/AlertService.go @@ -206,6 +206,7 @@ func (s *AlertService) ListAlerts(p *ListAlertsParams) (*ListAlertsResponse, err if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -298,6 +299,7 @@ func (s *AlertService) ArchiveAlerts(p *ArchiveAlertsParams) (*ArchiveAlertsResp if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -382,6 +384,7 @@ func (s *AlertService) DeleteAlerts(p *DeleteAlertsParams) (*DeleteAlertsRespons if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -495,6 +498,7 @@ func (s *AlertService) GenerateAlert(p *GenerateAlertParams) (*GenerateAlertResp return nil, err } } + return &r, nil } diff --git a/vendor/github.com/xanzy/go-cloudstack/cloudstack/AsyncjobService.go b/vendor/github.com/xanzy/go-cloudstack/cloudstack/AsyncjobService.go index b3e1fd89a..cafc3d87a 100644 --- a/vendor/github.com/xanzy/go-cloudstack/cloudstack/AsyncjobService.go +++ b/vendor/github.com/xanzy/go-cloudstack/cloudstack/AsyncjobService.go @@ -76,6 +76,7 @@ func (s *AsyncjobService) QueryAsyncJobResult(p *QueryAsyncJobResultParams) (*Qu if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -216,6 +217,7 @@ func (s *AsyncjobService) ListAsyncJobs(p *ListAsyncJobsParams) (*ListAsyncJobsR if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } diff --git a/vendor/github.com/xanzy/go-cloudstack/cloudstack/AuthenticationService.go b/vendor/github.com/xanzy/go-cloudstack/cloudstack/AuthenticationService.go index b97e70cfa..21094548d 100644 --- a/vendor/github.com/xanzy/go-cloudstack/cloudstack/AuthenticationService.go +++ b/vendor/github.com/xanzy/go-cloudstack/cloudstack/AuthenticationService.go @@ -100,6 +100,7 @@ func (s *AuthenticationService) Login(p *LoginParams) (*LoginResponse, error) { if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -148,6 +149,7 @@ func (s *AuthenticationService) Logout(p *LogoutParams) (*LogoutResponse, error) if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } diff --git a/vendor/github.com/xanzy/go-cloudstack/cloudstack/AutoScaleService.go b/vendor/github.com/xanzy/go-cloudstack/cloudstack/AutoScaleService.go index 27e328616..f3fd54e49 100644 --- a/vendor/github.com/xanzy/go-cloudstack/cloudstack/AutoScaleService.go +++ b/vendor/github.com/xanzy/go-cloudstack/cloudstack/AutoScaleService.go @@ -111,6 +111,7 @@ func (s *AutoScaleService) CreateCounter(p *CreateCounterParams) (*CreateCounter return nil, err } } + return &r, nil } @@ -233,6 +234,7 @@ func (s *AutoScaleService) CreateCondition(p *CreateConditionParams) (*CreateCon return nil, err } } + return &r, nil } @@ -351,6 +353,7 @@ func (s *AutoScaleService) CreateAutoScalePolicy(p *CreateAutoScalePolicyParams) return nil, err } } + return &r, nil } @@ -517,6 +520,7 @@ func (s *AutoScaleService) CreateAutoScaleVmProfile(p *CreateAutoScaleVmProfileP return nil, err } } + return &r, nil } @@ -688,6 +692,7 @@ func (s *AutoScaleService) CreateAutoScaleVmGroup(p *CreateAutoScaleVmGroupParam return nil, err } } + return &r, nil } @@ -768,6 +773,7 @@ func (s *AutoScaleService) DeleteCounter(p *DeleteCounterParams) (*DeleteCounter return nil, err } } + return &r, nil } @@ -835,6 +841,7 @@ func (s *AutoScaleService) DeleteCondition(p *DeleteConditionParams) (*DeleteCon return nil, err } } + return &r, nil } @@ -902,6 +909,7 @@ func (s *AutoScaleService) DeleteAutoScalePolicy(p *DeleteAutoScalePolicyParams) return nil, err } } + return &r, nil } @@ -969,6 +977,7 @@ func (s *AutoScaleService) DeleteAutoScaleVmProfile(p *DeleteAutoScaleVmProfileP return nil, err } } + return &r, nil } @@ -1036,6 +1045,7 @@ func (s *AutoScaleService) DeleteAutoScaleVmGroup(p *DeleteAutoScaleVmGroupParam return nil, err } } + return &r, nil } @@ -1227,6 +1237,7 @@ func (s *AutoScaleService) ListCounters(p *ListCountersParams) (*ListCountersRes if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -1421,6 +1432,7 @@ func (s *AutoScaleService) ListConditions(p *ListConditionsParams) (*ListConditi if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -1631,6 +1643,7 @@ func (s *AutoScaleService) ListAutoScalePolicies(p *ListAutoScalePoliciesParams) if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -1875,6 +1888,7 @@ func (s *AutoScaleService) ListAutoScaleVmProfiles(p *ListAutoScaleVmProfilesPar if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -2122,6 +2136,7 @@ func (s *AutoScaleService) ListAutoScaleVmGroups(p *ListAutoScaleVmGroupsParams) if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -2211,6 +2226,7 @@ func (s *AutoScaleService) EnableAutoScaleVmGroup(p *EnableAutoScaleVmGroupParam return nil, err } } + return &r, nil } @@ -2296,6 +2312,7 @@ func (s *AutoScaleService) DisableAutoScaleVmGroup(p *DisableAutoScaleVmGroupPar return nil, err } } + return &r, nil } @@ -2417,6 +2434,7 @@ func (s *AutoScaleService) UpdateAutoScalePolicy(p *UpdateAutoScalePolicyParams) return nil, err } } + return &r, nil } @@ -2570,6 +2588,7 @@ func (s *AutoScaleService) UpdateAutoScaleVmProfile(p *UpdateAutoScaleVmProfileP return nil, err } } + return &r, nil } @@ -2736,6 +2755,7 @@ func (s *AutoScaleService) UpdateAutoScaleVmGroup(p *UpdateAutoScaleVmGroupParam return nil, err } } + return &r, nil } diff --git a/vendor/github.com/xanzy/go-cloudstack/cloudstack/BaremetalService.go b/vendor/github.com/xanzy/go-cloudstack/cloudstack/BaremetalService.go index c1b7eaaba..861d16b3e 100644 --- a/vendor/github.com/xanzy/go-cloudstack/cloudstack/BaremetalService.go +++ b/vendor/github.com/xanzy/go-cloudstack/cloudstack/BaremetalService.go @@ -156,6 +156,7 @@ func (s *BaremetalService) AddBaremetalPxeKickStartServer(p *AddBaremetalPxeKick return nil, err } } + return &r, nil } @@ -344,6 +345,7 @@ func (s *BaremetalService) AddBaremetalPxePingServer(p *AddBaremetalPxePingServe return nil, err } } + return &r, nil } @@ -465,6 +467,7 @@ func (s *BaremetalService) AddBaremetalDhcp(p *AddBaremetalDhcpParams) (*AddBare return nil, err } } + return &r, nil } @@ -578,6 +581,7 @@ func (s *BaremetalService) ListBaremetalDhcp(p *ListBaremetalDhcpParams) (*ListB if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -684,6 +688,7 @@ func (s *BaremetalService) ListBaremetalPxeServers(p *ListBaremetalPxeServersPar if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -762,6 +767,7 @@ func (s *BaremetalService) AddBaremetalRct(p *AddBaremetalRctParams) (*AddBareme return nil, err } } + return &r, nil } @@ -829,6 +835,7 @@ func (s *BaremetalService) DeleteBaremetalRct(p *DeleteBaremetalRctParams) (*Del return nil, err } } + return &r, nil } @@ -904,6 +911,7 @@ func (s *BaremetalService) ListBaremetalRct(p *ListBaremetalRctParams) (*ListBar if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } diff --git a/vendor/github.com/xanzy/go-cloudstack/cloudstack/CertificateService.go b/vendor/github.com/xanzy/go-cloudstack/cloudstack/CertificateService.go index a13fcdfc2..24052d415 100644 --- a/vendor/github.com/xanzy/go-cloudstack/cloudstack/CertificateService.go +++ b/vendor/github.com/xanzy/go-cloudstack/cloudstack/CertificateService.go @@ -131,6 +131,7 @@ func (s *CertificateService) UploadCustomCertificate(p *UploadCustomCertificateP return nil, err } } + return &r, nil } diff --git a/vendor/github.com/xanzy/go-cloudstack/cloudstack/CloudIdentifierService.go b/vendor/github.com/xanzy/go-cloudstack/cloudstack/CloudIdentifierService.go index 99eeba2c8..7bc4acb7c 100644 --- a/vendor/github.com/xanzy/go-cloudstack/cloudstack/CloudIdentifierService.go +++ b/vendor/github.com/xanzy/go-cloudstack/cloudstack/CloudIdentifierService.go @@ -64,6 +64,7 @@ func (s *CloudIdentifierService) GetCloudIdentifier(p *GetCloudIdentifierParams) if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } diff --git a/vendor/github.com/xanzy/go-cloudstack/cloudstack/ClusterService.go b/vendor/github.com/xanzy/go-cloudstack/cloudstack/ClusterService.go index 0ba05b4d9..ea5984228 100644 --- a/vendor/github.com/xanzy/go-cloudstack/cloudstack/ClusterService.go +++ b/vendor/github.com/xanzy/go-cloudstack/cloudstack/ClusterService.go @@ -269,6 +269,7 @@ func (s *ClusterService) AddCluster(p *AddClusterParams) (*AddClusterResponse, e if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -343,6 +344,7 @@ func (s *ClusterService) DeleteCluster(p *DeleteClusterParams) (*DeleteClusterRe if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -449,6 +451,7 @@ func (s *ClusterService) UpdateCluster(p *UpdateClusterParams) (*UpdateClusterRe if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -729,6 +732,7 @@ func (s *ClusterService) ListClusters(p *ListClustersParams) (*ListClustersRespo if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -851,6 +855,7 @@ func (s *ClusterService) DedicateCluster(p *DedicateClusterParams) (*DedicateClu return nil, err } } + return &r, nil } @@ -922,6 +927,7 @@ func (s *ClusterService) ReleaseDedicatedCluster(p *ReleaseDedicatedClusterParam return nil, err } } + return &r, nil } @@ -1041,6 +1047,7 @@ func (s *ClusterService) ListDedicatedClusters(p *ListDedicatedClustersParams) ( if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } diff --git a/vendor/github.com/xanzy/go-cloudstack/cloudstack/ConfigurationService.go b/vendor/github.com/xanzy/go-cloudstack/cloudstack/ConfigurationService.go index b4a6a7b1b..280c7e654 100644 --- a/vendor/github.com/xanzy/go-cloudstack/cloudstack/ConfigurationService.go +++ b/vendor/github.com/xanzy/go-cloudstack/cloudstack/ConfigurationService.go @@ -120,6 +120,7 @@ func (s *ConfigurationService) UpdateConfiguration(p *UpdateConfigurationParams) if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -264,6 +265,7 @@ func (s *ConfigurationService) ListConfigurations(p *ListConfigurationsParams) ( if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -312,6 +314,7 @@ func (s *ConfigurationService) ListCapabilities(p *ListCapabilitiesParams) (*Lis if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -403,6 +406,7 @@ func (s *ConfigurationService) ListDeploymentPlanners(p *ListDeploymentPlannersP if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -504,6 +508,7 @@ func (s *ConfigurationService) ListLdapConfigurations(p *ListLdapConfigurationsP if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -573,6 +578,7 @@ func (s *ConfigurationService) AddLdapConfiguration(p *AddLdapConfigurationParam if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -624,6 +630,7 @@ func (s *ConfigurationService) DeleteLdapConfiguration(p *DeleteLdapConfiguratio if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } diff --git a/vendor/github.com/xanzy/go-cloudstack/cloudstack/DiskOfferingService.go b/vendor/github.com/xanzy/go-cloudstack/cloudstack/DiskOfferingService.go index ee85a07e3..3ecc3e0d0 100644 --- a/vendor/github.com/xanzy/go-cloudstack/cloudstack/DiskOfferingService.go +++ b/vendor/github.com/xanzy/go-cloudstack/cloudstack/DiskOfferingService.go @@ -255,6 +255,7 @@ func (s *DiskOfferingService) CreateDiskOffering(p *CreateDiskOfferingParams) (* if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -371,6 +372,7 @@ func (s *DiskOfferingService) UpdateDiskOffering(p *UpdateDiskOfferingParams) (* if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -441,6 +443,7 @@ func (s *DiskOfferingService) DeleteDiskOffering(p *DeleteDiskOfferingParams) (* if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -655,6 +658,7 @@ func (s *DiskOfferingService) ListDiskOfferings(p *ListDiskOfferingsParams) (*Li if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } diff --git a/vendor/github.com/xanzy/go-cloudstack/cloudstack/DomainService.go b/vendor/github.com/xanzy/go-cloudstack/cloudstack/DomainService.go index e21afbd82..eed3310fe 100644 --- a/vendor/github.com/xanzy/go-cloudstack/cloudstack/DomainService.go +++ b/vendor/github.com/xanzy/go-cloudstack/cloudstack/DomainService.go @@ -100,6 +100,7 @@ func (s *DomainService) CreateDomain(p *CreateDomainParams) (*CreateDomainRespon if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -216,6 +217,7 @@ func (s *DomainService) UpdateDomain(p *UpdateDomainParams) (*UpdateDomainRespon if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -337,6 +339,7 @@ func (s *DomainService) DeleteDomain(p *DeleteDomainParams) (*DeleteDomainRespon return nil, err } } + return &r, nil } @@ -541,6 +544,7 @@ func (s *DomainService) ListDomains(p *ListDomainsParams) (*ListDomainsResponse, if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -792,6 +796,7 @@ func (s *DomainService) ListDomainChildren(p *ListDomainChildrenParams) (*ListDo if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -939,6 +944,7 @@ func (s *DomainService) LinkDomainToLdap(p *LinkDomainToLdapParams) (*LinkDomain if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } diff --git a/vendor/github.com/xanzy/go-cloudstack/cloudstack/EventService.go b/vendor/github.com/xanzy/go-cloudstack/cloudstack/EventService.go index 84a8b9273..32e6ba92d 100644 --- a/vendor/github.com/xanzy/go-cloudstack/cloudstack/EventService.go +++ b/vendor/github.com/xanzy/go-cloudstack/cloudstack/EventService.go @@ -259,6 +259,7 @@ func (s *EventService) ListEvents(p *ListEventsParams) (*ListEventsResponse, err if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -314,6 +315,7 @@ func (s *EventService) ListEventTypes(p *ListEventTypesParams) (*ListEventTypesR if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -402,6 +404,7 @@ func (s *EventService) ArchiveEvents(p *ArchiveEventsParams) (*ArchiveEventsResp if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -486,6 +489,7 @@ func (s *EventService) DeleteEvents(p *DeleteEventsParams) (*DeleteEventsRespons if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } diff --git a/vendor/github.com/xanzy/go-cloudstack/cloudstack/FirewallService.go b/vendor/github.com/xanzy/go-cloudstack/cloudstack/FirewallService.go index 566643ab8..c0b6740ee 100644 --- a/vendor/github.com/xanzy/go-cloudstack/cloudstack/FirewallService.go +++ b/vendor/github.com/xanzy/go-cloudstack/cloudstack/FirewallService.go @@ -287,10 +287,16 @@ func (s *FirewallService) ListPortForwardingRules(p *ListPortForwardingRulesPara return nil, err } + resp, err = convertFirewallServiceResponse(resp) + if err != nil { + return nil, err + } + var r ListPortForwardingRulesResponse if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -530,6 +536,7 @@ func (s *FirewallService) CreatePortForwardingRule(p *CreatePortForwardingRulePa return nil, err } } + return &r, nil } @@ -628,6 +635,7 @@ func (s *FirewallService) DeletePortForwardingRule(p *DeletePortForwardingRulePa return nil, err } } + return &r, nil } @@ -762,6 +770,7 @@ func (s *FirewallService) UpdatePortForwardingRule(p *UpdatePortForwardingRulePa return nil, err } } + return &r, nil } @@ -960,6 +969,7 @@ func (s *FirewallService) CreateFirewallRule(p *CreateFirewallRuleParams) (*Crea return nil, err } } + return &r, nil } @@ -1054,6 +1064,7 @@ func (s *FirewallService) DeleteFirewallRule(p *DeleteFirewallRuleParams) (*Dele return nil, err } } + return &r, nil } @@ -1276,10 +1287,16 @@ func (s *FirewallService) ListFirewallRules(p *ListFirewallRulesParams) (*ListFi return nil, err } + resp, err = convertFirewallServiceResponse(resp) + if err != nil { + return nil, err + } + var r ListFirewallRulesResponse if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -1406,6 +1423,7 @@ func (s *FirewallService) UpdateFirewallRule(p *UpdateFirewallRuleParams) (*Upda return nil, err } } + return &r, nil } @@ -1600,6 +1618,7 @@ func (s *FirewallService) CreateEgressFirewallRule(p *CreateEgressFirewallRulePa return nil, err } } + return &r, nil } @@ -1694,6 +1713,7 @@ func (s *FirewallService) DeleteEgressFirewallRule(p *DeleteEgressFirewallRulePa return nil, err } } + return &r, nil } @@ -1916,10 +1936,16 @@ func (s *FirewallService) ListEgressFirewallRules(p *ListEgressFirewallRulesPara return nil, err } + resp, err = convertFirewallServiceResponse(resp) + if err != nil { + return nil, err + } + var r ListEgressFirewallRulesResponse if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -2046,6 +2072,7 @@ func (s *FirewallService) UpdateEgressFirewallRule(p *UpdateEgressFirewallRulePa return nil, err } } + return &r, nil } @@ -2193,6 +2220,7 @@ func (s *FirewallService) AddPaloAltoFirewall(p *AddPaloAltoFirewallParams) (*Ad return nil, err } } + return &r, nil } @@ -2279,6 +2307,7 @@ func (s *FirewallService) DeletePaloAltoFirewall(p *DeletePaloAltoFirewallParams return nil, err } } + return &r, nil } @@ -2368,6 +2397,7 @@ func (s *FirewallService) ConfigurePaloAltoFirewall(p *ConfigurePaloAltoFirewall return nil, err } } + return &r, nil } @@ -2475,10 +2505,16 @@ func (s *FirewallService) ListPaloAltoFirewalls(p *ListPaloAltoFirewallsParams) return nil, err } + resp, err = convertFirewallServiceResponse(resp) + if err != nil { + return nil, err + } + var r ListPaloAltoFirewallsResponse if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } diff --git a/vendor/github.com/xanzy/go-cloudstack/cloudstack/GuestOSService.go b/vendor/github.com/xanzy/go-cloudstack/cloudstack/GuestOSService.go index 2f7810044..d5cfa4030 100644 --- a/vendor/github.com/xanzy/go-cloudstack/cloudstack/GuestOSService.go +++ b/vendor/github.com/xanzy/go-cloudstack/cloudstack/GuestOSService.go @@ -156,6 +156,7 @@ func (s *GuestOSService) ListOsTypes(p *ListOsTypesParams) (*ListOsTypesResponse if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -342,6 +343,7 @@ func (s *GuestOSService) ListOsCategories(p *ListOsCategoriesParams) (*ListOsCat if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -441,6 +443,7 @@ func (s *GuestOSService) AddGuestOs(p *AddGuestOsParams) (*AddGuestOsResponse, e return nil, err } } + return &r, nil } @@ -527,6 +530,7 @@ func (s *GuestOSService) UpdateGuestOs(p *UpdateGuestOsParams) (*UpdateGuestOsRe return nil, err } } + return &r, nil } @@ -596,6 +600,7 @@ func (s *GuestOSService) RemoveGuestOs(p *RemoveGuestOsParams) (*RemoveGuestOsRe return nil, err } } + return &r, nil } @@ -748,6 +753,7 @@ func (s *GuestOSService) ListGuestOsMapping(p *ListGuestOsMappingParams) (*ListG if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -875,6 +881,7 @@ func (s *GuestOSService) AddGuestOsMapping(p *AddGuestOsMappingParams) (*AddGues return nil, err } } + return &r, nil } @@ -964,6 +971,7 @@ func (s *GuestOSService) UpdateGuestOsMapping(p *UpdateGuestOsMappingParams) (*U return nil, err } } + return &r, nil } @@ -1036,6 +1044,7 @@ func (s *GuestOSService) RemoveGuestOsMapping(p *RemoveGuestOsMappingParams) (*R return nil, err } } + return &r, nil } diff --git a/vendor/github.com/xanzy/go-cloudstack/cloudstack/HostService.go b/vendor/github.com/xanzy/go-cloudstack/cloudstack/HostService.go index 4306b5a9d..4510ef846 100644 --- a/vendor/github.com/xanzy/go-cloudstack/cloudstack/HostService.go +++ b/vendor/github.com/xanzy/go-cloudstack/cloudstack/HostService.go @@ -172,6 +172,7 @@ func (s *HostService) AddHost(p *AddHostParams) (*AddHostResponse, error) { if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -299,6 +300,7 @@ func (s *HostService) ReconnectHost(p *ReconnectHostParams) (*ReconnectHostRespo return nil, err } } + return &r, nil } @@ -452,6 +454,7 @@ func (s *HostService) UpdateHost(p *UpdateHostParams) (*UpdateHostResponse, erro if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -583,6 +586,7 @@ func (s *HostService) DeleteHost(p *DeleteHostParams) (*DeleteHostResponse, erro if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -654,6 +658,7 @@ func (s *HostService) PrepareHostForMaintenance(p *PrepareHostForMaintenancePara return nil, err } } + return &r, nil } @@ -782,6 +787,7 @@ func (s *HostService) CancelHostMaintenance(p *CancelHostMaintenanceParams) (*Ca return nil, err } } + return &r, nil } @@ -1130,6 +1136,7 @@ func (s *HostService) ListHosts(p *ListHostsParams) (*ListHostsResponse, error) if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -1301,6 +1308,7 @@ func (s *HostService) ListHostTags(p *ListHostTagsParams) (*ListHostTagsResponse if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -1393,6 +1401,7 @@ func (s *HostService) FindHostsForMigration(p *FindHostsForMigrationParams) (*Fi if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -1497,6 +1506,7 @@ func (s *HostService) AddSecondaryStorage(p *AddSecondaryStorageParams) (*AddSec if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -1601,6 +1611,7 @@ func (s *HostService) UpdateHostPassword(p *UpdateHostPasswordParams) (*UpdateHo if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -1667,6 +1678,7 @@ func (s *HostService) ReleaseHostReservation(p *ReleaseHostReservationParams) (* return nil, err } } + return &r, nil } @@ -1835,6 +1847,7 @@ func (s *HostService) AddBaremetalHost(p *AddBaremetalHostParams) (*AddBaremetal if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -1985,6 +1998,7 @@ func (s *HostService) DedicateHost(p *DedicateHostParams) (*DedicateHostResponse return nil, err } } + return &r, nil } @@ -2056,6 +2070,7 @@ func (s *HostService) ReleaseDedicatedHost(p *ReleaseDedicatedHostParams) (*Rele return nil, err } } + return &r, nil } @@ -2175,6 +2190,7 @@ func (s *HostService) ListDedicatedHosts(p *ListDedicatedHostsParams) (*ListDedi if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -2286,6 +2302,7 @@ func (s *HostService) AddGloboDnsHost(p *AddGloboDnsHostParams) (*AddGloboDnsHos return nil, err } } + return &r, nil } diff --git a/vendor/github.com/xanzy/go-cloudstack/cloudstack/HypervisorService.go b/vendor/github.com/xanzy/go-cloudstack/cloudstack/HypervisorService.go index c172615c9..31cc6a777 100644 --- a/vendor/github.com/xanzy/go-cloudstack/cloudstack/HypervisorService.go +++ b/vendor/github.com/xanzy/go-cloudstack/cloudstack/HypervisorService.go @@ -66,6 +66,7 @@ func (s *HypervisorService) ListHypervisors(p *ListHypervisorsParams) (*ListHype if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -144,6 +145,7 @@ func (s *HypervisorService) UpdateHypervisorCapabilities(p *UpdateHypervisorCapa if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -279,6 +281,7 @@ func (s *HypervisorService) ListHypervisorCapabilities(p *ListHypervisorCapabili if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } diff --git a/vendor/github.com/xanzy/go-cloudstack/cloudstack/ISOService.go b/vendor/github.com/xanzy/go-cloudstack/cloudstack/ISOService.go index a4ad582a6..1bb5fc026 100644 --- a/vendor/github.com/xanzy/go-cloudstack/cloudstack/ISOService.go +++ b/vendor/github.com/xanzy/go-cloudstack/cloudstack/ISOService.go @@ -99,6 +99,7 @@ func (s *ISOService) AttachIso(p *AttachIsoParams) (*AttachIsoResponse, error) { return nil, err } } + return &r, nil } @@ -342,6 +343,7 @@ func (s *ISOService) DetachIso(p *DetachIsoParams) (*DetachIsoResponse, error) { return nil, err } } + return &r, nil } @@ -849,6 +851,7 @@ func (s *ISOService) ListIsos(p *ListIsosParams) (*ListIsosResponse, error) { if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -1112,6 +1115,7 @@ func (s *ISOService) RegisterIso(p *RegisterIsoParams) (*RegisterIsoResponse, er if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -1340,6 +1344,7 @@ func (s *ISOService) UpdateIso(p *UpdateIsoParams) (*UpdateIsoResponse, error) { if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -1462,6 +1467,7 @@ func (s *ISOService) DeleteIso(p *DeleteIsoParams) (*DeleteIsoResponse, error) { return nil, err } } + return &r, nil } @@ -1557,6 +1563,7 @@ func (s *ISOService) CopyIso(p *CopyIsoParams) (*CopyIsoResponse, error) { return nil, err } } + return &r, nil } @@ -1725,6 +1732,7 @@ func (s *ISOService) UpdateIsoPermissions(p *UpdateIsoPermissionsParams) (*Updat if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -1809,6 +1817,7 @@ func (s *ISOService) ListIsoPermissions(p *ListIsoPermissionsParams) (*ListIsoPe if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -1922,6 +1931,7 @@ func (s *ISOService) ExtractIso(p *ExtractIsoParams) (*ExtractIsoResponse, error return nil, err } } + return &r, nil } diff --git a/vendor/github.com/xanzy/go-cloudstack/cloudstack/ImageStoreService.go b/vendor/github.com/xanzy/go-cloudstack/cloudstack/ImageStoreService.go index 58fce6e82..5af10c9f2 100644 --- a/vendor/github.com/xanzy/go-cloudstack/cloudstack/ImageStoreService.go +++ b/vendor/github.com/xanzy/go-cloudstack/cloudstack/ImageStoreService.go @@ -116,6 +116,7 @@ func (s *ImageStoreService) AddImageStore(p *AddImageStoreParams) (*AddImageStor if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -293,6 +294,7 @@ func (s *ImageStoreService) AddImageStoreS3(p *AddImageStoreS3Params) (*AddImage if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -512,6 +514,7 @@ func (s *ImageStoreService) ListImageStores(p *ListImageStoresParams) (*ListImag if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -575,6 +578,7 @@ func (s *ImageStoreService) DeleteImageStore(p *DeleteImageStoreParams) (*Delete if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -675,6 +679,7 @@ func (s *ImageStoreService) CreateSecondaryStagingStore(p *CreateSecondaryStagin if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -894,6 +899,7 @@ func (s *ImageStoreService) ListSecondaryStagingStores(p *ListSecondaryStagingSt if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -957,6 +963,7 @@ func (s *ImageStoreService) DeleteSecondaryStagingStore(p *DeleteSecondaryStagin if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -1046,6 +1053,7 @@ func (s *ImageStoreService) UpdateCloudToUseObjectStore(p *UpdateCloudToUseObjec if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } diff --git a/vendor/github.com/xanzy/go-cloudstack/cloudstack/InternalLBService.go b/vendor/github.com/xanzy/go-cloudstack/cloudstack/InternalLBService.go index ba86b3ee3..513005b3f 100644 --- a/vendor/github.com/xanzy/go-cloudstack/cloudstack/InternalLBService.go +++ b/vendor/github.com/xanzy/go-cloudstack/cloudstack/InternalLBService.go @@ -100,6 +100,7 @@ func (s *InternalLBService) ConfigureInternalLoadBalancerElement(p *ConfigureInt return nil, err } } + return &r, nil } @@ -173,6 +174,7 @@ func (s *InternalLBService) CreateInternalLoadBalancerElement(p *CreateInternalL return nil, err } } + return &r, nil } @@ -316,6 +318,7 @@ func (s *InternalLBService) ListInternalLoadBalancerElements(p *ListInternalLoad if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -405,6 +408,7 @@ func (s *InternalLBService) StopInternalLoadBalancerVM(p *StopInternalLoadBalanc return nil, err } } + return &r, nil } @@ -543,6 +547,7 @@ func (s *InternalLBService) StartInternalLoadBalancerVM(p *StartInternalLoadBala return nil, err } } + return &r, nil } @@ -924,6 +929,7 @@ func (s *InternalLBService) ListInternalLoadBalancerVMs(p *ListInternalLoadBalan if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } diff --git a/vendor/github.com/xanzy/go-cloudstack/cloudstack/LDAPService.go b/vendor/github.com/xanzy/go-cloudstack/cloudstack/LDAPService.go index 18935c294..fe7f52703 100644 --- a/vendor/github.com/xanzy/go-cloudstack/cloudstack/LDAPService.go +++ b/vendor/github.com/xanzy/go-cloudstack/cloudstack/LDAPService.go @@ -161,6 +161,7 @@ func (s *LDAPService) LdapCreateAccount(p *LdapCreateAccountParams) (*LdapCreate if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } diff --git a/vendor/github.com/xanzy/go-cloudstack/cloudstack/LimitService.go b/vendor/github.com/xanzy/go-cloudstack/cloudstack/LimitService.go index 276abecf8..d44d49813 100644 --- a/vendor/github.com/xanzy/go-cloudstack/cloudstack/LimitService.go +++ b/vendor/github.com/xanzy/go-cloudstack/cloudstack/LimitService.go @@ -111,6 +111,7 @@ func (s *LimitService) UpdateResourceLimit(p *UpdateResourceLimitParams) (*Updat if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -201,6 +202,7 @@ func (s *LimitService) UpdateResourceCount(p *UpdateResourceCountParams) (*Updat if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -361,6 +363,7 @@ func (s *LimitService) ListResourceLimits(p *ListResourceLimitsParams) (*ListRes if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -410,6 +413,7 @@ func (s *LimitService) GetApiLimit(p *GetApiLimitParams) (*GetApiLimitResponse, if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -463,6 +467,7 @@ func (s *LimitService) ResetApiLimit(p *ResetApiLimitParams) (*ResetApiLimitResp if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } diff --git a/vendor/github.com/xanzy/go-cloudstack/cloudstack/LoadBalancerService.go b/vendor/github.com/xanzy/go-cloudstack/cloudstack/LoadBalancerService.go index 9900a0715..6c7c76e98 100644 --- a/vendor/github.com/xanzy/go-cloudstack/cloudstack/LoadBalancerService.go +++ b/vendor/github.com/xanzy/go-cloudstack/cloudstack/LoadBalancerService.go @@ -238,6 +238,7 @@ func (s *LoadBalancerService) CreateLoadBalancerRule(p *CreateLoadBalancerRulePa return nil, err } } + return &r, nil } @@ -334,6 +335,7 @@ func (s *LoadBalancerService) DeleteLoadBalancerRule(p *DeleteLoadBalancerRulePa return nil, err } } + return &r, nil } @@ -429,6 +431,7 @@ func (s *LoadBalancerService) RemoveFromLoadBalancerRule(p *RemoveFromLoadBalanc return nil, err } } + return &r, nil } @@ -524,6 +527,7 @@ func (s *LoadBalancerService) AssignToLoadBalancerRule(p *AssignToLoadBalancerRu return nil, err } } + return &r, nil } @@ -659,6 +663,7 @@ func (s *LoadBalancerService) CreateLBStickinessPolicy(p *CreateLBStickinessPoli return nil, err } } + return &r, nil } @@ -769,6 +774,7 @@ func (s *LoadBalancerService) UpdateLBStickinessPolicy(p *UpdateLBStickinessPoli return nil, err } } + return &r, nil } @@ -851,6 +857,7 @@ func (s *LoadBalancerService) DeleteLBStickinessPolicy(p *DeleteLBStickinessPoli return nil, err } } + return &r, nil } @@ -1160,6 +1167,7 @@ func (s *LoadBalancerService) ListLoadBalancerRules(p *ListLoadBalancerRulesPara if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -1335,6 +1343,7 @@ func (s *LoadBalancerService) ListLBStickinessPolicies(p *ListLBStickinessPolici if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -1496,6 +1505,7 @@ func (s *LoadBalancerService) ListLBHealthCheckPolicies(p *ListLBHealthCheckPoli if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -1668,6 +1678,7 @@ func (s *LoadBalancerService) CreateLBHealthCheckPolicy(p *CreateLBHealthCheckPo return nil, err } } + return &r, nil } @@ -1777,6 +1788,7 @@ func (s *LoadBalancerService) UpdateLBHealthCheckPolicy(p *UpdateLBHealthCheckPo return nil, err } } + return &r, nil } @@ -1858,6 +1870,7 @@ func (s *LoadBalancerService) DeleteLBHealthCheckPolicy(p *DeleteLBHealthCheckPo return nil, err } } + return &r, nil } @@ -2002,6 +2015,7 @@ func (s *LoadBalancerService) ListLoadBalancerRuleInstances(p *ListLoadBalancerR if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -2135,6 +2149,7 @@ func (s *LoadBalancerService) UpdateLoadBalancerRule(p *UpdateLoadBalancerRulePa return nil, err } } + return &r, nil } @@ -2283,6 +2298,7 @@ func (s *LoadBalancerService) UploadSslCert(p *UploadSslCertParams) (*UploadSslC if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -2342,6 +2358,7 @@ func (s *LoadBalancerService) DeleteSslCert(p *DeleteSslCertParams) (*DeleteSslC if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -2425,6 +2442,7 @@ func (s *LoadBalancerService) ListSslCerts(p *ListSslCertsParams) (*ListSslCerts if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -2516,6 +2534,7 @@ func (s *LoadBalancerService) AssignCertToLoadBalancer(p *AssignCertToLoadBalanc return nil, err } } + return &r, nil } @@ -2583,6 +2602,7 @@ func (s *LoadBalancerService) RemoveCertFromLoadBalancer(p *RemoveCertFromLoadBa return nil, err } } + return &r, nil } @@ -2749,6 +2769,7 @@ func (s *LoadBalancerService) AddNetscalerLoadBalancer(p *AddNetscalerLoadBalanc return nil, err } } + return &r, nil } @@ -2829,6 +2850,7 @@ func (s *LoadBalancerService) DeleteNetscalerLoadBalancer(p *DeleteNetscalerLoad return nil, err } } + return &r, nil } @@ -2949,6 +2971,7 @@ func (s *LoadBalancerService) ConfigureNetscalerLoadBalancer(p *ConfigureNetscal return nil, err } } + return &r, nil } @@ -3059,6 +3082,7 @@ func (s *LoadBalancerService) ListNetscalerLoadBalancers(p *ListNetscalerLoadBal if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -3240,6 +3264,7 @@ func (s *LoadBalancerService) CreateGlobalLoadBalancerRule(p *CreateGlobalLoadBa return nil, err } } + return &r, nil } @@ -3351,6 +3376,7 @@ func (s *LoadBalancerService) DeleteGlobalLoadBalancerRule(p *DeleteGlobalLoadBa return nil, err } } + return &r, nil } @@ -3456,6 +3482,7 @@ func (s *LoadBalancerService) UpdateGlobalLoadBalancerRule(p *UpdateGlobalLoadBa return nil, err } } + return &r, nil } @@ -3754,6 +3781,7 @@ func (s *LoadBalancerService) ListGlobalLoadBalancerRules(p *ListGlobalLoadBalan if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -3898,6 +3926,7 @@ func (s *LoadBalancerService) AssignToGlobalLoadBalancerRule(p *AssignToGlobalLo return nil, err } } + return &r, nil } @@ -3978,6 +4007,7 @@ func (s *LoadBalancerService) RemoveFromGlobalLoadBalancerRule(p *RemoveFromGlob return nil, err } } + return &r, nil } @@ -4158,6 +4188,7 @@ func (s *LoadBalancerService) CreateLoadBalancer(p *CreateLoadBalancerParams) (* return nil, err } } + return &r, nil } @@ -4501,6 +4532,7 @@ func (s *LoadBalancerService) ListLoadBalancers(p *ListLoadBalancersParams) (*Li if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -4606,6 +4638,7 @@ func (s *LoadBalancerService) DeleteLoadBalancer(p *DeleteLoadBalancerParams) (* return nil, err } } + return &r, nil } @@ -4701,6 +4734,7 @@ func (s *LoadBalancerService) UpdateLoadBalancer(p *UpdateLoadBalancerParams) (* return nil, err } } + return &r, nil } diff --git a/vendor/github.com/xanzy/go-cloudstack/cloudstack/NATService.go b/vendor/github.com/xanzy/go-cloudstack/cloudstack/NATService.go index daaf10ede..20b897771 100644 --- a/vendor/github.com/xanzy/go-cloudstack/cloudstack/NATService.go +++ b/vendor/github.com/xanzy/go-cloudstack/cloudstack/NATService.go @@ -101,6 +101,7 @@ func (s *NATService) EnableStaticNat(p *EnableStaticNatParams) (*EnableStaticNat if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -233,6 +234,7 @@ func (s *NATService) CreateIpForwardingRule(p *CreateIpForwardingRuleParams) (*C return nil, err } } + return &r, nil } @@ -326,6 +328,7 @@ func (s *NATService) DeleteIpForwardingRule(p *DeleteIpForwardingRuleParams) (*D return nil, err } } + return &r, nil } @@ -524,6 +527,7 @@ func (s *NATService) ListIpForwardingRules(p *ListIpForwardingRulesParams) (*Lis if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -621,6 +625,7 @@ func (s *NATService) DisableStaticNat(p *DisableStaticNatParams) (*DisableStatic return nil, err } } + return &r, nil } diff --git a/vendor/github.com/xanzy/go-cloudstack/cloudstack/NetworkACLService.go b/vendor/github.com/xanzy/go-cloudstack/cloudstack/NetworkACLService.go index 8a53ddf6e..0a1a32d9f 100644 --- a/vendor/github.com/xanzy/go-cloudstack/cloudstack/NetworkACLService.go +++ b/vendor/github.com/xanzy/go-cloudstack/cloudstack/NetworkACLService.go @@ -215,6 +215,7 @@ func (s *NetworkACLService) CreateNetworkACL(p *CreateNetworkACLParams) (*Create return nil, err } } + return &r, nil } @@ -438,6 +439,7 @@ func (s *NetworkACLService) UpdateNetworkACLItem(p *UpdateNetworkACLItemParams) return nil, err } } + return &r, nil } @@ -528,6 +530,7 @@ func (s *NetworkACLService) DeleteNetworkACL(p *DeleteNetworkACLParams) (*Delete return nil, err } } + return &r, nil } @@ -787,6 +790,7 @@ func (s *NetworkACLService) ListNetworkACLs(p *ListNetworkACLsParams) (*ListNetw if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -921,6 +925,7 @@ func (s *NetworkACLService) CreateNetworkACLList(p *CreateNetworkACLListParams) return nil, err } } + return &r, nil } @@ -991,6 +996,7 @@ func (s *NetworkACLService) DeleteNetworkACLList(p *DeleteNetworkACLListParams) return nil, err } } + return &r, nil } @@ -1080,6 +1086,7 @@ func (s *NetworkACLService) ReplaceNetworkACLList(p *ReplaceNetworkACLListParams return nil, err } } + return &r, nil } @@ -1351,6 +1358,7 @@ func (s *NetworkACLService) ListNetworkACLLists(p *ListNetworkACLListsParams) (* if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -1448,6 +1456,7 @@ func (s *NetworkACLService) UpdateNetworkACLList(p *UpdateNetworkACLListParams) return nil, err } } + return &r, nil } diff --git a/vendor/github.com/xanzy/go-cloudstack/cloudstack/NetworkDeviceService.go b/vendor/github.com/xanzy/go-cloudstack/cloudstack/NetworkDeviceService.go index 878d5286e..36e8adc32 100644 --- a/vendor/github.com/xanzy/go-cloudstack/cloudstack/NetworkDeviceService.go +++ b/vendor/github.com/xanzy/go-cloudstack/cloudstack/NetworkDeviceService.go @@ -81,6 +81,7 @@ func (s *NetworkDeviceService) AddNetworkDevice(p *AddNetworkDeviceParams) (*Add if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -181,6 +182,7 @@ func (s *NetworkDeviceService) ListNetworkDevice(p *ListNetworkDeviceParams) (*L if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -236,6 +238,7 @@ func (s *NetworkDeviceService) DeleteNetworkDevice(p *DeleteNetworkDeviceParams) if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } diff --git a/vendor/github.com/xanzy/go-cloudstack/cloudstack/NetworkOfferingService.go b/vendor/github.com/xanzy/go-cloudstack/cloudstack/NetworkOfferingService.go index e0adf29af..bc5428b3a 100644 --- a/vendor/github.com/xanzy/go-cloudstack/cloudstack/NetworkOfferingService.go +++ b/vendor/github.com/xanzy/go-cloudstack/cloudstack/NetworkOfferingService.go @@ -297,6 +297,7 @@ func (s *NetworkOfferingService) CreateNetworkOffering(p *CreateNetworkOfferingP if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -463,6 +464,7 @@ func (s *NetworkOfferingService) UpdateNetworkOffering(p *UpdateNetworkOfferingP if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -550,6 +552,7 @@ func (s *NetworkOfferingService) DeleteNetworkOffering(p *DeleteNetworkOfferingP if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -901,6 +904,7 @@ func (s *NetworkOfferingService) ListNetworkOfferings(p *ListNetworkOfferingsPar if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } diff --git a/vendor/github.com/xanzy/go-cloudstack/cloudstack/NetworkService.go b/vendor/github.com/xanzy/go-cloudstack/cloudstack/NetworkService.go index ce07a3b9e..28c9d0f13 100644 --- a/vendor/github.com/xanzy/go-cloudstack/cloudstack/NetworkService.go +++ b/vendor/github.com/xanzy/go-cloudstack/cloudstack/NetworkService.go @@ -101,6 +101,7 @@ func (s *NetworkService) DedicatePublicIpRange(p *DedicatePublicIpRangeParams) ( if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -172,6 +173,7 @@ func (s *NetworkService) ReleasePublicIpRange(p *ReleasePublicIpRangeParams) (*R if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -485,6 +487,7 @@ func (s *NetworkService) CreateNetwork(p *CreateNetworkParams) (*CreateNetworkRe if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -636,6 +639,7 @@ func (s *NetworkService) DeleteNetwork(p *DeleteNetworkParams) (*DeleteNetworkRe return nil, err } } + return &r, nil } @@ -1028,6 +1032,7 @@ func (s *NetworkService) ListNetworks(p *ListNetworksParams) (*ListNetworksRespo if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -1189,6 +1194,7 @@ func (s *NetworkService) RestartNetwork(p *RestartNetworkParams) (*RestartNetwor return nil, err } } + return &r, nil } @@ -1390,6 +1396,7 @@ func (s *NetworkService) UpdateNetwork(p *UpdateNetworkParams) (*UpdateNetworkRe return nil, err } } + return &r, nil } @@ -1615,6 +1622,7 @@ func (s *NetworkService) CreatePhysicalNetwork(p *CreatePhysicalNetworkParams) ( return nil, err } } + return &r, nil } @@ -1690,6 +1698,7 @@ func (s *NetworkService) DeletePhysicalNetwork(p *DeletePhysicalNetworkParams) ( return nil, err } } + return &r, nil } @@ -1881,6 +1890,7 @@ func (s *NetworkService) ListPhysicalNetworks(p *ListPhysicalNetworksParams) (*L if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -2010,6 +2020,7 @@ func (s *NetworkService) UpdatePhysicalNetwork(p *UpdatePhysicalNetworkParams) ( return nil, err } } + return &r, nil } @@ -2115,6 +2126,7 @@ func (s *NetworkService) ListSupportedNetworkServices(p *ListSupportedNetworkSer if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -2239,6 +2251,7 @@ func (s *NetworkService) AddNetworkServiceProvider(p *AddNetworkServiceProviderP return nil, err } } + return &r, nil } @@ -2311,6 +2324,7 @@ func (s *NetworkService) DeleteNetworkServiceProvider(p *DeleteNetworkServicePro return nil, err } } + return &r, nil } @@ -2455,6 +2469,7 @@ func (s *NetworkService) ListNetworkServiceProviders(p *ListNetworkServiceProvid if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -2559,6 +2574,7 @@ func (s *NetworkService) UpdateNetworkServiceProvider(p *UpdateNetworkServicePro return nil, err } } + return &r, nil } @@ -2695,6 +2711,7 @@ func (s *NetworkService) CreateStorageNetworkIpRange(p *CreateStorageNetworkIpRa return nil, err } } + return &r, nil } @@ -2769,6 +2786,7 @@ func (s *NetworkService) DeleteStorageNetworkIpRange(p *DeleteStorageNetworkIpRa return nil, err } } + return &r, nil } @@ -2910,6 +2928,7 @@ func (s *NetworkService) ListStorageNetworkIpRange(p *ListStorageNetworkIpRangeP if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -3038,6 +3057,7 @@ func (s *NetworkService) UpdateStorageNetworkIpRange(p *UpdateStorageNetworkIpRa return nil, err } } + return &r, nil } @@ -3169,6 +3189,7 @@ func (s *NetworkService) ListPaloAltoFirewallNetworks(p *ListPaloAltoFirewallNet if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -3370,6 +3391,7 @@ func (s *NetworkService) ListNetscalerLoadBalancerNetworks(p *ListNetscalerLoadB if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -3571,6 +3593,7 @@ func (s *NetworkService) ListNiciraNvpDeviceNetworks(p *ListNiciraNvpDeviceNetwo if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -3723,6 +3746,7 @@ func (s *NetworkService) ListNetworkIsolationMethods(p *ListNetworkIsolationMeth if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -3834,6 +3858,7 @@ func (s *NetworkService) AddOpenDaylightController(p *AddOpenDaylightControllerP return nil, err } } + return &r, nil } @@ -3909,6 +3934,7 @@ func (s *NetworkService) DeleteOpenDaylightController(p *DeleteOpenDaylightContr return nil, err } } + return &r, nil } @@ -4007,6 +4033,7 @@ func (s *NetworkService) ListOpenDaylightControllers(p *ListOpenDaylightControll if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } diff --git a/vendor/github.com/xanzy/go-cloudstack/cloudstack/NicService.go b/vendor/github.com/xanzy/go-cloudstack/cloudstack/NicService.go index d83e07567..1f83135a3 100644 --- a/vendor/github.com/xanzy/go-cloudstack/cloudstack/NicService.go +++ b/vendor/github.com/xanzy/go-cloudstack/cloudstack/NicService.go @@ -96,6 +96,7 @@ func (s *NicService) AddIpToNic(p *AddIpToNicParams) (*AddIpToNicResponse, error return nil, err } } + return &r, nil } @@ -166,6 +167,7 @@ func (s *NicService) RemoveIpFromNic(p *RemoveIpFromNicParams) (*RemoveIpFromNic return nil, err } } + return &r, nil } @@ -249,6 +251,7 @@ func (s *NicService) UpdateVmNicIp(p *UpdateVmNicIpParams) (*UpdateVmNicIpRespon return nil, err } } + return &r, nil } @@ -541,6 +544,7 @@ func (s *NicService) ListNics(p *ListNicsParams) (*ListNicsResponse, error) { if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } diff --git a/vendor/github.com/xanzy/go-cloudstack/cloudstack/NiciraNVPService.go b/vendor/github.com/xanzy/go-cloudstack/cloudstack/NiciraNVPService.go index 2efcd1587..a97d71bdd 100644 --- a/vendor/github.com/xanzy/go-cloudstack/cloudstack/NiciraNVPService.go +++ b/vendor/github.com/xanzy/go-cloudstack/cloudstack/NiciraNVPService.go @@ -144,6 +144,7 @@ func (s *NiciraNVPService) AddNiciraNvpDevice(p *AddNiciraNvpDeviceParams) (*Add return nil, err } } + return &r, nil } @@ -216,6 +217,7 @@ func (s *NiciraNVPService) DeleteNiciraNvpDevice(p *DeleteNiciraNvpDeviceParams) return nil, err } } + return &r, nil } @@ -313,6 +315,7 @@ func (s *NiciraNVPService) ListNiciraNvpDevices(p *ListNiciraNvpDevicesParams) ( if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } diff --git a/vendor/github.com/xanzy/go-cloudstack/cloudstack/OvsElementService.go b/vendor/github.com/xanzy/go-cloudstack/cloudstack/OvsElementService.go index a86d61f28..f030be742 100644 --- a/vendor/github.com/xanzy/go-cloudstack/cloudstack/OvsElementService.go +++ b/vendor/github.com/xanzy/go-cloudstack/cloudstack/OvsElementService.go @@ -100,6 +100,7 @@ func (s *OvsElementService) ConfigureOvsElement(p *ConfigureOvsElementParams) (* return nil, err } } + return &r, nil } @@ -248,6 +249,7 @@ func (s *OvsElementService) ListOvsElements(p *ListOvsElementsParams) (*ListOvsE if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } diff --git a/vendor/github.com/xanzy/go-cloudstack/cloudstack/PodService.go b/vendor/github.com/xanzy/go-cloudstack/cloudstack/PodService.go index 2f0af1eec..dfb59acbb 100644 --- a/vendor/github.com/xanzy/go-cloudstack/cloudstack/PodService.go +++ b/vendor/github.com/xanzy/go-cloudstack/cloudstack/PodService.go @@ -137,6 +137,7 @@ func (s *PodService) CreatePod(p *CreatePodParams) (*CreatePodResponse, error) { if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -273,6 +274,7 @@ func (s *PodService) UpdatePod(p *UpdatePodParams) (*UpdatePodResponse, error) { if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -343,6 +345,7 @@ func (s *PodService) DeletePod(p *DeletePodParams) (*DeletePodResponse, error) { if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -556,6 +559,7 @@ func (s *PodService) ListPods(p *ListPodsParams) (*ListPodsResponse, error) { if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -674,6 +678,7 @@ func (s *PodService) DedicatePod(p *DedicatePodParams) (*DedicatePodResponse, er return nil, err } } + return &r, nil } @@ -745,6 +750,7 @@ func (s *PodService) ReleaseDedicatedPod(p *ReleaseDedicatedPodParams) (*Release return nil, err } } + return &r, nil } @@ -864,6 +870,7 @@ func (s *PodService) ListDedicatedPods(p *ListDedicatedPodsParams) (*ListDedicat if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } diff --git a/vendor/github.com/xanzy/go-cloudstack/cloudstack/PoolService.go b/vendor/github.com/xanzy/go-cloudstack/cloudstack/PoolService.go index f2f8fce99..13bdc8735 100644 --- a/vendor/github.com/xanzy/go-cloudstack/cloudstack/PoolService.go +++ b/vendor/github.com/xanzy/go-cloudstack/cloudstack/PoolService.go @@ -261,6 +261,7 @@ func (s *PoolService) ListStoragePools(p *ListStoragePoolsParams) (*ListStorageP if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -480,6 +481,7 @@ func (s *PoolService) CreateStoragePool(p *CreateStoragePoolParams) (*CreateStor if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -600,6 +602,7 @@ func (s *PoolService) UpdateStoragePool(p *UpdateStoragePoolParams) (*UpdateStor if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -684,6 +687,7 @@ func (s *PoolService) DeleteStoragePool(p *DeleteStoragePoolParams) (*DeleteStor if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -770,6 +774,7 @@ func (s *PoolService) FindStoragePoolsForMigration(p *FindStoragePoolsForMigrati if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } diff --git a/vendor/github.com/xanzy/go-cloudstack/cloudstack/PortableIPService.go b/vendor/github.com/xanzy/go-cloudstack/cloudstack/PortableIPService.go index 2896ae2bb..be4958af8 100644 --- a/vendor/github.com/xanzy/go-cloudstack/cloudstack/PortableIPService.go +++ b/vendor/github.com/xanzy/go-cloudstack/cloudstack/PortableIPService.go @@ -147,6 +147,7 @@ func (s *PortableIPService) CreatePortableIpRange(p *CreatePortableIpRangeParams return nil, err } } + return &r, nil } @@ -231,6 +232,7 @@ func (s *PortableIPService) DeletePortableIpRange(p *DeletePortableIpRangeParams return nil, err } } + return &r, nil } @@ -362,6 +364,7 @@ func (s *PortableIPService) ListPortableIpRanges(p *ListPortableIpRangesParams) if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } diff --git a/vendor/github.com/xanzy/go-cloudstack/cloudstack/ProjectService.go b/vendor/github.com/xanzy/go-cloudstack/cloudstack/ProjectService.go index 8b9c0e86f..e701d36d2 100644 --- a/vendor/github.com/xanzy/go-cloudstack/cloudstack/ProjectService.go +++ b/vendor/github.com/xanzy/go-cloudstack/cloudstack/ProjectService.go @@ -121,6 +121,7 @@ func (s *ProjectService) CreateProject(p *CreateProjectParams) (*CreateProjectRe return nil, err } } + return &r, nil } @@ -240,6 +241,7 @@ func (s *ProjectService) DeleteProject(p *DeleteProjectParams) (*DeleteProjectRe return nil, err } } + return &r, nil } @@ -334,6 +336,7 @@ func (s *ProjectService) UpdateProject(p *UpdateProjectParams) (*UpdateProjectRe return nil, err } } + return &r, nil } @@ -458,6 +461,7 @@ func (s *ProjectService) ActivateProject(p *ActivateProjectParams) (*ActivatePro return nil, err } } + return &r, nil } @@ -582,6 +586,7 @@ func (s *ProjectService) SuspendProject(p *SuspendProjectParams) (*SuspendProjec return nil, err } } + return &r, nil } @@ -898,6 +903,7 @@ func (s *ProjectService) ListProjects(p *ListProjectsParams) (*ListProjectsRespo if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -1153,6 +1159,7 @@ func (s *ProjectService) ListProjectInvitations(p *ListProjectInvitationsParams) if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -1264,6 +1271,7 @@ func (s *ProjectService) UpdateProjectInvitation(p *UpdateProjectInvitationParam return nil, err } } + return &r, nil } @@ -1331,6 +1339,7 @@ func (s *ProjectService) DeleteProjectInvitation(p *DeleteProjectInvitationParam return nil, err } } + return &r, nil } diff --git a/vendor/github.com/xanzy/go-cloudstack/cloudstack/QuotaService.go b/vendor/github.com/xanzy/go-cloudstack/cloudstack/QuotaService.go index 896a4d798..9ae21e690 100644 --- a/vendor/github.com/xanzy/go-cloudstack/cloudstack/QuotaService.go +++ b/vendor/github.com/xanzy/go-cloudstack/cloudstack/QuotaService.go @@ -52,6 +52,7 @@ func (s *QuotaService) QuotaIsEnabled(p *QuotaIsEnabledParams) (*QuotaIsEnabledR if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } diff --git a/vendor/github.com/xanzy/go-cloudstack/cloudstack/RegionService.go b/vendor/github.com/xanzy/go-cloudstack/cloudstack/RegionService.go index a434f8513..94dc503c5 100644 --- a/vendor/github.com/xanzy/go-cloudstack/cloudstack/RegionService.go +++ b/vendor/github.com/xanzy/go-cloudstack/cloudstack/RegionService.go @@ -90,6 +90,7 @@ func (s *RegionService) AddRegion(p *AddRegionParams) (*AddRegionResponse, error if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -167,6 +168,7 @@ func (s *RegionService) UpdateRegion(p *UpdateRegionParams) (*UpdateRegionRespon if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -222,6 +224,7 @@ func (s *RegionService) RemoveRegion(p *RemoveRegionParams) (*RemoveRegionRespon if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -319,6 +322,7 @@ func (s *RegionService) ListRegions(p *ListRegionsParams) (*ListRegionsResponse, if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } diff --git a/vendor/github.com/xanzy/go-cloudstack/cloudstack/ResourcemetadataService.go b/vendor/github.com/xanzy/go-cloudstack/cloudstack/ResourcemetadataService.go index 136b9d3b1..cf0e28ed4 100644 --- a/vendor/github.com/xanzy/go-cloudstack/cloudstack/ResourcemetadataService.go +++ b/vendor/github.com/xanzy/go-cloudstack/cloudstack/ResourcemetadataService.go @@ -122,6 +122,7 @@ func (s *ResourcemetadataService) AddResourceDetail(p *AddResourceDetailParams) return nil, err } } + return &r, nil } @@ -212,6 +213,7 @@ func (s *ResourcemetadataService) RemoveResourceDetail(p *RemoveResourceDetailPa return nil, err } } + return &r, nil } @@ -401,6 +403,7 @@ func (s *ResourcemetadataService) ListResourceDetails(p *ListResourceDetailsPara if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } diff --git a/vendor/github.com/xanzy/go-cloudstack/cloudstack/ResourcetagsService.go b/vendor/github.com/xanzy/go-cloudstack/cloudstack/ResourcetagsService.go index b285a2466..6995533d2 100644 --- a/vendor/github.com/xanzy/go-cloudstack/cloudstack/ResourcetagsService.go +++ b/vendor/github.com/xanzy/go-cloudstack/cloudstack/ResourcetagsService.go @@ -126,6 +126,7 @@ func (s *ResourcetagsService) ListStorageTags(p *ListStorageTagsParams) (*ListSt if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -239,6 +240,7 @@ func (s *ResourcetagsService) CreateTags(p *CreateTagsParams) (*CreateTagsRespon return nil, err } } + return &r, nil } @@ -335,6 +337,7 @@ func (s *ResourcetagsService) DeleteTags(p *DeleteTagsParams) (*DeleteTagsRespon return nil, err } } + return &r, nil } @@ -522,6 +525,7 @@ func (s *ResourcetagsService) ListTags(p *ListTagsParams) (*ListTagsResponse, er if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } diff --git a/vendor/github.com/xanzy/go-cloudstack/cloudstack/RouterService.go b/vendor/github.com/xanzy/go-cloudstack/cloudstack/RouterService.go index 05496b530..94efd9162 100644 --- a/vendor/github.com/xanzy/go-cloudstack/cloudstack/RouterService.go +++ b/vendor/github.com/xanzy/go-cloudstack/cloudstack/RouterService.go @@ -87,6 +87,7 @@ func (s *RouterService) StartRouter(p *StartRouterParams) (*StartRouterResponse, return nil, err } } + return &r, nil } @@ -225,6 +226,7 @@ func (s *RouterService) RebootRouter(p *RebootRouterParams) (*RebootRouterRespon return nil, err } } + return &r, nil } @@ -375,6 +377,7 @@ func (s *RouterService) StopRouter(p *StopRouterParams) (*StopRouterResponse, er return nil, err } } + return &r, nil } @@ -513,6 +516,7 @@ func (s *RouterService) DestroyRouter(p *DestroyRouterParams) (*DestroyRouterRes return nil, err } } + return &r, nil } @@ -643,6 +647,7 @@ func (s *RouterService) ChangeServiceForRouter(p *ChangeServiceForRouterParams) if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -1045,6 +1050,7 @@ func (s *RouterService) ListRouters(p *ListRoutersParams) (*ListRoutersResponse, if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -1257,6 +1263,7 @@ func (s *RouterService) ListVirtualRouterElements(p *ListVirtualRouterElementsPa if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -1352,6 +1359,7 @@ func (s *RouterService) ConfigureVirtualRouterElement(p *ConfigureVirtualRouterE return nil, err } } + return &r, nil } @@ -1441,6 +1449,7 @@ func (s *RouterService) CreateVirtualRouterElement(p *CreateVirtualRouterElement return nil, err } } + return &r, nil } diff --git a/vendor/github.com/xanzy/go-cloudstack/cloudstack/SSHService.go b/vendor/github.com/xanzy/go-cloudstack/cloudstack/SSHService.go index 2221a5921..f1e413313 100644 --- a/vendor/github.com/xanzy/go-cloudstack/cloudstack/SSHService.go +++ b/vendor/github.com/xanzy/go-cloudstack/cloudstack/SSHService.go @@ -130,6 +130,7 @@ func (s *SSHService) ResetSSHKeyForVirtualMachine(p *ResetSSHKeyForVirtualMachin return nil, err } } + return &r, nil } @@ -402,6 +403,7 @@ func (s *SSHService) RegisterSSHKeyPair(p *RegisterSSHKeyPairParams) (*RegisterS if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -493,6 +495,7 @@ func (s *SSHService) CreateSSHKeyPair(p *CreateSSHKeyPairParams) (*CreateSSHKeyP if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -576,6 +579,7 @@ func (s *SSHService) DeleteSSHKeyPair(p *DeleteSSHKeyPairParams) (*DeleteSSHKeyP if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -729,6 +733,7 @@ func (s *SSHService) ListSSHKeyPairs(p *ListSSHKeyPairsParams) (*ListSSHKeyPairs if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } diff --git a/vendor/github.com/xanzy/go-cloudstack/cloudstack/SecurityGroupService.go b/vendor/github.com/xanzy/go-cloudstack/cloudstack/SecurityGroupService.go index 7a56c1cbb..8e7c61499 100644 --- a/vendor/github.com/xanzy/go-cloudstack/cloudstack/SecurityGroupService.go +++ b/vendor/github.com/xanzy/go-cloudstack/cloudstack/SecurityGroupService.go @@ -147,6 +147,7 @@ func (s *SecurityGroupService) CreateSecurityGroup(p *CreateSecurityGroupParams) if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -307,6 +308,7 @@ func (s *SecurityGroupService) DeleteSecurityGroup(p *DeleteSecurityGroupParams) if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -513,6 +515,7 @@ func (s *SecurityGroupService) AuthorizeSecurityGroupIngress(p *AuthorizeSecurit return nil, err } } + return &r, nil } @@ -599,6 +602,7 @@ func (s *SecurityGroupService) RevokeSecurityGroupIngress(p *RevokeSecurityGroup return nil, err } } + return &r, nil } @@ -806,6 +810,7 @@ func (s *SecurityGroupService) AuthorizeSecurityGroupEgress(p *AuthorizeSecurity return nil, err } } + return &r, nil } @@ -892,6 +897,7 @@ func (s *SecurityGroupService) RevokeSecurityGroupEgress(p *RevokeSecurityGroupE return nil, err } } + return &r, nil } @@ -1156,6 +1162,7 @@ func (s *SecurityGroupService) ListSecurityGroups(p *ListSecurityGroupsParams) ( if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } diff --git a/vendor/github.com/xanzy/go-cloudstack/cloudstack/ServiceOfferingService.go b/vendor/github.com/xanzy/go-cloudstack/cloudstack/ServiceOfferingService.go index 95e764703..bfd657912 100644 --- a/vendor/github.com/xanzy/go-cloudstack/cloudstack/ServiceOfferingService.go +++ b/vendor/github.com/xanzy/go-cloudstack/cloudstack/ServiceOfferingService.go @@ -368,6 +368,7 @@ func (s *ServiceOfferingService) CreateServiceOffering(p *CreateServiceOfferingP if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -448,6 +449,7 @@ func (s *ServiceOfferingService) DeleteServiceOffering(p *DeleteServiceOfferingP if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -533,6 +535,7 @@ func (s *ServiceOfferingService) UpdateServiceOffering(p *UpdateServiceOfferingP if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -810,6 +813,7 @@ func (s *ServiceOfferingService) ListServiceOfferings(p *ListServiceOfferingsPar if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } diff --git a/vendor/github.com/xanzy/go-cloudstack/cloudstack/SnapshotService.go b/vendor/github.com/xanzy/go-cloudstack/cloudstack/SnapshotService.go index c81dea323..c1c432de1 100644 --- a/vendor/github.com/xanzy/go-cloudstack/cloudstack/SnapshotService.go +++ b/vendor/github.com/xanzy/go-cloudstack/cloudstack/SnapshotService.go @@ -143,6 +143,7 @@ func (s *SnapshotService) CreateSnapshot(p *CreateSnapshotParams) (*CreateSnapsh return nil, err } } + return &r, nil } @@ -467,6 +468,7 @@ func (s *SnapshotService) ListSnapshots(p *ListSnapshotsParams) (*ListSnapshotsR if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -565,6 +567,7 @@ func (s *SnapshotService) DeleteSnapshot(p *DeleteSnapshotParams) (*DeleteSnapsh return nil, err } } + return &r, nil } @@ -678,6 +681,7 @@ func (s *SnapshotService) CreateSnapshotPolicy(p *CreateSnapshotPolicyParams) (* if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -776,6 +780,7 @@ func (s *SnapshotService) UpdateSnapshotPolicy(p *UpdateSnapshotPolicyParams) (* return nil, err } } + return &r, nil } @@ -844,6 +849,7 @@ func (s *SnapshotService) DeleteSnapshotPolicies(p *DeleteSnapshotPoliciesParams if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -985,6 +991,7 @@ func (s *SnapshotService) ListSnapshotPolicies(p *ListSnapshotPoliciesParams) (* if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -1066,6 +1073,7 @@ func (s *SnapshotService) RevertSnapshot(p *RevertSnapshotParams) (*RevertSnapsh return nil, err } } + return &r, nil } @@ -1321,6 +1329,7 @@ func (s *SnapshotService) ListVMSnapshot(p *ListVMSnapshotParams) (*ListVMSnapsh if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -1458,6 +1467,7 @@ func (s *SnapshotService) CreateVMSnapshot(p *CreateVMSnapshotParams) (*CreateVM return nil, err } } + return &r, nil } @@ -1540,6 +1550,7 @@ func (s *SnapshotService) DeleteVMSnapshot(p *DeleteVMSnapshotParams) (*DeleteVM return nil, err } } + return &r, nil } @@ -1612,6 +1623,7 @@ func (s *SnapshotService) RevertToVMSnapshot(p *RevertToVMSnapshotParams) (*Reve return nil, err } } + return &r, nil } diff --git a/vendor/github.com/xanzy/go-cloudstack/cloudstack/StoragePoolService.go b/vendor/github.com/xanzy/go-cloudstack/cloudstack/StoragePoolService.go index 227678fe0..ec264e694 100644 --- a/vendor/github.com/xanzy/go-cloudstack/cloudstack/StoragePoolService.go +++ b/vendor/github.com/xanzy/go-cloudstack/cloudstack/StoragePoolService.go @@ -100,6 +100,7 @@ func (s *StoragePoolService) ListStorageProviders(p *ListStorageProvidersParams) if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -176,6 +177,7 @@ func (s *StoragePoolService) EnableStorageMaintenance(p *EnableStorageMaintenanc return nil, err } } + return &r, nil } @@ -269,6 +271,7 @@ func (s *StoragePoolService) CancelStorageMaintenance(p *CancelStorageMaintenanc return nil, err } } + return &r, nil } diff --git a/vendor/github.com/xanzy/go-cloudstack/cloudstack/StratosphereSSPService.go b/vendor/github.com/xanzy/go-cloudstack/cloudstack/StratosphereSSPService.go index 4e638f843..227b2b6e7 100644 --- a/vendor/github.com/xanzy/go-cloudstack/cloudstack/StratosphereSSPService.go +++ b/vendor/github.com/xanzy/go-cloudstack/cloudstack/StratosphereSSPService.go @@ -121,6 +121,7 @@ func (s *StratosphereSSPService) AddStratosphereSsp(p *AddStratosphereSspParams) if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } diff --git a/vendor/github.com/xanzy/go-cloudstack/cloudstack/SwiftService.go b/vendor/github.com/xanzy/go-cloudstack/cloudstack/SwiftService.go index 72bcfc608..0a82f79a8 100644 --- a/vendor/github.com/xanzy/go-cloudstack/cloudstack/SwiftService.go +++ b/vendor/github.com/xanzy/go-cloudstack/cloudstack/SwiftService.go @@ -99,6 +99,7 @@ func (s *SwiftService) AddSwift(p *AddSwiftParams) (*AddSwiftResponse, error) { if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -228,6 +229,7 @@ func (s *SwiftService) ListSwifts(p *ListSwiftsParams) (*ListSwiftsResponse, err if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } diff --git a/vendor/github.com/xanzy/go-cloudstack/cloudstack/SystemCapacityService.go b/vendor/github.com/xanzy/go-cloudstack/cloudstack/SystemCapacityService.go index fc30665c3..f137cb896 100644 --- a/vendor/github.com/xanzy/go-cloudstack/cloudstack/SystemCapacityService.go +++ b/vendor/github.com/xanzy/go-cloudstack/cloudstack/SystemCapacityService.go @@ -156,6 +156,7 @@ func (s *SystemCapacityService) ListCapacity(p *ListCapacityParams) (*ListCapaci if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } diff --git a/vendor/github.com/xanzy/go-cloudstack/cloudstack/SystemVMService.go b/vendor/github.com/xanzy/go-cloudstack/cloudstack/SystemVMService.go index 18b697a85..f169ca73c 100644 --- a/vendor/github.com/xanzy/go-cloudstack/cloudstack/SystemVMService.go +++ b/vendor/github.com/xanzy/go-cloudstack/cloudstack/SystemVMService.go @@ -87,6 +87,7 @@ func (s *SystemVMService) StartSystemVm(p *StartSystemVmParams) (*StartSystemVmR return nil, err } } + return &r, nil } @@ -185,6 +186,7 @@ func (s *SystemVMService) RebootSystemVm(p *RebootSystemVmParams) (*RebootSystem return nil, err } } + return &r, nil } @@ -295,6 +297,7 @@ func (s *SystemVMService) StopSystemVm(p *StopSystemVmParams) (*StopSystemVmResp return nil, err } } + return &r, nil } @@ -393,6 +396,7 @@ func (s *SystemVMService) DestroySystemVm(p *DestroySystemVmParams) (*DestroySys return nil, err } } + return &r, nil } @@ -665,6 +669,7 @@ func (s *SystemVMService) ListSystemVms(p *ListSystemVmsParams) (*ListSystemVmsR if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -779,6 +784,7 @@ func (s *SystemVMService) MigrateSystemVm(p *MigrateSystemVmParams) (*MigrateSys return nil, err } } + return &r, nil } @@ -885,6 +891,7 @@ func (s *SystemVMService) ChangeServiceForSystemVm(p *ChangeServiceForSystemVmPa if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -1010,6 +1017,7 @@ func (s *SystemVMService) ScaleSystemVm(p *ScaleSystemVmParams) (*ScaleSystemVmR return nil, err } } + return &r, nil } diff --git a/vendor/github.com/xanzy/go-cloudstack/cloudstack/TemplateService.go b/vendor/github.com/xanzy/go-cloudstack/cloudstack/TemplateService.go index 30498c7c6..3ccf39316 100644 --- a/vendor/github.com/xanzy/go-cloudstack/cloudstack/TemplateService.go +++ b/vendor/github.com/xanzy/go-cloudstack/cloudstack/TemplateService.go @@ -265,6 +265,7 @@ func (s *TemplateService) CreateTemplate(p *CreateTemplateParams) (*CreateTempla return nil, err } } + return &r, nil } @@ -613,6 +614,7 @@ func (s *TemplateService) RegisterTemplate(p *RegisterTemplateParams) (*Register if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -846,6 +848,7 @@ func (s *TemplateService) UpdateTemplate(p *UpdateTemplateParams) (*UpdateTempla if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -985,6 +988,7 @@ func (s *TemplateService) CopyTemplate(p *CopyTemplateParams) (*CopyTemplateResp return nil, err } } + return &r, nil } @@ -1108,6 +1112,7 @@ func (s *TemplateService) DeleteTemplate(p *DeleteTemplateParams) (*DeleteTempla return nil, err } } + return &r, nil } @@ -1410,6 +1415,7 @@ func (s *TemplateService) ListTemplates(p *ListTemplatesParams) (*ListTemplatesR if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -1582,6 +1588,7 @@ func (s *TemplateService) UpdateTemplatePermissions(p *UpdateTemplatePermissions if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -1666,6 +1673,7 @@ func (s *TemplateService) ListTemplatePermissions(p *ListTemplatePermissionsPara if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -1779,6 +1787,7 @@ func (s *TemplateService) ExtractTemplate(p *ExtractTemplateParams) (*ExtractTem return nil, err } } + return &r, nil } @@ -1866,6 +1875,7 @@ func (s *TemplateService) PrepareTemplate(p *PrepareTemplateParams) (*PrepareTem if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -2016,6 +2026,7 @@ func (s *TemplateService) UpgradeRouterTemplate(p *UpgradeRouterTemplateParams) if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -2306,6 +2317,7 @@ func (s *TemplateService) GetUploadParamsForTemplate(p *GetUploadParamsForTempla if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } diff --git a/vendor/github.com/xanzy/go-cloudstack/cloudstack/UCSService.go b/vendor/github.com/xanzy/go-cloudstack/cloudstack/UCSService.go index 3d5fbd33a..66e1b6c0b 100644 --- a/vendor/github.com/xanzy/go-cloudstack/cloudstack/UCSService.go +++ b/vendor/github.com/xanzy/go-cloudstack/cloudstack/UCSService.go @@ -114,6 +114,7 @@ func (s *UCSService) AddUcsManager(p *AddUcsManagerParams) (*AddUcsManagerRespon if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -295,6 +296,7 @@ func (s *UCSService) ListUcsManagers(p *ListUcsManagersParams) (*ListUcsManagers if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -388,6 +390,7 @@ func (s *UCSService) ListUcsProfiles(p *ListUcsProfilesParams) (*ListUcsProfiles if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -478,6 +481,7 @@ func (s *UCSService) ListUcsBlades(p *ListUcsBladesParams) (*ListUcsBladesRespon if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -581,6 +585,7 @@ func (s *UCSService) AssociateUcsProfileToBlade(p *AssociateUcsProfileToBladePar return nil, err } } + return &r, nil } diff --git a/vendor/github.com/xanzy/go-cloudstack/cloudstack/UsageService.go b/vendor/github.com/xanzy/go-cloudstack/cloudstack/UsageService.go index fb6e34306..67b683f95 100644 --- a/vendor/github.com/xanzy/go-cloudstack/cloudstack/UsageService.go +++ b/vendor/github.com/xanzy/go-cloudstack/cloudstack/UsageService.go @@ -175,6 +175,7 @@ func (s *UsageService) AddTrafficType(p *AddTrafficTypeParams) (*AddTrafficTypeR return nil, err } } + return &r, nil } @@ -248,6 +249,7 @@ func (s *UsageService) DeleteTrafficType(p *DeleteTrafficTypeParams) (*DeleteTra return nil, err } } + return &r, nil } @@ -372,6 +374,7 @@ func (s *UsageService) ListTrafficTypes(p *ListTrafficTypesParams) (*ListTraffic if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -508,6 +511,7 @@ func (s *UsageService) UpdateTrafficType(p *UpdateTrafficTypeParams) (*UpdateTra return nil, err } } + return &r, nil } @@ -600,6 +604,7 @@ func (s *UsageService) ListTrafficTypeImplementors(p *ListTrafficTypeImplementor if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -679,6 +684,7 @@ func (s *UsageService) GenerateUsageRecords(p *GenerateUsageRecordsParams) (*Gen if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -844,6 +850,7 @@ func (s *UsageService) ListUsageRecords(p *ListUsageRecordsParams) (*ListUsageRe if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -914,6 +921,7 @@ func (s *UsageService) ListUsageTypes(p *ListUsageTypesParams) (*ListUsageTypesR if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -971,6 +979,7 @@ func (s *UsageService) RemoveRawUsageRecords(p *RemoveRawUsageRecordsParams) (*R if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -1056,6 +1065,7 @@ func (s *UsageService) AddTrafficMonitor(p *AddTrafficMonitorParams) (*AddTraffi if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -1110,6 +1120,7 @@ func (s *UsageService) DeleteTrafficMonitor(p *DeleteTrafficMonitorParams) (*Del if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -1196,6 +1207,7 @@ func (s *UsageService) ListTrafficMonitors(p *ListTrafficMonitorsParams) (*ListT if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } diff --git a/vendor/github.com/xanzy/go-cloudstack/cloudstack/UserService.go b/vendor/github.com/xanzy/go-cloudstack/cloudstack/UserService.go index cf091225d..100920af4 100644 --- a/vendor/github.com/xanzy/go-cloudstack/cloudstack/UserService.go +++ b/vendor/github.com/xanzy/go-cloudstack/cloudstack/UserService.go @@ -160,6 +160,7 @@ func (s *UserService) CreateUser(p *CreateUserParams) (*CreateUserResponse, erro if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -226,6 +227,7 @@ func (s *UserService) DeleteUser(p *DeleteUserParams) (*DeleteUserResponse, erro if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -365,6 +367,7 @@ func (s *UserService) UpdateUser(p *UpdateUserParams) (*UpdateUserResponse, erro if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -578,6 +581,7 @@ func (s *UserService) ListUsers(p *ListUsersParams) (*ListUsersResponse, error) if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -649,6 +653,7 @@ func (s *UserService) LockUser(p *LockUserParams) (*LockUserResponse, error) { if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -735,6 +740,7 @@ func (s *UserService) DisableUser(p *DisableUserParams) (*DisableUserResponse, e return nil, err } } + return &r, nil } @@ -802,6 +808,7 @@ func (s *UserService) EnableUser(p *EnableUserParams) (*EnableUserResponse, erro if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -868,6 +875,7 @@ func (s *UserService) GetUser(p *GetUserParams) (*GetUserResponse, error) { if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -934,6 +942,7 @@ func (s *UserService) GetVirtualMachineUserData(p *GetVirtualMachineUserDataPara if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -985,6 +994,7 @@ func (s *UserService) RegisterUserKeys(p *RegisterUserKeysParams) (*RegisterUser if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -1070,6 +1080,7 @@ func (s *UserService) ListLdapUsers(p *ListLdapUsersParams) (*ListLdapUsersRespo if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -1226,6 +1237,7 @@ func (s *UserService) ImportLdapUsers(p *ImportLdapUsersParams) (*ImportLdapUser if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } diff --git a/vendor/github.com/xanzy/go-cloudstack/cloudstack/VLANService.go b/vendor/github.com/xanzy/go-cloudstack/cloudstack/VLANService.go index 0809b6dae..7c9b63795 100644 --- a/vendor/github.com/xanzy/go-cloudstack/cloudstack/VLANService.go +++ b/vendor/github.com/xanzy/go-cloudstack/cloudstack/VLANService.go @@ -243,6 +243,7 @@ func (s *VLANService) CreateVlanIpRange(p *CreateVlanIpRangeParams) (*CreateVlan if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -314,6 +315,7 @@ func (s *VLANService) DeleteVlanIpRange(p *DeleteVlanIpRangeParams) (*DeleteVlan if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -532,6 +534,7 @@ func (s *VLANService) ListVlanIpRanges(p *ListVlanIpRangesParams) (*ListVlanIpRa if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -655,6 +658,7 @@ func (s *VLANService) DedicateGuestVlanRange(p *DedicateGuestVlanRangeParams) (* if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -728,6 +732,7 @@ func (s *VLANService) ReleaseDedicatedGuestVlanRange(p *ReleaseDedicatedGuestVla return nil, err } } + return &r, nil } @@ -913,6 +918,7 @@ func (s *VLANService) ListDedicatedGuestVlanRanges(p *ListDedicatedGuestVlanRang if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } diff --git a/vendor/github.com/xanzy/go-cloudstack/cloudstack/VMGroupService.go b/vendor/github.com/xanzy/go-cloudstack/cloudstack/VMGroupService.go index d66768447..3e97bba64 100644 --- a/vendor/github.com/xanzy/go-cloudstack/cloudstack/VMGroupService.go +++ b/vendor/github.com/xanzy/go-cloudstack/cloudstack/VMGroupService.go @@ -100,6 +100,7 @@ func (s *VMGroupService) CreateInstanceGroup(p *CreateInstanceGroupParams) (*Cre if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -157,6 +158,7 @@ func (s *VMGroupService) DeleteInstanceGroup(p *DeleteInstanceGroupParams) (*Del if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -219,6 +221,7 @@ func (s *VMGroupService) UpdateInstanceGroup(p *UpdateInstanceGroupParams) (*Upd if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -461,6 +464,7 @@ func (s *VMGroupService) ListInstanceGroups(p *ListInstanceGroupsParams) (*ListI if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } diff --git a/vendor/github.com/xanzy/go-cloudstack/cloudstack/VPCService.go b/vendor/github.com/xanzy/go-cloudstack/cloudstack/VPCService.go index 86d8a5948..d2f735485 100644 --- a/vendor/github.com/xanzy/go-cloudstack/cloudstack/VPCService.go +++ b/vendor/github.com/xanzy/go-cloudstack/cloudstack/VPCService.go @@ -203,6 +203,7 @@ func (s *VPCService) CreateVPC(p *CreateVPCParams) (*CreateVPCResponse, error) { return nil, err } } + return &r, nil } @@ -671,6 +672,7 @@ func (s *VPCService) ListVPCs(p *ListVPCsParams) (*ListVPCsResponse, error) { if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -866,6 +868,7 @@ func (s *VPCService) DeleteVPC(p *DeleteVPCParams) (*DeleteVPCResponse, error) { return nil, err } } + return &r, nil } @@ -983,6 +986,7 @@ func (s *VPCService) UpdateVPC(p *UpdateVPCParams) (*UpdateVPCResponse, error) { return nil, err } } + return &r, nil } @@ -1203,6 +1207,7 @@ func (s *VPCService) RestartVPC(p *RestartVPCParams) (*RestartVPCResponse, error return nil, err } } + return &r, nil } @@ -1467,6 +1472,7 @@ func (s *VPCService) CreateVPCOffering(p *CreateVPCOfferingParams) (*CreateVPCOf return nil, err } } + return &r, nil } @@ -1595,6 +1601,7 @@ func (s *VPCService) UpdateVPCOffering(p *UpdateVPCOfferingParams) (*UpdateVPCOf return nil, err } } + return &r, nil } @@ -1685,6 +1692,7 @@ func (s *VPCService) DeleteVPCOffering(p *DeleteVPCOfferingParams) (*DeleteVPCOf return nil, err } } + return &r, nil } @@ -1911,6 +1919,7 @@ func (s *VPCService) ListVPCOfferings(p *ListVPCOfferingsParams) (*ListVPCOfferi if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -2103,6 +2112,7 @@ func (s *VPCService) CreatePrivateGateway(p *CreatePrivateGatewayParams) (*Creat return nil, err } } + return &r, nil } @@ -2338,6 +2348,7 @@ func (s *VPCService) ListPrivateGateways(p *ListPrivateGatewaysParams) (*ListPri if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -2424,6 +2435,7 @@ func (s *VPCService) DeletePrivateGateway(p *DeletePrivateGatewayParams) (*Delet return nil, err } } + return &r, nil } @@ -2508,6 +2520,7 @@ func (s *VPCService) CreateStaticRoute(p *CreateStaticRouteParams) (*CreateStati return nil, err } } + return &r, nil } @@ -2595,6 +2608,7 @@ func (s *VPCService) DeleteStaticRoute(p *DeleteStaticRouteParams) (*DeleteStati return nil, err } } + return &r, nil } @@ -2809,6 +2823,7 @@ func (s *VPCService) ListStaticRoutes(p *ListStaticRoutesParams) (*ListStaticRou if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } diff --git a/vendor/github.com/xanzy/go-cloudstack/cloudstack/VPNService.go b/vendor/github.com/xanzy/go-cloudstack/cloudstack/VPNService.go index 544b17324..94962c6bd 100644 --- a/vendor/github.com/xanzy/go-cloudstack/cloudstack/VPNService.go +++ b/vendor/github.com/xanzy/go-cloudstack/cloudstack/VPNService.go @@ -144,6 +144,7 @@ func (s *VPNService) CreateRemoteAccessVpn(p *CreateRemoteAccessVpnParams) (*Cre return nil, err } } + return &r, nil } @@ -221,6 +222,7 @@ func (s *VPNService) DeleteRemoteAccessVpn(p *DeleteRemoteAccessVpnParams) (*Del return nil, err } } + return &r, nil } @@ -431,6 +433,7 @@ func (s *VPNService) ListRemoteAccessVpns(p *ListRemoteAccessVpnsParams) (*ListR if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -540,6 +543,7 @@ func (s *VPNService) UpdateRemoteAccessVpn(p *UpdateRemoteAccessVpnParams) (*Upd return nil, err } } + return &r, nil } @@ -667,6 +671,7 @@ func (s *VPNService) AddVpnUser(p *AddVpnUserParams) (*AddVpnUserResponse, error return nil, err } } + return &r, nil } @@ -773,6 +778,7 @@ func (s *VPNService) RemoveVpnUser(p *RemoveVpnUserParams) (*RemoveVpnUserRespon return nil, err } } + return &r, nil } @@ -960,6 +966,7 @@ func (s *VPNService) ListVpnUsers(p *ListVpnUsersParams) (*ListVpnUsersResponse, if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -1182,6 +1189,7 @@ func (s *VPNService) CreateVpnCustomerGateway(p *CreateVpnCustomerGatewayParams) return nil, err } } + return &r, nil } @@ -1282,6 +1290,7 @@ func (s *VPNService) CreateVpnGateway(p *CreateVpnGatewayParams) (*CreateVpnGate return nil, err } } + return &r, nil } @@ -1398,6 +1407,7 @@ func (s *VPNService) CreateVpnConnection(p *CreateVpnConnectionParams) (*CreateV return nil, err } } + return &r, nil } @@ -1486,6 +1496,7 @@ func (s *VPNService) DeleteVpnCustomerGateway(p *DeleteVpnCustomerGatewayParams) return nil, err } } + return &r, nil } @@ -1553,6 +1564,7 @@ func (s *VPNService) DeleteVpnGateway(p *DeleteVpnGatewayParams) (*DeleteVpnGate return nil, err } } + return &r, nil } @@ -1620,6 +1632,7 @@ func (s *VPNService) DeleteVpnConnection(p *DeleteVpnConnectionParams) (*DeleteV return nil, err } } + return &r, nil } @@ -1833,6 +1846,7 @@ func (s *VPNService) UpdateVpnCustomerGateway(p *UpdateVpnCustomerGatewayParams) return nil, err } } + return &r, nil } @@ -1943,6 +1957,7 @@ func (s *VPNService) ResetVpnConnection(p *ResetVpnConnectionParams) (*ResetVpnC return nil, err } } + return &r, nil } @@ -2190,6 +2205,7 @@ func (s *VPNService) ListVpnCustomerGateways(p *ListVpnCustomerGatewaysParams) ( if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -2409,6 +2425,7 @@ func (s *VPNService) ListVpnGateways(p *ListVpnGatewaysParams) (*ListVpnGateways if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -2620,6 +2637,7 @@ func (s *VPNService) ListVpnConnections(p *ListVpnConnectionsParams) (*ListVpnCo if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -2740,6 +2758,7 @@ func (s *VPNService) UpdateVpnConnection(p *UpdateVpnConnectionParams) (*UpdateV return nil, err } } + return &r, nil } @@ -2856,6 +2875,7 @@ func (s *VPNService) UpdateVpnGateway(p *UpdateVpnGatewayParams) (*UpdateVpnGate return nil, err } } + return &r, nil } diff --git a/vendor/github.com/xanzy/go-cloudstack/cloudstack/VirtualMachineService.go b/vendor/github.com/xanzy/go-cloudstack/cloudstack/VirtualMachineService.go index 8be3066f4..e0149dc6a 100644 --- a/vendor/github.com/xanzy/go-cloudstack/cloudstack/VirtualMachineService.go +++ b/vendor/github.com/xanzy/go-cloudstack/cloudstack/VirtualMachineService.go @@ -427,6 +427,7 @@ func (s *VirtualMachineService) DeployVirtualMachine(p *DeployVirtualMachinePara return nil, err } } + return &r, nil } @@ -682,6 +683,7 @@ func (s *VirtualMachineService) DestroyVirtualMachine(p *DestroyVirtualMachinePa return nil, err } } + return &r, nil } @@ -925,6 +927,7 @@ func (s *VirtualMachineService) RebootVirtualMachine(p *RebootVirtualMachinePara return nil, err } } + return &r, nil } @@ -1190,6 +1193,7 @@ func (s *VirtualMachineService) StartVirtualMachine(p *StartVirtualMachineParams return nil, err } } + return &r, nil } @@ -1445,6 +1449,7 @@ func (s *VirtualMachineService) StopVirtualMachine(p *StopVirtualMachineParams) return nil, err } } + return &r, nil } @@ -1688,6 +1693,7 @@ func (s *VirtualMachineService) ResetPasswordForVirtualMachine(p *ResetPasswordF return nil, err } } + return &r, nil } @@ -2040,6 +2046,7 @@ func (s *VirtualMachineService) UpdateVirtualMachine(p *UpdateVirtualMachinePara if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -2685,6 +2692,7 @@ func (s *VirtualMachineService) ListVirtualMachines(p *ListVirtualMachinesParams if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -2912,6 +2920,7 @@ func (s *VirtualMachineService) GetVMPassword(p *GetVMPasswordParams) (*GetVMPas if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -2993,6 +3002,7 @@ func (s *VirtualMachineService) RestoreVirtualMachine(p *RestoreVirtualMachinePa return nil, err } } + return &r, nil } @@ -3244,6 +3254,7 @@ func (s *VirtualMachineService) ChangeServiceForVirtualMachine(p *ChangeServiceF if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -3509,6 +3520,7 @@ func (s *VirtualMachineService) ScaleVirtualMachine(p *ScaleVirtualMachineParams return nil, err } } + return &r, nil } @@ -3609,6 +3621,7 @@ func (s *VirtualMachineService) AssignVirtualMachine(p *AssignVirtualMachinePara if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -3873,6 +3886,7 @@ func (s *VirtualMachineService) MigrateVirtualMachine(p *MigrateVirtualMachinePa return nil, err } } + return &r, nil } @@ -4144,6 +4158,7 @@ func (s *VirtualMachineService) MigrateVirtualMachineWithVolume(p *MigrateVirtua return nil, err } } + return &r, nil } @@ -4367,6 +4382,7 @@ func (s *VirtualMachineService) RecoverVirtualMachine(p *RecoverVirtualMachinePa if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -4604,6 +4620,7 @@ func (s *VirtualMachineService) ExpungeVirtualMachine(p *ExpungeVirtualMachinePa return nil, err } } + return &r, nil } @@ -4659,6 +4676,7 @@ func (s *VirtualMachineService) CleanVMReservations(p *CleanVMReservationsParams return nil, err } } + return &r, nil } @@ -4754,6 +4772,7 @@ func (s *VirtualMachineService) AddNicToVirtualMachine(p *AddNicToVirtualMachine return nil, err } } + return &r, nil } @@ -5009,6 +5028,7 @@ func (s *VirtualMachineService) RemoveNicFromVirtualMachine(p *RemoveNicFromVirt return nil, err } } + return &r, nil } @@ -5264,6 +5284,7 @@ func (s *VirtualMachineService) UpdateDefaultNicForVirtualMachine(p *UpdateDefau return nil, err } } + return &r, nil } diff --git a/vendor/github.com/xanzy/go-cloudstack/cloudstack/VolumeService.go b/vendor/github.com/xanzy/go-cloudstack/cloudstack/VolumeService.go index 5b18eb4a5..6eb10f071 100644 --- a/vendor/github.com/xanzy/go-cloudstack/cloudstack/VolumeService.go +++ b/vendor/github.com/xanzy/go-cloudstack/cloudstack/VolumeService.go @@ -111,6 +111,7 @@ func (s *VolumeService) AttachVolume(p *AttachVolumeParams) (*AttachVolumeRespon return nil, err } } + return &r, nil } @@ -345,6 +346,7 @@ func (s *VolumeService) UploadVolume(p *UploadVolumeParams) (*UploadVolumeRespon return nil, err } } + return &r, nil } @@ -499,6 +501,7 @@ func (s *VolumeService) DetachVolume(p *DetachVolumeParams) (*DetachVolumeRespon return nil, err } } + return &r, nil } @@ -766,6 +769,7 @@ func (s *VolumeService) CreateVolume(p *CreateVolumeParams) (*CreateVolumeRespon return nil, err } } + return &r, nil } @@ -878,6 +882,7 @@ func (s *VolumeService) DeleteVolume(p *DeleteVolumeParams) (*DeleteVolumeRespon if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -1219,6 +1224,7 @@ func (s *VolumeService) ListVolumes(p *ListVolumesParams) (*ListVolumesResponse, if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -1390,6 +1396,7 @@ func (s *VolumeService) ExtractVolume(p *ExtractVolumeParams) (*ExtractVolumeRes return nil, err } } + return &r, nil } @@ -1498,6 +1505,7 @@ func (s *VolumeService) MigrateVolume(p *MigrateVolumeParams) (*MigrateVolumeRes return nil, err } } + return &r, nil } @@ -1689,6 +1697,7 @@ func (s *VolumeService) ResizeVolume(p *ResizeVolumeParams) (*ResizeVolumeRespon return nil, err } } + return &r, nil } @@ -1887,6 +1896,7 @@ func (s *VolumeService) UpdateVolume(p *UpdateVolumeParams) (*UpdateVolumeRespon return nil, err } } + return &r, nil } @@ -2011,6 +2021,7 @@ func (s *VolumeService) GetSolidFireVolumeSize(p *GetSolidFireVolumeSizeParams) if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -2073,6 +2084,7 @@ func (s *VolumeService) GetSolidFireVolumeAccessGroupId(p *GetSolidFireVolumeAcc if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -2123,6 +2135,7 @@ func (s *VolumeService) GetSolidFireVolumeIscsiName(p *GetSolidFireVolumeIscsiNa if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -2263,6 +2276,7 @@ func (s *VolumeService) GetUploadParamsForVolume(p *GetUploadParamsForVolumePara if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } diff --git a/vendor/github.com/xanzy/go-cloudstack/cloudstack/ZoneService.go b/vendor/github.com/xanzy/go-cloudstack/cloudstack/ZoneService.go index d02e4dcd7..c64d61856 100644 --- a/vendor/github.com/xanzy/go-cloudstack/cloudstack/ZoneService.go +++ b/vendor/github.com/xanzy/go-cloudstack/cloudstack/ZoneService.go @@ -215,6 +215,7 @@ func (s *ZoneService) CreateZone(p *CreateZoneParams) (*CreateZoneResponse, erro if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -482,6 +483,7 @@ func (s *ZoneService) UpdateZone(p *UpdateZoneParams) (*UpdateZoneResponse, erro if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -576,6 +578,7 @@ func (s *ZoneService) DeleteZone(p *DeleteZoneParams) (*DeleteZoneResponse, erro if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -817,6 +820,7 @@ func (s *ZoneService) ListZones(p *ListZonesParams) (*ListZonesResponse, error) if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } @@ -959,6 +963,7 @@ func (s *ZoneService) DedicateZone(p *DedicateZoneParams) (*DedicateZoneResponse return nil, err } } + return &r, nil } @@ -1030,6 +1035,7 @@ func (s *ZoneService) ReleaseDedicatedZone(p *ReleaseDedicatedZoneParams) (*Rele return nil, err } } + return &r, nil } @@ -1149,6 +1155,7 @@ func (s *ZoneService) ListDedicatedZones(p *ListDedicatedZonesParams) (*ListDedi if err := json.Unmarshal(resp, &r); err != nil { return nil, err } + return &r, nil } diff --git a/vendor/github.com/xanzy/go-gitlab/CHANGELOG.md b/vendor/github.com/xanzy/go-gitlab/CHANGELOG.md new file mode 100644 index 000000000..09cb6db4d --- /dev/null +++ b/vendor/github.com/xanzy/go-gitlab/CHANGELOG.md @@ -0,0 +1,22 @@ +go-github CHANGELOG +=================== + +0.4.0 +----- +- Add support to use [`sudo`](https://docs.gitlab.com/ce/api/README.html#sudo) for all API calls. +- Add support for the Notification Settings API. +- Add support for the Time Tracking API. +- Make sure that the error response correctly outputs any returned errors. +- And a reasonable number of smaller enhanchements and bugfixes. + +0.3.0 +----- +- Moved the tags related API calls to their own service, following the Gitlab API structure. + +0.2.0 +----- +- Convert all Option structs to use pointers for their fields. + +0.1.0 +----- +- Initial release. diff --git a/vendor/github.com/xanzy/go-gitlab/LICENSE b/vendor/github.com/xanzy/go-gitlab/LICENSE new file mode 100644 index 000000000..e06d20818 --- /dev/null +++ b/vendor/github.com/xanzy/go-gitlab/LICENSE @@ -0,0 +1,202 @@ +Apache License + Version 2.0, January 2004 + http://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 + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + 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. + diff --git a/vendor/github.com/xanzy/go-gitlab/README.md b/vendor/github.com/xanzy/go-gitlab/README.md new file mode 100644 index 000000000..7b6d1bcfd --- /dev/null +++ b/vendor/github.com/xanzy/go-gitlab/README.md @@ -0,0 +1,125 @@ +# go-gitlab + +A GitLab API client enabling Go programs to interact with GitLab in a simple and uniform way + +**Documentation:** [![GoDoc](https://godoc.org/github.com/xanzy/go-gitlab?status.svg)](https://godoc.org/github.com/xanzy/go-gitlab) +**Build Status:** [![Build Status](https://travis-ci.org/xanzy/go-gitlab.svg?branch=master)](https://travis-ci.org/xanzy/go-gitlab) + +## NOTE + +Release v0.5.0 (released on 22-03-2017) no longer supports Go versions older +then 1.7.x If you want (or need) to use an older Go version please use v0.4.1 + +## Coverage + +This API client package covers **100%** of the existing GitLab API calls! So this +includes all calls to the following services: + +- [x] Users +- [x] Session +- [x] Projects (including setting Webhooks) +- [x] Project Snippets +- [x] Services +- [x] Repositories +- [x] Repository Files +- [x] Commits +- [x] Branches +- [x] Merge Requests +- [x] Issues +- [x] Labels +- [x] Milestones +- [x] Notes (comments) +- [x] Deploy Keys +- [x] System Hooks +- [x] Groups +- [x] Namespaces +- [x] Settings +- [x] Pipelines + +## Usage + +```go +import "github.com/xanzy/go-gitlab" +``` + +Construct a new GitLab client, then use the various services on the client to +access different parts of the GitLab API. For example, to list all +users: + +```go +git := gitlab.NewClient(nil, "yourtokengoeshere") +//git.SetBaseURL("https://git.mydomain.com/api/v3") +users, _, err := git.Users.ListUsers() +``` + +Some API methods have optional parameters that can be passed. For example, +to list all projects for user "svanharmelen": + +```go +git := gitlab.NewClient(nil) +opt := &ListProjectsOptions{Search: gitlab.String("svanharmelen")}) +projects, _, err := git.Projects.ListProjects(opt) +``` + +### Examples + +The [examples](https://github.com/xanzy/go-gitlab/tree/master/examples) directory +contains a couple for clear examples, of which one is partially listed here as well: + +```go +package main + +import ( + "log" + + "github.com/xanzy/go-gitlab" +) + +func main() { + git := gitlab.NewClient(nil, "yourtokengoeshere") + + // Create new project + p := &gitlab.CreateProjectOptions{ + Name: gitlab.String("My Project"), + Description: gitlab.String("Just a test project to play with"), + MergeRequestsEnabled: gitlab.Bool(true), + SnippetsEnabled: gitlab.Bool(true), + VisibilityLevel: gitlab.VisibilityLevel(gitlab.PublicVisibility), + } + project, _, err := git.Projects.CreateProject(p) + if err != nil { + log.Fatal(err) + } + + // Add a new snippet + s := &gitlab.CreateSnippetOptions{ + Title: gitlab.String("Dummy Snippet"), + FileName: gitlab.String("snippet.go"), + Code: gitlab.String("package main...."), + VisibilityLevel: gitlab.VisibilityLevel(gitlab.PublicVisibility), + } + _, _, err = git.ProjectSnippets.CreateSnippet(project.ID, s) + if err != nil { + log.Fatal(err) + } +} + +``` + +For complete usage of go-gitlab, see the full [package docs](https://godoc.org/github.com/xanzy/go-gitlab). + +## ToDo + +- The biggest thing this package still needs is tests :disappointed: + +## Issues + +- If you have an issue: report it on the [issue tracker](https://github.com/xanzy/go-gitlab/issues) + +## Author + +Sander van Harmelen () + +## License + +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 diff --git a/vendor/github.com/xanzy/go-gitlab/branches.go b/vendor/github.com/xanzy/go-gitlab/branches.go new file mode 100644 index 000000000..adb4c739b --- /dev/null +++ b/vendor/github.com/xanzy/go-gitlab/branches.go @@ -0,0 +1,201 @@ +// +// Copyright 2015, Sander van Harmelen +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +package gitlab + +import ( + "fmt" + "net/url" +) + +// BranchesService handles communication with the branch related methods +// of the GitLab API. +// +// GitLab API docs: https://docs.gitlab.com/ce/api/branches.html +type BranchesService struct { + client *Client +} + +// Branch represents a GitLab branch. +// +// GitLab API docs: https://docs.gitlab.com/ce/api/branches.html +type Branch struct { + Commit *Commit `json:"commit"` + Name string `json:"name"` + Protected bool `json:"protected"` +} + +func (b Branch) String() string { + return Stringify(b) +} + +// ListBranches gets a list of repository branches from a project, sorted by +// name alphabetically. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/branches.html#list-repository-branches +func (s *BranchesService) ListBranches(pid interface{}, options ...OptionFunc) ([]*Branch, *Response, error) { + project, err := parseID(pid) + if err != nil { + return nil, nil, err + } + u := fmt.Sprintf("projects/%s/repository/branches", url.QueryEscape(project)) + + req, err := s.client.NewRequest("GET", u, nil, options) + if err != nil { + return nil, nil, err + } + + var b []*Branch + resp, err := s.client.Do(req, &b) + if err != nil { + return nil, resp, err + } + + return b, resp, err +} + +// GetBranch gets a single project repository branch. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/branches.html#get-single-repository-branch +func (s *BranchesService) GetBranch(pid interface{}, branch string, options ...OptionFunc) (*Branch, *Response, error) { + project, err := parseID(pid) + if err != nil { + return nil, nil, err + } + u := fmt.Sprintf("projects/%s/repository/branches/%s", url.QueryEscape(project), branch) + + req, err := s.client.NewRequest("GET", u, nil, options) + if err != nil { + return nil, nil, err + } + + b := new(Branch) + resp, err := s.client.Do(req, b) + if err != nil { + return nil, resp, err + } + + return b, resp, err +} + +// ProtectBranch protects a single project repository branch. This is an +// idempotent function, protecting an already protected repository branch +// still returns a 200 OK status code. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/branches.html#protect-repository-branch +func (s *BranchesService) ProtectBranch(pid interface{}, branch string, options ...OptionFunc) (*Branch, *Response, error) { + project, err := parseID(pid) + if err != nil { + return nil, nil, err + } + u := fmt.Sprintf("projects/%s/repository/branches/%s/protect", url.QueryEscape(project), branch) + + req, err := s.client.NewRequest("PUT", u, nil, options) + if err != nil { + return nil, nil, err + } + + b := new(Branch) + resp, err := s.client.Do(req, b) + if err != nil { + return nil, resp, err + } + + return b, resp, err +} + +// UnprotectBranch unprotects a single project repository branch. This is an +// idempotent function, unprotecting an already unprotected repository branch +// still returns a 200 OK status code. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/branches.html#unprotect-repository-branch +func (s *BranchesService) UnprotectBranch(pid interface{}, branch string, options ...OptionFunc) (*Branch, *Response, error) { + project, err := parseID(pid) + if err != nil { + return nil, nil, err + } + u := fmt.Sprintf("projects/%s/repository/branches/%s/unprotect", url.QueryEscape(project), branch) + + req, err := s.client.NewRequest("PUT", u, nil, options) + if err != nil { + return nil, nil, err + } + + b := new(Branch) + resp, err := s.client.Do(req, b) + if err != nil { + return nil, resp, err + } + + return b, resp, err +} + +// CreateBranchOptions represents the available CreateBranch() options. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/branches.html#create-repository-branch +type CreateBranchOptions struct { + BranchName *string `url:"branch_name,omitempty" json:"branch_name,omitempty"` + Ref *string `url:"ref,omitempty" json:"ref,omitempty"` +} + +// CreateBranch creates branch from commit SHA or existing branch. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/branches.html#create-repository-branch +func (s *BranchesService) CreateBranch(pid interface{}, opt *CreateBranchOptions, options ...OptionFunc) (*Branch, *Response, error) { + project, err := parseID(pid) + if err != nil { + return nil, nil, err + } + u := fmt.Sprintf("projects/%s/repository/branches", url.QueryEscape(project)) + + req, err := s.client.NewRequest("POST", u, opt, options) + if err != nil { + return nil, nil, err + } + + b := new(Branch) + resp, err := s.client.Do(req, b) + if err != nil { + return nil, resp, err + } + + return b, resp, err +} + +// DeleteBranch deletes an existing branch. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/branches.html#delete-repository-branch +func (s *BranchesService) DeleteBranch(pid interface{}, branch string, options ...OptionFunc) (*Response, error) { + project, err := parseID(pid) + if err != nil { + return nil, err + } + u := fmt.Sprintf("projects/%s/repository/branches/%s", url.QueryEscape(project), branch) + + req, err := s.client.NewRequest("DELETE", u, nil, options) + if err != nil { + return nil, err + } + + return s.client.Do(req, nil) +} diff --git a/vendor/github.com/xanzy/go-gitlab/build_variables.go b/vendor/github.com/xanzy/go-gitlab/build_variables.go new file mode 100644 index 000000000..a1bdf7f65 --- /dev/null +++ b/vendor/github.com/xanzy/go-gitlab/build_variables.go @@ -0,0 +1,146 @@ +package gitlab + +import ( + "fmt" + "net/url" +) + +// BuildVariablesService handles communication with the project variables related methods +// of the Gitlab API +// +// Gitlab API Docs : https://docs.gitlab.com/ce/api/build_variables.html +type BuildVariablesService struct { + client *Client +} + +// BuildVariable represents a variable available for each build of the given project +// +// Gitlab API Docs : https://docs.gitlab.com/ce/api/build_variables.html +type BuildVariable struct { + Key string `json:"key"` + Value string `json:"value"` +} + +func (v BuildVariable) String() string { + return Stringify(v) +} + +// ListBuildVariables gets the a list of project variables in a project +// +// Gitlab API Docs: +// https://docs.gitlab.com/ce/api/build_variables.html#list-project-variables +func (s *BuildVariablesService) ListBuildVariables(pid interface{}, options ...OptionFunc) ([]*BuildVariable, *Response, error) { + project, err := parseID(pid) + if err != nil { + return nil, nil, err + } + u := fmt.Sprintf("projects/%s/variables", url.QueryEscape(project)) + + req, err := s.client.NewRequest("GET", u, nil, options) + if err != nil { + return nil, nil, err + } + + var v []*BuildVariable + resp, err := s.client.Do(req, &v) + if err != nil { + return nil, resp, err + } + + return v, resp, err +} + +// GetBuildVariable gets a single project variable of a project +// +// Gitlab API Docs: +// https://docs.gitlab.com/ce/api/build_variables.html#show-variable-details +func (s *BuildVariablesService) GetBuildVariable(pid interface{}, key string, options ...OptionFunc) (*BuildVariable, *Response, error) { + project, err := parseID(pid) + if err != nil { + return nil, nil, err + } + u := fmt.Sprintf("projects/%s/variables/%s", url.QueryEscape(project), key) + + req, err := s.client.NewRequest("GET", u, nil, options) + if err != nil { + return nil, nil, err + } + + v := new(BuildVariable) + resp, err := s.client.Do(req, v) + if err != nil { + return nil, resp, err + } + + return v, resp, err +} + +// CreateBuildVariable creates a variable for a given project +// +// Gitlab API Docs: +// https://docs.gitlab.com/ce/api/build_variables.html#create-variable +func (s *BuildVariablesService) CreateBuildVariable(pid interface{}, key, value string, options ...OptionFunc) (*BuildVariable, *Response, error) { + project, err := parseID(pid) + if err != nil { + return nil, nil, err + } + u := fmt.Sprintf("projects/%s/variables", url.QueryEscape(project)) + + req, err := s.client.NewRequest("POST", u, BuildVariable{key, value}, options) + if err != nil { + return nil, nil, err + } + + v := new(BuildVariable) + resp, err := s.client.Do(req, v) + if err != nil { + return nil, resp, err + } + + return v, resp, err +} + +// UpdateBuildVariable updates an existing project variable +// The variable key must exist +// +// Gitlab API Docs: +// https://docs.gitlab.com/ce/api/build_variables.html#update-variable +func (s *BuildVariablesService) UpdateBuildVariable(pid interface{}, key, value string, options ...OptionFunc) (*BuildVariable, *Response, error) { + project, err := parseID(pid) + if err != nil { + return nil, nil, err + } + u := fmt.Sprintf("projects/%s/variables/%s", url.QueryEscape(project), key) + + req, err := s.client.NewRequest("PUT", u, BuildVariable{key, value}, options) + if err != nil { + return nil, nil, err + } + + v := new(BuildVariable) + resp, err := s.client.Do(req, v) + if err != nil { + return nil, resp, err + } + + return v, resp, err +} + +// RemoveBuildVariable removes a project variable of a given project identified by its key +// +// Gitlab API Docs: +// https://docs.gitlab.com/ce/api/build_variables.html#remove-variable +func (s *BuildVariablesService) RemoveBuildVariable(pid interface{}, key string, options ...OptionFunc) (*Response, error) { + project, err := parseID(pid) + if err != nil { + return nil, err + } + u := fmt.Sprintf("projects/%s/variables/%s", url.QueryEscape(project), key) + + req, err := s.client.NewRequest("DELETE", u, nil, options) + if err != nil { + return nil, err + } + + return s.client.Do(req, nil) +} diff --git a/vendor/github.com/xanzy/go-gitlab/builds.go b/vendor/github.com/xanzy/go-gitlab/builds.go new file mode 100644 index 000000000..dfee85b32 --- /dev/null +++ b/vendor/github.com/xanzy/go-gitlab/builds.go @@ -0,0 +1,349 @@ +// +// Copyright 2016, Arkbriar +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +package gitlab + +import ( + "bytes" + "fmt" + "io" + "net/url" + "time" +) + +// ListBuildsOptions are options for two list apis +type ListBuildsOptions struct { + ListOptions + Scope []BuildState `url:"scope,omitempty" json:"scope,omitempty"` +} + +// BuildsService handles communication with the ci builds related methods +// of the GitLab API. +// +// GitLab API docs: https://docs.gitlab.com/ce/api/builds.html +type BuildsService struct { + client *Client +} + +// Build represents a ci build. +// +// GitLab API docs: https://docs.gitlab.com/ce/api/builds.html +type Build struct { + Commit *Commit `json:"commit"` + CreatedAt *time.Time `json:"created_at"` + ArtifactsFile struct { + Filename string `json:"filename"` + Size int `json:"size"` + } `json:"artifacts_file"` + FinishedAt *time.Time `json:"finished_at"` + ID int `json:"id"` + Name string `json:"name"` + Ref string `json:"ref"` + Runner struct { + ID int `json:"id"` + Description string `json:"description"` + Active bool `json:"active"` + IsShared bool `json:"is_shared"` + Name string `json:"name"` + } `json:"runner"` + Stage string `json:"stage"` + StartedAt *time.Time `json:"started_at"` + Status string `json:"status"` + Tag bool `json:"tag"` + User *User `json:"user"` +} + +// ListProjectBuilds gets a list of builds in a project. +// +// The scope of builds to show, one or array of: pending, running, +// failed, success, canceled; showing all builds if none provided. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/builds.html#list-project-builds +func (s *BuildsService) ListProjectBuilds(pid interface{}, opts *ListBuildsOptions, options ...OptionFunc) ([]Build, *Response, error) { + project, err := parseID(pid) + if err != nil { + return nil, nil, err + } + u := fmt.Sprintf("projects/%s/builds", url.QueryEscape(project)) + + req, err := s.client.NewRequest("GET", u, opts, options) + if err != nil { + return nil, nil, err + } + + var builds []Build + resp, err := s.client.Do(req, &builds) + if err != nil { + return nil, resp, err + } + + return builds, resp, err +} + +// ListCommitBuilds gets a list of builds for specific commit in a +// project. If the commit SHA is not found, it will respond with 404. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/builds.html#list-commit-builds +func (s *BuildsService) ListCommitBuilds(pid interface{}, sha string, opts *ListBuildsOptions, options ...OptionFunc) ([]Build, *Response, error) { + project, err := parseID(pid) + if err != nil { + return nil, nil, err + } + u := fmt.Sprintf("projects/%s/repository/commits/%s/builds", project, sha) + + req, err := s.client.NewRequest("GET", u, opts, options) + if err != nil { + return nil, nil, err + } + + var builds []Build + resp, err := s.client.Do(req, &builds) + if err != nil { + return nil, resp, err + } + + return builds, resp, err +} + +// GetBuild gets a single build of a project. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/builds.html#get-a-single-build +func (s *BuildsService) GetBuild(pid interface{}, buildID int, options ...OptionFunc) (*Build, *Response, error) { + project, err := parseID(pid) + if err != nil { + return nil, nil, err + } + u := fmt.Sprintf("projects/%s/builds/%d", project, buildID) + + req, err := s.client.NewRequest("GET", u, nil, options) + if err != nil { + return nil, nil, err + } + + build := new(Build) + resp, err := s.client.Do(req, build) + if err != nil { + return nil, resp, err + } + + return build, resp, err +} + +// GetBuildArtifacts get builds artifacts of a project +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/builds.html#get-build-artifacts +func (s *BuildsService) GetBuildArtifacts(pid interface{}, buildID int, options ...OptionFunc) (io.Reader, *Response, error) { + project, err := parseID(pid) + if err != nil { + return nil, nil, err + } + u := fmt.Sprintf("projects/%s/builds/%d/artifacts", project, buildID) + + req, err := s.client.NewRequest("GET", u, nil, options) + if err != nil { + return nil, nil, err + } + + artifactsBuf := new(bytes.Buffer) + resp, err := s.client.Do(req, artifactsBuf) + if err != nil { + return nil, resp, err + } + + return artifactsBuf, resp, err +} + +// DownloadArtifactsFile download the artifacts file from the given +// reference name and job provided the build finished successfully. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/builds.html#download-the-artifacts-file +func (s *BuildsService) DownloadArtifactsFile(pid interface{}, refName string, job string, options ...OptionFunc) (io.Reader, *Response, error) { + project, err := parseID(pid) + if err != nil { + return nil, nil, err + } + u := fmt.Sprintf("projects/%s/builds/artifacts/%s/download?job=%s", project, refName, job) + + req, err := s.client.NewRequest("GET", u, nil, options) + if err != nil { + return nil, nil, err + } + + artifactsBuf := new(bytes.Buffer) + resp, err := s.client.Do(req, artifactsBuf) + if err != nil { + return nil, resp, err + } + + return artifactsBuf, resp, err +} + +// GetTraceFile gets a trace of a specific build of a project +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/builds.html#get-a-trace-file +func (s *BuildsService) GetTraceFile(pid interface{}, buildID int, options ...OptionFunc) (io.Reader, *Response, error) { + project, err := parseID(pid) + if err != nil { + return nil, nil, err + } + u := fmt.Sprintf("projects/%s/builds/%d/trace", project, buildID) + + req, err := s.client.NewRequest("GET", u, nil, options) + if err != nil { + return nil, nil, err + } + + traceBuf := new(bytes.Buffer) + resp, err := s.client.Do(req, traceBuf) + if err != nil { + return nil, resp, err + } + + return traceBuf, resp, err +} + +// CancelBuild cancels a single build of a project. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/builds.html#cancel-a-build +func (s *BuildsService) CancelBuild(pid interface{}, buildID int, options ...OptionFunc) (*Build, *Response, error) { + project, err := parseID(pid) + if err != nil { + return nil, nil, err + } + u := fmt.Sprintf("projects/%s/builds/%d/cancel", project, buildID) + + req, err := s.client.NewRequest("POST", u, nil, options) + if err != nil { + return nil, nil, err + } + + build := new(Build) + resp, err := s.client.Do(req, build) + if err != nil { + return nil, resp, err + } + + return build, resp, err +} + +// RetryBuild retries a single build of a project +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/builds.html#retry-a-build +func (s *BuildsService) RetryBuild(pid interface{}, buildID int, options ...OptionFunc) (*Build, *Response, error) { + project, err := parseID(pid) + if err != nil { + return nil, nil, err + } + u := fmt.Sprintf("projects/%s/builds/%d/retry", project, buildID) + + req, err := s.client.NewRequest("POST", u, nil, options) + if err != nil { + return nil, nil, err + } + + build := new(Build) + resp, err := s.client.Do(req, build) + if err != nil { + return nil, resp, err + } + + return build, resp, err +} + +// EraseBuild erases a single build of a project, removes a build +// artifacts and a build trace. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/builds.html#erase-a-build +func (s *BuildsService) EraseBuild(pid interface{}, buildID int, options ...OptionFunc) (*Build, *Response, error) { + project, err := parseID(pid) + if err != nil { + return nil, nil, err + } + u := fmt.Sprintf("projects/%s/builds/%d/erase", project, buildID) + + req, err := s.client.NewRequest("POST", u, nil, options) + if err != nil { + return nil, nil, err + } + + build := new(Build) + resp, err := s.client.Do(req, build) + if err != nil { + return nil, resp, err + } + + return build, resp, err +} + +// KeepArtifacts prevents artifacts from being deleted when +// expiration is set. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/builds.html#keep-artifacts +func (s *BuildsService) KeepArtifacts(pid interface{}, buildID int, options ...OptionFunc) (*Build, *Response, error) { + project, err := parseID(pid) + if err != nil { + return nil, nil, err + } + u := fmt.Sprintf("projects/%s/builds/%d/artifacts/keep", project, buildID) + + req, err := s.client.NewRequest("POST", u, nil, options) + if err != nil { + return nil, nil, err + } + + build := new(Build) + resp, err := s.client.Do(req, build) + if err != nil { + return nil, resp, err + } + + return build, resp, err +} + +// PlayBuild triggers a nanual action to start a build. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/builds.html#play-a-build +func (s *BuildsService) PlayBuild(pid interface{}, buildID int, options ...OptionFunc) (*Build, *Response, error) { + project, err := parseID(pid) + if err != nil { + return nil, nil, err + } + u := fmt.Sprintf("projects/%s/builds/%d/play", project, buildID) + + req, err := s.client.NewRequest("POST", u, nil, options) + if err != nil { + return nil, nil, err + } + + build := new(Build) + resp, err := s.client.Do(req, build) + if err != nil { + return nil, resp, err + } + + return build, resp, err +} diff --git a/vendor/github.com/xanzy/go-gitlab/commits.go b/vendor/github.com/xanzy/go-gitlab/commits.go new file mode 100644 index 000000000..7aa642c52 --- /dev/null +++ b/vendor/github.com/xanzy/go-gitlab/commits.go @@ -0,0 +1,444 @@ +// +// Copyright 2015, Sander van Harmelen +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +package gitlab + +import ( + "fmt" + "net/url" + "time" +) + +// CommitsService handles communication with the commit related methods +// of the GitLab API. +// +// GitLab API docs: https://docs.gitlab.com/ce/api/commits.html +type CommitsService struct { + client *Client +} + +// Commit represents a GitLab commit. +// +// GitLab API docs: https://docs.gitlab.com/ce/api/commits.html +type Commit struct { + ID string `json:"id"` + ShortID string `json:"short_id"` + Title string `json:"title"` + AuthorName string `json:"author_name"` + AuthorEmail string `json:"author_email"` + AuthoredDate *time.Time `json:"authored_date"` + CommitterName string `json:"committer_name"` + CommitterEmail string `json:"committer_email"` + CommittedDate *time.Time `json:"committed_date"` + CreatedAt *time.Time `json:"created_at"` + Message string `json:"message"` + ParentIDs []string `json:"parent_ids"` + Stats *CommitStats `json:"stats"` + Status *BuildState `json:"status"` +} + +// CommitStats represents the number of added and deleted files in a commit. +// +// GitLab API docs: https://docs.gitlab.com/ce/api/commits.html +type CommitStats struct { + Additions int `json:"additions"` + Deletions int `json:"deletions"` + Total int `json:"total"` +} + +func (c Commit) String() string { + return Stringify(c) +} + +// ListCommitsOptions represents the available ListCommits() options. +// +// GitLab API docs: https://docs.gitlab.com/ce/api/commits.html#list-repository-commits +type ListCommitsOptions struct { + ListOptions + RefName *string `url:"ref_name,omitempty" json:"ref_name,omitempty"` + Since time.Time `url:"since,omitempty" json:"since,omitempty"` + Until time.Time `url:"until,omitempty" json:"until,omitempty"` +} + +// ListCommits gets a list of repository commits in a project. +// +// GitLab API docs: https://docs.gitlab.com/ce/api/commits.html#list-commits +func (s *CommitsService) ListCommits(pid interface{}, opt *ListCommitsOptions, options ...OptionFunc) ([]*Commit, *Response, error) { + project, err := parseID(pid) + if err != nil { + return nil, nil, err + } + u := fmt.Sprintf("projects/%s/repository/commits", url.QueryEscape(project)) + + req, err := s.client.NewRequest("GET", u, opt, options) + if err != nil { + return nil, nil, err + } + + var c []*Commit + resp, err := s.client.Do(req, &c) + if err != nil { + return nil, resp, err + } + + return c, resp, err +} + +// FileAction represents the available actions that can be performed on a file. +// +// GitLab API docs: https://docs.gitlab.com/ce/api/commits.html#create-a-commit-with-multiple-files-and-actions +type FileAction string + +// The available file actions. +const ( + FileCreate FileAction = "create" + FileDelete FileAction = "delete" + FileMove FileAction = "move" + FileUpdate FileAction = "update" +) + +// CommitAction represents a single file action within a commit. +type CommitAction struct { + Action FileAction `url:"action" json:"action,omitempty"` + FilePath string `url:"file_path" json:"file_path,omitempty"` + PreviousPath string `url:"previous_path,omitempty" json:"previous_path,omitempty"` + Content string `url:"content,omitempty" json:"content,omitempty"` + Encoding string `url:"encoding,omitempty" json:"encoding,omitempty"` +} + +// CreateCommitOptions represents the available options for a new commit. +// +// GitLab API docs: https://docs.gitlab.com/ce/api/commits.html#create-a-commit-with-multiple-files-and-actions +type CreateCommitOptions struct { + BranchName *string `url:"branch_name" json:"branch_name,omitempty"` + CommitMessage *string `url:"commit_message" json:"commit_message,omitempty"` + Actions []*CommitAction `url:"actions" json:"actions,omitempty"` + AuthorEmail *string `url:"author_email,omitempty" json:"author_email,omitempty"` + AuthorName *string `url:"author_name,omitempty" json:"author_name,omitempty"` +} + +// CreateCommit creates a commit with multiple files and actions. +// +// GitLab API docs: https://docs.gitlab.com/ce/api/commits.html#create-a-commit-with-multiple-files-and-actions +func (s *CommitsService) CreateCommit(pid interface{}, opt *CreateCommitOptions, options ...OptionFunc) (*Commit, *Response, error) { + project, err := parseID(pid) + if err != nil { + return nil, nil, err + } + u := fmt.Sprintf("projects/%s/repository/commits", url.QueryEscape(project)) + + req, err := s.client.NewRequest("POST", u, opt, options) + if err != nil { + return nil, nil, err + } + + var c *Commit + resp, err := s.client.Do(req, &c) + if err != nil { + return nil, resp, err + } + + return c, resp, err +} + +// GetCommit gets a specific commit identified by the commit hash or name of a +// branch or tag. +// +// GitLab API docs: https://docs.gitlab.com/ce/api/commits.html#get-a-single-commit +func (s *CommitsService) GetCommit(pid interface{}, sha string, options ...OptionFunc) (*Commit, *Response, error) { + project, err := parseID(pid) + if err != nil { + return nil, nil, err + } + u := fmt.Sprintf("projects/%s/repository/commits/%s", url.QueryEscape(project), sha) + + req, err := s.client.NewRequest("GET", u, nil, options) + if err != nil { + return nil, nil, err + } + + c := new(Commit) + resp, err := s.client.Do(req, c) + if err != nil { + return nil, resp, err + } + + return c, resp, err +} + +// Diff represents a GitLab diff. +// +// GitLab API docs: https://docs.gitlab.com/ce/api/commits.html +type Diff struct { + Diff string `json:"diff"` + NewPath string `json:"new_path"` + OldPath string `json:"old_path"` + AMode string `json:"a_mode"` + BMode string `json:"b_mode"` + NewFile bool `json:"new_file"` + RenamedFile bool `json:"renamed_file"` + DeletedFile bool `json:"deleted_file"` +} + +func (d Diff) String() string { + return Stringify(d) +} + +// GetCommitDiff gets the diff of a commit in a project.. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/commits.html#get-the-diff-of-a-commit +func (s *CommitsService) GetCommitDiff(pid interface{}, sha string, options ...OptionFunc) ([]*Diff, *Response, error) { + project, err := parseID(pid) + if err != nil { + return nil, nil, err + } + u := fmt.Sprintf("projects/%s/repository/commits/%s/diff", url.QueryEscape(project), sha) + + req, err := s.client.NewRequest("GET", u, nil, options) + if err != nil { + return nil, nil, err + } + + var d []*Diff + resp, err := s.client.Do(req, &d) + if err != nil { + return nil, resp, err + } + + return d, resp, err +} + +// CommitComment represents a GitLab commit comment. +// +// GitLab API docs: https://docs.gitlab.com/ce/api/commits.html +type CommitComment struct { + Note string `json:"note"` + Path string `json:"path"` + Line int `json:"line"` + LineType string `json:"line_type"` + Author Author `json:"author"` +} + +// Author represents a GitLab commit author +type Author struct { + ID int `json:"id"` + Username string `json:"username"` + Email string `json:"email"` + Name string `json:"name"` + State string `json:"state"` + Blocked bool `json:"blocked"` + CreatedAt *time.Time `json:"created_at"` +} + +func (c CommitComment) String() string { + return Stringify(c) +} + +// GetCommitComments gets the comments of a commit in a project. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/commits.html#get-the-comments-of-a-commit +func (s *CommitsService) GetCommitComments(pid interface{}, sha string, options ...OptionFunc) ([]*CommitComment, *Response, error) { + project, err := parseID(pid) + if err != nil { + return nil, nil, err + } + u := fmt.Sprintf("projects/%s/repository/commits/%s/comments", url.QueryEscape(project), sha) + + req, err := s.client.NewRequest("GET", u, nil, options) + if err != nil { + return nil, nil, err + } + + var c []*CommitComment + resp, err := s.client.Do(req, &c) + if err != nil { + return nil, resp, err + } + + return c, resp, err +} + +// PostCommitCommentOptions represents the available PostCommitComment() +// options. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/commits.html#post-comment-to-commit +type PostCommitCommentOptions struct { + Note *string `url:"note,omitempty" json:"note,omitempty"` + Path *string `url:"path" json:"path"` + Line *int `url:"line" json:"line"` + LineType *string `url:"line_type" json:"line_type"` +} + +// PostCommitComment adds a comment to a commit. Optionally you can post +// comments on a specific line of a commit. Therefor both path, line_new and +// line_old are required. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/commits.html#post-comment-to-commit +func (s *CommitsService) PostCommitComment(pid interface{}, sha string, opt *PostCommitCommentOptions, options ...OptionFunc) (*CommitComment, *Response, error) { + project, err := parseID(pid) + if err != nil { + return nil, nil, err + } + u := fmt.Sprintf("projects/%s/repository/commits/%s/comments", url.QueryEscape(project), sha) + + req, err := s.client.NewRequest("POST", u, opt, options) + if err != nil { + return nil, nil, err + } + + c := new(CommitComment) + resp, err := s.client.Do(req, c) + if err != nil { + return nil, resp, err + } + + return c, resp, err +} + +// GetCommitStatusesOptions represents the available GetCommitStatuses() options. +// +// GitLab API docs: https://docs.gitlab.com/ce/api/commits.html#get-the-status-of-a-commit +type GetCommitStatusesOptions struct { + Ref *string `url:"ref,omitempty" json:"ref,omitempty"` + Stage *string `url:"stage,omitempty" json:"stage,omitempty"` + Name *string `url:"name,omitempty" json:"name,omitempty"` + All *bool `url:"all,omitempty" json:"all,omitempty"` +} + +// CommitStatus represents a GitLab commit status. +// +// GitLab API docs: https://docs.gitlab.com/ce/api/commits.html#get-the-status-of-a-commit +type CommitStatus struct { + ID int `json:"id"` + SHA string `json:"sha"` + Ref string `json:"ref"` + Status string `json:"status"` + Name string `json:"name"` + TargetURL string `json:"target_url"` + Description string `json:"description"` + CreatedAt *time.Time `json:"created_at"` + StartedAt *time.Time `json:"started_at"` + FinishedAt *time.Time `json:"finished_at"` + Author Author `json:"author"` +} + +// GetCommitStatuses gets the statuses of a commit in a project. +// +// GitLab API docs: https://docs.gitlab.com/ce/api/commits.html#get-the-status-of-a-commit +func (s *CommitsService) GetCommitStatuses(pid interface{}, sha string, opt *GetCommitStatusesOptions, options ...OptionFunc) ([]*CommitStatus, *Response, error) { + project, err := parseID(pid) + if err != nil { + return nil, nil, err + } + u := fmt.Sprintf("projects/%s/repository/commits/%s/statuses", url.QueryEscape(project), sha) + + req, err := s.client.NewRequest("GET", u, opt, options) + if err != nil { + return nil, nil, err + } + + var cs []*CommitStatus + resp, err := s.client.Do(req, &cs) + if err != nil { + return nil, resp, err + } + + return cs, resp, err +} + +// SetCommitStatusOptions represents the available SetCommitStatus() options. +// +// GitLab API docs: https://docs.gitlab.com/ce/api/commits.html#post-the-status-to-commit +type SetCommitStatusOptions struct { + State BuildState `url:"state" json:"state"` + Ref *string `url:"ref,omitempty" json:"ref,omitempty"` + Name *string `url:"name,omitempty" json:"name,omitempty"` + Context *string `url:"context,omitempty" json:"context,omitempty"` + TargetURL *string `url:"target_url,omitempty" json:"target_url,omitempty"` + Description *string `url:"description,omitempty" json:"description,omitempty"` +} + +// BuildState represents a GitLab build state. +type BuildState string + +// These constants represent all valid build states. +const ( + Pending BuildState = "pending" + Running BuildState = "running" + Success BuildState = "success" + Failed BuildState = "failed" + Canceled BuildState = "canceled" +) + +// SetCommitStatus sets the status of a commit in a project. +// +// GitLab API docs: https://docs.gitlab.com/ce/api/commits.html#post-the-status-to-commit +func (s *CommitsService) SetCommitStatus(pid interface{}, sha string, opt *SetCommitStatusOptions, options ...OptionFunc) (*CommitStatus, *Response, error) { + project, err := parseID(pid) + if err != nil { + return nil, nil, err + } + u := fmt.Sprintf("projects/%s/statuses/%s", url.QueryEscape(project), sha) + + req, err := s.client.NewRequest("POST", u, opt, options) + if err != nil { + return nil, nil, err + } + + var cs *CommitStatus + resp, err := s.client.Do(req, &cs) + if err != nil { + return nil, resp, err + } + + return cs, resp, err +} + +// CherryPickCommitOptions represents the available options for cherry-picking a commit. +// +// GitLab API docs: https://docs.gitlab.com/ce/api/commits.html#cherry-pick-a-commit +type CherryPickCommitOptions struct { + TargetBranch *string `url:"branch" json:"branch,omitempty"` +} + +// CherryPickCommit sherry picks a commit to a given branch. +// +// GitLab API docs: https://docs.gitlab.com/ce/api/commits.html#cherry-pick-a-commit +func (s *CommitsService) CherryPickCommit(pid interface{}, sha string, opt *CherryPickCommitOptions, options ...OptionFunc) (*Commit, *Response, error) { + project, err := parseID(pid) + if err != nil { + return nil, nil, err + } + u := fmt.Sprintf("projects/%s/repository/commits/%s/cherry_pick", + url.QueryEscape(project), url.QueryEscape(sha)) + + req, err := s.client.NewRequest("POST", u, opt, options) + if err != nil { + return nil, nil, err + } + + var c *Commit + resp, err := s.client.Do(req, &c) + if err != nil { + return nil, resp, err + } + + return c, resp, err +} diff --git a/vendor/github.com/xanzy/go-gitlab/deploy_keys.go b/vendor/github.com/xanzy/go-gitlab/deploy_keys.go new file mode 100644 index 000000000..1e9eae857 --- /dev/null +++ b/vendor/github.com/xanzy/go-gitlab/deploy_keys.go @@ -0,0 +1,150 @@ +// +// Copyright 2015, Sander van Harmelen +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +package gitlab + +import ( + "fmt" + "net/url" + "time" +) + +// DeployKeysService handles communication with the keys related methods +// of the GitLab API. +// +// GitLab API docs: https://docs.gitlab.com/ce/api/deploy_keys.html +type DeployKeysService struct { + client *Client +} + +// DeployKey represents a GitLab deploy key. +type DeployKey struct { + ID int `json:"id"` + Title string `json:"title"` + Key string `json:"key"` + CanPush *bool `json:"can_push"` + CreatedAt *time.Time `json:"created_at"` +} + +func (k DeployKey) String() string { + return Stringify(k) +} + +// ListDeployKeys gets a list of a project's deploy keys +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/deploy_keys.html#list-deploy-keys +func (s *DeployKeysService) ListDeployKeys(pid interface{}, options ...OptionFunc) ([]*DeployKey, *Response, error) { + project, err := parseID(pid) + if err != nil { + return nil, nil, err + } + u := fmt.Sprintf("projects/%s/keys", url.QueryEscape(project)) + + req, err := s.client.NewRequest("GET", u, nil, options) + if err != nil { + return nil, nil, err + } + + var k []*DeployKey + resp, err := s.client.Do(req, &k) + if err != nil { + return nil, resp, err + } + + return k, resp, err +} + +// GetDeployKey gets a single deploy key. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/deploy_keys.html#single-deploy-key +func (s *DeployKeysService) GetDeployKey(pid interface{}, deployKey int, options ...OptionFunc) (*DeployKey, *Response, error) { + project, err := parseID(pid) + if err != nil { + return nil, nil, err + } + u := fmt.Sprintf("projects/%s/keys/%d", url.QueryEscape(project), deployKey) + + req, err := s.client.NewRequest("GET", u, nil, options) + if err != nil { + return nil, nil, err + } + + k := new(DeployKey) + resp, err := s.client.Do(req, k) + if err != nil { + return nil, resp, err + } + + return k, resp, err +} + +// AddDeployKeyOptions represents the available ADDDeployKey() options. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/deploy_keys.html#add-deploy-key +type AddDeployKeyOptions struct { + Title *string `url:"title,omitempty" json:"title,omitempty"` + Key *string `url:"key,omitempty" json:"key,omitempty"` + CanPush *bool `url:"can_push,omitempty" json:"can_push,omitempty"` +} + +// AddDeployKey creates a new deploy key for a project. If deploy key already +// exists in another project - it will be joined to project but only if +// original one was is accessible by same user. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/deploy_keys.html#add-deploy-key +func (s *DeployKeysService) AddDeployKey(pid interface{}, opt *AddDeployKeyOptions, options ...OptionFunc) (*DeployKey, *Response, error) { + project, err := parseID(pid) + if err != nil { + return nil, nil, err + } + u := fmt.Sprintf("projects/%s/keys", url.QueryEscape(project)) + + req, err := s.client.NewRequest("POST", u, opt, options) + if err != nil { + return nil, nil, err + } + + k := new(DeployKey) + resp, err := s.client.Do(req, k) + if err != nil { + return nil, resp, err + } + + return k, resp, err +} + +// DeleteDeployKey deletes a deploy key from a project. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/deploy_keys.html#delete-deploy-key +func (s *DeployKeysService) DeleteDeployKey(pid interface{}, deployKey int, options ...OptionFunc) (*Response, error) { + project, err := parseID(pid) + if err != nil { + return nil, err + } + u := fmt.Sprintf("projects/%s/keys/%d", url.QueryEscape(project), deployKey) + + req, err := s.client.NewRequest("DELETE", u, nil, options) + if err != nil { + return nil, err + } + + return s.client.Do(req, nil) +} diff --git a/vendor/github.com/xanzy/go-gitlab/events.go b/vendor/github.com/xanzy/go-gitlab/events.go new file mode 100644 index 000000000..ef334592e --- /dev/null +++ b/vendor/github.com/xanzy/go-gitlab/events.go @@ -0,0 +1,557 @@ +// +// Copyright 2015, Sander van Harmelen +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +package gitlab + +import "time" + +// PushEvent represents a push event. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/web_hooks/web_hooks.html#push-events +type PushEvent struct { + ObjectKind string `json:"object_kind"` + Before string `json:"before"` + After string `json:"after"` + Ref string `json:"ref"` + CheckoutSha string `json:"checkout_sha"` + UserID int `json:"user_id"` + UserName string `json:"user_name"` + UserEmail string `json:"user_email"` + UserAvatar string `json:"user_avatar"` + ProjectID int `json:"project_id"` + Project struct { + Name string `json:"name"` + Description string `json:"description"` + AvatarURL string `json:"avatar_url"` + GitSSHURL string `json:"git_ssh_url"` + GitHTTPURL string `json:"git_http_url"` + Namespace string `json:"namespace"` + PathWithNamespace string `json:"path_with_namespace"` + DefaultBranch string `json:"default_branch"` + Homepage string `json:"homepage"` + URL string `json:"url"` + SSHURL string `json:"ssh_url"` + HTTPURL string `json:"http_url"` + WebURL string `json:"web_url"` + VisibilityLevel VisibilityLevelValue `json:"visibility_level"` + } `json:"project"` + Repository *Repository `json:"repository"` + Commits []*Commit `json:"commits"` + TotalCommitsCount int `json:"total_commits_count"` +} + +// TagEvent represents a tag event. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/web_hooks/web_hooks.html#tag-events +type TagEvent struct { + ObjectKind string `json:"object_kind"` + Before string `json:"before"` + After string `json:"after"` + Ref string `json:"ref"` + CheckoutSha string `json:"checkout_sha"` + UserID int `json:"user_id"` + UserName string `json:"user_name"` + UserAvatar string `json:"user_avatar"` + ProjectID int `json:"project_id"` + Project struct { + Name string `json:"name"` + Description string `json:"description"` + AvatarURL string `json:"avatar_url"` + GitSSHURL string `json:"git_ssh_url"` + GitHTTPURL string `json:"git_http_url"` + Namespace string `json:"namespace"` + PathWithNamespace string `json:"path_with_namespace"` + DefaultBranch string `json:"default_branch"` + Homepage string `json:"homepage"` + URL string `json:"url"` + SSHURL string `json:"ssh_url"` + HTTPURL string `json:"http_url"` + WebURL string `json:"web_url"` + VisibilityLevel VisibilityLevelValue `json:"visibility_level"` + } `json:"project"` + Repository *Repository `json:"repository"` + Commits []*Commit `json:"commits"` + TotalCommitsCount int `json:"total_commits_count"` +} + +// IssueEvent represents a issue event. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/web_hooks/web_hooks.html#issues-events +type IssueEvent struct { + ObjectKind string `json:"object_kind"` + User *User `json:"user"` + Project struct { + Name string `json:"name"` + Description string `json:"description"` + AvatarURL string `json:"avatar_url"` + GitSSHURL string `json:"git_ssh_url"` + GitHTTPURL string `json:"git_http_url"` + Namespace string `json:"namespace"` + PathWithNamespace string `json:"path_with_namespace"` + DefaultBranch string `json:"default_branch"` + Homepage string `json:"homepage"` + URL string `json:"url"` + SSHURL string `json:"ssh_url"` + HTTPURL string `json:"http_url"` + WebURL string `json:"web_url"` + VisibilityLevel VisibilityLevelValue `json:"visibility_level"` + } `json:"project"` + Repository *Repository `json:"repository"` + ObjectAttributes struct { + ID int `json:"id"` + Title string `json:"title"` + AssigneeID int `json:"assignee_id"` + AuthorID int `json:"author_id"` + ProjectID int `json:"project_id"` + CreatedAt string `json:"created_at"` // Should be *time.Time (see Gitlab issue #21468) + UpdatedAt string `json:"updated_at"` // Should be *time.Time (see Gitlab issue #21468) + Position int `json:"position"` + BranchName string `json:"branch_name"` + Description string `json:"description"` + MilestoneID int `json:"milestone_id"` + State string `json:"state"` + Iid int `json:"iid"` + URL string `json:"url"` + Action string `json:"action"` + } `json:"object_attributes"` + Assignee struct { + Name string `json:"name"` + Username string `json:"username"` + AvatarURL string `json:"avatar_url"` + } `json:"assignee"` +} + +// CommitCommentEvent represents a comment on a commit event. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/web_hooks/web_hooks.html#comment-on-commit +type CommitCommentEvent struct { + ObjectKind string `json:"object_kind"` + User *User `json:"user"` + ProjectID int `json:"project_id"` + Project struct { + Name string `json:"name"` + Description string `json:"description"` + AvatarURL string `json:"avatar_url"` + GitSSHURL string `json:"git_ssh_url"` + GitHTTPURL string `json:"git_http_url"` + Namespace string `json:"namespace"` + PathWithNamespace string `json:"path_with_namespace"` + DefaultBranch string `json:"default_branch"` + Homepage string `json:"homepage"` + URL string `json:"url"` + SSHURL string `json:"ssh_url"` + HTTPURL string `json:"http_url"` + WebURL string `json:"web_url"` + VisibilityLevel VisibilityLevelValue `json:"visibility_level"` + } `json:"project"` + Repository *Repository `json:"repository"` + ObjectAttributes struct { + ID int `json:"id"` + Note string `json:"note"` + NoteableType string `json:"noteable_type"` + AuthorID int `json:"author_id"` + CreatedAt string `json:"created_at"` + UpdatedAt string `json:"updated_at"` + ProjectID int `json:"project_id"` + Attachment string `json:"attachment"` + LineCode string `json:"line_code"` + CommitID string `json:"commit_id"` + NoteableID int `json:"noteable_id"` + System bool `json:"system"` + StDiff struct { + Diff string `json:"diff"` + NewPath string `json:"new_path"` + OldPath string `json:"old_path"` + AMode string `json:"a_mode"` + BMode string `json:"b_mode"` + NewFile bool `json:"new_file"` + RenamedFile bool `json:"renamed_file"` + DeletedFile bool `json:"deleted_file"` + } `json:"st_diff"` + } `json:"object_attributes"` + Commit *Commit `json:"commit"` +} + +// MergeCommentEvent represents a comment on a merge event. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/web_hooks/web_hooks.html#comment-on-merge-request +type MergeCommentEvent struct { + ObjectKind string `json:"object_kind"` + User *User `json:"user"` + ProjectID int `json:"project_id"` + Project struct { + Name string `json:"name"` + Description string `json:"description"` + AvatarURL string `json:"avatar_url"` + GitSSHURL string `json:"git_ssh_url"` + GitHTTPURL string `json:"git_http_url"` + Namespace string `json:"namespace"` + PathWithNamespace string `json:"path_with_namespace"` + DefaultBranch string `json:"default_branch"` + Homepage string `json:"homepage"` + URL string `json:"url"` + SSHURL string `json:"ssh_url"` + HTTPURL string `json:"http_url"` + WebURL string `json:"web_url"` + VisibilityLevel VisibilityLevelValue `json:"visibility_level"` + } `json:"project"` + Repository *Repository `json:"repository"` + ObjectAttributes struct { + ID int `json:"id"` + Note string `json:"note"` + NoteableType string `json:"noteable_type"` + AuthorID int `json:"author_id"` + CreatedAt string `json:"created_at"` + UpdatedAt string `json:"updated_at"` + ProjectID int `json:"project_id"` + Attachment string `json:"attachment"` + LineCode string `json:"line_code"` + CommitID string `json:"commit_id"` + NoteableID int `json:"noteable_id"` + System bool `json:"system"` + StDiff *Diff `json:"st_diff"` + URL string `json:"url"` + } `json:"object_attributes"` + MergeRequest *MergeRequest `json:"merge_request"` +} + +// IssueCommentEvent represents a comment on an issue event. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/web_hooks/web_hooks.html#comment-on-issue +type IssueCommentEvent struct { + ObjectKind string `json:"object_kind"` + User *User `json:"user"` + ProjectID int `json:"project_id"` + Project struct { + Name string `json:"name"` + Description string `json:"description"` + AvatarURL string `json:"avatar_url"` + GitSSHURL string `json:"git_ssh_url"` + GitHTTPURL string `json:"git_http_url"` + Namespace string `json:"namespace"` + PathWithNamespace string `json:"path_with_namespace"` + DefaultBranch string `json:"default_branch"` + Homepage string `json:"homepage"` + URL string `json:"url"` + SSHURL string `json:"ssh_url"` + HTTPURL string `json:"http_url"` + WebURL string `json:"web_url"` + VisibilityLevel VisibilityLevelValue `json:"visibility_level"` + } `json:"project"` + Repository *Repository `json:"repository"` + ObjectAttributes struct { + ID int `json:"id"` + Note string `json:"note"` + NoteableType string `json:"noteable_type"` + AuthorID int `json:"author_id"` + CreatedAt string `json:"created_at"` + UpdatedAt string `json:"updated_at"` + ProjectID int `json:"project_id"` + Attachment string `json:"attachment"` + LineCode string `json:"line_code"` + CommitID string `json:"commit_id"` + NoteableID int `json:"noteable_id"` + System bool `json:"system"` + StDiff []*Diff `json:"st_diff"` + URL string `json:"url"` + } `json:"object_attributes"` + Issue *Issue `json:"issue"` +} + +// SnippetCommentEvent represents a comment on a snippet event. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/web_hooks/web_hooks.html#comment-on-code-snippet +type SnippetCommentEvent struct { + ObjectKind string `json:"object_kind"` + User *User `json:"user"` + ProjectID int `json:"project_id"` + Project struct { + Name string `json:"name"` + Description string `json:"description"` + AvatarURL string `json:"avatar_url"` + GitSSHURL string `json:"git_ssh_url"` + GitHTTPURL string `json:"git_http_url"` + Namespace string `json:"namespace"` + PathWithNamespace string `json:"path_with_namespace"` + DefaultBranch string `json:"default_branch"` + Homepage string `json:"homepage"` + URL string `json:"url"` + SSHURL string `json:"ssh_url"` + HTTPURL string `json:"http_url"` + WebURL string `json:"web_url"` + VisibilityLevel VisibilityLevelValue `json:"visibility_level"` + } `json:"project"` + Repository *Repository `json:"repository"` + ObjectAttributes struct { + ID int `json:"id"` + Note string `json:"note"` + NoteableType string `json:"noteable_type"` + AuthorID int `json:"author_id"` + CreatedAt string `json:"created_at"` + UpdatedAt string `json:"updated_at"` + ProjectID int `json:"project_id"` + Attachment string `json:"attachment"` + LineCode string `json:"line_code"` + CommitID string `json:"commit_id"` + NoteableID int `json:"noteable_id"` + System bool `json:"system"` + StDiff *Diff `json:"st_diff"` + URL string `json:"url"` + } `json:"object_attributes"` + Snippet *Snippet `json:"snippet"` +} + +// MergeEvent represents a merge event. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/web_hooks/web_hooks.html#merge-request-events +type MergeEvent struct { + ObjectKind string `json:"object_kind"` + User *User `json:"user"` + Project struct { + Name string `json:"name"` + Description string `json:"description"` + AvatarURL string `json:"avatar_url"` + GitSSHURL string `json:"git_ssh_url"` + GitHTTPURL string `json:"git_http_url"` + Namespace string `json:"namespace"` + PathWithNamespace string `json:"path_with_namespace"` + DefaultBranch string `json:"default_branch"` + Homepage string `json:"homepage"` + URL string `json:"url"` + SSHURL string `json:"ssh_url"` + HTTPURL string `json:"http_url"` + WebURL string `json:"web_url"` + VisibilityLevel VisibilityLevelValue `json:"visibility_level"` + } `json:"project"` + ObjectAttributes struct { + ID int `json:"id"` + TargetBranch string `json:"target_branch"` + SourceBranch string `json:"source_branch"` + SourceProjectID int `json:"source_project_id"` + AuthorID int `json:"author_id"` + AssigneeID int `json:"assignee_id"` + Title string `json:"title"` + CreatedAt string `json:"created_at"` // Should be *time.Time (see Gitlab issue #21468) + UpdatedAt string `json:"updated_at"` // Should be *time.Time (see Gitlab issue #21468) + StCommits []*Commit `json:"st_commits"` + StDiffs []*Diff `json:"st_diffs"` + MilestoneID int `json:"milestone_id"` + State string `json:"state"` + MergeStatus string `json:"merge_status"` + TargetProjectID int `json:"target_project_id"` + Iid int `json:"iid"` + Description string `json:"description"` + Position int `json:"position"` + LockedAt string `json:"locked_at"` + UpdatedByID int `json:"updated_by_id"` + MergeError string `json:"merge_error"` + MergeParams struct { + ForceRemoveSourceBranch string `json:"force_remove_source_branch"` + } `json:"merge_params"` + MergeWhenBuildSucceeds bool `json:"merge_when_build_succeeds"` + MergeUserID int `json:"merge_user_id"` + MergeCommitSha string `json:"merge_commit_sha"` + DeletedAt string `json:"deleted_at"` + ApprovalsBeforeMerge string `json:"approvals_before_merge"` + RebaseCommitSha string `json:"rebase_commit_sha"` + InProgressMergeCommitSha string `json:"in_progress_merge_commit_sha"` + LockVersion int `json:"lock_version"` + TimeEstimate int `json:"time_estimate"` + Source *Repository `json:"source"` + Target *Repository `json:"target"` + LastCommit struct { + ID string `json:"id"` + Message string `json:"message"` + Timestamp *time.Time `json:"timestamp"` + URL string `json:"url"` + Author *Author `json:"author"` + } `json:"last_commit"` + WorkInProgress bool `json:"work_in_progress"` + URL string `json:"url"` + Action string `json:"action"` + Assignee struct { + Name string `json:"name"` + Username string `json:"username"` + AvatarURL string `json:"avatar_url"` + } `json:"assignee"` + } `json:"object_attributes"` + Repository *Repository `json:"repository"` + Assignee struct { + Name string `json:"name"` + Username string `json:"username"` + AvatarURL string `json:"avatar_url"` + } `json:"assignee"` +} + +// WikiPageEvent represents a wiki page event. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/web_hooks/web_hooks.html#wiki-page-events +type WikiPageEvent struct { + ObjectKind string `json:"object_kind"` + User *User `json:"user"` + Project struct { + Name string `json:"name"` + Description string `json:"description"` + AvatarURL string `json:"avatar_url"` + GitSSHURL string `json:"git_ssh_url"` + GitHTTPURL string `json:"git_http_url"` + Namespace string `json:"namespace"` + PathWithNamespace string `json:"path_with_namespace"` + DefaultBranch string `json:"default_branch"` + Homepage string `json:"homepage"` + URL string `json:"url"` + SSHURL string `json:"ssh_url"` + HTTPURL string `json:"http_url"` + WebURL string `json:"web_url"` + VisibilityLevel VisibilityLevelValue `json:"visibility_level"` + } `json:"project"` + Wiki struct { + WebURL string `json:"web_url"` + GitSSHURL string `json:"git_ssh_url"` + GitHTTPURL string `json:"git_http_url"` + PathWithNamespace string `json:"path_with_namespace"` + DefaultBranch string `json:"default_branch"` + } `json:"wiki"` + ObjectAttributes struct { + Title string `json:"title"` + Content string `json:"content"` + Format string `json:"format"` + Message string `json:"message"` + Slug string `json:"slug"` + URL string `json:"url"` + Action string `json:"action"` + } `json:"object_attributes"` +} + +// PipelineEvent represents a pipeline event. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/web_hooks/web_hooks.html#pipeline-events +type PipelineEvent struct { + ObjectKind string `json:"object_kind"` + ObjectAttributes struct { + ID int `json:"id"` + Ref string `json:"ref"` + Tag bool `json:"tag"` + Sha string `json:"sha"` + BeforeSha string `json:"before_sha"` + Status string `json:"status"` + Stages []string `json:"stages"` + CreatedAt string `json:"created_at"` + FinishedAt string `json:"finished_at"` + Duration int `json:"duration"` + } `json:"object_attributes"` + User struct { + Name string `json:"name"` + Username string `json:"username"` + AvatarURL string `json:"avatar_url"` + } `json:"user"` + Project struct { + Name string `json:"name"` + Description string `json:"description"` + AvatarURL string `json:"avatar_url"` + GitSSHURL string `json:"git_ssh_url"` + GitHTTPURL string `json:"git_http_url"` + Namespace string `json:"namespace"` + PathWithNamespace string `json:"path_with_namespace"` + DefaultBranch string `json:"default_branch"` + Homepage string `json:"homepage"` + URL string `json:"url"` + SSHURL string `json:"ssh_url"` + HTTPURL string `json:"http_url"` + WebURL string `json:"web_url"` + VisibilityLevel VisibilityLevelValue `json:"visibility_level"` + } `json:"project"` + Commit struct { + ID string `json:"id"` + Message string `json:"message"` + Timestamp time.Time `json:"timestamp"` + URL string `json:"url"` + Author struct { + Name string `json:"name"` + Email string `json:"email"` + } `json:"author"` + } `json:"commit"` + Builds []struct { + ID int `json:"id"` + Stage string `json:"stage"` + Name string `json:"name"` + Status string `json:"status"` + CreatedAt string `json:"created_at"` + StartedAt string `json:"started_at"` + FinishedAt string `json:"finished_at"` + When string `json:"when"` + Manual bool `json:"manual"` + User struct { + Name string `json:"name"` + Username string `json:"username"` + AvatarURL string `json:"avatar_url"` + } `json:"user"` + Runner string `json:"runner"` + ArtifactsFile struct { + Filename string `json:"filename"` + Size string `json:"size"` + } `json:"artifacts_file"` + } `json:"builds"` +} + +//BuildEvent represents a build event +// +// GitLab API docs: +// https://docs.gitlab.com/ce/web_hooks/web_hooks.html#build-events +type BuildEvent struct { + ObjectKind string `json:"object_kind"` + Ref string `json:"ref"` + Tag bool `json:"tag"` + BeforeSha string `json:"before_sha"` + Sha string `json:"sha"` + BuildID int `json:"build_id"` + BuildName string `json:"build_name"` + BuildStage string `json:"build_stage"` + BuildStatus string `json:"build_status"` + BuildStartedAt string `json:"build_started_at"` + BuildFinishedAt string `json:"build_finished_at"` + BuildDuration string `json:"build_duration"` + BuildAllowFailure bool `json:"build_allow_failure"` + ProjectID int `json:"project_id"` + ProjectName string `json:"project_name"` + User struct { + ID int `json:"id"` + Name string `json:"name"` + Email string `json:"email"` + } `json:"user"` + Commit struct { + ID int `json:"id"` + Sha string `json:"sha"` + Message string `json:"message"` + AuthorName string `json:"author_name"` + AuthorEmail string `json:"author_email"` + Status string `json:"status"` + Duration string `json:"duration"` + StartedAt string `json:"started_at"` + FinishedAt string `json:"finished_at"` + } `json:"commit"` + Repository *Repository `json:"repository"` +} diff --git a/vendor/github.com/xanzy/go-gitlab/gitlab.go b/vendor/github.com/xanzy/go-gitlab/gitlab.go new file mode 100644 index 000000000..655485d3c --- /dev/null +++ b/vendor/github.com/xanzy/go-gitlab/gitlab.go @@ -0,0 +1,605 @@ +// +// Copyright 2015, Sander van Harmelen +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +package gitlab + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "io" + "io/ioutil" + "net/http" + "net/url" + "sort" + "strconv" + "strings" + + "github.com/google/go-querystring/query" +) + +const ( + libraryVersion = "0.1.1" + defaultBaseURL = "https://gitlab.com/api/v3/" + userAgent = "go-gitlab/" + libraryVersion +) + +// tokenType represents a token type within GitLab. +// +// GitLab API docs: https://docs.gitlab.com/ce/api/ +type tokenType int + +// List of available token type +// +// GitLab API docs: https://docs.gitlab.com/ce/api/ +const ( + privateToken tokenType = iota + oAuthToken +) + +// AccessLevelValue represents a permission level within GitLab. +// +// GitLab API docs: https://docs.gitlab.com/ce/permissions/permissions.html +type AccessLevelValue int + +// List of available access levels +// +// GitLab API docs: https://docs.gitlab.com/ce/permissions/permissions.html +const ( + GuestPermissions AccessLevelValue = 10 + ReporterPermissions AccessLevelValue = 20 + DeveloperPermissions AccessLevelValue = 30 + MasterPermissions AccessLevelValue = 40 + OwnerPermission AccessLevelValue = 50 +) + +// NotificationLevelValue represents a notification level. +type NotificationLevelValue int + +// String implements the fmt.Stringer interface. +func (l NotificationLevelValue) String() string { + return notificationLevelNames[l] +} + +// MarshalJSON implements the json.Marshaler interface. +func (l NotificationLevelValue) MarshalJSON() ([]byte, error) { + return json.Marshal(l.String()) +} + +// UnmarshalJSON implements the json.Unmarshaler interface. +func (l *NotificationLevelValue) UnmarshalJSON(data []byte) error { + var raw interface{} + if err := json.Unmarshal(data, &raw); err != nil { + return err + } + + switch raw := raw.(type) { + case float64: + *l = NotificationLevelValue(raw) + case string: + *l = notificationLevelTypes[raw] + default: + return fmt.Errorf("json: cannot unmarshal %T into Go value of type %T", raw, *l) + } + + return nil +} + +// List of valid notification levels. +const ( + DisabledNotificationLevel NotificationLevelValue = iota + ParticipatingNotificationLevel + WatchNotificationLevel + GlobalNotificationLevel + MentionNotificationLevel + CustomNotificationLevel +) + +var notificationLevelNames = [...]string{ + "disabled", + "participating", + "watch", + "global", + "mention", + "custom", +} + +var notificationLevelTypes = map[string]NotificationLevelValue{ + "disabled": DisabledNotificationLevel, + "participating": ParticipatingNotificationLevel, + "watch": WatchNotificationLevel, + "global": GlobalNotificationLevel, + "mention": MentionNotificationLevel, + "custom": CustomNotificationLevel, +} + +// VisibilityLevelValue represents a visibility level within GitLab. +// +// GitLab API docs: https://docs.gitlab.com/ce/api/ +type VisibilityLevelValue int + +// List of available visibility levels +// +// GitLab API docs: https://docs.gitlab.com/ce/api/ +const ( + PrivateVisibility VisibilityLevelValue = 0 + InternalVisibility VisibilityLevelValue = 10 + PublicVisibility VisibilityLevelValue = 20 +) + +// A Client manages communication with the GitLab API. +type Client struct { + // HTTP client used to communicate with the API. + client *http.Client + + // Base URL for API requests. Defaults to the public GitLab API, but can be + // set to a domain endpoint to use with aself hosted GitLab server. baseURL + // should always be specified with a trailing slash. + baseURL *url.URL + + // token type used to make authenticated API calls. + tokenType tokenType + + // token used to make authenticated API calls. + token string + + // User agent used when communicating with the GitLab API. + UserAgent string + + // Services used for talking to different parts of the GitLab API. + Branches *BranchesService + BuildVariables *BuildVariablesService + Builds *BuildsService + Commits *CommitsService + DeployKeys *DeployKeysService + Groups *GroupsService + Issues *IssuesService + Labels *LabelsService + MergeRequests *MergeRequestsService + Milestones *MilestonesService + Namespaces *NamespacesService + Notes *NotesService + NotificationSettings *NotificationSettingsService + Projects *ProjectsService + ProjectSnippets *ProjectSnippetsService + Pipelines *PipelinesService + Repositories *RepositoriesService + RepositoryFiles *RepositoryFilesService + Services *ServicesService + Session *SessionService + Settings *SettingsService + SystemHooks *SystemHooksService + Tags *TagsService + TimeStats *TimeStatsService + Users *UsersService +} + +// ListOptions specifies the optional parameters to various List methods that +// support pagination. +type ListOptions struct { + // For paginated result sets, page of results to retrieve. + Page int `url:"page,omitempty" json:"page,omitempty"` + + // For paginated result sets, the number of results to include per page. + PerPage int `url:"per_page,omitempty" json:"per_page,omitempty"` +} + +// NewClient returns a new GitLab API client. If a nil httpClient is +// provided, http.DefaultClient will be used. To use API methods which require +// authentication, provide a valid private token. +func NewClient(httpClient *http.Client, token string) *Client { + return newClient(httpClient, privateToken, token) +} + +// NewOAuthClient returns a new GitLab API client. If a nil httpClient is +// provided, http.DefaultClient will be used. To use API methods which require +// authentication, provide a valid oauth token. +func NewOAuthClient(httpClient *http.Client, token string) *Client { + return newClient(httpClient, oAuthToken, token) +} + +func newClient(httpClient *http.Client, tokenType tokenType, token string) *Client { + if httpClient == nil { + httpClient = http.DefaultClient + } + + c := &Client{client: httpClient, tokenType: tokenType, token: token, UserAgent: userAgent} + if err := c.SetBaseURL(defaultBaseURL); err != nil { + // should never happen since defaultBaseURL is our constant + panic(err) + } + + c.Branches = &BranchesService{client: c} + c.BuildVariables = &BuildVariablesService{client: c} + c.Builds = &BuildsService{client: c} + c.Commits = &CommitsService{client: c} + c.DeployKeys = &DeployKeysService{client: c} + c.Groups = &GroupsService{client: c} + c.Issues = &IssuesService{client: c} + c.Labels = &LabelsService{client: c} + c.MergeRequests = &MergeRequestsService{client: c} + c.Milestones = &MilestonesService{client: c} + c.Namespaces = &NamespacesService{client: c} + c.Notes = &NotesService{client: c} + c.NotificationSettings = &NotificationSettingsService{client: c} + c.Projects = &ProjectsService{client: c} + c.ProjectSnippets = &ProjectSnippetsService{client: c} + c.Pipelines = &PipelinesService{client: c} + c.Repositories = &RepositoriesService{client: c} + c.RepositoryFiles = &RepositoryFilesService{client: c} + c.Services = &ServicesService{client: c} + c.Session = &SessionService{client: c} + c.Settings = &SettingsService{client: c} + c.SystemHooks = &SystemHooksService{client: c} + c.Tags = &TagsService{client: c} + c.TimeStats = &TimeStatsService{client: c} + c.Users = &UsersService{client: c} + + return c +} + +// BaseURL return a copy of the baseURL. +func (c *Client) BaseURL() *url.URL { + u := *c.baseURL + return &u +} + +// SetBaseURL sets the base URL for API requests to a custom endpoint. urlStr +// should always be specified with a trailing slash. +func (c *Client) SetBaseURL(urlStr string) error { + // Make sure the given URL end with a slash + if !strings.HasSuffix(urlStr, "/") { + urlStr += "/" + } + + var err error + c.baseURL, err = url.Parse(urlStr) + return err +} + +// NewRequest creates an API request. A relative URL path can be provided in +// urlStr, in which case it is resolved relative to the base URL of the Client. +// Relative URL paths should always be specified without a preceding slash. If +// specified, the value pointed to by body is JSON encoded and included as the +// request body. +func (c *Client) NewRequest(method, path string, opt interface{}, options []OptionFunc) (*http.Request, error) { + u := *c.baseURL + // Set the encoded opaque data + u.Opaque = c.baseURL.Path + path + + if opt != nil { + q, err := query.Values(opt) + if err != nil { + return nil, err + } + u.RawQuery = q.Encode() + } + + req := &http.Request{ + Method: method, + URL: &u, + Proto: "HTTP/1.1", + ProtoMajor: 1, + ProtoMinor: 1, + Header: make(http.Header), + Host: u.Host, + } + + for _, fn := range options { + if err := fn(req); err != nil { + return nil, err + } + } + + if method == "POST" || method == "PUT" { + bodyBytes, err := json.Marshal(opt) + if err != nil { + return nil, err + } + bodyReader := bytes.NewReader(bodyBytes) + + u.RawQuery = "" + req.Body = ioutil.NopCloser(bodyReader) + req.ContentLength = int64(bodyReader.Len()) + req.Header.Set("Content-Type", "application/json") + } + + req.Header.Set("Accept", "application/json") + + switch c.tokenType { + case privateToken: + req.Header.Set("PRIVATE-TOKEN", c.token) + case oAuthToken: + req.Header.Set("Authorization", "Bearer "+c.token) + } + + if c.UserAgent != "" { + req.Header.Set("User-Agent", c.UserAgent) + } + + return req, nil +} + +// Response is a GitLab API response. This wraps the standard http.Response +// returned from GitLab and provides convenient access to things like +// pagination links. +type Response struct { + *http.Response + + // These fields provide the page values for paginating through a set of + // results. Any or all of these may be set to the zero value for + // responses that are not part of a paginated set, or for which there + // are no additional pages. + + NextPage int + PrevPage int + FirstPage int + LastPage int +} + +// newResponse creats a new Response for the provided http.Response. +func newResponse(r *http.Response) *Response { + response := &Response{Response: r} + response.populatePageValues() + return response +} + +// populatePageValues parses the HTTP Link response headers and populates the +// various pagination link values in the Reponse. +func (r *Response) populatePageValues() { + if links, ok := r.Response.Header["Link"]; ok && len(links) > 0 { + for _, link := range strings.Split(links[0], ",") { + segments := strings.Split(strings.TrimSpace(link), ";") + + // link must at least have href and rel + if len(segments) < 2 { + continue + } + + // ensure href is properly formatted + if !strings.HasPrefix(segments[0], "<") || !strings.HasSuffix(segments[0], ">") { + continue + } + + // try to pull out page parameter + url, err := url.Parse(segments[0][1 : len(segments[0])-1]) + if err != nil { + continue + } + page := url.Query().Get("page") + if page == "" { + continue + } + + for _, segment := range segments[1:] { + switch strings.TrimSpace(segment) { + case `rel="next"`: + r.NextPage, _ = strconv.Atoi(page) + case `rel="prev"`: + r.PrevPage, _ = strconv.Atoi(page) + case `rel="first"`: + r.FirstPage, _ = strconv.Atoi(page) + case `rel="last"`: + r.LastPage, _ = strconv.Atoi(page) + } + + } + } + } +} + +// Do sends an API request and returns the API response. The API response is +// JSON decoded and stored in the value pointed to by v, or returned as an +// error if an API error has occurred. If v implements the io.Writer +// interface, the raw response body will be written to v, without attempting to +// first decode it. +func (c *Client) Do(req *http.Request, v interface{}) (*Response, error) { + resp, err := c.client.Do(req) + if err != nil { + return nil, err + } + defer resp.Body.Close() + + response := newResponse(resp) + + err = CheckResponse(resp) + if err != nil { + // even though there was an error, we still return the response + // in case the caller wants to inspect it further + return response, err + } + + if v != nil { + if w, ok := v.(io.Writer); ok { + _, err = io.Copy(w, resp.Body) + } else { + err = json.NewDecoder(resp.Body).Decode(v) + } + } + return response, err +} + +// Helper function to accept and format both the project ID or name as project +// identifier for all API calls. +func parseID(id interface{}) (string, error) { + switch v := id.(type) { + case int: + return strconv.Itoa(v), nil + case string: + return v, nil + default: + return "", fmt.Errorf("invalid ID type %#v, the ID must be an int or a string", id) + } +} + +// An ErrorResponse reports one or more errors caused by an API request. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/README.html#data-validation-and-error-reporting +type ErrorResponse struct { + Response *http.Response + Message string +} + +func (e *ErrorResponse) Error() string { + path, _ := url.QueryUnescape(e.Response.Request.URL.Opaque) + u := fmt.Sprintf("%s://%s%s", e.Response.Request.URL.Scheme, e.Response.Request.URL.Host, path) + return fmt.Sprintf("%s %s: %d %s", e.Response.Request.Method, u, e.Response.StatusCode, e.Message) +} + +// CheckResponse checks the API response for errors, and returns them if present. +func CheckResponse(r *http.Response) error { + switch r.StatusCode { + case 200, 201, 304: + return nil + } + + errorResponse := &ErrorResponse{Response: r} + data, err := ioutil.ReadAll(r.Body) + if err == nil && data != nil { + var raw interface{} + if err := json.Unmarshal(data, &raw); err != nil { + errorResponse.Message = "failed to parse unknown error format" + } + + errorResponse.Message = parseError(raw) + } + + return errorResponse +} + +// Format: +// { +// "message": { +// "": [ +// "", +// "", +// ... +// ], +// "": { +// "": [ +// "", +// "", +// ... +// ], +// } +// }, +// "error": "" +// } +func parseError(raw interface{}) string { + switch raw := raw.(type) { + case string: + return raw + + case []interface{}: + var errs []string + for _, v := range raw { + errs = append(errs, parseError(v)) + } + return fmt.Sprintf("[%s]", strings.Join(errs, ", ")) + + case map[string]interface{}: + var errs []string + for k, v := range raw { + errs = append(errs, fmt.Sprintf("{%s: %s}", k, parseError(v))) + } + sort.Strings(errs) + return fmt.Sprintf("%s", strings.Join(errs, ", ")) + + default: + return fmt.Sprintf("failed to parse unexpected error type: %T", raw) + } +} + +// OptionFunc can be passed to all API requests to make the API call as if you were +// another user, provided your private token is from an administrator account. +// +// GitLab docs: https://docs.gitlab.com/ce/api/README.html#sudo +type OptionFunc func(*http.Request) error + +// WithSudo takes either a username or user ID and sets the SUDO request header +func WithSudo(uid interface{}) OptionFunc { + return func(req *http.Request) error { + switch uid := uid.(type) { + case int: + req.Header.Set("SUDO", strconv.Itoa(uid)) + return nil + case string: + req.Header.Set("SUDO", uid) + return nil + default: + return fmt.Errorf("uid must be either a username or user ID") + } + } +} + +// WithContext runs the request with the provided context +func WithContext(ctx context.Context) OptionFunc { + return func(req *http.Request) error { + *req = *req.WithContext(ctx) + return nil + } +} + +// Bool is a helper routine that allocates a new bool value +// to store v and returns a pointer to it. +func Bool(v bool) *bool { + p := new(bool) + *p = v + return p +} + +// Int is a helper routine that allocates a new int32 value +// to store v and returns a pointer to it, but unlike Int32 +// its argument value is an int. +func Int(v int) *int { + p := new(int) + *p = v + return p +} + +// String is a helper routine that allocates a new string value +// to store v and returns a pointer to it. +func String(v string) *string { + p := new(string) + *p = v + return p +} + +// AccessLevel is a helper routine that allocates a new AccessLevelValue +// to store v and returns a pointer to it. +func AccessLevel(v AccessLevelValue) *AccessLevelValue { + p := new(AccessLevelValue) + *p = v + return p +} + +// NotificationLevel is a helper routine that allocates a new NotificationLevelValue +// to store v and returns a pointer to it. +func NotificationLevel(v NotificationLevelValue) *NotificationLevelValue { + p := new(NotificationLevelValue) + *p = v + return p +} + +// VisibilityLevel is a helper routine that allocates a new VisibilityLevelValue +// to store v and returns a pointer to it. +func VisibilityLevel(v VisibilityLevelValue) *VisibilityLevelValue { + p := new(VisibilityLevelValue) + *p = v + return p +} diff --git a/vendor/github.com/xanzy/go-gitlab/groups.go b/vendor/github.com/xanzy/go-gitlab/groups.go new file mode 100644 index 000000000..6e5e00187 --- /dev/null +++ b/vendor/github.com/xanzy/go-gitlab/groups.go @@ -0,0 +1,358 @@ +// +// Copyright 2015, Sander van Harmelen +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +package gitlab + +import ( + "fmt" + "time" +) + +// GroupsService handles communication with the group related methods of +// the GitLab API. +// +// GitLab API docs: https://docs.gitlab.com/ce/api/groups.html +type GroupsService struct { + client *Client +} + +// Group represents a GitLab group. +// +// GitLab API docs: https://docs.gitlab.com/ce/api/groups.html +type Group struct { + ID int `json:"id"` + Name string `json:"name"` + Path string `json:"path"` + Description string `json:"description"` + Projects []*Project `json:"projects"` + Statistics *StorageStatistics `json:"statistics"` +} + +// ListGroupsOptions represents the available ListGroups() options. +// +// GitLab API docs: https://docs.gitlab.com/ce/api/groups.html#list-project-groups +type ListGroupsOptions struct { + ListOptions + Search *string `url:"search,omitempty" json:"search,omitempty"` + Statistics *bool `url:"statistics,omitempty" json:"statistics,omitempty"` +} + +// ListGroups gets a list of groups. (As user: my groups, as admin: all groups) +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/groups.html#list-project-groups +func (s *GroupsService) ListGroups(opt *ListGroupsOptions, options ...OptionFunc) ([]*Group, *Response, error) { + req, err := s.client.NewRequest("GET", "groups", opt, options) + if err != nil { + return nil, nil, err + } + + var g []*Group + resp, err := s.client.Do(req, &g) + if err != nil { + return nil, resp, err + } + + return g, resp, err +} + +// GetGroup gets all details of a group. +// +// GitLab API docs: https://docs.gitlab.com/ce/api/groups.html#details-of-a-group +func (s *GroupsService) GetGroup(gid interface{}, options ...OptionFunc) (*Group, *Response, error) { + group, err := parseID(gid) + if err != nil { + return nil, nil, err + } + u := fmt.Sprintf("groups/%s", group) + + req, err := s.client.NewRequest("GET", u, nil, options) + if err != nil { + return nil, nil, err + } + + g := new(Group) + resp, err := s.client.Do(req, g) + if err != nil { + return nil, resp, err + } + + return g, resp, err +} + +// CreateGroupOptions represents the available CreateGroup() options. +// +// GitLab API docs: https://docs.gitlab.com/ce/api/groups.html#new-group +type CreateGroupOptions struct { + Name *string `url:"name,omitempty" json:"name,omitempty"` + Path *string `url:"path,omitempty" json:"path,omitempty"` + Description *string `url:"description,omitempty" json:"description,omitempty"` + VisibilityLevel *VisibilityLevelValue `url:"visibility_level" json:"visibility_level,omitempty"` +} + +// CreateGroup creates a new project group. Available only for users who can +// create groups. +// +// GitLab API docs: https://docs.gitlab.com/ce/api/groups.html#new-group +func (s *GroupsService) CreateGroup(opt *CreateGroupOptions, options ...OptionFunc) (*Group, *Response, error) { + req, err := s.client.NewRequest("POST", "groups", opt, options) + if err != nil { + return nil, nil, err + } + + g := new(Group) + resp, err := s.client.Do(req, g) + if err != nil { + return nil, resp, err + } + + return g, resp, err +} + +// TransferGroup transfers a project to the Group namespace. Available only +// for admin. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/groups.html#transfer-project-to-group +func (s *GroupsService) TransferGroup(gid interface{}, project int, options ...OptionFunc) (*Group, *Response, error) { + group, err := parseID(gid) + if err != nil { + return nil, nil, err + } + u := fmt.Sprintf("groups/%s/projects/%d", group, project) + + req, err := s.client.NewRequest("POST", u, nil, options) + if err != nil { + return nil, nil, err + } + + g := new(Group) + resp, err := s.client.Do(req, g) + if err != nil { + return nil, resp, err + } + + return g, resp, err +} + +// DeleteGroup removes group with all projects inside. +// +// GitLab API docs: https://docs.gitlab.com/ce/api/groups.html#remove-group +func (s *GroupsService) DeleteGroup(gid interface{}, options ...OptionFunc) (*Response, error) { + group, err := parseID(gid) + if err != nil { + return nil, err + } + u := fmt.Sprintf("groups/%s", group) + + req, err := s.client.NewRequest("DELETE", u, nil, options) + if err != nil { + return nil, err + } + + return s.client.Do(req, nil) +} + +// SearchGroup get all groups that match your string in their name or path. +// +// GitLab API docs: https://docs.gitlab.com/ce/api/groups.html#search-for-group +func (s *GroupsService) SearchGroup(query string, options ...OptionFunc) ([]*Group, *Response, error) { + var q struct { + Search string `url:"search,omitempty" json:"search,omitempty"` + } + q.Search = query + + req, err := s.client.NewRequest("GET", "groups", &q, options) + if err != nil { + return nil, nil, err + } + + var g []*Group + resp, err := s.client.Do(req, &g) + if err != nil { + return nil, resp, err + } + + return g, resp, err +} + +// GroupMember represents a GitLab group member. +// +// GitLab API docs: https://docs.gitlab.com/ce/api/groups.html +type GroupMember struct { + ID int `json:"id"` + Username string `json:"username"` + Email string `json:"email"` + Name string `json:"name"` + State string `json:"state"` + CreatedAt *time.Time `json:"created_at"` + AccessLevel AccessLevelValue `json:"access_level"` +} + +// ListGroupMembersOptions represents the available ListGroupMembers() +// options. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/groups.html#list-group-members +type ListGroupMembersOptions struct { + ListOptions +} + +// ListGroupMembers get a list of group members viewable by the authenticated +// user. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/groups.html#list-group-members +func (s *GroupsService) ListGroupMembers(gid interface{}, opt *ListGroupMembersOptions, options ...OptionFunc) ([]*GroupMember, *Response, error) { + group, err := parseID(gid) + if err != nil { + return nil, nil, err + } + u := fmt.Sprintf("groups/%s/members", group) + + req, err := s.client.NewRequest("GET", u, opt, options) + if err != nil { + return nil, nil, err + } + + var g []*GroupMember + resp, err := s.client.Do(req, &g) + if err != nil { + return nil, resp, err + } + + return g, resp, err +} + +// ListGroupProjectsOptions represents the available ListGroupProjects() +// options. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/groups.html#list-a-group-s-projects +type ListGroupProjectsOptions struct { + ListOptions +} + +// ListGroupProjects get a list of group projects +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/groups.html#list-a-group-s-projects +func (s *GroupsService) ListGroupProjects(gid interface{}, opt *ListGroupProjectsOptions, options ...OptionFunc) ([]*Project, *Response, error) { + group, err := parseID(gid) + if err != nil { + return nil, nil, err + } + u := fmt.Sprintf("groups/%s/projects", group) + + req, err := s.client.NewRequest("GET", u, opt, options) + if err != nil { + return nil, nil, err + } + + var p []*Project + resp, err := s.client.Do(req, &p) + if err != nil { + return nil, resp, err + } + + return p, resp, err +} + +// AddGroupMemberOptions represents the available AddGroupMember() options. +// +// GitLab API docs: https://docs.gitlab.com/ce/api/groups.html#add-group-member +type AddGroupMemberOptions struct { + UserID *int `url:"user_id,omitempty" json:"user_id,omitempty"` + AccessLevel *AccessLevelValue `url:"access_level,omitempty" json:"access_level,omitempty"` +} + +// AddGroupMember adds a user to the list of group members. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/groups.html#list-group-members +func (s *GroupsService) AddGroupMember(gid interface{}, opt *AddGroupMemberOptions, options ...OptionFunc) (*GroupMember, *Response, error) { + group, err := parseID(gid) + if err != nil { + return nil, nil, err + } + u := fmt.Sprintf("groups/%s/members", group) + + req, err := s.client.NewRequest("POST", u, opt, options) + if err != nil { + return nil, nil, err + } + + g := new(GroupMember) + resp, err := s.client.Do(req, g) + if err != nil { + return nil, resp, err + } + + return g, resp, err +} + +// UpdateGroupMemberOptions represents the available UpdateGroupMember() +// options. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/groups.html#edit-group-team-member +type UpdateGroupMemberOptions struct { + AccessLevel *AccessLevelValue `url:"access_level,omitempty" json:"access_level,omitempty"` +} + +// UpdateGroupMember updates a group team member to a specified access level. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/groups.html#list-group-members +func (s *GroupsService) UpdateGroupMember(gid interface{}, user int, opt *UpdateGroupMemberOptions, options ...OptionFunc) (*GroupMember, *Response, error) { + group, err := parseID(gid) + if err != nil { + return nil, nil, err + } + u := fmt.Sprintf("groups/%s/members/%d", group, user) + + req, err := s.client.NewRequest("PUT", u, opt, options) + if err != nil { + return nil, nil, err + } + + g := new(GroupMember) + resp, err := s.client.Do(req, g) + if err != nil { + return nil, resp, err + } + + return g, resp, err +} + +// RemoveGroupMember removes user from user team. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/groups.html#remove-user-from-user-team +func (s *GroupsService) RemoveGroupMember(gid interface{}, user int, options ...OptionFunc) (*Response, error) { + group, err := parseID(gid) + if err != nil { + return nil, err + } + u := fmt.Sprintf("groups/%s/members/%d", group, user) + + req, err := s.client.NewRequest("DELETE", u, nil, options) + if err != nil { + return nil, err + } + + return s.client.Do(req, nil) +} diff --git a/vendor/github.com/xanzy/go-gitlab/issues.go b/vendor/github.com/xanzy/go-gitlab/issues.go new file mode 100644 index 000000000..0a286c203 --- /dev/null +++ b/vendor/github.com/xanzy/go-gitlab/issues.go @@ -0,0 +1,264 @@ +// +// Copyright 2015, Sander van Harmelen +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +package gitlab + +import ( + "encoding/json" + "fmt" + "net/url" + "strings" + "time" +) + +// IssuesService handles communication with the issue related methods +// of the GitLab API. +// +// GitLab API docs: https://docs.gitlab.com/ce/api/issues.html +type IssuesService struct { + client *Client +} + +// Issue represents a GitLab issue. +// +// GitLab API docs: https://docs.gitlab.com/ce/api/issues.html +type Issue struct { + ID int `json:"id"` + IID int `json:"iid"` + ProjectID int `json:"project_id"` + Title string `json:"title"` + Description string `json:"description"` + Labels []string `json:"labels"` + Milestone *Milestone `json:"milestone"` + Assignee struct { + ID int `json:"id"` + Username string `json:"username"` + Email string `json:"email"` + Name string `json:"name"` + State string `json:"state"` + CreatedAt *time.Time `json:"created_at"` + } `json:"assignee"` + Author struct { + ID int `json:"id"` + Username string `json:"username"` + Email string `json:"email"` + Name string `json:"name"` + State string `json:"state"` + CreatedAt *time.Time `json:"created_at"` + } `json:"author"` + State string `json:"state"` + UpdatedAt *time.Time `json:"updated_at"` + CreatedAt *time.Time `json:"created_at"` + Subscribed bool `json:"subscribed"` + UserNotesCount int `json:"user_notes_count"` + Confidential bool `json:"confidential"` + DueDate string `json:"due_date"` + WebURL string `json:"web_url"` +} + +func (i Issue) String() string { + return Stringify(i) +} + +// Labels is a custom type with specific marshaling characteristics. +type Labels []string + +// MarshalJSON implements the json.Marshaler interface. +func (l *Labels) MarshalJSON() ([]byte, error) { + return json.Marshal(strings.Join(*l, ",")) +} + +// ListIssuesOptions represents the available ListIssues() options. +// +// GitLab API docs: https://docs.gitlab.com/ce/api/issues.html#list-issues +type ListIssuesOptions struct { + ListOptions + State *string `url:"state,omitempty" json:"state,omitempty"` + Labels Labels `url:"labels,comma,omitempty" json:"labels,omitempty"` + OrderBy *string `url:"order_by,omitempty" json:"order_by,omitempty"` + Sort *string `url:"sort,omitempty" json:"sort,omitempty"` +} + +// ListIssues gets all issues created by authenticated user. This function +// takes pagination parameters page and per_page to restrict the list of issues. +// +// GitLab API docs: https://docs.gitlab.com/ce/api/issues.html#list-issues +func (s *IssuesService) ListIssues(opt *ListIssuesOptions, options ...OptionFunc) ([]*Issue, *Response, error) { + req, err := s.client.NewRequest("GET", "issues", opt, options) + if err != nil { + return nil, nil, err + } + + var i []*Issue + resp, err := s.client.Do(req, &i) + if err != nil { + return nil, resp, err + } + + return i, resp, err +} + +// ListProjectIssuesOptions represents the available ListProjectIssues() options. +// +// GitLab API docs: https://docs.gitlab.com/ce/api/issues.html#list-issues +type ListProjectIssuesOptions struct { + ListOptions + IID *int `url:"iid,omitempty" json:"iid,omitempty"` + State *string `url:"state,omitempty" json:"state,omitempty"` + Labels Labels `url:"labels,comma,omitempty" json:"labels,omitempty"` + Milestone *string `url:"milestone,omitempty" json:"milestone,omitempty"` + OrderBy *string `url:"order_by,omitempty" json:"order_by,omitempty"` + Sort *string `url:"sort,omitempty" json:"sort,omitempty"` +} + +// ListProjectIssues gets a list of project issues. This function accepts +// pagination parameters page and per_page to return the list of project issues. +// +// GitLab API docs: https://docs.gitlab.com/ce/api/issues.html#list-project-issues +func (s *IssuesService) ListProjectIssues(pid interface{}, opt *ListProjectIssuesOptions, options ...OptionFunc) ([]*Issue, *Response, error) { + project, err := parseID(pid) + if err != nil { + return nil, nil, err + } + u := fmt.Sprintf("projects/%s/issues", url.QueryEscape(project)) + + req, err := s.client.NewRequest("GET", u, opt, options) + if err != nil { + return nil, nil, err + } + + var i []*Issue + resp, err := s.client.Do(req, &i) + if err != nil { + return nil, resp, err + } + + return i, resp, err +} + +// GetIssue gets a single project issue. +// +// GitLab API docs: https://docs.gitlab.com/ce/api/issues.html#single-issues +func (s *IssuesService) GetIssue(pid interface{}, issue int, options ...OptionFunc) (*Issue, *Response, error) { + project, err := parseID(pid) + if err != nil { + return nil, nil, err + } + u := fmt.Sprintf("projects/%s/issues/%d", url.QueryEscape(project), issue) + + req, err := s.client.NewRequest("GET", u, nil, options) + if err != nil { + return nil, nil, err + } + + i := new(Issue) + resp, err := s.client.Do(req, i) + if err != nil { + return nil, resp, err + } + + return i, resp, err +} + +// CreateIssueOptions represents the available CreateIssue() options. +// +// GitLab API docs: https://docs.gitlab.com/ce/api/issues.html#new-issues +type CreateIssueOptions struct { + Title *string `url:"title,omitempty" json:"title,omitempty"` + Description *string `url:"description,omitempty" json:"description,omitempty"` + AssigneeID *int `url:"assignee_id,omitempty" json:"assignee_id,omitempty"` + MilestoneID *int `url:"milestone_id,omitempty" json:"milestone_id,omitempty"` + Labels Labels `url:"labels,comma,omitempty" json:"labels,omitempty"` +} + +// CreateIssue creates a new project issue. +// +// GitLab API docs: https://docs.gitlab.com/ce/api/issues.html#new-issues +func (s *IssuesService) CreateIssue(pid interface{}, opt *CreateIssueOptions, options ...OptionFunc) (*Issue, *Response, error) { + project, err := parseID(pid) + if err != nil { + return nil, nil, err + } + u := fmt.Sprintf("projects/%s/issues", url.QueryEscape(project)) + + req, err := s.client.NewRequest("POST", u, opt, options) + if err != nil { + return nil, nil, err + } + + i := new(Issue) + resp, err := s.client.Do(req, i) + if err != nil { + return nil, resp, err + } + + return i, resp, err +} + +// UpdateIssueOptions represents the available UpdateIssue() options. +// +// GitLab API docs: https://docs.gitlab.com/ce/api/issues.html#edit-issues +type UpdateIssueOptions struct { + Title *string `url:"title,omitempty" json:"title,omitempty"` + Description *string `url:"description,omitempty" json:"description,omitempty"` + AssigneeID *int `url:"assignee_id,omitempty" json:"assignee_id,omitempty"` + MilestoneID *int `url:"milestone_id,omitempty" json:"milestone_id,omitempty"` + Labels Labels `url:"labels,comma,omitempty" json:"labels,omitempty"` + StateEvent *string `url:"state_event,omitempty" json:"state_event,omitempty"` +} + +// UpdateIssue updates an existing project issue. This function is also used +// to mark an issue as closed. +// +// GitLab API docs: https://docs.gitlab.com/ce/api/issues.html#edit-issues +func (s *IssuesService) UpdateIssue(pid interface{}, issue int, opt *UpdateIssueOptions, options ...OptionFunc) (*Issue, *Response, error) { + project, err := parseID(pid) + if err != nil { + return nil, nil, err + } + u := fmt.Sprintf("projects/%s/issues/%d", url.QueryEscape(project), issue) + + req, err := s.client.NewRequest("PUT", u, opt, options) + if err != nil { + return nil, nil, err + } + + i := new(Issue) + resp, err := s.client.Do(req, i) + if err != nil { + return nil, resp, err + } + + return i, resp, err +} + +// DeleteIssue deletes a single project issue. +// +// GitLab API docs: https://docs.gitlab.com/ce/api/issues.html#delete-an-issue +func (s *IssuesService) DeleteIssue(pid interface{}, issue int, options ...OptionFunc) (*Response, error) { + project, err := parseID(pid) + if err != nil { + return nil, err + } + u := fmt.Sprintf("projects/%s/issues/%d", url.QueryEscape(project), issue) + + req, err := s.client.NewRequest("DELETE", u, nil, options) + if err != nil { + return nil, err + } + + return s.client.Do(req, nil) +} diff --git a/vendor/github.com/xanzy/go-gitlab/labels.go b/vendor/github.com/xanzy/go-gitlab/labels.go new file mode 100644 index 000000000..8d571b7e8 --- /dev/null +++ b/vendor/github.com/xanzy/go-gitlab/labels.go @@ -0,0 +1,164 @@ +// +// Copyright 2015, Sander van Harmelen +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +package gitlab + +import ( + "fmt" + "net/url" +) + +// LabelsService handles communication with the label related methods +// of the GitLab API. +// +// GitLab API docs: https://docs.gitlab.com/ce/api/labels.html +type LabelsService struct { + client *Client +} + +// Label represents a GitLab label. +// +// GitLab API docs: https://docs.gitlab.com/ce/api/labels.html +type Label struct { + Name string `json:"name"` + Color string `json:"color"` + Description string `json:"description"` + OpenIssuesCount int `json:"open_issues_count"` + ClosedIssuesCount int `json:"closed_issues_count"` + OpenMergeRequestsCount int `json:"open_merge_requests_count"` +} + +func (l Label) String() string { + return Stringify(l) +} + +// ListLabels gets all labels for given project. +// +// GitLab API docs: https://docs.gitlab.com/ce/api/labels.html#list-labels +func (s *LabelsService) ListLabels(pid interface{}, options ...OptionFunc) ([]*Label, *Response, error) { + project, err := parseID(pid) + if err != nil { + return nil, nil, err + } + u := fmt.Sprintf("projects/%s/labels", url.QueryEscape(project)) + + req, err := s.client.NewRequest("GET", u, nil, options) + if err != nil { + return nil, nil, err + } + + var l []*Label + resp, err := s.client.Do(req, &l) + if err != nil { + return nil, resp, err + } + + return l, resp, err +} + +// CreateLabelOptions represents the available CreateLabel() options. +// +// GitLab API docs: https://docs.gitlab.com/ce/api/labels.html#create-a-new-label +type CreateLabelOptions struct { + Name *string `url:"name,omitempty" json:"name,omitempty"` + Color *string `url:"color,omitempty" json:"color,omitempty"` + Description *string `url:"description,omitempty" json:"description,omitempty"` +} + +// CreateLabel creates a new label for given repository with given name and +// color. +// +// GitLab API docs: https://docs.gitlab.com/ce/api/labels.html#create-a-new-label +func (s *LabelsService) CreateLabel(pid interface{}, opt *CreateLabelOptions, options ...OptionFunc) (*Label, *Response, error) { + project, err := parseID(pid) + if err != nil { + return nil, nil, err + } + u := fmt.Sprintf("projects/%s/labels", url.QueryEscape(project)) + + req, err := s.client.NewRequest("POST", u, opt, options) + if err != nil { + return nil, nil, err + } + + l := new(Label) + resp, err := s.client.Do(req, l) + if err != nil { + return nil, resp, err + } + + return l, resp, err +} + +// DeleteLabelOptions represents the available DeleteLabel() options. +// +// GitLab API docs: https://docs.gitlab.com/ce/api/labels.html#delete-a-label +type DeleteLabelOptions struct { + Name *string `url:"name,omitempty" json:"name,omitempty"` +} + +// DeleteLabel deletes a label given by its name. +// +// GitLab API docs: https://docs.gitlab.com/ce/api/labels.html#delete-a-label +func (s *LabelsService) DeleteLabel(pid interface{}, opt *DeleteLabelOptions, options ...OptionFunc) (*Response, error) { + project, err := parseID(pid) + if err != nil { + return nil, err + } + u := fmt.Sprintf("projects/%s/labels", url.QueryEscape(project)) + + req, err := s.client.NewRequest("DELETE", u, opt, options) + if err != nil { + return nil, err + } + + return s.client.Do(req, nil) +} + +// UpdateLabelOptions represents the available UpdateLabel() options. +// +// GitLab API docs: https://docs.gitlab.com/ce/api/labels.html#delete-a-label +type UpdateLabelOptions struct { + Name *string `url:"name,omitempty" json:"name,omitempty"` + NewName *string `url:"new_name,omitempty" json:"new_name,omitempty"` + Color *string `url:"color,omitempty" json:"color,omitempty"` + Description *string `url:"description,omitempty" json:"description,omitempty"` +} + +// UpdateLabel updates an existing label with new name or now color. At least +// one parameter is required, to update the label. +// +// GitLab API docs: https://docs.gitlab.com/ce/api/labels.html#edit-an-existing-label +func (s *LabelsService) UpdateLabel(pid interface{}, opt *UpdateLabelOptions, options ...OptionFunc) (*Label, *Response, error) { + project, err := parseID(pid) + if err != nil { + return nil, nil, err + } + u := fmt.Sprintf("projects/%s/labels", url.QueryEscape(project)) + + req, err := s.client.NewRequest("PUT", u, opt, options) + if err != nil { + return nil, nil, err + } + + l := new(Label) + resp, err := s.client.Do(req, l) + if err != nil { + return nil, resp, err + } + + return l, resp, err +} diff --git a/vendor/github.com/xanzy/go-gitlab/merge_requests.go b/vendor/github.com/xanzy/go-gitlab/merge_requests.go new file mode 100644 index 000000000..1d154067b --- /dev/null +++ b/vendor/github.com/xanzy/go-gitlab/merge_requests.go @@ -0,0 +1,333 @@ +// +// Copyright 2015, Sander van Harmelen +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +package gitlab + +import ( + "fmt" + "net/url" + "time" +) + +// MergeRequestsService handles communication with the merge requests related +// methods of the GitLab API. +// +// GitLab API docs: https://docs.gitlab.com/ce/api/merge_requests.html +type MergeRequestsService struct { + client *Client +} + +// MergeRequest represents a GitLab merge request. +// +// GitLab API docs: https://docs.gitlab.com/ce/api/merge_requests.html +type MergeRequest struct { + ID int `json:"id"` + IID int `json:"iid"` + ProjectID int `json:"project_id"` + Title string `json:"title"` + Description string `json:"description"` + WorkInProgress bool `json:"work_in_progress"` + State string `json:"state"` + CreatedAt *time.Time `json:"created_at"` + UpdatedAt *time.Time `json:"updated_at"` + TargetBranch string `json:"target_branch"` + SourceBranch string `json:"source_branch"` + Upvotes int `json:"upvotes"` + Downvotes int `json:"downvotes"` + Author struct { + Name string `json:"name"` + Username string `json:"username"` + ID int `json:"id"` + State string `json:"state"` + AvatarURL string `json:"avatar_url"` + } `json:"author"` + Assignee struct { + Name string `json:"name"` + Username string `json:"username"` + ID int `json:"id"` + State string `json:"state"` + AvatarURL string `json:"avatar_url"` + } `json:"assignee"` + SourceProjectID int `json:"source_project_id"` + TargetProjectID int `json:"target_project_id"` + Labels []string `json:"labels"` + Milestone struct { + ID int `json:"id"` + Iid int `json:"iid"` + ProjectID int `json:"project_id"` + Title string `json:"title"` + Description string `json:"description"` + State string `json:"state"` + CreatedAt *time.Time `json:"created_at"` + UpdatedAt *time.Time `json:"updated_at"` + DueDate string `json:"due_date"` + } `json:"milestone"` + MergeWhenBuildSucceeds bool `json:"merge_when_build_succeeds"` + MergeStatus string `json:"merge_status"` + Subscribed bool `json:"subscribed"` + UserNotesCount int `json:"user_notes_count"` + SouldRemoveSourceBranch bool `json:"should_remove_source_branch"` + ForceRemoveSourceBranch bool `json:"force_remove_source_branch"` + Changes []struct { + OldPath string `json:"old_path"` + NewPath string `json:"new_path"` + AMode string `json:"a_mode"` + BMode string `json:"b_mode"` + Diff string `json:"diff"` + NewFile bool `json:"new_file"` + RenamedFile bool `json:"renamed_file"` + DeletedFile bool `json:"deleted_file"` + } `json:"changes"` + WebURL string `json:"web_url"` +} + +func (m MergeRequest) String() string { + return Stringify(m) +} + +// ListMergeRequestsOptions represents the available ListMergeRequests() +// options. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/merge_requests.html#list-merge-requests +type ListMergeRequestsOptions struct { + ListOptions + IID *int `url:"iid,omitempty" json:"iid,omitempty"` + State *string `url:"state,omitempty" json:"state,omitempty"` + OrderBy *string `url:"order_by,omitempty" json:"order_by,omitempty"` + Sort *string `url:"sort,omitempty" json:"sort,omitempty"` +} + +// ListMergeRequests gets all merge requests for this project. The state +// parameter can be used to get only merge requests with a given state (opened, +// closed, or merged) or all of them (all). The pagination parameters page and +// per_page can be used to restrict the list of merge requests. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/merge_requests.html#list-merge-requests +func (s *MergeRequestsService) ListMergeRequests(pid interface{}, opt *ListMergeRequestsOptions, options ...OptionFunc) ([]*MergeRequest, *Response, error) { + project, err := parseID(pid) + if err != nil { + return nil, nil, err + } + u := fmt.Sprintf("projects/%s/merge_requests", url.QueryEscape(project)) + + req, err := s.client.NewRequest("GET", u, opt, options) + if err != nil { + return nil, nil, err + } + + var m []*MergeRequest + resp, err := s.client.Do(req, &m) + if err != nil { + return nil, resp, err + } + + return m, resp, err +} + +// GetMergeRequest shows information about a single merge request. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/merge_requests.html#get-single-mr +func (s *MergeRequestsService) GetMergeRequest(pid interface{}, mergeRequest int, options ...OptionFunc) (*MergeRequest, *Response, error) { + project, err := parseID(pid) + if err != nil { + return nil, nil, err + } + u := fmt.Sprintf("projects/%s/merge_requests/%d", url.QueryEscape(project), mergeRequest) + + req, err := s.client.NewRequest("GET", u, nil, options) + if err != nil { + return nil, nil, err + } + + m := new(MergeRequest) + resp, err := s.client.Do(req, m) + if err != nil { + return nil, resp, err + } + + return m, resp, err +} + +// GetMergeRequestCommits gets a list of merge request commits. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/merge_requests.html#get-single-mr-commits +func (s *MergeRequestsService) GetMergeRequestCommits(pid interface{}, mergeRequest int, options ...OptionFunc) ([]*Commit, *Response, error) { + project, err := parseID(pid) + if err != nil { + return nil, nil, err + } + u := fmt.Sprintf("projects/%s/merge_requests/%d/commits", url.QueryEscape(project), mergeRequest) + + req, err := s.client.NewRequest("GET", u, nil, options) + if err != nil { + return nil, nil, err + } + + var c []*Commit + resp, err := s.client.Do(req, &c) + if err != nil { + return nil, resp, err + } + + return c, resp, err +} + +// GetMergeRequestChanges shows information about the merge request including +// its files and changes. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/merge_requests.html#get-single-mr-changes +func (s *MergeRequestsService) GetMergeRequestChanges(pid interface{}, mergeRequest int, options ...OptionFunc) (*MergeRequest, *Response, error) { + project, err := parseID(pid) + if err != nil { + return nil, nil, err + } + u := fmt.Sprintf("projects/%s/merge_requests/%d/changes", url.QueryEscape(project), mergeRequest) + + req, err := s.client.NewRequest("GET", u, nil, options) + if err != nil { + return nil, nil, err + } + + m := new(MergeRequest) + resp, err := s.client.Do(req, m) + if err != nil { + return nil, resp, err + } + + return m, resp, err +} + +// CreateMergeRequestOptions represents the available CreateMergeRequest() +// options. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/merge_requests.html#create-mr +type CreateMergeRequestOptions struct { + Title *string `url:"title,omitempty" json:"title,omitempty"` + Description *string `url:"description,omitempty" json:"description,omitempty"` + SourceBranch *string `url:"source_branch,omitemtpy" json:"source_branch,omitemtpy"` + TargetBranch *string `url:"target_branch,omitemtpy" json:"target_branch,omitemtpy"` + AssigneeID *int `url:"assignee_id,omitempty" json:"assignee_id,omitempty"` + TargetProjectID *int `url:"target_project_id,omitempty" json:"target_project_id,omitempty"` +} + +// CreateMergeRequest creates a new merge request. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/merge_requests.html#create-mr +func (s *MergeRequestsService) CreateMergeRequest(pid interface{}, opt *CreateMergeRequestOptions, options ...OptionFunc) (*MergeRequest, *Response, error) { + project, err := parseID(pid) + if err != nil { + return nil, nil, err + } + u := fmt.Sprintf("projects/%s/merge_requests", url.QueryEscape(project)) + + req, err := s.client.NewRequest("POST", u, opt, options) + if err != nil { + return nil, nil, err + } + + m := new(MergeRequest) + resp, err := s.client.Do(req, m) + if err != nil { + return nil, resp, err + } + + return m, resp, err +} + +// UpdateMergeRequestOptions represents the available UpdateMergeRequest() +// options. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/merge_requests.html#update-mr +type UpdateMergeRequestOptions struct { + Title *string `url:"title,omitempty" json:"title,omitempty"` + Description *string `url:"description,omitempty" json:"description,omitempty"` + TargetBranch *string `url:"target_branch,omitemtpy" json:"target_branch,omitemtpy"` + AssigneeID *int `url:"assignee_id,omitempty" json:"assignee_id,omitempty"` + StateEvent *string `url:"state_event,omitempty" json:"state_event,omitempty"` +} + +// UpdateMergeRequest updates an existing project milestone. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/merge_requests.html#update-mr +func (s *MergeRequestsService) UpdateMergeRequest(pid interface{}, mergeRequest int, opt *UpdateMergeRequestOptions, options ...OptionFunc) (*MergeRequest, *Response, error) { + project, err := parseID(pid) + if err != nil { + return nil, nil, err + } + u := fmt.Sprintf("projects/%s/merge_requests/%d", url.QueryEscape(project), mergeRequest) + + req, err := s.client.NewRequest("PUT", u, opt, options) + if err != nil { + return nil, nil, err + } + + m := new(MergeRequest) + resp, err := s.client.Do(req, m) + if err != nil { + return nil, resp, err + } + + return m, resp, err +} + +// AcceptMergeRequestOptions represents the available AcceptMergeRequest() +// options. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/merge_requests.html#accept-mr +type AcceptMergeRequestOptions struct { + MergeCommitMessage *string `url:"merge_commit_message,omitempty" json:"merge_commit_message,omitempty"` + ShouldRemoveSourceBranch *bool `url:"should_remove_source_branch,omitempty" json:"should_remove_source_branch,omitempty"` + MergeWhenBuildSucceeds *bool `url:"merge_when_build_succeeds,omitempty" json:"merge_when_build_succeeds,omitempty"` + Sha *string `url:"sha,omitempty" json:"sha,omitempty"` +} + +// AcceptMergeRequest merges changes submitted with MR using this API. If merge +// success you get 200 OK. If it has some conflicts and can not be merged - you +// get 405 and error message 'Branch cannot be merged'. If merge request is +// already merged or closed - you get 405 and error message 'Method Not Allowed' +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/merge_requests.html#accept-mr +func (s *MergeRequestsService) AcceptMergeRequest(pid interface{}, mergeRequest int, opt *AcceptMergeRequestOptions, options ...OptionFunc) (*MergeRequest, *Response, error) { + project, err := parseID(pid) + if err != nil { + return nil, nil, err + } + u := fmt.Sprintf("projects/%s/merge_requests/%d/merge", url.QueryEscape(project), mergeRequest) + + req, err := s.client.NewRequest("PUT", u, opt, options) + if err != nil { + return nil, nil, err + } + + m := new(MergeRequest) + resp, err := s.client.Do(req, m) + if err != nil { + return nil, resp, err + } + + return m, resp, err +} diff --git a/vendor/github.com/xanzy/go-gitlab/milestones.go b/vendor/github.com/xanzy/go-gitlab/milestones.go new file mode 100644 index 000000000..eeaf9cce2 --- /dev/null +++ b/vendor/github.com/xanzy/go-gitlab/milestones.go @@ -0,0 +1,216 @@ +// +// Copyright 2015, Sander van Harmelen +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +package gitlab + +import ( + "fmt" + "net/url" + "time" +) + +// MilestonesService handles communication with the milestone related methods +// of the GitLab API. +// +// GitLab API docs: https://docs.gitlab.com/ce/api/milestones.html +type MilestonesService struct { + client *Client +} + +// Milestone represents a GitLab milestone. +// +// GitLab API docs: https://docs.gitlab.com/ce/api/milestones.html +type Milestone struct { + ID int `json:"id"` + Iid int `json:"iid"` + ProjectID int `json:"project_id"` + Title string `json:"title"` + Description string `json:"description"` + StartDate string `json:"start_date"` + DueDate string `json:"due_date"` + State string `json:"state"` + UpdatedAt *time.Time `json:"updated_at"` + CreatedAt *time.Time `json:"created_at"` +} + +func (m Milestone) String() string { + return Stringify(m) +} + +// ListMilestonesOptions represents the available ListMilestones() options. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/milestones.html#list-project-milestones +type ListMilestonesOptions struct { + ListOptions + IID *int `url:"iid,omitempty" json:"iid,omitempty"` +} + +// ListMilestones returns a list of project milestones. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/milestones.html#list-project-milestones +func (s *MilestonesService) ListMilestones(pid interface{}, opt *ListMilestonesOptions, options ...OptionFunc) ([]*Milestone, *Response, error) { + project, err := parseID(pid) + if err != nil { + return nil, nil, err + } + u := fmt.Sprintf("projects/%s/milestones", url.QueryEscape(project)) + + req, err := s.client.NewRequest("GET", u, opt, options) + if err != nil { + return nil, nil, err + } + + var m []*Milestone + resp, err := s.client.Do(req, &m) + if err != nil { + return nil, resp, err + } + + return m, resp, err +} + +// GetMilestone gets a single project milestone. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/milestones.html#get-single-milestone +func (s *MilestonesService) GetMilestone(pid interface{}, milestone int, options ...OptionFunc) (*Milestone, *Response, error) { + project, err := parseID(pid) + if err != nil { + return nil, nil, err + } + u := fmt.Sprintf("projects/%s/milestones/%d", url.QueryEscape(project), milestone) + + req, err := s.client.NewRequest("GET", u, nil, options) + if err != nil { + return nil, nil, err + } + + m := new(Milestone) + resp, err := s.client.Do(req, m) + if err != nil { + return nil, resp, err + } + + return m, resp, err +} + +// CreateMilestoneOptions represents the available CreateMilestone() options. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/milestones.html#create-new-milestone +type CreateMilestoneOptions struct { + Title *string `url:"title,omitempty" json:"title,omitempty"` + Description *string `url:"description,omitempty" json:"description,omitempty"` + StartDate *string `url:"start_date,omitempty" json:"start_date,omitempty"` + DueDate *string `url:"due_date,omitempty" json:"due_date,omitempty"` +} + +// CreateMilestone creates a new project milestone. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/milestones.html#create-new-milestone +func (s *MilestonesService) CreateMilestone(pid interface{}, opt *CreateMilestoneOptions, options ...OptionFunc) (*Milestone, *Response, error) { + project, err := parseID(pid) + if err != nil { + return nil, nil, err + } + u := fmt.Sprintf("projects/%s/milestones", url.QueryEscape(project)) + + req, err := s.client.NewRequest("POST", u, opt, options) + if err != nil { + return nil, nil, err + } + + m := new(Milestone) + resp, err := s.client.Do(req, m) + if err != nil { + return nil, resp, err + } + + return m, resp, err +} + +// UpdateMilestoneOptions represents the available UpdateMilestone() options. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/milestones.html#edit-milestone +type UpdateMilestoneOptions struct { + Title *string `url:"title,omitempty" json:"title,omitempty"` + Description *string `url:"description,omitempty" json:"description,omitempty"` + StartDate *string `url:"start_date,omitempty" json:"start_date,omitempty"` + DueDate *string `url:"due_date,omitempty" json:"due_date,omitempty"` + StateEvent *string `url:"state_event,omitempty" json:"state_event,omitempty"` +} + +// UpdateMilestone updates an existing project milestone. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/milestones.html#edit-milestone +func (s *MilestonesService) UpdateMilestone(pid interface{}, milestone int, opt *UpdateMilestoneOptions, options ...OptionFunc) (*Milestone, *Response, error) { + project, err := parseID(pid) + if err != nil { + return nil, nil, err + } + u := fmt.Sprintf("projects/%s/milestones/%d", url.QueryEscape(project), milestone) + + req, err := s.client.NewRequest("PUT", u, opt, options) + if err != nil { + return nil, nil, err + } + + m := new(Milestone) + resp, err := s.client.Do(req, m) + if err != nil { + return nil, resp, err + } + + return m, resp, err +} + +// GetMilestoneIssuesOptions represents the available GetMilestoneIssues() options. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/milestones.html#get-all-issues-assigned-to-a-single-milestone +type GetMilestoneIssuesOptions struct { + ListOptions +} + +// GetMilestoneIssues gets all issues assigned to a single project milestone. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/milestones.html#get-all-issues-assigned-to-a-single-milestone +func (s *MilestonesService) GetMilestoneIssues(pid interface{}, milestone int, opt *GetMilestoneIssuesOptions, options ...OptionFunc) ([]*Issue, *Response, error) { + project, err := parseID(pid) + if err != nil { + return nil, nil, err + } + u := fmt.Sprintf("projects/%s/milestones/%d/issues", url.QueryEscape(project), milestone) + + req, err := s.client.NewRequest("GET", u, opt, options) + if err != nil { + return nil, nil, err + } + + var i []*Issue + resp, err := s.client.Do(req, &i) + if err != nil { + return nil, resp, err + } + + return i, resp, err +} diff --git a/vendor/github.com/xanzy/go-gitlab/namespaces.go b/vendor/github.com/xanzy/go-gitlab/namespaces.go new file mode 100644 index 000000000..d4b5e4508 --- /dev/null +++ b/vendor/github.com/xanzy/go-gitlab/namespaces.go @@ -0,0 +1,89 @@ +// +// Copyright 2015, Sander van Harmelen +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +package gitlab + +// NamespacesService handles communication with the namespace related methods +// of the GitLab API. +// +// GitLab API docs: https://docs.gitlab.com/ce/api/namespaces.html +type NamespacesService struct { + client *Client +} + +// Namespace represents a GitLab namespace. +// +// GitLab API docs: https://docs.gitlab.com/ce/api/namespaces.html +type Namespace struct { + ID int `json:"id"` + Path string `json:"path"` + Kind string `json:"kind"` +} + +func (n Namespace) String() string { + return Stringify(n) +} + +// ListNamespacesOptions represents the available ListNamespaces() options. +// +// GitLab API docs: https://docs.gitlab.com/ce/api/namespaces.html#list-namespaces +type ListNamespacesOptions struct { + ListOptions + Search *string `url:"search,omitempty" json:"search,omitempty"` +} + +// ListNamespaces gets a list of projects accessible by the authenticated user. +// +// GitLab API docs: https://docs.gitlab.com/ce/api/namespaces.html#list-namespaces +func (s *NamespacesService) ListNamespaces(opt *ListNamespacesOptions, options ...OptionFunc) ([]*Namespace, *Response, error) { + req, err := s.client.NewRequest("GET", "namespaces", opt, options) + if err != nil { + return nil, nil, err + } + + var n []*Namespace + resp, err := s.client.Do(req, &n) + if err != nil { + return nil, resp, err + } + + return n, resp, err +} + +// SearchNamespace gets all namespaces that match your string in their name +// or path. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/namespaces.html#search-for-namespace +func (s *NamespacesService) SearchNamespace(query string, options ...OptionFunc) ([]*Namespace, *Response, error) { + var q struct { + Search string `url:"search,omitempty" json:"search,omitempty"` + } + q.Search = query + + req, err := s.client.NewRequest("GET", "namespaces", &q, options) + if err != nil { + return nil, nil, err + } + + var n []*Namespace + resp, err := s.client.Do(req, &n) + if err != nil { + return nil, resp, err + } + + return n, resp, err +} diff --git a/vendor/github.com/xanzy/go-gitlab/notes.go b/vendor/github.com/xanzy/go-gitlab/notes.go new file mode 100644 index 000000000..c1836c2b8 --- /dev/null +++ b/vendor/github.com/xanzy/go-gitlab/notes.go @@ -0,0 +1,418 @@ +// +// Copyright 2015, Sander van Harmelen +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +package gitlab + +import ( + "fmt" + "net/url" + "time" +) + +// NotesService handles communication with the notes related methods +// of the GitLab API. +// +// GitLab API docs: https://docs.gitlab.com/ce/api/notes.html +type NotesService struct { + client *Client +} + +// Note represents a GitLab note. +// +// GitLab API docs: https://docs.gitlab.com/ce/api/notes.html +type Note struct { + ID int `json:"id"` + Body string `json:"body"` + Attachment string `json:"attachment"` + Title string `json:"title"` + FileName string `json:"file_name"` + Author struct { + ID int `json:"id"` + Username string `json:"username"` + Email string `json:"email"` + Name string `json:"name"` + State string `json:"state"` + CreatedAt *time.Time `json:"created_at"` + } `json:"author"` + ExpiresAt *time.Time `json:"expires_at"` + UpdatedAt *time.Time `json:"updated_at"` + CreatedAt *time.Time `json:"created_at"` +} + +func (n Note) String() string { + return Stringify(n) +} + +// ListIssueNotesOptions represents the available ListIssueNotes() options. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/notes.html#list-project-issue-notes +type ListIssueNotesOptions struct { + ListOptions +} + +// ListIssueNotes gets a list of all notes for a single issue. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/notes.html#list-project-issue-notes +func (s *NotesService) ListIssueNotes(pid interface{}, issue int, opt *ListIssueNotesOptions, options ...OptionFunc) ([]*Note, *Response, error) { + project, err := parseID(pid) + if err != nil { + return nil, nil, err + } + u := fmt.Sprintf("projects/%s/issues/%d/notes", url.QueryEscape(project), issue) + + req, err := s.client.NewRequest("GET", u, opt, options) + if err != nil { + return nil, nil, err + } + + var n []*Note + resp, err := s.client.Do(req, &n) + if err != nil { + return nil, resp, err + } + + return n, resp, err +} + +// GetIssueNote returns a single note for a specific project issue. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/notes.html#get-single-issue-note +func (s *NotesService) GetIssueNote(pid interface{}, issue int, note int, options ...OptionFunc) (*Note, *Response, error) { + project, err := parseID(pid) + if err != nil { + return nil, nil, err + } + u := fmt.Sprintf("projects/%s/issues/%d/notes/%d", url.QueryEscape(project), issue, note) + + req, err := s.client.NewRequest("GET", u, nil, options) + if err != nil { + return nil, nil, err + } + + n := new(Note) + resp, err := s.client.Do(req, n) + if err != nil { + return nil, resp, err + } + + return n, resp, err +} + +// CreateIssueNoteOptions represents the available CreateIssueNote() +// options. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/notes.html#create-new-issue-note +type CreateIssueNoteOptions struct { + Body *string `url:"body,omitempty" json:"body,omitempty"` +} + +// CreateIssueNote creates a new note to a single project issue. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/notes.html#create-new-issue-note +func (s *NotesService) CreateIssueNote(pid interface{}, issue int, opt *CreateIssueNoteOptions, options ...OptionFunc) (*Note, *Response, error) { + project, err := parseID(pid) + if err != nil { + return nil, nil, err + } + u := fmt.Sprintf("projects/%s/issues/%d/notes", url.QueryEscape(project), issue) + + req, err := s.client.NewRequest("POST", u, opt, options) + if err != nil { + return nil, nil, err + } + + n := new(Note) + resp, err := s.client.Do(req, n) + if err != nil { + return nil, resp, err + } + + return n, resp, err +} + +// UpdateIssueNoteOptions represents the available UpdateIssueNote() +// options. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/notes.html#modify-existing-issue-note +type UpdateIssueNoteOptions struct { + Body *string `url:"body,omitempty" json:"body,omitempty"` +} + +// UpdateIssueNote modifies existing note of an issue. +// +// https://docs.gitlab.com/ce/api/notes.html#modify-existing-issue-note +func (s *NotesService) UpdateIssueNote(pid interface{}, issue int, note int, opt *UpdateIssueNoteOptions, options ...OptionFunc) (*Note, *Response, error) { + project, err := parseID(pid) + if err != nil { + return nil, nil, err + } + u := fmt.Sprintf("projects/%s/issues/%d/notes/%d", url.QueryEscape(project), issue, note) + + req, err := s.client.NewRequest("PUT", u, opt, options) + if err != nil { + return nil, nil, err + } + + n := new(Note) + resp, err := s.client.Do(req, n) + if err != nil { + return nil, resp, err + } + + return n, resp, err +} + +// ListSnippetNotes gets a list of all notes for a single snippet. Snippet +// notes are comments users can post to a snippet. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/notes.html#list-all-snippet-notes +func (s *NotesService) ListSnippetNotes(pid interface{}, snippet int, options ...OptionFunc) ([]*Note, *Response, error) { + project, err := parseID(pid) + if err != nil { + return nil, nil, err + } + u := fmt.Sprintf("projects/%s/snippets/%d/notes", url.QueryEscape(project), snippet) + + req, err := s.client.NewRequest("GET", u, nil, options) + if err != nil { + return nil, nil, err + } + + var n []*Note + resp, err := s.client.Do(req, &n) + if err != nil { + return nil, resp, err + } + + return n, resp, err +} + +// GetSnippetNote returns a single note for a given snippet. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/notes.html#get-single-snippet-note +func (s *NotesService) GetSnippetNote(pid interface{}, snippet int, note int, options ...OptionFunc) (*Note, *Response, error) { + project, err := parseID(pid) + if err != nil { + return nil, nil, err + } + u := fmt.Sprintf("projects/%s/snippets/%d/notes/%d", url.QueryEscape(project), snippet, note) + + req, err := s.client.NewRequest("GET", u, nil, options) + if err != nil { + return nil, nil, err + } + + n := new(Note) + resp, err := s.client.Do(req, n) + if err != nil { + return nil, resp, err + } + + return n, resp, err +} + +// CreateSnippetNoteOptions represents the available CreateSnippetNote() +// options. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/notes.html#create-new-snippet-note +type CreateSnippetNoteOptions struct { + Body *string `url:"body,omitempty" json:"body,omitempty"` +} + +// CreateSnippetNote creates a new note for a single snippet. Snippet notes are +// comments users can post to a snippet. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/notes.html#create-new-snippet-note +func (s *NotesService) CreateSnippetNote(pid interface{}, snippet int, opt *CreateSnippetNoteOptions, options ...OptionFunc) (*Note, *Response, error) { + project, err := parseID(pid) + if err != nil { + return nil, nil, err + } + u := fmt.Sprintf("projects/%s/snippets/%d/notes", url.QueryEscape(project), snippet) + + req, err := s.client.NewRequest("POST", u, opt, options) + if err != nil { + return nil, nil, err + } + + n := new(Note) + resp, err := s.client.Do(req, n) + if err != nil { + return nil, resp, err + } + + return n, resp, err +} + +// UpdateSnippetNoteOptions represents the available UpdateSnippetNote() +// options. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/notes.html#modify-existing-snippet-note +type UpdateSnippetNoteOptions struct { + Body *string `url:"body,omitempty" json:"body,omitempty"` +} + +// UpdateSnippetNote modifies existing note of a snippet. +// +// https://docs.gitlab.com/ce/api/notes.html#modify-existing-snippet-note +func (s *NotesService) UpdateSnippetNote(pid interface{}, snippet int, note int, opt *UpdateSnippetNoteOptions, options ...OptionFunc) (*Note, *Response, error) { + project, err := parseID(pid) + if err != nil { + return nil, nil, err + } + u := fmt.Sprintf("projects/%s/snippets/%d/notes/%d", url.QueryEscape(project), snippet, note) + + req, err := s.client.NewRequest("PUT", u, opt, options) + if err != nil { + return nil, nil, err + } + + n := new(Note) + resp, err := s.client.Do(req, n) + if err != nil { + return nil, resp, err + } + + return n, resp, err +} + +// ListMergeRequestNotes gets a list of all notes for a single merge request. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/notes.html#list-all-merge-request-notes +func (s *NotesService) ListMergeRequestNotes(pid interface{}, mergeRequest int, options ...OptionFunc) ([]*Note, *Response, error) { + project, err := parseID(pid) + if err != nil { + return nil, nil, err + } + u := fmt.Sprintf("projects/%s/merge_requests/%d/notes", url.QueryEscape(project), mergeRequest) + + req, err := s.client.NewRequest("GET", u, nil, options) + if err != nil { + return nil, nil, err + } + + var n []*Note + resp, err := s.client.Do(req, &n) + if err != nil { + return nil, resp, err + } + + return n, resp, err +} + +// GetMergeRequestNote returns a single note for a given merge request. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/notes.html#get-single-merge-request-note +func (s *NotesService) GetMergeRequestNote(pid interface{}, mergeRequest int, note int, options ...OptionFunc) (*Note, *Response, error) { + project, err := parseID(pid) + if err != nil { + return nil, nil, err + } + u := fmt.Sprintf("projects/%s/merge_requests/%d/notes/%d", url.QueryEscape(project), mergeRequest, note) + + req, err := s.client.NewRequest("GET", u, nil, options) + if err != nil { + return nil, nil, err + } + + n := new(Note) + resp, err := s.client.Do(req, n) + if err != nil { + return nil, resp, err + } + + return n, resp, err +} + +// CreateMergeRequestNoteOptions represents the available +// CreateMergeRequestNote() options. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/notes.html#create-new-merge-request-note +type CreateMergeRequestNoteOptions struct { + Body *string `url:"body,omitempty" json:"body,omitempty"` +} + +// CreateMergeRequestNote creates a new note for a single merge request. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/notes.html#create-new-merge-request-note +func (s *NotesService) CreateMergeRequestNote(pid interface{}, mergeRequest int, opt *CreateMergeRequestNoteOptions, options ...OptionFunc) (*Note, *Response, error) { + project, err := parseID(pid) + if err != nil { + return nil, nil, err + } + u := fmt.Sprintf("projects/%s/merge_requests/%d/notes", url.QueryEscape(project), mergeRequest) + + req, err := s.client.NewRequest("POST", u, opt, options) + if err != nil { + return nil, nil, err + } + + n := new(Note) + resp, err := s.client.Do(req, n) + if err != nil { + return nil, resp, err + } + + return n, resp, err +} + +// UpdateMergeRequestNoteOptions represents the available +// UpdateMergeRequestNote() options. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/notes.html#modify-existing-merge-request-note +type UpdateMergeRequestNoteOptions struct { + Body *string `url:"body,omitempty" json:"body,omitempty"` +} + +// UpdateMergeRequestNote modifies existing note of a merge request. +// +// https://docs.gitlab.com/ce/api/notes.html#modify-existing-merge-request-note +func (s *NotesService) UpdateMergeRequestNote(pid interface{}, mergeRequest int, note int, opt *UpdateMergeRequestNoteOptions, options ...OptionFunc) (*Note, *Response, error) { + project, err := parseID(pid) + if err != nil { + return nil, nil, err + } + u := fmt.Sprintf( + "projects/%s/merge_requests/%d/notes/%d", url.QueryEscape(project), mergeRequest, note) + req, err := s.client.NewRequest("PUT", u, opt, options) + if err != nil { + return nil, nil, err + } + + n := new(Note) + resp, err := s.client.Do(req, n) + if err != nil { + return nil, resp, err + } + + return n, resp, err +} diff --git a/vendor/github.com/xanzy/go-gitlab/notifications.go b/vendor/github.com/xanzy/go-gitlab/notifications.go new file mode 100644 index 000000000..04424c293 --- /dev/null +++ b/vendor/github.com/xanzy/go-gitlab/notifications.go @@ -0,0 +1,214 @@ +package gitlab + +import ( + "errors" + "fmt" + "net/url" +) + +// NotificationSettingsService handles communication with the notification settings +// related methods of the GitLab API. +// +// GitLab API docs: https://docs.gitlab.com/ce/api/notification_settings.html +type NotificationSettingsService struct { + client *Client +} + +// NotificationSettings represents the Gitlab notification setting. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/notification_settings.html#notification-settings +type NotificationSettings struct { + Level NotificationLevelValue `json:"level"` + NotificationEmail string `json:"notification_email"` + Events *NotificationEvents `json:"events"` +} + +// NotificationEvents represents the avialable notification setting events. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/notification_settings.html#notification-settings +type NotificationEvents struct { + CloseIssue bool `json:"close_issue"` + CloseMergeRequest bool `json:"close_merge_request"` + FailedPipeline bool `json:"failed_pipeline"` + MergeMergeRequest bool `json:"merge_merge_request"` + NewIssue bool `json:"new_issue"` + NewMergeRequest bool `json:"new_merge_request"` + NewNote bool `json:"new_note"` + ReassignIssue bool `json:"reassign_issue"` + ReassignMergeRequest bool `json:"reassign_merge_request"` + ReopenIssue bool `json:"reopen_issue"` + ReopenMergeRequest bool `json:"reopen_merge_request"` + SuccessPipeline bool `json:"success_pipeline"` +} + +func (ns NotificationSettings) String() string { + return Stringify(ns) +} + +// GetGlobalSettings returns current notification settings and email address. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/notification_settings.html#global-notification-settings +func (s *NotificationSettingsService) GetGlobalSettings(options ...OptionFunc) (*NotificationSettings, *Response, error) { + u := "notification_settings" + + req, err := s.client.NewRequest("GET", u, nil, options) + if err != nil { + return nil, nil, err + } + + ns := new(NotificationSettings) + resp, err := s.client.Do(req, ns) + if err != nil { + return nil, resp, err + } + + return ns, resp, err +} + +// NotificationSettingsOptions represents the available options that can be passed +// to the API when updating the notification settings. +type NotificationSettingsOptions struct { + Level *NotificationLevelValue `url:"level,omitempty" json:"level,omitempty"` + NotificationEmail *string `url:"notification_email,omitempty" json:"notification_email,omitempty"` + CloseIssue *bool `url:"close_issue,omitempty" json:"close_issue,omitempty"` + CloseMergeRequest *bool `url:"close_merge_request,omitempty" json:"close_merge_request,omitempty"` + FailedPipeline *bool `url:"failed_pipeline,omitempty" json:"failed_pipeline,omitempty"` + MergeMergeRequest *bool `url:"merge_merge_request,omitempty" json:"merge_merge_request,omitempty"` + NewIssue *bool `url:"new_issue,omitempty" json:"new_issue,omitempty"` + NewMergeRequest *bool `url:"new_merge_request,omitempty" json:"new_merge_request,omitempty"` + NewNote *bool `url:"new_note,omitempty" json:"new_note,omitempty"` + ReassignIssue *bool `url:"reassign_issue,omitempty" json:"reassign_issue,omitempty"` + ReassignMergeRequest *bool `url:"reassign_merge_request,omitempty" json:"reassign_merge_request,omitempty"` + ReopenIssue *bool `url:"reopen_issue,omitempty" json:"reopen_issue,omitempty"` + ReopenMergeRequest *bool `url:"reopen_merge_request,omitempty" json:"reopen_merge_request,omitempty"` + SuccessPipeline *bool `url:"success_pipeline,omitempty" json:"success_pipeline,omitempty"` +} + +// UpdateGlobalSettings updates current notification settings and email address. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/notification_settings.html#update-global-notification-settings +func (s *NotificationSettingsService) UpdateGlobalSettings(opt *NotificationSettingsOptions, options ...OptionFunc) (*NotificationSettings, *Response, error) { + if opt.Level != nil && *opt.Level == GlobalNotificationLevel { + return nil, nil, errors.New( + "notification level 'global' is not valid for global notification settings") + } + + u := "notification_settings" + + req, err := s.client.NewRequest("PUT", u, opt, options) + if err != nil { + return nil, nil, err + } + + ns := new(NotificationSettings) + resp, err := s.client.Do(req, ns) + if err != nil { + return nil, resp, err + } + + return ns, resp, err +} + +// GetSettingsForGroup returns current group notification settings. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/notification_settings.html#group-project-level-notification-settings +func (s *NotificationSettingsService) GetSettingsForGroup(gid interface{}, options ...OptionFunc) (*NotificationSettings, *Response, error) { + group, err := parseID(gid) + if err != nil { + return nil, nil, err + } + u := fmt.Sprintf("groups/%s/notification_settings", url.QueryEscape(group)) + + req, err := s.client.NewRequest("GET", u, nil, options) + if err != nil { + return nil, nil, err + } + + ns := new(NotificationSettings) + resp, err := s.client.Do(req, ns) + if err != nil { + return nil, resp, err + } + + return ns, resp, err +} + +// GetSettingsForProject returns current project notification settings. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/notification_settings.html#group-project-level-notification-settings +func (s *NotificationSettingsService) GetSettingsForProject(pid interface{}, options ...OptionFunc) (*NotificationSettings, *Response, error) { + project, err := parseID(pid) + if err != nil { + return nil, nil, err + } + u := fmt.Sprintf("projects/%s/notification_settings", url.QueryEscape(project)) + + req, err := s.client.NewRequest("GET", u, nil, options) + if err != nil { + return nil, nil, err + } + + ns := new(NotificationSettings) + resp, err := s.client.Do(req, ns) + if err != nil { + return nil, resp, err + } + + return ns, resp, err +} + +// UpdateSettingsForGroup updates current group notification settings. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/notification_settings.html#update-group-project-level-notification-settings +func (s *NotificationSettingsService) UpdateSettingsForGroup(gid interface{}, opt *NotificationSettingsOptions, options ...OptionFunc) (*NotificationSettings, *Response, error) { + group, err := parseID(gid) + if err != nil { + return nil, nil, err + } + u := fmt.Sprintf("groups/%s/notification_settings", url.QueryEscape(group)) + + req, err := s.client.NewRequest("PUT", u, opt, options) + if err != nil { + return nil, nil, err + } + + ns := new(NotificationSettings) + resp, err := s.client.Do(req, ns) + if err != nil { + return nil, resp, err + } + + return ns, resp, err +} + +// UpdateSettingsForProject updates current project notification settings. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/notification_settings.html#update-group-project-level-notification-settings +func (s *NotificationSettingsService) UpdateSettingsForProject(pid interface{}, opt *NotificationSettingsOptions, options ...OptionFunc) (*NotificationSettings, *Response, error) { + project, err := parseID(pid) + if err != nil { + return nil, nil, err + } + u := fmt.Sprintf("projects/%s/notification_settings", url.QueryEscape(project)) + + req, err := s.client.NewRequest("PUT", u, opt, options) + if err != nil { + return nil, nil, err + } + + ns := new(NotificationSettings) + resp, err := s.client.Do(req, ns) + if err != nil { + return nil, resp, err + } + + return ns, resp, err +} diff --git a/vendor/github.com/xanzy/go-gitlab/pipelines.go b/vendor/github.com/xanzy/go-gitlab/pipelines.go new file mode 100644 index 000000000..4ade3fce9 --- /dev/null +++ b/vendor/github.com/xanzy/go-gitlab/pipelines.go @@ -0,0 +1,191 @@ +// +// Copyright 2017, Igor Varavko +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +package gitlab + +import ( + "fmt" + "net/url" + "time" +) + +// PipelinesService handles communication with the repositories related +// methods of the GitLab API. +// +// GitLab API docs: https://docs.gitlab.com/ce/api/pipelines.html +type PipelinesService struct { + client *Client +} + +// Pipeline represents a GitLab pipeline. +// +// GitLab API docs: https://docs.gitlab.com/ce/api/pipelines.html +type Pipeline struct { + ID int `json:"id"` + Status string `json:"status"` + Ref string `json:"ref"` + Sha string `json:"sha"` + BeforeSha string `json:"before_sha"` + Tag bool `json:"tag"` + YamlErrors string `json:"yaml_errors"` + User struct { + Name string `json:"name"` + Username string `json:"username"` + ID int `json:"id"` + State string `json:"state"` + AvatarURL string `json:"avatar_url"` + WebURL string `json:"web_url"` + } + UpdatedAt *time.Time `json:"updated_at"` + CreatedAt *time.Time `json:"created_at"` + StartedAt *time.Time `json:"started_at"` + FinishedAt *time.Time `json:"finished_at"` + CommittedAt *time.Time `json:"committed_at"` + Duration int `json:"duration"` + Coverage string `json:"coverage"` +} + +func (i Pipeline) String() string { + return Stringify(i) +} + +// ListProjectPipelines gets a list of project piplines. +// +// GitLab API docs: https://docs.gitlab.com/ce/api/pipelines.html#list-project-pipelines +func (s *PipelinesService) ListProjectPipelines(pid interface{}, options ...OptionFunc) ([]*Pipeline, *Response, error) { + project, err := parseID(pid) + if err != nil { + return nil, nil, err + } + u := fmt.Sprintf("projects/%s/pipelines", url.QueryEscape(project)) + + req, err := s.client.NewRequest("GET", u, nil, options) + if err != nil { + return nil, nil, err + } + + var p []*Pipeline + resp, err := s.client.Do(req, &p) + if err != nil { + return nil, resp, err + } + return p, resp, err +} + +// GetPipeline gets a single project pipeline. +// +// GitLab API docs: https://docs.gitlab.com/ce/api/pipelines.html#get-a-single-pipeline +func (s *PipelinesService) GetPipeline(pid interface{}, pipeline int, options ...OptionFunc) (*Pipeline, *Response, error) { + project, err := parseID(pid) + if err != nil { + return nil, nil, err + } + u := fmt.Sprintf("projects/%s/pipelines/%d", url.QueryEscape(project), pipeline) + + req, err := s.client.NewRequest("GET", u, nil, options) + if err != nil { + return nil, nil, err + } + + p := new(Pipeline) + resp, err := s.client.Do(req, p) + if err != nil { + return nil, resp, err + } + + return p, resp, err +} + +// CreatePipelineOptions represents the available CreatePipeline() options. +// +// GitLab API docs: https://docs.gitlab.com/ce/api/pipelines.html#create-a-new-pipeline +type CreatePipelineOptions struct { + Ref *string `url:"ref,omitempty" json:"ref"` +} + +// CreatePipeline creates a new project pipeline. +// +// GitLab API docs: https://docs.gitlab.com/ce/api/pipelines.html#create-a-new-pipeline +func (s *PipelinesService) CreatePipeline(pid interface{}, opt *CreatePipelineOptions, options ...OptionFunc) (*Pipeline, *Response, error) { + project, err := parseID(pid) + if err != nil { + return nil, nil, err + } + u := fmt.Sprintf("projects/%s/pipeline", url.QueryEscape(project)) + + req, err := s.client.NewRequest("POST", u, opt, options) + if err != nil { + return nil, nil, err + } + + p := new(Pipeline) + resp, err := s.client.Do(req, p) + if err != nil { + return nil, resp, err + } + + return p, resp, err +} + +// RetryPipelineBuild retries failed builds in a pipeline +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/pipelines.html#retry-failed-builds-in-a-pipeline +func (s *PipelinesService) RetryPipelineBuild(pid interface{}, pipelineID int, options ...OptionFunc) (*Pipeline, *Response, error) { + project, err := parseID(pid) + if err != nil { + return nil, nil, err + } + u := fmt.Sprintf("projects/%s/pipelines/%d/retry", project, pipelineID) + + req, err := s.client.NewRequest("POST", u, nil, options) + if err != nil { + return nil, nil, err + } + + p := new(Pipeline) + resp, err := s.client.Do(req, p) + if err != nil { + return nil, resp, err + } + + return p, resp, err +} + +// CancelPipelineBuild cancels a pipeline builds +// +// GitLab API docs: +//https://docs.gitlab.com/ce/api/pipelines.html#cancel-a-pipelines-builds +func (s *PipelinesService) CancelPipelineBuild(pid interface{}, pipelineID int, options ...OptionFunc) (*Pipeline, *Response, error) { + project, err := parseID(pid) + if err != nil { + return nil, nil, err + } + u := fmt.Sprintf("projects/%s/pipelines/%d/cancel", project, pipelineID) + + req, err := s.client.NewRequest("POST", u, nil, options) + if err != nil { + return nil, nil, err + } + + p := new(Pipeline) + resp, err := s.client.Do(req, p) + if err != nil { + return nil, resp, err + } + + return p, resp, err +} diff --git a/vendor/github.com/xanzy/go-gitlab/project_snippets.go b/vendor/github.com/xanzy/go-gitlab/project_snippets.go new file mode 100644 index 000000000..65dab67be --- /dev/null +++ b/vendor/github.com/xanzy/go-gitlab/project_snippets.go @@ -0,0 +1,232 @@ +// +// Copyright 2015, Sander van Harmelen +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +package gitlab + +import ( + "bytes" + "fmt" + "net/url" + "time" +) + +// ProjectSnippetsService handles communication with the project snippets +// related methods of the GitLab API. +// +// GitLab API docs: https://docs.gitlab.com/ce/api/project_snippets.html +type ProjectSnippetsService struct { + client *Client +} + +// Snippet represents a GitLab project snippet. +// +// GitLab API docs: https://docs.gitlab.com/ce/api/project_snippets.html +type Snippet struct { + ID int `json:"id"` + Title string `json:"title"` + FileName string `json:"file_name"` + Author struct { + ID int `json:"id"` + Username string `json:"username"` + Email string `json:"email"` + Name string `json:"name"` + State string `json:"state"` + CreatedAt *time.Time `json:"created_at"` + } `json:"author"` + ExpiresAt *time.Time `json:"expires_at"` + UpdatedAt *time.Time `json:"updated_at"` + CreatedAt *time.Time `json:"created_at"` +} + +func (s Snippet) String() string { + return Stringify(s) +} + +// ListSnippetsOptions represents the available ListSnippets() options. +// +// GitLab API docs: https://docs.gitlab.com/ce/api/project_snippets.html#list-snippets +type ListSnippetsOptions struct { + ListOptions +} + +// ListSnippets gets a list of project snippets. +// +// GitLab API docs: https://docs.gitlab.com/ce/api/project_snippets.html#list-snippets +func (s *ProjectSnippetsService) ListSnippets(pid interface{}, opt *ListSnippetsOptions, options ...OptionFunc) ([]*Snippet, *Response, error) { + project, err := parseID(pid) + if err != nil { + return nil, nil, err + } + u := fmt.Sprintf("projects/%s/snippets", url.QueryEscape(project)) + + req, err := s.client.NewRequest("GET", u, opt, options) + if err != nil { + return nil, nil, err + } + + var ps []*Snippet + resp, err := s.client.Do(req, &ps) + if err != nil { + return nil, resp, err + } + + return ps, resp, err +} + +// GetSnippet gets a single project snippet +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/project_snippets.html#single-snippet +func (s *ProjectSnippetsService) GetSnippet(pid interface{}, snippet int, options ...OptionFunc) (*Snippet, *Response, error) { + project, err := parseID(pid) + if err != nil { + return nil, nil, err + } + u := fmt.Sprintf("projects/%s/snippets/%d", url.QueryEscape(project), snippet) + + req, err := s.client.NewRequest("GET", u, nil, options) + if err != nil { + return nil, nil, err + } + + ps := new(Snippet) + resp, err := s.client.Do(req, ps) + if err != nil { + return nil, resp, err + } + + return ps, resp, err +} + +// CreateSnippetOptions represents the available CreateSnippet() options. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/project_snippets.html#create-new-snippet +type CreateSnippetOptions struct { + Title *string `url:"title,omitempty" json:"title,omitempty"` + FileName *string `url:"file_name,omitempty" json:"file_name,omitempty"` + Code *string `url:"code,omitempty" json:"code,omitempty"` + VisibilityLevel *VisibilityLevelValue `url:"visibility_level,omitempty" json:"visibility_level,omitempty"` +} + +// CreateSnippet creates a new project snippet. The user must have permission +// to create new snippets. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/project_snippets.html#create-new-snippet +func (s *ProjectSnippetsService) CreateSnippet(pid interface{}, opt *CreateSnippetOptions, options ...OptionFunc) (*Snippet, *Response, error) { + project, err := parseID(pid) + if err != nil { + return nil, nil, err + } + u := fmt.Sprintf("projects/%s/snippets", url.QueryEscape(project)) + + req, err := s.client.NewRequest("POST", u, opt, options) + if err != nil { + return nil, nil, err + } + + ps := new(Snippet) + resp, err := s.client.Do(req, ps) + if err != nil { + return nil, resp, err + } + + return ps, resp, err +} + +// UpdateSnippetOptions represents the available UpdateSnippet() options. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/project_snippets.html#update-snippet +type UpdateSnippetOptions struct { + Title *string `url:"title,omitempty" json:"title,omitempty"` + FileName *string `url:"file_name,omitempty" json:"file_name,omitempty"` + Code *string `url:"code,omitempty" json:"code,omitempty"` + VisibilityLevel *VisibilityLevelValue `url:"visibility_level,omitempty" json:"visibility_level,omitempty"` +} + +// UpdateSnippet updates an existing project snippet. The user must have +// permission to change an existing snippet. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/project_snippets.html#update-snippet +func (s *ProjectSnippetsService) UpdateSnippet(pid interface{}, snippet int, opt *UpdateSnippetOptions, options ...OptionFunc) (*Snippet, *Response, error) { + project, err := parseID(pid) + if err != nil { + return nil, nil, err + } + u := fmt.Sprintf("projects/%s/snippets/%d", url.QueryEscape(project), snippet) + + req, err := s.client.NewRequest("PUT", u, opt, options) + if err != nil { + return nil, nil, err + } + + ps := new(Snippet) + resp, err := s.client.Do(req, ps) + if err != nil { + return nil, resp, err + } + + return ps, resp, err +} + +// DeleteSnippet deletes an existing project snippet. This is an idempotent +// function and deleting a non-existent snippet still returns a 200 OK status +// code. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/project_snippets.html#delete-snippet +func (s *ProjectSnippetsService) DeleteSnippet(pid interface{}, snippet int, options ...OptionFunc) (*Response, error) { + project, err := parseID(pid) + if err != nil { + return nil, err + } + u := fmt.Sprintf("projects/%s/snippets/%d", url.QueryEscape(project), snippet) + + req, err := s.client.NewRequest("DELETE", u, nil, options) + if err != nil { + return nil, err + } + + return s.client.Do(req, nil) +} + +// SnippetContent returns the raw project snippet as plain text. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/project_snippets.html#snippet-content +func (s *ProjectSnippetsService) SnippetContent(pid interface{}, snippet int, options ...OptionFunc) ([]byte, *Response, error) { + project, err := parseID(pid) + if err != nil { + return nil, nil, err + } + u := fmt.Sprintf("projects/%s/snippets/%d/raw", url.QueryEscape(project), snippet) + + req, err := s.client.NewRequest("GET", u, nil, options) + if err != nil { + return nil, nil, err + } + + var b bytes.Buffer + resp, err := s.client.Do(req, &b) + if err != nil { + return nil, resp, err + } + + return b.Bytes(), resp, err +} diff --git a/vendor/github.com/xanzy/go-gitlab/projects.go b/vendor/github.com/xanzy/go-gitlab/projects.go new file mode 100644 index 000000000..9abc6b141 --- /dev/null +++ b/vendor/github.com/xanzy/go-gitlab/projects.go @@ -0,0 +1,981 @@ +// +// Copyright 2015, Sander van Harmelen +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +package gitlab + +import ( + "fmt" + "net/url" + "time" +) + +// ProjectsService handles communication with the repositories related methods +// of the GitLab API. +// +// GitLab API docs: https://docs.gitlab.com/ce/api/projects.html +type ProjectsService struct { + client *Client +} + +// Project represents a GitLab project. +// +// GitLab API docs: https://docs.gitlab.com/ce/api/projects.html +type Project struct { + ID int `json:"id"` + Description string `json:"description"` + DefaultBranch string `json:"default_branch"` + Public bool `json:"public"` + VisibilityLevel VisibilityLevelValue `json:"visibility_level"` + SSHURLToRepo string `json:"ssh_url_to_repo"` + HTTPURLToRepo string `json:"http_url_to_repo"` + WebURL string `json:"web_url"` + TagList []string `json:"tag_list"` + Owner *User `json:"owner"` + Name string `json:"name"` + NameWithNamespace string `json:"name_with_namespace"` + Path string `json:"path"` + PathWithNamespace string `json:"path_with_namespace"` + IssuesEnabled bool `json:"issues_enabled"` + OpenIssuesCount int `json:"open_issues_count"` + MergeRequestsEnabled bool `json:"merge_requests_enabled"` + ApprovalsBeforeMerge int `json:"approvals_before_merge"` + BuildsEnabled bool `json:"builds_enabled"` + WikiEnabled bool `json:"wiki_enabled"` + SnippetsEnabled bool `json:"snippets_enabled"` + ContainerRegistryEnabled bool `json:"container_registry_enabled"` + CreatedAt *time.Time `json:"created_at,omitempty"` + LastActivityAt *time.Time `json:"last_activity_at,omitempty"` + CreatorID int `json:"creator_id"` + Namespace *ProjectNamespace `json:"namespace"` + Permissions *Permissions `json:"permissions"` + Archived bool `json:"archived"` + AvatarURL string `json:"avatar_url"` + SharedRunnersEnabled bool `json:"shared_runners_enabled"` + ForksCount int `json:"forks_count"` + StarCount int `json:"star_count"` + RunnersToken string `json:"runners_token"` + PublicBuilds bool `json:"public_builds"` + OnlyAllowMergeIfBuildSucceeds bool `json:"only_allow_merge_if_build_succeeds"` + OnlyAllowMergeIfAllDiscussionsAreResolved bool `json:"only_allow_merge_if_all_discussions_are_resolved"` + LFSEnabled bool `json:"lfs_enabled"` + RequestAccessEnabled bool `json:"request_access_enabled"` + SharedWithGroups []struct { + GroupID int `json:"group_id"` + GroupName string `json:"group_name"` + GroupAccessLevel int `json:"group_access_level"` + } `json:"shared_with_groups"` + Statistics *ProjectStatistics `json:"statistics"` +} + +// Repository represents a repository. +type Repository struct { + Name string `json:"name"` + Description string `json:"description"` + WebURL string `json:"web_url"` + AvatarURL string `json:"avatar_url"` + GitSSHURL string `json:"git_ssh_url"` + GitHTTPURL string `json:"git_http_url"` + Namespace string `json:"namespace"` + VisibilityLevel int `json:"visibility_level"` + PathWithNamespace string `json:"path_with_namespace"` + DefaultBranch string `json:"default_branch"` + Homepage string `json:"homepage"` + URL string `json:"url"` + SSHURL string `json:"ssh_url"` + HTTPURL string `json:"http_url"` +} + +// ProjectNamespace represents a project namespace. +type ProjectNamespace struct { + CreatedAt *time.Time `json:"created_at"` + Description string `json:"description"` + ID int `json:"id"` + Name string `json:"name"` + OwnerID int `json:"owner_id"` + Path string `json:"path"` + UpdatedAt *time.Time `json:"updated_at"` +} + +// StorageStatistics represents a statistics record for a group or project. +type StorageStatistics struct { + StorageSize int64 `json:"storage_size"` + RepositorySize int64 `json:"repository_size"` + LfsObjectsSize int64 `json:"lfs_objects_size"` + BuildArtifactsSize int64 `json:"build_artifacts_size"` +} + +// ProjectStatistics represents a statistics record for a project. +type ProjectStatistics struct { + StorageStatistics + CommitCount int `json:"commit_count"` +} + +// Permissions represents premissions. +type Permissions struct { + ProjectAccess *ProjectAccess `json:"project_access"` + GroupAccess *GroupAccess `json:"group_access"` +} + +// ProjectAccess represents project access. +type ProjectAccess struct { + AccessLevel AccessLevelValue `json:"access_level"` + NotificationLevel NotificationLevelValue `json:"notification_level"` +} + +// GroupAccess represents group access. +type GroupAccess struct { + AccessLevel AccessLevelValue `json:"access_level"` + NotificationLevel NotificationLevelValue `json:"notification_level"` +} + +func (s Project) String() string { + return Stringify(s) +} + +// ListProjectsOptions represents the available ListProjects() options. +// +// GitLab API docs: https://docs.gitlab.com/ce/api/projects.html#list-projects +type ListProjectsOptions struct { + ListOptions + Archived *bool `url:"archived,omitempty" json:"archived,omitempty"` + OrderBy *string `url:"order_by,omitempty" json:"order_by,omitempty"` + Sort *string `url:"sort,omitempty" json:"sort,omitempty"` + Search *string `url:"search,omitempty" json:"search,omitempty"` + Simple *bool `url:"simple,omitempty" json:"simple,omitempty"` + Visibility *string `url:"visibility,omitempty" json:"visibility,omitempty"` + Statistics *bool `url:"statistics,omitempty" json:"statistics,omitempty"` +} + +// ListProjects gets a list of projects accessible by the authenticated user. +// +// GitLab API docs: https://docs.gitlab.com/ce/api/projects.html#list-projects +func (s *ProjectsService) ListProjects(opt *ListProjectsOptions, options ...OptionFunc) ([]*Project, *Response, error) { + req, err := s.client.NewRequest("GET", "projects", opt, options) + if err != nil { + return nil, nil, err + } + + var p []*Project + resp, err := s.client.Do(req, &p) + if err != nil { + return nil, resp, err + } + + return p, resp, err +} + +// ListOwnedProjects gets a list of projects which are owned by the +// authenticated user. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/projects.html#list-owned-projects +func (s *ProjectsService) ListOwnedProjects(opt *ListProjectsOptions, options ...OptionFunc) ([]*Project, *Response, error) { + req, err := s.client.NewRequest("GET", "projects/owned", opt, options) + if err != nil { + return nil, nil, err + } + + var p []*Project + resp, err := s.client.Do(req, &p) + if err != nil { + return nil, resp, err + } + + return p, resp, err +} + +// ListStarredProjects gets a list of projects which are starred by the +// authenticated user. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/projects.html#list-starred-projects +func (s *ProjectsService) ListStarredProjects(opt *ListProjectsOptions, options ...OptionFunc) ([]*Project, *Response, error) { + req, err := s.client.NewRequest("GET", "projects/starred", opt, options) + if err != nil { + return nil, nil, err + } + + var p []*Project + resp, err := s.client.Do(req, &p) + if err != nil { + return nil, resp, err + } + + return p, resp, err +} + +// ListAllProjects gets a list of all GitLab projects (admin only). +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/projects.html#list-all-projects +func (s *ProjectsService) ListAllProjects(opt *ListProjectsOptions, options ...OptionFunc) ([]*Project, *Response, error) { + req, err := s.client.NewRequest("GET", "projects/all", opt, options) + if err != nil { + return nil, nil, err + } + + var p []*Project + resp, err := s.client.Do(req, &p) + if err != nil { + return nil, resp, err + } + + return p, resp, err +} + +// GetProject gets a specific project, identified by project ID or +// NAMESPACE/PROJECT_NAME, which is owned by the authenticated user. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/projects.html#get-single-project +func (s *ProjectsService) GetProject(pid interface{}, options ...OptionFunc) (*Project, *Response, error) { + project, err := parseID(pid) + if err != nil { + return nil, nil, err + } + u := fmt.Sprintf("projects/%s", url.QueryEscape(project)) + + req, err := s.client.NewRequest("GET", u, nil, options) + if err != nil { + return nil, nil, err + } + + p := new(Project) + resp, err := s.client.Do(req, p) + if err != nil { + return nil, resp, err + } + + return p, resp, err +} + +// SearchProjectsOptions represents the available SearchProjects() options. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/projects.html#search-for-projects-by-name +type SearchProjectsOptions struct { + ListOptions + OrderBy *string `url:"order_by,omitempty" json:"order_by,omitempty"` + Sort *string `url:"sort,omitempty" json:"sort,omitempty"` +} + +// SearchProjects searches for projects by name which are accessible to the +// authenticated user. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/projects.html#search-for-projects-by-name +func (s *ProjectsService) SearchProjects(query string, opt *SearchProjectsOptions, options ...OptionFunc) ([]*Project, *Response, error) { + u := fmt.Sprintf("projects/search/%s", query) + + req, err := s.client.NewRequest("GET", u, opt, options) + if err != nil { + return nil, nil, err + } + + var p []*Project + resp, err := s.client.Do(req, &p) + if err != nil { + return nil, resp, err + } + + return p, resp, err +} + +// ProjectEvent represents a GitLab project event. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/projects.html#get-project-events +type ProjectEvent struct { + Title interface{} `json:"title"` + ProjectID int `json:"project_id"` + ActionName string `json:"action_name"` + TargetID interface{} `json:"target_id"` + TargetType interface{} `json:"target_type"` + AuthorID int `json:"author_id"` + AuthorUsername string `json:"author_username"` + Data struct { + Before string `json:"before"` + After string `json:"after"` + Ref string `json:"ref"` + UserID int `json:"user_id"` + UserName string `json:"user_name"` + Repository *Repository `json:"repository"` + Commits []*Commit `json:"commits"` + TotalCommitsCount int `json:"total_commits_count"` + } `json:"data"` + TargetTitle interface{} `json:"target_title"` +} + +func (s ProjectEvent) String() string { + return Stringify(s) +} + +// GetProjectEventsOptions represents the available GetProjectEvents() options. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/projects.html#get-project-events +type GetProjectEventsOptions struct { + ListOptions +} + +// GetProjectEvents gets the events for the specified project. Sorted from +// newest to latest. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/projects.html#get-project-events +func (s *ProjectsService) GetProjectEvents(pid interface{}, opt *GetProjectEventsOptions, options ...OptionFunc) ([]*ProjectEvent, *Response, error) { + project, err := parseID(pid) + if err != nil { + return nil, nil, err + } + u := fmt.Sprintf("projects/%s/events", url.QueryEscape(project)) + + req, err := s.client.NewRequest("GET", u, opt, options) + if err != nil { + return nil, nil, err + } + + var p []*ProjectEvent + resp, err := s.client.Do(req, &p) + if err != nil { + return nil, resp, err + } + + return p, resp, err +} + +// CreateProjectOptions represents the available CreateProjects() options. +// +// GitLab API docs: https://docs.gitlab.com/ce/api/projects.html#create-project +type CreateProjectOptions struct { + Name *string `url:"name,omitempty" json:"name,omitempty"` + Path *string `url:"path,omitempty" json:"path,omitempty"` + NamespaceID *int `url:"namespace_id,omitempty" json:"namespace_id,omitempty"` + Description *string `url:"description,omitempty" json:"description,omitempty"` + IssuesEnabled *bool `url:"issues_enabled,omitempty" json:"issues_enabled,omitempty"` + MergeRequestsEnabled *bool `url:"merge_requests_enabled,omitempty" json:"merge_requests_enabled,omitempty"` + BuildsEnabled *bool `url:"builds_enabled,omitempty" json:"builds_enabled,omitempty"` + WikiEnabled *bool `url:"wiki_enabled,omitempty" json:"wiki_enabled,omitempty"` + SnippetsEnabled *bool `url:"snippets_enabled,omitempty" json:"snippets_enabled,omitempty"` + ContainerRegistryEnabled *bool `url:"container_registry_enabled,omitempty" json:"container_registry_enabled,omitempty"` + SharedRunnersEnabled *bool `url:"shared_runners_enabled,omitempty" json:"shared_runners_enabled,omitempty"` + Public *bool `url:"public,omitempty" json:"public,omitempty"` + VisibilityLevel *VisibilityLevelValue `url:"visibility_level,omitempty" json:"visibility_level,omitempty"` + ImportURL *string `url:"import_url,omitempty" json:"import_url,omitempty"` + PublicBuilds *bool `url:"public_builds,omitempty" json:"public_builds,omitempty"` + OnlyAllowMergeIfBuildSucceeds *bool `url:"only_allow_merge_if_build_succeeds,omitempty" json:"only_allow_merge_if_build_succeeds,omitempty"` + LFSEnabled *bool `url:"lfs_enabled,omitempty" json:"lfs_enabled,omitempty"` + RequestAccessEnabled *bool `url:"request_access_enabled,omitempty" json:"request_access_enabled,omitempty"` +} + +// CreateProject creates a new project owned by the authenticated user. +// +// GitLab API docs: https://docs.gitlab.com/ce/api/projects.html#create-project +func (s *ProjectsService) CreateProject(opt *CreateProjectOptions, options ...OptionFunc) (*Project, *Response, error) { + req, err := s.client.NewRequest("POST", "projects", opt, options) + if err != nil { + return nil, nil, err + } + + p := new(Project) + resp, err := s.client.Do(req, p) + if err != nil { + return nil, resp, err + } + + return p, resp, err +} + +// CreateProjectForUserOptions represents the available CreateProjectForUser() +// options. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/projects.html#create-project-for-user +type CreateProjectForUserOptions struct { + Name *string `url:"name,omitempty" json:"name,omitempty"` + Description *string `url:"description,omitempty" json:"description,omitempty"` + DefaultBranch *string `url:"default_branch,omitempty" json:"default_branch,omitempty"` + IssuesEnabled *bool `url:"issues_enabled,omitempty" json:"issues_enabled,omitempty"` + MergeRequestsEnabled *bool `url:"merge_requests_enabled,omitempty" json:"merge_requests_enabled,omitempty"` + WikiEnabled *bool `url:"wiki_enabled,omitempty" json:"wiki_enabled,omitempty"` + SnippetsEnabled *bool `url:"snippets_enabled,omitempty" json:"snippets_enabled,omitempty"` + Public *bool `url:"public,omitempty" json:"public,omitempty"` + VisibilityLevel *VisibilityLevelValue `url:"visibility_level,omitempty" json:"visibility_level,omitempty"` + ImportURL *string `url:"import_url,omitempty" json:"import_url,omitempty"` +} + +// CreateProjectForUser creates a new project owned by the specified user. +// Available only for admins. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/projects.html#create-project-for-user +func (s *ProjectsService) CreateProjectForUser(user int, opt *CreateProjectForUserOptions, options ...OptionFunc) (*Project, *Response, error) { + u := fmt.Sprintf("projects/user/%d", user) + + req, err := s.client.NewRequest("POST", u, opt, options) + if err != nil { + return nil, nil, err + } + + p := new(Project) + resp, err := s.client.Do(req, p) + if err != nil { + return nil, resp, err + } + + return p, resp, err +} + +// EditProjectOptions represents the available EditProject() options. +// +// GitLab API docs: https://docs.gitlab.com/ce/api/projects.html#edit-project +type EditProjectOptions struct { + Name *string `url:"name,omitempty" json:"name,omitempty"` + Path *string `url:"path,omitempty" json:"path,omitempty"` + Description *string `url:"description,omitempty" json:"description,omitempty"` + DefaultBranch *string `url:"default_branch,omitempty" json:"default_branch,omitempty"` + IssuesEnabled *bool `url:"issues_enabled,omitempty" json:"issues_enabled,omitempty"` + MergeRequestsEnabled *bool `url:"merge_requests_enabled,omitempty" json:"merge_requests_enabled,omitempty"` + ApprovalsBeforeMerge *int `url:"approvals_before_merge,omitempty" json:"approvals_before_merge,omitempty"` + BuildsEnabled *bool `url:"builds_enabled,omitempty" json:"builds_enabled,omitempty"` + WikiEnabled *bool `url:"wiki_enabled,omitempty" json:"wiki_enabled,omitempty"` + SnippetsEnabled *bool `url:"snippets_enabled,omitempty" json:"snippets_enabled,omitempty"` + ContainerRegistryEnabled *bool `url:"container_registry_enabled,omitempty" json:"container_registry_enabled,omitempty"` + SharedRunnersEnabled *bool `url:"shared_runners_enabled,omitempty" json:"shared_runners_enabled,omitempty"` + Public *bool `url:"public,omitempty" json:"public,omitempty"` + VisibilityLevel *VisibilityLevelValue `url:"visibility_level,omitempty" json:"visibility_level,omitempty"` + ImportURL *bool `url:"import_url,omitempty" json:"import_url,omitempty"` + PublicBuilds *bool `url:"public_builds,omitempty" json:"public_builds,omitempty"` + OnlyAllowMergeIfBuildSucceeds *bool `url:"only_allow_merge_if_build_succeeds,omitempty" json:"only_allow_merge_if_build_succeeds,omitempty"` + OnlyAllowMergeIfAllDiscussionsAreResolved *bool `url:"only_allow_merge_if_all_discussions_are_resolved,omitempty" json:"only_allow_merge_if_all_discussions_are_resolved,omitempty"` + LFSEnabled *bool `url:"lfs_enabled,omitempty" json:"lfs_enabled,omitempty"` + RequestAccessEnabled *bool `url:"request_access_enabled,omitempty" json:"request_access_enabled,omitempty"` +} + +// EditProject updates an existing project. +// +// GitLab API docs: https://docs.gitlab.com/ce/api/projects.html#edit-project +func (s *ProjectsService) EditProject(pid interface{}, opt *EditProjectOptions, options ...OptionFunc) (*Project, *Response, error) { + project, err := parseID(pid) + if err != nil { + return nil, nil, err + } + u := fmt.Sprintf("projects/%s", url.QueryEscape(project)) + + req, err := s.client.NewRequest("PUT", u, opt, options) + if err != nil { + return nil, nil, err + } + + p := new(Project) + resp, err := s.client.Do(req, p) + if err != nil { + return nil, resp, err + } + + return p, resp, err +} + +// ForkProject forks a project into the user namespace of the authenticated +// user. +// +// GitLab API docs: https://docs.gitlab.com/ce/api/projects.html#fork-project +func (s *ProjectsService) ForkProject(pid interface{}, options ...OptionFunc) (*Project, *Response, error) { + project, err := parseID(pid) + if err != nil { + return nil, nil, err + } + u := fmt.Sprintf("projects/fork/%s", url.QueryEscape(project)) + + req, err := s.client.NewRequest("POST", u, nil, options) + if err != nil { + return nil, nil, err + } + + p := new(Project) + resp, err := s.client.Do(req, p) + if err != nil { + return nil, resp, err + } + + return p, resp, err +} + +// DeleteProject removes a project including all associated resources +// (issues, merge requests etc.) +// +// GitLab API docs: https://docs.gitlab.com/ce/api/projects.html#remove-project +func (s *ProjectsService) DeleteProject(pid interface{}, options ...OptionFunc) (*Response, error) { + project, err := parseID(pid) + if err != nil { + return nil, err + } + u := fmt.Sprintf("projects/%s", url.QueryEscape(project)) + + req, err := s.client.NewRequest("DELETE", u, nil, options) + if err != nil { + return nil, err + } + + return s.client.Do(req, nil) +} + +// ProjectMember represents a project member. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/projects.html#list-project-team-members +type ProjectMember struct { + ID int `json:"id"` + Username string `json:"username"` + Email string `json:"email"` + Name string `json:"name"` + State string `json:"state"` + CreatedAt *time.Time `json:"created_at"` + AccessLevel AccessLevelValue `json:"access_level"` +} + +// ListProjectMembersOptions represents the available ListProjectMembers() +// options. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/projects.html#list-project-team-members +type ListProjectMembersOptions struct { + ListOptions + Query *string `url:"query,omitempty" json:"query,omitempty"` +} + +// ListProjectMembers gets a list of a project's team members. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/projects.html#list-project-team-members +func (s *ProjectsService) ListProjectMembers(pid interface{}, opt *ListProjectMembersOptions, options ...OptionFunc) ([]*ProjectMember, *Response, error) { + project, err := parseID(pid) + if err != nil { + return nil, nil, err + } + u := fmt.Sprintf("projects/%s/members", url.QueryEscape(project)) + + req, err := s.client.NewRequest("GET", u, opt, options) + if err != nil { + return nil, nil, err + } + + var pm []*ProjectMember + resp, err := s.client.Do(req, &pm) + if err != nil { + return nil, resp, err + } + + return pm, resp, err +} + +// GetProjectMember gets a project team member. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/projects.html#get-project-team-member +func (s *ProjectsService) GetProjectMember(pid interface{}, user int, options ...OptionFunc) (*ProjectMember, *Response, error) { + project, err := parseID(pid) + if err != nil { + return nil, nil, err + } + u := fmt.Sprintf("projects/%s/members/%d", url.QueryEscape(project), user) + + req, err := s.client.NewRequest("GET", u, nil, options) + if err != nil { + return nil, nil, err + } + + pm := new(ProjectMember) + resp, err := s.client.Do(req, pm) + if err != nil { + return nil, resp, err + } + + return pm, resp, err +} + +// AddProjectMemberOptions represents the available AddProjectMember() options. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/projects.html#add-project-team-member +type AddProjectMemberOptions struct { + UserID *int `url:"user_id,omitempty" json:"user_id,omitempty"` + AccessLevel *AccessLevelValue `url:"access_level,omitempty" json:"access_level,omitempty"` +} + +// AddProjectMember adds a user to a project team. This is an idempotent +// method and can be called multiple times with the same parameters. Adding +// team membership to a user that is already a member does not affect the +// existing membership. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/projects.html#add-project-team-member +func (s *ProjectsService) AddProjectMember(pid interface{}, opt *AddProjectMemberOptions, options ...OptionFunc) (*ProjectMember, *Response, error) { + project, err := parseID(pid) + if err != nil { + return nil, nil, err + } + u := fmt.Sprintf("projects/%s/members", url.QueryEscape(project)) + + req, err := s.client.NewRequest("POST", u, opt, options) + if err != nil { + return nil, nil, err + } + + pm := new(ProjectMember) + resp, err := s.client.Do(req, pm) + if err != nil { + return nil, resp, err + } + + return pm, resp, err +} + +// EditProjectMemberOptions represents the available EditProjectMember() options. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/projects.html#edit-project-team-member +type EditProjectMemberOptions struct { + AccessLevel *AccessLevelValue `url:"access_level,omitempty" json:"access_level,omitempty"` +} + +// EditProjectMember updates a project team member to a specified access level.. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/projects.html#edit-project-team-member +func (s *ProjectsService) EditProjectMember(pid interface{}, user int, opt *EditProjectMemberOptions, options ...OptionFunc) (*ProjectMember, *Response, error) { + project, err := parseID(pid) + if err != nil { + return nil, nil, err + } + u := fmt.Sprintf("projects/%s/members/%d", url.QueryEscape(project), user) + + req, err := s.client.NewRequest("PUT", u, opt, options) + if err != nil { + return nil, nil, err + } + + pm := new(ProjectMember) + resp, err := s.client.Do(req, pm) + if err != nil { + return nil, resp, err + } + + return pm, resp, err +} + +// DeleteProjectMember removes a user from a project team. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/projects.html#remove-project-team-member +func (s *ProjectsService) DeleteProjectMember(pid interface{}, user int, options ...OptionFunc) (*Response, error) { + project, err := parseID(pid) + if err != nil { + return nil, err + } + u := fmt.Sprintf("projects/%s/members/%d", url.QueryEscape(project), user) + + req, err := s.client.NewRequest("DELETE", u, nil, options) + if err != nil { + return nil, err + } + + return s.client.Do(req, nil) +} + +// ProjectHook represents a project hook. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/projects.html#list-project-hooks +type ProjectHook struct { + ID int `json:"id"` + URL string `json:"url"` + ProjectID int `json:"project_id"` + PushEvents bool `json:"push_events"` + IssuesEvents bool `json:"issues_events"` + MergeRequestsEvents bool `json:"merge_requests_events"` + TagPushEvents bool `json:"tag_push_events"` + NoteEvents bool `json:"note_events"` + BuildEvents bool `json:"build_events"` + PipelineEvents bool `json:"pipeline_events"` + WikiPageEvents bool `json:"wiki_page_events"` + EnableSSLVerification bool `json:"enable_ssl_verification"` + CreatedAt *time.Time `json:"created_at"` +} + +// ListProjectHooksOptions represents the available ListProjectHooks() options. +// +// GitLab API docs: https://docs.gitlab.com/ce/api/projects.html#list-project-hooks +type ListProjectHooksOptions struct { + ListOptions +} + +// ListProjectHooks gets a list of project hooks. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/projects.html#list-project-hooks +func (s *ProjectsService) ListProjectHooks(pid interface{}, opt *ListProjectHooksOptions, options ...OptionFunc) ([]*ProjectHook, *Response, error) { + project, err := parseID(pid) + if err != nil { + return nil, nil, err + } + u := fmt.Sprintf("projects/%s/hooks", url.QueryEscape(project)) + + req, err := s.client.NewRequest("GET", u, opt, options) + if err != nil { + return nil, nil, err + } + + var ph []*ProjectHook + resp, err := s.client.Do(req, &ph) + if err != nil { + return nil, resp, err + } + + return ph, resp, err +} + +// GetProjectHook gets a specific hook for a project. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/projects.html#get-project-hook +func (s *ProjectsService) GetProjectHook(pid interface{}, hook int, options ...OptionFunc) (*ProjectHook, *Response, error) { + project, err := parseID(pid) + if err != nil { + return nil, nil, err + } + u := fmt.Sprintf("projects/%s/hooks/%d", url.QueryEscape(project), hook) + + req, err := s.client.NewRequest("GET", u, nil, options) + if err != nil { + return nil, nil, err + } + + ph := new(ProjectHook) + resp, err := s.client.Do(req, ph) + if err != nil { + return nil, resp, err + } + + return ph, resp, err +} + +// AddProjectHookOptions represents the available AddProjectHook() options. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/projects.html#add-project-hook +type AddProjectHookOptions struct { + URL *string `url:"url,omitempty" json:"url,omitempty"` + PushEvents *bool `url:"push_events,omitempty" json:"push_events,omitempty"` + IssuesEvents *bool `url:"issues_events,omitempty" json:"issues_events,omitempty"` + MergeRequestsEvents *bool `url:"merge_requests_events,omitempty" json:"merge_requests_events,omitempty"` + TagPushEvents *bool `url:"tag_push_events,omitempty" json:"tag_push_events,omitempty"` + NoteEvents *bool `url:"note_events,omitempty" json:"note_events,omitempty"` + BuildEvents *bool `url:"build_events,omitempty" json:"build_events,omitempty"` + PipelineEvents *bool `url:"pipeline_events,omitempty" json:"pipeline_events,omitempty"` + WikiPageEvents *bool `url:"wiki_page_events,omitempty" json:"wiki_page_events,omitempty"` + EnableSSLVerification *bool `url:"enable_ssl_verification,omitempty" json:"enable_ssl_verification,omitempty"` + Token *string `url:"token,omitempty" json:"token,omitempty"` +} + +// AddProjectHook adds a hook to a specified project. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/projects.html#add-project-hook +func (s *ProjectsService) AddProjectHook(pid interface{}, opt *AddProjectHookOptions, options ...OptionFunc) (*ProjectHook, *Response, error) { + project, err := parseID(pid) + if err != nil { + return nil, nil, err + } + u := fmt.Sprintf("projects/%s/hooks", url.QueryEscape(project)) + + req, err := s.client.NewRequest("POST", u, opt, options) + if err != nil { + return nil, nil, err + } + + ph := new(ProjectHook) + resp, err := s.client.Do(req, ph) + if err != nil { + return nil, resp, err + } + + return ph, resp, err +} + +// EditProjectHookOptions represents the available EditProjectHook() options. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/projects.html#edit-project-hook +type EditProjectHookOptions struct { + URL *string `url:"url,omitempty" json:"url,omitempty"` + PushEvents *bool `url:"push_events,omitempty" json:"push_events,omitempty"` + IssuesEvents *bool `url:"issues_events,omitempty" json:"issues_events,omitempty"` + MergeRequestsEvents *bool `url:"merge_requests_events,omitempty" json:"merge_requests_events,omitempty"` + TagPushEvents *bool `url:"tag_push_events,omitempty" json:"tag_push_events,omitempty"` + NoteEvents *bool `url:"note_events,omitempty" json:"note_events,omitempty"` + BuildEvents *bool `url:"build_events,omitempty" json:"build_events,omitempty"` + PipelineEvents *bool `url:"pipeline_events,omitempty" json:"pipeline_events,omitempty"` + WikiPageEvents *bool `url:"wiki_page_events,omitempty" json:"wiki_page_events,omitempty"` + EnableSSLVerification *bool `url:"enable_ssl_verification,omitempty" json:"enable_ssl_verification,omitempty"` + Token *string `url:"token,omitempty" json:"token,omitempty"` +} + +// EditProjectHook edits a hook for a specified project. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/projects.html#edit-project-hook +func (s *ProjectsService) EditProjectHook(pid interface{}, hook int, opt *EditProjectHookOptions, options ...OptionFunc) (*ProjectHook, *Response, error) { + project, err := parseID(pid) + if err != nil { + return nil, nil, err + } + u := fmt.Sprintf("projects/%s/hooks/%d", url.QueryEscape(project), hook) + + req, err := s.client.NewRequest("PUT", u, opt, options) + if err != nil { + return nil, nil, err + } + + ph := new(ProjectHook) + resp, err := s.client.Do(req, ph) + if err != nil { + return nil, resp, err + } + + return ph, resp, err +} + +// DeleteProjectHook removes a hook from a project. This is an idempotent +// method and can be called multiple times. Either the hook is available or not. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/projects.html#delete-project-hook +func (s *ProjectsService) DeleteProjectHook(pid interface{}, hook int, options ...OptionFunc) (*Response, error) { + project, err := parseID(pid) + if err != nil { + return nil, err + } + u := fmt.Sprintf("projects/%s/hooks/%d", url.QueryEscape(project), hook) + + req, err := s.client.NewRequest("DELETE", u, nil, options) + if err != nil { + return nil, err + } + + return s.client.Do(req, nil) +} + +// ProjectForkRelation represents a project fork relationship. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/projects.html#admin-fork-relation +type ProjectForkRelation struct { + ID int `json:"id"` + ForkedToProjectID int `json:"forked_to_project_id"` + ForkedFromProjectID int `json:"forked_from_project_id"` + CreatedAt *time.Time `json:"created_at"` + UpdatedAt *time.Time `json:"updated_at"` +} + +// CreateProjectForkRelation creates a forked from/to relation between +// existing projects. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/projects.html#create-a-forked-fromto-relation-between-existing-projects. +func (s *ProjectsService) CreateProjectForkRelation(pid int, fork int, options ...OptionFunc) (*ProjectForkRelation, *Response, error) { + u := fmt.Sprintf("projects/%d/fork/%d", pid, fork) + + req, err := s.client.NewRequest("POST", u, nil, options) + if err != nil { + return nil, nil, err + } + + pfr := new(ProjectForkRelation) + resp, err := s.client.Do(req, pfr) + if err != nil { + return nil, resp, err + } + + return pfr, resp, err +} + +// DeleteProjectForkRelation deletes an existing forked from relationship. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/projects.html#delete-an-existing-forked-from-relationship +func (s *ProjectsService) DeleteProjectForkRelation(pid int, options ...OptionFunc) (*Response, error) { + u := fmt.Sprintf("projects/%d/fork", pid) + + req, err := s.client.NewRequest("DELETE", u, nil, options) + if err != nil { + return nil, err + } + + return s.client.Do(req, nil) +} + +// ArchiveProject archives the project if the user is either admin or the +// project owner of this project. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/projects.html#archive-a-project +func (s *ProjectsService) ArchiveProject(pid interface{}, options ...OptionFunc) (*Project, *Response, error) { + project, err := parseID(pid) + if err != nil { + return nil, nil, err + } + u := fmt.Sprintf("projects/%s/archive", url.QueryEscape(project)) + + req, err := s.client.NewRequest("POST", u, nil, options) + if err != nil { + return nil, nil, err + } + + p := new(Project) + resp, err := s.client.Do(req, p) + if err != nil { + return nil, resp, err + } + + return p, resp, err +} + +// UnarchiveProject unarchives the project if the user is either admin or +// the project owner of this project. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/projects.html#unarchive-a-project +func (s *ProjectsService) UnarchiveProject(pid interface{}, options ...OptionFunc) (*Project, *Response, error) { + project, err := parseID(pid) + if err != nil { + return nil, nil, err + } + u := fmt.Sprintf("projects/%s/unarchive", url.QueryEscape(project)) + + req, err := s.client.NewRequest("POST", u, nil, options) + if err != nil { + return nil, nil, err + } + + p := new(Project) + resp, err := s.client.Do(req, p) + if err != nil { + return nil, resp, err + } + + return p, resp, err +} diff --git a/vendor/github.com/xanzy/go-gitlab/repositories.go b/vendor/github.com/xanzy/go-gitlab/repositories.go new file mode 100644 index 000000000..aa1052ff6 --- /dev/null +++ b/vendor/github.com/xanzy/go-gitlab/repositories.go @@ -0,0 +1,259 @@ +// +// Copyright 2015, Sander van Harmelen +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +package gitlab + +import ( + "bytes" + "fmt" + "net/url" +) + +// RepositoriesService handles communication with the repositories related +// methods of the GitLab API. +// +// GitLab API docs: https://docs.gitlab.com/ce/api/repositories.html +type RepositoriesService struct { + client *Client +} + +// TreeNode represents a GitLab repository file or directory. +// +// GitLab API docs: https://docs.gitlab.com/ce/api/repositories.html +type TreeNode struct { + ID string `json:"id"` + Name string `json:"name"` + Type string `json:"type"` + Mode string `json:"mode"` +} + +func (t TreeNode) String() string { + return Stringify(t) +} + +// ListTreeOptions represents the available ListTree() options. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/repositories.html#list-repository-tree +type ListTreeOptions struct { + Path *string `url:"path,omitempty" json:"path,omitempty"` + RefName *string `url:"ref_name,omitempty" json:"ref_name,omitempty"` +} + +// ListTree gets a list of repository files and directories in a project. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/repositories.html#list-repository-tree +func (s *RepositoriesService) ListTree(pid interface{}, opt *ListTreeOptions, options ...OptionFunc) ([]*TreeNode, *Response, error) { + project, err := parseID(pid) + if err != nil { + return nil, nil, err + } + u := fmt.Sprintf("projects/%s/repository/tree", url.QueryEscape(project)) + + req, err := s.client.NewRequest("GET", u, opt, options) + if err != nil { + return nil, nil, err + } + + var t []*TreeNode + resp, err := s.client.Do(req, &t) + if err != nil { + return nil, resp, err + } + + return t, resp, err +} + +// RawFileContentOptions represents the available RawFileContent() options. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/repositories.html#raw-file-content +type RawFileContentOptions struct { + FilePath *string `url:"filepath,omitempty" json:"filepath,omitempty"` +} + +// RawFileContent gets the raw file contents for a file by commit SHA and path +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/repositories.html#raw-file-content +func (s *RepositoriesService) RawFileContent(pid interface{}, sha string, opt *RawFileContentOptions, options ...OptionFunc) ([]byte, *Response, error) { + project, err := parseID(pid) + if err != nil { + return nil, nil, err + } + u := fmt.Sprintf("projects/%s/repository/blobs/%s", url.QueryEscape(project), sha) + + req, err := s.client.NewRequest("GET", u, opt, options) + if err != nil { + return nil, nil, err + } + + var b bytes.Buffer + resp, err := s.client.Do(req, &b) + if err != nil { + return nil, resp, err + } + + return b.Bytes(), resp, err +} + +// RawBlobContent gets the raw file contents for a blob by blob SHA. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/repositories.html#raw-blob-content +func (s *RepositoriesService) RawBlobContent(pid interface{}, sha string, options ...OptionFunc) ([]byte, *Response, error) { + project, err := parseID(pid) + if err != nil { + return nil, nil, err + } + u := fmt.Sprintf("projects/%s/repository/raw_blobs/%s", url.QueryEscape(project), sha) + + req, err := s.client.NewRequest("GET", u, nil, options) + if err != nil { + return nil, nil, err + } + + var b bytes.Buffer + resp, err := s.client.Do(req, &b) + if err != nil { + return nil, resp, err + } + + return b.Bytes(), resp, err +} + +// ArchiveOptions represents the available Archive() options. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/repositories.html#get-file-archive +type ArchiveOptions struct { + SHA *string `url:"sha,omitempty" json:"sha,omitempty"` +} + +// Archive gets an archive of the repository. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/repositories.html#get-file-archive +func (s *RepositoriesService) Archive(pid interface{}, opt *ArchiveOptions, options ...OptionFunc) ([]byte, *Response, error) { + project, err := parseID(pid) + if err != nil { + return nil, nil, err + } + u := fmt.Sprintf("projects/%s/repository/archive", url.QueryEscape(project)) + + req, err := s.client.NewRequest("GET", u, opt, options) + if err != nil { + return nil, nil, err + } + + var b bytes.Buffer + resp, err := s.client.Do(req, &b) + if err != nil { + return nil, resp, err + } + + return b.Bytes(), resp, err +} + +// Compare represents the result of a comparison of branches, tags or commits. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/repositories.html#compare-branches-tags-or-commits +type Compare struct { + Commit *Commit `json:"commit"` + Commits []*Commit `json:"commits"` + Diffs []*Diff `json:"diffs"` + CompareTimeout bool `json:"compare_timeout"` + CompareSameRef bool `json:"compare_same_ref"` +} + +func (c Compare) String() string { + return Stringify(c) +} + +// CompareOptions represents the available Compare() options. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/repositories.html#compare-branches-tags-or-commits +type CompareOptions struct { + From *string `url:"from,omitempty" json:"from,omitempty"` + To *string `url:"to,omitempty" json:"to,omitempty"` +} + +// Compare compares branches, tags or commits. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/repositories.html#compare-branches-tags-or-commits +func (s *RepositoriesService) Compare(pid interface{}, opt *CompareOptions, options ...OptionFunc) (*Compare, *Response, error) { + project, err := parseID(pid) + if err != nil { + return nil, nil, err + } + u := fmt.Sprintf("projects/%s/repository/compare", url.QueryEscape(project)) + + req, err := s.client.NewRequest("GET", u, opt, options) + if err != nil { + return nil, nil, err + } + + c := new(Compare) + resp, err := s.client.Do(req, c) + if err != nil { + return nil, resp, err + } + + return c, resp, err +} + +// Contributor represents a GitLap contributor. +// +// GitLab API docs: https://docs.gitlab.com/ce/api/repositories.html#contributer +type Contributor struct { + Name string `json:"name,omitempty"` + Email string `json:"email,omitempty"` + Commits int `json:"commits,omitempty"` + Additions int `json:"additions,omitempty"` + Deletions int `json:"deletions,omitempty"` +} + +func (c Contributor) String() string { + return Stringify(c) +} + +// Contributors gets the repository contributors list. +// +// GitLab API docs: https://docs.gitlab.com/ce/api/repositories.html#contributer +func (s *RepositoriesService) Contributors(pid interface{}, options ...OptionFunc) ([]*Contributor, *Response, error) { + project, err := parseID(pid) + if err != nil { + return nil, nil, err + } + u := fmt.Sprintf("projects/%s/repository/contributors", url.QueryEscape(project)) + + req, err := s.client.NewRequest("GET", u, nil, options) + if err != nil { + return nil, nil, err + } + + var c []*Contributor + resp, err := s.client.Do(req, &c) + if err != nil { + return nil, resp, err + } + + return c, resp, err +} diff --git a/vendor/github.com/xanzy/go-gitlab/repository_files.go b/vendor/github.com/xanzy/go-gitlab/repository_files.go new file mode 100644 index 000000000..21e5f65cf --- /dev/null +++ b/vendor/github.com/xanzy/go-gitlab/repository_files.go @@ -0,0 +1,210 @@ +// +// Copyright 2015, Sander van Harmelen +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +package gitlab + +import ( + "fmt" + "net/url" +) + +// RepositoryFilesService handles communication with the repository files +// related methods of the GitLab API. +// +// GitLab API docs: https://docs.gitlab.com/ce/api/repository_files.html +type RepositoryFilesService struct { + client *Client +} + +// File represents a GitLab repository file. +// +// GitLab API docs: https://docs.gitlab.com/ce/api/repository_files.html +type File struct { + FileName string `json:"file_name"` + FilePath string `json:"file_path"` + Size int `json:"size"` + Encoding string `json:"encoding"` + Content string `json:"content"` + Ref string `json:"ref"` + BlobID string `json:"blob_id"` + CommitID string `json:"commit_id"` +} + +func (r File) String() string { + return Stringify(r) +} + +// GetFileOptions represents the available GetFile() options. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/repository_files.html#get-file-from-respository +type GetFileOptions struct { + FilePath *string `url:"file_path,omitempty" json:"file_path,omitempty"` + Ref *string `url:"ref,omitempty" json:"ref,omitempty"` +} + +// GetFile allows you to receive information about a file in repository like +// name, size, content. Note that file content is Base64 encoded. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/repository_files.html#get-file-from-respository +func (s *RepositoryFilesService) GetFile(pid interface{}, opt *GetFileOptions, options ...OptionFunc) (*File, *Response, error) { + project, err := parseID(pid) + if err != nil { + return nil, nil, err + } + u := fmt.Sprintf("projects/%s/repository/files", url.QueryEscape(project)) + + req, err := s.client.NewRequest("GET", u, opt, options) + if err != nil { + return nil, nil, err + } + + f := new(File) + resp, err := s.client.Do(req, f) + if err != nil { + return nil, resp, err + } + + return f, resp, err +} + +// FileInfo represents file details of a GitLab repository file. +// +// GitLab API docs: https://docs.gitlab.com/ce/api/repository_files.html +type FileInfo struct { + FilePath string `json:"file_path"` + BranchName string `json:"branch_name"` +} + +func (r FileInfo) String() string { + return Stringify(r) +} + +// CreateFileOptions represents the available CreateFile() options. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/repository_files.html#create-new-file-in-repository +type CreateFileOptions struct { + FilePath *string `url:"file_path,omitempty" json:"file_path,omitempty"` + BranchName *string `url:"branch_name,omitempty" json:"branch_name,omitempty"` + Encoding *string `url:"encoding,omitempty" json:"encoding,omitempty"` + AuthorEmail *string `url:"author_email,omitempty" json:"author_email,omitempty"` + AuthorName *string `url:"author_name,omitempty" json:"author_name,omitempty"` + Content *string `url:"content,omitempty" json:"content,omitempty"` + CommitMessage *string `url:"commit_message,omitempty" json:"commit_message,omitempty"` +} + +// CreateFile creates a new file in a repository. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/repository_files.html#create-new-file-in-repository +func (s *RepositoryFilesService) CreateFile(pid interface{}, opt *CreateFileOptions, options ...OptionFunc) (*FileInfo, *Response, error) { + project, err := parseID(pid) + if err != nil { + return nil, nil, err + } + u := fmt.Sprintf("projects/%s/repository/files", url.QueryEscape(project)) + + req, err := s.client.NewRequest("POST", u, opt, options) + if err != nil { + return nil, nil, err + } + + f := new(FileInfo) + resp, err := s.client.Do(req, f) + if err != nil { + return nil, resp, err + } + + return f, resp, err +} + +// UpdateFileOptions represents the available UpdateFile() options. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/repository_files.html#update-existing-file-in-repository +type UpdateFileOptions struct { + FilePath *string `url:"file_path,omitempty" json:"file_path,omitempty"` + BranchName *string `url:"branch_name,omitempty" json:"branch_name,omitempty"` + Encoding *string `url:"encoding,omitempty" json:"encoding,omitempty"` + AuthorEmail *string `url:"author_email,omitempty" json:"author_email,omitempty"` + AuthorName *string `url:"author_name,omitempty" json:"author_name,omitempty"` + Content *string `url:"content,omitempty" json:"content,omitempty"` + CommitMessage *string `url:"commit_message,omitempty" json:"commit_message,omitempty"` +} + +// UpdateFile updates an existing file in a repository +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/repository_files.html#update-existing-file-in-repository +func (s *RepositoryFilesService) UpdateFile(pid interface{}, opt *UpdateFileOptions, options ...OptionFunc) (*FileInfo, *Response, error) { + project, err := parseID(pid) + if err != nil { + return nil, nil, err + } + u := fmt.Sprintf("projects/%s/repository/files", url.QueryEscape(project)) + + req, err := s.client.NewRequest("PUT", u, opt, options) + if err != nil { + return nil, nil, err + } + + f := new(FileInfo) + resp, err := s.client.Do(req, f) + if err != nil { + return nil, resp, err + } + + return f, resp, err +} + +// DeleteFileOptions represents the available DeleteFile() options. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/repository_files.html#delete-existing-file-in-repository +type DeleteFileOptions struct { + FilePath *string `url:"file_path,omitempty" json:"file_path,omitempty"` + BranchName *string `url:"branch_name,omitempty" json:"branch_name,omitempty"` + AuthorEmail *string `url:"author_email,omitempty" json:"author_email,omitempty"` + AuthorName *string `url:"author_name,omitempty" json:"author_name,omitempty"` + CommitMessage *string `url:"commit_message,omitempty" json:"commit_message,omitempty"` +} + +// DeleteFile deletes an existing file in a repository +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/repository_files.html#delete-existing-file-in-repository +func (s *RepositoryFilesService) DeleteFile(pid interface{}, opt *DeleteFileOptions, options ...OptionFunc) (*FileInfo, *Response, error) { + project, err := parseID(pid) + if err != nil { + return nil, nil, err + } + u := fmt.Sprintf("projects/%s/repository/files", url.QueryEscape(project)) + + req, err := s.client.NewRequest("DELETE", u, opt, options) + if err != nil { + return nil, nil, err + } + + f := new(FileInfo) + resp, err := s.client.Do(req, f) + if err != nil { + return nil, resp, err + } + + return f, resp, err +} diff --git a/vendor/github.com/xanzy/go-gitlab/services.go b/vendor/github.com/xanzy/go-gitlab/services.go new file mode 100644 index 000000000..dbcdf84ab --- /dev/null +++ b/vendor/github.com/xanzy/go-gitlab/services.go @@ -0,0 +1,279 @@ +// +// Copyright 2015, Sander van Harmelen +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +package gitlab + +import ( + "fmt" + "net/url" + "time" +) + +// ServicesService handles communication with the services related methods of +// the GitLab API. +// +// GitLab API docs: https://docs.gitlab.com/ce/api/services.html +type ServicesService struct { + client *Client +} + +// Service represents a GitLab service. +// +// GitLab API docs: https://docs.gitlab.com/ce/api/services.html +type Service struct { + ID *int `json:"id"` + Title *string `json:"title"` + CreatedAt *time.Time `json:"created_at"` + UpdatedAt *time.Time `json:"created_at"` + Active *bool `json:"active"` + PushEvents *bool `json:"push_events"` + IssuesEvents *bool `json:"issues_events"` + MergeRequestsEvents *bool `json:"merge_requests_events"` + TagPushEvents *bool `json:"tag_push_events"` + NoteEvents *bool `json:"note_events"` +} + +// SetGitLabCIServiceOptions represents the available SetGitLabCIService() +// options. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/services.html#edit-gitlab-ci-service +type SetGitLabCIServiceOptions struct { + Token *string `url:"token,omitempty" json:"token,omitempty"` + ProjectURL *string `url:"project_url,omitempty" json:"project_url,omitempty"` +} + +// SetGitLabCIService sets GitLab CI service for a project. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/services.html#edit-gitlab-ci-service +func (s *ServicesService) SetGitLabCIService(pid interface{}, opt *SetGitLabCIServiceOptions, options ...OptionFunc) (*Response, error) { + project, err := parseID(pid) + if err != nil { + return nil, err + } + u := fmt.Sprintf("projects/%s/services/gitlab-ci", url.QueryEscape(project)) + + req, err := s.client.NewRequest("PUT", u, opt, options) + if err != nil { + return nil, err + } + + return s.client.Do(req, nil) +} + +// DeleteGitLabCIService deletes GitLab CI service settings for a project. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/services.html#delete-gitlab-ci-service +func (s *ServicesService) DeleteGitLabCIService(pid interface{}, options ...OptionFunc) (*Response, error) { + project, err := parseID(pid) + if err != nil { + return nil, err + } + u := fmt.Sprintf("projects/%s/services/gitlab-ci", url.QueryEscape(project)) + + req, err := s.client.NewRequest("DELETE", u, nil, options) + if err != nil { + return nil, err + } + + return s.client.Do(req, nil) +} + +// SetHipChatServiceOptions represents the available SetHipChatService() +// options. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/services.html#edit-hipchat-service +type SetHipChatServiceOptions struct { + Token *string `url:"token,omitempty" json:"token,omitempty" ` + Room *string `url:"room,omitempty" json:"room,omitempty"` +} + +// SetHipChatService sets HipChat service for a project +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/services.html#edit-hipchat-service +func (s *ServicesService) SetHipChatService(pid interface{}, opt *SetHipChatServiceOptions, options ...OptionFunc) (*Response, error) { + project, err := parseID(pid) + if err != nil { + return nil, err + } + u := fmt.Sprintf("projects/%s/services/hipchat", url.QueryEscape(project)) + + req, err := s.client.NewRequest("PUT", u, opt, options) + if err != nil { + return nil, err + } + + return s.client.Do(req, nil) +} + +// DeleteHipChatService deletes HipChat service for project. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/services.html#delete-hipchat-service +func (s *ServicesService) DeleteHipChatService(pid interface{}, options ...OptionFunc) (*Response, error) { + project, err := parseID(pid) + if err != nil { + return nil, err + } + u := fmt.Sprintf("projects/%s/services/hipchat", url.QueryEscape(project)) + + req, err := s.client.NewRequest("DELETE", u, nil, options) + if err != nil { + return nil, err + } + + return s.client.Do(req, nil) +} + +// SetDroneCIServiceOptions represents the available SetDroneCIService() +// options. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/services.html#createedit-drone-ci-service +type SetDroneCIServiceOptions struct { + Token *string `url:"token" json:"token" ` + DroneURL *string `url:"drone_url" json:"drone_url"` + EnableSSLVerification *string `url:"enable_ssl_verification,omitempty" json:"enable_ssl_verification,omitempty"` +} + +// SetDroneCIService sets Drone CI service for a project. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/services.html#createedit-drone-ci-service +func (s *ServicesService) SetDroneCIService(pid interface{}, opt *SetDroneCIServiceOptions, options ...OptionFunc) (*Response, error) { + project, err := parseID(pid) + if err != nil { + return nil, err + } + u := fmt.Sprintf("projects/%s/services/drone-ci", url.QueryEscape(project)) + + req, err := s.client.NewRequest("PUT", u, opt, options) + if err != nil { + return nil, err + } + + return s.client.Do(req, nil) +} + +// DeleteDroneCIService deletes Drone CI service settings for a project. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/services.html#delete-drone-ci-service +func (s *ServicesService) DeleteDroneCIService(pid interface{}, options ...OptionFunc) (*Response, error) { + project, err := parseID(pid) + if err != nil { + return nil, err + } + u := fmt.Sprintf("projects/%s/services/drone-ci", url.QueryEscape(project)) + + req, err := s.client.NewRequest("DELETE", u, nil, options) + if err != nil { + return nil, err + } + + return s.client.Do(req, nil) +} + +// DroneCIServiceProperties represents Drone CI specific properties. +type DroneCIServiceProperties struct { + Token *string `url:"token" json:"token"` + DroneURL *string `url:"drone_url" json:"drone_url"` + EnableSSLVerification *string `url:"enable_ssl_verification" json:"enable_ssl_verification"` +} + +// DroneCIService represents Drone CI service settings. +type DroneCIService struct { + Service + Properties *DroneCIServiceProperties `json:"properties"` +} + +// GetDroneCIService gets Drone CI service settings for a project. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/services.html#get-drone-ci-service-settings +func (s *ServicesService) GetDroneCIService(pid interface{}, options ...OptionFunc) (*DroneCIService, *Response, error) { + project, err := parseID(pid) + if err != nil { + return nil, nil, err + } + u := fmt.Sprintf("projects/%s/services/drone-ci", url.QueryEscape(project)) + + req, err := s.client.NewRequest("GET", u, nil, options) + if err != nil { + return nil, nil, err + } + + opt := new(DroneCIService) + resp, err := s.client.Do(req, opt) + if err != nil { + return nil, resp, err + } + + return opt, resp, err +} + +// SetSlackServiceOptions represents the available SetSlackService() +// options. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/services.html#edit-slack-service +type SetSlackServiceOptions struct { + WebHook *string `url:"webhook,omitempty" json:"webhook,omitempty" ` + Username *string `url:"username,omitempty" json:"username,omitempty" ` + Channel *string `url:"channel,omitempty" json:"channel,omitempty"` +} + +// SetSlackService sets Slack service for a project +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/services.html#edit-slack-service +func (s *ServicesService) SetSlackService(pid interface{}, opt *SetSlackServiceOptions, options ...OptionFunc) (*Response, error) { + project, err := parseID(pid) + if err != nil { + return nil, err + } + u := fmt.Sprintf("projects/%s/services/slack", url.QueryEscape(project)) + + req, err := s.client.NewRequest("PUT", u, opt, options) + if err != nil { + return nil, err + } + + return s.client.Do(req, nil) +} + +// DeleteSlackService deletes Slack service for project. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/services.html#delete-slack-service +func (s *ServicesService) DeleteSlackService(pid interface{}, options ...OptionFunc) (*Response, error) { + project, err := parseID(pid) + if err != nil { + return nil, err + } + u := fmt.Sprintf("projects/%s/services/slack", url.QueryEscape(project)) + + req, err := s.client.NewRequest("DELETE", u, nil, options) + if err != nil { + return nil, err + } + + return s.client.Do(req, nil) +} diff --git a/vendor/github.com/xanzy/go-gitlab/session.go b/vendor/github.com/xanzy/go-gitlab/session.go new file mode 100644 index 000000000..571483cd3 --- /dev/null +++ b/vendor/github.com/xanzy/go-gitlab/session.go @@ -0,0 +1,78 @@ +// +// Copyright 2015, Sander van Harmelen +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +package gitlab + +import "time" + +// SessionService handles communication with the session related methods of +// the GitLab API. +// +// GitLab API docs: https://docs.gitlab.com/ce/api/session.html +type SessionService struct { + client *Client +} + +// Session represents a GitLab session. +// +// GitLab API docs: https://docs.gitlab.com/ce/api/session.html#session +type Session struct { + ID int `json:"id"` + Username string `json:"username"` + Email string `json:"email"` + Name string `json:"name"` + PrivateToken string `json:"private_token"` + Blocked bool `json:"blocked"` + CreatedAt *time.Time `json:"created_at"` + Bio interface{} `json:"bio"` + Skype string `json:"skype"` + Linkedin string `json:"linkedin"` + Twitter string `json:"twitter"` + WebsiteURL string `json:"website_url"` + DarkScheme bool `json:"dark_scheme"` + ThemeID int `json:"theme_id"` + IsAdmin bool `json:"is_admin"` + CanCreateGroup bool `json:"can_create_group"` + CanCreateTeam bool `json:"can_create_team"` + CanCreateProject bool `json:"can_create_project"` +} + +// GetSessionOptions represents the available Session() options. +// +// GitLab API docs: https://docs.gitlab.com/ce/api/session.html#session +type GetSessionOptions struct { + Login *string `url:"login,omitempty" json:"login,omitempty"` + Email *string `url:"email,omitempty" json:"email,omitempty"` + Password *string `url:"password,omitempty" json:"password,omitempty"` +} + +// GetSession logs in to get private token. +// +// GitLab API docs: https://docs.gitlab.com/ce/api/session.html#session +func (s *SessionService) GetSession(opt *GetSessionOptions, options ...OptionFunc) (*Session, *Response, error) { + req, err := s.client.NewRequest("POST", "session", opt, options) + if err != nil { + return nil, nil, err + } + + session := new(Session) + resp, err := s.client.Do(req, session) + if err != nil { + return nil, resp, err + } + + return session, resp, err +} diff --git a/vendor/github.com/xanzy/go-gitlab/settings.go b/vendor/github.com/xanzy/go-gitlab/settings.go new file mode 100644 index 000000000..41e9c9dab --- /dev/null +++ b/vendor/github.com/xanzy/go-gitlab/settings.go @@ -0,0 +1,117 @@ +// +// Copyright 2015, Sander van Harmelen +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +package gitlab + +import "time" + +// SettingsService handles communication with the application SettingsService +// related methods of the GitLab API. +// +// GitLab API docs: https://docs.gitlab.com/ce/api/settings.html +type SettingsService struct { + client *Client +} + +// Settings represents the GitLab application settings. +// +// GitLab API docs: https://docs.gitlab.com/ce/api/settings.html +type Settings struct { + ID int `json:"id"` + DefaultProjectsLimit int `json:"default_projects_limit"` + SignupEnabled bool `json:"signup_enabled"` + SigninEnabled bool `json:"signin_enabled"` + GravatarEnabled bool `json:"gravatar_enabled"` + SignInText string `json:"sign_in_text"` + CreatedAt *time.Time `json:"created_at"` + UpdatedAt *time.Time `json:"updated_at"` + HomePageURL string `json:"home_page_url"` + DefaultBranchProtection int `json:"default_branch_protection"` + TwitterSharingEnabled bool `json:"twitter_sharing_enabled"` + RestrictedVisibilityLevels []VisibilityLevelValue `json:"restricted_visibility_levels"` + MaxAttachmentSize int `json:"max_attachment_size"` + SessionExpireDelay int `json:"session_expire_delay"` + DefaultProjectVisibility int `json:"default_project_visibility"` + DefaultSnippetVisibility int `json:"default_snippet_visibility"` + RestrictedSignupDomains []string `json:"restricted_signup_domains"` + UserOauthApplications bool `json:"user_oauth_applications"` + AfterSignOutPath string `json:"after_sign_out_path"` +} + +func (s Settings) String() string { + return Stringify(s) +} + +// GetSettings gets the current application settings. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/settings.html#get-current-application.settings +func (s *SettingsService) GetSettings(options ...OptionFunc) (*Settings, *Response, error) { + req, err := s.client.NewRequest("GET", "application/settings", nil, options) + if err != nil { + return nil, nil, err + } + + as := new(Settings) + resp, err := s.client.Do(req, as) + if err != nil { + return nil, resp, err + } + + return as, resp, err +} + +// UpdateSettingsOptions represents the available UpdateSettings() options. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/settings.html#change-application.settings +type UpdateSettingsOptions struct { + DefaultProjectsLimit *int `url:"default_projects_limit,omitempty" json:"default_projects_limit,omitempty"` + SignupEnabled *bool `url:"signup_enabled,omitempty" json:"signup_enabled,omitempty"` + SigninEnabled *bool `url:"signin_enabled,omitempty" json:"signin_enabled,omitempty"` + GravatarEnabled *bool `url:"gravatar_enabled,omitempty" json:"gravatar_enabled,omitempty"` + SignInText *string `url:"sign_in_text,omitempty" json:"sign_in_text,omitempty"` + HomePageURL *string `url:"home_page_url,omitempty" json:"home_page_url,omitempty"` + DefaultBranchProtection *int `url:"default_branch_protection,omitempty" json:"default_branch_protection,omitempty"` + TwitterSharingEnabled *bool `url:"twitter_sharing_enabled,omitempty" json:"twitter_sharing_enabled,omitempty"` + RestrictedVisibilityLevels []VisibilityLevelValue `url:"restricted_visibility_levels,omitempty" json:"restricted_visibility_levels,omitempty"` + MaxAttachmentSize *int `url:"max_attachment_size,omitempty" json:"max_attachment_size,omitempty"` + SessionExpireDelay *int `url:"session_expire_delay,omitempty" json:"session_expire_delay,omitempty"` + DefaultProjectVisibility *int `url:"default_project_visibility,omitempty" json:"default_project_visibility,omitempty"` + DefaultSnippetVisibility *int `url:"default_snippet_visibility,omitempty" json:"default_snippet_visibility,omitempty"` + RestrictedSignupDomains []string `url:"restricted_signup_domains,omitempty" json:"restricted_signup_domains,omitempty"` + UserOauthApplications *bool `url:"user_oauth_applications,omitempty" json:"user_oauth_applications,omitempty"` + AfterSignOutPath *string `url:"after_sign_out_path,omitempty" json:"after_sign_out_path,omitempty"` +} + +// UpdateSettings updates the application settings. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/settings.html#change-application.settings +func (s *SettingsService) UpdateSettings(opt *UpdateSettingsOptions, options ...OptionFunc) (*Settings, *Response, error) { + req, err := s.client.NewRequest("PUT", "application/settings", opt, options) + if err != nil { + return nil, nil, err + } + + as := new(Settings) + resp, err := s.client.Do(req, as) + if err != nil { + return nil, resp, err + } + + return as, resp, err +} diff --git a/vendor/github.com/xanzy/go-gitlab/strings.go b/vendor/github.com/xanzy/go-gitlab/strings.go new file mode 100644 index 000000000..d0e7679b3 --- /dev/null +++ b/vendor/github.com/xanzy/go-gitlab/strings.go @@ -0,0 +1,94 @@ +// +// Copyright 2015, Sander van Harmelen +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +package gitlab + +import ( + "bytes" + "fmt" + + "reflect" +) + +// Stringify attempts to create a reasonable string representation of types in +// the GitHub library. It does things like resolve pointers to their values +// and omits struct fields with nil values. +func Stringify(message interface{}) string { + var buf bytes.Buffer + v := reflect.ValueOf(message) + stringifyValue(&buf, v) + return buf.String() +} + +// stringifyValue was heavily inspired by the goprotobuf library. +func stringifyValue(buf *bytes.Buffer, val reflect.Value) { + if val.Kind() == reflect.Ptr && val.IsNil() { + buf.WriteString("") + return + } + + v := reflect.Indirect(val) + + switch v.Kind() { + case reflect.String: + fmt.Fprintf(buf, `"%s"`, v) + case reflect.Slice: + buf.WriteByte('[') + for i := 0; i < v.Len(); i++ { + if i > 0 { + buf.WriteByte(' ') + } + + stringifyValue(buf, v.Index(i)) + } + + buf.WriteByte(']') + return + case reflect.Struct: + if v.Type().Name() != "" { + buf.WriteString(v.Type().String()) + } + + buf.WriteByte('{') + + var sep bool + for i := 0; i < v.NumField(); i++ { + fv := v.Field(i) + if fv.Kind() == reflect.Ptr && fv.IsNil() { + continue + } + if fv.Kind() == reflect.Slice && fv.IsNil() { + continue + } + + if sep { + buf.WriteString(", ") + } else { + sep = true + } + + buf.WriteString(v.Type().Field(i).Name) + buf.WriteByte(':') + stringifyValue(buf, fv) + } + + buf.WriteByte('}') + default: + if v.CanInterface() { + fmt.Fprint(buf, v.Interface()) + } + } +} diff --git a/vendor/github.com/xanzy/go-gitlab/system_hooks.go b/vendor/github.com/xanzy/go-gitlab/system_hooks.go new file mode 100644 index 000000000..20277a9af --- /dev/null +++ b/vendor/github.com/xanzy/go-gitlab/system_hooks.go @@ -0,0 +1,143 @@ +// +// Copyright 2015, Sander van Harmelen +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +package gitlab + +import ( + "fmt" + "time" +) + +// SystemHooksService handles communication with the system hooks related +// methods of the GitLab API. +// +// GitLab API docs: https://docs.gitlab.com/ce/api/system_hooks.html +type SystemHooksService struct { + client *Client +} + +// Hook represents a GitLap system hook. +// +// GitLab API docs: https://docs.gitlab.com/ce/api/system_hooks.html +type Hook struct { + ID int `json:"id"` + URL string `json:"url"` + CreatedAt *time.Time `json:"created_at"` +} + +func (h Hook) String() string { + return Stringify(h) +} + +// ListHooks gets a list of system hooks. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/system_hooks.html#list-system-hooks +func (s *SystemHooksService) ListHooks(options ...OptionFunc) ([]*Hook, *Response, error) { + req, err := s.client.NewRequest("GET", "hooks", nil, options) + if err != nil { + return nil, nil, err + } + + var h []*Hook + resp, err := s.client.Do(req, &h) + if err != nil { + return nil, resp, err + } + + return h, resp, err +} + +// AddHookOptions represents the available AddHook() options. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/system_hooks.html#add-new-system-hook-hook +type AddHookOptions struct { + URL *string `url:"url,omitempty" json:"url,omitempty"` +} + +// AddHook adds a new system hook hook. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/system_hooks.html#add-new-system-hook-hook +func (s *SystemHooksService) AddHook(opt *AddHookOptions, options ...OptionFunc) (*Hook, *Response, error) { + req, err := s.client.NewRequest("POST", "hooks", opt, options) + if err != nil { + return nil, nil, err + } + + h := new(Hook) + resp, err := s.client.Do(req, h) + if err != nil { + return nil, resp, err + } + + return h, resp, err +} + +// HookEvent represents an event triggert by a GitLab system hook. +// +// GitLab API docs: https://docs.gitlab.com/ce/api/system_hooks.html +type HookEvent struct { + EventName string `json:"event_name"` + Name string `json:"name"` + Path string `json:"path"` + ProjectID int `json:"project_id"` + OwnerName string `json:"owner_name"` + OwnerEmail string `json:"owner_email"` +} + +func (h HookEvent) String() string { + return Stringify(h) +} + +// TestHook tests a system hook. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/system_hooks.html#test-system-hook +func (s *SystemHooksService) TestHook(hook int, options ...OptionFunc) (*HookEvent, *Response, error) { + u := fmt.Sprintf("hooks/%d", hook) + + req, err := s.client.NewRequest("GET", u, nil, options) + if err != nil { + return nil, nil, err + } + + h := new(HookEvent) + resp, err := s.client.Do(req, h) + if err != nil { + return nil, resp, err + } + + return h, resp, err +} + +// DeleteHook deletes a system hook. This is an idempotent API function and +// returns 200 OK even if the hook is not available. If the hook is deleted it +// is also returned as JSON. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/system_hooks.html#delete-system-hook +func (s *SystemHooksService) DeleteHook(hook int, options ...OptionFunc) (*Response, error) { + u := fmt.Sprintf("hooks/%d", hook) + + req, err := s.client.NewRequest("DELETE", u, nil, options) + if err != nil { + return nil, err + } + + return s.client.Do(req, nil) +} diff --git a/vendor/github.com/xanzy/go-gitlab/tags.go b/vendor/github.com/xanzy/go-gitlab/tags.go new file mode 100644 index 000000000..196f6d454 --- /dev/null +++ b/vendor/github.com/xanzy/go-gitlab/tags.go @@ -0,0 +1,149 @@ +// +// Copyright 2015, Sander van Harmelen +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +package gitlab + +import ( + "fmt" + "net/url" +) + +// TagsService handles communication with the tags related methods +// of the GitLab API. +// +// GitLab API docs: https://docs.gitlab.com/ce/api/tags.html +type TagsService struct { + client *Client +} + +// Tag represents a GitLab tag. +// +// GitLab API docs: https://docs.gitlab.com/ce/api/tags.html +type Tag struct { + Commit *Commit `json:"commit"` + Name string `json:"name"` + Message string `json:"message"` +} + +func (r Tag) String() string { + return Stringify(r) +} + +// ListTags gets a list of tags from a project, sorted by name in reverse +// alphabetical order. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/tags.html#list-project-repository-tags +func (s *TagsService) ListTags(pid interface{}, options ...OptionFunc) ([]*Tag, *Response, error) { + project, err := parseID(pid) + if err != nil { + return nil, nil, err + } + u := fmt.Sprintf("projects/%s/repository/tags", url.QueryEscape(project)) + + req, err := s.client.NewRequest("GET", u, nil, options) + if err != nil { + return nil, nil, err + } + + var t []*Tag + resp, err := s.client.Do(req, &t) + if err != nil { + return nil, resp, err + } + + return t, resp, err +} + +// GetTag a specific repository tag determined by its name. It returns 200 together +// with the tag information if the tag exists. It returns 404 if the tag does not exist. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/tags.html#get-a-single-repository-tag +func (s *TagsService) GetTag(pid interface{}, tag string, options ...OptionFunc) (*Tag, *Response, error) { + project, err := parseID(pid) + if err != nil { + return nil, nil, err + } + u := fmt.Sprintf("projects/%s/repository/tags/%s", url.QueryEscape(project), tag) + + req, err := s.client.NewRequest("GET", u, nil, options) + if err != nil { + return nil, nil, err + } + + var t *Tag + resp, err := s.client.Do(req, &t) + if err != nil { + return nil, resp, err + } + + return t, resp, err +} + +// CreateTagOptions represents the available CreateTag() options. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/tags.html#create-a-new-tag +type CreateTagOptions struct { + TagName *string `url:"tag_name,omitempty" json:"tag_name,omitempty"` + Ref *string `url:"ref,omitempty" json:"ref,omitempty"` + Message *string `url:"message,omitempty" json:"message,omitempty"` +} + +// CreateTag creates a new tag in the repository that points to the supplied ref. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/tags.html#create-a-new-tag +func (s *TagsService) CreateTag(pid interface{}, opt *CreateTagOptions, options ...OptionFunc) (*Tag, *Response, error) { + project, err := parseID(pid) + if err != nil { + return nil, nil, err + } + u := fmt.Sprintf("projects/%s/repository/tags", url.QueryEscape(project)) + + req, err := s.client.NewRequest("POST", u, opt, options) + if err != nil { + return nil, nil, err + } + + t := new(Tag) + resp, err := s.client.Do(req, t) + if err != nil { + return nil, resp, err + } + + return t, resp, err +} + +// DeleteTag deletes a tag of a repository with given name. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/tags.html#delete-a-tag +func (s *TagsService) DeleteTag(pid interface{}, tag string, options ...OptionFunc) (*Response, error) { + project, err := parseID(pid) + if err != nil { + return nil, err + } + u := fmt.Sprintf("projects/%s/repository/tags/%s", url.QueryEscape(project), tag) + + req, err := s.client.NewRequest("DELETE", u, nil, options) + if err != nil { + return nil, err + } + + return s.client.Do(req, nil) +} diff --git a/vendor/github.com/xanzy/go-gitlab/time_stats.go b/vendor/github.com/xanzy/go-gitlab/time_stats.go new file mode 100644 index 000000000..c4a4ad40f --- /dev/null +++ b/vendor/github.com/xanzy/go-gitlab/time_stats.go @@ -0,0 +1,171 @@ +package gitlab + +import ( + "fmt" + "net/url" +) + +// TimeStatsService handles communication with the time tracking related +// methods of the GitLab API. +// +// GitLab docs: https://docs.gitlab.com/ce/workflow/time_tracking.html +// GitLab API docs: https://docs.gitlab.com/ce/api/issues.html +type TimeStatsService struct { + client *Client +} + +// TimeStats represents the time estimates and time spent for an issue. +// +// GitLab API docs: https://docs.gitlab.com/ce/api/issues.html +type TimeStats struct { + HumanTimeEstimate string `json:"human_time_estimate"` + HumanTotalTimeSpent string `json:"human_total_time_spent"` + TimeEstimate int `json:"time_estimate"` + TotalTimeSpent int `json:"total_time_spent"` +} + +func (t TimeStats) String() string { + return Stringify(t) +} + +// SetTimeEstimateOptions represents the available SetTimeEstimate() +// options. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/issues.html#set-a-time-estimate-for-an-issue +type SetTimeEstimateOptions struct { + Duration *string `url:"duration,omitempty" json:"duration,omitempty"` +} + +// SetTimeEstimate sets the time estimate for a single project issue. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/issues.html#set-a-time-estimate-for-an-issue +func (s *TimeStatsService) SetTimeEstimate(pid interface{}, issue int, opt *SetTimeEstimateOptions, options ...OptionFunc) (*TimeStats, *Response, error) { + project, err := parseID(pid) + if err != nil { + return nil, nil, err + } + u := fmt.Sprintf("projects/%s/issues/%d/time_estimate", url.QueryEscape(project), issue) + + req, err := s.client.NewRequest("POST", u, opt, options) + if err != nil { + return nil, nil, err + } + + t := new(TimeStats) + resp, err := s.client.Do(req, t) + if err != nil { + return nil, resp, err + } + + return t, resp, err +} + +// ResetTimeEstimate resets the time estimate for a single project issue. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/issues.html#reset-the-time-estimate-for-an-issue +func (s *TimeStatsService) ResetTimeEstimate(pid interface{}, issue int, options ...OptionFunc) (*TimeStats, *Response, error) { + project, err := parseID(pid) + if err != nil { + return nil, nil, err + } + u := fmt.Sprintf("projects/%s/issues/%d/reset_time_estimate", url.QueryEscape(project), issue) + + req, err := s.client.NewRequest("POST", u, nil, options) + if err != nil { + return nil, nil, err + } + + t := new(TimeStats) + resp, err := s.client.Do(req, t) + if err != nil { + return nil, resp, err + } + + return t, resp, err +} + +// AddSpentTimeOptions represents the available AddSpentTime() options. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/issues.html#add-spent-time-for-an-issue +type AddSpentTimeOptions struct { + Duration *string `url:"duration,omitempty" json:"duration,omitempty"` +} + +// AddSpentTime adds spent time for a single project issue. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/issues.html#add-spent-time-for-an-issue +func (s *TimeStatsService) AddSpentTime(pid interface{}, issue int, opt *AddSpentTimeOptions, options ...OptionFunc) (*TimeStats, *Response, error) { + project, err := parseID(pid) + if err != nil { + return nil, nil, err + } + u := fmt.Sprintf("projects/%s/issues/%d/add_spent_time", url.QueryEscape(project), issue) + + req, err := s.client.NewRequest("POST", u, opt, options) + if err != nil { + return nil, nil, err + } + + t := new(TimeStats) + resp, err := s.client.Do(req, t) + if err != nil { + return nil, resp, err + } + + return t, resp, err +} + +// ResetSpentTime resets the spent time for a single project issue. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/issues.html#reset-spent-time-for-an-issue +func (s *TimeStatsService) ResetSpentTime(pid interface{}, issue int, options ...OptionFunc) (*TimeStats, *Response, error) { + project, err := parseID(pid) + if err != nil { + return nil, nil, err + } + u := fmt.Sprintf("projects/%s/issues/%d/reset_spent_time", url.QueryEscape(project), issue) + + req, err := s.client.NewRequest("POST", u, nil, options) + if err != nil { + return nil, nil, err + } + + t := new(TimeStats) + resp, err := s.client.Do(req, t) + if err != nil { + return nil, resp, err + } + + return t, resp, err +} + +// GetTimeSpent gets the spent time for a single project issue. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/issues.html#get-time-tracking-stats +func (s *TimeStatsService) GetTimeSpent(pid interface{}, issue int, options ...OptionFunc) (*TimeStats, *Response, error) { + project, err := parseID(pid) + if err != nil { + return nil, nil, err + } + u := fmt.Sprintf("projects/%s/issues/%d/time_stats", url.QueryEscape(project), issue) + + req, err := s.client.NewRequest("GET", u, nil, options) + if err != nil { + return nil, nil, err + } + + t := new(TimeStats) + resp, err := s.client.Do(req, t) + if err != nil { + return nil, resp, err + } + + return t, resp, err +} diff --git a/vendor/github.com/xanzy/go-gitlab/users.go b/vendor/github.com/xanzy/go-gitlab/users.go new file mode 100644 index 000000000..ba955a82f --- /dev/null +++ b/vendor/github.com/xanzy/go-gitlab/users.go @@ -0,0 +1,584 @@ +// +// Copyright 2015, Sander van Harmelen +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +package gitlab + +import ( + "errors" + "fmt" + "time" +) + +// UsersService handles communication with the user related methods of +// the GitLab API. +// +// GitLab API docs: https://docs.gitlab.com/ce/api/users.html +type UsersService struct { + client *Client +} + +// User represents a GitLab user. +// +// GitLab API docs: https://docs.gitlab.com/ce/api/users.html +type User struct { + ID int `json:"id"` + Username string `json:"username"` + Email string `json:"email"` + Name string `json:"name"` + State string `json:"state"` + CreatedAt *time.Time `json:"created_at"` + Bio string `json:"bio"` + Skype string `json:"skype"` + Linkedin string `json:"linkedin"` + Twitter string `json:"twitter"` + WebsiteURL string `json:"website_url"` + ExternUID string `json:"extern_uid"` + Provider string `json:"provider"` + ThemeID int `json:"theme_id"` + ColorSchemeID int `json:"color_scheme_id"` + IsAdmin bool `json:"is_admin"` + AvatarURL string `json:"avatar_url"` + CanCreateGroup bool `json:"can_create_group"` + CanCreateProject bool `json:"can_create_project"` + ProjectsLimit int `json:"projects_limit"` + CurrentSignInAt *time.Time `json:"current_sign_in_at"` + LastSignInAt *time.Time `json:"last_sign_in_at"` + TwoFactorEnabled bool `json:"two_factor_enabled"` + Identities []*UserIdentity `json:"identities"` +} + +// UserIdentity represents a user identity +type UserIdentity struct { + Provider string `json:"provider"` + ExternUID string `json:"extern_uid"` +} + +// ListUsersOptions represents the available ListUsers() options. +// +// GitLab API docs: https://docs.gitlab.com/ce/api/users.html#list-users +type ListUsersOptions struct { + ListOptions + Active *bool `url:"active,omitempty" json:"active,omitempty"` + Search *string `url:"search,omitempty" json:"search,omitempty"` + Username *string `url:"username,omitempty" json:"username,omitempty"` +} + +// ListUsers gets a list of users. +// +// GitLab API docs: https://docs.gitlab.com/ce/api/users.html#list-users +func (s *UsersService) ListUsers(opt *ListUsersOptions, options ...OptionFunc) ([]*User, *Response, error) { + req, err := s.client.NewRequest("GET", "users", opt, options) + if err != nil { + return nil, nil, err + } + + var usr []*User + resp, err := s.client.Do(req, &usr) + if err != nil { + return nil, resp, err + } + + return usr, resp, err +} + +// GetUser gets a single user. +// +// GitLab API docs: https://docs.gitlab.com/ce/api/users.html#single-user +func (s *UsersService) GetUser(user int, options ...OptionFunc) (*User, *Response, error) { + u := fmt.Sprintf("users/%d", user) + + req, err := s.client.NewRequest("GET", u, nil, options) + if err != nil { + return nil, nil, err + } + + usr := new(User) + resp, err := s.client.Do(req, usr) + if err != nil { + return nil, resp, err + } + + return usr, resp, err +} + +// CreateUserOptions represents the available CreateUser() options. +// +// GitLab API docs: https://docs.gitlab.com/ce/api/users.html#user-creation +type CreateUserOptions struct { + Email *string `url:"email,omitempty" json:"email,omitempty"` + Password *string `url:"password,omitempty" json:"password,omitempty"` + Username *string `url:"username,omitempty" json:"username,omitempty"` + Name *string `url:"name,omitempty" json:"name,omitempty"` + Skype *string `url:"skype,omitempty" json:"skype,omitempty"` + Linkedin *string `url:"linkedin,omitempty" json:"linkedin,omitempty"` + Twitter *string `url:"twitter,omitempty" json:"twitter,omitempty"` + WebsiteURL *string `url:"website_url,omitempty" json:"website_url,omitempty"` + ProjectsLimit *int `url:"projects_limit,omitempty" json:"projects_limit,omitempty"` + ExternUID *string `url:"extern_uid,omitempty" json:"extern_uid,omitempty"` + Provider *string `url:"provider,omitempty" json:"provider,omitempty"` + Bio *string `url:"bio,omitempty" json:"bio,omitempty"` + Admin *bool `url:"admin,omitempty" json:"admin,omitempty"` + CanCreateGroup *bool `url:"can_create_group,omitempty" json:"can_create_group,omitempty"` + Confirm *bool `url:"confirm,omitempty" json:"confirm,omitempty"` +} + +// CreateUser creates a new user. Note only administrators can create new users. +// +// GitLab API docs: https://docs.gitlab.com/ce/api/users.html#user-creation +func (s *UsersService) CreateUser(opt *CreateUserOptions, options ...OptionFunc) (*User, *Response, error) { + req, err := s.client.NewRequest("POST", "users", opt, options) + if err != nil { + return nil, nil, err + } + + usr := new(User) + resp, err := s.client.Do(req, usr) + if err != nil { + return nil, resp, err + } + + return usr, resp, err +} + +// ModifyUserOptions represents the available ModifyUser() options. +// +// GitLab API docs: https://docs.gitlab.com/ce/api/users.html#user-modification +type ModifyUserOptions struct { + Email *string `url:"email,omitempty" json:"email,omitempty"` + Password *string `url:"password,omitempty" json:"password,omitempty"` + Username *string `url:"username,omitempty" json:"username,omitempty"` + Name *string `url:"name,omitempty" json:"name,omitempty"` + Skype *string `url:"skype,omitempty" json:"skype,omitempty"` + Linkedin *string `url:"linkedin,omitempty" json:"linkedin,omitempty"` + Twitter *string `url:"twitter,omitempty" json:"twitter,omitempty"` + WebsiteURL *string `url:"website_url,omitempty" json:"website_url,omitempty"` + ProjectsLimit *int `url:"projects_limit,omitempty" json:"projects_limit,omitempty"` + ExternUID *string `url:"extern_uid,omitempty" json:"extern_uid,omitempty"` + Provider *string `url:"provider,omitempty" json:"provider,omitempty"` + Bio *string `url:"bio,omitempty" json:"bio,omitempty"` + Admin *bool `url:"admin,omitempty" json:"admin,omitempty"` + CanCreateGroup *bool `url:"can_create_group,omitempty" json:"can_create_group,omitempty"` +} + +// ModifyUser modifies an existing user. Only administrators can change attributes +// of a user. +// +// GitLab API docs: https://docs.gitlab.com/ce/api/users.html#user-modification +func (s *UsersService) ModifyUser(user int, opt *ModifyUserOptions, options ...OptionFunc) (*User, *Response, error) { + u := fmt.Sprintf("users/%d", user) + + req, err := s.client.NewRequest("PUT", u, opt, options) + if err != nil { + return nil, nil, err + } + + usr := new(User) + resp, err := s.client.Do(req, usr) + if err != nil { + return nil, resp, err + } + + return usr, resp, err +} + +// DeleteUser deletes a user. Available only for administrators. This is an +// idempotent function, calling this function for a non-existent user id still +// returns a status code 200 OK. The JSON response differs if the user was +// actually deleted or not. In the former the user is returned and in the +// latter not. +// +// GitLab API docs: https://docs.gitlab.com/ce/api/users.html#user-deletion +func (s *UsersService) DeleteUser(user int, options ...OptionFunc) (*Response, error) { + u := fmt.Sprintf("users/%d", user) + + req, err := s.client.NewRequest("DELETE", u, nil, options) + if err != nil { + return nil, err + } + + return s.client.Do(req, nil) +} + +// CurrentUser gets currently authenticated user. +// +// GitLab API docs: https://docs.gitlab.com/ce/api/users.html#current-user +func (s *UsersService) CurrentUser(options ...OptionFunc) (*User, *Response, error) { + req, err := s.client.NewRequest("GET", "user", nil, options) + if err != nil { + return nil, nil, err + } + + usr := new(User) + resp, err := s.client.Do(req, usr) + if err != nil { + return nil, resp, err + } + + return usr, resp, err +} + +// SSHKey represents a SSH key. +// +// GitLab API docs: https://docs.gitlab.com/ce/api/users.html#list-ssh-keys +type SSHKey struct { + ID int `json:"id"` + Title string `json:"title"` + Key string `json:"key"` + CreatedAt *time.Time `json:"created_at"` +} + +// ListSSHKeys gets a list of currently authenticated user's SSH keys. +// +// GitLab API docs: https://docs.gitlab.com/ce/api/users.html#list-ssh-keys +func (s *UsersService) ListSSHKeys(options ...OptionFunc) ([]*SSHKey, *Response, error) { + req, err := s.client.NewRequest("GET", "user/keys", nil, options) + if err != nil { + return nil, nil, err + } + + var k []*SSHKey + resp, err := s.client.Do(req, &k) + if err != nil { + return nil, resp, err + } + + return k, resp, err +} + +// ListSSHKeysForUser gets a list of a specified user's SSH keys. Available +// only for admin +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/users.html#list-ssh-keys-for-user +func (s *UsersService) ListSSHKeysForUser(user int, options ...OptionFunc) ([]*SSHKey, *Response, error) { + u := fmt.Sprintf("users/%d/keys", user) + + req, err := s.client.NewRequest("GET", u, nil, options) + if err != nil { + return nil, nil, err + } + + var k []*SSHKey + resp, err := s.client.Do(req, &k) + if err != nil { + return nil, resp, err + } + + return k, resp, err +} + +// GetSSHKey gets a single key. +// +// GitLab API docs: https://docs.gitlab.com/ce/api/users.html#single-ssh-key +func (s *UsersService) GetSSHKey(kid int, options ...OptionFunc) (*SSHKey, *Response, error) { + u := fmt.Sprintf("user/keys/%d", kid) + + req, err := s.client.NewRequest("GET", u, nil, options) + if err != nil { + return nil, nil, err + } + + k := new(SSHKey) + resp, err := s.client.Do(req, k) + if err != nil { + return nil, resp, err + } + + return k, resp, err +} + +// AddSSHKeyOptions represents the available AddSSHKey() options. +// +// GitLab API docs: https://docs.gitlab.com/ce/api/projects.html#add-ssh-key +type AddSSHKeyOptions struct { + Title *string `url:"title,omitempty" json:"title,omitempty"` + Key *string `url:"key,omitempty" json:"key,omitempty"` +} + +// AddSSHKey creates a new key owned by the currently authenticated user. +// +// GitLab API docs: https://docs.gitlab.com/ce/api/users.html#add-ssh-key +func (s *UsersService) AddSSHKey(opt *AddSSHKeyOptions, options ...OptionFunc) (*SSHKey, *Response, error) { + req, err := s.client.NewRequest("POST", "user/keys", opt, options) + if err != nil { + return nil, nil, err + } + + k := new(SSHKey) + resp, err := s.client.Do(req, k) + if err != nil { + return nil, resp, err + } + + return k, resp, err +} + +// AddSSHKeyForUser creates new key owned by specified user. Available only for +// admin. +// +// GitLab API docs: https://docs.gitlab.com/ce/api/users.html#add-ssh-key-for-user +func (s *UsersService) AddSSHKeyForUser(user int, opt *AddSSHKeyOptions, options ...OptionFunc) (*SSHKey, *Response, error) { + u := fmt.Sprintf("users/%d/keys", user) + + req, err := s.client.NewRequest("POST", u, opt, options) + if err != nil { + return nil, nil, err + } + + k := new(SSHKey) + resp, err := s.client.Do(req, k) + if err != nil { + return nil, resp, err + } + + return k, resp, err +} + +// DeleteSSHKey deletes key owned by currently authenticated user. This is an +// idempotent function and calling it on a key that is already deleted or not +// available results in 200 OK. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/users.html#delete-ssh-key-for-current-owner +func (s *UsersService) DeleteSSHKey(kid int, options ...OptionFunc) (*Response, error) { + u := fmt.Sprintf("user/keys/%d", kid) + + req, err := s.client.NewRequest("DELETE", u, nil, options) + if err != nil { + return nil, err + } + + return s.client.Do(req, nil) +} + +// DeleteSSHKeyForUser deletes key owned by a specified user. Available only +// for admin. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/users.html#delete-ssh-key-for-given-user +func (s *UsersService) DeleteSSHKeyForUser(user int, kid int, options ...OptionFunc) (*Response, error) { + u := fmt.Sprintf("users/%d/keys/%d", user, kid) + + req, err := s.client.NewRequest("DELETE", u, nil, options) + if err != nil { + return nil, err + } + + return s.client.Do(req, nil) +} + +// BlockUser blocks the specified user. Available only for admin. +// +// GitLab API docs: https://docs.gitlab.com/ce/api/users.html#block-user +func (s *UsersService) BlockUser(user int, options ...OptionFunc) error { + u := fmt.Sprintf("users/%d/block", user) + + req, err := s.client.NewRequest("PUT", u, nil, options) + if err != nil { + return err + } + + resp, err := s.client.Do(req, nil) + if err != nil { + return err + } + + switch resp.StatusCode { + case 200: + return nil + case 403: + return errors.New("Cannot block a user that is already blocked by LDAP synchronization") + case 404: + return errors.New("User does not exists") + default: + return fmt.Errorf("Received unexpected result code: %d", resp.StatusCode) + } +} + +// UnblockUser unblocks the specified user. Available only for admin. +// +// GitLab API docs: https://docs.gitlab.com/ce/api/users.html#unblock-user +func (s *UsersService) UnblockUser(user int, options ...OptionFunc) error { + u := fmt.Sprintf("users/%d/unblock", user) + + req, err := s.client.NewRequest("PUT", u, nil, options) + if err != nil { + return err + } + + resp, err := s.client.Do(req, nil) + if err != nil { + return err + } + + switch resp.StatusCode { + case 200: + return nil + case 403: + return errors.New("Cannot unblock a user that is blocked by LDAP synchronization") + case 404: + return errors.New("User does not exists") + default: + return fmt.Errorf("Received unexpected result code: %d", resp.StatusCode) + } +} + +// Email represents an Email. +// +// GitLab API docs: https://doc.gitlab.com/ce/api/users.html#list-emails +type Email struct { + ID int `json:"id"` + Email string `json:"email"` +} + +// ListEmails gets a list of currently authenticated user's Emails. +// +// GitLab API docs: https://docs.gitlab.com/ce/api/users.html#list-emails +func (s *UsersService) ListEmails(options ...OptionFunc) ([]*Email, *Response, error) { + req, err := s.client.NewRequest("GET", "user/emails", nil, options) + if err != nil { + return nil, nil, err + } + + var e []*Email + resp, err := s.client.Do(req, &e) + if err != nil { + return nil, resp, err + } + + return e, resp, err +} + +// ListEmailsForUser gets a list of a specified user's Emails. Available +// only for admin +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/users.html#list-emails-for-user +func (s *UsersService) ListEmailsForUser(uid int, options ...OptionFunc) ([]*Email, *Response, error) { + u := fmt.Sprintf("users/%d/emails", uid) + + req, err := s.client.NewRequest("GET", u, nil, options) + if err != nil { + return nil, nil, err + } + + var e []*Email + resp, err := s.client.Do(req, &e) + if err != nil { + return nil, resp, err + } + + return e, resp, err +} + +// GetEmail gets a single email. +// +// GitLab API docs: https://docs.gitlab.com/ce/api/users.html#single-email +func (s *UsersService) GetEmail(eid int, options ...OptionFunc) (*Email, *Response, error) { + u := fmt.Sprintf("user/emails/%d", eid) + + req, err := s.client.NewRequest("GET", u, nil, options) + if err != nil { + return nil, nil, err + } + + e := new(Email) + resp, err := s.client.Do(req, e) + if err != nil { + return nil, resp, err + } + + return e, resp, err +} + +// AddEmailOptions represents the available AddEmail() options. +// +// GitLab API docs: https://docs.gitlab.com/ce/api/projects.html#add-email +type AddEmailOptions struct { + Email *string `url:"email,omitempty" json:"email,omitempty"` +} + +// AddEmail creates a new email owned by the currently authenticated user. +// +// GitLab API docs: https://docs.gitlab.com/ce/api/users.html#add-email +func (s *UsersService) AddEmail(opt *AddEmailOptions, options ...OptionFunc) (*Email, *Response, error) { + req, err := s.client.NewRequest("POST", "user/emails", opt, options) + if err != nil { + return nil, nil, err + } + + e := new(Email) + resp, err := s.client.Do(req, e) + if err != nil { + return nil, resp, err + } + + return e, resp, err +} + +// AddEmailForUser creates new email owned by specified user. Available only for +// admin. +// +// GitLab API docs: https://docs.gitlab.com/ce/api/users.html#add-email-for-user +func (s *UsersService) AddEmailForUser(uid int, opt *AddEmailOptions, options ...OptionFunc) (*Email, *Response, error) { + u := fmt.Sprintf("users/%d/emails", uid) + + req, err := s.client.NewRequest("POST", u, opt, options) + if err != nil { + return nil, nil, err + } + + e := new(Email) + resp, err := s.client.Do(req, e) + if err != nil { + return nil, resp, err + } + + return e, resp, err +} + +// DeleteEmail deletes email owned by currently authenticated user. This is an +// idempotent function and calling it on a key that is already deleted or not +// available results in 200 OK. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/users.html#delete-email-for-current-owner +func (s *UsersService) DeleteEmail(eid int, options ...OptionFunc) (*Response, error) { + u := fmt.Sprintf("user/emails/%d", eid) + + req, err := s.client.NewRequest("DELETE", u, nil, options) + if err != nil { + return nil, err + } + + return s.client.Do(req, nil) +} + +// DeleteEmailForUser deletes email owned by a specified user. Available only +// for admin. +// +// GitLab API docs: +// https://docs.gitlab.com/ce/api/users.html#delete-email-for-given-user +func (s *UsersService) DeleteEmailForUser(uid int, eid int, options ...OptionFunc) (*Response, error) { + u := fmt.Sprintf("users/%d/emails/%d", uid, eid) + + req, err := s.client.NewRequest("DELETE", u, nil, options) + if err != nil { + return nil, err + } + + return s.client.Do(req, nil) +} diff --git a/vendor/google.golang.org/api/bigquery/v2/bigquery-api.json b/vendor/google.golang.org/api/bigquery/v2/bigquery-api.json new file mode 100644 index 000000000..93a4ec3d6 --- /dev/null +++ b/vendor/google.golang.org/api/bigquery/v2/bigquery-api.json @@ -0,0 +1,2787 @@ +{ + "kind": "discovery#restDescription", + "etag": "\"tbys6C40o18GZwyMen5GMkdK-3s/2pbHVnKgRBtlI769YwDOp1uiQ0w\"", + "discoveryVersion": "v1", + "id": "bigquery:v2", + "name": "bigquery", + "version": "v2", + "revision": "20170224", + "title": "BigQuery API", + "description": "A data platform for customers to create, manage, share and query data.", + "ownerDomain": "google.com", + "ownerName": "Google", + "icons": { + "x16": "https://www.google.com/images/icons/product/search-16.gif", + "x32": "https://www.google.com/images/icons/product/search-32.gif" + }, + "documentationLink": "https://cloud.google.com/bigquery/", + "protocol": "rest", + "baseUrl": "https://www.googleapis.com/bigquery/v2/", + "basePath": "/bigquery/v2/", + "rootUrl": "https://www.googleapis.com/", + "servicePath": "bigquery/v2/", + "batchPath": "batch", + "parameters": { + "alt": { + "type": "string", + "description": "Data format for the response.", + "default": "json", + "enum": [ + "json" + ], + "enumDescriptions": [ + "Responses with Content-Type of application/json" + ], + "location": "query" + }, + "fields": { + "type": "string", + "description": "Selector specifying which fields to include in a partial response.", + "location": "query" + }, + "key": { + "type": "string", + "description": "API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.", + "location": "query" + }, + "oauth_token": { + "type": "string", + "description": "OAuth 2.0 token for the current user.", + "location": "query" + }, + "prettyPrint": { + "type": "boolean", + "description": "Returns response with indentations and line breaks.", + "default": "true", + "location": "query" + }, + "quotaUser": { + "type": "string", + "description": "Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided.", + "location": "query" + }, + "userIp": { + "type": "string", + "description": "IP address of the site where the request originates. Use this if you want to enforce per-user limits.", + "location": "query" + } + }, + "auth": { + "oauth2": { + "scopes": { + "https://www.googleapis.com/auth/bigquery": { + "description": "View and manage your data in Google BigQuery" + }, + "https://www.googleapis.com/auth/bigquery.insertdata": { + "description": "Insert data into Google BigQuery" + }, + "https://www.googleapis.com/auth/cloud-platform": { + "description": "View and manage your data across Google Cloud Platform services" + }, + "https://www.googleapis.com/auth/cloud-platform.read-only": { + "description": "View your data across Google Cloud Platform services" + }, + "https://www.googleapis.com/auth/devstorage.full_control": { + "description": "Manage your data and permissions in Google Cloud Storage" + }, + "https://www.googleapis.com/auth/devstorage.read_only": { + "description": "View your data in Google Cloud Storage" + }, + "https://www.googleapis.com/auth/devstorage.read_write": { + "description": "Manage your data in Google Cloud Storage" + } + } + } + }, + "schemas": { + "BigtableColumn": { + "id": "BigtableColumn", + "type": "object", + "properties": { + "encoding": { + "type": "string", + "description": "[Optional] The encoding of the values when the type is not STRING. Acceptable encoding values are: TEXT - indicates values are alphanumeric text strings. BINARY - indicates values are encoded using HBase Bytes.toBytes family of functions. 'encoding' can also be set at the column family level. However, the setting at this level takes precedence if 'encoding' is set at both levels." + }, + "fieldName": { + "type": "string", + "description": "[Optional] If the qualifier is not a valid BigQuery field identifier i.e. does not match [a-zA-Z][a-zA-Z0-9_]*, a valid identifier must be provided as the column field name and is used as field name in queries." + }, + "onlyReadLatest": { + "type": "boolean", + "description": "[Optional] If this is set, only the latest version of value in this column are exposed. 'onlyReadLatest' can also be set at the column family level. However, the setting at this level takes precedence if 'onlyReadLatest' is set at both levels." + }, + "qualifierEncoded": { + "type": "string", + "description": "[Required] Qualifier of the column. Columns in the parent column family that has this exact qualifier are exposed as . field. If the qualifier is valid UTF-8 string, it can be specified in the qualifier_string field. Otherwise, a base-64 encoded value must be set to qualifier_encoded. The column field name is the same as the column qualifier. However, if the qualifier is not a valid BigQuery field identifier i.e. does not match [a-zA-Z][a-zA-Z0-9_]*, a valid identifier must be provided as field_name.", + "format": "byte" + }, + "qualifierString": { + "type": "string" + }, + "type": { + "type": "string", + "description": "[Optional] The type to convert the value in cells of this column. The values are expected to be encoded using HBase Bytes.toBytes function when using the BINARY encoding value. Following BigQuery types are allowed (case-sensitive) - BYTES STRING INTEGER FLOAT BOOLEAN Default type is BYTES. 'type' can also be set at the column family level. However, the setting at this level takes precedence if 'type' is set at both levels." + } + } + }, + "BigtableColumnFamily": { + "id": "BigtableColumnFamily", + "type": "object", + "properties": { + "columns": { + "type": "array", + "description": "[Optional] Lists of columns that should be exposed as individual fields as opposed to a list of (column name, value) pairs. All columns whose qualifier matches a qualifier in this list can be accessed as .. Other columns can be accessed as a list through .Column field.", + "items": { + "$ref": "BigtableColumn" + } + }, + "encoding": { + "type": "string", + "description": "[Optional] The encoding of the values when the type is not STRING. Acceptable encoding values are: TEXT - indicates values are alphanumeric text strings. BINARY - indicates values are encoded using HBase Bytes.toBytes family of functions. This can be overridden for a specific column by listing that column in 'columns' and specifying an encoding for it." + }, + "familyId": { + "type": "string", + "description": "Identifier of the column family." + }, + "onlyReadLatest": { + "type": "boolean", + "description": "[Optional] If this is set only the latest version of value are exposed for all columns in this column family. This can be overridden for a specific column by listing that column in 'columns' and specifying a different setting for that column." + }, + "type": { + "type": "string", + "description": "[Optional] The type to convert the value in cells of this column family. The values are expected to be encoded using HBase Bytes.toBytes function when using the BINARY encoding value. Following BigQuery types are allowed (case-sensitive) - BYTES STRING INTEGER FLOAT BOOLEAN Default type is BYTES. This can be overridden for a specific column by listing that column in 'columns' and specifying a type for it." + } + } + }, + "BigtableOptions": { + "id": "BigtableOptions", + "type": "object", + "properties": { + "columnFamilies": { + "type": "array", + "description": "[Optional] List of column families to expose in the table schema along with their types. This list restricts the column families that can be referenced in queries and specifies their value types. You can use this list to do type conversions - see the 'type' field for more details. If you leave this list empty, all column families are present in the table schema and their values are read as BYTES. During a query only the column families referenced in that query are read from Bigtable.", + "items": { + "$ref": "BigtableColumnFamily" + } + }, + "ignoreUnspecifiedColumnFamilies": { + "type": "boolean", + "description": "[Optional] If field is true, then the column families that are not specified in columnFamilies list are not exposed in the table schema. Otherwise, they are read with BYTES type values. The default value is false." + }, + "readRowkeyAsString": { + "type": "boolean", + "description": "[Optional] If field is true, then the rowkey column families will be read and converted to string. Otherwise they are read with BYTES type values and users need to manually cast them with CAST if necessary. The default value is false." + } + } + }, + "CsvOptions": { + "id": "CsvOptions", + "type": "object", + "properties": { + "allowJaggedRows": { + "type": "boolean", + "description": "[Optional] Indicates if BigQuery should accept rows that are missing trailing optional columns. If true, BigQuery treats missing trailing columns as null values. If false, records with missing trailing columns are treated as bad records, and if there are too many bad records, an invalid error is returned in the job result. The default value is false." + }, + "allowQuotedNewlines": { + "type": "boolean", + "description": "[Optional] Indicates if BigQuery should allow quoted data sections that contain newline characters in a CSV file. The default value is false." + }, + "encoding": { + "type": "string", + "description": "[Optional] The character encoding of the data. The supported values are UTF-8 or ISO-8859-1. The default value is UTF-8. BigQuery decodes the data after the raw, binary data has been split using the values of the quote and fieldDelimiter properties." + }, + "fieldDelimiter": { + "type": "string", + "description": "[Optional] The separator for fields in a CSV file. BigQuery converts the string to ISO-8859-1 encoding, and then uses the first byte of the encoded string to split the data in its raw, binary state. BigQuery also supports the escape sequence \"\\t\" to specify a tab separator. The default value is a comma (',')." + }, + "quote": { + "type": "string", + "description": "[Optional] The value that is used to quote data sections in a CSV file. BigQuery converts the string to ISO-8859-1 encoding, and then uses the first byte of the encoded string to split the data in its raw, binary state. The default value is a double-quote ('\"'). If your data does not contain quoted sections, set the property value to an empty string. If your data contains quoted newline characters, you must also set the allowQuotedNewlines property to true.", + "default": "\"", + "pattern": ".?" + }, + "skipLeadingRows": { + "type": "string", + "description": "[Optional] The number of rows at the top of a CSV file that BigQuery will skip when reading the data. The default value is 0. This property is useful if you have header rows in the file that should be skipped.", + "format": "int64" + } + } + }, + "Dataset": { + "id": "Dataset", + "type": "object", + "properties": { + "access": { + "type": "array", + "description": "[Optional] An array of objects that define dataset access for one or more entities. You can set this property when inserting or updating a dataset in order to control who is allowed to access the data. If unspecified at dataset creation time, BigQuery adds default dataset access for the following entities: access.specialGroup: projectReaders; access.role: READER; access.specialGroup: projectWriters; access.role: WRITER; access.specialGroup: projectOwners; access.role: OWNER; access.userByEmail: [dataset creator email]; access.role: OWNER;", + "items": { + "type": "object", + "properties": { + "domain": { + "type": "string", + "description": "[Pick one] A domain to grant access to. Any users signed in with the domain specified will be granted the specified access. Example: \"example.com\"." + }, + "groupByEmail": { + "type": "string", + "description": "[Pick one] An email address of a Google Group to grant access to." + }, + "role": { + "type": "string", + "description": "[Required] Describes the rights granted to the user specified by the other member of the access object. The following string values are supported: READER, WRITER, OWNER." + }, + "specialGroup": { + "type": "string", + "description": "[Pick one] A special group to grant access to. Possible values include: projectOwners: Owners of the enclosing project. projectReaders: Readers of the enclosing project. projectWriters: Writers of the enclosing project. allAuthenticatedUsers: All authenticated BigQuery users." + }, + "userByEmail": { + "type": "string", + "description": "[Pick one] An email address of a user to grant access to. For example: fred@example.com." + }, + "view": { + "$ref": "TableReference", + "description": "[Pick one] A view from a different dataset to grant access to. Queries executed against that view will have read access to tables in this dataset. The role field is not required when this field is set. If that view is updated by any user, access to the view needs to be granted again via an update operation." + } + } + } + }, + "creationTime": { + "type": "string", + "description": "[Output-only] The time when this dataset was created, in milliseconds since the epoch.", + "format": "int64" + }, + "datasetReference": { + "$ref": "DatasetReference", + "description": "[Required] A reference that identifies the dataset." + }, + "defaultTableExpirationMs": { + "type": "string", + "description": "[Optional] The default lifetime of all tables in the dataset, in milliseconds. The minimum value is 3600000 milliseconds (one hour). Once this property is set, all newly-created tables in the dataset will have an expirationTime property set to the creation time plus the value in this property, and changing the value will only affect new tables, not existing ones. When the expirationTime for a given table is reached, that table will be deleted automatically. If a table's expirationTime is modified or removed before the table expires, or if you provide an explicit expirationTime when creating a table, that value takes precedence over the default expiration time indicated by this property.", + "format": "int64" + }, + "description": { + "type": "string", + "description": "[Optional] A user-friendly description of the dataset." + }, + "etag": { + "type": "string", + "description": "[Output-only] A hash of the resource." + }, + "friendlyName": { + "type": "string", + "description": "[Optional] A descriptive name for the dataset." + }, + "id": { + "type": "string", + "description": "[Output-only] The fully-qualified unique name of the dataset in the format projectId:datasetId. The dataset name without the project name is given in the datasetId field. When creating a new dataset, leave this field blank, and instead specify the datasetId field." + }, + "kind": { + "type": "string", + "description": "[Output-only] The resource type.", + "default": "bigquery#dataset" + }, + "labels": { + "type": "object", + "description": "[Experimental] The labels associated with this dataset. You can use these to organize and group your datasets. You can set this property when inserting or updating a dataset. See Labeling Datasets for more information.", + "additionalProperties": { + "type": "string" + } + }, + "lastModifiedTime": { + "type": "string", + "description": "[Output-only] The date when this dataset or any of its tables was last modified, in milliseconds since the epoch.", + "format": "int64" + }, + "location": { + "type": "string", + "description": "[Experimental] The geographic location where the dataset should reside. Possible values include EU and US. The default value is US." + }, + "selfLink": { + "type": "string", + "description": "[Output-only] A URL that can be used to access the resource again. You can use this URL in Get or Update requests to the resource." + } + } + }, + "DatasetList": { + "id": "DatasetList", + "type": "object", + "properties": { + "datasets": { + "type": "array", + "description": "An array of the dataset resources in the project. Each resource contains basic information. For full information about a particular dataset resource, use the Datasets: get method. This property is omitted when there are no datasets in the project.", + "items": { + "type": "object", + "properties": { + "datasetReference": { + "$ref": "DatasetReference", + "description": "The dataset reference. Use this property to access specific parts of the dataset's ID, such as project ID or dataset ID." + }, + "friendlyName": { + "type": "string", + "description": "A descriptive name for the dataset, if one exists." + }, + "id": { + "type": "string", + "description": "The fully-qualified, unique, opaque ID of the dataset." + }, + "kind": { + "type": "string", + "description": "The resource type. This property always returns the value \"bigquery#dataset\".", + "default": "bigquery#dataset" + }, + "labels": { + "type": "object", + "description": "[Experimental] The labels associated with this dataset. You can use these to organize and group your datasets.", + "additionalProperties": { + "type": "string" + } + } + } + } + }, + "etag": { + "type": "string", + "description": "A hash value of the results page. You can use this property to determine if the page has changed since the last request." + }, + "kind": { + "type": "string", + "description": "The list type. This property always returns the value \"bigquery#datasetList\".", + "default": "bigquery#datasetList" + }, + "nextPageToken": { + "type": "string", + "description": "A token that can be used to request the next results page. This property is omitted on the final results page." + } + } + }, + "DatasetReference": { + "id": "DatasetReference", + "type": "object", + "properties": { + "datasetId": { + "type": "string", + "description": "[Required] A unique ID for this dataset, without the project name. The ID must contain only letters (a-z, A-Z), numbers (0-9), or underscores (_). The maximum length is 1,024 characters.", + "annotations": { + "required": [ + "bigquery.datasets.update" + ] + } + }, + "projectId": { + "type": "string", + "description": "[Optional] The ID of the project containing this dataset.", + "annotations": { + "required": [ + "bigquery.datasets.update" + ] + } + } + } + }, + "ErrorProto": { + "id": "ErrorProto", + "type": "object", + "properties": { + "debugInfo": { + "type": "string", + "description": "Debugging information. This property is internal to Google and should not be used." + }, + "location": { + "type": "string", + "description": "Specifies where the error occurred, if present." + }, + "message": { + "type": "string", + "description": "A human-readable description of the error." + }, + "reason": { + "type": "string", + "description": "A short error code that summarizes the error." + } + } + }, + "ExplainQueryStage": { + "id": "ExplainQueryStage", + "type": "object", + "properties": { + "computeRatioAvg": { + "type": "number", + "description": "Relative amount of time the average shard spent on CPU-bound tasks.", + "format": "double" + }, + "computeRatioMax": { + "type": "number", + "description": "Relative amount of time the slowest shard spent on CPU-bound tasks.", + "format": "double" + }, + "id": { + "type": "string", + "description": "Unique ID for stage within plan.", + "format": "int64" + }, + "name": { + "type": "string", + "description": "Human-readable name for stage." + }, + "readRatioAvg": { + "type": "number", + "description": "Relative amount of time the average shard spent reading input.", + "format": "double" + }, + "readRatioMax": { + "type": "number", + "description": "Relative amount of time the slowest shard spent reading input.", + "format": "double" + }, + "recordsRead": { + "type": "string", + "description": "Number of records read into the stage.", + "format": "int64" + }, + "recordsWritten": { + "type": "string", + "description": "Number of records written by the stage.", + "format": "int64" + }, + "status": { + "type": "string", + "description": "Current status for the stage." + }, + "steps": { + "type": "array", + "description": "List of operations within the stage in dependency order (approximately chronological).", + "items": { + "$ref": "ExplainQueryStep" + } + }, + "waitRatioAvg": { + "type": "number", + "description": "Relative amount of time the average shard spent waiting to be scheduled.", + "format": "double" + }, + "waitRatioMax": { + "type": "number", + "description": "Relative amount of time the slowest shard spent waiting to be scheduled.", + "format": "double" + }, + "writeRatioAvg": { + "type": "number", + "description": "Relative amount of time the average shard spent on writing output.", + "format": "double" + }, + "writeRatioMax": { + "type": "number", + "description": "Relative amount of time the slowest shard spent on writing output.", + "format": "double" + } + } + }, + "ExplainQueryStep": { + "id": "ExplainQueryStep", + "type": "object", + "properties": { + "kind": { + "type": "string", + "description": "Machine-readable operation type." + }, + "substeps": { + "type": "array", + "description": "Human-readable stage descriptions.", + "items": { + "type": "string" + } + } + } + }, + "ExternalDataConfiguration": { + "id": "ExternalDataConfiguration", + "type": "object", + "properties": { + "autodetect": { + "type": "boolean", + "description": "[Experimental] Try to detect schema and format options automatically. Any option specified explicitly will be honored." + }, + "bigtableOptions": { + "$ref": "BigtableOptions", + "description": "[Optional] Additional options if sourceFormat is set to BIGTABLE." + }, + "compression": { + "type": "string", + "description": "[Optional] The compression type of the data source. Possible values include GZIP and NONE. The default value is NONE. This setting is ignored for Google Cloud Bigtable, Google Cloud Datastore backups and Avro formats." + }, + "csvOptions": { + "$ref": "CsvOptions", + "description": "Additional properties to set if sourceFormat is set to CSV." + }, + "googleSheetsOptions": { + "$ref": "GoogleSheetsOptions", + "description": "[Optional] Additional options if sourceFormat is set to GOOGLE_SHEETS." + }, + "ignoreUnknownValues": { + "type": "boolean", + "description": "[Optional] Indicates if BigQuery should allow extra values that are not represented in the table schema. If true, the extra values are ignored. If false, records with extra columns are treated as bad records, and if there are too many bad records, an invalid error is returned in the job result. The default value is false. The sourceFormat property determines what BigQuery treats as an extra value: CSV: Trailing columns JSON: Named values that don't match any column names Google Cloud Bigtable: This setting is ignored. Google Cloud Datastore backups: This setting is ignored. Avro: This setting is ignored." + }, + "maxBadRecords": { + "type": "integer", + "description": "[Optional] The maximum number of bad records that BigQuery can ignore when reading data. If the number of bad records exceeds this value, an invalid error is returned in the job result. The default value is 0, which requires that all records are valid. This setting is ignored for Google Cloud Bigtable, Google Cloud Datastore backups and Avro formats.", + "format": "int32" + }, + "schema": { + "$ref": "TableSchema", + "description": "[Optional] The schema for the data. Schema is required for CSV and JSON formats. Schema is disallowed for Google Cloud Bigtable, Cloud Datastore backups, and Avro formats." + }, + "sourceFormat": { + "type": "string", + "description": "[Required] The data format. For CSV files, specify \"CSV\". For Google sheets, specify \"GOOGLE_SHEETS\". For newline-delimited JSON, specify \"NEWLINE_DELIMITED_JSON\". For Avro files, specify \"AVRO\". For Google Cloud Datastore backups, specify \"DATASTORE_BACKUP\". [Experimental] For Google Cloud Bigtable, specify \"BIGTABLE\". Please note that reading from Google Cloud Bigtable is experimental and has to be enabled for your project. Please contact Google Cloud Support to enable this for your project." + }, + "sourceUris": { + "type": "array", + "description": "[Required] The fully-qualified URIs that point to your data in Google Cloud. For Google Cloud Storage URIs: Each URI can contain one '*' wildcard character and it must come after the 'bucket' name. Size limits related to load jobs apply to external data sources. For Google Cloud Bigtable URIs: Exactly one URI can be specified and it has be a fully specified and valid HTTPS URL for a Google Cloud Bigtable table. For Google Cloud Datastore backups, exactly one URI can be specified, and it must end with '.backup_info'. Also, the '*' wildcard character is not allowed.", + "items": { + "type": "string" + } + } + } + }, + "GetQueryResultsResponse": { + "id": "GetQueryResultsResponse", + "type": "object", + "properties": { + "cacheHit": { + "type": "boolean", + "description": "Whether the query result was fetched from the query cache." + }, + "errors": { + "type": "array", + "description": "[Output-only] All errors and warnings encountered during the running of the job. Errors here do not necessarily mean that the job has completed or was unsuccessful.", + "items": { + "$ref": "ErrorProto" + } + }, + "etag": { + "type": "string", + "description": "A hash of this response." + }, + "jobComplete": { + "type": "boolean", + "description": "Whether the query has completed or not. If rows or totalRows are present, this will always be true. If this is false, totalRows will not be available." + }, + "jobReference": { + "$ref": "JobReference", + "description": "Reference to the BigQuery Job that was created to run the query. This field will be present even if the original request timed out, in which case GetQueryResults can be used to read the results once the query has completed. Since this API only returns the first page of results, subsequent pages can be fetched via the same mechanism (GetQueryResults)." + }, + "kind": { + "type": "string", + "description": "The resource type of the response.", + "default": "bigquery#getQueryResultsResponse" + }, + "numDmlAffectedRows": { + "type": "string", + "description": "[Output-only, Experimental] The number of rows affected by a DML statement. Present only for DML statements INSERT, UPDATE or DELETE.", + "format": "int64" + }, + "pageToken": { + "type": "string", + "description": "A token used for paging results." + }, + "rows": { + "type": "array", + "description": "An object with as many results as can be contained within the maximum permitted reply size. To get any additional rows, you can call GetQueryResults and specify the jobReference returned above. Present only when the query completes successfully.", + "items": { + "$ref": "TableRow" + } + }, + "schema": { + "$ref": "TableSchema", + "description": "The schema of the results. Present only when the query completes successfully." + }, + "totalBytesProcessed": { + "type": "string", + "description": "The total number of bytes processed for this query.", + "format": "int64" + }, + "totalRows": { + "type": "string", + "description": "The total number of rows in the complete query result set, which can be more than the number of rows in this single page of results. Present only when the query completes successfully.", + "format": "uint64" + } + } + }, + "GoogleSheetsOptions": { + "id": "GoogleSheetsOptions", + "type": "object", + "properties": { + "skipLeadingRows": { + "type": "string", + "description": "[Optional] The number of rows at the top of a sheet that BigQuery will skip when reading the data. The default value is 0. This property is useful if you have header rows that should be skipped. When autodetect is on, behavior is the following: * skipLeadingRows unspecified - Autodetect tries to detect headers in the first row. If they are not detected, the row is read as data. Otherwise data is read starting from the second row. * skipLeadingRows is 0 - Instructs autodetect that there are no headers and data should be read starting from the first row. * skipLeadingRows = N \u003e 0 - Autodetect skips N-1 rows and tries to detect headers in row N. If headers are not detected, row N is just skipped. Otherwise row N is used to extract column names for the detected schema.", + "format": "int64" + } + } + }, + "Job": { + "id": "Job", + "type": "object", + "properties": { + "configuration": { + "$ref": "JobConfiguration", + "description": "[Required] Describes the job configuration." + }, + "etag": { + "type": "string", + "description": "[Output-only] A hash of this resource." + }, + "id": { + "type": "string", + "description": "[Output-only] Opaque ID field of the job" + }, + "jobReference": { + "$ref": "JobReference", + "description": "[Optional] Reference describing the unique-per-user name of the job." + }, + "kind": { + "type": "string", + "description": "[Output-only] The type of the resource.", + "default": "bigquery#job" + }, + "selfLink": { + "type": "string", + "description": "[Output-only] A URL that can be used to access this resource again." + }, + "statistics": { + "$ref": "JobStatistics", + "description": "[Output-only] Information about the job, including starting time and ending time of the job." + }, + "status": { + "$ref": "JobStatus", + "description": "[Output-only] The status of this job. Examine this value when polling an asynchronous job to see if the job is complete." + }, + "user_email": { + "type": "string", + "description": "[Output-only] Email address of the user who ran the job." + } + } + }, + "JobCancelResponse": { + "id": "JobCancelResponse", + "type": "object", + "properties": { + "job": { + "$ref": "Job", + "description": "The final state of the job." + }, + "kind": { + "type": "string", + "description": "The resource type of the response.", + "default": "bigquery#jobCancelResponse" + } + } + }, + "JobConfiguration": { + "id": "JobConfiguration", + "type": "object", + "properties": { + "copy": { + "$ref": "JobConfigurationTableCopy", + "description": "[Pick one] Copies a table." + }, + "dryRun": { + "type": "boolean", + "description": "[Optional] If set, don't actually run this job. A valid query will return a mostly empty response with some processing statistics, while an invalid query will return the same error it would if it wasn't a dry run. Behavior of non-query jobs is undefined." + }, + "extract": { + "$ref": "JobConfigurationExtract", + "description": "[Pick one] Configures an extract job." + }, + "labels": { + "type": "object", + "description": "[Experimental] The labels associated with this job. You can use these to organize and group your jobs. Label keys and values can be no longer than 63 characters, can only contain lowercase letters, numeric characters, underscores and dashes. International characters are allowed. Label values are optional. Label keys must start with a letter and each label in the list must have a different key.", + "additionalProperties": { + "type": "string" + } + }, + "load": { + "$ref": "JobConfigurationLoad", + "description": "[Pick one] Configures a load job." + }, + "query": { + "$ref": "JobConfigurationQuery", + "description": "[Pick one] Configures a query job." + } + } + }, + "JobConfigurationExtract": { + "id": "JobConfigurationExtract", + "type": "object", + "properties": { + "compression": { + "type": "string", + "description": "[Optional] The compression type to use for exported files. Possible values include GZIP and NONE. The default value is NONE." + }, + "destinationFormat": { + "type": "string", + "description": "[Optional] The exported file format. Possible values include CSV, NEWLINE_DELIMITED_JSON and AVRO. The default value is CSV. Tables with nested or repeated fields cannot be exported as CSV." + }, + "destinationUri": { + "type": "string", + "description": "[Pick one] DEPRECATED: Use destinationUris instead, passing only one URI as necessary. The fully-qualified Google Cloud Storage URI where the extracted table should be written." + }, + "destinationUris": { + "type": "array", + "description": "[Pick one] A list of fully-qualified Google Cloud Storage URIs where the extracted table should be written.", + "items": { + "type": "string" + } + }, + "fieldDelimiter": { + "type": "string", + "description": "[Optional] Delimiter to use between fields in the exported data. Default is ','" + }, + "printHeader": { + "type": "boolean", + "description": "[Optional] Whether to print out a header row in the results. Default is true.", + "default": "true" + }, + "sourceTable": { + "$ref": "TableReference", + "description": "[Required] A reference to the table being exported." + } + } + }, + "JobConfigurationLoad": { + "id": "JobConfigurationLoad", + "type": "object", + "properties": { + "allowJaggedRows": { + "type": "boolean", + "description": "[Optional] Accept rows that are missing trailing optional columns. The missing values are treated as nulls. If false, records with missing trailing columns are treated as bad records, and if there are too many bad records, an invalid error is returned in the job result. The default value is false. Only applicable to CSV, ignored for other formats." + }, + "allowQuotedNewlines": { + "type": "boolean", + "description": "Indicates if BigQuery should allow quoted data sections that contain newline characters in a CSV file. The default value is false." + }, + "autodetect": { + "type": "boolean", + "description": "[Experimental] Indicates if we should automatically infer the options and schema for CSV and JSON sources." + }, + "createDisposition": { + "type": "string", + "description": "[Optional] Specifies whether the job is allowed to create new tables. The following values are supported: CREATE_IF_NEEDED: If the table does not exist, BigQuery creates the table. CREATE_NEVER: The table must already exist. If it does not, a 'notFound' error is returned in the job result. The default value is CREATE_IF_NEEDED. Creation, truncation and append actions occur as one atomic update upon job completion." + }, + "destinationTable": { + "$ref": "TableReference", + "description": "[Required] The destination table to load the data into." + }, + "encoding": { + "type": "string", + "description": "[Optional] The character encoding of the data. The supported values are UTF-8 or ISO-8859-1. The default value is UTF-8. BigQuery decodes the data after the raw, binary data has been split using the values of the quote and fieldDelimiter properties." + }, + "fieldDelimiter": { + "type": "string", + "description": "[Optional] The separator for fields in a CSV file. The separator can be any ISO-8859-1 single-byte character. To use a character in the range 128-255, you must encode the character as UTF8. BigQuery converts the string to ISO-8859-1 encoding, and then uses the first byte of the encoded string to split the data in its raw, binary state. BigQuery also supports the escape sequence \"\\t\" to specify a tab separator. The default value is a comma (',')." + }, + "ignoreUnknownValues": { + "type": "boolean", + "description": "[Optional] Indicates if BigQuery should allow extra values that are not represented in the table schema. If true, the extra values are ignored. If false, records with extra columns are treated as bad records, and if there are too many bad records, an invalid error is returned in the job result. The default value is false. The sourceFormat property determines what BigQuery treats as an extra value: CSV: Trailing columns JSON: Named values that don't match any column names" + }, + "maxBadRecords": { + "type": "integer", + "description": "[Optional] The maximum number of bad records that BigQuery can ignore when running the job. If the number of bad records exceeds this value, an invalid error is returned in the job result. The default value is 0, which requires that all records are valid.", + "format": "int32" + }, + "nullMarker": { + "type": "string", + "description": "[Optional] Specifies a string that represents a null value in a CSV file. For example, if you specify \"\\N\", BigQuery interprets \"\\N\" as a null value when loading a CSV file. The default value is the empty string. If you set this property to a custom value, BigQuery still interprets the empty string as a null value for all data types except for STRING and BYTE. For STRING and BYTE columns, BigQuery interprets the empty string as an empty value." + }, + "projectionFields": { + "type": "array", + "description": "[Experimental] If sourceFormat is set to \"DATASTORE_BACKUP\", indicates which entity properties to load into BigQuery from a Cloud Datastore backup. Property names are case sensitive and must be top-level properties. If no properties are specified, BigQuery loads all properties. If any named property isn't found in the Cloud Datastore backup, an invalid error is returned in the job result.", + "items": { + "type": "string" + } + }, + "quote": { + "type": "string", + "description": "[Optional] The value that is used to quote data sections in a CSV file. BigQuery converts the string to ISO-8859-1 encoding, and then uses the first byte of the encoded string to split the data in its raw, binary state. The default value is a double-quote ('\"'). If your data does not contain quoted sections, set the property value to an empty string. If your data contains quoted newline characters, you must also set the allowQuotedNewlines property to true.", + "default": "\"", + "pattern": ".?" + }, + "schema": { + "$ref": "TableSchema", + "description": "[Optional] The schema for the destination table. The schema can be omitted if the destination table already exists, or if you're loading data from Google Cloud Datastore." + }, + "schemaInline": { + "type": "string", + "description": "[Deprecated] The inline schema. For CSV schemas, specify as \"Field1:Type1[,Field2:Type2]*\". For example, \"foo:STRING, bar:INTEGER, baz:FLOAT\"." + }, + "schemaInlineFormat": { + "type": "string", + "description": "[Deprecated] The format of the schemaInline property." + }, + "schemaUpdateOptions": { + "type": "array", + "description": "[Experimental] Allows the schema of the desitination table to be updated as a side effect of the load job. Schema update options are supported in two cases: when writeDisposition is WRITE_APPEND; when writeDisposition is WRITE_TRUNCATE and the destination table is a partition of a table, specified by partition decorators. For normal tables, WRITE_TRUNCATE will always overwrite the schema. One or more of the following values are specified: ALLOW_FIELD_ADDITION: allow adding a nullable field to the schema. ALLOW_FIELD_RELAXATION: allow relaxing a required field in the original schema to nullable.", + "items": { + "type": "string" + } + }, + "skipLeadingRows": { + "type": "integer", + "description": "[Optional] The number of rows at the top of a CSV file that BigQuery will skip when loading the data. The default value is 0. This property is useful if you have header rows in the file that should be skipped.", + "format": "int32" + }, + "sourceFormat": { + "type": "string", + "description": "[Optional] The format of the data files. For CSV files, specify \"CSV\". For datastore backups, specify \"DATASTORE_BACKUP\". For newline-delimited JSON, specify \"NEWLINE_DELIMITED_JSON\". For Avro, specify \"AVRO\". The default value is CSV." + }, + "sourceUris": { + "type": "array", + "description": "[Required] The fully-qualified URIs that point to your data in Google Cloud Storage. Each URI can contain one '*' wildcard character and it must come after the 'bucket' name.", + "items": { + "type": "string" + } + }, + "writeDisposition": { + "type": "string", + "description": "[Optional] Specifies the action that occurs if the destination table already exists. The following values are supported: WRITE_TRUNCATE: If the table already exists, BigQuery overwrites the table data. WRITE_APPEND: If the table already exists, BigQuery appends the data to the table. WRITE_EMPTY: If the table already exists and contains data, a 'duplicate' error is returned in the job result. The default value is WRITE_APPEND. Each action is atomic and only occurs if BigQuery is able to complete the job successfully. Creation, truncation and append actions occur as one atomic update upon job completion." + } + } + }, + "JobConfigurationQuery": { + "id": "JobConfigurationQuery", + "type": "object", + "properties": { + "allowLargeResults": { + "type": "boolean", + "description": "If true, allows the query to produce arbitrarily large result tables at a slight cost in performance. Requires destinationTable to be set." + }, + "createDisposition": { + "type": "string", + "description": "[Optional] Specifies whether the job is allowed to create new tables. The following values are supported: CREATE_IF_NEEDED: If the table does not exist, BigQuery creates the table. CREATE_NEVER: The table must already exist. If it does not, a 'notFound' error is returned in the job result. The default value is CREATE_IF_NEEDED. Creation, truncation and append actions occur as one atomic update upon job completion." + }, + "defaultDataset": { + "$ref": "DatasetReference", + "description": "[Optional] Specifies the default dataset to use for unqualified table names in the query." + }, + "destinationTable": { + "$ref": "TableReference", + "description": "[Optional] Describes the table where the query results should be stored. If not present, a new table will be created to store the results." + }, + "flattenResults": { + "type": "boolean", + "description": "[Optional] Flattens all nested and repeated fields in the query results. The default value is true. allowLargeResults must be true if this is set to false.", + "default": "true" + }, + "maximumBillingTier": { + "type": "integer", + "description": "[Optional] Limits the billing tier for this job. Queries that have resource usage beyond this tier will fail (without incurring a charge). If unspecified, this will be set to your project default.", + "default": "1", + "format": "int32" + }, + "maximumBytesBilled": { + "type": "string", + "description": "[Optional] Limits the bytes billed for this job. Queries that will have bytes billed beyond this limit will fail (without incurring a charge). If unspecified, this will be set to your project default.", + "format": "int64" + }, + "parameterMode": { + "type": "string", + "description": "[Experimental] Standard SQL only. Set to POSITIONAL to use positional (?) query parameters or to NAMED to use named (@myparam) query parameters in this query." + }, + "preserveNulls": { + "type": "boolean", + "description": "[Deprecated] This property is deprecated." + }, + "priority": { + "type": "string", + "description": "[Optional] Specifies a priority for the query. Possible values include INTERACTIVE and BATCH. The default value is INTERACTIVE." + }, + "query": { + "type": "string", + "description": "[Required] BigQuery SQL query to execute." + }, + "queryParameters": { + "type": "array", + "description": "Query parameters for standard SQL queries.", + "items": { + "$ref": "QueryParameter" + } + }, + "schemaUpdateOptions": { + "type": "array", + "description": "[Experimental] Allows the schema of the destination table to be updated as a side effect of the query job. Schema update options are supported in two cases: when writeDisposition is WRITE_APPEND; when writeDisposition is WRITE_TRUNCATE and the destination table is a partition of a table, specified by partition decorators. For normal tables, WRITE_TRUNCATE will always overwrite the schema. One or more of the following values are specified: ALLOW_FIELD_ADDITION: allow adding a nullable field to the schema. ALLOW_FIELD_RELAXATION: allow relaxing a required field in the original schema to nullable.", + "items": { + "type": "string" + } + }, + "tableDefinitions": { + "type": "object", + "description": "[Optional] If querying an external data source outside of BigQuery, describes the data format, location and other properties of the data source. By defining these properties, the data source can then be queried as if it were a standard BigQuery table.", + "additionalProperties": { + "$ref": "ExternalDataConfiguration" + } + }, + "useLegacySql": { + "type": "boolean", + "description": "Specifies whether to use BigQuery's legacy SQL dialect for this query. The default value is true. If set to false, the query will use BigQuery's standard SQL: https://cloud.google.com/bigquery/sql-reference/ When useLegacySql is set to false, the values of allowLargeResults and flattenResults are ignored; query will be run as if allowLargeResults is true and flattenResults is false." + }, + "useQueryCache": { + "type": "boolean", + "description": "[Optional] Whether to look for the result in the query cache. The query cache is a best-effort cache that will be flushed whenever tables in the query are modified. Moreover, the query cache is only available when a query does not have a destination table specified. The default value is true.", + "default": "true" + }, + "userDefinedFunctionResources": { + "type": "array", + "description": "[Experimental] Describes user-defined function resources used in the query.", + "items": { + "$ref": "UserDefinedFunctionResource" + } + }, + "writeDisposition": { + "type": "string", + "description": "[Optional] Specifies the action that occurs if the destination table already exists. The following values are supported: WRITE_TRUNCATE: If the table already exists, BigQuery overwrites the table data. WRITE_APPEND: If the table already exists, BigQuery appends the data to the table. WRITE_EMPTY: If the table already exists and contains data, a 'duplicate' error is returned in the job result. The default value is WRITE_EMPTY. Each action is atomic and only occurs if BigQuery is able to complete the job successfully. Creation, truncation and append actions occur as one atomic update upon job completion." + } + } + }, + "JobConfigurationTableCopy": { + "id": "JobConfigurationTableCopy", + "type": "object", + "properties": { + "createDisposition": { + "type": "string", + "description": "[Optional] Specifies whether the job is allowed to create new tables. The following values are supported: CREATE_IF_NEEDED: If the table does not exist, BigQuery creates the table. CREATE_NEVER: The table must already exist. If it does not, a 'notFound' error is returned in the job result. The default value is CREATE_IF_NEEDED. Creation, truncation and append actions occur as one atomic update upon job completion." + }, + "destinationTable": { + "$ref": "TableReference", + "description": "[Required] The destination table" + }, + "sourceTable": { + "$ref": "TableReference", + "description": "[Pick one] Source table to copy." + }, + "sourceTables": { + "type": "array", + "description": "[Pick one] Source tables to copy.", + "items": { + "$ref": "TableReference" + } + }, + "writeDisposition": { + "type": "string", + "description": "[Optional] Specifies the action that occurs if the destination table already exists. The following values are supported: WRITE_TRUNCATE: If the table already exists, BigQuery overwrites the table data. WRITE_APPEND: If the table already exists, BigQuery appends the data to the table. WRITE_EMPTY: If the table already exists and contains data, a 'duplicate' error is returned in the job result. The default value is WRITE_EMPTY. Each action is atomic and only occurs if BigQuery is able to complete the job successfully. Creation, truncation and append actions occur as one atomic update upon job completion." + } + } + }, + "JobList": { + "id": "JobList", + "type": "object", + "properties": { + "etag": { + "type": "string", + "description": "A hash of this page of results." + }, + "jobs": { + "type": "array", + "description": "List of jobs that were requested.", + "items": { + "type": "object", + "properties": { + "configuration": { + "$ref": "JobConfiguration", + "description": "[Full-projection-only] Specifies the job configuration." + }, + "errorResult": { + "$ref": "ErrorProto", + "description": "A result object that will be present only if the job has failed." + }, + "id": { + "type": "string", + "description": "Unique opaque ID of the job." + }, + "jobReference": { + "$ref": "JobReference", + "description": "Job reference uniquely identifying the job." + }, + "kind": { + "type": "string", + "description": "The resource type.", + "default": "bigquery#job" + }, + "state": { + "type": "string", + "description": "Running state of the job. When the state is DONE, errorResult can be checked to determine whether the job succeeded or failed." + }, + "statistics": { + "$ref": "JobStatistics", + "description": "[Output-only] Information about the job, including starting time and ending time of the job." + }, + "status": { + "$ref": "JobStatus", + "description": "[Full-projection-only] Describes the state of the job." + }, + "user_email": { + "type": "string", + "description": "[Full-projection-only] Email address of the user who ran the job." + } + } + } + }, + "kind": { + "type": "string", + "description": "The resource type of the response.", + "default": "bigquery#jobList" + }, + "nextPageToken": { + "type": "string", + "description": "A token to request the next page of results." + } + } + }, + "JobReference": { + "id": "JobReference", + "type": "object", + "properties": { + "jobId": { + "type": "string", + "description": "[Required] The ID of the job. The ID must contain only letters (a-z, A-Z), numbers (0-9), underscores (_), or dashes (-). The maximum length is 1,024 characters.", + "annotations": { + "required": [ + "bigquery.jobs.getQueryResults" + ] + } + }, + "projectId": { + "type": "string", + "description": "[Required] The ID of the project containing this job.", + "annotations": { + "required": [ + "bigquery.jobs.getQueryResults" + ] + } + } + } + }, + "JobStatistics": { + "id": "JobStatistics", + "type": "object", + "properties": { + "creationTime": { + "type": "string", + "description": "[Output-only] Creation time of this job, in milliseconds since the epoch. This field will be present on all jobs.", + "format": "int64" + }, + "endTime": { + "type": "string", + "description": "[Output-only] End time of this job, in milliseconds since the epoch. This field will be present whenever a job is in the DONE state.", + "format": "int64" + }, + "extract": { + "$ref": "JobStatistics4", + "description": "[Output-only] Statistics for an extract job." + }, + "load": { + "$ref": "JobStatistics3", + "description": "[Output-only] Statistics for a load job." + }, + "query": { + "$ref": "JobStatistics2", + "description": "[Output-only] Statistics for a query job." + }, + "startTime": { + "type": "string", + "description": "[Output-only] Start time of this job, in milliseconds since the epoch. This field will be present when the job transitions from the PENDING state to either RUNNING or DONE.", + "format": "int64" + }, + "totalBytesProcessed": { + "type": "string", + "description": "[Output-only] [Deprecated] Use the bytes processed in the query statistics instead.", + "format": "int64" + } + } + }, + "JobStatistics2": { + "id": "JobStatistics2", + "type": "object", + "properties": { + "billingTier": { + "type": "integer", + "description": "[Output-only] Billing tier for the job.", + "format": "int32" + }, + "cacheHit": { + "type": "boolean", + "description": "[Output-only] Whether the query result was fetched from the query cache." + }, + "numDmlAffectedRows": { + "type": "string", + "description": "[Output-only, Experimental] The number of rows affected by a DML statement. Present only for DML statements INSERT, UPDATE or DELETE.", + "format": "int64" + }, + "queryPlan": { + "type": "array", + "description": "[Output-only, Experimental] Describes execution plan for the query.", + "items": { + "$ref": "ExplainQueryStage" + } + }, + "referencedTables": { + "type": "array", + "description": "[Output-only, Experimental] Referenced tables for the job. Queries that reference more than 50 tables will not have a complete list.", + "items": { + "$ref": "TableReference" + } + }, + "schema": { + "$ref": "TableSchema", + "description": "[Output-only, Experimental] The schema of the results. Present only for successful dry run of non-legacy SQL queries." + }, + "statementType": { + "type": "string", + "description": "[Output-only, Experimental] The type of query statement, if valid." + }, + "totalBytesBilled": { + "type": "string", + "description": "[Output-only] Total bytes billed for the job.", + "format": "int64" + }, + "totalBytesProcessed": { + "type": "string", + "description": "[Output-only] Total bytes processed for the job.", + "format": "int64" + }, + "undeclaredQueryParameters": { + "type": "array", + "description": "[Output-only, Experimental] Standard SQL only: list of undeclared query parameters detected during a dry run validation.", + "items": { + "$ref": "QueryParameter" + } + } + } + }, + "JobStatistics3": { + "id": "JobStatistics3", + "type": "object", + "properties": { + "inputFileBytes": { + "type": "string", + "description": "[Output-only] Number of bytes of source data in a load job.", + "format": "int64" + }, + "inputFiles": { + "type": "string", + "description": "[Output-only] Number of source files in a load job.", + "format": "int64" + }, + "outputBytes": { + "type": "string", + "description": "[Output-only] Size of the loaded data in bytes. Note that while a load job is in the running state, this value may change.", + "format": "int64" + }, + "outputRows": { + "type": "string", + "description": "[Output-only] Number of rows imported in a load job. Note that while an import job is in the running state, this value may change.", + "format": "int64" + } + } + }, + "JobStatistics4": { + "id": "JobStatistics4", + "type": "object", + "properties": { + "destinationUriFileCounts": { + "type": "array", + "description": "[Output-only] Number of files per destination URI or URI pattern specified in the extract configuration. These values will be in the same order as the URIs specified in the 'destinationUris' field.", + "items": { + "type": "string", + "format": "int64" + } + } + } + }, + "JobStatus": { + "id": "JobStatus", + "type": "object", + "properties": { + "errorResult": { + "$ref": "ErrorProto", + "description": "[Output-only] Final error result of the job. If present, indicates that the job has completed and was unsuccessful." + }, + "errors": { + "type": "array", + "description": "[Output-only] All errors encountered during the running of the job. Errors here do not necessarily mean that the job has completed or was unsuccessful.", + "items": { + "$ref": "ErrorProto" + } + }, + "state": { + "type": "string", + "description": "[Output-only] Running state of the job." + } + } + }, + "JsonObject": { + "id": "JsonObject", + "type": "object", + "description": "Represents a single JSON object.", + "additionalProperties": { + "$ref": "JsonValue" + } + }, + "JsonValue": { + "id": "JsonValue", + "type": "any" + }, + "ProjectList": { + "id": "ProjectList", + "type": "object", + "properties": { + "etag": { + "type": "string", + "description": "A hash of the page of results" + }, + "kind": { + "type": "string", + "description": "The type of list.", + "default": "bigquery#projectList" + }, + "nextPageToken": { + "type": "string", + "description": "A token to request the next page of results." + }, + "projects": { + "type": "array", + "description": "Projects to which you have at least READ access.", + "items": { + "type": "object", + "properties": { + "friendlyName": { + "type": "string", + "description": "A descriptive name for this project." + }, + "id": { + "type": "string", + "description": "An opaque ID of this project." + }, + "kind": { + "type": "string", + "description": "The resource type.", + "default": "bigquery#project" + }, + "numericId": { + "type": "string", + "description": "The numeric ID of this project.", + "format": "uint64" + }, + "projectReference": { + "$ref": "ProjectReference", + "description": "A unique reference to this project." + } + } + } + }, + "totalItems": { + "type": "integer", + "description": "The total number of projects in the list.", + "format": "int32" + } + } + }, + "ProjectReference": { + "id": "ProjectReference", + "type": "object", + "properties": { + "projectId": { + "type": "string", + "description": "[Required] ID of the project. Can be either the numeric ID or the assigned ID of the project." + } + } + }, + "QueryParameter": { + "id": "QueryParameter", + "type": "object", + "properties": { + "name": { + "type": "string", + "description": "[Optional] If unset, this is a positional parameter. Otherwise, should be unique within a query." + }, + "parameterType": { + "$ref": "QueryParameterType", + "description": "[Required] The type of this parameter." + }, + "parameterValue": { + "$ref": "QueryParameterValue", + "description": "[Required] The value of this parameter." + } + } + }, + "QueryParameterType": { + "id": "QueryParameterType", + "type": "object", + "properties": { + "arrayType": { + "$ref": "QueryParameterType", + "description": "[Optional] The type of the array's elements, if this is an array." + }, + "structTypes": { + "type": "array", + "description": "[Optional] The types of the fields of this struct, in order, if this is a struct.", + "items": { + "type": "object", + "properties": { + "description": { + "type": "string", + "description": "[Optional] Human-oriented description of the field." + }, + "name": { + "type": "string", + "description": "[Optional] The name of this field." + }, + "type": { + "$ref": "QueryParameterType", + "description": "[Required] The type of this field." + } + } + } + }, + "type": { + "type": "string", + "description": "[Required] The top level type of this field." + } + } + }, + "QueryParameterValue": { + "id": "QueryParameterValue", + "type": "object", + "properties": { + "arrayValues": { + "type": "array", + "description": "[Optional] The array values, if this is an array type.", + "items": { + "$ref": "QueryParameterValue" + } + }, + "structValues": { + "type": "object", + "description": "[Optional] The struct field values, in order of the struct type's declaration.", + "additionalProperties": { + "$ref": "QueryParameterValue" + } + }, + "value": { + "type": "string", + "description": "[Optional] The value of this value, if a simple scalar type." + } + } + }, + "QueryRequest": { + "id": "QueryRequest", + "type": "object", + "properties": { + "defaultDataset": { + "$ref": "DatasetReference", + "description": "[Optional] Specifies the default datasetId and projectId to assume for any unqualified table names in the query. If not set, all table names in the query string must be qualified in the format 'datasetId.tableId'." + }, + "dryRun": { + "type": "boolean", + "description": "[Optional] If set to true, BigQuery doesn't run the job. Instead, if the query is valid, BigQuery returns statistics about the job such as how many bytes would be processed. If the query is invalid, an error returns. The default value is false." + }, + "kind": { + "type": "string", + "description": "The resource type of the request.", + "default": "bigquery#queryRequest" + }, + "maxResults": { + "type": "integer", + "description": "[Optional] The maximum number of rows of data to return per page of results. Setting this flag to a small value such as 1000 and then paging through results might improve reliability when the query result set is large. In addition to this limit, responses are also limited to 10 MB. By default, there is no maximum row count, and only the byte limit applies.", + "format": "uint32" + }, + "parameterMode": { + "type": "string", + "description": "[Experimental] Standard SQL only. Set to POSITIONAL to use positional (?) query parameters or to NAMED to use named (@myparam) query parameters in this query." + }, + "preserveNulls": { + "type": "boolean", + "description": "[Deprecated] This property is deprecated." + }, + "query": { + "type": "string", + "description": "[Required] A query string, following the BigQuery query syntax, of the query to execute. Example: \"SELECT count(f1) FROM [myProjectId:myDatasetId.myTableId]\".", + "annotations": { + "required": [ + "bigquery.jobs.query" + ] + } + }, + "queryParameters": { + "type": "array", + "description": "[Experimental] Query parameters for Standard SQL queries.", + "items": { + "$ref": "QueryParameter" + } + }, + "timeoutMs": { + "type": "integer", + "description": "[Optional] How long to wait for the query to complete, in milliseconds, before the request times out and returns. Note that this is only a timeout for the request, not the query. If the query takes longer to run than the timeout value, the call returns without any results and with the 'jobComplete' flag set to false. You can call GetQueryResults() to wait for the query to complete and read the results. The default value is 10000 milliseconds (10 seconds).", + "format": "uint32" + }, + "useLegacySql": { + "type": "boolean", + "description": "Specifies whether to use BigQuery's legacy SQL dialect for this query. The default value is true. If set to false, the query will use BigQuery's standard SQL: https://cloud.google.com/bigquery/sql-reference/ When useLegacySql is set to false, the values of allowLargeResults and flattenResults are ignored; query will be run as if allowLargeResults is true and flattenResults is false.", + "default": "true" + }, + "useQueryCache": { + "type": "boolean", + "description": "[Optional] Whether to look for the result in the query cache. The query cache is a best-effort cache that will be flushed whenever tables in the query are modified. The default value is true.", + "default": "true" + } + } + }, + "QueryResponse": { + "id": "QueryResponse", + "type": "object", + "properties": { + "cacheHit": { + "type": "boolean", + "description": "Whether the query result was fetched from the query cache." + }, + "errors": { + "type": "array", + "description": "[Output-only] All errors and warnings encountered during the running of the job. Errors here do not necessarily mean that the job has completed or was unsuccessful.", + "items": { + "$ref": "ErrorProto" + } + }, + "jobComplete": { + "type": "boolean", + "description": "Whether the query has completed or not. If rows or totalRows are present, this will always be true. If this is false, totalRows will not be available." + }, + "jobReference": { + "$ref": "JobReference", + "description": "Reference to the Job that was created to run the query. This field will be present even if the original request timed out, in which case GetQueryResults can be used to read the results once the query has completed. Since this API only returns the first page of results, subsequent pages can be fetched via the same mechanism (GetQueryResults)." + }, + "kind": { + "type": "string", + "description": "The resource type.", + "default": "bigquery#queryResponse" + }, + "numDmlAffectedRows": { + "type": "string", + "description": "[Output-only, Experimental] The number of rows affected by a DML statement. Present only for DML statements INSERT, UPDATE or DELETE.", + "format": "int64" + }, + "pageToken": { + "type": "string", + "description": "A token used for paging results." + }, + "rows": { + "type": "array", + "description": "An object with as many results as can be contained within the maximum permitted reply size. To get any additional rows, you can call GetQueryResults and specify the jobReference returned above.", + "items": { + "$ref": "TableRow" + } + }, + "schema": { + "$ref": "TableSchema", + "description": "The schema of the results. Present only when the query completes successfully." + }, + "totalBytesProcessed": { + "type": "string", + "description": "The total number of bytes processed for this query. If this query was a dry run, this is the number of bytes that would be processed if the query were run.", + "format": "int64" + }, + "totalRows": { + "type": "string", + "description": "The total number of rows in the complete query result set, which can be more than the number of rows in this single page of results.", + "format": "uint64" + } + } + }, + "Streamingbuffer": { + "id": "Streamingbuffer", + "type": "object", + "properties": { + "estimatedBytes": { + "type": "string", + "description": "[Output-only] A lower-bound estimate of the number of bytes currently in the streaming buffer.", + "format": "uint64" + }, + "estimatedRows": { + "type": "string", + "description": "[Output-only] A lower-bound estimate of the number of rows currently in the streaming buffer.", + "format": "uint64" + }, + "oldestEntryTime": { + "type": "string", + "description": "[Output-only] Contains the timestamp of the oldest entry in the streaming buffer, in milliseconds since the epoch, if the streaming buffer is available.", + "format": "uint64" + } + } + }, + "Table": { + "id": "Table", + "type": "object", + "properties": { + "creationTime": { + "type": "string", + "description": "[Output-only] The time when this table was created, in milliseconds since the epoch.", + "format": "int64" + }, + "description": { + "type": "string", + "description": "[Optional] A user-friendly description of this table." + }, + "etag": { + "type": "string", + "description": "[Output-only] A hash of this resource." + }, + "expirationTime": { + "type": "string", + "description": "[Optional] The time when this table expires, in milliseconds since the epoch. If not present, the table will persist indefinitely. Expired tables will be deleted and their storage reclaimed.", + "format": "int64" + }, + "externalDataConfiguration": { + "$ref": "ExternalDataConfiguration", + "description": "[Optional] Describes the data format, location, and other properties of a table stored outside of BigQuery. By defining these properties, the data source can then be queried as if it were a standard BigQuery table." + }, + "friendlyName": { + "type": "string", + "description": "[Optional] A descriptive name for this table." + }, + "id": { + "type": "string", + "description": "[Output-only] An opaque ID uniquely identifying the table." + }, + "kind": { + "type": "string", + "description": "[Output-only] The type of the resource.", + "default": "bigquery#table" + }, + "labels": { + "type": "object", + "description": "[Experimental] The labels associated with this table. You can use these to organize and group your tables. Label keys and values can be no longer than 63 characters, can only contain lowercase letters, numeric characters, underscores and dashes. International characters are allowed. Label values are optional. Label keys must start with a letter and each label in the list must have a different key.", + "additionalProperties": { + "type": "string" + } + }, + "lastModifiedTime": { + "type": "string", + "description": "[Output-only] The time when this table was last modified, in milliseconds since the epoch.", + "format": "uint64" + }, + "location": { + "type": "string", + "description": "[Output-only] The geographic location where the table resides. This value is inherited from the dataset." + }, + "numBytes": { + "type": "string", + "description": "[Output-only] The size of this table in bytes, excluding any data in the streaming buffer.", + "format": "int64" + }, + "numLongTermBytes": { + "type": "string", + "description": "[Output-only] The number of bytes in the table that are considered \"long-term storage\".", + "format": "int64" + }, + "numRows": { + "type": "string", + "description": "[Output-only] The number of rows of data in this table, excluding any data in the streaming buffer.", + "format": "uint64" + }, + "schema": { + "$ref": "TableSchema", + "description": "[Optional] Describes the schema of this table." + }, + "selfLink": { + "type": "string", + "description": "[Output-only] A URL that can be used to access this resource again." + }, + "streamingBuffer": { + "$ref": "Streamingbuffer", + "description": "[Output-only] Contains information regarding this table's streaming buffer, if one is present. This field will be absent if the table is not being streamed to or if there is no data in the streaming buffer." + }, + "tableReference": { + "$ref": "TableReference", + "description": "[Required] Reference describing the ID of this table." + }, + "timePartitioning": { + "$ref": "TimePartitioning", + "description": "[Experimental] If specified, configures time-based partitioning for this table." + }, + "type": { + "type": "string", + "description": "[Output-only] Describes the table type. The following values are supported: TABLE: A normal BigQuery table. VIEW: A virtual table defined by a SQL query. EXTERNAL: A table that references data stored in an external storage system, such as Google Cloud Storage. The default value is TABLE." + }, + "view": { + "$ref": "ViewDefinition", + "description": "[Optional] The view definition." + } + } + }, + "TableCell": { + "id": "TableCell", + "type": "object", + "properties": { + "v": { + "type": "any" + } + } + }, + "TableDataInsertAllRequest": { + "id": "TableDataInsertAllRequest", + "type": "object", + "properties": { + "ignoreUnknownValues": { + "type": "boolean", + "description": "[Optional] Accept rows that contain values that do not match the schema. The unknown values are ignored. Default is false, which treats unknown values as errors." + }, + "kind": { + "type": "string", + "description": "The resource type of the response.", + "default": "bigquery#tableDataInsertAllRequest" + }, + "rows": { + "type": "array", + "description": "The rows to insert.", + "items": { + "type": "object", + "properties": { + "insertId": { + "type": "string", + "description": "[Optional] A unique ID for each row. BigQuery uses this property to detect duplicate insertion requests on a best-effort basis." + }, + "json": { + "$ref": "JsonObject", + "description": "[Required] A JSON object that contains a row of data. The object's properties and values must match the destination table's schema." + } + } + } + }, + "skipInvalidRows": { + "type": "boolean", + "description": "[Optional] Insert all valid rows of a request, even if invalid rows exist. The default value is false, which causes the entire request to fail if any invalid rows exist." + }, + "templateSuffix": { + "type": "string", + "description": "[Experimental] If specified, treats the destination table as a base template, and inserts the rows into an instance table named \"{destination}{templateSuffix}\". BigQuery will manage creation of the instance table, using the schema of the base template table. See https://cloud.google.com/bigquery/streaming-data-into-bigquery#template-tables for considerations when working with templates tables." + } + } + }, + "TableDataInsertAllResponse": { + "id": "TableDataInsertAllResponse", + "type": "object", + "properties": { + "insertErrors": { + "type": "array", + "description": "An array of errors for rows that were not inserted.", + "items": { + "type": "object", + "properties": { + "errors": { + "type": "array", + "description": "Error information for the row indicated by the index property.", + "items": { + "$ref": "ErrorProto" + } + }, + "index": { + "type": "integer", + "description": "The index of the row that error applies to.", + "format": "uint32" + } + } + } + }, + "kind": { + "type": "string", + "description": "The resource type of the response.", + "default": "bigquery#tableDataInsertAllResponse" + } + } + }, + "TableDataList": { + "id": "TableDataList", + "type": "object", + "properties": { + "etag": { + "type": "string", + "description": "A hash of this page of results." + }, + "kind": { + "type": "string", + "description": "The resource type of the response.", + "default": "bigquery#tableDataList" + }, + "pageToken": { + "type": "string", + "description": "A token used for paging results. Providing this token instead of the startIndex parameter can help you retrieve stable results when an underlying table is changing." + }, + "rows": { + "type": "array", + "description": "Rows of results.", + "items": { + "$ref": "TableRow" + } + }, + "totalRows": { + "type": "string", + "description": "The total number of rows in the complete table.", + "format": "int64" + } + } + }, + "TableFieldSchema": { + "id": "TableFieldSchema", + "type": "object", + "properties": { + "description": { + "type": "string", + "description": "[Optional] The field description. The maximum length is 16K characters." + }, + "fields": { + "type": "array", + "description": "[Optional] Describes the nested schema fields if the type property is set to RECORD.", + "items": { + "$ref": "TableFieldSchema" + } + }, + "mode": { + "type": "string", + "description": "[Optional] The field mode. Possible values include NULLABLE, REQUIRED and REPEATED. The default value is NULLABLE." + }, + "name": { + "type": "string", + "description": "[Required] The field name. The name must contain only letters (a-z, A-Z), numbers (0-9), or underscores (_), and must start with a letter or underscore. The maximum length is 128 characters." + }, + "type": { + "type": "string", + "description": "[Required] The field data type. Possible values include STRING, BYTES, INTEGER, INT64 (same as INTEGER), FLOAT, FLOAT64 (same as FLOAT), BOOLEAN, BOOL (same as BOOLEAN), TIMESTAMP, DATE, TIME, DATETIME, RECORD (where RECORD indicates that the field contains a nested schema) or STRUCT (same as RECORD)." + } + } + }, + "TableList": { + "id": "TableList", + "type": "object", + "properties": { + "etag": { + "type": "string", + "description": "A hash of this page of results." + }, + "kind": { + "type": "string", + "description": "The type of list.", + "default": "bigquery#tableList" + }, + "nextPageToken": { + "type": "string", + "description": "A token to request the next page of results." + }, + "tables": { + "type": "array", + "description": "Tables in the requested dataset.", + "items": { + "type": "object", + "properties": { + "friendlyName": { + "type": "string", + "description": "The user-friendly name for this table." + }, + "id": { + "type": "string", + "description": "An opaque ID of the table" + }, + "kind": { + "type": "string", + "description": "The resource type.", + "default": "bigquery#table" + }, + "labels": { + "type": "object", + "description": "[Experimental] The labels associated with this table. You can use these to organize and group your tables.", + "additionalProperties": { + "type": "string" + } + }, + "tableReference": { + "$ref": "TableReference", + "description": "A reference uniquely identifying the table." + }, + "type": { + "type": "string", + "description": "The type of table. Possible values are: TABLE, VIEW." + }, + "view": { + "type": "object", + "description": "Additional details for a view.", + "properties": { + "useLegacySql": { + "type": "boolean", + "description": "True if view is defined in legacy SQL dialect, false if in standard SQL." + } + } + } + } + } + }, + "totalItems": { + "type": "integer", + "description": "The total number of tables in the dataset.", + "format": "int32" + } + } + }, + "TableReference": { + "id": "TableReference", + "type": "object", + "properties": { + "datasetId": { + "type": "string", + "description": "[Required] The ID of the dataset containing this table.", + "annotations": { + "required": [ + "bigquery.tables.update" + ] + } + }, + "projectId": { + "type": "string", + "description": "[Required] The ID of the project containing this table.", + "annotations": { + "required": [ + "bigquery.tables.update" + ] + } + }, + "tableId": { + "type": "string", + "description": "[Required] The ID of the table. The ID must contain only letters (a-z, A-Z), numbers (0-9), or underscores (_). The maximum length is 1,024 characters.", + "annotations": { + "required": [ + "bigquery.tables.update" + ] + } + } + } + }, + "TableRow": { + "id": "TableRow", + "type": "object", + "properties": { + "f": { + "type": "array", + "description": "Represents a single row in the result set, consisting of one or more fields.", + "items": { + "$ref": "TableCell" + } + } + } + }, + "TableSchema": { + "id": "TableSchema", + "type": "object", + "properties": { + "fields": { + "type": "array", + "description": "Describes the fields in a table.", + "items": { + "$ref": "TableFieldSchema" + } + } + } + }, + "TimePartitioning": { + "id": "TimePartitioning", + "type": "object", + "properties": { + "expirationMs": { + "type": "string", + "description": "[Optional] Number of milliseconds for which to keep the storage for a partition.", + "format": "int64" + }, + "type": { + "type": "string", + "description": "[Required] The only type supported is DAY, which will generate one partition per day based on data loading time." + } + } + }, + "UserDefinedFunctionResource": { + "id": "UserDefinedFunctionResource", + "type": "object", + "properties": { + "inlineCode": { + "type": "string", + "description": "[Pick one] An inline resource that contains code for a user-defined function (UDF). Providing a inline code resource is equivalent to providing a URI for a file containing the same code." + }, + "resourceUri": { + "type": "string", + "description": "[Pick one] A code resource to load from a Google Cloud Storage URI (gs://bucket/path)." + } + } + }, + "ViewDefinition": { + "id": "ViewDefinition", + "type": "object", + "properties": { + "query": { + "type": "string", + "description": "[Required] A query that BigQuery executes when the view is referenced." + }, + "useLegacySql": { + "type": "boolean", + "description": "Specifies whether to use BigQuery's legacy SQL for this view. The default value is true. If set to false, the view will use BigQuery's standard SQL: https://cloud.google.com/bigquery/sql-reference/ Queries and views that reference this view must use the same flag value." + }, + "userDefinedFunctionResources": { + "type": "array", + "description": "[Experimental] Describes user-defined function resources used in the query.", + "items": { + "$ref": "UserDefinedFunctionResource" + } + } + } + } + }, + "resources": { + "datasets": { + "methods": { + "delete": { + "id": "bigquery.datasets.delete", + "path": "projects/{projectId}/datasets/{datasetId}", + "httpMethod": "DELETE", + "description": "Deletes the dataset specified by the datasetId value. Before you can delete a dataset, you must delete all its tables, either manually or by specifying deleteContents. Immediately after deletion, you can create another dataset with the same name.", + "parameters": { + "datasetId": { + "type": "string", + "description": "Dataset ID of dataset being deleted", + "required": true, + "location": "path" + }, + "deleteContents": { + "type": "boolean", + "description": "If True, delete all the tables in the dataset. If False and the dataset contains tables, the request will fail. Default is False", + "location": "query" + }, + "projectId": { + "type": "string", + "description": "Project ID of the dataset being deleted", + "required": true, + "location": "path" + } + }, + "parameterOrder": [ + "projectId", + "datasetId" + ], + "scopes": [ + "https://www.googleapis.com/auth/bigquery", + "https://www.googleapis.com/auth/cloud-platform" + ] + }, + "get": { + "id": "bigquery.datasets.get", + "path": "projects/{projectId}/datasets/{datasetId}", + "httpMethod": "GET", + "description": "Returns the dataset specified by datasetID.", + "parameters": { + "datasetId": { + "type": "string", + "description": "Dataset ID of the requested dataset", + "required": true, + "location": "path" + }, + "projectId": { + "type": "string", + "description": "Project ID of the requested dataset", + "required": true, + "location": "path" + } + }, + "parameterOrder": [ + "projectId", + "datasetId" + ], + "response": { + "$ref": "Dataset" + }, + "scopes": [ + "https://www.googleapis.com/auth/bigquery", + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-platform.read-only" + ] + }, + "insert": { + "id": "bigquery.datasets.insert", + "path": "projects/{projectId}/datasets", + "httpMethod": "POST", + "description": "Creates a new empty dataset.", + "parameters": { + "projectId": { + "type": "string", + "description": "Project ID of the new dataset", + "required": true, + "location": "path" + } + }, + "parameterOrder": [ + "projectId" + ], + "request": { + "$ref": "Dataset" + }, + "response": { + "$ref": "Dataset" + }, + "scopes": [ + "https://www.googleapis.com/auth/bigquery", + "https://www.googleapis.com/auth/cloud-platform" + ] + }, + "list": { + "id": "bigquery.datasets.list", + "path": "projects/{projectId}/datasets", + "httpMethod": "GET", + "description": "Lists all datasets in the specified project to which you have been granted the READER dataset role.", + "parameters": { + "all": { + "type": "boolean", + "description": "Whether to list all datasets, including hidden ones", + "location": "query" + }, + "filter": { + "type": "string", + "description": "An expression for filtering the results of the request by label. The syntax is \"labels.\u003cname\u003e[:\u003cvalue\u003e]\". Multiple filters can be ANDed together by connecting with a space. Example: \"labels.department:receiving labels.active\". See Filtering datasets using labels for details.", + "location": "query" + }, + "maxResults": { + "type": "integer", + "description": "The maximum number of results to return", + "format": "uint32", + "location": "query" + }, + "pageToken": { + "type": "string", + "description": "Page token, returned by a previous call, to request the next page of results", + "location": "query" + }, + "projectId": { + "type": "string", + "description": "Project ID of the datasets to be listed", + "required": true, + "location": "path" + } + }, + "parameterOrder": [ + "projectId" + ], + "response": { + "$ref": "DatasetList" + }, + "scopes": [ + "https://www.googleapis.com/auth/bigquery", + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-platform.read-only" + ] + }, + "patch": { + "id": "bigquery.datasets.patch", + "path": "projects/{projectId}/datasets/{datasetId}", + "httpMethod": "PATCH", + "description": "Updates information in an existing dataset. The update method replaces the entire dataset resource, whereas the patch method only replaces fields that are provided in the submitted dataset resource. This method supports patch semantics.", + "parameters": { + "datasetId": { + "type": "string", + "description": "Dataset ID of the dataset being updated", + "required": true, + "location": "path" + }, + "projectId": { + "type": "string", + "description": "Project ID of the dataset being updated", + "required": true, + "location": "path" + } + }, + "parameterOrder": [ + "projectId", + "datasetId" + ], + "request": { + "$ref": "Dataset" + }, + "response": { + "$ref": "Dataset" + }, + "scopes": [ + "https://www.googleapis.com/auth/bigquery", + "https://www.googleapis.com/auth/cloud-platform" + ] + }, + "update": { + "id": "bigquery.datasets.update", + "path": "projects/{projectId}/datasets/{datasetId}", + "httpMethod": "PUT", + "description": "Updates information in an existing dataset. The update method replaces the entire dataset resource, whereas the patch method only replaces fields that are provided in the submitted dataset resource.", + "parameters": { + "datasetId": { + "type": "string", + "description": "Dataset ID of the dataset being updated", + "required": true, + "location": "path" + }, + "projectId": { + "type": "string", + "description": "Project ID of the dataset being updated", + "required": true, + "location": "path" + } + }, + "parameterOrder": [ + "projectId", + "datasetId" + ], + "request": { + "$ref": "Dataset" + }, + "response": { + "$ref": "Dataset" + }, + "scopes": [ + "https://www.googleapis.com/auth/bigquery", + "https://www.googleapis.com/auth/cloud-platform" + ] + } + } + }, + "jobs": { + "methods": { + "cancel": { + "id": "bigquery.jobs.cancel", + "path": "projects/{projectId}/jobs/{jobId}/cancel", + "httpMethod": "POST", + "description": "Requests that a job be cancelled. This call will return immediately, and the client will need to poll for the job status to see if the cancel completed successfully. Cancelled jobs may still incur costs.", + "parameters": { + "jobId": { + "type": "string", + "description": "[Required] Job ID of the job to cancel", + "required": true, + "location": "path" + }, + "projectId": { + "type": "string", + "description": "[Required] Project ID of the job to cancel", + "required": true, + "location": "path" + } + }, + "parameterOrder": [ + "projectId", + "jobId" + ], + "response": { + "$ref": "JobCancelResponse" + }, + "scopes": [ + "https://www.googleapis.com/auth/bigquery", + "https://www.googleapis.com/auth/cloud-platform" + ] + }, + "get": { + "id": "bigquery.jobs.get", + "path": "projects/{projectId}/jobs/{jobId}", + "httpMethod": "GET", + "description": "Returns information about a specific job. Job information is available for a six month period after creation. Requires that you're the person who ran the job, or have the Is Owner project role.", + "parameters": { + "jobId": { + "type": "string", + "description": "[Required] Job ID of the requested job", + "required": true, + "location": "path" + }, + "projectId": { + "type": "string", + "description": "[Required] Project ID of the requested job", + "required": true, + "location": "path" + } + }, + "parameterOrder": [ + "projectId", + "jobId" + ], + "response": { + "$ref": "Job" + }, + "scopes": [ + "https://www.googleapis.com/auth/bigquery", + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-platform.read-only" + ] + }, + "getQueryResults": { + "id": "bigquery.jobs.getQueryResults", + "path": "projects/{projectId}/queries/{jobId}", + "httpMethod": "GET", + "description": "Retrieves the results of a query job.", + "parameters": { + "jobId": { + "type": "string", + "description": "[Required] Job ID of the query job", + "required": true, + "location": "path" + }, + "maxResults": { + "type": "integer", + "description": "Maximum number of results to read", + "format": "uint32", + "location": "query" + }, + "pageToken": { + "type": "string", + "description": "Page token, returned by a previous call, to request the next page of results", + "location": "query" + }, + "projectId": { + "type": "string", + "description": "[Required] Project ID of the query job", + "required": true, + "location": "path" + }, + "startIndex": { + "type": "string", + "description": "Zero-based index of the starting row", + "format": "uint64", + "location": "query" + }, + "timeoutMs": { + "type": "integer", + "description": "How long to wait for the query to complete, in milliseconds, before returning. Default is 10 seconds. If the timeout passes before the job completes, the 'jobComplete' field in the response will be false", + "format": "uint32", + "location": "query" + } + }, + "parameterOrder": [ + "projectId", + "jobId" + ], + "response": { + "$ref": "GetQueryResultsResponse" + }, + "scopes": [ + "https://www.googleapis.com/auth/bigquery", + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-platform.read-only" + ] + }, + "insert": { + "id": "bigquery.jobs.insert", + "path": "projects/{projectId}/jobs", + "httpMethod": "POST", + "description": "Starts a new asynchronous job. Requires the Can View project role.", + "parameters": { + "projectId": { + "type": "string", + "description": "Project ID of the project that will be billed for the job", + "required": true, + "location": "path" + } + }, + "parameterOrder": [ + "projectId" + ], + "request": { + "$ref": "Job" + }, + "response": { + "$ref": "Job" + }, + "scopes": [ + "https://www.googleapis.com/auth/bigquery", + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/devstorage.full_control", + "https://www.googleapis.com/auth/devstorage.read_only", + "https://www.googleapis.com/auth/devstorage.read_write" + ], + "supportsMediaUpload": true, + "mediaUpload": { + "accept": [ + "*/*" + ], + "protocols": { + "simple": { + "multipart": true, + "path": "/upload/bigquery/v2/projects/{projectId}/jobs" + }, + "resumable": { + "multipart": true, + "path": "/resumable/upload/bigquery/v2/projects/{projectId}/jobs" + } + } + } + }, + "list": { + "id": "bigquery.jobs.list", + "path": "projects/{projectId}/jobs", + "httpMethod": "GET", + "description": "Lists all jobs that you started in the specified project. Job information is available for a six month period after creation. The job list is sorted in reverse chronological order, by job creation time. Requires the Can View project role, or the Is Owner project role if you set the allUsers property.", + "parameters": { + "allUsers": { + "type": "boolean", + "description": "Whether to display jobs owned by all users in the project. Default false", + "location": "query" + }, + "maxResults": { + "type": "integer", + "description": "Maximum number of results to return", + "format": "uint32", + "location": "query" + }, + "pageToken": { + "type": "string", + "description": "Page token, returned by a previous call, to request the next page of results", + "location": "query" + }, + "projectId": { + "type": "string", + "description": "Project ID of the jobs to list", + "required": true, + "location": "path" + }, + "projection": { + "type": "string", + "description": "Restrict information returned to a set of selected fields", + "enum": [ + "full", + "minimal" + ], + "enumDescriptions": [ + "Includes all job data", + "Does not include the job configuration" + ], + "location": "query" + }, + "stateFilter": { + "type": "string", + "description": "Filter for job state", + "enum": [ + "done", + "pending", + "running" + ], + "enumDescriptions": [ + "Finished jobs", + "Pending jobs", + "Running jobs" + ], + "repeated": true, + "location": "query" + } + }, + "parameterOrder": [ + "projectId" + ], + "response": { + "$ref": "JobList" + }, + "scopes": [ + "https://www.googleapis.com/auth/bigquery", + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-platform.read-only" + ] + }, + "query": { + "id": "bigquery.jobs.query", + "path": "projects/{projectId}/queries", + "httpMethod": "POST", + "description": "Runs a BigQuery SQL query synchronously and returns query results if the query completes within a specified timeout.", + "parameters": { + "projectId": { + "type": "string", + "description": "Project ID of the project billed for the query", + "required": true, + "location": "path" + } + }, + "parameterOrder": [ + "projectId" + ], + "request": { + "$ref": "QueryRequest" + }, + "response": { + "$ref": "QueryResponse" + }, + "scopes": [ + "https://www.googleapis.com/auth/bigquery", + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-platform.read-only" + ] + } + } + }, + "projects": { + "methods": { + "list": { + "id": "bigquery.projects.list", + "path": "projects", + "httpMethod": "GET", + "description": "Lists all projects to which you have been granted any project role.", + "parameters": { + "maxResults": { + "type": "integer", + "description": "Maximum number of results to return", + "format": "uint32", + "location": "query" + }, + "pageToken": { + "type": "string", + "description": "Page token, returned by a previous call, to request the next page of results", + "location": "query" + } + }, + "response": { + "$ref": "ProjectList" + }, + "scopes": [ + "https://www.googleapis.com/auth/bigquery", + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-platform.read-only" + ] + } + } + }, + "tabledata": { + "methods": { + "insertAll": { + "id": "bigquery.tabledata.insertAll", + "path": "projects/{projectId}/datasets/{datasetId}/tables/{tableId}/insertAll", + "httpMethod": "POST", + "description": "Streams data into BigQuery one record at a time without needing to run a load job. Requires the WRITER dataset role.", + "parameters": { + "datasetId": { + "type": "string", + "description": "Dataset ID of the destination table.", + "required": true, + "location": "path" + }, + "projectId": { + "type": "string", + "description": "Project ID of the destination table.", + "required": true, + "location": "path" + }, + "tableId": { + "type": "string", + "description": "Table ID of the destination table.", + "required": true, + "location": "path" + } + }, + "parameterOrder": [ + "projectId", + "datasetId", + "tableId" + ], + "request": { + "$ref": "TableDataInsertAllRequest" + }, + "response": { + "$ref": "TableDataInsertAllResponse" + }, + "scopes": [ + "https://www.googleapis.com/auth/bigquery", + "https://www.googleapis.com/auth/bigquery.insertdata", + "https://www.googleapis.com/auth/cloud-platform" + ] + }, + "list": { + "id": "bigquery.tabledata.list", + "path": "projects/{projectId}/datasets/{datasetId}/tables/{tableId}/data", + "httpMethod": "GET", + "description": "Retrieves table data from a specified set of rows. Requires the READER dataset role.", + "parameters": { + "datasetId": { + "type": "string", + "description": "Dataset ID of the table to read", + "required": true, + "location": "path" + }, + "maxResults": { + "type": "integer", + "description": "Maximum number of results to return", + "format": "uint32", + "location": "query" + }, + "pageToken": { + "type": "string", + "description": "Page token, returned by a previous call, identifying the result set", + "location": "query" + }, + "projectId": { + "type": "string", + "description": "Project ID of the table to read", + "required": true, + "location": "path" + }, + "startIndex": { + "type": "string", + "description": "Zero-based index of the starting row to read", + "format": "uint64", + "location": "query" + }, + "tableId": { + "type": "string", + "description": "Table ID of the table to read", + "required": true, + "location": "path" + } + }, + "parameterOrder": [ + "projectId", + "datasetId", + "tableId" + ], + "response": { + "$ref": "TableDataList" + }, + "scopes": [ + "https://www.googleapis.com/auth/bigquery", + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-platform.read-only" + ] + } + } + }, + "tables": { + "methods": { + "delete": { + "id": "bigquery.tables.delete", + "path": "projects/{projectId}/datasets/{datasetId}/tables/{tableId}", + "httpMethod": "DELETE", + "description": "Deletes the table specified by tableId from the dataset. If the table contains data, all the data will be deleted.", + "parameters": { + "datasetId": { + "type": "string", + "description": "Dataset ID of the table to delete", + "required": true, + "location": "path" + }, + "projectId": { + "type": "string", + "description": "Project ID of the table to delete", + "required": true, + "location": "path" + }, + "tableId": { + "type": "string", + "description": "Table ID of the table to delete", + "required": true, + "location": "path" + } + }, + "parameterOrder": [ + "projectId", + "datasetId", + "tableId" + ], + "scopes": [ + "https://www.googleapis.com/auth/bigquery", + "https://www.googleapis.com/auth/cloud-platform" + ] + }, + "get": { + "id": "bigquery.tables.get", + "path": "projects/{projectId}/datasets/{datasetId}/tables/{tableId}", + "httpMethod": "GET", + "description": "Gets the specified table resource by table ID. This method does not return the data in the table, it only returns the table resource, which describes the structure of this table.", + "parameters": { + "datasetId": { + "type": "string", + "description": "Dataset ID of the requested table", + "required": true, + "location": "path" + }, + "projectId": { + "type": "string", + "description": "Project ID of the requested table", + "required": true, + "location": "path" + }, + "tableId": { + "type": "string", + "description": "Table ID of the requested table", + "required": true, + "location": "path" + } + }, + "parameterOrder": [ + "projectId", + "datasetId", + "tableId" + ], + "response": { + "$ref": "Table" + }, + "scopes": [ + "https://www.googleapis.com/auth/bigquery", + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-platform.read-only" + ] + }, + "insert": { + "id": "bigquery.tables.insert", + "path": "projects/{projectId}/datasets/{datasetId}/tables", + "httpMethod": "POST", + "description": "Creates a new, empty table in the dataset.", + "parameters": { + "datasetId": { + "type": "string", + "description": "Dataset ID of the new table", + "required": true, + "location": "path" + }, + "projectId": { + "type": "string", + "description": "Project ID of the new table", + "required": true, + "location": "path" + } + }, + "parameterOrder": [ + "projectId", + "datasetId" + ], + "request": { + "$ref": "Table" + }, + "response": { + "$ref": "Table" + }, + "scopes": [ + "https://www.googleapis.com/auth/bigquery", + "https://www.googleapis.com/auth/cloud-platform" + ] + }, + "list": { + "id": "bigquery.tables.list", + "path": "projects/{projectId}/datasets/{datasetId}/tables", + "httpMethod": "GET", + "description": "Lists all tables in the specified dataset. Requires the READER dataset role.", + "parameters": { + "datasetId": { + "type": "string", + "description": "Dataset ID of the tables to list", + "required": true, + "location": "path" + }, + "maxResults": { + "type": "integer", + "description": "Maximum number of results to return", + "format": "uint32", + "location": "query" + }, + "pageToken": { + "type": "string", + "description": "Page token, returned by a previous call, to request the next page of results", + "location": "query" + }, + "projectId": { + "type": "string", + "description": "Project ID of the tables to list", + "required": true, + "location": "path" + } + }, + "parameterOrder": [ + "projectId", + "datasetId" + ], + "response": { + "$ref": "TableList" + }, + "scopes": [ + "https://www.googleapis.com/auth/bigquery", + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-platform.read-only" + ] + }, + "patch": { + "id": "bigquery.tables.patch", + "path": "projects/{projectId}/datasets/{datasetId}/tables/{tableId}", + "httpMethod": "PATCH", + "description": "Updates information in an existing table. The update method replaces the entire table resource, whereas the patch method only replaces fields that are provided in the submitted table resource. This method supports patch semantics.", + "parameters": { + "datasetId": { + "type": "string", + "description": "Dataset ID of the table to update", + "required": true, + "location": "path" + }, + "projectId": { + "type": "string", + "description": "Project ID of the table to update", + "required": true, + "location": "path" + }, + "tableId": { + "type": "string", + "description": "Table ID of the table to update", + "required": true, + "location": "path" + } + }, + "parameterOrder": [ + "projectId", + "datasetId", + "tableId" + ], + "request": { + "$ref": "Table" + }, + "response": { + "$ref": "Table" + }, + "scopes": [ + "https://www.googleapis.com/auth/bigquery", + "https://www.googleapis.com/auth/cloud-platform" + ] + }, + "update": { + "id": "bigquery.tables.update", + "path": "projects/{projectId}/datasets/{datasetId}/tables/{tableId}", + "httpMethod": "PUT", + "description": "Updates information in an existing table. The update method replaces the entire table resource, whereas the patch method only replaces fields that are provided in the submitted table resource.", + "parameters": { + "datasetId": { + "type": "string", + "description": "Dataset ID of the table to update", + "required": true, + "location": "path" + }, + "projectId": { + "type": "string", + "description": "Project ID of the table to update", + "required": true, + "location": "path" + }, + "tableId": { + "type": "string", + "description": "Table ID of the table to update", + "required": true, + "location": "path" + } + }, + "parameterOrder": [ + "projectId", + "datasetId", + "tableId" + ], + "request": { + "$ref": "Table" + }, + "response": { + "$ref": "Table" + }, + "scopes": [ + "https://www.googleapis.com/auth/bigquery", + "https://www.googleapis.com/auth/cloud-platform" + ] + } + } + } + } +} diff --git a/vendor/google.golang.org/api/bigquery/v2/bigquery-gen.go b/vendor/google.golang.org/api/bigquery/v2/bigquery-gen.go new file mode 100644 index 000000000..b907ac827 --- /dev/null +++ b/vendor/google.golang.org/api/bigquery/v2/bigquery-gen.go @@ -0,0 +1,6690 @@ +// Package bigquery provides access to the BigQuery API. +// +// See https://cloud.google.com/bigquery/ +// +// Usage example: +// +// import "google.golang.org/api/bigquery/v2" +// ... +// bigqueryService, err := bigquery.New(oauthHttpClient) +package bigquery // import "google.golang.org/api/bigquery/v2" + +import ( + "bytes" + "encoding/json" + "errors" + "fmt" + context "golang.org/x/net/context" + ctxhttp "golang.org/x/net/context/ctxhttp" + gensupport "google.golang.org/api/gensupport" + googleapi "google.golang.org/api/googleapi" + "io" + "net/http" + "net/url" + "strconv" + "strings" +) + +// Always reference these packages, just in case the auto-generated code +// below doesn't. +var _ = bytes.NewBuffer +var _ = strconv.Itoa +var _ = fmt.Sprintf +var _ = json.NewDecoder +var _ = io.Copy +var _ = url.Parse +var _ = gensupport.MarshalJSON +var _ = googleapi.Version +var _ = errors.New +var _ = strings.Replace +var _ = context.Canceled +var _ = ctxhttp.Do + +const apiId = "bigquery:v2" +const apiName = "bigquery" +const apiVersion = "v2" +const basePath = "https://www.googleapis.com/bigquery/v2/" + +// OAuth2 scopes used by this API. +const ( + // View and manage your data in Google BigQuery + BigqueryScope = "https://www.googleapis.com/auth/bigquery" + + // Insert data into Google BigQuery + BigqueryInsertdataScope = "https://www.googleapis.com/auth/bigquery.insertdata" + + // View and manage your data across Google Cloud Platform services + CloudPlatformScope = "https://www.googleapis.com/auth/cloud-platform" + + // View your data across Google Cloud Platform services + CloudPlatformReadOnlyScope = "https://www.googleapis.com/auth/cloud-platform.read-only" + + // Manage your data and permissions in Google Cloud Storage + DevstorageFullControlScope = "https://www.googleapis.com/auth/devstorage.full_control" + + // View your data in Google Cloud Storage + DevstorageReadOnlyScope = "https://www.googleapis.com/auth/devstorage.read_only" + + // Manage your data in Google Cloud Storage + DevstorageReadWriteScope = "https://www.googleapis.com/auth/devstorage.read_write" +) + +func New(client *http.Client) (*Service, error) { + if client == nil { + return nil, errors.New("client is nil") + } + s := &Service{client: client, BasePath: basePath} + s.Datasets = NewDatasetsService(s) + s.Jobs = NewJobsService(s) + s.Projects = NewProjectsService(s) + s.Tabledata = NewTabledataService(s) + s.Tables = NewTablesService(s) + return s, nil +} + +type Service struct { + client *http.Client + BasePath string // API endpoint base URL + UserAgent string // optional additional User-Agent fragment + GoogleClientHeaderElement string // client header fragment, for Google use only + + Datasets *DatasetsService + + Jobs *JobsService + + Projects *ProjectsService + + Tabledata *TabledataService + + Tables *TablesService +} + +func (s *Service) userAgent() string { + if s.UserAgent == "" { + return googleapi.UserAgent + } + return googleapi.UserAgent + " " + s.UserAgent +} + +func (s *Service) clientHeader() string { + return gensupport.GoogleClientHeader("20170210", s.GoogleClientHeaderElement) +} + +func NewDatasetsService(s *Service) *DatasetsService { + rs := &DatasetsService{s: s} + return rs +} + +type DatasetsService struct { + s *Service +} + +func NewJobsService(s *Service) *JobsService { + rs := &JobsService{s: s} + return rs +} + +type JobsService struct { + s *Service +} + +func NewProjectsService(s *Service) *ProjectsService { + rs := &ProjectsService{s: s} + return rs +} + +type ProjectsService struct { + s *Service +} + +func NewTabledataService(s *Service) *TabledataService { + rs := &TabledataService{s: s} + return rs +} + +type TabledataService struct { + s *Service +} + +func NewTablesService(s *Service) *TablesService { + rs := &TablesService{s: s} + return rs +} + +type TablesService struct { + s *Service +} + +type BigtableColumn struct { + // Encoding: [Optional] The encoding of the values when the type is not + // STRING. Acceptable encoding values are: TEXT - indicates values are + // alphanumeric text strings. BINARY - indicates values are encoded + // using HBase Bytes.toBytes family of functions. 'encoding' can also be + // set at the column family level. However, the setting at this level + // takes precedence if 'encoding' is set at both levels. + Encoding string `json:"encoding,omitempty"` + + // FieldName: [Optional] If the qualifier is not a valid BigQuery field + // identifier i.e. does not match [a-zA-Z][a-zA-Z0-9_]*, a valid + // identifier must be provided as the column field name and is used as + // field name in queries. + FieldName string `json:"fieldName,omitempty"` + + // OnlyReadLatest: [Optional] If this is set, only the latest version of + // value in this column are exposed. 'onlyReadLatest' can also be set at + // the column family level. However, the setting at this level takes + // precedence if 'onlyReadLatest' is set at both levels. + OnlyReadLatest bool `json:"onlyReadLatest,omitempty"` + + // QualifierEncoded: [Required] Qualifier of the column. Columns in the + // parent column family that has this exact qualifier are exposed as . + // field. If the qualifier is valid UTF-8 string, it can be specified in + // the qualifier_string field. Otherwise, a base-64 encoded value must + // be set to qualifier_encoded. The column field name is the same as the + // column qualifier. However, if the qualifier is not a valid BigQuery + // field identifier i.e. does not match [a-zA-Z][a-zA-Z0-9_]*, a valid + // identifier must be provided as field_name. + QualifierEncoded string `json:"qualifierEncoded,omitempty"` + + QualifierString string `json:"qualifierString,omitempty"` + + // Type: [Optional] The type to convert the value in cells of this + // column. The values are expected to be encoded using HBase + // Bytes.toBytes function when using the BINARY encoding value. + // Following BigQuery types are allowed (case-sensitive) - BYTES STRING + // INTEGER FLOAT BOOLEAN Default type is BYTES. 'type' can also be set + // at the column family level. However, the setting at this level takes + // precedence if 'type' is set at both levels. + Type string `json:"type,omitempty"` + + // ForceSendFields is a list of field names (e.g. "Encoding") to + // unconditionally include in API requests. By default, fields with + // empty values are omitted from API requests. However, any non-pointer, + // non-interface field appearing in ForceSendFields will be sent to the + // server regardless of whether the field is empty or not. This may be + // used to include empty fields in Patch requests. + ForceSendFields []string `json:"-"` + + // NullFields is a list of field names (e.g. "Encoding") to include in + // API requests with the JSON null value. By default, fields with empty + // values are omitted from API requests. However, any field with an + // empty value appearing in NullFields will be sent to the server as + // null. It is an error if a field in this list has a non-empty value. + // This may be used to include null fields in Patch requests. + NullFields []string `json:"-"` +} + +func (s *BigtableColumn) MarshalJSON() ([]byte, error) { + type noMethod BigtableColumn + raw := noMethod(*s) + return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) +} + +type BigtableColumnFamily struct { + // Columns: [Optional] Lists of columns that should be exposed as + // individual fields as opposed to a list of (column name, value) pairs. + // All columns whose qualifier matches a qualifier in this list can be + // accessed as .. Other columns can be accessed as a list through + // .Column field. + Columns []*BigtableColumn `json:"columns,omitempty"` + + // Encoding: [Optional] The encoding of the values when the type is not + // STRING. Acceptable encoding values are: TEXT - indicates values are + // alphanumeric text strings. BINARY - indicates values are encoded + // using HBase Bytes.toBytes family of functions. This can be overridden + // for a specific column by listing that column in 'columns' and + // specifying an encoding for it. + Encoding string `json:"encoding,omitempty"` + + // FamilyId: Identifier of the column family. + FamilyId string `json:"familyId,omitempty"` + + // OnlyReadLatest: [Optional] If this is set only the latest version of + // value are exposed for all columns in this column family. This can be + // overridden for a specific column by listing that column in 'columns' + // and specifying a different setting for that column. + OnlyReadLatest bool `json:"onlyReadLatest,omitempty"` + + // Type: [Optional] The type to convert the value in cells of this + // column family. The values are expected to be encoded using HBase + // Bytes.toBytes function when using the BINARY encoding value. + // Following BigQuery types are allowed (case-sensitive) - BYTES STRING + // INTEGER FLOAT BOOLEAN Default type is BYTES. This can be overridden + // for a specific column by listing that column in 'columns' and + // specifying a type for it. + Type string `json:"type,omitempty"` + + // ForceSendFields is a list of field names (e.g. "Columns") to + // unconditionally include in API requests. By default, fields with + // empty values are omitted from API requests. However, any non-pointer, + // non-interface field appearing in ForceSendFields will be sent to the + // server regardless of whether the field is empty or not. This may be + // used to include empty fields in Patch requests. + ForceSendFields []string `json:"-"` + + // NullFields is a list of field names (e.g. "Columns") to include in + // API requests with the JSON null value. By default, fields with empty + // values are omitted from API requests. However, any field with an + // empty value appearing in NullFields will be sent to the server as + // null. It is an error if a field in this list has a non-empty value. + // This may be used to include null fields in Patch requests. + NullFields []string `json:"-"` +} + +func (s *BigtableColumnFamily) MarshalJSON() ([]byte, error) { + type noMethod BigtableColumnFamily + raw := noMethod(*s) + return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) +} + +type BigtableOptions struct { + // ColumnFamilies: [Optional] List of column families to expose in the + // table schema along with their types. This list restricts the column + // families that can be referenced in queries and specifies their value + // types. You can use this list to do type conversions - see the 'type' + // field for more details. If you leave this list empty, all column + // families are present in the table schema and their values are read as + // BYTES. During a query only the column families referenced in that + // query are read from Bigtable. + ColumnFamilies []*BigtableColumnFamily `json:"columnFamilies,omitempty"` + + // IgnoreUnspecifiedColumnFamilies: [Optional] If field is true, then + // the column families that are not specified in columnFamilies list are + // not exposed in the table schema. Otherwise, they are read with BYTES + // type values. The default value is false. + IgnoreUnspecifiedColumnFamilies bool `json:"ignoreUnspecifiedColumnFamilies,omitempty"` + + // ReadRowkeyAsString: [Optional] If field is true, then the rowkey + // column families will be read and converted to string. Otherwise they + // are read with BYTES type values and users need to manually cast them + // with CAST if necessary. The default value is false. + ReadRowkeyAsString bool `json:"readRowkeyAsString,omitempty"` + + // ForceSendFields is a list of field names (e.g. "ColumnFamilies") to + // unconditionally include in API requests. By default, fields with + // empty values are omitted from API requests. However, any non-pointer, + // non-interface field appearing in ForceSendFields will be sent to the + // server regardless of whether the field is empty or not. This may be + // used to include empty fields in Patch requests. + ForceSendFields []string `json:"-"` + + // NullFields is a list of field names (e.g. "ColumnFamilies") to + // include in API requests with the JSON null value. By default, fields + // with empty values are omitted from API requests. However, any field + // with an empty value appearing in NullFields will be sent to the + // server as null. It is an error if a field in this list has a + // non-empty value. This may be used to include null fields in Patch + // requests. + NullFields []string `json:"-"` +} + +func (s *BigtableOptions) MarshalJSON() ([]byte, error) { + type noMethod BigtableOptions + raw := noMethod(*s) + return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) +} + +type CsvOptions struct { + // AllowJaggedRows: [Optional] Indicates if BigQuery should accept rows + // that are missing trailing optional columns. If true, BigQuery treats + // missing trailing columns as null values. If false, records with + // missing trailing columns are treated as bad records, and if there are + // too many bad records, an invalid error is returned in the job result. + // The default value is false. + AllowJaggedRows bool `json:"allowJaggedRows,omitempty"` + + // AllowQuotedNewlines: [Optional] Indicates if BigQuery should allow + // quoted data sections that contain newline characters in a CSV file. + // The default value is false. + AllowQuotedNewlines bool `json:"allowQuotedNewlines,omitempty"` + + // Encoding: [Optional] The character encoding of the data. The + // supported values are UTF-8 or ISO-8859-1. The default value is UTF-8. + // BigQuery decodes the data after the raw, binary data has been split + // using the values of the quote and fieldDelimiter properties. + Encoding string `json:"encoding,omitempty"` + + // FieldDelimiter: [Optional] The separator for fields in a CSV file. + // BigQuery converts the string to ISO-8859-1 encoding, and then uses + // the first byte of the encoded string to split the data in its raw, + // binary state. BigQuery also supports the escape sequence "\t" to + // specify a tab separator. The default value is a comma (','). + FieldDelimiter string `json:"fieldDelimiter,omitempty"` + + // Quote: [Optional] The value that is used to quote data sections in a + // CSV file. BigQuery converts the string to ISO-8859-1 encoding, and + // then uses the first byte of the encoded string to split the data in + // its raw, binary state. The default value is a double-quote ('"'). If + // your data does not contain quoted sections, set the property value to + // an empty string. If your data contains quoted newline characters, you + // must also set the allowQuotedNewlines property to true. + // + // Default: " + Quote *string `json:"quote,omitempty"` + + // SkipLeadingRows: [Optional] The number of rows at the top of a CSV + // file that BigQuery will skip when reading the data. The default value + // is 0. This property is useful if you have header rows in the file + // that should be skipped. + SkipLeadingRows int64 `json:"skipLeadingRows,omitempty,string"` + + // ForceSendFields is a list of field names (e.g. "AllowJaggedRows") to + // unconditionally include in API requests. By default, fields with + // empty values are omitted from API requests. However, any non-pointer, + // non-interface field appearing in ForceSendFields will be sent to the + // server regardless of whether the field is empty or not. This may be + // used to include empty fields in Patch requests. + ForceSendFields []string `json:"-"` + + // NullFields is a list of field names (e.g. "AllowJaggedRows") to + // include in API requests with the JSON null value. By default, fields + // with empty values are omitted from API requests. However, any field + // with an empty value appearing in NullFields will be sent to the + // server as null. It is an error if a field in this list has a + // non-empty value. This may be used to include null fields in Patch + // requests. + NullFields []string `json:"-"` +} + +func (s *CsvOptions) MarshalJSON() ([]byte, error) { + type noMethod CsvOptions + raw := noMethod(*s) + return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) +} + +type Dataset struct { + // Access: [Optional] An array of objects that define dataset access for + // one or more entities. You can set this property when inserting or + // updating a dataset in order to control who is allowed to access the + // data. If unspecified at dataset creation time, BigQuery adds default + // dataset access for the following entities: access.specialGroup: + // projectReaders; access.role: READER; access.specialGroup: + // projectWriters; access.role: WRITER; access.specialGroup: + // projectOwners; access.role: OWNER; access.userByEmail: [dataset + // creator email]; access.role: OWNER; + Access []*DatasetAccess `json:"access,omitempty"` + + // CreationTime: [Output-only] The time when this dataset was created, + // in milliseconds since the epoch. + CreationTime int64 `json:"creationTime,omitempty,string"` + + // DatasetReference: [Required] A reference that identifies the dataset. + DatasetReference *DatasetReference `json:"datasetReference,omitempty"` + + // DefaultTableExpirationMs: [Optional] The default lifetime of all + // tables in the dataset, in milliseconds. The minimum value is 3600000 + // milliseconds (one hour). Once this property is set, all newly-created + // tables in the dataset will have an expirationTime property set to the + // creation time plus the value in this property, and changing the value + // will only affect new tables, not existing ones. When the + // expirationTime for a given table is reached, that table will be + // deleted automatically. If a table's expirationTime is modified or + // removed before the table expires, or if you provide an explicit + // expirationTime when creating a table, that value takes precedence + // over the default expiration time indicated by this property. + DefaultTableExpirationMs int64 `json:"defaultTableExpirationMs,omitempty,string"` + + // Description: [Optional] A user-friendly description of the dataset. + Description string `json:"description,omitempty"` + + // Etag: [Output-only] A hash of the resource. + Etag string `json:"etag,omitempty"` + + // FriendlyName: [Optional] A descriptive name for the dataset. + FriendlyName string `json:"friendlyName,omitempty"` + + // Id: [Output-only] The fully-qualified unique name of the dataset in + // the format projectId:datasetId. The dataset name without the project + // name is given in the datasetId field. When creating a new dataset, + // leave this field blank, and instead specify the datasetId field. + Id string `json:"id,omitempty"` + + // Kind: [Output-only] The resource type. + Kind string `json:"kind,omitempty"` + + // Labels: [Experimental] The labels associated with this dataset. You + // can use these to organize and group your datasets. You can set this + // property when inserting or updating a dataset. See Labeling Datasets + // for more information. + Labels map[string]string `json:"labels,omitempty"` + + // LastModifiedTime: [Output-only] The date when this dataset or any of + // its tables was last modified, in milliseconds since the epoch. + LastModifiedTime int64 `json:"lastModifiedTime,omitempty,string"` + + // Location: [Experimental] The geographic location where the dataset + // should reside. Possible values include EU and US. The default value + // is US. + Location string `json:"location,omitempty"` + + // SelfLink: [Output-only] A URL that can be used to access the resource + // again. You can use this URL in Get or Update requests to the + // resource. + SelfLink string `json:"selfLink,omitempty"` + + // ServerResponse contains the HTTP response code and headers from the + // server. + googleapi.ServerResponse `json:"-"` + + // ForceSendFields is a list of field names (e.g. "Access") to + // unconditionally include in API requests. By default, fields with + // empty values are omitted from API requests. However, any non-pointer, + // non-interface field appearing in ForceSendFields will be sent to the + // server regardless of whether the field is empty or not. This may be + // used to include empty fields in Patch requests. + ForceSendFields []string `json:"-"` + + // NullFields is a list of field names (e.g. "Access") to include in API + // requests with the JSON null value. By default, fields with empty + // values are omitted from API requests. However, any field with an + // empty value appearing in NullFields will be sent to the server as + // null. It is an error if a field in this list has a non-empty value. + // This may be used to include null fields in Patch requests. + NullFields []string `json:"-"` +} + +func (s *Dataset) MarshalJSON() ([]byte, error) { + type noMethod Dataset + raw := noMethod(*s) + return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) +} + +type DatasetAccess struct { + // Domain: [Pick one] A domain to grant access to. Any users signed in + // with the domain specified will be granted the specified access. + // Example: "example.com". + Domain string `json:"domain,omitempty"` + + // GroupByEmail: [Pick one] An email address of a Google Group to grant + // access to. + GroupByEmail string `json:"groupByEmail,omitempty"` + + // Role: [Required] Describes the rights granted to the user specified + // by the other member of the access object. The following string values + // are supported: READER, WRITER, OWNER. + Role string `json:"role,omitempty"` + + // SpecialGroup: [Pick one] A special group to grant access to. Possible + // values include: projectOwners: Owners of the enclosing project. + // projectReaders: Readers of the enclosing project. projectWriters: + // Writers of the enclosing project. allAuthenticatedUsers: All + // authenticated BigQuery users. + SpecialGroup string `json:"specialGroup,omitempty"` + + // UserByEmail: [Pick one] An email address of a user to grant access + // to. For example: fred@example.com. + UserByEmail string `json:"userByEmail,omitempty"` + + // View: [Pick one] A view from a different dataset to grant access to. + // Queries executed against that view will have read access to tables in + // this dataset. The role field is not required when this field is set. + // If that view is updated by any user, access to the view needs to be + // granted again via an update operation. + View *TableReference `json:"view,omitempty"` + + // ForceSendFields is a list of field names (e.g. "Domain") to + // unconditionally include in API requests. By default, fields with + // empty values are omitted from API requests. However, any non-pointer, + // non-interface field appearing in ForceSendFields will be sent to the + // server regardless of whether the field is empty or not. This may be + // used to include empty fields in Patch requests. + ForceSendFields []string `json:"-"` + + // NullFields is a list of field names (e.g. "Domain") to include in API + // requests with the JSON null value. By default, fields with empty + // values are omitted from API requests. However, any field with an + // empty value appearing in NullFields will be sent to the server as + // null. It is an error if a field in this list has a non-empty value. + // This may be used to include null fields in Patch requests. + NullFields []string `json:"-"` +} + +func (s *DatasetAccess) MarshalJSON() ([]byte, error) { + type noMethod DatasetAccess + raw := noMethod(*s) + return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) +} + +type DatasetList struct { + // Datasets: An array of the dataset resources in the project. Each + // resource contains basic information. For full information about a + // particular dataset resource, use the Datasets: get method. This + // property is omitted when there are no datasets in the project. + Datasets []*DatasetListDatasets `json:"datasets,omitempty"` + + // Etag: A hash value of the results page. You can use this property to + // determine if the page has changed since the last request. + Etag string `json:"etag,omitempty"` + + // Kind: The list type. This property always returns the value + // "bigquery#datasetList". + Kind string `json:"kind,omitempty"` + + // NextPageToken: A token that can be used to request the next results + // page. This property is omitted on the final results page. + NextPageToken string `json:"nextPageToken,omitempty"` + + // ServerResponse contains the HTTP response code and headers from the + // server. + googleapi.ServerResponse `json:"-"` + + // ForceSendFields is a list of field names (e.g. "Datasets") to + // unconditionally include in API requests. By default, fields with + // empty values are omitted from API requests. However, any non-pointer, + // non-interface field appearing in ForceSendFields will be sent to the + // server regardless of whether the field is empty or not. This may be + // used to include empty fields in Patch requests. + ForceSendFields []string `json:"-"` + + // NullFields is a list of field names (e.g. "Datasets") to include in + // API requests with the JSON null value. By default, fields with empty + // values are omitted from API requests. However, any field with an + // empty value appearing in NullFields will be sent to the server as + // null. It is an error if a field in this list has a non-empty value. + // This may be used to include null fields in Patch requests. + NullFields []string `json:"-"` +} + +func (s *DatasetList) MarshalJSON() ([]byte, error) { + type noMethod DatasetList + raw := noMethod(*s) + return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) +} + +type DatasetListDatasets struct { + // DatasetReference: The dataset reference. Use this property to access + // specific parts of the dataset's ID, such as project ID or dataset ID. + DatasetReference *DatasetReference `json:"datasetReference,omitempty"` + + // FriendlyName: A descriptive name for the dataset, if one exists. + FriendlyName string `json:"friendlyName,omitempty"` + + // Id: The fully-qualified, unique, opaque ID of the dataset. + Id string `json:"id,omitempty"` + + // Kind: The resource type. This property always returns the value + // "bigquery#dataset". + Kind string `json:"kind,omitempty"` + + // Labels: [Experimental] The labels associated with this dataset. You + // can use these to organize and group your datasets. + Labels map[string]string `json:"labels,omitempty"` + + // ForceSendFields is a list of field names (e.g. "DatasetReference") to + // unconditionally include in API requests. By default, fields with + // empty values are omitted from API requests. However, any non-pointer, + // non-interface field appearing in ForceSendFields will be sent to the + // server regardless of whether the field is empty or not. This may be + // used to include empty fields in Patch requests. + ForceSendFields []string `json:"-"` + + // NullFields is a list of field names (e.g. "DatasetReference") to + // include in API requests with the JSON null value. By default, fields + // with empty values are omitted from API requests. However, any field + // with an empty value appearing in NullFields will be sent to the + // server as null. It is an error if a field in this list has a + // non-empty value. This may be used to include null fields in Patch + // requests. + NullFields []string `json:"-"` +} + +func (s *DatasetListDatasets) MarshalJSON() ([]byte, error) { + type noMethod DatasetListDatasets + raw := noMethod(*s) + return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) +} + +type DatasetReference struct { + // DatasetId: [Required] A unique ID for this dataset, without the + // project name. The ID must contain only letters (a-z, A-Z), numbers + // (0-9), or underscores (_). The maximum length is 1,024 characters. + DatasetId string `json:"datasetId,omitempty"` + + // ProjectId: [Optional] The ID of the project containing this dataset. + ProjectId string `json:"projectId,omitempty"` + + // ForceSendFields is a list of field names (e.g. "DatasetId") to + // unconditionally include in API requests. By default, fields with + // empty values are omitted from API requests. However, any non-pointer, + // non-interface field appearing in ForceSendFields will be sent to the + // server regardless of whether the field is empty or not. This may be + // used to include empty fields in Patch requests. + ForceSendFields []string `json:"-"` + + // NullFields is a list of field names (e.g. "DatasetId") to include in + // API requests with the JSON null value. By default, fields with empty + // values are omitted from API requests. However, any field with an + // empty value appearing in NullFields will be sent to the server as + // null. It is an error if a field in this list has a non-empty value. + // This may be used to include null fields in Patch requests. + NullFields []string `json:"-"` +} + +func (s *DatasetReference) MarshalJSON() ([]byte, error) { + type noMethod DatasetReference + raw := noMethod(*s) + return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) +} + +type ErrorProto struct { + // DebugInfo: Debugging information. This property is internal to Google + // and should not be used. + DebugInfo string `json:"debugInfo,omitempty"` + + // Location: Specifies where the error occurred, if present. + Location string `json:"location,omitempty"` + + // Message: A human-readable description of the error. + Message string `json:"message,omitempty"` + + // Reason: A short error code that summarizes the error. + Reason string `json:"reason,omitempty"` + + // ForceSendFields is a list of field names (e.g. "DebugInfo") to + // unconditionally include in API requests. By default, fields with + // empty values are omitted from API requests. However, any non-pointer, + // non-interface field appearing in ForceSendFields will be sent to the + // server regardless of whether the field is empty or not. This may be + // used to include empty fields in Patch requests. + ForceSendFields []string `json:"-"` + + // NullFields is a list of field names (e.g. "DebugInfo") to include in + // API requests with the JSON null value. By default, fields with empty + // values are omitted from API requests. However, any field with an + // empty value appearing in NullFields will be sent to the server as + // null. It is an error if a field in this list has a non-empty value. + // This may be used to include null fields in Patch requests. + NullFields []string `json:"-"` +} + +func (s *ErrorProto) MarshalJSON() ([]byte, error) { + type noMethod ErrorProto + raw := noMethod(*s) + return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) +} + +type ExplainQueryStage struct { + // ComputeRatioAvg: Relative amount of time the average shard spent on + // CPU-bound tasks. + ComputeRatioAvg float64 `json:"computeRatioAvg,omitempty"` + + // ComputeRatioMax: Relative amount of time the slowest shard spent on + // CPU-bound tasks. + ComputeRatioMax float64 `json:"computeRatioMax,omitempty"` + + // Id: Unique ID for stage within plan. + Id int64 `json:"id,omitempty,string"` + + // Name: Human-readable name for stage. + Name string `json:"name,omitempty"` + + // ReadRatioAvg: Relative amount of time the average shard spent reading + // input. + ReadRatioAvg float64 `json:"readRatioAvg,omitempty"` + + // ReadRatioMax: Relative amount of time the slowest shard spent reading + // input. + ReadRatioMax float64 `json:"readRatioMax,omitempty"` + + // RecordsRead: Number of records read into the stage. + RecordsRead int64 `json:"recordsRead,omitempty,string"` + + // RecordsWritten: Number of records written by the stage. + RecordsWritten int64 `json:"recordsWritten,omitempty,string"` + + // Status: Current status for the stage. + Status string `json:"status,omitempty"` + + // Steps: List of operations within the stage in dependency order + // (approximately chronological). + Steps []*ExplainQueryStep `json:"steps,omitempty"` + + // WaitRatioAvg: Relative amount of time the average shard spent waiting + // to be scheduled. + WaitRatioAvg float64 `json:"waitRatioAvg,omitempty"` + + // WaitRatioMax: Relative amount of time the slowest shard spent waiting + // to be scheduled. + WaitRatioMax float64 `json:"waitRatioMax,omitempty"` + + // WriteRatioAvg: Relative amount of time the average shard spent on + // writing output. + WriteRatioAvg float64 `json:"writeRatioAvg,omitempty"` + + // WriteRatioMax: Relative amount of time the slowest shard spent on + // writing output. + WriteRatioMax float64 `json:"writeRatioMax,omitempty"` + + // ForceSendFields is a list of field names (e.g. "ComputeRatioAvg") to + // unconditionally include in API requests. By default, fields with + // empty values are omitted from API requests. However, any non-pointer, + // non-interface field appearing in ForceSendFields will be sent to the + // server regardless of whether the field is empty or not. This may be + // used to include empty fields in Patch requests. + ForceSendFields []string `json:"-"` + + // NullFields is a list of field names (e.g. "ComputeRatioAvg") to + // include in API requests with the JSON null value. By default, fields + // with empty values are omitted from API requests. However, any field + // with an empty value appearing in NullFields will be sent to the + // server as null. It is an error if a field in this list has a + // non-empty value. This may be used to include null fields in Patch + // requests. + NullFields []string `json:"-"` +} + +func (s *ExplainQueryStage) MarshalJSON() ([]byte, error) { + type noMethod ExplainQueryStage + raw := noMethod(*s) + return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) +} + +func (s *ExplainQueryStage) UnmarshalJSON(data []byte) error { + type noMethod ExplainQueryStage + var s1 struct { + ComputeRatioAvg gensupport.JSONFloat64 `json:"computeRatioAvg"` + ComputeRatioMax gensupport.JSONFloat64 `json:"computeRatioMax"` + ReadRatioAvg gensupport.JSONFloat64 `json:"readRatioAvg"` + ReadRatioMax gensupport.JSONFloat64 `json:"readRatioMax"` + WaitRatioAvg gensupport.JSONFloat64 `json:"waitRatioAvg"` + WaitRatioMax gensupport.JSONFloat64 `json:"waitRatioMax"` + WriteRatioAvg gensupport.JSONFloat64 `json:"writeRatioAvg"` + WriteRatioMax gensupport.JSONFloat64 `json:"writeRatioMax"` + *noMethod + } + s1.noMethod = (*noMethod)(s) + if err := json.Unmarshal(data, &s1); err != nil { + return err + } + s.ComputeRatioAvg = float64(s1.ComputeRatioAvg) + s.ComputeRatioMax = float64(s1.ComputeRatioMax) + s.ReadRatioAvg = float64(s1.ReadRatioAvg) + s.ReadRatioMax = float64(s1.ReadRatioMax) + s.WaitRatioAvg = float64(s1.WaitRatioAvg) + s.WaitRatioMax = float64(s1.WaitRatioMax) + s.WriteRatioAvg = float64(s1.WriteRatioAvg) + s.WriteRatioMax = float64(s1.WriteRatioMax) + return nil +} + +type ExplainQueryStep struct { + // Kind: Machine-readable operation type. + Kind string `json:"kind,omitempty"` + + // Substeps: Human-readable stage descriptions. + Substeps []string `json:"substeps,omitempty"` + + // ForceSendFields is a list of field names (e.g. "Kind") to + // unconditionally include in API requests. By default, fields with + // empty values are omitted from API requests. However, any non-pointer, + // non-interface field appearing in ForceSendFields will be sent to the + // server regardless of whether the field is empty or not. This may be + // used to include empty fields in Patch requests. + ForceSendFields []string `json:"-"` + + // NullFields is a list of field names (e.g. "Kind") to include in API + // requests with the JSON null value. By default, fields with empty + // values are omitted from API requests. However, any field with an + // empty value appearing in NullFields will be sent to the server as + // null. It is an error if a field in this list has a non-empty value. + // This may be used to include null fields in Patch requests. + NullFields []string `json:"-"` +} + +func (s *ExplainQueryStep) MarshalJSON() ([]byte, error) { + type noMethod ExplainQueryStep + raw := noMethod(*s) + return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) +} + +type ExternalDataConfiguration struct { + // Autodetect: [Experimental] Try to detect schema and format options + // automatically. Any option specified explicitly will be honored. + Autodetect bool `json:"autodetect,omitempty"` + + // BigtableOptions: [Optional] Additional options if sourceFormat is set + // to BIGTABLE. + BigtableOptions *BigtableOptions `json:"bigtableOptions,omitempty"` + + // Compression: [Optional] The compression type of the data source. + // Possible values include GZIP and NONE. The default value is NONE. + // This setting is ignored for Google Cloud Bigtable, Google Cloud + // Datastore backups and Avro formats. + Compression string `json:"compression,omitempty"` + + // CsvOptions: Additional properties to set if sourceFormat is set to + // CSV. + CsvOptions *CsvOptions `json:"csvOptions,omitempty"` + + // GoogleSheetsOptions: [Optional] Additional options if sourceFormat is + // set to GOOGLE_SHEETS. + GoogleSheetsOptions *GoogleSheetsOptions `json:"googleSheetsOptions,omitempty"` + + // IgnoreUnknownValues: [Optional] Indicates if BigQuery should allow + // extra values that are not represented in the table schema. If true, + // the extra values are ignored. If false, records with extra columns + // are treated as bad records, and if there are too many bad records, an + // invalid error is returned in the job result. The default value is + // false. The sourceFormat property determines what BigQuery treats as + // an extra value: CSV: Trailing columns JSON: Named values that don't + // match any column names Google Cloud Bigtable: This setting is + // ignored. Google Cloud Datastore backups: This setting is ignored. + // Avro: This setting is ignored. + IgnoreUnknownValues bool `json:"ignoreUnknownValues,omitempty"` + + // MaxBadRecords: [Optional] The maximum number of bad records that + // BigQuery can ignore when reading data. If the number of bad records + // exceeds this value, an invalid error is returned in the job result. + // The default value is 0, which requires that all records are valid. + // This setting is ignored for Google Cloud Bigtable, Google Cloud + // Datastore backups and Avro formats. + MaxBadRecords int64 `json:"maxBadRecords,omitempty"` + + // Schema: [Optional] The schema for the data. Schema is required for + // CSV and JSON formats. Schema is disallowed for Google Cloud Bigtable, + // Cloud Datastore backups, and Avro formats. + Schema *TableSchema `json:"schema,omitempty"` + + // SourceFormat: [Required] The data format. For CSV files, specify + // "CSV". For Google sheets, specify "GOOGLE_SHEETS". For + // newline-delimited JSON, specify "NEWLINE_DELIMITED_JSON". For Avro + // files, specify "AVRO". For Google Cloud Datastore backups, specify + // "DATASTORE_BACKUP". [Experimental] For Google Cloud Bigtable, specify + // "BIGTABLE". Please note that reading from Google Cloud Bigtable is + // experimental and has to be enabled for your project. Please contact + // Google Cloud Support to enable this for your project. + SourceFormat string `json:"sourceFormat,omitempty"` + + // SourceUris: [Required] The fully-qualified URIs that point to your + // data in Google Cloud. For Google Cloud Storage URIs: Each URI can + // contain one '*' wildcard character and it must come after the + // 'bucket' name. Size limits related to load jobs apply to external + // data sources. For Google Cloud Bigtable URIs: Exactly one URI can be + // specified and it has be a fully specified and valid HTTPS URL for a + // Google Cloud Bigtable table. For Google Cloud Datastore backups, + // exactly one URI can be specified, and it must end with + // '.backup_info'. Also, the '*' wildcard character is not allowed. + SourceUris []string `json:"sourceUris,omitempty"` + + // ForceSendFields is a list of field names (e.g. "Autodetect") to + // unconditionally include in API requests. By default, fields with + // empty values are omitted from API requests. However, any non-pointer, + // non-interface field appearing in ForceSendFields will be sent to the + // server regardless of whether the field is empty or not. This may be + // used to include empty fields in Patch requests. + ForceSendFields []string `json:"-"` + + // NullFields is a list of field names (e.g. "Autodetect") to include in + // API requests with the JSON null value. By default, fields with empty + // values are omitted from API requests. However, any field with an + // empty value appearing in NullFields will be sent to the server as + // null. It is an error if a field in this list has a non-empty value. + // This may be used to include null fields in Patch requests. + NullFields []string `json:"-"` +} + +func (s *ExternalDataConfiguration) MarshalJSON() ([]byte, error) { + type noMethod ExternalDataConfiguration + raw := noMethod(*s) + return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) +} + +type GetQueryResultsResponse struct { + // CacheHit: Whether the query result was fetched from the query cache. + CacheHit bool `json:"cacheHit,omitempty"` + + // Errors: [Output-only] All errors and warnings encountered during the + // running of the job. Errors here do not necessarily mean that the job + // has completed or was unsuccessful. + Errors []*ErrorProto `json:"errors,omitempty"` + + // Etag: A hash of this response. + Etag string `json:"etag,omitempty"` + + // JobComplete: Whether the query has completed or not. If rows or + // totalRows are present, this will always be true. If this is false, + // totalRows will not be available. + JobComplete bool `json:"jobComplete,omitempty"` + + // JobReference: Reference to the BigQuery Job that was created to run + // the query. This field will be present even if the original request + // timed out, in which case GetQueryResults can be used to read the + // results once the query has completed. Since this API only returns the + // first page of results, subsequent pages can be fetched via the same + // mechanism (GetQueryResults). + JobReference *JobReference `json:"jobReference,omitempty"` + + // Kind: The resource type of the response. + Kind string `json:"kind,omitempty"` + + // NumDmlAffectedRows: [Output-only, Experimental] The number of rows + // affected by a DML statement. Present only for DML statements INSERT, + // UPDATE or DELETE. + NumDmlAffectedRows int64 `json:"numDmlAffectedRows,omitempty,string"` + + // PageToken: A token used for paging results. + PageToken string `json:"pageToken,omitempty"` + + // Rows: An object with as many results as can be contained within the + // maximum permitted reply size. To get any additional rows, you can + // call GetQueryResults and specify the jobReference returned above. + // Present only when the query completes successfully. + Rows []*TableRow `json:"rows,omitempty"` + + // Schema: The schema of the results. Present only when the query + // completes successfully. + Schema *TableSchema `json:"schema,omitempty"` + + // TotalBytesProcessed: The total number of bytes processed for this + // query. + TotalBytesProcessed int64 `json:"totalBytesProcessed,omitempty,string"` + + // TotalRows: The total number of rows in the complete query result set, + // which can be more than the number of rows in this single page of + // results. Present only when the query completes successfully. + TotalRows uint64 `json:"totalRows,omitempty,string"` + + // ServerResponse contains the HTTP response code and headers from the + // server. + googleapi.ServerResponse `json:"-"` + + // ForceSendFields is a list of field names (e.g. "CacheHit") to + // unconditionally include in API requests. By default, fields with + // empty values are omitted from API requests. However, any non-pointer, + // non-interface field appearing in ForceSendFields will be sent to the + // server regardless of whether the field is empty or not. This may be + // used to include empty fields in Patch requests. + ForceSendFields []string `json:"-"` + + // NullFields is a list of field names (e.g. "CacheHit") to include in + // API requests with the JSON null value. By default, fields with empty + // values are omitted from API requests. However, any field with an + // empty value appearing in NullFields will be sent to the server as + // null. It is an error if a field in this list has a non-empty value. + // This may be used to include null fields in Patch requests. + NullFields []string `json:"-"` +} + +func (s *GetQueryResultsResponse) MarshalJSON() ([]byte, error) { + type noMethod GetQueryResultsResponse + raw := noMethod(*s) + return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) +} + +type GoogleSheetsOptions struct { + // SkipLeadingRows: [Optional] The number of rows at the top of a sheet + // that BigQuery will skip when reading the data. The default value is + // 0. This property is useful if you have header rows that should be + // skipped. When autodetect is on, behavior is the following: * + // skipLeadingRows unspecified - Autodetect tries to detect headers in + // the first row. If they are not detected, the row is read as data. + // Otherwise data is read starting from the second row. * + // skipLeadingRows is 0 - Instructs autodetect that there are no headers + // and data should be read starting from the first row. * + // skipLeadingRows = N > 0 - Autodetect skips N-1 rows and tries to + // detect headers in row N. If headers are not detected, row N is just + // skipped. Otherwise row N is used to extract column names for the + // detected schema. + SkipLeadingRows int64 `json:"skipLeadingRows,omitempty,string"` + + // ForceSendFields is a list of field names (e.g. "SkipLeadingRows") to + // unconditionally include in API requests. By default, fields with + // empty values are omitted from API requests. However, any non-pointer, + // non-interface field appearing in ForceSendFields will be sent to the + // server regardless of whether the field is empty or not. This may be + // used to include empty fields in Patch requests. + ForceSendFields []string `json:"-"` + + // NullFields is a list of field names (e.g. "SkipLeadingRows") to + // include in API requests with the JSON null value. By default, fields + // with empty values are omitted from API requests. However, any field + // with an empty value appearing in NullFields will be sent to the + // server as null. It is an error if a field in this list has a + // non-empty value. This may be used to include null fields in Patch + // requests. + NullFields []string `json:"-"` +} + +func (s *GoogleSheetsOptions) MarshalJSON() ([]byte, error) { + type noMethod GoogleSheetsOptions + raw := noMethod(*s) + return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) +} + +type Job struct { + // Configuration: [Required] Describes the job configuration. + Configuration *JobConfiguration `json:"configuration,omitempty"` + + // Etag: [Output-only] A hash of this resource. + Etag string `json:"etag,omitempty"` + + // Id: [Output-only] Opaque ID field of the job + Id string `json:"id,omitempty"` + + // JobReference: [Optional] Reference describing the unique-per-user + // name of the job. + JobReference *JobReference `json:"jobReference,omitempty"` + + // Kind: [Output-only] The type of the resource. + Kind string `json:"kind,omitempty"` + + // SelfLink: [Output-only] A URL that can be used to access this + // resource again. + SelfLink string `json:"selfLink,omitempty"` + + // Statistics: [Output-only] Information about the job, including + // starting time and ending time of the job. + Statistics *JobStatistics `json:"statistics,omitempty"` + + // Status: [Output-only] The status of this job. Examine this value when + // polling an asynchronous job to see if the job is complete. + Status *JobStatus `json:"status,omitempty"` + + // UserEmail: [Output-only] Email address of the user who ran the job. + UserEmail string `json:"user_email,omitempty"` + + // ServerResponse contains the HTTP response code and headers from the + // server. + googleapi.ServerResponse `json:"-"` + + // ForceSendFields is a list of field names (e.g. "Configuration") to + // unconditionally include in API requests. By default, fields with + // empty values are omitted from API requests. However, any non-pointer, + // non-interface field appearing in ForceSendFields will be sent to the + // server regardless of whether the field is empty or not. This may be + // used to include empty fields in Patch requests. + ForceSendFields []string `json:"-"` + + // NullFields is a list of field names (e.g. "Configuration") to include + // in API requests with the JSON null value. By default, fields with + // empty values are omitted from API requests. However, any field with + // an empty value appearing in NullFields will be sent to the server as + // null. It is an error if a field in this list has a non-empty value. + // This may be used to include null fields in Patch requests. + NullFields []string `json:"-"` +} + +func (s *Job) MarshalJSON() ([]byte, error) { + type noMethod Job + raw := noMethod(*s) + return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) +} + +type JobCancelResponse struct { + // Job: The final state of the job. + Job *Job `json:"job,omitempty"` + + // Kind: The resource type of the response. + Kind string `json:"kind,omitempty"` + + // ServerResponse contains the HTTP response code and headers from the + // server. + googleapi.ServerResponse `json:"-"` + + // ForceSendFields is a list of field names (e.g. "Job") to + // unconditionally include in API requests. By default, fields with + // empty values are omitted from API requests. However, any non-pointer, + // non-interface field appearing in ForceSendFields will be sent to the + // server regardless of whether the field is empty or not. This may be + // used to include empty fields in Patch requests. + ForceSendFields []string `json:"-"` + + // NullFields is a list of field names (e.g. "Job") to include in API + // requests with the JSON null value. By default, fields with empty + // values are omitted from API requests. However, any field with an + // empty value appearing in NullFields will be sent to the server as + // null. It is an error if a field in this list has a non-empty value. + // This may be used to include null fields in Patch requests. + NullFields []string `json:"-"` +} + +func (s *JobCancelResponse) MarshalJSON() ([]byte, error) { + type noMethod JobCancelResponse + raw := noMethod(*s) + return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) +} + +type JobConfiguration struct { + // Copy: [Pick one] Copies a table. + Copy *JobConfigurationTableCopy `json:"copy,omitempty"` + + // DryRun: [Optional] If set, don't actually run this job. A valid query + // will return a mostly empty response with some processing statistics, + // while an invalid query will return the same error it would if it + // wasn't a dry run. Behavior of non-query jobs is undefined. + DryRun bool `json:"dryRun,omitempty"` + + // Extract: [Pick one] Configures an extract job. + Extract *JobConfigurationExtract `json:"extract,omitempty"` + + // Labels: [Experimental] The labels associated with this job. You can + // use these to organize and group your jobs. Label keys and values can + // be no longer than 63 characters, can only contain lowercase letters, + // numeric characters, underscores and dashes. International characters + // are allowed. Label values are optional. Label keys must start with a + // letter and each label in the list must have a different key. + Labels map[string]string `json:"labels,omitempty"` + + // Load: [Pick one] Configures a load job. + Load *JobConfigurationLoad `json:"load,omitempty"` + + // Query: [Pick one] Configures a query job. + Query *JobConfigurationQuery `json:"query,omitempty"` + + // ForceSendFields is a list of field names (e.g. "Copy") to + // unconditionally include in API requests. By default, fields with + // empty values are omitted from API requests. However, any non-pointer, + // non-interface field appearing in ForceSendFields will be sent to the + // server regardless of whether the field is empty or not. This may be + // used to include empty fields in Patch requests. + ForceSendFields []string `json:"-"` + + // NullFields is a list of field names (e.g. "Copy") to include in API + // requests with the JSON null value. By default, fields with empty + // values are omitted from API requests. However, any field with an + // empty value appearing in NullFields will be sent to the server as + // null. It is an error if a field in this list has a non-empty value. + // This may be used to include null fields in Patch requests. + NullFields []string `json:"-"` +} + +func (s *JobConfiguration) MarshalJSON() ([]byte, error) { + type noMethod JobConfiguration + raw := noMethod(*s) + return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) +} + +type JobConfigurationExtract struct { + // Compression: [Optional] The compression type to use for exported + // files. Possible values include GZIP and NONE. The default value is + // NONE. + Compression string `json:"compression,omitempty"` + + // DestinationFormat: [Optional] The exported file format. Possible + // values include CSV, NEWLINE_DELIMITED_JSON and AVRO. The default + // value is CSV. Tables with nested or repeated fields cannot be + // exported as CSV. + DestinationFormat string `json:"destinationFormat,omitempty"` + + // DestinationUri: [Pick one] DEPRECATED: Use destinationUris instead, + // passing only one URI as necessary. The fully-qualified Google Cloud + // Storage URI where the extracted table should be written. + DestinationUri string `json:"destinationUri,omitempty"` + + // DestinationUris: [Pick one] A list of fully-qualified Google Cloud + // Storage URIs where the extracted table should be written. + DestinationUris []string `json:"destinationUris,omitempty"` + + // FieldDelimiter: [Optional] Delimiter to use between fields in the + // exported data. Default is ',' + FieldDelimiter string `json:"fieldDelimiter,omitempty"` + + // PrintHeader: [Optional] Whether to print out a header row in the + // results. Default is true. + // + // Default: true + PrintHeader *bool `json:"printHeader,omitempty"` + + // SourceTable: [Required] A reference to the table being exported. + SourceTable *TableReference `json:"sourceTable,omitempty"` + + // ForceSendFields is a list of field names (e.g. "Compression") to + // unconditionally include in API requests. By default, fields with + // empty values are omitted from API requests. However, any non-pointer, + // non-interface field appearing in ForceSendFields will be sent to the + // server regardless of whether the field is empty or not. This may be + // used to include empty fields in Patch requests. + ForceSendFields []string `json:"-"` + + // NullFields is a list of field names (e.g. "Compression") to include + // in API requests with the JSON null value. By default, fields with + // empty values are omitted from API requests. However, any field with + // an empty value appearing in NullFields will be sent to the server as + // null. It is an error if a field in this list has a non-empty value. + // This may be used to include null fields in Patch requests. + NullFields []string `json:"-"` +} + +func (s *JobConfigurationExtract) MarshalJSON() ([]byte, error) { + type noMethod JobConfigurationExtract + raw := noMethod(*s) + return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) +} + +type JobConfigurationLoad struct { + // AllowJaggedRows: [Optional] Accept rows that are missing trailing + // optional columns. The missing values are treated as nulls. If false, + // records with missing trailing columns are treated as bad records, and + // if there are too many bad records, an invalid error is returned in + // the job result. The default value is false. Only applicable to CSV, + // ignored for other formats. + AllowJaggedRows bool `json:"allowJaggedRows,omitempty"` + + // AllowQuotedNewlines: Indicates if BigQuery should allow quoted data + // sections that contain newline characters in a CSV file. The default + // value is false. + AllowQuotedNewlines bool `json:"allowQuotedNewlines,omitempty"` + + // Autodetect: [Experimental] Indicates if we should automatically infer + // the options and schema for CSV and JSON sources. + Autodetect bool `json:"autodetect,omitempty"` + + // CreateDisposition: [Optional] Specifies whether the job is allowed to + // create new tables. The following values are supported: + // CREATE_IF_NEEDED: If the table does not exist, BigQuery creates the + // table. CREATE_NEVER: The table must already exist. If it does not, a + // 'notFound' error is returned in the job result. The default value is + // CREATE_IF_NEEDED. Creation, truncation and append actions occur as + // one atomic update upon job completion. + CreateDisposition string `json:"createDisposition,omitempty"` + + // DestinationTable: [Required] The destination table to load the data + // into. + DestinationTable *TableReference `json:"destinationTable,omitempty"` + + // Encoding: [Optional] The character encoding of the data. The + // supported values are UTF-8 or ISO-8859-1. The default value is UTF-8. + // BigQuery decodes the data after the raw, binary data has been split + // using the values of the quote and fieldDelimiter properties. + Encoding string `json:"encoding,omitempty"` + + // FieldDelimiter: [Optional] The separator for fields in a CSV file. + // The separator can be any ISO-8859-1 single-byte character. To use a + // character in the range 128-255, you must encode the character as + // UTF8. BigQuery converts the string to ISO-8859-1 encoding, and then + // uses the first byte of the encoded string to split the data in its + // raw, binary state. BigQuery also supports the escape sequence "\t" to + // specify a tab separator. The default value is a comma (','). + FieldDelimiter string `json:"fieldDelimiter,omitempty"` + + // IgnoreUnknownValues: [Optional] Indicates if BigQuery should allow + // extra values that are not represented in the table schema. If true, + // the extra values are ignored. If false, records with extra columns + // are treated as bad records, and if there are too many bad records, an + // invalid error is returned in the job result. The default value is + // false. The sourceFormat property determines what BigQuery treats as + // an extra value: CSV: Trailing columns JSON: Named values that don't + // match any column names + IgnoreUnknownValues bool `json:"ignoreUnknownValues,omitempty"` + + // MaxBadRecords: [Optional] The maximum number of bad records that + // BigQuery can ignore when running the job. If the number of bad + // records exceeds this value, an invalid error is returned in the job + // result. The default value is 0, which requires that all records are + // valid. + MaxBadRecords int64 `json:"maxBadRecords,omitempty"` + + // NullMarker: [Optional] Specifies a string that represents a null + // value in a CSV file. For example, if you specify "\N", BigQuery + // interprets "\N" as a null value when loading a CSV file. The default + // value is the empty string. If you set this property to a custom + // value, BigQuery still interprets the empty string as a null value for + // all data types except for STRING and BYTE. For STRING and BYTE + // columns, BigQuery interprets the empty string as an empty value. + NullMarker string `json:"nullMarker,omitempty"` + + // ProjectionFields: [Experimental] If sourceFormat is set to + // "DATASTORE_BACKUP", indicates which entity properties to load into + // BigQuery from a Cloud Datastore backup. Property names are case + // sensitive and must be top-level properties. If no properties are + // specified, BigQuery loads all properties. If any named property isn't + // found in the Cloud Datastore backup, an invalid error is returned in + // the job result. + ProjectionFields []string `json:"projectionFields,omitempty"` + + // Quote: [Optional] The value that is used to quote data sections in a + // CSV file. BigQuery converts the string to ISO-8859-1 encoding, and + // then uses the first byte of the encoded string to split the data in + // its raw, binary state. The default value is a double-quote ('"'). If + // your data does not contain quoted sections, set the property value to + // an empty string. If your data contains quoted newline characters, you + // must also set the allowQuotedNewlines property to true. + // + // Default: " + Quote *string `json:"quote,omitempty"` + + // Schema: [Optional] The schema for the destination table. The schema + // can be omitted if the destination table already exists, or if you're + // loading data from Google Cloud Datastore. + Schema *TableSchema `json:"schema,omitempty"` + + // SchemaInline: [Deprecated] The inline schema. For CSV schemas, + // specify as "Field1:Type1[,Field2:Type2]*". For example, "foo:STRING, + // bar:INTEGER, baz:FLOAT". + SchemaInline string `json:"schemaInline,omitempty"` + + // SchemaInlineFormat: [Deprecated] The format of the schemaInline + // property. + SchemaInlineFormat string `json:"schemaInlineFormat,omitempty"` + + // SchemaUpdateOptions: [Experimental] Allows the schema of the + // desitination table to be updated as a side effect of the load job. + // Schema update options are supported in two cases: when + // writeDisposition is WRITE_APPEND; when writeDisposition is + // WRITE_TRUNCATE and the destination table is a partition of a table, + // specified by partition decorators. For normal tables, WRITE_TRUNCATE + // will always overwrite the schema. One or more of the following values + // are specified: ALLOW_FIELD_ADDITION: allow adding a nullable field to + // the schema. ALLOW_FIELD_RELAXATION: allow relaxing a required field + // in the original schema to nullable. + SchemaUpdateOptions []string `json:"schemaUpdateOptions,omitempty"` + + // SkipLeadingRows: [Optional] The number of rows at the top of a CSV + // file that BigQuery will skip when loading the data. The default value + // is 0. This property is useful if you have header rows in the file + // that should be skipped. + SkipLeadingRows int64 `json:"skipLeadingRows,omitempty"` + + // SourceFormat: [Optional] The format of the data files. For CSV files, + // specify "CSV". For datastore backups, specify "DATASTORE_BACKUP". For + // newline-delimited JSON, specify "NEWLINE_DELIMITED_JSON". For Avro, + // specify "AVRO". The default value is CSV. + SourceFormat string `json:"sourceFormat,omitempty"` + + // SourceUris: [Required] The fully-qualified URIs that point to your + // data in Google Cloud Storage. Each URI can contain one '*' wildcard + // character and it must come after the 'bucket' name. + SourceUris []string `json:"sourceUris,omitempty"` + + // WriteDisposition: [Optional] Specifies the action that occurs if the + // destination table already exists. The following values are supported: + // WRITE_TRUNCATE: If the table already exists, BigQuery overwrites the + // table data. WRITE_APPEND: If the table already exists, BigQuery + // appends the data to the table. WRITE_EMPTY: If the table already + // exists and contains data, a 'duplicate' error is returned in the job + // result. The default value is WRITE_APPEND. Each action is atomic and + // only occurs if BigQuery is able to complete the job successfully. + // Creation, truncation and append actions occur as one atomic update + // upon job completion. + WriteDisposition string `json:"writeDisposition,omitempty"` + + // ForceSendFields is a list of field names (e.g. "AllowJaggedRows") to + // unconditionally include in API requests. By default, fields with + // empty values are omitted from API requests. However, any non-pointer, + // non-interface field appearing in ForceSendFields will be sent to the + // server regardless of whether the field is empty or not. This may be + // used to include empty fields in Patch requests. + ForceSendFields []string `json:"-"` + + // NullFields is a list of field names (e.g. "AllowJaggedRows") to + // include in API requests with the JSON null value. By default, fields + // with empty values are omitted from API requests. However, any field + // with an empty value appearing in NullFields will be sent to the + // server as null. It is an error if a field in this list has a + // non-empty value. This may be used to include null fields in Patch + // requests. + NullFields []string `json:"-"` +} + +func (s *JobConfigurationLoad) MarshalJSON() ([]byte, error) { + type noMethod JobConfigurationLoad + raw := noMethod(*s) + return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) +} + +type JobConfigurationQuery struct { + // AllowLargeResults: If true, allows the query to produce arbitrarily + // large result tables at a slight cost in performance. Requires + // destinationTable to be set. + AllowLargeResults bool `json:"allowLargeResults,omitempty"` + + // CreateDisposition: [Optional] Specifies whether the job is allowed to + // create new tables. The following values are supported: + // CREATE_IF_NEEDED: If the table does not exist, BigQuery creates the + // table. CREATE_NEVER: The table must already exist. If it does not, a + // 'notFound' error is returned in the job result. The default value is + // CREATE_IF_NEEDED. Creation, truncation and append actions occur as + // one atomic update upon job completion. + CreateDisposition string `json:"createDisposition,omitempty"` + + // DefaultDataset: [Optional] Specifies the default dataset to use for + // unqualified table names in the query. + DefaultDataset *DatasetReference `json:"defaultDataset,omitempty"` + + // DestinationTable: [Optional] Describes the table where the query + // results should be stored. If not present, a new table will be created + // to store the results. + DestinationTable *TableReference `json:"destinationTable,omitempty"` + + // FlattenResults: [Optional] Flattens all nested and repeated fields in + // the query results. The default value is true. allowLargeResults must + // be true if this is set to false. + // + // Default: true + FlattenResults *bool `json:"flattenResults,omitempty"` + + // MaximumBillingTier: [Optional] Limits the billing tier for this job. + // Queries that have resource usage beyond this tier will fail (without + // incurring a charge). If unspecified, this will be set to your project + // default. + // + // Default: 1 + MaximumBillingTier *int64 `json:"maximumBillingTier,omitempty"` + + // MaximumBytesBilled: [Optional] Limits the bytes billed for this job. + // Queries that will have bytes billed beyond this limit will fail + // (without incurring a charge). If unspecified, this will be set to + // your project default. + MaximumBytesBilled int64 `json:"maximumBytesBilled,omitempty,string"` + + // ParameterMode: [Experimental] Standard SQL only. Set to POSITIONAL to + // use positional (?) query parameters or to NAMED to use named + // (@myparam) query parameters in this query. + ParameterMode string `json:"parameterMode,omitempty"` + + // PreserveNulls: [Deprecated] This property is deprecated. + PreserveNulls bool `json:"preserveNulls,omitempty"` + + // Priority: [Optional] Specifies a priority for the query. Possible + // values include INTERACTIVE and BATCH. The default value is + // INTERACTIVE. + Priority string `json:"priority,omitempty"` + + // Query: [Required] BigQuery SQL query to execute. + Query string `json:"query,omitempty"` + + // QueryParameters: Query parameters for standard SQL queries. + QueryParameters []*QueryParameter `json:"queryParameters,omitempty"` + + // SchemaUpdateOptions: [Experimental] Allows the schema of the + // destination table to be updated as a side effect of the query job. + // Schema update options are supported in two cases: when + // writeDisposition is WRITE_APPEND; when writeDisposition is + // WRITE_TRUNCATE and the destination table is a partition of a table, + // specified by partition decorators. For normal tables, WRITE_TRUNCATE + // will always overwrite the schema. One or more of the following values + // are specified: ALLOW_FIELD_ADDITION: allow adding a nullable field to + // the schema. ALLOW_FIELD_RELAXATION: allow relaxing a required field + // in the original schema to nullable. + SchemaUpdateOptions []string `json:"schemaUpdateOptions,omitempty"` + + // TableDefinitions: [Optional] If querying an external data source + // outside of BigQuery, describes the data format, location and other + // properties of the data source. By defining these properties, the data + // source can then be queried as if it were a standard BigQuery table. + TableDefinitions map[string]ExternalDataConfiguration `json:"tableDefinitions,omitempty"` + + // UseLegacySql: Specifies whether to use BigQuery's legacy SQL dialect + // for this query. The default value is true. If set to false, the query + // will use BigQuery's standard SQL: + // https://cloud.google.com/bigquery/sql-reference/ When useLegacySql is + // set to false, the values of allowLargeResults and flattenResults are + // ignored; query will be run as if allowLargeResults is true and + // flattenResults is false. + UseLegacySql bool `json:"useLegacySql,omitempty"` + + // UseQueryCache: [Optional] Whether to look for the result in the query + // cache. The query cache is a best-effort cache that will be flushed + // whenever tables in the query are modified. Moreover, the query cache + // is only available when a query does not have a destination table + // specified. The default value is true. + // + // Default: true + UseQueryCache *bool `json:"useQueryCache,omitempty"` + + // UserDefinedFunctionResources: [Experimental] Describes user-defined + // function resources used in the query. + UserDefinedFunctionResources []*UserDefinedFunctionResource `json:"userDefinedFunctionResources,omitempty"` + + // WriteDisposition: [Optional] Specifies the action that occurs if the + // destination table already exists. The following values are supported: + // WRITE_TRUNCATE: If the table already exists, BigQuery overwrites the + // table data. WRITE_APPEND: If the table already exists, BigQuery + // appends the data to the table. WRITE_EMPTY: If the table already + // exists and contains data, a 'duplicate' error is returned in the job + // result. The default value is WRITE_EMPTY. Each action is atomic and + // only occurs if BigQuery is able to complete the job successfully. + // Creation, truncation and append actions occur as one atomic update + // upon job completion. + WriteDisposition string `json:"writeDisposition,omitempty"` + + // ForceSendFields is a list of field names (e.g. "AllowLargeResults") + // to unconditionally include in API requests. By default, fields with + // empty values are omitted from API requests. However, any non-pointer, + // non-interface field appearing in ForceSendFields will be sent to the + // server regardless of whether the field is empty or not. This may be + // used to include empty fields in Patch requests. + ForceSendFields []string `json:"-"` + + // NullFields is a list of field names (e.g. "AllowLargeResults") to + // include in API requests with the JSON null value. By default, fields + // with empty values are omitted from API requests. However, any field + // with an empty value appearing in NullFields will be sent to the + // server as null. It is an error if a field in this list has a + // non-empty value. This may be used to include null fields in Patch + // requests. + NullFields []string `json:"-"` +} + +func (s *JobConfigurationQuery) MarshalJSON() ([]byte, error) { + type noMethod JobConfigurationQuery + raw := noMethod(*s) + return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) +} + +type JobConfigurationTableCopy struct { + // CreateDisposition: [Optional] Specifies whether the job is allowed to + // create new tables. The following values are supported: + // CREATE_IF_NEEDED: If the table does not exist, BigQuery creates the + // table. CREATE_NEVER: The table must already exist. If it does not, a + // 'notFound' error is returned in the job result. The default value is + // CREATE_IF_NEEDED. Creation, truncation and append actions occur as + // one atomic update upon job completion. + CreateDisposition string `json:"createDisposition,omitempty"` + + // DestinationTable: [Required] The destination table + DestinationTable *TableReference `json:"destinationTable,omitempty"` + + // SourceTable: [Pick one] Source table to copy. + SourceTable *TableReference `json:"sourceTable,omitempty"` + + // SourceTables: [Pick one] Source tables to copy. + SourceTables []*TableReference `json:"sourceTables,omitempty"` + + // WriteDisposition: [Optional] Specifies the action that occurs if the + // destination table already exists. The following values are supported: + // WRITE_TRUNCATE: If the table already exists, BigQuery overwrites the + // table data. WRITE_APPEND: If the table already exists, BigQuery + // appends the data to the table. WRITE_EMPTY: If the table already + // exists and contains data, a 'duplicate' error is returned in the job + // result. The default value is WRITE_EMPTY. Each action is atomic and + // only occurs if BigQuery is able to complete the job successfully. + // Creation, truncation and append actions occur as one atomic update + // upon job completion. + WriteDisposition string `json:"writeDisposition,omitempty"` + + // ForceSendFields is a list of field names (e.g. "CreateDisposition") + // to unconditionally include in API requests. By default, fields with + // empty values are omitted from API requests. However, any non-pointer, + // non-interface field appearing in ForceSendFields will be sent to the + // server regardless of whether the field is empty or not. This may be + // used to include empty fields in Patch requests. + ForceSendFields []string `json:"-"` + + // NullFields is a list of field names (e.g. "CreateDisposition") to + // include in API requests with the JSON null value. By default, fields + // with empty values are omitted from API requests. However, any field + // with an empty value appearing in NullFields will be sent to the + // server as null. It is an error if a field in this list has a + // non-empty value. This may be used to include null fields in Patch + // requests. + NullFields []string `json:"-"` +} + +func (s *JobConfigurationTableCopy) MarshalJSON() ([]byte, error) { + type noMethod JobConfigurationTableCopy + raw := noMethod(*s) + return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) +} + +type JobList struct { + // Etag: A hash of this page of results. + Etag string `json:"etag,omitempty"` + + // Jobs: List of jobs that were requested. + Jobs []*JobListJobs `json:"jobs,omitempty"` + + // Kind: The resource type of the response. + Kind string `json:"kind,omitempty"` + + // NextPageToken: A token to request the next page of results. + NextPageToken string `json:"nextPageToken,omitempty"` + + // ServerResponse contains the HTTP response code and headers from the + // server. + googleapi.ServerResponse `json:"-"` + + // ForceSendFields is a list of field names (e.g. "Etag") to + // unconditionally include in API requests. By default, fields with + // empty values are omitted from API requests. However, any non-pointer, + // non-interface field appearing in ForceSendFields will be sent to the + // server regardless of whether the field is empty or not. This may be + // used to include empty fields in Patch requests. + ForceSendFields []string `json:"-"` + + // NullFields is a list of field names (e.g. "Etag") to include in API + // requests with the JSON null value. By default, fields with empty + // values are omitted from API requests. However, any field with an + // empty value appearing in NullFields will be sent to the server as + // null. It is an error if a field in this list has a non-empty value. + // This may be used to include null fields in Patch requests. + NullFields []string `json:"-"` +} + +func (s *JobList) MarshalJSON() ([]byte, error) { + type noMethod JobList + raw := noMethod(*s) + return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) +} + +type JobListJobs struct { + // Configuration: [Full-projection-only] Specifies the job + // configuration. + Configuration *JobConfiguration `json:"configuration,omitempty"` + + // ErrorResult: A result object that will be present only if the job has + // failed. + ErrorResult *ErrorProto `json:"errorResult,omitempty"` + + // Id: Unique opaque ID of the job. + Id string `json:"id,omitempty"` + + // JobReference: Job reference uniquely identifying the job. + JobReference *JobReference `json:"jobReference,omitempty"` + + // Kind: The resource type. + Kind string `json:"kind,omitempty"` + + // State: Running state of the job. When the state is DONE, errorResult + // can be checked to determine whether the job succeeded or failed. + State string `json:"state,omitempty"` + + // Statistics: [Output-only] Information about the job, including + // starting time and ending time of the job. + Statistics *JobStatistics `json:"statistics,omitempty"` + + // Status: [Full-projection-only] Describes the state of the job. + Status *JobStatus `json:"status,omitempty"` + + // UserEmail: [Full-projection-only] Email address of the user who ran + // the job. + UserEmail string `json:"user_email,omitempty"` + + // ForceSendFields is a list of field names (e.g. "Configuration") to + // unconditionally include in API requests. By default, fields with + // empty values are omitted from API requests. However, any non-pointer, + // non-interface field appearing in ForceSendFields will be sent to the + // server regardless of whether the field is empty or not. This may be + // used to include empty fields in Patch requests. + ForceSendFields []string `json:"-"` + + // NullFields is a list of field names (e.g. "Configuration") to include + // in API requests with the JSON null value. By default, fields with + // empty values are omitted from API requests. However, any field with + // an empty value appearing in NullFields will be sent to the server as + // null. It is an error if a field in this list has a non-empty value. + // This may be used to include null fields in Patch requests. + NullFields []string `json:"-"` +} + +func (s *JobListJobs) MarshalJSON() ([]byte, error) { + type noMethod JobListJobs + raw := noMethod(*s) + return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) +} + +type JobReference struct { + // JobId: [Required] The ID of the job. The ID must contain only letters + // (a-z, A-Z), numbers (0-9), underscores (_), or dashes (-). The + // maximum length is 1,024 characters. + JobId string `json:"jobId,omitempty"` + + // ProjectId: [Required] The ID of the project containing this job. + ProjectId string `json:"projectId,omitempty"` + + // ForceSendFields is a list of field names (e.g. "JobId") to + // unconditionally include in API requests. By default, fields with + // empty values are omitted from API requests. However, any non-pointer, + // non-interface field appearing in ForceSendFields will be sent to the + // server regardless of whether the field is empty or not. This may be + // used to include empty fields in Patch requests. + ForceSendFields []string `json:"-"` + + // NullFields is a list of field names (e.g. "JobId") to include in API + // requests with the JSON null value. By default, fields with empty + // values are omitted from API requests. However, any field with an + // empty value appearing in NullFields will be sent to the server as + // null. It is an error if a field in this list has a non-empty value. + // This may be used to include null fields in Patch requests. + NullFields []string `json:"-"` +} + +func (s *JobReference) MarshalJSON() ([]byte, error) { + type noMethod JobReference + raw := noMethod(*s) + return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) +} + +type JobStatistics struct { + // CreationTime: [Output-only] Creation time of this job, in + // milliseconds since the epoch. This field will be present on all jobs. + CreationTime int64 `json:"creationTime,omitempty,string"` + + // EndTime: [Output-only] End time of this job, in milliseconds since + // the epoch. This field will be present whenever a job is in the DONE + // state. + EndTime int64 `json:"endTime,omitempty,string"` + + // Extract: [Output-only] Statistics for an extract job. + Extract *JobStatistics4 `json:"extract,omitempty"` + + // Load: [Output-only] Statistics for a load job. + Load *JobStatistics3 `json:"load,omitempty"` + + // Query: [Output-only] Statistics for a query job. + Query *JobStatistics2 `json:"query,omitempty"` + + // StartTime: [Output-only] Start time of this job, in milliseconds + // since the epoch. This field will be present when the job transitions + // from the PENDING state to either RUNNING or DONE. + StartTime int64 `json:"startTime,omitempty,string"` + + // TotalBytesProcessed: [Output-only] [Deprecated] Use the bytes + // processed in the query statistics instead. + TotalBytesProcessed int64 `json:"totalBytesProcessed,omitempty,string"` + + // ForceSendFields is a list of field names (e.g. "CreationTime") to + // unconditionally include in API requests. By default, fields with + // empty values are omitted from API requests. However, any non-pointer, + // non-interface field appearing in ForceSendFields will be sent to the + // server regardless of whether the field is empty or not. This may be + // used to include empty fields in Patch requests. + ForceSendFields []string `json:"-"` + + // NullFields is a list of field names (e.g. "CreationTime") to include + // in API requests with the JSON null value. By default, fields with + // empty values are omitted from API requests. However, any field with + // an empty value appearing in NullFields will be sent to the server as + // null. It is an error if a field in this list has a non-empty value. + // This may be used to include null fields in Patch requests. + NullFields []string `json:"-"` +} + +func (s *JobStatistics) MarshalJSON() ([]byte, error) { + type noMethod JobStatistics + raw := noMethod(*s) + return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) +} + +type JobStatistics2 struct { + // BillingTier: [Output-only] Billing tier for the job. + BillingTier int64 `json:"billingTier,omitempty"` + + // CacheHit: [Output-only] Whether the query result was fetched from the + // query cache. + CacheHit bool `json:"cacheHit,omitempty"` + + // NumDmlAffectedRows: [Output-only, Experimental] The number of rows + // affected by a DML statement. Present only for DML statements INSERT, + // UPDATE or DELETE. + NumDmlAffectedRows int64 `json:"numDmlAffectedRows,omitempty,string"` + + // QueryPlan: [Output-only, Experimental] Describes execution plan for + // the query. + QueryPlan []*ExplainQueryStage `json:"queryPlan,omitempty"` + + // ReferencedTables: [Output-only, Experimental] Referenced tables for + // the job. Queries that reference more than 50 tables will not have a + // complete list. + ReferencedTables []*TableReference `json:"referencedTables,omitempty"` + + // Schema: [Output-only, Experimental] The schema of the results. + // Present only for successful dry run of non-legacy SQL queries. + Schema *TableSchema `json:"schema,omitempty"` + + // StatementType: [Output-only, Experimental] The type of query + // statement, if valid. + StatementType string `json:"statementType,omitempty"` + + // TotalBytesBilled: [Output-only] Total bytes billed for the job. + TotalBytesBilled int64 `json:"totalBytesBilled,omitempty,string"` + + // TotalBytesProcessed: [Output-only] Total bytes processed for the job. + TotalBytesProcessed int64 `json:"totalBytesProcessed,omitempty,string"` + + // UndeclaredQueryParameters: [Output-only, Experimental] Standard SQL + // only: list of undeclared query parameters detected during a dry run + // validation. + UndeclaredQueryParameters []*QueryParameter `json:"undeclaredQueryParameters,omitempty"` + + // ForceSendFields is a list of field names (e.g. "BillingTier") to + // unconditionally include in API requests. By default, fields with + // empty values are omitted from API requests. However, any non-pointer, + // non-interface field appearing in ForceSendFields will be sent to the + // server regardless of whether the field is empty or not. This may be + // used to include empty fields in Patch requests. + ForceSendFields []string `json:"-"` + + // NullFields is a list of field names (e.g. "BillingTier") to include + // in API requests with the JSON null value. By default, fields with + // empty values are omitted from API requests. However, any field with + // an empty value appearing in NullFields will be sent to the server as + // null. It is an error if a field in this list has a non-empty value. + // This may be used to include null fields in Patch requests. + NullFields []string `json:"-"` +} + +func (s *JobStatistics2) MarshalJSON() ([]byte, error) { + type noMethod JobStatistics2 + raw := noMethod(*s) + return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) +} + +type JobStatistics3 struct { + // InputFileBytes: [Output-only] Number of bytes of source data in a + // load job. + InputFileBytes int64 `json:"inputFileBytes,omitempty,string"` + + // InputFiles: [Output-only] Number of source files in a load job. + InputFiles int64 `json:"inputFiles,omitempty,string"` + + // OutputBytes: [Output-only] Size of the loaded data in bytes. Note + // that while a load job is in the running state, this value may change. + OutputBytes int64 `json:"outputBytes,omitempty,string"` + + // OutputRows: [Output-only] Number of rows imported in a load job. Note + // that while an import job is in the running state, this value may + // change. + OutputRows int64 `json:"outputRows,omitempty,string"` + + // ForceSendFields is a list of field names (e.g. "InputFileBytes") to + // unconditionally include in API requests. By default, fields with + // empty values are omitted from API requests. However, any non-pointer, + // non-interface field appearing in ForceSendFields will be sent to the + // server regardless of whether the field is empty or not. This may be + // used to include empty fields in Patch requests. + ForceSendFields []string `json:"-"` + + // NullFields is a list of field names (e.g. "InputFileBytes") to + // include in API requests with the JSON null value. By default, fields + // with empty values are omitted from API requests. However, any field + // with an empty value appearing in NullFields will be sent to the + // server as null. It is an error if a field in this list has a + // non-empty value. This may be used to include null fields in Patch + // requests. + NullFields []string `json:"-"` +} + +func (s *JobStatistics3) MarshalJSON() ([]byte, error) { + type noMethod JobStatistics3 + raw := noMethod(*s) + return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) +} + +type JobStatistics4 struct { + // DestinationUriFileCounts: [Output-only] Number of files per + // destination URI or URI pattern specified in the extract + // configuration. These values will be in the same order as the URIs + // specified in the 'destinationUris' field. + DestinationUriFileCounts googleapi.Int64s `json:"destinationUriFileCounts,omitempty"` + + // ForceSendFields is a list of field names (e.g. + // "DestinationUriFileCounts") to unconditionally include in API + // requests. By default, fields with empty values are omitted from API + // requests. However, any non-pointer, non-interface field appearing in + // ForceSendFields will be sent to the server regardless of whether the + // field is empty or not. This may be used to include empty fields in + // Patch requests. + ForceSendFields []string `json:"-"` + + // NullFields is a list of field names (e.g. "DestinationUriFileCounts") + // to include in API requests with the JSON null value. By default, + // fields with empty values are omitted from API requests. However, any + // field with an empty value appearing in NullFields will be sent to the + // server as null. It is an error if a field in this list has a + // non-empty value. This may be used to include null fields in Patch + // requests. + NullFields []string `json:"-"` +} + +func (s *JobStatistics4) MarshalJSON() ([]byte, error) { + type noMethod JobStatistics4 + raw := noMethod(*s) + return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) +} + +type JobStatus struct { + // ErrorResult: [Output-only] Final error result of the job. If present, + // indicates that the job has completed and was unsuccessful. + ErrorResult *ErrorProto `json:"errorResult,omitempty"` + + // Errors: [Output-only] All errors encountered during the running of + // the job. Errors here do not necessarily mean that the job has + // completed or was unsuccessful. + Errors []*ErrorProto `json:"errors,omitempty"` + + // State: [Output-only] Running state of the job. + State string `json:"state,omitempty"` + + // ForceSendFields is a list of field names (e.g. "ErrorResult") to + // unconditionally include in API requests. By default, fields with + // empty values are omitted from API requests. However, any non-pointer, + // non-interface field appearing in ForceSendFields will be sent to the + // server regardless of whether the field is empty or not. This may be + // used to include empty fields in Patch requests. + ForceSendFields []string `json:"-"` + + // NullFields is a list of field names (e.g. "ErrorResult") to include + // in API requests with the JSON null value. By default, fields with + // empty values are omitted from API requests. However, any field with + // an empty value appearing in NullFields will be sent to the server as + // null. It is an error if a field in this list has a non-empty value. + // This may be used to include null fields in Patch requests. + NullFields []string `json:"-"` +} + +func (s *JobStatus) MarshalJSON() ([]byte, error) { + type noMethod JobStatus + raw := noMethod(*s) + return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) +} + +type JsonValue interface{} + +type ProjectList struct { + // Etag: A hash of the page of results + Etag string `json:"etag,omitempty"` + + // Kind: The type of list. + Kind string `json:"kind,omitempty"` + + // NextPageToken: A token to request the next page of results. + NextPageToken string `json:"nextPageToken,omitempty"` + + // Projects: Projects to which you have at least READ access. + Projects []*ProjectListProjects `json:"projects,omitempty"` + + // TotalItems: The total number of projects in the list. + TotalItems int64 `json:"totalItems,omitempty"` + + // ServerResponse contains the HTTP response code and headers from the + // server. + googleapi.ServerResponse `json:"-"` + + // ForceSendFields is a list of field names (e.g. "Etag") to + // unconditionally include in API requests. By default, fields with + // empty values are omitted from API requests. However, any non-pointer, + // non-interface field appearing in ForceSendFields will be sent to the + // server regardless of whether the field is empty or not. This may be + // used to include empty fields in Patch requests. + ForceSendFields []string `json:"-"` + + // NullFields is a list of field names (e.g. "Etag") to include in API + // requests with the JSON null value. By default, fields with empty + // values are omitted from API requests. However, any field with an + // empty value appearing in NullFields will be sent to the server as + // null. It is an error if a field in this list has a non-empty value. + // This may be used to include null fields in Patch requests. + NullFields []string `json:"-"` +} + +func (s *ProjectList) MarshalJSON() ([]byte, error) { + type noMethod ProjectList + raw := noMethod(*s) + return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) +} + +type ProjectListProjects struct { + // FriendlyName: A descriptive name for this project. + FriendlyName string `json:"friendlyName,omitempty"` + + // Id: An opaque ID of this project. + Id string `json:"id,omitempty"` + + // Kind: The resource type. + Kind string `json:"kind,omitempty"` + + // NumericId: The numeric ID of this project. + NumericId uint64 `json:"numericId,omitempty,string"` + + // ProjectReference: A unique reference to this project. + ProjectReference *ProjectReference `json:"projectReference,omitempty"` + + // ForceSendFields is a list of field names (e.g. "FriendlyName") to + // unconditionally include in API requests. By default, fields with + // empty values are omitted from API requests. However, any non-pointer, + // non-interface field appearing in ForceSendFields will be sent to the + // server regardless of whether the field is empty or not. This may be + // used to include empty fields in Patch requests. + ForceSendFields []string `json:"-"` + + // NullFields is a list of field names (e.g. "FriendlyName") to include + // in API requests with the JSON null value. By default, fields with + // empty values are omitted from API requests. However, any field with + // an empty value appearing in NullFields will be sent to the server as + // null. It is an error if a field in this list has a non-empty value. + // This may be used to include null fields in Patch requests. + NullFields []string `json:"-"` +} + +func (s *ProjectListProjects) MarshalJSON() ([]byte, error) { + type noMethod ProjectListProjects + raw := noMethod(*s) + return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) +} + +type ProjectReference struct { + // ProjectId: [Required] ID of the project. Can be either the numeric ID + // or the assigned ID of the project. + ProjectId string `json:"projectId,omitempty"` + + // ForceSendFields is a list of field names (e.g. "ProjectId") to + // unconditionally include in API requests. By default, fields with + // empty values are omitted from API requests. However, any non-pointer, + // non-interface field appearing in ForceSendFields will be sent to the + // server regardless of whether the field is empty or not. This may be + // used to include empty fields in Patch requests. + ForceSendFields []string `json:"-"` + + // NullFields is a list of field names (e.g. "ProjectId") to include in + // API requests with the JSON null value. By default, fields with empty + // values are omitted from API requests. However, any field with an + // empty value appearing in NullFields will be sent to the server as + // null. It is an error if a field in this list has a non-empty value. + // This may be used to include null fields in Patch requests. + NullFields []string `json:"-"` +} + +func (s *ProjectReference) MarshalJSON() ([]byte, error) { + type noMethod ProjectReference + raw := noMethod(*s) + return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) +} + +type QueryParameter struct { + // Name: [Optional] If unset, this is a positional parameter. Otherwise, + // should be unique within a query. + Name string `json:"name,omitempty"` + + // ParameterType: [Required] The type of this parameter. + ParameterType *QueryParameterType `json:"parameterType,omitempty"` + + // ParameterValue: [Required] The value of this parameter. + ParameterValue *QueryParameterValue `json:"parameterValue,omitempty"` + + // ForceSendFields is a list of field names (e.g. "Name") to + // unconditionally include in API requests. By default, fields with + // empty values are omitted from API requests. However, any non-pointer, + // non-interface field appearing in ForceSendFields will be sent to the + // server regardless of whether the field is empty or not. This may be + // used to include empty fields in Patch requests. + ForceSendFields []string `json:"-"` + + // NullFields is a list of field names (e.g. "Name") to include in API + // requests with the JSON null value. By default, fields with empty + // values are omitted from API requests. However, any field with an + // empty value appearing in NullFields will be sent to the server as + // null. It is an error if a field in this list has a non-empty value. + // This may be used to include null fields in Patch requests. + NullFields []string `json:"-"` +} + +func (s *QueryParameter) MarshalJSON() ([]byte, error) { + type noMethod QueryParameter + raw := noMethod(*s) + return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) +} + +type QueryParameterType struct { + // ArrayType: [Optional] The type of the array's elements, if this is an + // array. + ArrayType *QueryParameterType `json:"arrayType,omitempty"` + + // StructTypes: [Optional] The types of the fields of this struct, in + // order, if this is a struct. + StructTypes []*QueryParameterTypeStructTypes `json:"structTypes,omitempty"` + + // Type: [Required] The top level type of this field. + Type string `json:"type,omitempty"` + + // ForceSendFields is a list of field names (e.g. "ArrayType") to + // unconditionally include in API requests. By default, fields with + // empty values are omitted from API requests. However, any non-pointer, + // non-interface field appearing in ForceSendFields will be sent to the + // server regardless of whether the field is empty or not. This may be + // used to include empty fields in Patch requests. + ForceSendFields []string `json:"-"` + + // NullFields is a list of field names (e.g. "ArrayType") to include in + // API requests with the JSON null value. By default, fields with empty + // values are omitted from API requests. However, any field with an + // empty value appearing in NullFields will be sent to the server as + // null. It is an error if a field in this list has a non-empty value. + // This may be used to include null fields in Patch requests. + NullFields []string `json:"-"` +} + +func (s *QueryParameterType) MarshalJSON() ([]byte, error) { + type noMethod QueryParameterType + raw := noMethod(*s) + return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) +} + +type QueryParameterTypeStructTypes struct { + // Description: [Optional] Human-oriented description of the field. + Description string `json:"description,omitempty"` + + // Name: [Optional] The name of this field. + Name string `json:"name,omitempty"` + + // Type: [Required] The type of this field. + Type *QueryParameterType `json:"type,omitempty"` + + // ForceSendFields is a list of field names (e.g. "Description") to + // unconditionally include in API requests. By default, fields with + // empty values are omitted from API requests. However, any non-pointer, + // non-interface field appearing in ForceSendFields will be sent to the + // server regardless of whether the field is empty or not. This may be + // used to include empty fields in Patch requests. + ForceSendFields []string `json:"-"` + + // NullFields is a list of field names (e.g. "Description") to include + // in API requests with the JSON null value. By default, fields with + // empty values are omitted from API requests. However, any field with + // an empty value appearing in NullFields will be sent to the server as + // null. It is an error if a field in this list has a non-empty value. + // This may be used to include null fields in Patch requests. + NullFields []string `json:"-"` +} + +func (s *QueryParameterTypeStructTypes) MarshalJSON() ([]byte, error) { + type noMethod QueryParameterTypeStructTypes + raw := noMethod(*s) + return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) +} + +type QueryParameterValue struct { + // ArrayValues: [Optional] The array values, if this is an array type. + ArrayValues []*QueryParameterValue `json:"arrayValues,omitempty"` + + // StructValues: [Optional] The struct field values, in order of the + // struct type's declaration. + StructValues map[string]QueryParameterValue `json:"structValues,omitempty"` + + // Value: [Optional] The value of this value, if a simple scalar type. + Value string `json:"value,omitempty"` + + // ForceSendFields is a list of field names (e.g. "ArrayValues") to + // unconditionally include in API requests. By default, fields with + // empty values are omitted from API requests. However, any non-pointer, + // non-interface field appearing in ForceSendFields will be sent to the + // server regardless of whether the field is empty or not. This may be + // used to include empty fields in Patch requests. + ForceSendFields []string `json:"-"` + + // NullFields is a list of field names (e.g. "ArrayValues") to include + // in API requests with the JSON null value. By default, fields with + // empty values are omitted from API requests. However, any field with + // an empty value appearing in NullFields will be sent to the server as + // null. It is an error if a field in this list has a non-empty value. + // This may be used to include null fields in Patch requests. + NullFields []string `json:"-"` +} + +func (s *QueryParameterValue) MarshalJSON() ([]byte, error) { + type noMethod QueryParameterValue + raw := noMethod(*s) + return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) +} + +type QueryRequest struct { + // DefaultDataset: [Optional] Specifies the default datasetId and + // projectId to assume for any unqualified table names in the query. If + // not set, all table names in the query string must be qualified in the + // format 'datasetId.tableId'. + DefaultDataset *DatasetReference `json:"defaultDataset,omitempty"` + + // DryRun: [Optional] If set to true, BigQuery doesn't run the job. + // Instead, if the query is valid, BigQuery returns statistics about the + // job such as how many bytes would be processed. If the query is + // invalid, an error returns. The default value is false. + DryRun bool `json:"dryRun,omitempty"` + + // Kind: The resource type of the request. + Kind string `json:"kind,omitempty"` + + // MaxResults: [Optional] The maximum number of rows of data to return + // per page of results. Setting this flag to a small value such as 1000 + // and then paging through results might improve reliability when the + // query result set is large. In addition to this limit, responses are + // also limited to 10 MB. By default, there is no maximum row count, and + // only the byte limit applies. + MaxResults int64 `json:"maxResults,omitempty"` + + // ParameterMode: [Experimental] Standard SQL only. Set to POSITIONAL to + // use positional (?) query parameters or to NAMED to use named + // (@myparam) query parameters in this query. + ParameterMode string `json:"parameterMode,omitempty"` + + // PreserveNulls: [Deprecated] This property is deprecated. + PreserveNulls bool `json:"preserveNulls,omitempty"` + + // Query: [Required] A query string, following the BigQuery query + // syntax, of the query to execute. Example: "SELECT count(f1) FROM + // [myProjectId:myDatasetId.myTableId]". + Query string `json:"query,omitempty"` + + // QueryParameters: [Experimental] Query parameters for Standard SQL + // queries. + QueryParameters []*QueryParameter `json:"queryParameters,omitempty"` + + // TimeoutMs: [Optional] How long to wait for the query to complete, in + // milliseconds, before the request times out and returns. Note that + // this is only a timeout for the request, not the query. If the query + // takes longer to run than the timeout value, the call returns without + // any results and with the 'jobComplete' flag set to false. You can + // call GetQueryResults() to wait for the query to complete and read the + // results. The default value is 10000 milliseconds (10 seconds). + TimeoutMs int64 `json:"timeoutMs,omitempty"` + + // UseLegacySql: Specifies whether to use BigQuery's legacy SQL dialect + // for this query. The default value is true. If set to false, the query + // will use BigQuery's standard SQL: + // https://cloud.google.com/bigquery/sql-reference/ When useLegacySql is + // set to false, the values of allowLargeResults and flattenResults are + // ignored; query will be run as if allowLargeResults is true and + // flattenResults is false. + // + // Default: true + UseLegacySql *bool `json:"useLegacySql,omitempty"` + + // UseQueryCache: [Optional] Whether to look for the result in the query + // cache. The query cache is a best-effort cache that will be flushed + // whenever tables in the query are modified. The default value is true. + // + // Default: true + UseQueryCache *bool `json:"useQueryCache,omitempty"` + + // ForceSendFields is a list of field names (e.g. "DefaultDataset") to + // unconditionally include in API requests. By default, fields with + // empty values are omitted from API requests. However, any non-pointer, + // non-interface field appearing in ForceSendFields will be sent to the + // server regardless of whether the field is empty or not. This may be + // used to include empty fields in Patch requests. + ForceSendFields []string `json:"-"` + + // NullFields is a list of field names (e.g. "DefaultDataset") to + // include in API requests with the JSON null value. By default, fields + // with empty values are omitted from API requests. However, any field + // with an empty value appearing in NullFields will be sent to the + // server as null. It is an error if a field in this list has a + // non-empty value. This may be used to include null fields in Patch + // requests. + NullFields []string `json:"-"` +} + +func (s *QueryRequest) MarshalJSON() ([]byte, error) { + type noMethod QueryRequest + raw := noMethod(*s) + return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) +} + +type QueryResponse struct { + // CacheHit: Whether the query result was fetched from the query cache. + CacheHit bool `json:"cacheHit,omitempty"` + + // Errors: [Output-only] All errors and warnings encountered during the + // running of the job. Errors here do not necessarily mean that the job + // has completed or was unsuccessful. + Errors []*ErrorProto `json:"errors,omitempty"` + + // JobComplete: Whether the query has completed or not. If rows or + // totalRows are present, this will always be true. If this is false, + // totalRows will not be available. + JobComplete bool `json:"jobComplete,omitempty"` + + // JobReference: Reference to the Job that was created to run the query. + // This field will be present even if the original request timed out, in + // which case GetQueryResults can be used to read the results once the + // query has completed. Since this API only returns the first page of + // results, subsequent pages can be fetched via the same mechanism + // (GetQueryResults). + JobReference *JobReference `json:"jobReference,omitempty"` + + // Kind: The resource type. + Kind string `json:"kind,omitempty"` + + // NumDmlAffectedRows: [Output-only, Experimental] The number of rows + // affected by a DML statement. Present only for DML statements INSERT, + // UPDATE or DELETE. + NumDmlAffectedRows int64 `json:"numDmlAffectedRows,omitempty,string"` + + // PageToken: A token used for paging results. + PageToken string `json:"pageToken,omitempty"` + + // Rows: An object with as many results as can be contained within the + // maximum permitted reply size. To get any additional rows, you can + // call GetQueryResults and specify the jobReference returned above. + Rows []*TableRow `json:"rows,omitempty"` + + // Schema: The schema of the results. Present only when the query + // completes successfully. + Schema *TableSchema `json:"schema,omitempty"` + + // TotalBytesProcessed: The total number of bytes processed for this + // query. If this query was a dry run, this is the number of bytes that + // would be processed if the query were run. + TotalBytesProcessed int64 `json:"totalBytesProcessed,omitempty,string"` + + // TotalRows: The total number of rows in the complete query result set, + // which can be more than the number of rows in this single page of + // results. + TotalRows uint64 `json:"totalRows,omitempty,string"` + + // ServerResponse contains the HTTP response code and headers from the + // server. + googleapi.ServerResponse `json:"-"` + + // ForceSendFields is a list of field names (e.g. "CacheHit") to + // unconditionally include in API requests. By default, fields with + // empty values are omitted from API requests. However, any non-pointer, + // non-interface field appearing in ForceSendFields will be sent to the + // server regardless of whether the field is empty or not. This may be + // used to include empty fields in Patch requests. + ForceSendFields []string `json:"-"` + + // NullFields is a list of field names (e.g. "CacheHit") to include in + // API requests with the JSON null value. By default, fields with empty + // values are omitted from API requests. However, any field with an + // empty value appearing in NullFields will be sent to the server as + // null. It is an error if a field in this list has a non-empty value. + // This may be used to include null fields in Patch requests. + NullFields []string `json:"-"` +} + +func (s *QueryResponse) MarshalJSON() ([]byte, error) { + type noMethod QueryResponse + raw := noMethod(*s) + return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) +} + +type Streamingbuffer struct { + // EstimatedBytes: [Output-only] A lower-bound estimate of the number of + // bytes currently in the streaming buffer. + EstimatedBytes uint64 `json:"estimatedBytes,omitempty,string"` + + // EstimatedRows: [Output-only] A lower-bound estimate of the number of + // rows currently in the streaming buffer. + EstimatedRows uint64 `json:"estimatedRows,omitempty,string"` + + // OldestEntryTime: [Output-only] Contains the timestamp of the oldest + // entry in the streaming buffer, in milliseconds since the epoch, if + // the streaming buffer is available. + OldestEntryTime uint64 `json:"oldestEntryTime,omitempty,string"` + + // ForceSendFields is a list of field names (e.g. "EstimatedBytes") to + // unconditionally include in API requests. By default, fields with + // empty values are omitted from API requests. However, any non-pointer, + // non-interface field appearing in ForceSendFields will be sent to the + // server regardless of whether the field is empty or not. This may be + // used to include empty fields in Patch requests. + ForceSendFields []string `json:"-"` + + // NullFields is a list of field names (e.g. "EstimatedBytes") to + // include in API requests with the JSON null value. By default, fields + // with empty values are omitted from API requests. However, any field + // with an empty value appearing in NullFields will be sent to the + // server as null. It is an error if a field in this list has a + // non-empty value. This may be used to include null fields in Patch + // requests. + NullFields []string `json:"-"` +} + +func (s *Streamingbuffer) MarshalJSON() ([]byte, error) { + type noMethod Streamingbuffer + raw := noMethod(*s) + return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) +} + +type Table struct { + // CreationTime: [Output-only] The time when this table was created, in + // milliseconds since the epoch. + CreationTime int64 `json:"creationTime,omitempty,string"` + + // Description: [Optional] A user-friendly description of this table. + Description string `json:"description,omitempty"` + + // Etag: [Output-only] A hash of this resource. + Etag string `json:"etag,omitempty"` + + // ExpirationTime: [Optional] The time when this table expires, in + // milliseconds since the epoch. If not present, the table will persist + // indefinitely. Expired tables will be deleted and their storage + // reclaimed. + ExpirationTime int64 `json:"expirationTime,omitempty,string"` + + // ExternalDataConfiguration: [Optional] Describes the data format, + // location, and other properties of a table stored outside of BigQuery. + // By defining these properties, the data source can then be queried as + // if it were a standard BigQuery table. + ExternalDataConfiguration *ExternalDataConfiguration `json:"externalDataConfiguration,omitempty"` + + // FriendlyName: [Optional] A descriptive name for this table. + FriendlyName string `json:"friendlyName,omitempty"` + + // Id: [Output-only] An opaque ID uniquely identifying the table. + Id string `json:"id,omitempty"` + + // Kind: [Output-only] The type of the resource. + Kind string `json:"kind,omitempty"` + + // Labels: [Experimental] The labels associated with this table. You can + // use these to organize and group your tables. Label keys and values + // can be no longer than 63 characters, can only contain lowercase + // letters, numeric characters, underscores and dashes. International + // characters are allowed. Label values are optional. Label keys must + // start with a letter and each label in the list must have a different + // key. + Labels map[string]string `json:"labels,omitempty"` + + // LastModifiedTime: [Output-only] The time when this table was last + // modified, in milliseconds since the epoch. + LastModifiedTime uint64 `json:"lastModifiedTime,omitempty,string"` + + // Location: [Output-only] The geographic location where the table + // resides. This value is inherited from the dataset. + Location string `json:"location,omitempty"` + + // NumBytes: [Output-only] The size of this table in bytes, excluding + // any data in the streaming buffer. + NumBytes int64 `json:"numBytes,omitempty,string"` + + // NumLongTermBytes: [Output-only] The number of bytes in the table that + // are considered "long-term storage". + NumLongTermBytes int64 `json:"numLongTermBytes,omitempty,string"` + + // NumRows: [Output-only] The number of rows of data in this table, + // excluding any data in the streaming buffer. + NumRows uint64 `json:"numRows,omitempty,string"` + + // Schema: [Optional] Describes the schema of this table. + Schema *TableSchema `json:"schema,omitempty"` + + // SelfLink: [Output-only] A URL that can be used to access this + // resource again. + SelfLink string `json:"selfLink,omitempty"` + + // StreamingBuffer: [Output-only] Contains information regarding this + // table's streaming buffer, if one is present. This field will be + // absent if the table is not being streamed to or if there is no data + // in the streaming buffer. + StreamingBuffer *Streamingbuffer `json:"streamingBuffer,omitempty"` + + // TableReference: [Required] Reference describing the ID of this table. + TableReference *TableReference `json:"tableReference,omitempty"` + + // TimePartitioning: [Experimental] If specified, configures time-based + // partitioning for this table. + TimePartitioning *TimePartitioning `json:"timePartitioning,omitempty"` + + // Type: [Output-only] Describes the table type. The following values + // are supported: TABLE: A normal BigQuery table. VIEW: A virtual table + // defined by a SQL query. EXTERNAL: A table that references data stored + // in an external storage system, such as Google Cloud Storage. The + // default value is TABLE. + Type string `json:"type,omitempty"` + + // View: [Optional] The view definition. + View *ViewDefinition `json:"view,omitempty"` + + // ServerResponse contains the HTTP response code and headers from the + // server. + googleapi.ServerResponse `json:"-"` + + // ForceSendFields is a list of field names (e.g. "CreationTime") to + // unconditionally include in API requests. By default, fields with + // empty values are omitted from API requests. However, any non-pointer, + // non-interface field appearing in ForceSendFields will be sent to the + // server regardless of whether the field is empty or not. This may be + // used to include empty fields in Patch requests. + ForceSendFields []string `json:"-"` + + // NullFields is a list of field names (e.g. "CreationTime") to include + // in API requests with the JSON null value. By default, fields with + // empty values are omitted from API requests. However, any field with + // an empty value appearing in NullFields will be sent to the server as + // null. It is an error if a field in this list has a non-empty value. + // This may be used to include null fields in Patch requests. + NullFields []string `json:"-"` +} + +func (s *Table) MarshalJSON() ([]byte, error) { + type noMethod Table + raw := noMethod(*s) + return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) +} + +type TableCell struct { + V interface{} `json:"v,omitempty"` + + // ForceSendFields is a list of field names (e.g. "V") to + // unconditionally include in API requests. By default, fields with + // empty values are omitted from API requests. However, any non-pointer, + // non-interface field appearing in ForceSendFields will be sent to the + // server regardless of whether the field is empty or not. This may be + // used to include empty fields in Patch requests. + ForceSendFields []string `json:"-"` + + // NullFields is a list of field names (e.g. "V") to include in API + // requests with the JSON null value. By default, fields with empty + // values are omitted from API requests. However, any field with an + // empty value appearing in NullFields will be sent to the server as + // null. It is an error if a field in this list has a non-empty value. + // This may be used to include null fields in Patch requests. + NullFields []string `json:"-"` +} + +func (s *TableCell) MarshalJSON() ([]byte, error) { + type noMethod TableCell + raw := noMethod(*s) + return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) +} + +type TableDataInsertAllRequest struct { + // IgnoreUnknownValues: [Optional] Accept rows that contain values that + // do not match the schema. The unknown values are ignored. Default is + // false, which treats unknown values as errors. + IgnoreUnknownValues bool `json:"ignoreUnknownValues,omitempty"` + + // Kind: The resource type of the response. + Kind string `json:"kind,omitempty"` + + // Rows: The rows to insert. + Rows []*TableDataInsertAllRequestRows `json:"rows,omitempty"` + + // SkipInvalidRows: [Optional] Insert all valid rows of a request, even + // if invalid rows exist. The default value is false, which causes the + // entire request to fail if any invalid rows exist. + SkipInvalidRows bool `json:"skipInvalidRows,omitempty"` + + // TemplateSuffix: [Experimental] If specified, treats the destination + // table as a base template, and inserts the rows into an instance table + // named "{destination}{templateSuffix}". BigQuery will manage creation + // of the instance table, using the schema of the base template table. + // See + // https://cloud.google.com/bigquery/streaming-data-into-bigquery#template-tables for considerations when working with templates + // tables. + TemplateSuffix string `json:"templateSuffix,omitempty"` + + // ForceSendFields is a list of field names (e.g. "IgnoreUnknownValues") + // to unconditionally include in API requests. By default, fields with + // empty values are omitted from API requests. However, any non-pointer, + // non-interface field appearing in ForceSendFields will be sent to the + // server regardless of whether the field is empty or not. This may be + // used to include empty fields in Patch requests. + ForceSendFields []string `json:"-"` + + // NullFields is a list of field names (e.g. "IgnoreUnknownValues") to + // include in API requests with the JSON null value. By default, fields + // with empty values are omitted from API requests. However, any field + // with an empty value appearing in NullFields will be sent to the + // server as null. It is an error if a field in this list has a + // non-empty value. This may be used to include null fields in Patch + // requests. + NullFields []string `json:"-"` +} + +func (s *TableDataInsertAllRequest) MarshalJSON() ([]byte, error) { + type noMethod TableDataInsertAllRequest + raw := noMethod(*s) + return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) +} + +type TableDataInsertAllRequestRows struct { + // InsertId: [Optional] A unique ID for each row. BigQuery uses this + // property to detect duplicate insertion requests on a best-effort + // basis. + InsertId string `json:"insertId,omitempty"` + + // Json: [Required] A JSON object that contains a row of data. The + // object's properties and values must match the destination table's + // schema. + Json map[string]JsonValue `json:"json,omitempty"` + + // ForceSendFields is a list of field names (e.g. "InsertId") to + // unconditionally include in API requests. By default, fields with + // empty values are omitted from API requests. However, any non-pointer, + // non-interface field appearing in ForceSendFields will be sent to the + // server regardless of whether the field is empty or not. This may be + // used to include empty fields in Patch requests. + ForceSendFields []string `json:"-"` + + // NullFields is a list of field names (e.g. "InsertId") to include in + // API requests with the JSON null value. By default, fields with empty + // values are omitted from API requests. However, any field with an + // empty value appearing in NullFields will be sent to the server as + // null. It is an error if a field in this list has a non-empty value. + // This may be used to include null fields in Patch requests. + NullFields []string `json:"-"` +} + +func (s *TableDataInsertAllRequestRows) MarshalJSON() ([]byte, error) { + type noMethod TableDataInsertAllRequestRows + raw := noMethod(*s) + return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) +} + +type TableDataInsertAllResponse struct { + // InsertErrors: An array of errors for rows that were not inserted. + InsertErrors []*TableDataInsertAllResponseInsertErrors `json:"insertErrors,omitempty"` + + // Kind: The resource type of the response. + Kind string `json:"kind,omitempty"` + + // ServerResponse contains the HTTP response code and headers from the + // server. + googleapi.ServerResponse `json:"-"` + + // ForceSendFields is a list of field names (e.g. "InsertErrors") to + // unconditionally include in API requests. By default, fields with + // empty values are omitted from API requests. However, any non-pointer, + // non-interface field appearing in ForceSendFields will be sent to the + // server regardless of whether the field is empty or not. This may be + // used to include empty fields in Patch requests. + ForceSendFields []string `json:"-"` + + // NullFields is a list of field names (e.g. "InsertErrors") to include + // in API requests with the JSON null value. By default, fields with + // empty values are omitted from API requests. However, any field with + // an empty value appearing in NullFields will be sent to the server as + // null. It is an error if a field in this list has a non-empty value. + // This may be used to include null fields in Patch requests. + NullFields []string `json:"-"` +} + +func (s *TableDataInsertAllResponse) MarshalJSON() ([]byte, error) { + type noMethod TableDataInsertAllResponse + raw := noMethod(*s) + return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) +} + +type TableDataInsertAllResponseInsertErrors struct { + // Errors: Error information for the row indicated by the index + // property. + Errors []*ErrorProto `json:"errors,omitempty"` + + // Index: The index of the row that error applies to. + Index int64 `json:"index,omitempty"` + + // ForceSendFields is a list of field names (e.g. "Errors") to + // unconditionally include in API requests. By default, fields with + // empty values are omitted from API requests. However, any non-pointer, + // non-interface field appearing in ForceSendFields will be sent to the + // server regardless of whether the field is empty or not. This may be + // used to include empty fields in Patch requests. + ForceSendFields []string `json:"-"` + + // NullFields is a list of field names (e.g. "Errors") to include in API + // requests with the JSON null value. By default, fields with empty + // values are omitted from API requests. However, any field with an + // empty value appearing in NullFields will be sent to the server as + // null. It is an error if a field in this list has a non-empty value. + // This may be used to include null fields in Patch requests. + NullFields []string `json:"-"` +} + +func (s *TableDataInsertAllResponseInsertErrors) MarshalJSON() ([]byte, error) { + type noMethod TableDataInsertAllResponseInsertErrors + raw := noMethod(*s) + return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) +} + +type TableDataList struct { + // Etag: A hash of this page of results. + Etag string `json:"etag,omitempty"` + + // Kind: The resource type of the response. + Kind string `json:"kind,omitempty"` + + // PageToken: A token used for paging results. Providing this token + // instead of the startIndex parameter can help you retrieve stable + // results when an underlying table is changing. + PageToken string `json:"pageToken,omitempty"` + + // Rows: Rows of results. + Rows []*TableRow `json:"rows,omitempty"` + + // TotalRows: The total number of rows in the complete table. + TotalRows int64 `json:"totalRows,omitempty,string"` + + // ServerResponse contains the HTTP response code and headers from the + // server. + googleapi.ServerResponse `json:"-"` + + // ForceSendFields is a list of field names (e.g. "Etag") to + // unconditionally include in API requests. By default, fields with + // empty values are omitted from API requests. However, any non-pointer, + // non-interface field appearing in ForceSendFields will be sent to the + // server regardless of whether the field is empty or not. This may be + // used to include empty fields in Patch requests. + ForceSendFields []string `json:"-"` + + // NullFields is a list of field names (e.g. "Etag") to include in API + // requests with the JSON null value. By default, fields with empty + // values are omitted from API requests. However, any field with an + // empty value appearing in NullFields will be sent to the server as + // null. It is an error if a field in this list has a non-empty value. + // This may be used to include null fields in Patch requests. + NullFields []string `json:"-"` +} + +func (s *TableDataList) MarshalJSON() ([]byte, error) { + type noMethod TableDataList + raw := noMethod(*s) + return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) +} + +type TableFieldSchema struct { + // Description: [Optional] The field description. The maximum length is + // 16K characters. + Description string `json:"description,omitempty"` + + // Fields: [Optional] Describes the nested schema fields if the type + // property is set to RECORD. + Fields []*TableFieldSchema `json:"fields,omitempty"` + + // Mode: [Optional] The field mode. Possible values include NULLABLE, + // REQUIRED and REPEATED. The default value is NULLABLE. + Mode string `json:"mode,omitempty"` + + // Name: [Required] The field name. The name must contain only letters + // (a-z, A-Z), numbers (0-9), or underscores (_), and must start with a + // letter or underscore. The maximum length is 128 characters. + Name string `json:"name,omitempty"` + + // Type: [Required] The field data type. Possible values include STRING, + // BYTES, INTEGER, INT64 (same as INTEGER), FLOAT, FLOAT64 (same as + // FLOAT), BOOLEAN, BOOL (same as BOOLEAN), TIMESTAMP, DATE, TIME, + // DATETIME, RECORD (where RECORD indicates that the field contains a + // nested schema) or STRUCT (same as RECORD). + Type string `json:"type,omitempty"` + + // ForceSendFields is a list of field names (e.g. "Description") to + // unconditionally include in API requests. By default, fields with + // empty values are omitted from API requests. However, any non-pointer, + // non-interface field appearing in ForceSendFields will be sent to the + // server regardless of whether the field is empty or not. This may be + // used to include empty fields in Patch requests. + ForceSendFields []string `json:"-"` + + // NullFields is a list of field names (e.g. "Description") to include + // in API requests with the JSON null value. By default, fields with + // empty values are omitted from API requests. However, any field with + // an empty value appearing in NullFields will be sent to the server as + // null. It is an error if a field in this list has a non-empty value. + // This may be used to include null fields in Patch requests. + NullFields []string `json:"-"` +} + +func (s *TableFieldSchema) MarshalJSON() ([]byte, error) { + type noMethod TableFieldSchema + raw := noMethod(*s) + return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) +} + +type TableList struct { + // Etag: A hash of this page of results. + Etag string `json:"etag,omitempty"` + + // Kind: The type of list. + Kind string `json:"kind,omitempty"` + + // NextPageToken: A token to request the next page of results. + NextPageToken string `json:"nextPageToken,omitempty"` + + // Tables: Tables in the requested dataset. + Tables []*TableListTables `json:"tables,omitempty"` + + // TotalItems: The total number of tables in the dataset. + TotalItems int64 `json:"totalItems,omitempty"` + + // ServerResponse contains the HTTP response code and headers from the + // server. + googleapi.ServerResponse `json:"-"` + + // ForceSendFields is a list of field names (e.g. "Etag") to + // unconditionally include in API requests. By default, fields with + // empty values are omitted from API requests. However, any non-pointer, + // non-interface field appearing in ForceSendFields will be sent to the + // server regardless of whether the field is empty or not. This may be + // used to include empty fields in Patch requests. + ForceSendFields []string `json:"-"` + + // NullFields is a list of field names (e.g. "Etag") to include in API + // requests with the JSON null value. By default, fields with empty + // values are omitted from API requests. However, any field with an + // empty value appearing in NullFields will be sent to the server as + // null. It is an error if a field in this list has a non-empty value. + // This may be used to include null fields in Patch requests. + NullFields []string `json:"-"` +} + +func (s *TableList) MarshalJSON() ([]byte, error) { + type noMethod TableList + raw := noMethod(*s) + return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) +} + +type TableListTables struct { + // FriendlyName: The user-friendly name for this table. + FriendlyName string `json:"friendlyName,omitempty"` + + // Id: An opaque ID of the table + Id string `json:"id,omitempty"` + + // Kind: The resource type. + Kind string `json:"kind,omitempty"` + + // Labels: [Experimental] The labels associated with this table. You can + // use these to organize and group your tables. + Labels map[string]string `json:"labels,omitempty"` + + // TableReference: A reference uniquely identifying the table. + TableReference *TableReference `json:"tableReference,omitempty"` + + // Type: The type of table. Possible values are: TABLE, VIEW. + Type string `json:"type,omitempty"` + + // View: Additional details for a view. + View *TableListTablesView `json:"view,omitempty"` + + // ForceSendFields is a list of field names (e.g. "FriendlyName") to + // unconditionally include in API requests. By default, fields with + // empty values are omitted from API requests. However, any non-pointer, + // non-interface field appearing in ForceSendFields will be sent to the + // server regardless of whether the field is empty or not. This may be + // used to include empty fields in Patch requests. + ForceSendFields []string `json:"-"` + + // NullFields is a list of field names (e.g. "FriendlyName") to include + // in API requests with the JSON null value. By default, fields with + // empty values are omitted from API requests. However, any field with + // an empty value appearing in NullFields will be sent to the server as + // null. It is an error if a field in this list has a non-empty value. + // This may be used to include null fields in Patch requests. + NullFields []string `json:"-"` +} + +func (s *TableListTables) MarshalJSON() ([]byte, error) { + type noMethod TableListTables + raw := noMethod(*s) + return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) +} + +// TableListTablesView: Additional details for a view. +type TableListTablesView struct { + // UseLegacySql: True if view is defined in legacy SQL dialect, false if + // in standard SQL. + UseLegacySql bool `json:"useLegacySql,omitempty"` + + // ForceSendFields is a list of field names (e.g. "UseLegacySql") to + // unconditionally include in API requests. By default, fields with + // empty values are omitted from API requests. However, any non-pointer, + // non-interface field appearing in ForceSendFields will be sent to the + // server regardless of whether the field is empty or not. This may be + // used to include empty fields in Patch requests. + ForceSendFields []string `json:"-"` + + // NullFields is a list of field names (e.g. "UseLegacySql") to include + // in API requests with the JSON null value. By default, fields with + // empty values are omitted from API requests. However, any field with + // an empty value appearing in NullFields will be sent to the server as + // null. It is an error if a field in this list has a non-empty value. + // This may be used to include null fields in Patch requests. + NullFields []string `json:"-"` +} + +func (s *TableListTablesView) MarshalJSON() ([]byte, error) { + type noMethod TableListTablesView + raw := noMethod(*s) + return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) +} + +type TableReference struct { + // DatasetId: [Required] The ID of the dataset containing this table. + DatasetId string `json:"datasetId,omitempty"` + + // ProjectId: [Required] The ID of the project containing this table. + ProjectId string `json:"projectId,omitempty"` + + // TableId: [Required] The ID of the table. The ID must contain only + // letters (a-z, A-Z), numbers (0-9), or underscores (_). The maximum + // length is 1,024 characters. + TableId string `json:"tableId,omitempty"` + + // ForceSendFields is a list of field names (e.g. "DatasetId") to + // unconditionally include in API requests. By default, fields with + // empty values are omitted from API requests. However, any non-pointer, + // non-interface field appearing in ForceSendFields will be sent to the + // server regardless of whether the field is empty or not. This may be + // used to include empty fields in Patch requests. + ForceSendFields []string `json:"-"` + + // NullFields is a list of field names (e.g. "DatasetId") to include in + // API requests with the JSON null value. By default, fields with empty + // values are omitted from API requests. However, any field with an + // empty value appearing in NullFields will be sent to the server as + // null. It is an error if a field in this list has a non-empty value. + // This may be used to include null fields in Patch requests. + NullFields []string `json:"-"` +} + +func (s *TableReference) MarshalJSON() ([]byte, error) { + type noMethod TableReference + raw := noMethod(*s) + return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) +} + +type TableRow struct { + // F: Represents a single row in the result set, consisting of one or + // more fields. + F []*TableCell `json:"f,omitempty"` + + // ForceSendFields is a list of field names (e.g. "F") to + // unconditionally include in API requests. By default, fields with + // empty values are omitted from API requests. However, any non-pointer, + // non-interface field appearing in ForceSendFields will be sent to the + // server regardless of whether the field is empty or not. This may be + // used to include empty fields in Patch requests. + ForceSendFields []string `json:"-"` + + // NullFields is a list of field names (e.g. "F") to include in API + // requests with the JSON null value. By default, fields with empty + // values are omitted from API requests. However, any field with an + // empty value appearing in NullFields will be sent to the server as + // null. It is an error if a field in this list has a non-empty value. + // This may be used to include null fields in Patch requests. + NullFields []string `json:"-"` +} + +func (s *TableRow) MarshalJSON() ([]byte, error) { + type noMethod TableRow + raw := noMethod(*s) + return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) +} + +type TableSchema struct { + // Fields: Describes the fields in a table. + Fields []*TableFieldSchema `json:"fields,omitempty"` + + // ForceSendFields is a list of field names (e.g. "Fields") to + // unconditionally include in API requests. By default, fields with + // empty values are omitted from API requests. However, any non-pointer, + // non-interface field appearing in ForceSendFields will be sent to the + // server regardless of whether the field is empty or not. This may be + // used to include empty fields in Patch requests. + ForceSendFields []string `json:"-"` + + // NullFields is a list of field names (e.g. "Fields") to include in API + // requests with the JSON null value. By default, fields with empty + // values are omitted from API requests. However, any field with an + // empty value appearing in NullFields will be sent to the server as + // null. It is an error if a field in this list has a non-empty value. + // This may be used to include null fields in Patch requests. + NullFields []string `json:"-"` +} + +func (s *TableSchema) MarshalJSON() ([]byte, error) { + type noMethod TableSchema + raw := noMethod(*s) + return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) +} + +type TimePartitioning struct { + // ExpirationMs: [Optional] Number of milliseconds for which to keep the + // storage for a partition. + ExpirationMs int64 `json:"expirationMs,omitempty,string"` + + // Type: [Required] The only type supported is DAY, which will generate + // one partition per day based on data loading time. + Type string `json:"type,omitempty"` + + // ForceSendFields is a list of field names (e.g. "ExpirationMs") to + // unconditionally include in API requests. By default, fields with + // empty values are omitted from API requests. However, any non-pointer, + // non-interface field appearing in ForceSendFields will be sent to the + // server regardless of whether the field is empty or not. This may be + // used to include empty fields in Patch requests. + ForceSendFields []string `json:"-"` + + // NullFields is a list of field names (e.g. "ExpirationMs") to include + // in API requests with the JSON null value. By default, fields with + // empty values are omitted from API requests. However, any field with + // an empty value appearing in NullFields will be sent to the server as + // null. It is an error if a field in this list has a non-empty value. + // This may be used to include null fields in Patch requests. + NullFields []string `json:"-"` +} + +func (s *TimePartitioning) MarshalJSON() ([]byte, error) { + type noMethod TimePartitioning + raw := noMethod(*s) + return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) +} + +type UserDefinedFunctionResource struct { + // InlineCode: [Pick one] An inline resource that contains code for a + // user-defined function (UDF). Providing a inline code resource is + // equivalent to providing a URI for a file containing the same code. + InlineCode string `json:"inlineCode,omitempty"` + + // ResourceUri: [Pick one] A code resource to load from a Google Cloud + // Storage URI (gs://bucket/path). + ResourceUri string `json:"resourceUri,omitempty"` + + // ForceSendFields is a list of field names (e.g. "InlineCode") to + // unconditionally include in API requests. By default, fields with + // empty values are omitted from API requests. However, any non-pointer, + // non-interface field appearing in ForceSendFields will be sent to the + // server regardless of whether the field is empty or not. This may be + // used to include empty fields in Patch requests. + ForceSendFields []string `json:"-"` + + // NullFields is a list of field names (e.g. "InlineCode") to include in + // API requests with the JSON null value. By default, fields with empty + // values are omitted from API requests. However, any field with an + // empty value appearing in NullFields will be sent to the server as + // null. It is an error if a field in this list has a non-empty value. + // This may be used to include null fields in Patch requests. + NullFields []string `json:"-"` +} + +func (s *UserDefinedFunctionResource) MarshalJSON() ([]byte, error) { + type noMethod UserDefinedFunctionResource + raw := noMethod(*s) + return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) +} + +type ViewDefinition struct { + // Query: [Required] A query that BigQuery executes when the view is + // referenced. + Query string `json:"query,omitempty"` + + // UseLegacySql: Specifies whether to use BigQuery's legacy SQL for this + // view. The default value is true. If set to false, the view will use + // BigQuery's standard SQL: + // https://cloud.google.com/bigquery/sql-reference/ Queries and views + // that reference this view must use the same flag value. + UseLegacySql bool `json:"useLegacySql,omitempty"` + + // UserDefinedFunctionResources: [Experimental] Describes user-defined + // function resources used in the query. + UserDefinedFunctionResources []*UserDefinedFunctionResource `json:"userDefinedFunctionResources,omitempty"` + + // ForceSendFields is a list of field names (e.g. "Query") to + // unconditionally include in API requests. By default, fields with + // empty values are omitted from API requests. However, any non-pointer, + // non-interface field appearing in ForceSendFields will be sent to the + // server regardless of whether the field is empty or not. This may be + // used to include empty fields in Patch requests. + ForceSendFields []string `json:"-"` + + // NullFields is a list of field names (e.g. "Query") to include in API + // requests with the JSON null value. By default, fields with empty + // values are omitted from API requests. However, any field with an + // empty value appearing in NullFields will be sent to the server as + // null. It is an error if a field in this list has a non-empty value. + // This may be used to include null fields in Patch requests. + NullFields []string `json:"-"` +} + +func (s *ViewDefinition) MarshalJSON() ([]byte, error) { + type noMethod ViewDefinition + raw := noMethod(*s) + return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) +} + +// method id "bigquery.datasets.delete": + +type DatasetsDeleteCall struct { + s *Service + projectId string + datasetId string + urlParams_ gensupport.URLParams + ctx_ context.Context + header_ http.Header +} + +// Delete: Deletes the dataset specified by the datasetId value. Before +// you can delete a dataset, you must delete all its tables, either +// manually or by specifying deleteContents. Immediately after deletion, +// you can create another dataset with the same name. +func (r *DatasetsService) Delete(projectId string, datasetId string) *DatasetsDeleteCall { + c := &DatasetsDeleteCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.projectId = projectId + c.datasetId = datasetId + return c +} + +// DeleteContents sets the optional parameter "deleteContents": If True, +// delete all the tables in the dataset. If False and the dataset +// contains tables, the request will fail. Default is False +func (c *DatasetsDeleteCall) DeleteContents(deleteContents bool) *DatasetsDeleteCall { + c.urlParams_.Set("deleteContents", fmt.Sprint(deleteContents)) + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse +// for more information. +func (c *DatasetsDeleteCall) Fields(s ...googleapi.Field) *DatasetsDeleteCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// Context sets the context to be used in this call's Do method. Any +// pending HTTP request will be aborted if the provided context is +// canceled. +func (c *DatasetsDeleteCall) Context(ctx context.Context) *DatasetsDeleteCall { + c.ctx_ = ctx + return c +} + +// Header returns an http.Header that can be modified by the caller to +// add HTTP headers to the request. +func (c *DatasetsDeleteCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *DatasetsDeleteCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := make(http.Header) + for k, v := range c.header_ { + reqHeaders[k] = v + } + reqHeaders.Set("User-Agent", c.s.userAgent()) + reqHeaders.Set("x-goog-api-client", c.s.clientHeader()) + var body io.Reader = nil + c.urlParams_.Set("alt", alt) + urls := googleapi.ResolveRelative(c.s.BasePath, "projects/{projectId}/datasets/{datasetId}") + urls += "?" + c.urlParams_.Encode() + req, _ := http.NewRequest("DELETE", urls, body) + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "projectId": c.projectId, + "datasetId": c.datasetId, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "bigquery.datasets.delete" call. +func (c *DatasetsDeleteCall) Do(opts ...googleapi.CallOption) error { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if err != nil { + return err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return err + } + return nil + // { + // "description": "Deletes the dataset specified by the datasetId value. Before you can delete a dataset, you must delete all its tables, either manually or by specifying deleteContents. Immediately after deletion, you can create another dataset with the same name.", + // "httpMethod": "DELETE", + // "id": "bigquery.datasets.delete", + // "parameterOrder": [ + // "projectId", + // "datasetId" + // ], + // "parameters": { + // "datasetId": { + // "description": "Dataset ID of dataset being deleted", + // "location": "path", + // "required": true, + // "type": "string" + // }, + // "deleteContents": { + // "description": "If True, delete all the tables in the dataset. If False and the dataset contains tables, the request will fail. Default is False", + // "location": "query", + // "type": "boolean" + // }, + // "projectId": { + // "description": "Project ID of the dataset being deleted", + // "location": "path", + // "required": true, + // "type": "string" + // } + // }, + // "path": "projects/{projectId}/datasets/{datasetId}", + // "scopes": [ + // "https://www.googleapis.com/auth/bigquery", + // "https://www.googleapis.com/auth/cloud-platform" + // ] + // } + +} + +// method id "bigquery.datasets.get": + +type DatasetsGetCall struct { + s *Service + projectId string + datasetId string + urlParams_ gensupport.URLParams + ifNoneMatch_ string + ctx_ context.Context + header_ http.Header +} + +// Get: Returns the dataset specified by datasetID. +func (r *DatasetsService) Get(projectId string, datasetId string) *DatasetsGetCall { + c := &DatasetsGetCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.projectId = projectId + c.datasetId = datasetId + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse +// for more information. +func (c *DatasetsGetCall) Fields(s ...googleapi.Field) *DatasetsGetCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// IfNoneMatch sets the optional parameter which makes the operation +// fail if the object's ETag matches the given value. This is useful for +// getting updates only after the object has changed since the last +// request. Use googleapi.IsNotModified to check whether the response +// error from Do is the result of In-None-Match. +func (c *DatasetsGetCall) IfNoneMatch(entityTag string) *DatasetsGetCall { + c.ifNoneMatch_ = entityTag + return c +} + +// Context sets the context to be used in this call's Do method. Any +// pending HTTP request will be aborted if the provided context is +// canceled. +func (c *DatasetsGetCall) Context(ctx context.Context) *DatasetsGetCall { + c.ctx_ = ctx + return c +} + +// Header returns an http.Header that can be modified by the caller to +// add HTTP headers to the request. +func (c *DatasetsGetCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *DatasetsGetCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := make(http.Header) + for k, v := range c.header_ { + reqHeaders[k] = v + } + reqHeaders.Set("User-Agent", c.s.userAgent()) + reqHeaders.Set("x-goog-api-client", c.s.clientHeader()) + if c.ifNoneMatch_ != "" { + reqHeaders.Set("If-None-Match", c.ifNoneMatch_) + } + var body io.Reader = nil + c.urlParams_.Set("alt", alt) + urls := googleapi.ResolveRelative(c.s.BasePath, "projects/{projectId}/datasets/{datasetId}") + urls += "?" + c.urlParams_.Encode() + req, _ := http.NewRequest("GET", urls, body) + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "projectId": c.projectId, + "datasetId": c.datasetId, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "bigquery.datasets.get" call. +// Exactly one of *Dataset or error will be non-nil. Any non-2xx status +// code is an error. Response headers are in either +// *Dataset.ServerResponse.Header or (if a response was returned at all) +// in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to +// check whether the returned error was because http.StatusNotModified +// was returned. +func (c *DatasetsGetCall) Do(opts ...googleapi.CallOption) (*Dataset, error) { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if res != nil && res.StatusCode == http.StatusNotModified { + if res.Body != nil { + res.Body.Close() + } + return nil, &googleapi.Error{ + Code: res.StatusCode, + Header: res.Header, + } + } + if err != nil { + return nil, err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return nil, err + } + ret := &Dataset{ + ServerResponse: googleapi.ServerResponse{ + Header: res.Header, + HTTPStatusCode: res.StatusCode, + }, + } + target := &ret + if err := json.NewDecoder(res.Body).Decode(target); err != nil { + return nil, err + } + return ret, nil + // { + // "description": "Returns the dataset specified by datasetID.", + // "httpMethod": "GET", + // "id": "bigquery.datasets.get", + // "parameterOrder": [ + // "projectId", + // "datasetId" + // ], + // "parameters": { + // "datasetId": { + // "description": "Dataset ID of the requested dataset", + // "location": "path", + // "required": true, + // "type": "string" + // }, + // "projectId": { + // "description": "Project ID of the requested dataset", + // "location": "path", + // "required": true, + // "type": "string" + // } + // }, + // "path": "projects/{projectId}/datasets/{datasetId}", + // "response": { + // "$ref": "Dataset" + // }, + // "scopes": [ + // "https://www.googleapis.com/auth/bigquery", + // "https://www.googleapis.com/auth/cloud-platform", + // "https://www.googleapis.com/auth/cloud-platform.read-only" + // ] + // } + +} + +// method id "bigquery.datasets.insert": + +type DatasetsInsertCall struct { + s *Service + projectId string + dataset *Dataset + urlParams_ gensupport.URLParams + ctx_ context.Context + header_ http.Header +} + +// Insert: Creates a new empty dataset. +func (r *DatasetsService) Insert(projectId string, dataset *Dataset) *DatasetsInsertCall { + c := &DatasetsInsertCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.projectId = projectId + c.dataset = dataset + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse +// for more information. +func (c *DatasetsInsertCall) Fields(s ...googleapi.Field) *DatasetsInsertCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// Context sets the context to be used in this call's Do method. Any +// pending HTTP request will be aborted if the provided context is +// canceled. +func (c *DatasetsInsertCall) Context(ctx context.Context) *DatasetsInsertCall { + c.ctx_ = ctx + return c +} + +// Header returns an http.Header that can be modified by the caller to +// add HTTP headers to the request. +func (c *DatasetsInsertCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *DatasetsInsertCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := make(http.Header) + for k, v := range c.header_ { + reqHeaders[k] = v + } + reqHeaders.Set("User-Agent", c.s.userAgent()) + reqHeaders.Set("x-goog-api-client", c.s.clientHeader()) + var body io.Reader = nil + body, err := googleapi.WithoutDataWrapper.JSONReader(c.dataset) + if err != nil { + return nil, err + } + reqHeaders.Set("Content-Type", "application/json") + c.urlParams_.Set("alt", alt) + urls := googleapi.ResolveRelative(c.s.BasePath, "projects/{projectId}/datasets") + urls += "?" + c.urlParams_.Encode() + req, _ := http.NewRequest("POST", urls, body) + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "projectId": c.projectId, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "bigquery.datasets.insert" call. +// Exactly one of *Dataset or error will be non-nil. Any non-2xx status +// code is an error. Response headers are in either +// *Dataset.ServerResponse.Header or (if a response was returned at all) +// in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to +// check whether the returned error was because http.StatusNotModified +// was returned. +func (c *DatasetsInsertCall) Do(opts ...googleapi.CallOption) (*Dataset, error) { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if res != nil && res.StatusCode == http.StatusNotModified { + if res.Body != nil { + res.Body.Close() + } + return nil, &googleapi.Error{ + Code: res.StatusCode, + Header: res.Header, + } + } + if err != nil { + return nil, err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return nil, err + } + ret := &Dataset{ + ServerResponse: googleapi.ServerResponse{ + Header: res.Header, + HTTPStatusCode: res.StatusCode, + }, + } + target := &ret + if err := json.NewDecoder(res.Body).Decode(target); err != nil { + return nil, err + } + return ret, nil + // { + // "description": "Creates a new empty dataset.", + // "httpMethod": "POST", + // "id": "bigquery.datasets.insert", + // "parameterOrder": [ + // "projectId" + // ], + // "parameters": { + // "projectId": { + // "description": "Project ID of the new dataset", + // "location": "path", + // "required": true, + // "type": "string" + // } + // }, + // "path": "projects/{projectId}/datasets", + // "request": { + // "$ref": "Dataset" + // }, + // "response": { + // "$ref": "Dataset" + // }, + // "scopes": [ + // "https://www.googleapis.com/auth/bigquery", + // "https://www.googleapis.com/auth/cloud-platform" + // ] + // } + +} + +// method id "bigquery.datasets.list": + +type DatasetsListCall struct { + s *Service + projectId string + urlParams_ gensupport.URLParams + ifNoneMatch_ string + ctx_ context.Context + header_ http.Header +} + +// List: Lists all datasets in the specified project to which you have +// been granted the READER dataset role. +func (r *DatasetsService) List(projectId string) *DatasetsListCall { + c := &DatasetsListCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.projectId = projectId + return c +} + +// All sets the optional parameter "all": Whether to list all datasets, +// including hidden ones +func (c *DatasetsListCall) All(all bool) *DatasetsListCall { + c.urlParams_.Set("all", fmt.Sprint(all)) + return c +} + +// Filter sets the optional parameter "filter": An expression for +// filtering the results of the request by label. The syntax is +// "labels.[:]". Multiple filters can be ANDed together by +// connecting with a space. Example: "labels.department:receiving +// labels.active". See Filtering datasets using labels for details. +func (c *DatasetsListCall) Filter(filter string) *DatasetsListCall { + c.urlParams_.Set("filter", filter) + return c +} + +// MaxResults sets the optional parameter "maxResults": The maximum +// number of results to return +func (c *DatasetsListCall) MaxResults(maxResults int64) *DatasetsListCall { + c.urlParams_.Set("maxResults", fmt.Sprint(maxResults)) + return c +} + +// PageToken sets the optional parameter "pageToken": Page token, +// returned by a previous call, to request the next page of results +func (c *DatasetsListCall) PageToken(pageToken string) *DatasetsListCall { + c.urlParams_.Set("pageToken", pageToken) + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse +// for more information. +func (c *DatasetsListCall) Fields(s ...googleapi.Field) *DatasetsListCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// IfNoneMatch sets the optional parameter which makes the operation +// fail if the object's ETag matches the given value. This is useful for +// getting updates only after the object has changed since the last +// request. Use googleapi.IsNotModified to check whether the response +// error from Do is the result of In-None-Match. +func (c *DatasetsListCall) IfNoneMatch(entityTag string) *DatasetsListCall { + c.ifNoneMatch_ = entityTag + return c +} + +// Context sets the context to be used in this call's Do method. Any +// pending HTTP request will be aborted if the provided context is +// canceled. +func (c *DatasetsListCall) Context(ctx context.Context) *DatasetsListCall { + c.ctx_ = ctx + return c +} + +// Header returns an http.Header that can be modified by the caller to +// add HTTP headers to the request. +func (c *DatasetsListCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *DatasetsListCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := make(http.Header) + for k, v := range c.header_ { + reqHeaders[k] = v + } + reqHeaders.Set("User-Agent", c.s.userAgent()) + reqHeaders.Set("x-goog-api-client", c.s.clientHeader()) + if c.ifNoneMatch_ != "" { + reqHeaders.Set("If-None-Match", c.ifNoneMatch_) + } + var body io.Reader = nil + c.urlParams_.Set("alt", alt) + urls := googleapi.ResolveRelative(c.s.BasePath, "projects/{projectId}/datasets") + urls += "?" + c.urlParams_.Encode() + req, _ := http.NewRequest("GET", urls, body) + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "projectId": c.projectId, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "bigquery.datasets.list" call. +// Exactly one of *DatasetList or error will be non-nil. Any non-2xx +// status code is an error. Response headers are in either +// *DatasetList.ServerResponse.Header or (if a response was returned at +// all) in error.(*googleapi.Error).Header. Use googleapi.IsNotModified +// to check whether the returned error was because +// http.StatusNotModified was returned. +func (c *DatasetsListCall) Do(opts ...googleapi.CallOption) (*DatasetList, error) { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if res != nil && res.StatusCode == http.StatusNotModified { + if res.Body != nil { + res.Body.Close() + } + return nil, &googleapi.Error{ + Code: res.StatusCode, + Header: res.Header, + } + } + if err != nil { + return nil, err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return nil, err + } + ret := &DatasetList{ + ServerResponse: googleapi.ServerResponse{ + Header: res.Header, + HTTPStatusCode: res.StatusCode, + }, + } + target := &ret + if err := json.NewDecoder(res.Body).Decode(target); err != nil { + return nil, err + } + return ret, nil + // { + // "description": "Lists all datasets in the specified project to which you have been granted the READER dataset role.", + // "httpMethod": "GET", + // "id": "bigquery.datasets.list", + // "parameterOrder": [ + // "projectId" + // ], + // "parameters": { + // "all": { + // "description": "Whether to list all datasets, including hidden ones", + // "location": "query", + // "type": "boolean" + // }, + // "filter": { + // "description": "An expression for filtering the results of the request by label. The syntax is \"labels.\u003cname\u003e[:\u003cvalue\u003e]\". Multiple filters can be ANDed together by connecting with a space. Example: \"labels.department:receiving labels.active\". See Filtering datasets using labels for details.", + // "location": "query", + // "type": "string" + // }, + // "maxResults": { + // "description": "The maximum number of results to return", + // "format": "uint32", + // "location": "query", + // "type": "integer" + // }, + // "pageToken": { + // "description": "Page token, returned by a previous call, to request the next page of results", + // "location": "query", + // "type": "string" + // }, + // "projectId": { + // "description": "Project ID of the datasets to be listed", + // "location": "path", + // "required": true, + // "type": "string" + // } + // }, + // "path": "projects/{projectId}/datasets", + // "response": { + // "$ref": "DatasetList" + // }, + // "scopes": [ + // "https://www.googleapis.com/auth/bigquery", + // "https://www.googleapis.com/auth/cloud-platform", + // "https://www.googleapis.com/auth/cloud-platform.read-only" + // ] + // } + +} + +// Pages invokes f for each page of results. +// A non-nil error returned from f will halt the iteration. +// The provided context supersedes any context provided to the Context method. +func (c *DatasetsListCall) Pages(ctx context.Context, f func(*DatasetList) error) error { + c.ctx_ = ctx + defer c.PageToken(c.urlParams_.Get("pageToken")) // reset paging to original point + for { + x, err := c.Do() + if err != nil { + return err + } + if err := f(x); err != nil { + return err + } + if x.NextPageToken == "" { + return nil + } + c.PageToken(x.NextPageToken) + } +} + +// method id "bigquery.datasets.patch": + +type DatasetsPatchCall struct { + s *Service + projectId string + datasetId string + dataset *Dataset + urlParams_ gensupport.URLParams + ctx_ context.Context + header_ http.Header +} + +// Patch: Updates information in an existing dataset. The update method +// replaces the entire dataset resource, whereas the patch method only +// replaces fields that are provided in the submitted dataset resource. +// This method supports patch semantics. +func (r *DatasetsService) Patch(projectId string, datasetId string, dataset *Dataset) *DatasetsPatchCall { + c := &DatasetsPatchCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.projectId = projectId + c.datasetId = datasetId + c.dataset = dataset + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse +// for more information. +func (c *DatasetsPatchCall) Fields(s ...googleapi.Field) *DatasetsPatchCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// Context sets the context to be used in this call's Do method. Any +// pending HTTP request will be aborted if the provided context is +// canceled. +func (c *DatasetsPatchCall) Context(ctx context.Context) *DatasetsPatchCall { + c.ctx_ = ctx + return c +} + +// Header returns an http.Header that can be modified by the caller to +// add HTTP headers to the request. +func (c *DatasetsPatchCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *DatasetsPatchCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := make(http.Header) + for k, v := range c.header_ { + reqHeaders[k] = v + } + reqHeaders.Set("User-Agent", c.s.userAgent()) + reqHeaders.Set("x-goog-api-client", c.s.clientHeader()) + var body io.Reader = nil + body, err := googleapi.WithoutDataWrapper.JSONReader(c.dataset) + if err != nil { + return nil, err + } + reqHeaders.Set("Content-Type", "application/json") + c.urlParams_.Set("alt", alt) + urls := googleapi.ResolveRelative(c.s.BasePath, "projects/{projectId}/datasets/{datasetId}") + urls += "?" + c.urlParams_.Encode() + req, _ := http.NewRequest("PATCH", urls, body) + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "projectId": c.projectId, + "datasetId": c.datasetId, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "bigquery.datasets.patch" call. +// Exactly one of *Dataset or error will be non-nil. Any non-2xx status +// code is an error. Response headers are in either +// *Dataset.ServerResponse.Header or (if a response was returned at all) +// in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to +// check whether the returned error was because http.StatusNotModified +// was returned. +func (c *DatasetsPatchCall) Do(opts ...googleapi.CallOption) (*Dataset, error) { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if res != nil && res.StatusCode == http.StatusNotModified { + if res.Body != nil { + res.Body.Close() + } + return nil, &googleapi.Error{ + Code: res.StatusCode, + Header: res.Header, + } + } + if err != nil { + return nil, err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return nil, err + } + ret := &Dataset{ + ServerResponse: googleapi.ServerResponse{ + Header: res.Header, + HTTPStatusCode: res.StatusCode, + }, + } + target := &ret + if err := json.NewDecoder(res.Body).Decode(target); err != nil { + return nil, err + } + return ret, nil + // { + // "description": "Updates information in an existing dataset. The update method replaces the entire dataset resource, whereas the patch method only replaces fields that are provided in the submitted dataset resource. This method supports patch semantics.", + // "httpMethod": "PATCH", + // "id": "bigquery.datasets.patch", + // "parameterOrder": [ + // "projectId", + // "datasetId" + // ], + // "parameters": { + // "datasetId": { + // "description": "Dataset ID of the dataset being updated", + // "location": "path", + // "required": true, + // "type": "string" + // }, + // "projectId": { + // "description": "Project ID of the dataset being updated", + // "location": "path", + // "required": true, + // "type": "string" + // } + // }, + // "path": "projects/{projectId}/datasets/{datasetId}", + // "request": { + // "$ref": "Dataset" + // }, + // "response": { + // "$ref": "Dataset" + // }, + // "scopes": [ + // "https://www.googleapis.com/auth/bigquery", + // "https://www.googleapis.com/auth/cloud-platform" + // ] + // } + +} + +// method id "bigquery.datasets.update": + +type DatasetsUpdateCall struct { + s *Service + projectId string + datasetId string + dataset *Dataset + urlParams_ gensupport.URLParams + ctx_ context.Context + header_ http.Header +} + +// Update: Updates information in an existing dataset. The update method +// replaces the entire dataset resource, whereas the patch method only +// replaces fields that are provided in the submitted dataset resource. +func (r *DatasetsService) Update(projectId string, datasetId string, dataset *Dataset) *DatasetsUpdateCall { + c := &DatasetsUpdateCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.projectId = projectId + c.datasetId = datasetId + c.dataset = dataset + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse +// for more information. +func (c *DatasetsUpdateCall) Fields(s ...googleapi.Field) *DatasetsUpdateCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// Context sets the context to be used in this call's Do method. Any +// pending HTTP request will be aborted if the provided context is +// canceled. +func (c *DatasetsUpdateCall) Context(ctx context.Context) *DatasetsUpdateCall { + c.ctx_ = ctx + return c +} + +// Header returns an http.Header that can be modified by the caller to +// add HTTP headers to the request. +func (c *DatasetsUpdateCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *DatasetsUpdateCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := make(http.Header) + for k, v := range c.header_ { + reqHeaders[k] = v + } + reqHeaders.Set("User-Agent", c.s.userAgent()) + reqHeaders.Set("x-goog-api-client", c.s.clientHeader()) + var body io.Reader = nil + body, err := googleapi.WithoutDataWrapper.JSONReader(c.dataset) + if err != nil { + return nil, err + } + reqHeaders.Set("Content-Type", "application/json") + c.urlParams_.Set("alt", alt) + urls := googleapi.ResolveRelative(c.s.BasePath, "projects/{projectId}/datasets/{datasetId}") + urls += "?" + c.urlParams_.Encode() + req, _ := http.NewRequest("PUT", urls, body) + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "projectId": c.projectId, + "datasetId": c.datasetId, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "bigquery.datasets.update" call. +// Exactly one of *Dataset or error will be non-nil. Any non-2xx status +// code is an error. Response headers are in either +// *Dataset.ServerResponse.Header or (if a response was returned at all) +// in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to +// check whether the returned error was because http.StatusNotModified +// was returned. +func (c *DatasetsUpdateCall) Do(opts ...googleapi.CallOption) (*Dataset, error) { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if res != nil && res.StatusCode == http.StatusNotModified { + if res.Body != nil { + res.Body.Close() + } + return nil, &googleapi.Error{ + Code: res.StatusCode, + Header: res.Header, + } + } + if err != nil { + return nil, err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return nil, err + } + ret := &Dataset{ + ServerResponse: googleapi.ServerResponse{ + Header: res.Header, + HTTPStatusCode: res.StatusCode, + }, + } + target := &ret + if err := json.NewDecoder(res.Body).Decode(target); err != nil { + return nil, err + } + return ret, nil + // { + // "description": "Updates information in an existing dataset. The update method replaces the entire dataset resource, whereas the patch method only replaces fields that are provided in the submitted dataset resource.", + // "httpMethod": "PUT", + // "id": "bigquery.datasets.update", + // "parameterOrder": [ + // "projectId", + // "datasetId" + // ], + // "parameters": { + // "datasetId": { + // "description": "Dataset ID of the dataset being updated", + // "location": "path", + // "required": true, + // "type": "string" + // }, + // "projectId": { + // "description": "Project ID of the dataset being updated", + // "location": "path", + // "required": true, + // "type": "string" + // } + // }, + // "path": "projects/{projectId}/datasets/{datasetId}", + // "request": { + // "$ref": "Dataset" + // }, + // "response": { + // "$ref": "Dataset" + // }, + // "scopes": [ + // "https://www.googleapis.com/auth/bigquery", + // "https://www.googleapis.com/auth/cloud-platform" + // ] + // } + +} + +// method id "bigquery.jobs.cancel": + +type JobsCancelCall struct { + s *Service + projectId string + jobId string + urlParams_ gensupport.URLParams + ctx_ context.Context + header_ http.Header +} + +// Cancel: Requests that a job be cancelled. This call will return +// immediately, and the client will need to poll for the job status to +// see if the cancel completed successfully. Cancelled jobs may still +// incur costs. +func (r *JobsService) Cancel(projectId string, jobId string) *JobsCancelCall { + c := &JobsCancelCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.projectId = projectId + c.jobId = jobId + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse +// for more information. +func (c *JobsCancelCall) Fields(s ...googleapi.Field) *JobsCancelCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// Context sets the context to be used in this call's Do method. Any +// pending HTTP request will be aborted if the provided context is +// canceled. +func (c *JobsCancelCall) Context(ctx context.Context) *JobsCancelCall { + c.ctx_ = ctx + return c +} + +// Header returns an http.Header that can be modified by the caller to +// add HTTP headers to the request. +func (c *JobsCancelCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *JobsCancelCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := make(http.Header) + for k, v := range c.header_ { + reqHeaders[k] = v + } + reqHeaders.Set("User-Agent", c.s.userAgent()) + reqHeaders.Set("x-goog-api-client", c.s.clientHeader()) + var body io.Reader = nil + c.urlParams_.Set("alt", alt) + urls := googleapi.ResolveRelative(c.s.BasePath, "projects/{projectId}/jobs/{jobId}/cancel") + urls += "?" + c.urlParams_.Encode() + req, _ := http.NewRequest("POST", urls, body) + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "projectId": c.projectId, + "jobId": c.jobId, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "bigquery.jobs.cancel" call. +// Exactly one of *JobCancelResponse or error will be non-nil. Any +// non-2xx status code is an error. Response headers are in either +// *JobCancelResponse.ServerResponse.Header or (if a response was +// returned at all) in error.(*googleapi.Error).Header. Use +// googleapi.IsNotModified to check whether the returned error was +// because http.StatusNotModified was returned. +func (c *JobsCancelCall) Do(opts ...googleapi.CallOption) (*JobCancelResponse, error) { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if res != nil && res.StatusCode == http.StatusNotModified { + if res.Body != nil { + res.Body.Close() + } + return nil, &googleapi.Error{ + Code: res.StatusCode, + Header: res.Header, + } + } + if err != nil { + return nil, err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return nil, err + } + ret := &JobCancelResponse{ + ServerResponse: googleapi.ServerResponse{ + Header: res.Header, + HTTPStatusCode: res.StatusCode, + }, + } + target := &ret + if err := json.NewDecoder(res.Body).Decode(target); err != nil { + return nil, err + } + return ret, nil + // { + // "description": "Requests that a job be cancelled. This call will return immediately, and the client will need to poll for the job status to see if the cancel completed successfully. Cancelled jobs may still incur costs.", + // "httpMethod": "POST", + // "id": "bigquery.jobs.cancel", + // "parameterOrder": [ + // "projectId", + // "jobId" + // ], + // "parameters": { + // "jobId": { + // "description": "[Required] Job ID of the job to cancel", + // "location": "path", + // "required": true, + // "type": "string" + // }, + // "projectId": { + // "description": "[Required] Project ID of the job to cancel", + // "location": "path", + // "required": true, + // "type": "string" + // } + // }, + // "path": "projects/{projectId}/jobs/{jobId}/cancel", + // "response": { + // "$ref": "JobCancelResponse" + // }, + // "scopes": [ + // "https://www.googleapis.com/auth/bigquery", + // "https://www.googleapis.com/auth/cloud-platform" + // ] + // } + +} + +// method id "bigquery.jobs.get": + +type JobsGetCall struct { + s *Service + projectId string + jobId string + urlParams_ gensupport.URLParams + ifNoneMatch_ string + ctx_ context.Context + header_ http.Header +} + +// Get: Returns information about a specific job. Job information is +// available for a six month period after creation. Requires that you're +// the person who ran the job, or have the Is Owner project role. +func (r *JobsService) Get(projectId string, jobId string) *JobsGetCall { + c := &JobsGetCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.projectId = projectId + c.jobId = jobId + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse +// for more information. +func (c *JobsGetCall) Fields(s ...googleapi.Field) *JobsGetCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// IfNoneMatch sets the optional parameter which makes the operation +// fail if the object's ETag matches the given value. This is useful for +// getting updates only after the object has changed since the last +// request. Use googleapi.IsNotModified to check whether the response +// error from Do is the result of In-None-Match. +func (c *JobsGetCall) IfNoneMatch(entityTag string) *JobsGetCall { + c.ifNoneMatch_ = entityTag + return c +} + +// Context sets the context to be used in this call's Do method. Any +// pending HTTP request will be aborted if the provided context is +// canceled. +func (c *JobsGetCall) Context(ctx context.Context) *JobsGetCall { + c.ctx_ = ctx + return c +} + +// Header returns an http.Header that can be modified by the caller to +// add HTTP headers to the request. +func (c *JobsGetCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *JobsGetCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := make(http.Header) + for k, v := range c.header_ { + reqHeaders[k] = v + } + reqHeaders.Set("User-Agent", c.s.userAgent()) + reqHeaders.Set("x-goog-api-client", c.s.clientHeader()) + if c.ifNoneMatch_ != "" { + reqHeaders.Set("If-None-Match", c.ifNoneMatch_) + } + var body io.Reader = nil + c.urlParams_.Set("alt", alt) + urls := googleapi.ResolveRelative(c.s.BasePath, "projects/{projectId}/jobs/{jobId}") + urls += "?" + c.urlParams_.Encode() + req, _ := http.NewRequest("GET", urls, body) + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "projectId": c.projectId, + "jobId": c.jobId, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "bigquery.jobs.get" call. +// Exactly one of *Job or error will be non-nil. Any non-2xx status code +// is an error. Response headers are in either +// *Job.ServerResponse.Header or (if a response was returned at all) in +// error.(*googleapi.Error).Header. Use googleapi.IsNotModified to check +// whether the returned error was because http.StatusNotModified was +// returned. +func (c *JobsGetCall) Do(opts ...googleapi.CallOption) (*Job, error) { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if res != nil && res.StatusCode == http.StatusNotModified { + if res.Body != nil { + res.Body.Close() + } + return nil, &googleapi.Error{ + Code: res.StatusCode, + Header: res.Header, + } + } + if err != nil { + return nil, err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return nil, err + } + ret := &Job{ + ServerResponse: googleapi.ServerResponse{ + Header: res.Header, + HTTPStatusCode: res.StatusCode, + }, + } + target := &ret + if err := json.NewDecoder(res.Body).Decode(target); err != nil { + return nil, err + } + return ret, nil + // { + // "description": "Returns information about a specific job. Job information is available for a six month period after creation. Requires that you're the person who ran the job, or have the Is Owner project role.", + // "httpMethod": "GET", + // "id": "bigquery.jobs.get", + // "parameterOrder": [ + // "projectId", + // "jobId" + // ], + // "parameters": { + // "jobId": { + // "description": "[Required] Job ID of the requested job", + // "location": "path", + // "required": true, + // "type": "string" + // }, + // "projectId": { + // "description": "[Required] Project ID of the requested job", + // "location": "path", + // "required": true, + // "type": "string" + // } + // }, + // "path": "projects/{projectId}/jobs/{jobId}", + // "response": { + // "$ref": "Job" + // }, + // "scopes": [ + // "https://www.googleapis.com/auth/bigquery", + // "https://www.googleapis.com/auth/cloud-platform", + // "https://www.googleapis.com/auth/cloud-platform.read-only" + // ] + // } + +} + +// method id "bigquery.jobs.getQueryResults": + +type JobsGetQueryResultsCall struct { + s *Service + projectId string + jobId string + urlParams_ gensupport.URLParams + ifNoneMatch_ string + ctx_ context.Context + header_ http.Header +} + +// GetQueryResults: Retrieves the results of a query job. +func (r *JobsService) GetQueryResults(projectId string, jobId string) *JobsGetQueryResultsCall { + c := &JobsGetQueryResultsCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.projectId = projectId + c.jobId = jobId + return c +} + +// MaxResults sets the optional parameter "maxResults": Maximum number +// of results to read +func (c *JobsGetQueryResultsCall) MaxResults(maxResults int64) *JobsGetQueryResultsCall { + c.urlParams_.Set("maxResults", fmt.Sprint(maxResults)) + return c +} + +// PageToken sets the optional parameter "pageToken": Page token, +// returned by a previous call, to request the next page of results +func (c *JobsGetQueryResultsCall) PageToken(pageToken string) *JobsGetQueryResultsCall { + c.urlParams_.Set("pageToken", pageToken) + return c +} + +// StartIndex sets the optional parameter "startIndex": Zero-based index +// of the starting row +func (c *JobsGetQueryResultsCall) StartIndex(startIndex uint64) *JobsGetQueryResultsCall { + c.urlParams_.Set("startIndex", fmt.Sprint(startIndex)) + return c +} + +// TimeoutMs sets the optional parameter "timeoutMs": How long to wait +// for the query to complete, in milliseconds, before returning. Default +// is 10 seconds. If the timeout passes before the job completes, the +// 'jobComplete' field in the response will be false +func (c *JobsGetQueryResultsCall) TimeoutMs(timeoutMs int64) *JobsGetQueryResultsCall { + c.urlParams_.Set("timeoutMs", fmt.Sprint(timeoutMs)) + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse +// for more information. +func (c *JobsGetQueryResultsCall) Fields(s ...googleapi.Field) *JobsGetQueryResultsCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// IfNoneMatch sets the optional parameter which makes the operation +// fail if the object's ETag matches the given value. This is useful for +// getting updates only after the object has changed since the last +// request. Use googleapi.IsNotModified to check whether the response +// error from Do is the result of In-None-Match. +func (c *JobsGetQueryResultsCall) IfNoneMatch(entityTag string) *JobsGetQueryResultsCall { + c.ifNoneMatch_ = entityTag + return c +} + +// Context sets the context to be used in this call's Do method. Any +// pending HTTP request will be aborted if the provided context is +// canceled. +func (c *JobsGetQueryResultsCall) Context(ctx context.Context) *JobsGetQueryResultsCall { + c.ctx_ = ctx + return c +} + +// Header returns an http.Header that can be modified by the caller to +// add HTTP headers to the request. +func (c *JobsGetQueryResultsCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *JobsGetQueryResultsCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := make(http.Header) + for k, v := range c.header_ { + reqHeaders[k] = v + } + reqHeaders.Set("User-Agent", c.s.userAgent()) + reqHeaders.Set("x-goog-api-client", c.s.clientHeader()) + if c.ifNoneMatch_ != "" { + reqHeaders.Set("If-None-Match", c.ifNoneMatch_) + } + var body io.Reader = nil + c.urlParams_.Set("alt", alt) + urls := googleapi.ResolveRelative(c.s.BasePath, "projects/{projectId}/queries/{jobId}") + urls += "?" + c.urlParams_.Encode() + req, _ := http.NewRequest("GET", urls, body) + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "projectId": c.projectId, + "jobId": c.jobId, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "bigquery.jobs.getQueryResults" call. +// Exactly one of *GetQueryResultsResponse or error will be non-nil. Any +// non-2xx status code is an error. Response headers are in either +// *GetQueryResultsResponse.ServerResponse.Header or (if a response was +// returned at all) in error.(*googleapi.Error).Header. Use +// googleapi.IsNotModified to check whether the returned error was +// because http.StatusNotModified was returned. +func (c *JobsGetQueryResultsCall) Do(opts ...googleapi.CallOption) (*GetQueryResultsResponse, error) { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if res != nil && res.StatusCode == http.StatusNotModified { + if res.Body != nil { + res.Body.Close() + } + return nil, &googleapi.Error{ + Code: res.StatusCode, + Header: res.Header, + } + } + if err != nil { + return nil, err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return nil, err + } + ret := &GetQueryResultsResponse{ + ServerResponse: googleapi.ServerResponse{ + Header: res.Header, + HTTPStatusCode: res.StatusCode, + }, + } + target := &ret + if err := json.NewDecoder(res.Body).Decode(target); err != nil { + return nil, err + } + return ret, nil + // { + // "description": "Retrieves the results of a query job.", + // "httpMethod": "GET", + // "id": "bigquery.jobs.getQueryResults", + // "parameterOrder": [ + // "projectId", + // "jobId" + // ], + // "parameters": { + // "jobId": { + // "description": "[Required] Job ID of the query job", + // "location": "path", + // "required": true, + // "type": "string" + // }, + // "maxResults": { + // "description": "Maximum number of results to read", + // "format": "uint32", + // "location": "query", + // "type": "integer" + // }, + // "pageToken": { + // "description": "Page token, returned by a previous call, to request the next page of results", + // "location": "query", + // "type": "string" + // }, + // "projectId": { + // "description": "[Required] Project ID of the query job", + // "location": "path", + // "required": true, + // "type": "string" + // }, + // "startIndex": { + // "description": "Zero-based index of the starting row", + // "format": "uint64", + // "location": "query", + // "type": "string" + // }, + // "timeoutMs": { + // "description": "How long to wait for the query to complete, in milliseconds, before returning. Default is 10 seconds. If the timeout passes before the job completes, the 'jobComplete' field in the response will be false", + // "format": "uint32", + // "location": "query", + // "type": "integer" + // } + // }, + // "path": "projects/{projectId}/queries/{jobId}", + // "response": { + // "$ref": "GetQueryResultsResponse" + // }, + // "scopes": [ + // "https://www.googleapis.com/auth/bigquery", + // "https://www.googleapis.com/auth/cloud-platform", + // "https://www.googleapis.com/auth/cloud-platform.read-only" + // ] + // } + +} + +// Pages invokes f for each page of results. +// A non-nil error returned from f will halt the iteration. +// The provided context supersedes any context provided to the Context method. +func (c *JobsGetQueryResultsCall) Pages(ctx context.Context, f func(*GetQueryResultsResponse) error) error { + c.ctx_ = ctx + defer c.PageToken(c.urlParams_.Get("pageToken")) // reset paging to original point + for { + x, err := c.Do() + if err != nil { + return err + } + if err := f(x); err != nil { + return err + } + if x.PageToken == "" { + return nil + } + c.PageToken(x.PageToken) + } +} + +// method id "bigquery.jobs.insert": + +type JobsInsertCall struct { + s *Service + projectId string + job *Job + urlParams_ gensupport.URLParams + media_ io.Reader + mediaBuffer_ *gensupport.MediaBuffer + mediaType_ string + mediaSize_ int64 // mediaSize, if known. Used only for calls to progressUpdater_. + progressUpdater_ googleapi.ProgressUpdater + ctx_ context.Context + header_ http.Header +} + +// Insert: Starts a new asynchronous job. Requires the Can View project +// role. +func (r *JobsService) Insert(projectId string, job *Job) *JobsInsertCall { + c := &JobsInsertCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.projectId = projectId + c.job = job + return c +} + +// Media specifies the media to upload in one or more chunks. The chunk +// size may be controlled by supplying a MediaOption generated by +// googleapi.ChunkSize. The chunk size defaults to +// googleapi.DefaultUploadChunkSize.The Content-Type header used in the +// upload request will be determined by sniffing the contents of r, +// unless a MediaOption generated by googleapi.ContentType is +// supplied. +// At most one of Media and ResumableMedia may be set. +func (c *JobsInsertCall) Media(r io.Reader, options ...googleapi.MediaOption) *JobsInsertCall { + opts := googleapi.ProcessMediaOptions(options) + chunkSize := opts.ChunkSize + if !opts.ForceEmptyContentType { + r, c.mediaType_ = gensupport.DetermineContentType(r, opts.ContentType) + } + c.media_, c.mediaBuffer_ = gensupport.PrepareUpload(r, chunkSize) + return c +} + +// ResumableMedia specifies the media to upload in chunks and can be +// canceled with ctx. +// +// Deprecated: use Media instead. +// +// At most one of Media and ResumableMedia may be set. mediaType +// identifies the MIME media type of the upload, such as "image/png". If +// mediaType is "", it will be auto-detected. The provided ctx will +// supersede any context previously provided to the Context method. +func (c *JobsInsertCall) ResumableMedia(ctx context.Context, r io.ReaderAt, size int64, mediaType string) *JobsInsertCall { + c.ctx_ = ctx + rdr := gensupport.ReaderAtToReader(r, size) + rdr, c.mediaType_ = gensupport.DetermineContentType(rdr, mediaType) + c.mediaBuffer_ = gensupport.NewMediaBuffer(rdr, googleapi.DefaultUploadChunkSize) + c.media_ = nil + c.mediaSize_ = size + return c +} + +// ProgressUpdater provides a callback function that will be called +// after every chunk. It should be a low-latency function in order to +// not slow down the upload operation. This should only be called when +// using ResumableMedia (as opposed to Media). +func (c *JobsInsertCall) ProgressUpdater(pu googleapi.ProgressUpdater) *JobsInsertCall { + c.progressUpdater_ = pu + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse +// for more information. +func (c *JobsInsertCall) Fields(s ...googleapi.Field) *JobsInsertCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// Context sets the context to be used in this call's Do method. Any +// pending HTTP request will be aborted if the provided context is +// canceled. +// This context will supersede any context previously provided to the +// ResumableMedia method. +func (c *JobsInsertCall) Context(ctx context.Context) *JobsInsertCall { + c.ctx_ = ctx + return c +} + +// Header returns an http.Header that can be modified by the caller to +// add HTTP headers to the request. +func (c *JobsInsertCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *JobsInsertCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := make(http.Header) + for k, v := range c.header_ { + reqHeaders[k] = v + } + reqHeaders.Set("User-Agent", c.s.userAgent()) + reqHeaders.Set("x-goog-api-client", c.s.clientHeader()) + var body io.Reader = nil + body, err := googleapi.WithoutDataWrapper.JSONReader(c.job) + if err != nil { + return nil, err + } + reqHeaders.Set("Content-Type", "application/json") + c.urlParams_.Set("alt", alt) + urls := googleapi.ResolveRelative(c.s.BasePath, "projects/{projectId}/jobs") + if c.media_ != nil || c.mediaBuffer_ != nil { + urls = strings.Replace(urls, "https://www.googleapis.com/", "https://www.googleapis.com/upload/", 1) + protocol := "multipart" + if c.mediaBuffer_ != nil { + protocol = "resumable" + } + c.urlParams_.Set("uploadType", protocol) + } + if body == nil { + body = new(bytes.Buffer) + reqHeaders.Set("Content-Type", "application/json") + } + if c.media_ != nil { + combined, ctype := gensupport.CombineBodyMedia(body, "application/json", c.media_, c.mediaType_) + defer combined.Close() + reqHeaders.Set("Content-Type", ctype) + body = combined + } + if c.mediaBuffer_ != nil && c.mediaType_ != "" { + reqHeaders.Set("X-Upload-Content-Type", c.mediaType_) + } + urls += "?" + c.urlParams_.Encode() + req, _ := http.NewRequest("POST", urls, body) + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "projectId": c.projectId, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "bigquery.jobs.insert" call. +// Exactly one of *Job or error will be non-nil. Any non-2xx status code +// is an error. Response headers are in either +// *Job.ServerResponse.Header or (if a response was returned at all) in +// error.(*googleapi.Error).Header. Use googleapi.IsNotModified to check +// whether the returned error was because http.StatusNotModified was +// returned. +func (c *JobsInsertCall) Do(opts ...googleapi.CallOption) (*Job, error) { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if res != nil && res.StatusCode == http.StatusNotModified { + if res.Body != nil { + res.Body.Close() + } + return nil, &googleapi.Error{ + Code: res.StatusCode, + Header: res.Header, + } + } + if err != nil { + return nil, err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return nil, err + } + if c.mediaBuffer_ != nil { + loc := res.Header.Get("Location") + rx := &gensupport.ResumableUpload{ + Client: c.s.client, + UserAgent: c.s.userAgent(), + URI: loc, + Media: c.mediaBuffer_, + MediaType: c.mediaType_, + Callback: func(curr int64) { + if c.progressUpdater_ != nil { + c.progressUpdater_(curr, c.mediaSize_) + } + }, + } + ctx := c.ctx_ + if ctx == nil { + ctx = context.TODO() + } + res, err = rx.Upload(ctx) + if err != nil { + return nil, err + } + defer res.Body.Close() + if err := googleapi.CheckResponse(res); err != nil { + return nil, err + } + } + ret := &Job{ + ServerResponse: googleapi.ServerResponse{ + Header: res.Header, + HTTPStatusCode: res.StatusCode, + }, + } + target := &ret + if err := json.NewDecoder(res.Body).Decode(target); err != nil { + return nil, err + } + return ret, nil + // { + // "description": "Starts a new asynchronous job. Requires the Can View project role.", + // "httpMethod": "POST", + // "id": "bigquery.jobs.insert", + // "mediaUpload": { + // "accept": [ + // "*/*" + // ], + // "protocols": { + // "resumable": { + // "multipart": true, + // "path": "/resumable/upload/bigquery/v2/projects/{projectId}/jobs" + // }, + // "simple": { + // "multipart": true, + // "path": "/upload/bigquery/v2/projects/{projectId}/jobs" + // } + // } + // }, + // "parameterOrder": [ + // "projectId" + // ], + // "parameters": { + // "projectId": { + // "description": "Project ID of the project that will be billed for the job", + // "location": "path", + // "required": true, + // "type": "string" + // } + // }, + // "path": "projects/{projectId}/jobs", + // "request": { + // "$ref": "Job" + // }, + // "response": { + // "$ref": "Job" + // }, + // "scopes": [ + // "https://www.googleapis.com/auth/bigquery", + // "https://www.googleapis.com/auth/cloud-platform", + // "https://www.googleapis.com/auth/devstorage.full_control", + // "https://www.googleapis.com/auth/devstorage.read_only", + // "https://www.googleapis.com/auth/devstorage.read_write" + // ], + // "supportsMediaUpload": true + // } + +} + +// method id "bigquery.jobs.list": + +type JobsListCall struct { + s *Service + projectId string + urlParams_ gensupport.URLParams + ifNoneMatch_ string + ctx_ context.Context + header_ http.Header +} + +// List: Lists all jobs that you started in the specified project. Job +// information is available for a six month period after creation. The +// job list is sorted in reverse chronological order, by job creation +// time. Requires the Can View project role, or the Is Owner project +// role if you set the allUsers property. +func (r *JobsService) List(projectId string) *JobsListCall { + c := &JobsListCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.projectId = projectId + return c +} + +// AllUsers sets the optional parameter "allUsers": Whether to display +// jobs owned by all users in the project. Default false +func (c *JobsListCall) AllUsers(allUsers bool) *JobsListCall { + c.urlParams_.Set("allUsers", fmt.Sprint(allUsers)) + return c +} + +// MaxResults sets the optional parameter "maxResults": Maximum number +// of results to return +func (c *JobsListCall) MaxResults(maxResults int64) *JobsListCall { + c.urlParams_.Set("maxResults", fmt.Sprint(maxResults)) + return c +} + +// PageToken sets the optional parameter "pageToken": Page token, +// returned by a previous call, to request the next page of results +func (c *JobsListCall) PageToken(pageToken string) *JobsListCall { + c.urlParams_.Set("pageToken", pageToken) + return c +} + +// Projection sets the optional parameter "projection": Restrict +// information returned to a set of selected fields +// +// Possible values: +// "full" - Includes all job data +// "minimal" - Does not include the job configuration +func (c *JobsListCall) Projection(projection string) *JobsListCall { + c.urlParams_.Set("projection", projection) + return c +} + +// StateFilter sets the optional parameter "stateFilter": Filter for job +// state +// +// Possible values: +// "done" - Finished jobs +// "pending" - Pending jobs +// "running" - Running jobs +func (c *JobsListCall) StateFilter(stateFilter ...string) *JobsListCall { + c.urlParams_.SetMulti("stateFilter", append([]string{}, stateFilter...)) + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse +// for more information. +func (c *JobsListCall) Fields(s ...googleapi.Field) *JobsListCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// IfNoneMatch sets the optional parameter which makes the operation +// fail if the object's ETag matches the given value. This is useful for +// getting updates only after the object has changed since the last +// request. Use googleapi.IsNotModified to check whether the response +// error from Do is the result of In-None-Match. +func (c *JobsListCall) IfNoneMatch(entityTag string) *JobsListCall { + c.ifNoneMatch_ = entityTag + return c +} + +// Context sets the context to be used in this call's Do method. Any +// pending HTTP request will be aborted if the provided context is +// canceled. +func (c *JobsListCall) Context(ctx context.Context) *JobsListCall { + c.ctx_ = ctx + return c +} + +// Header returns an http.Header that can be modified by the caller to +// add HTTP headers to the request. +func (c *JobsListCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *JobsListCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := make(http.Header) + for k, v := range c.header_ { + reqHeaders[k] = v + } + reqHeaders.Set("User-Agent", c.s.userAgent()) + reqHeaders.Set("x-goog-api-client", c.s.clientHeader()) + if c.ifNoneMatch_ != "" { + reqHeaders.Set("If-None-Match", c.ifNoneMatch_) + } + var body io.Reader = nil + c.urlParams_.Set("alt", alt) + urls := googleapi.ResolveRelative(c.s.BasePath, "projects/{projectId}/jobs") + urls += "?" + c.urlParams_.Encode() + req, _ := http.NewRequest("GET", urls, body) + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "projectId": c.projectId, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "bigquery.jobs.list" call. +// Exactly one of *JobList or error will be non-nil. Any non-2xx status +// code is an error. Response headers are in either +// *JobList.ServerResponse.Header or (if a response was returned at all) +// in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to +// check whether the returned error was because http.StatusNotModified +// was returned. +func (c *JobsListCall) Do(opts ...googleapi.CallOption) (*JobList, error) { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if res != nil && res.StatusCode == http.StatusNotModified { + if res.Body != nil { + res.Body.Close() + } + return nil, &googleapi.Error{ + Code: res.StatusCode, + Header: res.Header, + } + } + if err != nil { + return nil, err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return nil, err + } + ret := &JobList{ + ServerResponse: googleapi.ServerResponse{ + Header: res.Header, + HTTPStatusCode: res.StatusCode, + }, + } + target := &ret + if err := json.NewDecoder(res.Body).Decode(target); err != nil { + return nil, err + } + return ret, nil + // { + // "description": "Lists all jobs that you started in the specified project. Job information is available for a six month period after creation. The job list is sorted in reverse chronological order, by job creation time. Requires the Can View project role, or the Is Owner project role if you set the allUsers property.", + // "httpMethod": "GET", + // "id": "bigquery.jobs.list", + // "parameterOrder": [ + // "projectId" + // ], + // "parameters": { + // "allUsers": { + // "description": "Whether to display jobs owned by all users in the project. Default false", + // "location": "query", + // "type": "boolean" + // }, + // "maxResults": { + // "description": "Maximum number of results to return", + // "format": "uint32", + // "location": "query", + // "type": "integer" + // }, + // "pageToken": { + // "description": "Page token, returned by a previous call, to request the next page of results", + // "location": "query", + // "type": "string" + // }, + // "projectId": { + // "description": "Project ID of the jobs to list", + // "location": "path", + // "required": true, + // "type": "string" + // }, + // "projection": { + // "description": "Restrict information returned to a set of selected fields", + // "enum": [ + // "full", + // "minimal" + // ], + // "enumDescriptions": [ + // "Includes all job data", + // "Does not include the job configuration" + // ], + // "location": "query", + // "type": "string" + // }, + // "stateFilter": { + // "description": "Filter for job state", + // "enum": [ + // "done", + // "pending", + // "running" + // ], + // "enumDescriptions": [ + // "Finished jobs", + // "Pending jobs", + // "Running jobs" + // ], + // "location": "query", + // "repeated": true, + // "type": "string" + // } + // }, + // "path": "projects/{projectId}/jobs", + // "response": { + // "$ref": "JobList" + // }, + // "scopes": [ + // "https://www.googleapis.com/auth/bigquery", + // "https://www.googleapis.com/auth/cloud-platform", + // "https://www.googleapis.com/auth/cloud-platform.read-only" + // ] + // } + +} + +// Pages invokes f for each page of results. +// A non-nil error returned from f will halt the iteration. +// The provided context supersedes any context provided to the Context method. +func (c *JobsListCall) Pages(ctx context.Context, f func(*JobList) error) error { + c.ctx_ = ctx + defer c.PageToken(c.urlParams_.Get("pageToken")) // reset paging to original point + for { + x, err := c.Do() + if err != nil { + return err + } + if err := f(x); err != nil { + return err + } + if x.NextPageToken == "" { + return nil + } + c.PageToken(x.NextPageToken) + } +} + +// method id "bigquery.jobs.query": + +type JobsQueryCall struct { + s *Service + projectId string + queryrequest *QueryRequest + urlParams_ gensupport.URLParams + ctx_ context.Context + header_ http.Header +} + +// Query: Runs a BigQuery SQL query synchronously and returns query +// results if the query completes within a specified timeout. +func (r *JobsService) Query(projectId string, queryrequest *QueryRequest) *JobsQueryCall { + c := &JobsQueryCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.projectId = projectId + c.queryrequest = queryrequest + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse +// for more information. +func (c *JobsQueryCall) Fields(s ...googleapi.Field) *JobsQueryCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// Context sets the context to be used in this call's Do method. Any +// pending HTTP request will be aborted if the provided context is +// canceled. +func (c *JobsQueryCall) Context(ctx context.Context) *JobsQueryCall { + c.ctx_ = ctx + return c +} + +// Header returns an http.Header that can be modified by the caller to +// add HTTP headers to the request. +func (c *JobsQueryCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *JobsQueryCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := make(http.Header) + for k, v := range c.header_ { + reqHeaders[k] = v + } + reqHeaders.Set("User-Agent", c.s.userAgent()) + reqHeaders.Set("x-goog-api-client", c.s.clientHeader()) + var body io.Reader = nil + body, err := googleapi.WithoutDataWrapper.JSONReader(c.queryrequest) + if err != nil { + return nil, err + } + reqHeaders.Set("Content-Type", "application/json") + c.urlParams_.Set("alt", alt) + urls := googleapi.ResolveRelative(c.s.BasePath, "projects/{projectId}/queries") + urls += "?" + c.urlParams_.Encode() + req, _ := http.NewRequest("POST", urls, body) + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "projectId": c.projectId, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "bigquery.jobs.query" call. +// Exactly one of *QueryResponse or error will be non-nil. Any non-2xx +// status code is an error. Response headers are in either +// *QueryResponse.ServerResponse.Header or (if a response was returned +// at all) in error.(*googleapi.Error).Header. Use +// googleapi.IsNotModified to check whether the returned error was +// because http.StatusNotModified was returned. +func (c *JobsQueryCall) Do(opts ...googleapi.CallOption) (*QueryResponse, error) { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if res != nil && res.StatusCode == http.StatusNotModified { + if res.Body != nil { + res.Body.Close() + } + return nil, &googleapi.Error{ + Code: res.StatusCode, + Header: res.Header, + } + } + if err != nil { + return nil, err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return nil, err + } + ret := &QueryResponse{ + ServerResponse: googleapi.ServerResponse{ + Header: res.Header, + HTTPStatusCode: res.StatusCode, + }, + } + target := &ret + if err := json.NewDecoder(res.Body).Decode(target); err != nil { + return nil, err + } + return ret, nil + // { + // "description": "Runs a BigQuery SQL query synchronously and returns query results if the query completes within a specified timeout.", + // "httpMethod": "POST", + // "id": "bigquery.jobs.query", + // "parameterOrder": [ + // "projectId" + // ], + // "parameters": { + // "projectId": { + // "description": "Project ID of the project billed for the query", + // "location": "path", + // "required": true, + // "type": "string" + // } + // }, + // "path": "projects/{projectId}/queries", + // "request": { + // "$ref": "QueryRequest" + // }, + // "response": { + // "$ref": "QueryResponse" + // }, + // "scopes": [ + // "https://www.googleapis.com/auth/bigquery", + // "https://www.googleapis.com/auth/cloud-platform", + // "https://www.googleapis.com/auth/cloud-platform.read-only" + // ] + // } + +} + +// method id "bigquery.projects.list": + +type ProjectsListCall struct { + s *Service + urlParams_ gensupport.URLParams + ifNoneMatch_ string + ctx_ context.Context + header_ http.Header +} + +// List: Lists all projects to which you have been granted any project +// role. +func (r *ProjectsService) List() *ProjectsListCall { + c := &ProjectsListCall{s: r.s, urlParams_: make(gensupport.URLParams)} + return c +} + +// MaxResults sets the optional parameter "maxResults": Maximum number +// of results to return +func (c *ProjectsListCall) MaxResults(maxResults int64) *ProjectsListCall { + c.urlParams_.Set("maxResults", fmt.Sprint(maxResults)) + return c +} + +// PageToken sets the optional parameter "pageToken": Page token, +// returned by a previous call, to request the next page of results +func (c *ProjectsListCall) PageToken(pageToken string) *ProjectsListCall { + c.urlParams_.Set("pageToken", pageToken) + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse +// for more information. +func (c *ProjectsListCall) Fields(s ...googleapi.Field) *ProjectsListCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// IfNoneMatch sets the optional parameter which makes the operation +// fail if the object's ETag matches the given value. This is useful for +// getting updates only after the object has changed since the last +// request. Use googleapi.IsNotModified to check whether the response +// error from Do is the result of In-None-Match. +func (c *ProjectsListCall) IfNoneMatch(entityTag string) *ProjectsListCall { + c.ifNoneMatch_ = entityTag + return c +} + +// Context sets the context to be used in this call's Do method. Any +// pending HTTP request will be aborted if the provided context is +// canceled. +func (c *ProjectsListCall) Context(ctx context.Context) *ProjectsListCall { + c.ctx_ = ctx + return c +} + +// Header returns an http.Header that can be modified by the caller to +// add HTTP headers to the request. +func (c *ProjectsListCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *ProjectsListCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := make(http.Header) + for k, v := range c.header_ { + reqHeaders[k] = v + } + reqHeaders.Set("User-Agent", c.s.userAgent()) + reqHeaders.Set("x-goog-api-client", c.s.clientHeader()) + if c.ifNoneMatch_ != "" { + reqHeaders.Set("If-None-Match", c.ifNoneMatch_) + } + var body io.Reader = nil + c.urlParams_.Set("alt", alt) + urls := googleapi.ResolveRelative(c.s.BasePath, "projects") + urls += "?" + c.urlParams_.Encode() + req, _ := http.NewRequest("GET", urls, body) + req.Header = reqHeaders + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "bigquery.projects.list" call. +// Exactly one of *ProjectList or error will be non-nil. Any non-2xx +// status code is an error. Response headers are in either +// *ProjectList.ServerResponse.Header or (if a response was returned at +// all) in error.(*googleapi.Error).Header. Use googleapi.IsNotModified +// to check whether the returned error was because +// http.StatusNotModified was returned. +func (c *ProjectsListCall) Do(opts ...googleapi.CallOption) (*ProjectList, error) { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if res != nil && res.StatusCode == http.StatusNotModified { + if res.Body != nil { + res.Body.Close() + } + return nil, &googleapi.Error{ + Code: res.StatusCode, + Header: res.Header, + } + } + if err != nil { + return nil, err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return nil, err + } + ret := &ProjectList{ + ServerResponse: googleapi.ServerResponse{ + Header: res.Header, + HTTPStatusCode: res.StatusCode, + }, + } + target := &ret + if err := json.NewDecoder(res.Body).Decode(target); err != nil { + return nil, err + } + return ret, nil + // { + // "description": "Lists all projects to which you have been granted any project role.", + // "httpMethod": "GET", + // "id": "bigquery.projects.list", + // "parameters": { + // "maxResults": { + // "description": "Maximum number of results to return", + // "format": "uint32", + // "location": "query", + // "type": "integer" + // }, + // "pageToken": { + // "description": "Page token, returned by a previous call, to request the next page of results", + // "location": "query", + // "type": "string" + // } + // }, + // "path": "projects", + // "response": { + // "$ref": "ProjectList" + // }, + // "scopes": [ + // "https://www.googleapis.com/auth/bigquery", + // "https://www.googleapis.com/auth/cloud-platform", + // "https://www.googleapis.com/auth/cloud-platform.read-only" + // ] + // } + +} + +// Pages invokes f for each page of results. +// A non-nil error returned from f will halt the iteration. +// The provided context supersedes any context provided to the Context method. +func (c *ProjectsListCall) Pages(ctx context.Context, f func(*ProjectList) error) error { + c.ctx_ = ctx + defer c.PageToken(c.urlParams_.Get("pageToken")) // reset paging to original point + for { + x, err := c.Do() + if err != nil { + return err + } + if err := f(x); err != nil { + return err + } + if x.NextPageToken == "" { + return nil + } + c.PageToken(x.NextPageToken) + } +} + +// method id "bigquery.tabledata.insertAll": + +type TabledataInsertAllCall struct { + s *Service + projectId string + datasetId string + tableId string + tabledatainsertallrequest *TableDataInsertAllRequest + urlParams_ gensupport.URLParams + ctx_ context.Context + header_ http.Header +} + +// InsertAll: Streams data into BigQuery one record at a time without +// needing to run a load job. Requires the WRITER dataset role. +func (r *TabledataService) InsertAll(projectId string, datasetId string, tableId string, tabledatainsertallrequest *TableDataInsertAllRequest) *TabledataInsertAllCall { + c := &TabledataInsertAllCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.projectId = projectId + c.datasetId = datasetId + c.tableId = tableId + c.tabledatainsertallrequest = tabledatainsertallrequest + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse +// for more information. +func (c *TabledataInsertAllCall) Fields(s ...googleapi.Field) *TabledataInsertAllCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// Context sets the context to be used in this call's Do method. Any +// pending HTTP request will be aborted if the provided context is +// canceled. +func (c *TabledataInsertAllCall) Context(ctx context.Context) *TabledataInsertAllCall { + c.ctx_ = ctx + return c +} + +// Header returns an http.Header that can be modified by the caller to +// add HTTP headers to the request. +func (c *TabledataInsertAllCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *TabledataInsertAllCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := make(http.Header) + for k, v := range c.header_ { + reqHeaders[k] = v + } + reqHeaders.Set("User-Agent", c.s.userAgent()) + reqHeaders.Set("x-goog-api-client", c.s.clientHeader()) + var body io.Reader = nil + body, err := googleapi.WithoutDataWrapper.JSONReader(c.tabledatainsertallrequest) + if err != nil { + return nil, err + } + reqHeaders.Set("Content-Type", "application/json") + c.urlParams_.Set("alt", alt) + urls := googleapi.ResolveRelative(c.s.BasePath, "projects/{projectId}/datasets/{datasetId}/tables/{tableId}/insertAll") + urls += "?" + c.urlParams_.Encode() + req, _ := http.NewRequest("POST", urls, body) + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "projectId": c.projectId, + "datasetId": c.datasetId, + "tableId": c.tableId, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "bigquery.tabledata.insertAll" call. +// Exactly one of *TableDataInsertAllResponse or error will be non-nil. +// Any non-2xx status code is an error. Response headers are in either +// *TableDataInsertAllResponse.ServerResponse.Header or (if a response +// was returned at all) in error.(*googleapi.Error).Header. Use +// googleapi.IsNotModified to check whether the returned error was +// because http.StatusNotModified was returned. +func (c *TabledataInsertAllCall) Do(opts ...googleapi.CallOption) (*TableDataInsertAllResponse, error) { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if res != nil && res.StatusCode == http.StatusNotModified { + if res.Body != nil { + res.Body.Close() + } + return nil, &googleapi.Error{ + Code: res.StatusCode, + Header: res.Header, + } + } + if err != nil { + return nil, err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return nil, err + } + ret := &TableDataInsertAllResponse{ + ServerResponse: googleapi.ServerResponse{ + Header: res.Header, + HTTPStatusCode: res.StatusCode, + }, + } + target := &ret + if err := json.NewDecoder(res.Body).Decode(target); err != nil { + return nil, err + } + return ret, nil + // { + // "description": "Streams data into BigQuery one record at a time without needing to run a load job. Requires the WRITER dataset role.", + // "httpMethod": "POST", + // "id": "bigquery.tabledata.insertAll", + // "parameterOrder": [ + // "projectId", + // "datasetId", + // "tableId" + // ], + // "parameters": { + // "datasetId": { + // "description": "Dataset ID of the destination table.", + // "location": "path", + // "required": true, + // "type": "string" + // }, + // "projectId": { + // "description": "Project ID of the destination table.", + // "location": "path", + // "required": true, + // "type": "string" + // }, + // "tableId": { + // "description": "Table ID of the destination table.", + // "location": "path", + // "required": true, + // "type": "string" + // } + // }, + // "path": "projects/{projectId}/datasets/{datasetId}/tables/{tableId}/insertAll", + // "request": { + // "$ref": "TableDataInsertAllRequest" + // }, + // "response": { + // "$ref": "TableDataInsertAllResponse" + // }, + // "scopes": [ + // "https://www.googleapis.com/auth/bigquery", + // "https://www.googleapis.com/auth/bigquery.insertdata", + // "https://www.googleapis.com/auth/cloud-platform" + // ] + // } + +} + +// method id "bigquery.tabledata.list": + +type TabledataListCall struct { + s *Service + projectId string + datasetId string + tableId string + urlParams_ gensupport.URLParams + ifNoneMatch_ string + ctx_ context.Context + header_ http.Header +} + +// List: Retrieves table data from a specified set of rows. Requires the +// READER dataset role. +func (r *TabledataService) List(projectId string, datasetId string, tableId string) *TabledataListCall { + c := &TabledataListCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.projectId = projectId + c.datasetId = datasetId + c.tableId = tableId + return c +} + +// MaxResults sets the optional parameter "maxResults": Maximum number +// of results to return +func (c *TabledataListCall) MaxResults(maxResults int64) *TabledataListCall { + c.urlParams_.Set("maxResults", fmt.Sprint(maxResults)) + return c +} + +// PageToken sets the optional parameter "pageToken": Page token, +// returned by a previous call, identifying the result set +func (c *TabledataListCall) PageToken(pageToken string) *TabledataListCall { + c.urlParams_.Set("pageToken", pageToken) + return c +} + +// StartIndex sets the optional parameter "startIndex": Zero-based index +// of the starting row to read +func (c *TabledataListCall) StartIndex(startIndex uint64) *TabledataListCall { + c.urlParams_.Set("startIndex", fmt.Sprint(startIndex)) + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse +// for more information. +func (c *TabledataListCall) Fields(s ...googleapi.Field) *TabledataListCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// IfNoneMatch sets the optional parameter which makes the operation +// fail if the object's ETag matches the given value. This is useful for +// getting updates only after the object has changed since the last +// request. Use googleapi.IsNotModified to check whether the response +// error from Do is the result of In-None-Match. +func (c *TabledataListCall) IfNoneMatch(entityTag string) *TabledataListCall { + c.ifNoneMatch_ = entityTag + return c +} + +// Context sets the context to be used in this call's Do method. Any +// pending HTTP request will be aborted if the provided context is +// canceled. +func (c *TabledataListCall) Context(ctx context.Context) *TabledataListCall { + c.ctx_ = ctx + return c +} + +// Header returns an http.Header that can be modified by the caller to +// add HTTP headers to the request. +func (c *TabledataListCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *TabledataListCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := make(http.Header) + for k, v := range c.header_ { + reqHeaders[k] = v + } + reqHeaders.Set("User-Agent", c.s.userAgent()) + reqHeaders.Set("x-goog-api-client", c.s.clientHeader()) + if c.ifNoneMatch_ != "" { + reqHeaders.Set("If-None-Match", c.ifNoneMatch_) + } + var body io.Reader = nil + c.urlParams_.Set("alt", alt) + urls := googleapi.ResolveRelative(c.s.BasePath, "projects/{projectId}/datasets/{datasetId}/tables/{tableId}/data") + urls += "?" + c.urlParams_.Encode() + req, _ := http.NewRequest("GET", urls, body) + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "projectId": c.projectId, + "datasetId": c.datasetId, + "tableId": c.tableId, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "bigquery.tabledata.list" call. +// Exactly one of *TableDataList or error will be non-nil. Any non-2xx +// status code is an error. Response headers are in either +// *TableDataList.ServerResponse.Header or (if a response was returned +// at all) in error.(*googleapi.Error).Header. Use +// googleapi.IsNotModified to check whether the returned error was +// because http.StatusNotModified was returned. +func (c *TabledataListCall) Do(opts ...googleapi.CallOption) (*TableDataList, error) { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if res != nil && res.StatusCode == http.StatusNotModified { + if res.Body != nil { + res.Body.Close() + } + return nil, &googleapi.Error{ + Code: res.StatusCode, + Header: res.Header, + } + } + if err != nil { + return nil, err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return nil, err + } + ret := &TableDataList{ + ServerResponse: googleapi.ServerResponse{ + Header: res.Header, + HTTPStatusCode: res.StatusCode, + }, + } + target := &ret + if err := json.NewDecoder(res.Body).Decode(target); err != nil { + return nil, err + } + return ret, nil + // { + // "description": "Retrieves table data from a specified set of rows. Requires the READER dataset role.", + // "httpMethod": "GET", + // "id": "bigquery.tabledata.list", + // "parameterOrder": [ + // "projectId", + // "datasetId", + // "tableId" + // ], + // "parameters": { + // "datasetId": { + // "description": "Dataset ID of the table to read", + // "location": "path", + // "required": true, + // "type": "string" + // }, + // "maxResults": { + // "description": "Maximum number of results to return", + // "format": "uint32", + // "location": "query", + // "type": "integer" + // }, + // "pageToken": { + // "description": "Page token, returned by a previous call, identifying the result set", + // "location": "query", + // "type": "string" + // }, + // "projectId": { + // "description": "Project ID of the table to read", + // "location": "path", + // "required": true, + // "type": "string" + // }, + // "startIndex": { + // "description": "Zero-based index of the starting row to read", + // "format": "uint64", + // "location": "query", + // "type": "string" + // }, + // "tableId": { + // "description": "Table ID of the table to read", + // "location": "path", + // "required": true, + // "type": "string" + // } + // }, + // "path": "projects/{projectId}/datasets/{datasetId}/tables/{tableId}/data", + // "response": { + // "$ref": "TableDataList" + // }, + // "scopes": [ + // "https://www.googleapis.com/auth/bigquery", + // "https://www.googleapis.com/auth/cloud-platform", + // "https://www.googleapis.com/auth/cloud-platform.read-only" + // ] + // } + +} + +// Pages invokes f for each page of results. +// A non-nil error returned from f will halt the iteration. +// The provided context supersedes any context provided to the Context method. +func (c *TabledataListCall) Pages(ctx context.Context, f func(*TableDataList) error) error { + c.ctx_ = ctx + defer c.PageToken(c.urlParams_.Get("pageToken")) // reset paging to original point + for { + x, err := c.Do() + if err != nil { + return err + } + if err := f(x); err != nil { + return err + } + if x.PageToken == "" { + return nil + } + c.PageToken(x.PageToken) + } +} + +// method id "bigquery.tables.delete": + +type TablesDeleteCall struct { + s *Service + projectId string + datasetId string + tableId string + urlParams_ gensupport.URLParams + ctx_ context.Context + header_ http.Header +} + +// Delete: Deletes the table specified by tableId from the dataset. If +// the table contains data, all the data will be deleted. +func (r *TablesService) Delete(projectId string, datasetId string, tableId string) *TablesDeleteCall { + c := &TablesDeleteCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.projectId = projectId + c.datasetId = datasetId + c.tableId = tableId + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse +// for more information. +func (c *TablesDeleteCall) Fields(s ...googleapi.Field) *TablesDeleteCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// Context sets the context to be used in this call's Do method. Any +// pending HTTP request will be aborted if the provided context is +// canceled. +func (c *TablesDeleteCall) Context(ctx context.Context) *TablesDeleteCall { + c.ctx_ = ctx + return c +} + +// Header returns an http.Header that can be modified by the caller to +// add HTTP headers to the request. +func (c *TablesDeleteCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *TablesDeleteCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := make(http.Header) + for k, v := range c.header_ { + reqHeaders[k] = v + } + reqHeaders.Set("User-Agent", c.s.userAgent()) + reqHeaders.Set("x-goog-api-client", c.s.clientHeader()) + var body io.Reader = nil + c.urlParams_.Set("alt", alt) + urls := googleapi.ResolveRelative(c.s.BasePath, "projects/{projectId}/datasets/{datasetId}/tables/{tableId}") + urls += "?" + c.urlParams_.Encode() + req, _ := http.NewRequest("DELETE", urls, body) + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "projectId": c.projectId, + "datasetId": c.datasetId, + "tableId": c.tableId, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "bigquery.tables.delete" call. +func (c *TablesDeleteCall) Do(opts ...googleapi.CallOption) error { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if err != nil { + return err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return err + } + return nil + // { + // "description": "Deletes the table specified by tableId from the dataset. If the table contains data, all the data will be deleted.", + // "httpMethod": "DELETE", + // "id": "bigquery.tables.delete", + // "parameterOrder": [ + // "projectId", + // "datasetId", + // "tableId" + // ], + // "parameters": { + // "datasetId": { + // "description": "Dataset ID of the table to delete", + // "location": "path", + // "required": true, + // "type": "string" + // }, + // "projectId": { + // "description": "Project ID of the table to delete", + // "location": "path", + // "required": true, + // "type": "string" + // }, + // "tableId": { + // "description": "Table ID of the table to delete", + // "location": "path", + // "required": true, + // "type": "string" + // } + // }, + // "path": "projects/{projectId}/datasets/{datasetId}/tables/{tableId}", + // "scopes": [ + // "https://www.googleapis.com/auth/bigquery", + // "https://www.googleapis.com/auth/cloud-platform" + // ] + // } + +} + +// method id "bigquery.tables.get": + +type TablesGetCall struct { + s *Service + projectId string + datasetId string + tableId string + urlParams_ gensupport.URLParams + ifNoneMatch_ string + ctx_ context.Context + header_ http.Header +} + +// Get: Gets the specified table resource by table ID. This method does +// not return the data in the table, it only returns the table resource, +// which describes the structure of this table. +func (r *TablesService) Get(projectId string, datasetId string, tableId string) *TablesGetCall { + c := &TablesGetCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.projectId = projectId + c.datasetId = datasetId + c.tableId = tableId + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse +// for more information. +func (c *TablesGetCall) Fields(s ...googleapi.Field) *TablesGetCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// IfNoneMatch sets the optional parameter which makes the operation +// fail if the object's ETag matches the given value. This is useful for +// getting updates only after the object has changed since the last +// request. Use googleapi.IsNotModified to check whether the response +// error from Do is the result of In-None-Match. +func (c *TablesGetCall) IfNoneMatch(entityTag string) *TablesGetCall { + c.ifNoneMatch_ = entityTag + return c +} + +// Context sets the context to be used in this call's Do method. Any +// pending HTTP request will be aborted if the provided context is +// canceled. +func (c *TablesGetCall) Context(ctx context.Context) *TablesGetCall { + c.ctx_ = ctx + return c +} + +// Header returns an http.Header that can be modified by the caller to +// add HTTP headers to the request. +func (c *TablesGetCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *TablesGetCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := make(http.Header) + for k, v := range c.header_ { + reqHeaders[k] = v + } + reqHeaders.Set("User-Agent", c.s.userAgent()) + reqHeaders.Set("x-goog-api-client", c.s.clientHeader()) + if c.ifNoneMatch_ != "" { + reqHeaders.Set("If-None-Match", c.ifNoneMatch_) + } + var body io.Reader = nil + c.urlParams_.Set("alt", alt) + urls := googleapi.ResolveRelative(c.s.BasePath, "projects/{projectId}/datasets/{datasetId}/tables/{tableId}") + urls += "?" + c.urlParams_.Encode() + req, _ := http.NewRequest("GET", urls, body) + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "projectId": c.projectId, + "datasetId": c.datasetId, + "tableId": c.tableId, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "bigquery.tables.get" call. +// Exactly one of *Table or error will be non-nil. Any non-2xx status +// code is an error. Response headers are in either +// *Table.ServerResponse.Header or (if a response was returned at all) +// in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to +// check whether the returned error was because http.StatusNotModified +// was returned. +func (c *TablesGetCall) Do(opts ...googleapi.CallOption) (*Table, error) { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if res != nil && res.StatusCode == http.StatusNotModified { + if res.Body != nil { + res.Body.Close() + } + return nil, &googleapi.Error{ + Code: res.StatusCode, + Header: res.Header, + } + } + if err != nil { + return nil, err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return nil, err + } + ret := &Table{ + ServerResponse: googleapi.ServerResponse{ + Header: res.Header, + HTTPStatusCode: res.StatusCode, + }, + } + target := &ret + if err := json.NewDecoder(res.Body).Decode(target); err != nil { + return nil, err + } + return ret, nil + // { + // "description": "Gets the specified table resource by table ID. This method does not return the data in the table, it only returns the table resource, which describes the structure of this table.", + // "httpMethod": "GET", + // "id": "bigquery.tables.get", + // "parameterOrder": [ + // "projectId", + // "datasetId", + // "tableId" + // ], + // "parameters": { + // "datasetId": { + // "description": "Dataset ID of the requested table", + // "location": "path", + // "required": true, + // "type": "string" + // }, + // "projectId": { + // "description": "Project ID of the requested table", + // "location": "path", + // "required": true, + // "type": "string" + // }, + // "tableId": { + // "description": "Table ID of the requested table", + // "location": "path", + // "required": true, + // "type": "string" + // } + // }, + // "path": "projects/{projectId}/datasets/{datasetId}/tables/{tableId}", + // "response": { + // "$ref": "Table" + // }, + // "scopes": [ + // "https://www.googleapis.com/auth/bigquery", + // "https://www.googleapis.com/auth/cloud-platform", + // "https://www.googleapis.com/auth/cloud-platform.read-only" + // ] + // } + +} + +// method id "bigquery.tables.insert": + +type TablesInsertCall struct { + s *Service + projectId string + datasetId string + table *Table + urlParams_ gensupport.URLParams + ctx_ context.Context + header_ http.Header +} + +// Insert: Creates a new, empty table in the dataset. +func (r *TablesService) Insert(projectId string, datasetId string, table *Table) *TablesInsertCall { + c := &TablesInsertCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.projectId = projectId + c.datasetId = datasetId + c.table = table + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse +// for more information. +func (c *TablesInsertCall) Fields(s ...googleapi.Field) *TablesInsertCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// Context sets the context to be used in this call's Do method. Any +// pending HTTP request will be aborted if the provided context is +// canceled. +func (c *TablesInsertCall) Context(ctx context.Context) *TablesInsertCall { + c.ctx_ = ctx + return c +} + +// Header returns an http.Header that can be modified by the caller to +// add HTTP headers to the request. +func (c *TablesInsertCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *TablesInsertCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := make(http.Header) + for k, v := range c.header_ { + reqHeaders[k] = v + } + reqHeaders.Set("User-Agent", c.s.userAgent()) + reqHeaders.Set("x-goog-api-client", c.s.clientHeader()) + var body io.Reader = nil + body, err := googleapi.WithoutDataWrapper.JSONReader(c.table) + if err != nil { + return nil, err + } + reqHeaders.Set("Content-Type", "application/json") + c.urlParams_.Set("alt", alt) + urls := googleapi.ResolveRelative(c.s.BasePath, "projects/{projectId}/datasets/{datasetId}/tables") + urls += "?" + c.urlParams_.Encode() + req, _ := http.NewRequest("POST", urls, body) + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "projectId": c.projectId, + "datasetId": c.datasetId, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "bigquery.tables.insert" call. +// Exactly one of *Table or error will be non-nil. Any non-2xx status +// code is an error. Response headers are in either +// *Table.ServerResponse.Header or (if a response was returned at all) +// in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to +// check whether the returned error was because http.StatusNotModified +// was returned. +func (c *TablesInsertCall) Do(opts ...googleapi.CallOption) (*Table, error) { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if res != nil && res.StatusCode == http.StatusNotModified { + if res.Body != nil { + res.Body.Close() + } + return nil, &googleapi.Error{ + Code: res.StatusCode, + Header: res.Header, + } + } + if err != nil { + return nil, err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return nil, err + } + ret := &Table{ + ServerResponse: googleapi.ServerResponse{ + Header: res.Header, + HTTPStatusCode: res.StatusCode, + }, + } + target := &ret + if err := json.NewDecoder(res.Body).Decode(target); err != nil { + return nil, err + } + return ret, nil + // { + // "description": "Creates a new, empty table in the dataset.", + // "httpMethod": "POST", + // "id": "bigquery.tables.insert", + // "parameterOrder": [ + // "projectId", + // "datasetId" + // ], + // "parameters": { + // "datasetId": { + // "description": "Dataset ID of the new table", + // "location": "path", + // "required": true, + // "type": "string" + // }, + // "projectId": { + // "description": "Project ID of the new table", + // "location": "path", + // "required": true, + // "type": "string" + // } + // }, + // "path": "projects/{projectId}/datasets/{datasetId}/tables", + // "request": { + // "$ref": "Table" + // }, + // "response": { + // "$ref": "Table" + // }, + // "scopes": [ + // "https://www.googleapis.com/auth/bigquery", + // "https://www.googleapis.com/auth/cloud-platform" + // ] + // } + +} + +// method id "bigquery.tables.list": + +type TablesListCall struct { + s *Service + projectId string + datasetId string + urlParams_ gensupport.URLParams + ifNoneMatch_ string + ctx_ context.Context + header_ http.Header +} + +// List: Lists all tables in the specified dataset. Requires the READER +// dataset role. +func (r *TablesService) List(projectId string, datasetId string) *TablesListCall { + c := &TablesListCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.projectId = projectId + c.datasetId = datasetId + return c +} + +// MaxResults sets the optional parameter "maxResults": Maximum number +// of results to return +func (c *TablesListCall) MaxResults(maxResults int64) *TablesListCall { + c.urlParams_.Set("maxResults", fmt.Sprint(maxResults)) + return c +} + +// PageToken sets the optional parameter "pageToken": Page token, +// returned by a previous call, to request the next page of results +func (c *TablesListCall) PageToken(pageToken string) *TablesListCall { + c.urlParams_.Set("pageToken", pageToken) + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse +// for more information. +func (c *TablesListCall) Fields(s ...googleapi.Field) *TablesListCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// IfNoneMatch sets the optional parameter which makes the operation +// fail if the object's ETag matches the given value. This is useful for +// getting updates only after the object has changed since the last +// request. Use googleapi.IsNotModified to check whether the response +// error from Do is the result of In-None-Match. +func (c *TablesListCall) IfNoneMatch(entityTag string) *TablesListCall { + c.ifNoneMatch_ = entityTag + return c +} + +// Context sets the context to be used in this call's Do method. Any +// pending HTTP request will be aborted if the provided context is +// canceled. +func (c *TablesListCall) Context(ctx context.Context) *TablesListCall { + c.ctx_ = ctx + return c +} + +// Header returns an http.Header that can be modified by the caller to +// add HTTP headers to the request. +func (c *TablesListCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *TablesListCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := make(http.Header) + for k, v := range c.header_ { + reqHeaders[k] = v + } + reqHeaders.Set("User-Agent", c.s.userAgent()) + reqHeaders.Set("x-goog-api-client", c.s.clientHeader()) + if c.ifNoneMatch_ != "" { + reqHeaders.Set("If-None-Match", c.ifNoneMatch_) + } + var body io.Reader = nil + c.urlParams_.Set("alt", alt) + urls := googleapi.ResolveRelative(c.s.BasePath, "projects/{projectId}/datasets/{datasetId}/tables") + urls += "?" + c.urlParams_.Encode() + req, _ := http.NewRequest("GET", urls, body) + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "projectId": c.projectId, + "datasetId": c.datasetId, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "bigquery.tables.list" call. +// Exactly one of *TableList or error will be non-nil. Any non-2xx +// status code is an error. Response headers are in either +// *TableList.ServerResponse.Header or (if a response was returned at +// all) in error.(*googleapi.Error).Header. Use googleapi.IsNotModified +// to check whether the returned error was because +// http.StatusNotModified was returned. +func (c *TablesListCall) Do(opts ...googleapi.CallOption) (*TableList, error) { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if res != nil && res.StatusCode == http.StatusNotModified { + if res.Body != nil { + res.Body.Close() + } + return nil, &googleapi.Error{ + Code: res.StatusCode, + Header: res.Header, + } + } + if err != nil { + return nil, err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return nil, err + } + ret := &TableList{ + ServerResponse: googleapi.ServerResponse{ + Header: res.Header, + HTTPStatusCode: res.StatusCode, + }, + } + target := &ret + if err := json.NewDecoder(res.Body).Decode(target); err != nil { + return nil, err + } + return ret, nil + // { + // "description": "Lists all tables in the specified dataset. Requires the READER dataset role.", + // "httpMethod": "GET", + // "id": "bigquery.tables.list", + // "parameterOrder": [ + // "projectId", + // "datasetId" + // ], + // "parameters": { + // "datasetId": { + // "description": "Dataset ID of the tables to list", + // "location": "path", + // "required": true, + // "type": "string" + // }, + // "maxResults": { + // "description": "Maximum number of results to return", + // "format": "uint32", + // "location": "query", + // "type": "integer" + // }, + // "pageToken": { + // "description": "Page token, returned by a previous call, to request the next page of results", + // "location": "query", + // "type": "string" + // }, + // "projectId": { + // "description": "Project ID of the tables to list", + // "location": "path", + // "required": true, + // "type": "string" + // } + // }, + // "path": "projects/{projectId}/datasets/{datasetId}/tables", + // "response": { + // "$ref": "TableList" + // }, + // "scopes": [ + // "https://www.googleapis.com/auth/bigquery", + // "https://www.googleapis.com/auth/cloud-platform", + // "https://www.googleapis.com/auth/cloud-platform.read-only" + // ] + // } + +} + +// Pages invokes f for each page of results. +// A non-nil error returned from f will halt the iteration. +// The provided context supersedes any context provided to the Context method. +func (c *TablesListCall) Pages(ctx context.Context, f func(*TableList) error) error { + c.ctx_ = ctx + defer c.PageToken(c.urlParams_.Get("pageToken")) // reset paging to original point + for { + x, err := c.Do() + if err != nil { + return err + } + if err := f(x); err != nil { + return err + } + if x.NextPageToken == "" { + return nil + } + c.PageToken(x.NextPageToken) + } +} + +// method id "bigquery.tables.patch": + +type TablesPatchCall struct { + s *Service + projectId string + datasetId string + tableId string + table *Table + urlParams_ gensupport.URLParams + ctx_ context.Context + header_ http.Header +} + +// Patch: Updates information in an existing table. The update method +// replaces the entire table resource, whereas the patch method only +// replaces fields that are provided in the submitted table resource. +// This method supports patch semantics. +func (r *TablesService) Patch(projectId string, datasetId string, tableId string, table *Table) *TablesPatchCall { + c := &TablesPatchCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.projectId = projectId + c.datasetId = datasetId + c.tableId = tableId + c.table = table + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse +// for more information. +func (c *TablesPatchCall) Fields(s ...googleapi.Field) *TablesPatchCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// Context sets the context to be used in this call's Do method. Any +// pending HTTP request will be aborted if the provided context is +// canceled. +func (c *TablesPatchCall) Context(ctx context.Context) *TablesPatchCall { + c.ctx_ = ctx + return c +} + +// Header returns an http.Header that can be modified by the caller to +// add HTTP headers to the request. +func (c *TablesPatchCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *TablesPatchCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := make(http.Header) + for k, v := range c.header_ { + reqHeaders[k] = v + } + reqHeaders.Set("User-Agent", c.s.userAgent()) + reqHeaders.Set("x-goog-api-client", c.s.clientHeader()) + var body io.Reader = nil + body, err := googleapi.WithoutDataWrapper.JSONReader(c.table) + if err != nil { + return nil, err + } + reqHeaders.Set("Content-Type", "application/json") + c.urlParams_.Set("alt", alt) + urls := googleapi.ResolveRelative(c.s.BasePath, "projects/{projectId}/datasets/{datasetId}/tables/{tableId}") + urls += "?" + c.urlParams_.Encode() + req, _ := http.NewRequest("PATCH", urls, body) + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "projectId": c.projectId, + "datasetId": c.datasetId, + "tableId": c.tableId, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "bigquery.tables.patch" call. +// Exactly one of *Table or error will be non-nil. Any non-2xx status +// code is an error. Response headers are in either +// *Table.ServerResponse.Header or (if a response was returned at all) +// in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to +// check whether the returned error was because http.StatusNotModified +// was returned. +func (c *TablesPatchCall) Do(opts ...googleapi.CallOption) (*Table, error) { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if res != nil && res.StatusCode == http.StatusNotModified { + if res.Body != nil { + res.Body.Close() + } + return nil, &googleapi.Error{ + Code: res.StatusCode, + Header: res.Header, + } + } + if err != nil { + return nil, err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return nil, err + } + ret := &Table{ + ServerResponse: googleapi.ServerResponse{ + Header: res.Header, + HTTPStatusCode: res.StatusCode, + }, + } + target := &ret + if err := json.NewDecoder(res.Body).Decode(target); err != nil { + return nil, err + } + return ret, nil + // { + // "description": "Updates information in an existing table. The update method replaces the entire table resource, whereas the patch method only replaces fields that are provided in the submitted table resource. This method supports patch semantics.", + // "httpMethod": "PATCH", + // "id": "bigquery.tables.patch", + // "parameterOrder": [ + // "projectId", + // "datasetId", + // "tableId" + // ], + // "parameters": { + // "datasetId": { + // "description": "Dataset ID of the table to update", + // "location": "path", + // "required": true, + // "type": "string" + // }, + // "projectId": { + // "description": "Project ID of the table to update", + // "location": "path", + // "required": true, + // "type": "string" + // }, + // "tableId": { + // "description": "Table ID of the table to update", + // "location": "path", + // "required": true, + // "type": "string" + // } + // }, + // "path": "projects/{projectId}/datasets/{datasetId}/tables/{tableId}", + // "request": { + // "$ref": "Table" + // }, + // "response": { + // "$ref": "Table" + // }, + // "scopes": [ + // "https://www.googleapis.com/auth/bigquery", + // "https://www.googleapis.com/auth/cloud-platform" + // ] + // } + +} + +// method id "bigquery.tables.update": + +type TablesUpdateCall struct { + s *Service + projectId string + datasetId string + tableId string + table *Table + urlParams_ gensupport.URLParams + ctx_ context.Context + header_ http.Header +} + +// Update: Updates information in an existing table. The update method +// replaces the entire table resource, whereas the patch method only +// replaces fields that are provided in the submitted table resource. +func (r *TablesService) Update(projectId string, datasetId string, tableId string, table *Table) *TablesUpdateCall { + c := &TablesUpdateCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.projectId = projectId + c.datasetId = datasetId + c.tableId = tableId + c.table = table + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse +// for more information. +func (c *TablesUpdateCall) Fields(s ...googleapi.Field) *TablesUpdateCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// Context sets the context to be used in this call's Do method. Any +// pending HTTP request will be aborted if the provided context is +// canceled. +func (c *TablesUpdateCall) Context(ctx context.Context) *TablesUpdateCall { + c.ctx_ = ctx + return c +} + +// Header returns an http.Header that can be modified by the caller to +// add HTTP headers to the request. +func (c *TablesUpdateCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *TablesUpdateCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := make(http.Header) + for k, v := range c.header_ { + reqHeaders[k] = v + } + reqHeaders.Set("User-Agent", c.s.userAgent()) + reqHeaders.Set("x-goog-api-client", c.s.clientHeader()) + var body io.Reader = nil + body, err := googleapi.WithoutDataWrapper.JSONReader(c.table) + if err != nil { + return nil, err + } + reqHeaders.Set("Content-Type", "application/json") + c.urlParams_.Set("alt", alt) + urls := googleapi.ResolveRelative(c.s.BasePath, "projects/{projectId}/datasets/{datasetId}/tables/{tableId}") + urls += "?" + c.urlParams_.Encode() + req, _ := http.NewRequest("PUT", urls, body) + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "projectId": c.projectId, + "datasetId": c.datasetId, + "tableId": c.tableId, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "bigquery.tables.update" call. +// Exactly one of *Table or error will be non-nil. Any non-2xx status +// code is an error. Response headers are in either +// *Table.ServerResponse.Header or (if a response was returned at all) +// in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to +// check whether the returned error was because http.StatusNotModified +// was returned. +func (c *TablesUpdateCall) Do(opts ...googleapi.CallOption) (*Table, error) { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if res != nil && res.StatusCode == http.StatusNotModified { + if res.Body != nil { + res.Body.Close() + } + return nil, &googleapi.Error{ + Code: res.StatusCode, + Header: res.Header, + } + } + if err != nil { + return nil, err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return nil, err + } + ret := &Table{ + ServerResponse: googleapi.ServerResponse{ + Header: res.Header, + HTTPStatusCode: res.StatusCode, + }, + } + target := &ret + if err := json.NewDecoder(res.Body).Decode(target); err != nil { + return nil, err + } + return ret, nil + // { + // "description": "Updates information in an existing table. The update method replaces the entire table resource, whereas the patch method only replaces fields that are provided in the submitted table resource.", + // "httpMethod": "PUT", + // "id": "bigquery.tables.update", + // "parameterOrder": [ + // "projectId", + // "datasetId", + // "tableId" + // ], + // "parameters": { + // "datasetId": { + // "description": "Dataset ID of the table to update", + // "location": "path", + // "required": true, + // "type": "string" + // }, + // "projectId": { + // "description": "Project ID of the table to update", + // "location": "path", + // "required": true, + // "type": "string" + // }, + // "tableId": { + // "description": "Table ID of the table to update", + // "location": "path", + // "required": true, + // "type": "string" + // } + // }, + // "path": "projects/{projectId}/datasets/{datasetId}/tables/{tableId}", + // "request": { + // "$ref": "Table" + // }, + // "response": { + // "$ref": "Table" + // }, + // "scopes": [ + // "https://www.googleapis.com/auth/bigquery", + // "https://www.googleapis.com/auth/cloud-platform" + // ] + // } + +} diff --git a/vendor/google.golang.org/api/compute/v1/compute-api.json b/vendor/google.golang.org/api/compute/v1/compute-api.json index 391300e3c..1a90deafc 100644 --- a/vendor/google.golang.org/api/compute/v1/compute-api.json +++ b/vendor/google.golang.org/api/compute/v1/compute-api.json @@ -1,11 +1,11 @@ { "kind": "discovery#restDescription", - "etag": "\"tbys6C40o18GZwyMen5GMkdK-3s/BIPueDp4_YHmOXWnzCh7vT7JOHQ\"", + "etag": "\"YWOzh2SDasdU84ArJnpYek-OMdg/Jd_rZl9yiuNZcWvcgDDlnKBhwlY\"", "discoveryVersion": "v1", "id": "compute:v1", "name": "compute", "version": "v1", - "revision": "20161123", + "revision": "20170329", "title": "Compute Engine API", "description": "Creates and runs virtual machines on Google Cloud Platform.", "ownerDomain": "google.com", @@ -103,7 +103,7 @@ }, "name": { "type": "string", - "description": "Name of this access configuration." + "description": "The name of this access configuration. The default and recommended name is External NAT but you can use any arbitrary string you would like. For example, My external IP or Network Access." }, "natIP": { "type": "string", @@ -282,6 +282,7 @@ "NOT_CRITICAL_ERROR", "NO_RESULTS_ON_PAGE", "REQUIRED_TOS_AGREEMENT", + "RESOURCE_IN_USE_BY_OTHER_RESOURCE_WARNING", "RESOURCE_NOT_DELETED", "SINGLE_INSTANCE_PROPERTY_TEMPLATE", "UNREACHABLE" @@ -302,6 +303,7 @@ "", "", "", + "", "" ] }, @@ -410,12 +412,7 @@ "enumDescriptions": [ "", "" - ], - "annotations": { - "required": [ - "compute.instances.insert" - ] - } + ] } } }, @@ -596,6 +593,7 @@ "NOT_CRITICAL_ERROR", "NO_RESULTS_ON_PAGE", "REQUIRED_TOS_AGREEMENT", + "RESOURCE_IN_USE_BY_OTHER_RESOURCE_WARNING", "RESOURCE_NOT_DELETED", "SINGLE_INSTANCE_PROPERTY_TEMPLATE", "UNREACHABLE" @@ -616,6 +614,7 @@ "", "", "", + "", "" ] }, @@ -794,6 +793,79 @@ } } }, + "BackendBucket": { + "id": "BackendBucket", + "type": "object", + "description": "A BackendBucket resource. This resource defines a Cloud Storage bucket.", + "properties": { + "bucketName": { + "type": "string", + "description": "Cloud Storage bucket name." + }, + "creationTimestamp": { + "type": "string", + "description": "[Output Only] Creation timestamp in RFC3339 text format." + }, + "description": { + "type": "string", + "description": "An optional textual description of the resource; provided by the client when the resource is created." + }, + "enableCdn": { + "type": "boolean", + "description": "If true, enable Cloud CDN for this BackendBucket." + }, + "id": { + "type": "string", + "description": "[Output Only] Unique identifier for the resource; defined by the server.", + "format": "uint64" + }, + "kind": { + "type": "string", + "description": "Type of the resource.", + "default": "compute#backendBucket" + }, + "name": { + "type": "string", + "description": "Name of the resource. Provided by the client when the resource is created. The name must be 1-63 characters long, and comply with RFC1035. Specifically, the name must be 1-63 characters long and match the regular expression [a-z]([-a-z0-9]*[a-z0-9])? which means the first character must be a lowercase letter, and all following characters must be a dash, lowercase letter, or digit, except the last character, which cannot be a dash.", + "pattern": "[a-z](?:[-a-z0-9]{0,61}[a-z0-9])?" + }, + "selfLink": { + "type": "string", + "description": "[Output Only] Server-defined URL for the resource." + } + } + }, + "BackendBucketList": { + "id": "BackendBucketList", + "type": "object", + "description": "Contains a list of BackendBucket resources.", + "properties": { + "id": { + "type": "string", + "description": "[Output Only] Unique identifier for the resource; defined by the server." + }, + "items": { + "type": "array", + "description": "A list of BackendBucket resources.", + "items": { + "$ref": "BackendBucket" + } + }, + "kind": { + "type": "string", + "description": "Type of resource.", + "default": "compute#backendBucketList" + }, + "nextPageToken": { + "type": "string", + "description": "[Output Only] A token used to continue a truncated list request." + }, + "selfLink": { + "type": "string", + "description": "[Output Only] Server-defined URL for this resource." + } + } + }, "BackendService": { "id": "BackendService", "type": "object", @@ -811,6 +883,10 @@ "$ref": "Backend" } }, + "cdnPolicy": { + "$ref": "BackendServiceCdnPolicy", + "description": "Cloud CDN configuration for this BackendService." + }, "connectionDraining": { "$ref": "ConnectionDraining" }, @@ -877,7 +953,7 @@ }, "protocol": { "type": "string", - "description": "The protocol this BackendService uses to communicate with backends.\n\nPossible values are HTTP, HTTPS, HTTP2, TCP and SSL. The default is HTTP.\n\nFor internal load balancing, the possible values are TCP and UDP, and the default is TCP.", + "description": "The protocol this BackendService uses to communicate with backends.\n\nPossible values are HTTP, HTTPS, TCP, and SSL. The default is HTTP.\n\nFor internal load balancing, the possible values are TCP and UDP, and the default is TCP.", "enum": [ "HTTP", "HTTPS", @@ -958,6 +1034,17 @@ } } }, + "BackendServiceCdnPolicy": { + "id": "BackendServiceCdnPolicy", + "type": "object", + "description": "Message containing Cloud CDN configuration for a backend service.", + "properties": { + "cacheKeyPolicy": { + "$ref": "CacheKeyPolicy", + "description": "The CacheKeyPolicy for this CdnPolicy." + } + } + }, "BackendServiceGroupHealth": { "id": "BackendServiceGroupHealth", "type": "object", @@ -998,7 +1085,7 @@ }, "nextPageToken": { "type": "string", - "description": "[Output Only] A token used to continue a truncated list request." + "description": "[Output Only] This token allows you to get the next page of results for list requests. If the number of results is larger than maxResults, use the nextPageToken as a value for the query parameter pageToken in the next list request. Subsequent list requests will have their own nextPageToken to continue paging through the results." }, "selfLink": { "type": "string", @@ -1038,6 +1125,7 @@ "NOT_CRITICAL_ERROR", "NO_RESULTS_ON_PAGE", "REQUIRED_TOS_AGREEMENT", + "RESOURCE_IN_USE_BY_OTHER_RESOURCE_WARNING", "RESOURCE_NOT_DELETED", "SINGLE_INSTANCE_PROPERTY_TEMPLATE", "UNREACHABLE" @@ -1058,6 +1146,7 @@ "", "", "", + "", "" ] }, @@ -1099,6 +1188,39 @@ } } }, + "CacheKeyPolicy": { + "id": "CacheKeyPolicy", + "type": "object", + "description": "Message containing what to include in the cache key for a request for Cloud CDN.", + "properties": { + "includeHost": { + "type": "boolean", + "description": "If true, requests to different hosts will be cached separately." + }, + "includeProtocol": { + "type": "boolean", + "description": "If true, http and https requests will be cached separately." + }, + "includeQueryString": { + "type": "boolean", + "description": "If true, include query string parameters in the cache key according to query_string_whitelist and query_string_blacklist. If neither is set, the entire query string will be included. If false, the query string will be excluded from the cache key entirely." + }, + "queryStringBlacklist": { + "type": "array", + "description": "Names of query string parameters to exclude in cache keys. All other parameters will be included. Either specify query_string_whitelist or query_string_blacklist, not both. '&' and '=' will be percent encoded and not treated as delimiters.", + "items": { + "type": "string" + } + }, + "queryStringWhitelist": { + "type": "array", + "description": "Names of query string parameters to include in cache keys. All other parameters will be excluded. Either specify query_string_whitelist or query_string_blacklist, not both. '&' and '=' will be percent encoded and not treated as delimiters.", + "items": { + "type": "string" + } + } + } + }, "ConnectionDraining": { "id": "ConnectionDraining", "type": "object", @@ -1322,7 +1444,7 @@ }, "nextPageToken": { "type": "string", - "description": "[Output Only] This token allows you to get the next page of results for list requests. If the number of results is larger than maxResults, use the nextPageToken as a value for the query parameter pageToken in the next list request. Subsequent list requests will have their own nextPageToken to continue paging through the results." + "description": "[Output Only] This token allows you to get the next page of results for list requests. If the number of results is larger than maxResults, use the nextPageToken as a value for the query parameter pageToken in the next list request. Subsequent list requests will have their own nextPageToken to continue paging through the results. Acceptable values are 0 to 500, inclusive. (Default: 500)" }, "selfLink": { "type": "string", @@ -1337,11 +1459,11 @@ "properties": { "id": { "type": "string", - "description": "[Output Only] The unique identifier for the resource. This identifier is defined by the server." + "description": "[Output Only] Unique identifier for the resource; defined by the server." }, "items": { "type": "array", - "description": "[Output Only] A list of persistent disks.", + "description": "A list of Disk resources.", "items": { "$ref": "Disk" } @@ -1353,7 +1475,7 @@ }, "nextPageToken": { "type": "string", - "description": "[Output Only] This token allows you to get the next page of results for list requests. If the number of results is larger than maxResults, use the nextPageToken as a value for the query parameter pageToken in the next list request. Subsequent list requests will have their own nextPageToken to continue paging through the results." + "description": "This token allows you to get the next page of results for list requests. If the number of results is larger than maxResults, use the nextPageToken as a value for the query parameter pageToken in the next list request. Subsequent list requests will have their own nextPageToken to continue paging through the results." }, "selfLink": { "type": "string", @@ -1520,6 +1642,7 @@ "NOT_CRITICAL_ERROR", "NO_RESULTS_ON_PAGE", "REQUIRED_TOS_AGREEMENT", + "RESOURCE_IN_USE_BY_OTHER_RESOURCE_WARNING", "RESOURCE_NOT_DELETED", "SINGLE_INSTANCE_PROPERTY_TEMPLATE", "UNREACHABLE" @@ -1540,6 +1663,7 @@ "", "", "", + "", "" ] }, @@ -1611,6 +1735,7 @@ "NOT_CRITICAL_ERROR", "NO_RESULTS_ON_PAGE", "REQUIRED_TOS_AGREEMENT", + "RESOURCE_IN_USE_BY_OTHER_RESOURCE_WARNING", "RESOURCE_NOT_DELETED", "SINGLE_INSTANCE_PROPERTY_TEMPLATE", "UNREACHABLE" @@ -1631,6 +1756,7 @@ "", "", "", + "", "" ] }, @@ -1723,7 +1849,7 @@ }, "sourceRanges": { "type": "array", - "description": "If source ranges are specified, the firewall will apply only to traffic that has source IP address in these ranges. These ranges must be expressed in CIDR format. One or both of sourceRanges and sourceTags may be set. If both properties are set, the firewall will apply to traffic that has source IP address within sourceRanges OR the source IP that belongs to a tag listed in the sourceTags property. The connection does not need to match both properties for the firewall to apply.", + "description": "If source ranges are specified, the firewall will apply only to traffic that has source IP address in these ranges. These ranges must be expressed in CIDR format. One or both of sourceRanges and sourceTags may be set. If both properties are set, the firewall will apply to traffic that has source IP address within sourceRanges OR the source IP that belongs to a tag listed in the sourceTags property. The connection does not need to match both properties for the firewall to apply. Only IPv4 is supported.", "items": { "type": "string" } @@ -1782,14 +1908,15 @@ "properties": { "IPAddress": { "type": "string", - "description": "The IP address that this forwarding rule is serving on behalf of.\n\nFor global forwarding rules, the address must be a global IP; for regional forwarding rules, the address must live in the same region as the forwarding rule. By default, this field is empty and an ephemeral IP from the same scope (global or regional) will be assigned.\n\nWhen the load balancing scheme is INTERNAL, this can only be an RFC 1918 IP address belonging to the network/subnetwork configured for the forwarding rule. A reserved address cannot be used. If the field is empty, the IP address will be automatically allocated from the internal IP range of the subnetwork or network configured for this forwarding rule." + "description": "The IP address that this forwarding rule is serving on behalf of.\n\nFor global forwarding rules, the address must be a global IP. For regional forwarding rules, the address must live in the same region as the forwarding rule. By default, this field is empty and an ephemeral IP from the same scope (global or regional) will be assigned.\n\nWhen the load balancing scheme is INTERNAL, this can only be an RFC 1918 IP address belonging to the network/subnetwork configured for the forwarding rule. A reserved address cannot be used. If the field is empty, the IP address will be automatically allocated from the internal IP range of the subnetwork or network configured for this forwarding rule. Only IPv4 is supported." }, "IPProtocol": { "type": "string", - "description": "The IP protocol to which this rule applies. Valid options are TCP, UDP, ESP, AH, SCTP or ICMP.\n\nWhen the load balancing scheme is INTERNAL\u003c/code, only TCP and UDP are valid.", + "description": "The IP protocol to which this rule applies. Valid options are TCP, UDP, ESP, AH, SCTP or ICMP.\n\nWhen the load balancing scheme is INTERNAL, only TCP and UDP are valid.", "enum": [ "AH", "ESP", + "ICMP", "SCTP", "TCP", "UDP" @@ -1799,6 +1926,7 @@ "", "", "", + "", "" ] }, @@ -1826,7 +1954,7 @@ }, "loadBalancingScheme": { "type": "string", - "description": "This signifies what the ForwardingRule will be used for and can only take the following values: INTERNAL EXTERNAL The value of INTERNAL means that this will be used for Internal Network Load Balancing (TCP, UDP). The value of EXTERNAL means that this will be used for External Load Balancing (HTTP(S) LB, External TCP/UDP LB, SSL Proxy)", + "description": "This signifies what the ForwardingRule will be used for and can only take the following values: INTERNAL, EXTERNAL The value of INTERNAL means that this will be used for Internal Network Load Balancing (TCP, UDP). The value of EXTERNAL means that this will be used for External Load Balancing (HTTP(S) LB, External TCP/UDP LB, SSL Proxy)", "enum": [ "EXTERNAL", "INTERNAL", @@ -1853,7 +1981,7 @@ }, "ports": { "type": "array", - "description": "This field is not used for external load balancing.\n\nWhen the load balancing scheme is INTERNAL, a single port or a comma separated list of ports can be configured. Only packets addressed to these ports will be forwarded to the backends configured with this forwarding rule. If the port list is not provided then all ports are allowed to pass through.\n\nYou may specify a maximum of up to 5 ports.", + "description": "This field is not used for external load balancing.\n\nWhen the load balancing scheme is INTERNAL, a single port or a comma separated list of ports can be configured. Only packets addressed to these ports will be forwarded to the backends configured with this forwarding rule.\n\nYou may specify a maximum of up to 5 ports.", "items": { "type": "string" } @@ -1872,7 +2000,7 @@ }, "target": { "type": "string", - "description": "The URL of the target resource to receive the matched traffic. For regional forwarding rules, this target must live in the same region as the forwarding rule. For global forwarding rules, this target must be a global TargetHttpProxy or TargetHttpsProxy resource. The forwarded traffic must be of a type appropriate to the target object. For example, TargetHttpProxy requires HTTP traffic, and TargetHttpsProxy requires HTTPS traffic.\n\nThis field is not used for internal load balancing." + "description": "The URL of the target resource to receive the matched traffic. For regional forwarding rules, this target must live in the same region as the forwarding rule. For global forwarding rules, this target must be a global load balancing resource. The forwarded traffic must be of a type appropriate to the target object.\n\nThis field is not used for internal load balancing." } } }, @@ -1970,6 +2098,7 @@ "NOT_CRITICAL_ERROR", "NO_RESULTS_ON_PAGE", "REQUIRED_TOS_AGREEMENT", + "RESOURCE_IN_USE_BY_OTHER_RESOURCE_WARNING", "RESOURCE_NOT_DELETED", "SINGLE_INSTANCE_PROPERTY_TEMPLATE", "UNREACHABLE" @@ -1990,6 +2119,7 @@ "", "", "", + "", "" ] }, @@ -2049,7 +2179,7 @@ }, "port": { "type": "integer", - "description": "The TCP port number for the health check request. The default value is 80.", + "description": "The TCP port number for the health check request. The default value is 80. Valid values are 1 through 65535.", "format": "int32" }, "portName": { @@ -2084,7 +2214,7 @@ }, "port": { "type": "integer", - "description": "The TCP port number for the health check request. The default value is 443.", + "description": "The TCP port number for the health check request. The default value is 443. Valid values are 1 through 65535.", "format": "int32" }, "portName": { @@ -2709,7 +2839,13 @@ }, "name": { "type": "string", - "description": "The name of the resource, provided by the client when initially creating the resource. The resource name must be 1-63 characters long, and comply with RFC1035. Specifically, the name must be 1-63 characters long and match the regular expression [a-z]([-a-z0-9]*[a-z0-9])? which means the first character must be a lowercase letter, and all following characters must be a dash, lowercase letter, or digit, except the last character, which cannot be a dash." + "description": "The name of the resource, provided by the client when initially creating the resource. The resource name must be 1-63 characters long, and comply with RFC1035. Specifically, the name must be 1-63 characters long and match the regular expression [a-z]([-a-z0-9]*[a-z0-9])? which means the first character must be a lowercase letter, and all following characters must be a dash, lowercase letter, or digit, except the last character, which cannot be a dash.", + "pattern": "[a-z](?:[-a-z0-9]{0,61}[a-z0-9])?", + "annotations": { + "required": [ + "compute.instances.insert" + ] + } }, "networkInterfaces": { "type": "array", @@ -2720,7 +2856,7 @@ }, "scheduling": { "$ref": "Scheduling", - "description": "Scheduling options for this instance." + "description": "Sets the scheduling options for this instance." }, "selfLink": { "type": "string", @@ -2728,7 +2864,7 @@ }, "serviceAccounts": { "type": "array", - "description": "A list of service accounts, with their specified scopes, authorized for this instance. Service accounts generate access tokens that can be accessed through the metadata server and used to authenticate applications on the instance. See Service Accounts for more information.", + "description": "A list of service accounts, with their specified scopes, authorized for this instance. Only one service account per VM instance is supported.\n\nService accounts generate access tokens that can be accessed through the metadata server and used to authenticate applications on the instance. See Service Accounts for more information.", "items": { "$ref": "ServiceAccount" } @@ -3225,6 +3361,7 @@ "NOT_CRITICAL_ERROR", "NO_RESULTS_ON_PAGE", "REQUIRED_TOS_AGREEMENT", + "RESOURCE_IN_USE_BY_OTHER_RESOURCE_WARNING", "RESOURCE_NOT_DELETED", "SINGLE_INSTANCE_PROPERTY_TEMPLATE", "UNREACHABLE" @@ -3245,6 +3382,7 @@ "", "", "", + "", "" ] }, @@ -3407,6 +3545,7 @@ "NOT_CRITICAL_ERROR", "NO_RESULTS_ON_PAGE", "REQUIRED_TOS_AGREEMENT", + "RESOURCE_IN_USE_BY_OTHER_RESOURCE_WARNING", "RESOURCE_NOT_DELETED", "SINGLE_INSTANCE_PROPERTY_TEMPLATE", "UNREACHABLE" @@ -3427,6 +3566,7 @@ "", "", "", + "", "" ] }, @@ -3732,6 +3872,7 @@ "NOT_CRITICAL_ERROR", "NO_RESULTS_ON_PAGE", "REQUIRED_TOS_AGREEMENT", + "RESOURCE_IN_USE_BY_OTHER_RESOURCE_WARNING", "RESOURCE_NOT_DELETED", "SINGLE_INSTANCE_PROPERTY_TEMPLATE", "UNREACHABLE" @@ -3752,6 +3893,7 @@ "", "", "", + "", "" ] }, @@ -3790,6 +3932,23 @@ } } }, + "InstancesSetServiceAccountRequest": { + "id": "InstancesSetServiceAccountRequest", + "type": "object", + "properties": { + "email": { + "type": "string", + "description": "Email address of the service account." + }, + "scopes": { + "type": "array", + "description": "The list of scopes to be made available for this service account.", + "items": { + "type": "string" + } + } + } + }, "InstancesStartWithEncryptionKeyRequest": { "id": "InstancesStartWithEncryptionKeyRequest", "type": "object", @@ -4012,6 +4171,7 @@ "NOT_CRITICAL_ERROR", "NO_RESULTS_ON_PAGE", "REQUIRED_TOS_AGREEMENT", + "RESOURCE_IN_USE_BY_OTHER_RESOURCE_WARNING", "RESOURCE_NOT_DELETED", "SINGLE_INSTANCE_PROPERTY_TEMPLATE", "UNREACHABLE" @@ -4032,6 +4192,7 @@ "", "", "", + "", "" ] }, @@ -4295,18 +4456,18 @@ "$ref": "AccessConfig" } }, + "kind": { + "type": "string", + "description": "[Output Only] Type of the resource. Always compute#networkInterface for network interfaces.", + "default": "compute#networkInterface" + }, "name": { "type": "string", "description": "[Output Only] The name of the network interface, generated by the server. For network devices, these are eth0, eth1, etc." }, "network": { "type": "string", - "description": "URL of the network resource for this instance. This is required for creating an instance but optional when creating a firewall rule. If not specified when creating a firewall rule, the default network is used:\n\nglobal/networks/default \n\nIf you specify this property, you can specify the network as a full or partial URL. For example, the following are all valid URLs: \n- https://www.googleapis.com/compute/v1/projects/project/global/networks/network \n- projects/project/global/networks/network \n- global/networks/default", - "annotations": { - "required": [ - "compute.instances.insert" - ] - } + "description": "URL of the network resource for this instance. When creating an instance, if neither the network nor the subnetwork is specified, the default network global/networks/default is used; if the network is not specified but the subnetwork is specified, the network is inferred.\n\nThis field is optional when creating a firewall rule. If not specified when creating a firewall rule, the default network global/networks/default is used.\n\nIf you specify this property, you can specify the network as a full or partial URL. For example, the following are all valid URLs: \n- https://www.googleapis.com/compute/v1/projects/project/global/networks/network \n- projects/project/global/networks/network \n- global/networks/default" }, "networkIP": { "type": "string", @@ -4360,7 +4521,7 @@ }, "creationTimestamp": { "type": "string", - "description": "[Output Only] Creation timestamp in RFC3339 text format." + "description": "[Deprecated] This field is deprecated." }, "description": { "type": "string", @@ -4499,6 +4660,7 @@ "NOT_CRITICAL_ERROR", "NO_RESULTS_ON_PAGE", "REQUIRED_TOS_AGREEMENT", + "RESOURCE_IN_USE_BY_OTHER_RESOURCE_WARNING", "RESOURCE_NOT_DELETED", "SINGLE_INSTANCE_PROPERTY_TEMPLATE", "UNREACHABLE" @@ -4519,6 +4681,7 @@ "", "", "", + "", "" ] }, @@ -4646,6 +4809,7 @@ "NOT_CRITICAL_ERROR", "NO_RESULTS_ON_PAGE", "REQUIRED_TOS_AGREEMENT", + "RESOURCE_IN_USE_BY_OTHER_RESOURCE_WARNING", "RESOURCE_NOT_DELETED", "SINGLE_INSTANCE_PROPERTY_TEMPLATE", "UNREACHABLE" @@ -4666,6 +4830,7 @@ "", "", "", + "", "" ] }, @@ -4812,8 +4977,10 @@ "description": "[Output Only] Name of the quota metric.", "enum": [ "AUTOSCALERS", + "BACKEND_BUCKETS", "BACKEND_SERVICES", "CPUS", + "CPUS_ALL_REGIONS", "DISKS_TOTAL_GB", "FIREWALLS", "FORWARDING_RULES", @@ -4842,7 +5009,6 @@ "TARGET_POOLS", "TARGET_SSL_PROXIES", "TARGET_VPN_GATEWAYS", - "TOTAL_CPUS", "URL_MAPS", "VPN_TUNNELS" ], @@ -4880,6 +5046,7 @@ "", "", "", + "", "" ] }, @@ -5052,7 +5219,7 @@ "properties": { "instances": { "type": "array", - "description": "The names of one or more instances to abandon.", + "description": "The URLs of one or more instances to abandon. This can be a full URL or a partial URL, such as zones/[ZONE]/instances/[INSTANCE_NAME].", "items": { "type": "string" } @@ -5065,7 +5232,7 @@ "properties": { "instances": { "type": "array", - "description": "The names of one or more instances to delete.", + "description": "The URLs of one or more instances to delete. This can be a full URL or a partial URL, such as zones/[ZONE]/instances/[INSTANCE_NAME].", "items": { "type": "string" } @@ -5241,7 +5408,7 @@ "Route": { "id": "Route", "type": "object", - "description": "Represents a Route resource. A route specifies how certain packets should be handled by the network. Routes are associated with instances by tags and the set of routes for a particular instance is called its routing table.\n\nFor each packet leaving a instance, the system searches that instance's routing table for a single best matching route. Routes match packets by destination IP address, preferring smaller or more specific ranges over larger ones. If there is a tie, the system selects the route with the smallest priority value. If there is still a tie, it uses the layer three and four packet headers to select just one of the remaining matching routes. The packet is then forwarded as specified by the nextHop field of the winning route - either to another instance destination, a instance gateway or a Google Compute Engine-operated gateway.\n\nPackets that do not match any route in the sending instance's routing table are dropped.", + "description": "Represents a Route resource. A route specifies how certain packets should be handled by the network. Routes are associated with instances by tags and the set of routes for a particular instance is called its routing table.\n\nFor each packet leaving a instance, the system searches that instance's routing table for a single best matching route. Routes match packets by destination IP address, preferring smaller or more specific ranges over larger ones. If there is a tie, the system selects the route with the smallest priority value. If there is still a tie, it uses the layer three and four packet headers to select just one of the remaining matching routes. The packet is then forwarded as specified by the nextHop field of the winning route - either to another instance destination, an instance gateway, or a Google Compute Engine-operated gateway.\n\nPackets that do not match any route in the sending instance's routing table are dropped.", "properties": { "creationTimestamp": { "type": "string", @@ -5253,7 +5420,7 @@ }, "destRange": { "type": "string", - "description": "The destination range of outgoing packets that this route applies to.", + "description": "The destination range of outgoing packets that this route applies to. Only IPv4 is supported.", "annotations": { "required": [ "compute.routes.insert" @@ -5299,7 +5466,7 @@ }, "nextHopIp": { "type": "string", - "description": "The network IP address of an instance that should handle matching packets." + "description": "The network IP address of an instance that should handle matching packets. Only IPv4 is supported." }, "nextHopNetwork": { "type": "string", @@ -5358,6 +5525,7 @@ "NOT_CRITICAL_ERROR", "NO_RESULTS_ON_PAGE", "REQUIRED_TOS_AGREEMENT", + "RESOURCE_IN_USE_BY_OTHER_RESOURCE_WARNING", "RESOURCE_NOT_DELETED", "SINGLE_INSTANCE_PROPERTY_TEMPLATE", "UNREACHABLE" @@ -5378,6 +5546,7 @@ "", "", "", + "", "" ] }, @@ -5566,7 +5735,7 @@ }, "ipAddress": { "type": "string", - "description": "IP address of the interface inside Google Cloud Platform." + "description": "IP address of the interface inside Google Cloud Platform. Only IPv4 is supported." }, "name": { "type": "string", @@ -5580,7 +5749,7 @@ }, "peerIpAddress": { "type": "string", - "description": "IP address of the BGP interface outside Google cloud." + "description": "IP address of the BGP interface outside Google cloud. Only IPv4 is supported." } } }, @@ -5594,7 +5763,7 @@ }, "linkedVpnTunnel": { "type": "string", - "description": "URI of linked VPN tunnel. It must be in the same region as the router. Each interface can have at most one linked resource." + "description": "URI of the linked VPN tunnel. It must be in the same region as the router. Each interface can have at most one linked resource and it could either be a VPN Tunnel or an interconnect attachment." }, "name": { "type": "string", @@ -5773,6 +5942,7 @@ "NOT_CRITICAL_ERROR", "NO_RESULTS_ON_PAGE", "REQUIRED_TOS_AGREEMENT", + "RESOURCE_IN_USE_BY_OTHER_RESOURCE_WARNING", "RESOURCE_NOT_DELETED", "SINGLE_INSTANCE_PROPERTY_TEMPLATE", "UNREACHABLE" @@ -5793,6 +5963,7 @@ "", "", "", + "", "" ] }, @@ -5827,7 +5998,7 @@ "properties": { "port": { "type": "integer", - "description": "The TCP port number for the health check request. The default value is 443.", + "description": "The TCP port number for the health check request. The default value is 443. Valid values are 1 through 65535.", "format": "int32" }, "portName": { @@ -5863,7 +6034,7 @@ "properties": { "automaticRestart": { "type": "boolean", - "description": "Specifies whether the instance should be automatically restarted if it is terminated by Compute Engine (not terminated by a user). You can only set the automatic restart option for standard instances. Preemptible instances cannot be automatically restarted." + "description": "Specifies whether the instance should be automatically restarted if it is terminated by Compute Engine (not terminated by a user). You can only set the automatic restart option for standard instances. Preemptible instances cannot be automatically restarted.\n\nBy default, this is set to true so an instance is automatically restarted if it is terminated by Compute Engine." }, "onHostMaintenance": { "type": "string", @@ -5879,7 +6050,7 @@ }, "preemptible": { "type": "boolean", - "description": "Whether the instance is preemptible." + "description": "Defines whether the instance is preemptible. This can only be set during instance creation, it cannot be set or changed after the instance has been created." } } }, @@ -5908,7 +6079,7 @@ }, "start": { "type": "string", - "description": "[Output Only] The starting byte position of the output that was returned. This should match the start parameter sent with the request. If the serial console output exceeds the size of the buffer, older output will be overwritten by newer content and the start values will be mismatched.", + "description": "The starting byte position of the output that was returned. This should match the start parameter sent with the request. If the serial console output exceeds the size of the buffer, older output will be overwritten by newer content and the start values will be mismatched.", "format": "int64" } } @@ -6156,7 +6327,7 @@ }, "ipCidrRange": { "type": "string", - "description": "The range of internal addresses that are owned by this subnetwork. Provide this property when you create the subnetwork. For example, 10.0.0.0/8 or 192.168.0.0/16. Ranges must be unique and non-overlapping within a network." + "description": "The range of internal addresses that are owned by this subnetwork. Provide this property when you create the subnetwork. For example, 10.0.0.0/8 or 192.168.0.0/16. Ranges must be unique and non-overlapping within a network. Only IPv4 is supported." }, "kind": { "type": "string", @@ -6172,6 +6343,10 @@ "type": "string", "description": "The URL of the network to which this subnetwork belongs, provided by the client when initially creating the subnetwork. Only networks that are in the distributed mode can have subnetworks." }, + "privateIpGoogleAccess": { + "type": "boolean", + "description": "Whether the VMs in this subnet can access Google services without assigned external IP addresses." + }, "region": { "type": "string", "description": "URL of the region where the Subnetwork resides." @@ -6286,6 +6461,7 @@ "NOT_CRITICAL_ERROR", "NO_RESULTS_ON_PAGE", "REQUIRED_TOS_AGREEMENT", + "RESOURCE_IN_USE_BY_OTHER_RESOURCE_WARNING", "RESOURCE_NOT_DELETED", "SINGLE_INSTANCE_PROPERTY_TEMPLATE", "UNREACHABLE" @@ -6306,6 +6482,7 @@ "", "", "", + "", "" ] }, @@ -6334,13 +6511,22 @@ } } }, + "SubnetworksSetPrivateIpGoogleAccessRequest": { + "id": "SubnetworksSetPrivateIpGoogleAccessRequest", + "type": "object", + "properties": { + "privateIpGoogleAccess": { + "type": "boolean" + } + } + }, "TCPHealthCheck": { "id": "TCPHealthCheck", "type": "object", "properties": { "port": { "type": "integer", - "description": "The TCP port number for the health check request. The default value is 80.", + "description": "The TCP port number for the health check request. The default value is 80. Valid values are 1 through 65535.", "format": "int32" }, "portName": { @@ -6692,6 +6878,7 @@ "NOT_CRITICAL_ERROR", "NO_RESULTS_ON_PAGE", "REQUIRED_TOS_AGREEMENT", + "RESOURCE_IN_USE_BY_OTHER_RESOURCE_WARNING", "RESOURCE_NOT_DELETED", "SINGLE_INSTANCE_PROPERTY_TEMPLATE", "UNREACHABLE" @@ -6712,6 +6899,7 @@ "", "", "", + "", "" ] }, @@ -6743,7 +6931,7 @@ "TargetPool": { "id": "TargetPool", "type": "object", - "description": "A TargetPool resource. This resource defines a pool of instances, associated HttpHealthCheck resources, and the fallback target pool.", + "description": "A TargetPool resource. This resource defines a pool of instances, an associated HttpHealthCheck resource, and the fallback target pool.", "properties": { "backupPool": { "type": "string", @@ -6764,7 +6952,7 @@ }, "healthChecks": { "type": "array", - "description": "A list of URLs to the HttpHealthCheck resource. A member instance in this pool is considered healthy if and only if all specified health checks pass. An empty list means all member instances will be considered healthy at all times.", + "description": "The URL of the HttpHealthCheck resource. A member instance in this pool is considered healthy if and only if the health checks pass. An empty list means all member instances will be considered healthy at all times. Only HttpHealthChecks are supported. Only one health check may be specified.", "items": { "type": "string" } @@ -6904,7 +7092,7 @@ "properties": { "healthChecks": { "type": "array", - "description": "A list of HttpHealthCheck resources to add to the target pool.", + "description": "The HttpHealthCheck to add to the target pool.", "items": { "$ref": "HealthCheckReference" } @@ -6982,6 +7170,7 @@ "NOT_CRITICAL_ERROR", "NO_RESULTS_ON_PAGE", "REQUIRED_TOS_AGREEMENT", + "RESOURCE_IN_USE_BY_OTHER_RESOURCE_WARNING", "RESOURCE_NOT_DELETED", "SINGLE_INSTANCE_PROPERTY_TEMPLATE", "UNREACHABLE" @@ -7002,6 +7191,7 @@ "", "", "", + "", "" ] }, @@ -7344,6 +7534,7 @@ "NOT_CRITICAL_ERROR", "NO_RESULTS_ON_PAGE", "REQUIRED_TOS_AGREEMENT", + "RESOURCE_IN_USE_BY_OTHER_RESOURCE_WARNING", "RESOURCE_NOT_DELETED", "SINGLE_INSTANCE_PROPERTY_TEMPLATE", "UNREACHABLE" @@ -7364,6 +7555,7 @@ "", "", "", + "", "" ] }, @@ -7631,7 +7823,7 @@ }, "localTrafficSelector": { "type": "array", - "description": "Local traffic selector to use when establishing the VPN tunnel with peer VPN gateway. The value should be a CIDR formatted string, for example: 192.168.0.0/16. The ranges should be disjoint.", + "description": "Local traffic selector to use when establishing the VPN tunnel with peer VPN gateway. The value should be a CIDR formatted string, for example: 192.168.0.0/16. The ranges should be disjoint. Only IPv4 is supported.", "items": { "type": "string" } @@ -7648,7 +7840,7 @@ }, "peerIp": { "type": "string", - "description": "IP address of the peer VPN gateway." + "description": "IP address of the peer VPN gateway. Only IPv4 is supported." }, "region": { "type": "string", @@ -7656,7 +7848,7 @@ }, "remoteTrafficSelector": { "type": "array", - "description": "Remote traffic selectors to use when establishing the VPN tunnel with peer VPN gateway. The value should be a CIDR formatted string, for example: 192.168.0.0/16. The ranges should be disjoint.", + "description": "Remote traffic selectors to use when establishing the VPN tunnel with peer VPN gateway. The value should be a CIDR formatted string, for example: 192.168.0.0/16. The ranges should be disjoint. Only IPv4 is supported.", "items": { "type": "string" } @@ -7814,6 +8006,7 @@ "NOT_CRITICAL_ERROR", "NO_RESULTS_ON_PAGE", "REQUIRED_TOS_AGREEMENT", + "RESOURCE_IN_USE_BY_OTHER_RESOURCE_WARNING", "RESOURCE_NOT_DELETED", "SINGLE_INSTANCE_PROPERTY_TEMPLATE", "UNREACHABLE" @@ -7834,6 +8027,7 @@ "", "", "", + "", "" ] }, @@ -7963,11 +8157,10 @@ }, "maxResults": { "type": "integer", - "description": "The maximum number of results per page that should be returned. If the number of available results is larger than maxResults, Compute Engine returns a nextPageToken that can be used to get the next page of results in subsequent list requests.", + "description": "The maximum number of results per page that should be returned. If the number of available results is larger than maxResults, Compute Engine returns a nextPageToken that can be used to get the next page of results in subsequent list requests. Acceptable values are 0 to 500, inclusive. (Default: 500)", "default": "500", "format": "uint32", "minimum": "0", - "maximum": "500", "location": "query" }, "orderBy": { @@ -8132,11 +8325,10 @@ }, "maxResults": { "type": "integer", - "description": "The maximum number of results per page that should be returned. If the number of available results is larger than maxResults, Compute Engine returns a nextPageToken that can be used to get the next page of results in subsequent list requests.", + "description": "The maximum number of results per page that should be returned. If the number of available results is larger than maxResults, Compute Engine returns a nextPageToken that can be used to get the next page of results in subsequent list requests. Acceptable values are 0 to 500, inclusive. (Default: 500)", "default": "500", "format": "uint32", "minimum": "0", - "maximum": "500", "location": "query" }, "orderBy": { @@ -8194,11 +8386,10 @@ }, "maxResults": { "type": "integer", - "description": "The maximum number of results per page that should be returned. If the number of available results is larger than maxResults, Compute Engine returns a nextPageToken that can be used to get the next page of results in subsequent list requests.", + "description": "The maximum number of results per page that should be returned. If the number of available results is larger than maxResults, Compute Engine returns a nextPageToken that can be used to get the next page of results in subsequent list requests. Acceptable values are 0 to 500, inclusive. (Default: 500)", "default": "500", "format": "uint32", "minimum": "0", - "maximum": "500", "location": "query" }, "orderBy": { @@ -8363,11 +8554,10 @@ }, "maxResults": { "type": "integer", - "description": "The maximum number of results per page that should be returned. If the number of available results is larger than maxResults, Compute Engine returns a nextPageToken that can be used to get the next page of results in subsequent list requests.", + "description": "The maximum number of results per page that should be returned. If the number of available results is larger than maxResults, Compute Engine returns a nextPageToken that can be used to get the next page of results in subsequent list requests. Acceptable values are 0 to 500, inclusive. (Default: 500)", "default": "500", "format": "uint32", "minimum": "0", - "maximum": "500", "location": "query" }, "orderBy": { @@ -8416,8 +8606,7 @@ "parameters": { "autoscaler": { "type": "string", - "description": "Name of the autoscaler to update.", - "required": true, + "description": "Name of the autoscaler to patch.", "pattern": "[a-z](?:[-a-z0-9]{0,61}[a-z0-9])?", "location": "query" }, @@ -8438,8 +8627,7 @@ }, "parameterOrder": [ "project", - "zone", - "autoscaler" + "zone" ], "request": { "$ref": "Autoscaler" @@ -8449,7 +8637,8 @@ }, "scopes": [ "https://www.googleapis.com/auth/cloud-platform", - "https://www.googleapis.com/auth/compute" + "https://www.googleapis.com/auth/compute", + "https://www.googleapis.com/auth/compute.readonly" ] }, "update": { @@ -8496,6 +8685,227 @@ } } }, + "backendBuckets": { + "methods": { + "delete": { + "id": "compute.backendBuckets.delete", + "path": "{project}/global/backendBuckets/{backendBucket}", + "httpMethod": "DELETE", + "description": "Deletes the specified BackendBucket resource.", + "parameters": { + "backendBucket": { + "type": "string", + "description": "Name of the BackendBucket resource to delete.", + "required": true, + "pattern": "[a-z](?:[-a-z0-9]{0,61}[a-z0-9])?", + "location": "path" + }, + "project": { + "type": "string", + "description": "Project ID for this request.", + "required": true, + "pattern": "(?:(?:[-a-z0-9]{1,63}\\.)*(?:[a-z](?:[-a-z0-9]{0,61}[a-z0-9])?):)?(?:[0-9]{1,19}|(?:[a-z0-9](?:[-a-z0-9]{0,61}[a-z0-9])?))", + "location": "path" + } + }, + "parameterOrder": [ + "project", + "backendBucket" + ], + "response": { + "$ref": "Operation" + }, + "scopes": [ + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/compute" + ] + }, + "get": { + "id": "compute.backendBuckets.get", + "path": "{project}/global/backendBuckets/{backendBucket}", + "httpMethod": "GET", + "description": "Returns the specified BackendBucket resource. Get a list of available backend buckets by making a list() request.", + "parameters": { + "backendBucket": { + "type": "string", + "description": "Name of the BackendBucket resource to return.", + "required": true, + "pattern": "[a-z](?:[-a-z0-9]{0,61}[a-z0-9])?", + "location": "path" + }, + "project": { + "type": "string", + "description": "Project ID for this request.", + "required": true, + "pattern": "(?:(?:[-a-z0-9]{1,63}\\.)*(?:[a-z](?:[-a-z0-9]{0,61}[a-z0-9])?):)?(?:[0-9]{1,19}|(?:[a-z0-9](?:[-a-z0-9]{0,61}[a-z0-9])?))", + "location": "path" + } + }, + "parameterOrder": [ + "project", + "backendBucket" + ], + "response": { + "$ref": "BackendBucket" + }, + "scopes": [ + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/compute", + "https://www.googleapis.com/auth/compute.readonly" + ] + }, + "insert": { + "id": "compute.backendBuckets.insert", + "path": "{project}/global/backendBuckets", + "httpMethod": "POST", + "description": "Creates a BackendBucket resource in the specified project using the data included in the request.", + "parameters": { + "project": { + "type": "string", + "description": "Project ID for this request.", + "required": true, + "pattern": "(?:(?:[-a-z0-9]{1,63}\\.)*(?:[a-z](?:[-a-z0-9]{0,61}[a-z0-9])?):)?(?:[0-9]{1,19}|(?:[a-z0-9](?:[-a-z0-9]{0,61}[a-z0-9])?))", + "location": "path" + } + }, + "parameterOrder": [ + "project" + ], + "request": { + "$ref": "BackendBucket" + }, + "response": { + "$ref": "Operation" + }, + "scopes": [ + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/compute" + ] + }, + "list": { + "id": "compute.backendBuckets.list", + "path": "{project}/global/backendBuckets", + "httpMethod": "GET", + "description": "Retrieves the list of BackendBucket resources available to the specified project.", + "parameters": { + "filter": { + "type": "string", + "description": "Sets a filter expression for filtering listed resources, in the form filter={expression}. Your {expression} must be in the format: field_name comparison_string literal_string.\n\nThe field_name is the name of the field you want to compare. Only atomic field types are supported (string, number, boolean). The comparison_string must be either eq (equals) or ne (not equals). The literal_string is the string value to filter to. The literal value must be valid for the type of field you are filtering by (string, number, boolean). For string fields, the literal value is interpreted as a regular expression using RE2 syntax. The literal value must match the entire field.\n\nFor example, to filter for instances that do not have a name of example-instance, you would use filter=name ne example-instance.\n\nYou can filter on nested fields. For example, you could filter on instances that have set the scheduling.automaticRestart field to true. Use filtering on nested fields to take advantage of labels to organize and search for results based on label values.\n\nTo filter on multiple expressions, provide each separate expression within parentheses. For example, (scheduling.automaticRestart eq true) (zone eq us-central1-f). Multiple expressions are treated as AND expressions, meaning that resources must match all expressions to pass the filters.", + "location": "query" + }, + "maxResults": { + "type": "integer", + "description": "The maximum number of results per page that should be returned. If the number of available results is larger than maxResults, Compute Engine returns a nextPageToken that can be used to get the next page of results in subsequent list requests. Acceptable values are 0 to 500, inclusive. (Default: 500)", + "default": "500", + "format": "uint32", + "minimum": "0", + "location": "query" + }, + "orderBy": { + "type": "string", + "description": "Sorts list results by a certain order. By default, results are returned in alphanumerical order based on the resource name.\n\nYou can also sort results in descending order based on the creation timestamp using orderBy=\"creationTimestamp desc\". This sorts results based on the creationTimestamp field in reverse chronological order (newest result first). Use this to sort resources like operations so that the newest operation is returned first.\n\nCurrently, only sorting by name or creationTimestamp desc is supported.", + "location": "query" + }, + "pageToken": { + "type": "string", + "description": "Specifies a page token to use. Set pageToken to the nextPageToken returned by a previous list request to get the next page of results.", + "location": "query" + }, + "project": { + "type": "string", + "description": "Project ID for this request.", + "required": true, + "pattern": "(?:(?:[-a-z0-9]{1,63}\\.)*(?:[a-z](?:[-a-z0-9]{0,61}[a-z0-9])?):)?(?:[0-9]{1,19}|(?:[a-z0-9](?:[-a-z0-9]{0,61}[a-z0-9])?))", + "location": "path" + } + }, + "parameterOrder": [ + "project" + ], + "response": { + "$ref": "BackendBucketList" + }, + "scopes": [ + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/compute", + "https://www.googleapis.com/auth/compute.readonly" + ] + }, + "patch": { + "id": "compute.backendBuckets.patch", + "path": "{project}/global/backendBuckets/{backendBucket}", + "httpMethod": "PATCH", + "description": "Updates the specified BackendBucket resource with the data included in the request. This method supports patch semantics.", + "parameters": { + "backendBucket": { + "type": "string", + "description": "Name of the BackendBucket resource to patch.", + "required": true, + "pattern": "[a-z](?:[-a-z0-9]{0,61}[a-z0-9])?", + "location": "path" + }, + "project": { + "type": "string", + "description": "Project ID for this request.", + "required": true, + "pattern": "(?:(?:[-a-z0-9]{1,63}\\.)*(?:[a-z](?:[-a-z0-9]{0,61}[a-z0-9])?):)?(?:[0-9]{1,19}|(?:[a-z0-9](?:[-a-z0-9]{0,61}[a-z0-9])?))", + "location": "path" + } + }, + "parameterOrder": [ + "project", + "backendBucket" + ], + "request": { + "$ref": "BackendBucket" + }, + "response": { + "$ref": "Operation" + }, + "scopes": [ + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/compute", + "https://www.googleapis.com/auth/compute.readonly" + ] + }, + "update": { + "id": "compute.backendBuckets.update", + "path": "{project}/global/backendBuckets/{backendBucket}", + "httpMethod": "PUT", + "description": "Updates the specified BackendBucket resource with the data included in the request.", + "parameters": { + "backendBucket": { + "type": "string", + "description": "Name of the BackendBucket resource to update.", + "required": true, + "pattern": "[a-z](?:[-a-z0-9]{0,61}[a-z0-9])?", + "location": "path" + }, + "project": { + "type": "string", + "description": "Project ID for this request.", + "required": true, + "pattern": "(?:(?:[-a-z0-9]{1,63}\\.)*(?:[a-z](?:[-a-z0-9]{0,61}[a-z0-9])?):)?(?:[0-9]{1,19}|(?:[a-z0-9](?:[-a-z0-9]{0,61}[a-z0-9])?))", + "location": "path" + } + }, + "parameterOrder": [ + "project", + "backendBucket" + ], + "request": { + "$ref": "BackendBucket" + }, + "response": { + "$ref": "Operation" + }, + "scopes": [ + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/compute" + ] + } + } + }, "backendServices": { "methods": { "aggregatedList": { @@ -8511,11 +8921,10 @@ }, "maxResults": { "type": "integer", - "description": "The maximum number of results per page that should be returned. If the number of available results is larger than maxResults, Compute Engine returns a nextPageToken that can be used to get the next page of results in subsequent list requests.", + "description": "The maximum number of results per page that should be returned. If the number of available results is larger than maxResults, Compute Engine returns a nextPageToken that can be used to get the next page of results in subsequent list requests. Acceptable values are 0 to 500, inclusive. (Default: 500)", "default": "500", "format": "uint32", "minimum": "0", - "maximum": "500", "location": "query" }, "orderBy": { @@ -8692,11 +9101,10 @@ }, "maxResults": { "type": "integer", - "description": "The maximum number of results per page that should be returned. If the number of available results is larger than maxResults, Compute Engine returns a nextPageToken that can be used to get the next page of results in subsequent list requests.", + "description": "The maximum number of results per page that should be returned. If the number of available results is larger than maxResults, Compute Engine returns a nextPageToken that can be used to get the next page of results in subsequent list requests. Acceptable values are 0 to 500, inclusive. (Default: 500)", "default": "500", "format": "uint32", "minimum": "0", - "maximum": "500", "location": "query" }, "orderBy": { @@ -8733,11 +9141,11 @@ "id": "compute.backendServices.patch", "path": "{project}/global/backendServices/{backendService}", "httpMethod": "PATCH", - "description": "Updates the specified BackendService resource with the data included in the request. There are several restrictions and guidelines to keep in mind when updating a backend service. Read Restrictions and Guidelines for more information. This method supports patch semantics.", + "description": "Patches the specified BackendService resource with the data included in the request. There are several restrictions and guidelines to keep in mind when updating a backend service. Read Restrictions and Guidelines for more information. This method supports patch semantics.", "parameters": { "backendService": { "type": "string", - "description": "Name of the BackendService resource to update.", + "description": "Name of the BackendService resource to patch.", "required": true, "pattern": "[a-z](?:[-a-z0-9]{0,61}[a-z0-9])?", "location": "path" @@ -8762,7 +9170,8 @@ }, "scopes": [ "https://www.googleapis.com/auth/cloud-platform", - "https://www.googleapis.com/auth/compute" + "https://www.googleapis.com/auth/compute", + "https://www.googleapis.com/auth/compute.readonly" ] }, "update": { @@ -8818,11 +9227,10 @@ }, "maxResults": { "type": "integer", - "description": "The maximum number of results per page that should be returned. If the number of available results is larger than maxResults, Compute Engine returns a nextPageToken that can be used to get the next page of results in subsequent list requests.", + "description": "The maximum number of results per page that should be returned. If the number of available results is larger than maxResults, Compute Engine returns a nextPageToken that can be used to get the next page of results in subsequent list requests. Acceptable values are 0 to 500, inclusive. (Default: 500)", "default": "500", "format": "uint32", "minimum": "0", - "maximum": "500", "location": "query" }, "orderBy": { @@ -8910,11 +9318,10 @@ }, "maxResults": { "type": "integer", - "description": "The maximum number of results per page that should be returned. If the number of available results is larger than maxResults, Compute Engine returns a nextPageToken that can be used to get the next page of results in subsequent list requests.", + "description": "The maximum number of results per page that should be returned. If the number of available results is larger than maxResults, Compute Engine returns a nextPageToken that can be used to get the next page of results in subsequent list requests. Acceptable values are 0 to 500, inclusive. (Default: 500)", "default": "500", "format": "uint32", "minimum": "0", - "maximum": "500", "location": "query" }, "orderBy": { @@ -8972,11 +9379,10 @@ }, "maxResults": { "type": "integer", - "description": "The maximum number of results per page that should be returned. If the number of available results is larger than maxResults, Compute Engine returns a nextPageToken that can be used to get the next page of results in subsequent list requests.", + "description": "The maximum number of results per page that should be returned. If the number of available results is larger than maxResults, Compute Engine returns a nextPageToken that can be used to get the next page of results in subsequent list requests. Acceptable values are 0 to 500, inclusive. (Default: 500)", "default": "500", "format": "uint32", "minimum": "0", - "maximum": "500", "location": "query" }, "orderBy": { @@ -9022,6 +9428,10 @@ "pattern": "[a-z](?:[-a-z0-9]{0,61}[a-z0-9])?", "location": "path" }, + "guestFlush": { + "type": "boolean", + "location": "query" + }, "project": { "type": "string", "description": "Project ID for this request.", @@ -9189,11 +9599,10 @@ }, "maxResults": { "type": "integer", - "description": "The maximum number of results per page that should be returned. If the number of available results is larger than maxResults, Compute Engine returns a nextPageToken that can be used to get the next page of results in subsequent list requests.", + "description": "The maximum number of results per page that should be returned. If the number of available results is larger than maxResults, Compute Engine returns a nextPageToken that can be used to get the next page of results in subsequent list requests. Acceptable values are 0 to 500, inclusive. (Default: 500)", "default": "500", "format": "uint32", "minimum": "0", - "maximum": "500", "location": "query" }, "orderBy": { @@ -9390,11 +9799,10 @@ }, "maxResults": { "type": "integer", - "description": "The maximum number of results per page that should be returned. If the number of available results is larger than maxResults, Compute Engine returns a nextPageToken that can be used to get the next page of results in subsequent list requests.", + "description": "The maximum number of results per page that should be returned. If the number of available results is larger than maxResults, Compute Engine returns a nextPageToken that can be used to get the next page of results in subsequent list requests. Acceptable values are 0 to 500, inclusive. (Default: 500)", "default": "500", "format": "uint32", "minimum": "0", - "maximum": "500", "location": "query" }, "orderBy": { @@ -9431,7 +9839,7 @@ "id": "compute.firewalls.patch", "path": "{project}/global/firewalls/{firewall}", "httpMethod": "PATCH", - "description": "Updates the specified firewall rule with the data included in the request. This method supports patch semantics.", + "description": "Updates the specified firewall rule with the data included in the request. Using PUT method, can only update following fields of firewall rule: allowed, description, sourceRanges, sourceTags, targetTags. This method supports patch semantics.", "parameters": { "firewall": { "type": "string", @@ -9467,7 +9875,7 @@ "id": "compute.firewalls.update", "path": "{project}/global/firewalls/{firewall}", "httpMethod": "PUT", - "description": "Updates the specified firewall rule with the data included in the request.", + "description": "Updates the specified firewall rule with the data included in the request. Using PUT method, can only update following fields of firewall rule: allowed, description, sourceRanges, sourceTags, targetTags.", "parameters": { "firewall": { "type": "string", @@ -9516,11 +9924,10 @@ }, "maxResults": { "type": "integer", - "description": "The maximum number of results per page that should be returned. If the number of available results is larger than maxResults, Compute Engine returns a nextPageToken that can be used to get the next page of results in subsequent list requests.", + "description": "The maximum number of results per page that should be returned. If the number of available results is larger than maxResults, Compute Engine returns a nextPageToken that can be used to get the next page of results in subsequent list requests. Acceptable values are 0 to 500, inclusive. (Default: 500)", "default": "500", "format": "uint32", "minimum": "0", - "maximum": "500", "location": "query" }, "orderBy": { @@ -9685,11 +10092,10 @@ }, "maxResults": { "type": "integer", - "description": "The maximum number of results per page that should be returned. If the number of available results is larger than maxResults, Compute Engine returns a nextPageToken that can be used to get the next page of results in subsequent list requests.", + "description": "The maximum number of results per page that should be returned. If the number of available results is larger than maxResults, Compute Engine returns a nextPageToken that can be used to get the next page of results in subsequent list requests. Acceptable values are 0 to 500, inclusive. (Default: 500)", "default": "500", "format": "uint32", "minimum": "0", - "maximum": "500", "location": "query" }, "orderBy": { @@ -9886,11 +10292,10 @@ }, "maxResults": { "type": "integer", - "description": "The maximum number of results per page that should be returned. If the number of available results is larger than maxResults, Compute Engine returns a nextPageToken that can be used to get the next page of results in subsequent list requests.", + "description": "The maximum number of results per page that should be returned. If the number of available results is larger than maxResults, Compute Engine returns a nextPageToken that can be used to get the next page of results in subsequent list requests. Acceptable values are 0 to 500, inclusive. (Default: 500)", "default": "500", "format": "uint32", "minimum": "0", - "maximum": "500", "location": "query" }, "orderBy": { @@ -10035,11 +10440,10 @@ }, "maxResults": { "type": "integer", - "description": "The maximum number of results per page that should be returned. If the number of available results is larger than maxResults, Compute Engine returns a nextPageToken that can be used to get the next page of results in subsequent list requests.", + "description": "The maximum number of results per page that should be returned. If the number of available results is larger than maxResults, Compute Engine returns a nextPageToken that can be used to get the next page of results in subsequent list requests. Acceptable values are 0 to 500, inclusive. (Default: 500)", "default": "500", "format": "uint32", "minimum": "0", - "maximum": "500", "location": "query" }, "orderBy": { @@ -10125,11 +10529,10 @@ }, "maxResults": { "type": "integer", - "description": "The maximum number of results per page that should be returned. If the number of available results is larger than maxResults, Compute Engine returns a nextPageToken that can be used to get the next page of results in subsequent list requests.", + "description": "The maximum number of results per page that should be returned. If the number of available results is larger than maxResults, Compute Engine returns a nextPageToken that can be used to get the next page of results in subsequent list requests. Acceptable values are 0 to 500, inclusive. (Default: 500)", "default": "500", "format": "uint32", "minimum": "0", - "maximum": "500", "location": "query" }, "orderBy": { @@ -10239,11 +10642,10 @@ }, "maxResults": { "type": "integer", - "description": "The maximum number of results per page that should be returned. If the number of available results is larger than maxResults, Compute Engine returns a nextPageToken that can be used to get the next page of results in subsequent list requests.", + "description": "The maximum number of results per page that should be returned. If the number of available results is larger than maxResults, Compute Engine returns a nextPageToken that can be used to get the next page of results in subsequent list requests. Acceptable values are 0 to 500, inclusive. (Default: 500)", "default": "500", "format": "uint32", "minimum": "0", - "maximum": "500", "location": "query" }, "orderBy": { @@ -10388,11 +10790,10 @@ }, "maxResults": { "type": "integer", - "description": "The maximum number of results per page that should be returned. If the number of available results is larger than maxResults, Compute Engine returns a nextPageToken that can be used to get the next page of results in subsequent list requests.", + "description": "The maximum number of results per page that should be returned. If the number of available results is larger than maxResults, Compute Engine returns a nextPageToken that can be used to get the next page of results in subsequent list requests. Acceptable values are 0 to 500, inclusive. (Default: 500)", "default": "500", "format": "uint32", "minimum": "0", - "maximum": "500", "location": "query" }, "orderBy": { @@ -10433,7 +10834,7 @@ "parameters": { "healthCheck": { "type": "string", - "description": "Name of the HealthCheck resource to update.", + "description": "Name of the HealthCheck resource to patch.", "required": true, "pattern": "[a-z](?:[-a-z0-9]{0,61}[a-z0-9])?", "location": "path" @@ -10458,7 +10859,8 @@ }, "scopes": [ "https://www.googleapis.com/auth/cloud-platform", - "https://www.googleapis.com/auth/compute" + "https://www.googleapis.com/auth/compute", + "https://www.googleapis.com/auth/compute.readonly" ] }, "update": { @@ -10609,11 +11011,10 @@ }, "maxResults": { "type": "integer", - "description": "The maximum number of results per page that should be returned. If the number of available results is larger than maxResults, Compute Engine returns a nextPageToken that can be used to get the next page of results in subsequent list requests.", + "description": "The maximum number of results per page that should be returned. If the number of available results is larger than maxResults, Compute Engine returns a nextPageToken that can be used to get the next page of results in subsequent list requests. Acceptable values are 0 to 500, inclusive. (Default: 500)", "default": "500", "format": "uint32", "minimum": "0", - "maximum": "500", "location": "query" }, "orderBy": { @@ -10654,7 +11055,7 @@ "parameters": { "httpHealthCheck": { "type": "string", - "description": "Name of the HttpHealthCheck resource to update.", + "description": "Name of the HttpHealthCheck resource to patch.", "required": true, "pattern": "[a-z](?:[-a-z0-9]{0,61}[a-z0-9])?", "location": "path" @@ -10679,7 +11080,8 @@ }, "scopes": [ "https://www.googleapis.com/auth/cloud-platform", - "https://www.googleapis.com/auth/compute" + "https://www.googleapis.com/auth/compute", + "https://www.googleapis.com/auth/compute.readonly" ] }, "update": { @@ -10830,11 +11232,10 @@ }, "maxResults": { "type": "integer", - "description": "The maximum number of results per page that should be returned. If the number of available results is larger than maxResults, Compute Engine returns a nextPageToken that can be used to get the next page of results in subsequent list requests.", + "description": "The maximum number of results per page that should be returned. If the number of available results is larger than maxResults, Compute Engine returns a nextPageToken that can be used to get the next page of results in subsequent list requests. Acceptable values are 0 to 500, inclusive. (Default: 500)", "default": "500", "format": "uint32", "minimum": "0", - "maximum": "500", "location": "query" }, "orderBy": { @@ -10875,7 +11276,7 @@ "parameters": { "httpsHealthCheck": { "type": "string", - "description": "Name of the HttpsHealthCheck resource to update.", + "description": "Name of the HttpsHealthCheck resource to patch.", "required": true, "pattern": "[a-z](?:[-a-z0-9]{0,61}[a-z0-9])?", "location": "path" @@ -10900,7 +11301,8 @@ }, "scopes": [ "https://www.googleapis.com/auth/cloud-platform", - "https://www.googleapis.com/auth/compute" + "https://www.googleapis.com/auth/compute", + "https://www.googleapis.com/auth/compute.readonly" ] }, "update": { @@ -11124,11 +11526,10 @@ }, "maxResults": { "type": "integer", - "description": "The maximum number of results per page that should be returned. If the number of available results is larger than maxResults, Compute Engine returns a nextPageToken that can be used to get the next page of results in subsequent list requests.", + "description": "The maximum number of results per page that should be returned. If the number of available results is larger than maxResults, Compute Engine returns a nextPageToken that can be used to get the next page of results in subsequent list requests. Acceptable values are 0 to 500, inclusive. (Default: 500)", "default": "500", "format": "uint32", "minimum": "0", - "maximum": "500", "location": "query" }, "orderBy": { @@ -11169,7 +11570,7 @@ "id": "compute.instanceGroupManagers.abandonInstances", "path": "{project}/zones/{zone}/instanceGroupManagers/{instanceGroupManager}/abandonInstances", "httpMethod": "POST", - "description": "Schedules a group action to remove the specified instances from the managed instance group. Abandoning an instance does not delete the instance, but it does remove the instance from any target pools that are applied by the managed instance group. This method reduces the targetSize of the managed instance group by the number of instances that you abandon. This operation is marked as DONE when the action is scheduled even if the instances have not yet been removed from the group. You must separately verify the status of the abandoning action with the listmanagedinstances method.", + "description": "Schedules a group action to remove the specified instances from the managed instance group. Abandoning an instance does not delete the instance, but it does remove the instance from any target pools that are applied by the managed instance group. This method reduces the targetSize of the managed instance group by the number of instances that you abandon. This operation is marked as DONE when the action is scheduled even if the instances have not yet been removed from the group. You must separately verify the status of the abandoning action with the listmanagedinstances method.\n\nYou can specify a maximum of 1000 instances with this method per request.", "parameters": { "instanceGroupManager": { "type": "string", @@ -11220,11 +11621,10 @@ }, "maxResults": { "type": "integer", - "description": "The maximum number of results per page that should be returned. If the number of available results is larger than maxResults, Compute Engine returns a nextPageToken that can be used to get the next page of results in subsequent list requests.", + "description": "The maximum number of results per page that should be returned. If the number of available results is larger than maxResults, Compute Engine returns a nextPageToken that can be used to get the next page of results in subsequent list requests. Acceptable values are 0 to 500, inclusive. (Default: 500)", "default": "500", "format": "uint32", "minimum": "0", - "maximum": "500", "location": "query" }, "orderBy": { @@ -11300,7 +11700,7 @@ "id": "compute.instanceGroupManagers.deleteInstances", "path": "{project}/zones/{zone}/instanceGroupManagers/{instanceGroupManager}/deleteInstances", "httpMethod": "POST", - "description": "Schedules a group action to delete the specified instances in the managed instance group. The instances are also removed from any target pools of which they were a member. This method reduces the targetSize of the managed instance group by the number of instances that you delete. This operation is marked as DONE when the action is scheduled even if the instances are still being deleted. You must separately verify the status of the deleting action with the listmanagedinstances method.", + "description": "Schedules a group action to delete the specified instances in the managed instance group. The instances are also removed from any target pools of which they were a member. This method reduces the targetSize of the managed instance group by the number of instances that you delete. This operation is marked as DONE when the action is scheduled even if the instances are still being deleted. You must separately verify the status of the deleting action with the listmanagedinstances method.\n\nYou can specify a maximum of 1000 instances with this method per request.", "parameters": { "instanceGroupManager": { "type": "string", @@ -11382,7 +11782,7 @@ "id": "compute.instanceGroupManagers.insert", "path": "{project}/zones/{zone}/instanceGroupManagers", "httpMethod": "POST", - "description": "Creates a managed instance group using the information that you specify in the request. After the group is created, it schedules an action to create instances in the group using the specified instance template. This operation is marked as DONE when the group is created even if the instances in the group have not yet been created. You must separately verify the status of the individual instances with the listmanagedinstances method.", + "description": "Creates a managed instance group using the information that you specify in the request. After the group is created, it schedules an action to create instances in the group using the specified instance template. This operation is marked as DONE when the group is created even if the instances in the group have not yet been created. You must separately verify the status of the individual instances with the listmanagedinstances method.\n\nA managed instance group can have up to 1000 VM instances per group.", "parameters": { "project": { "type": "string", @@ -11426,11 +11826,10 @@ }, "maxResults": { "type": "integer", - "description": "The maximum number of results per page that should be returned. If the number of available results is larger than maxResults, Compute Engine returns a nextPageToken that can be used to get the next page of results in subsequent list requests.", + "description": "The maximum number of results per page that should be returned. If the number of available results is larger than maxResults, Compute Engine returns a nextPageToken that can be used to get the next page of results in subsequent list requests. Acceptable values are 0 to 500, inclusive. (Default: 500)", "default": "500", "format": "uint32", "minimum": "0", - "maximum": "500", "location": "query" }, "orderBy": { @@ -11491,7 +11890,6 @@ "default": "500", "format": "uint32", "minimum": "0", - "maximum": "500", "location": "query" }, "order_by": { @@ -11534,7 +11932,7 @@ "id": "compute.instanceGroupManagers.recreateInstances", "path": "{project}/zones/{zone}/instanceGroupManagers/{instanceGroupManager}/recreateInstances", "httpMethod": "POST", - "description": "Schedules a group action to recreate the specified instances in the managed instance group. The instances are deleted and recreated using the current instance template for the managed instance group. This operation is marked as DONE when the action is scheduled even if the instances have not yet been recreated. You must separately verify the status of the recreating action with the listmanagedinstances method.", + "description": "Schedules a group action to recreate the specified instances in the managed instance group. The instances are deleted and recreated using the current instance template for the managed instance group. This operation is marked as DONE when the action is scheduled even if the instances have not yet been recreated. You must separately verify the status of the recreating action with the listmanagedinstances method.\n\nYou can specify a maximum of 1000 instances with this method per request.", "parameters": { "instanceGroupManager": { "type": "string", @@ -11762,11 +12160,10 @@ }, "maxResults": { "type": "integer", - "description": "The maximum number of results per page that should be returned. If the number of available results is larger than maxResults, Compute Engine returns a nextPageToken that can be used to get the next page of results in subsequent list requests.", + "description": "The maximum number of results per page that should be returned. If the number of available results is larger than maxResults, Compute Engine returns a nextPageToken that can be used to get the next page of results in subsequent list requests. Acceptable values are 0 to 500, inclusive. (Default: 500)", "default": "500", "format": "uint32", "minimum": "0", - "maximum": "500", "location": "query" }, "orderBy": { @@ -11926,11 +12323,10 @@ }, "maxResults": { "type": "integer", - "description": "The maximum number of results per page that should be returned. If the number of available results is larger than maxResults, Compute Engine returns a nextPageToken that can be used to get the next page of results in subsequent list requests.", + "description": "The maximum number of results per page that should be returned. If the number of available results is larger than maxResults, Compute Engine returns a nextPageToken that can be used to get the next page of results in subsequent list requests. Acceptable values are 0 to 500, inclusive. (Default: 500)", "default": "500", "format": "uint32", "minimum": "0", - "maximum": "500", "location": "query" }, "orderBy": { @@ -11989,11 +12385,10 @@ }, "maxResults": { "type": "integer", - "description": "The maximum number of results per page that should be returned. If the number of available results is larger than maxResults, Compute Engine returns a nextPageToken that can be used to get the next page of results in subsequent list requests.", + "description": "The maximum number of results per page that should be returned. If the number of available results is larger than maxResults, Compute Engine returns a nextPageToken that can be used to get the next page of results in subsequent list requests. Acceptable values are 0 to 500, inclusive. (Default: 500)", "default": "500", "format": "uint32", "minimum": "0", - "maximum": "500", "location": "query" }, "orderBy": { @@ -12233,11 +12628,10 @@ }, "maxResults": { "type": "integer", - "description": "The maximum number of results per page that should be returned. If the number of available results is larger than maxResults, Compute Engine returns a nextPageToken that can be used to get the next page of results in subsequent list requests.", + "description": "The maximum number of results per page that should be returned. If the number of available results is larger than maxResults, Compute Engine returns a nextPageToken that can be used to get the next page of results in subsequent list requests. Acceptable values are 0 to 500, inclusive. (Default: 500)", "default": "500", "format": "uint32", "minimum": "0", - "maximum": "500", "location": "query" }, "orderBy": { @@ -12338,11 +12732,10 @@ }, "maxResults": { "type": "integer", - "description": "The maximum number of results per page that should be returned. If the number of available results is larger than maxResults, Compute Engine returns a nextPageToken that can be used to get the next page of results in subsequent list requests.", + "description": "The maximum number of results per page that should be returned. If the number of available results is larger than maxResults, Compute Engine returns a nextPageToken that can be used to get the next page of results in subsequent list requests. Acceptable values are 0 to 500, inclusive. (Default: 500)", "default": "500", "format": "uint32", "minimum": "0", - "maximum": "500", "location": "query" }, "orderBy": { @@ -12636,7 +13029,7 @@ }, "start": { "type": "string", - "description": "For the initial request, leave this field unspecified. For subsequent calls, this field should be set to the next value that was returned in the previous call.", + "description": "Returns output starting from a specific byte position. Use this to page through output when the output is too large to return in a single request. For the initial request, leave this field unspecified. For subsequent calls, this field should be set to the next value returned in the previous call.", "format": "int64", "location": "query" }, @@ -12711,11 +13104,10 @@ }, "maxResults": { "type": "integer", - "description": "The maximum number of results per page that should be returned. If the number of available results is larger than maxResults, Compute Engine returns a nextPageToken that can be used to get the next page of results in subsequent list requests.", + "description": "The maximum number of results per page that should be returned. If the number of available results is larger than maxResults, Compute Engine returns a nextPageToken that can be used to get the next page of results in subsequent list requests. Acceptable values are 0 to 500, inclusive. (Default: 500)", "default": "500", "format": "uint32", "minimum": "0", - "maximum": "500", "location": "query" }, "orderBy": { @@ -12760,7 +13152,7 @@ "id": "compute.instances.reset", "path": "{project}/zones/{zone}/instances/{instance}/reset", "httpMethod": "POST", - "description": "Performs a hard reset on the instance.", + "description": "Performs a reset on the instance. For more information, see Resetting an instance.", "parameters": { "instance": { "type": "string", @@ -12985,6 +13377,50 @@ "https://www.googleapis.com/auth/compute" ] }, + "setServiceAccount": { + "id": "compute.instances.setServiceAccount", + "path": "{project}/zones/{zone}/instances/{instance}/setServiceAccount", + "httpMethod": "POST", + "description": "Sets the service account on the instance. For more information, read Changing the service account and access scopes for an instance.", + "parameters": { + "instance": { + "type": "string", + "description": "Name of the instance resource to start.", + "required": true, + "pattern": "[a-z](?:[-a-z0-9]{0,61}[a-z0-9])?", + "location": "path" + }, + "project": { + "type": "string", + "description": "Project ID for this request.", + "required": true, + "pattern": "(?:(?:[-a-z0-9]{1,63}\\.)*(?:[a-z](?:[-a-z0-9]{0,61}[a-z0-9])?):)?(?:[0-9]{1,19}|(?:[a-z0-9](?:[-a-z0-9]{0,61}[a-z0-9])?))", + "location": "path" + }, + "zone": { + "type": "string", + "description": "The name of the zone for this request.", + "required": true, + "pattern": "[a-z](?:[-a-z0-9]{0,61}[a-z0-9])?", + "location": "path" + } + }, + "parameterOrder": [ + "project", + "zone", + "instance" + ], + "request": { + "$ref": "InstancesSetServiceAccountRequest" + }, + "response": { + "$ref": "Operation" + }, + "scopes": [ + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/compute" + ] + }, "setTags": { "id": "compute.instances.setTags", "path": "{project}/zones/{zone}/instances/{instance}/setTags", @@ -13210,11 +13646,10 @@ }, "maxResults": { "type": "integer", - "description": "The maximum number of results per page that should be returned. If the number of available results is larger than maxResults, Compute Engine returns a nextPageToken that can be used to get the next page of results in subsequent list requests.", + "description": "The maximum number of results per page that should be returned. If the number of available results is larger than maxResults, Compute Engine returns a nextPageToken that can be used to get the next page of results in subsequent list requests. Acceptable values are 0 to 500, inclusive. (Default: 500)", "default": "500", "format": "uint32", "minimum": "0", - "maximum": "500", "location": "query" }, "orderBy": { @@ -13302,11 +13737,10 @@ }, "maxResults": { "type": "integer", - "description": "The maximum number of results per page that should be returned. If the number of available results is larger than maxResults, Compute Engine returns a nextPageToken that can be used to get the next page of results in subsequent list requests.", + "description": "The maximum number of results per page that should be returned. If the number of available results is larger than maxResults, Compute Engine returns a nextPageToken that can be used to get the next page of results in subsequent list requests. Acceptable values are 0 to 500, inclusive. (Default: 500)", "default": "500", "format": "uint32", "minimum": "0", - "maximum": "500", "location": "query" }, "orderBy": { @@ -13459,11 +13893,10 @@ }, "maxResults": { "type": "integer", - "description": "The maximum number of results per page that should be returned. If the number of available results is larger than maxResults, Compute Engine returns a nextPageToken that can be used to get the next page of results in subsequent list requests.", + "description": "The maximum number of results per page that should be returned. If the number of available results is larger than maxResults, Compute Engine returns a nextPageToken that can be used to get the next page of results in subsequent list requests. Acceptable values are 0 to 500, inclusive. (Default: 500)", "default": "500", "format": "uint32", "minimum": "0", - "maximum": "500", "location": "query" }, "orderBy": { @@ -13810,11 +14243,10 @@ }, "maxResults": { "type": "integer", - "description": "The maximum number of results per page that should be returned. If the number of available results is larger than maxResults, Compute Engine returns a nextPageToken that can be used to get the next page of results in subsequent list requests.", + "description": "The maximum number of results per page that should be returned. If the number of available results is larger than maxResults, Compute Engine returns a nextPageToken that can be used to get the next page of results in subsequent list requests. Acceptable values are 0 to 500, inclusive. (Default: 500)", "default": "500", "format": "uint32", "minimum": "0", - "maximum": "500", "location": "query" }, "orderBy": { @@ -13863,8 +14295,7 @@ "parameters": { "autoscaler": { "type": "string", - "description": "Name of the autoscaler to update.", - "required": true, + "description": "Name of the autoscaler to patch.", "pattern": "[a-z](?:[-a-z0-9]{0,61}[a-z0-9])?", "location": "query" }, @@ -13885,8 +14316,7 @@ }, "parameterOrder": [ "project", - "region", - "autoscaler" + "region" ], "request": { "$ref": "Autoscaler" @@ -13896,7 +14326,8 @@ }, "scopes": [ "https://www.googleapis.com/auth/cloud-platform", - "https://www.googleapis.com/auth/compute" + "https://www.googleapis.com/auth/compute", + "https://www.googleapis.com/auth/compute.readonly" ] }, "update": { @@ -14121,11 +14552,10 @@ }, "maxResults": { "type": "integer", - "description": "The maximum number of results per page that should be returned. If the number of available results is larger than maxResults, Compute Engine returns a nextPageToken that can be used to get the next page of results in subsequent list requests.", + "description": "The maximum number of results per page that should be returned. If the number of available results is larger than maxResults, Compute Engine returns a nextPageToken that can be used to get the next page of results in subsequent list requests. Acceptable values are 0 to 500, inclusive. (Default: 500)", "default": "500", "format": "uint32", "minimum": "0", - "maximum": "500", "location": "query" }, "orderBy": { @@ -14174,7 +14604,7 @@ "parameters": { "backendService": { "type": "string", - "description": "Name of the BackendService resource to update.", + "description": "Name of the BackendService resource to patch.", "required": true, "pattern": "[a-z](?:[-a-z0-9]{0,61}[a-z0-9])?", "location": "path" @@ -14207,7 +14637,8 @@ }, "scopes": [ "https://www.googleapis.com/auth/cloud-platform", - "https://www.googleapis.com/auth/compute" + "https://www.googleapis.com/auth/compute", + "https://www.googleapis.com/auth/compute.readonly" ] }, "update": { @@ -14262,7 +14693,7 @@ "id": "compute.regionInstanceGroupManagers.abandonInstances", "path": "{project}/regions/{region}/instanceGroupManagers/{instanceGroupManager}/abandonInstances", "httpMethod": "POST", - "description": "Schedules a group action to remove the specified instances from the managed instance group. Abandoning an instance does not delete the instance, but it does remove the instance from any target pools that are applied by the managed instance group. This method reduces the targetSize of the managed instance group by the number of instances that you abandon. This operation is marked as DONE when the action is scheduled even if the instances have not yet been removed from the group. You must separately verify the status of the abandoning action with the listmanagedinstances method.", + "description": "Schedules a group action to remove the specified instances from the managed instance group. Abandoning an instance does not delete the instance, but it does remove the instance from any target pools that are applied by the managed instance group. This method reduces the targetSize of the managed instance group by the number of instances that you abandon. This operation is marked as DONE when the action is scheduled even if the instances have not yet been removed from the group. You must separately verify the status of the abandoning action with the listmanagedinstances method.\n\nYou can specify a maximum of 1000 instances with this method per request.", "parameters": { "instanceGroupManager": { "type": "string", @@ -14343,7 +14774,7 @@ "id": "compute.regionInstanceGroupManagers.deleteInstances", "path": "{project}/regions/{region}/instanceGroupManagers/{instanceGroupManager}/deleteInstances", "httpMethod": "POST", - "description": "Schedules a group action to delete the specified instances in the managed instance group. The instances are also removed from any target pools of which they were a member. This method reduces the targetSize of the managed instance group by the number of instances that you delete. This operation is marked as DONE when the action is scheduled even if the instances are still being deleted. You must separately verify the status of the deleting action with the listmanagedinstances method.", + "description": "Schedules a group action to delete the specified instances in the managed instance group. The instances are also removed from any target pools of which they were a member. This method reduces the targetSize of the managed instance group by the number of instances that you delete. This operation is marked as DONE when the action is scheduled even if the instances are still being deleted. You must separately verify the status of the deleting action with the listmanagedinstances method.\n\nYou can specify a maximum of 1000 instances with this method per request.", "parameters": { "instanceGroupManager": { "type": "string", @@ -14425,7 +14856,7 @@ "id": "compute.regionInstanceGroupManagers.insert", "path": "{project}/regions/{region}/instanceGroupManagers", "httpMethod": "POST", - "description": "Creates a managed instance group using the information that you specify in the request. After the group is created, it schedules an action to create instances in the group using the specified instance template. This operation is marked as DONE when the group is created even if the instances in the group have not yet been created. You must separately verify the status of the individual instances with the listmanagedinstances method.", + "description": "Creates a managed instance group using the information that you specify in the request. After the group is created, it schedules an action to create instances in the group using the specified instance template. This operation is marked as DONE when the group is created even if the instances in the group have not yet been created. You must separately verify the status of the individual instances with the listmanagedinstances method.\n\nA regional managed instance group can contain up to 2000 instances.", "parameters": { "project": { "type": "string", @@ -14469,11 +14900,10 @@ }, "maxResults": { "type": "integer", - "description": "The maximum number of results per page that should be returned. If the number of available results is larger than maxResults, Compute Engine returns a nextPageToken that can be used to get the next page of results in subsequent list requests.", + "description": "The maximum number of results per page that should be returned. If the number of available results is larger than maxResults, Compute Engine returns a nextPageToken that can be used to get the next page of results in subsequent list requests. Acceptable values are 0 to 500, inclusive. (Default: 500)", "default": "500", "format": "uint32", "minimum": "0", - "maximum": "500", "location": "query" }, "orderBy": { @@ -14534,7 +14964,6 @@ "default": "500", "format": "uint32", "minimum": "0", - "maximum": "500", "location": "query" }, "order_by": { @@ -14577,7 +15006,7 @@ "id": "compute.regionInstanceGroupManagers.recreateInstances", "path": "{project}/regions/{region}/instanceGroupManagers/{instanceGroupManager}/recreateInstances", "httpMethod": "POST", - "description": "Schedules a group action to recreate the specified instances in the managed instance group. The instances are deleted and recreated using the current instance template for the managed instance group. This operation is marked as DONE when the action is scheduled even if the instances have not yet been recreated. You must separately verify the status of the recreating action with the listmanagedinstances method.", + "description": "Schedules a group action to recreate the specified instances in the managed instance group. The instances are deleted and recreated using the current instance template for the managed instance group. This operation is marked as DONE when the action is scheduled even if the instances have not yet been recreated. You must separately verify the status of the recreating action with the listmanagedinstances method.\n\nYou can specify a maximum of 1000 instances with this method per request.", "parameters": { "instanceGroupManager": { "type": "string", @@ -14804,11 +15233,10 @@ }, "maxResults": { "type": "integer", - "description": "The maximum number of results per page that should be returned. If the number of available results is larger than maxResults, Compute Engine returns a nextPageToken that can be used to get the next page of results in subsequent list requests.", + "description": "The maximum number of results per page that should be returned. If the number of available results is larger than maxResults, Compute Engine returns a nextPageToken that can be used to get the next page of results in subsequent list requests. Acceptable values are 0 to 500, inclusive. (Default: 500)", "default": "500", "format": "uint32", "minimum": "0", - "maximum": "500", "location": "query" }, "orderBy": { @@ -14867,11 +15295,10 @@ }, "maxResults": { "type": "integer", - "description": "The maximum number of results per page that should be returned. If the number of available results is larger than maxResults, Compute Engine returns a nextPageToken that can be used to get the next page of results in subsequent list requests.", + "description": "The maximum number of results per page that should be returned. If the number of available results is larger than maxResults, Compute Engine returns a nextPageToken that can be used to get the next page of results in subsequent list requests. Acceptable values are 0 to 500, inclusive. (Default: 500)", "default": "500", "format": "uint32", "minimum": "0", - "maximum": "500", "location": "query" }, "orderBy": { @@ -15054,11 +15481,10 @@ }, "maxResults": { "type": "integer", - "description": "The maximum number of results per page that should be returned. If the number of available results is larger than maxResults, Compute Engine returns a nextPageToken that can be used to get the next page of results in subsequent list requests.", + "description": "The maximum number of results per page that should be returned. If the number of available results is larger than maxResults, Compute Engine returns a nextPageToken that can be used to get the next page of results in subsequent list requests. Acceptable values are 0 to 500, inclusive. (Default: 500)", "default": "500", "format": "uint32", "minimum": "0", - "maximum": "500", "location": "query" }, "orderBy": { @@ -15150,11 +15576,10 @@ }, "maxResults": { "type": "integer", - "description": "The maximum number of results per page that should be returned. If the number of available results is larger than maxResults, Compute Engine returns a nextPageToken that can be used to get the next page of results in subsequent list requests.", + "description": "The maximum number of results per page that should be returned. If the number of available results is larger than maxResults, Compute Engine returns a nextPageToken that can be used to get the next page of results in subsequent list requests. Acceptable values are 0 to 500, inclusive. (Default: 500)", "default": "500", "format": "uint32", "minimum": "0", - "maximum": "500", "location": "query" }, "orderBy": { @@ -15204,11 +15629,10 @@ }, "maxResults": { "type": "integer", - "description": "The maximum number of results per page that should be returned. If the number of available results is larger than maxResults, Compute Engine returns a nextPageToken that can be used to get the next page of results in subsequent list requests.", + "description": "The maximum number of results per page that should be returned. If the number of available results is larger than maxResults, Compute Engine returns a nextPageToken that can be used to get the next page of results in subsequent list requests. Acceptable values are 0 to 500, inclusive. (Default: 500)", "default": "500", "format": "uint32", "minimum": "0", - "maximum": "500", "location": "query" }, "orderBy": { @@ -15415,11 +15839,10 @@ }, "maxResults": { "type": "integer", - "description": "The maximum number of results per page that should be returned. If the number of available results is larger than maxResults, Compute Engine returns a nextPageToken that can be used to get the next page of results in subsequent list requests.", + "description": "The maximum number of results per page that should be returned. If the number of available results is larger than maxResults, Compute Engine returns a nextPageToken that can be used to get the next page of results in subsequent list requests. Acceptable values are 0 to 500, inclusive. (Default: 500)", "default": "500", "format": "uint32", "minimum": "0", - "maximum": "500", "location": "query" }, "orderBy": { @@ -15464,7 +15887,7 @@ "id": "compute.routers.patch", "path": "{project}/regions/{region}/routers/{router}", "httpMethod": "PATCH", - "description": "Updates the specified Router resource with the data included in the request. This method supports patch semantics.", + "description": "Patches the specified Router resource with the data included in the request. This method supports patch semantics.", "parameters": { "project": { "type": "string", @@ -15482,7 +15905,7 @@ }, "router": { "type": "string", - "description": "Name of the Router resource to update.", + "description": "Name of the Router resource to patch.", "required": true, "pattern": "[a-z](?:[-a-z0-9]{0,61}[a-z0-9])?", "location": "path" @@ -15501,7 +15924,8 @@ }, "scopes": [ "https://www.googleapis.com/auth/cloud-platform", - "https://www.googleapis.com/auth/compute" + "https://www.googleapis.com/auth/compute", + "https://www.googleapis.com/auth/compute.readonly" ] }, "preview": { @@ -15705,11 +16129,10 @@ }, "maxResults": { "type": "integer", - "description": "The maximum number of results per page that should be returned. If the number of available results is larger than maxResults, Compute Engine returns a nextPageToken that can be used to get the next page of results in subsequent list requests.", + "description": "The maximum number of results per page that should be returned. If the number of available results is larger than maxResults, Compute Engine returns a nextPageToken that can be used to get the next page of results in subsequent list requests. Acceptable values are 0 to 500, inclusive. (Default: 500)", "default": "500", "format": "uint32", "minimum": "0", - "maximum": "500", "location": "query" }, "orderBy": { @@ -15826,11 +16249,10 @@ }, "maxResults": { "type": "integer", - "description": "The maximum number of results per page that should be returned. If the number of available results is larger than maxResults, Compute Engine returns a nextPageToken that can be used to get the next page of results in subsequent list requests.", + "description": "The maximum number of results per page that should be returned. If the number of available results is larger than maxResults, Compute Engine returns a nextPageToken that can be used to get the next page of results in subsequent list requests. Acceptable values are 0 to 500, inclusive. (Default: 500)", "default": "500", "format": "uint32", "minimum": "0", - "maximum": "500", "location": "query" }, "orderBy": { @@ -15975,11 +16397,10 @@ }, "maxResults": { "type": "integer", - "description": "The maximum number of results per page that should be returned. If the number of available results is larger than maxResults, Compute Engine returns a nextPageToken that can be used to get the next page of results in subsequent list requests.", + "description": "The maximum number of results per page that should be returned. If the number of available results is larger than maxResults, Compute Engine returns a nextPageToken that can be used to get the next page of results in subsequent list requests. Acceptable values are 0 to 500, inclusive. (Default: 500)", "default": "500", "format": "uint32", "minimum": "0", - "maximum": "500", "location": "query" }, "orderBy": { @@ -16029,11 +16450,10 @@ }, "maxResults": { "type": "integer", - "description": "The maximum number of results per page that should be returned. If the number of available results is larger than maxResults, Compute Engine returns a nextPageToken that can be used to get the next page of results in subsequent list requests.", + "description": "The maximum number of results per page that should be returned. If the number of available results is larger than maxResults, Compute Engine returns a nextPageToken that can be used to get the next page of results in subsequent list requests. Acceptable values are 0 to 500, inclusive. (Default: 500)", "default": "500", "format": "uint32", "minimum": "0", - "maximum": "500", "location": "query" }, "orderBy": { @@ -16242,11 +16662,10 @@ }, "maxResults": { "type": "integer", - "description": "The maximum number of results per page that should be returned. If the number of available results is larger than maxResults, Compute Engine returns a nextPageToken that can be used to get the next page of results in subsequent list requests.", + "description": "The maximum number of results per page that should be returned. If the number of available results is larger than maxResults, Compute Engine returns a nextPageToken that can be used to get the next page of results in subsequent list requests. Acceptable values are 0 to 500, inclusive. (Default: 500)", "default": "500", "format": "uint32", "minimum": "0", - "maximum": "500", "location": "query" }, "orderBy": { @@ -16286,6 +16705,50 @@ "https://www.googleapis.com/auth/compute", "https://www.googleapis.com/auth/compute.readonly" ] + }, + "setPrivateIpGoogleAccess": { + "id": "compute.subnetworks.setPrivateIpGoogleAccess", + "path": "{project}/regions/{region}/subnetworks/{subnetwork}/setPrivateIpGoogleAccess", + "httpMethod": "POST", + "description": "Set whether VMs in this subnet can access Google services without assigning external IP addresses through Cloudpath.", + "parameters": { + "project": { + "type": "string", + "description": "Project ID for this request.", + "required": true, + "pattern": "(?:(?:[-a-z0-9]{1,63}\\.)*(?:[a-z](?:[-a-z0-9]{0,61}[a-z0-9])?):)?(?:[0-9]{1,19}|(?:[a-z0-9](?:[-a-z0-9]{0,61}[a-z0-9])?))", + "location": "path" + }, + "region": { + "type": "string", + "description": "Name of the region scoping this request.", + "required": true, + "pattern": "[a-z](?:[-a-z0-9]{0,61}[a-z0-9])?", + "location": "path" + }, + "subnetwork": { + "type": "string", + "description": "Name of the Subnetwork resource.", + "required": true, + "pattern": "[a-z](?:[-a-z0-9]{0,61}[a-z0-9])?", + "location": "path" + } + }, + "parameterOrder": [ + "project", + "region", + "subnetwork" + ], + "request": { + "$ref": "SubnetworksSetPrivateIpGoogleAccessRequest" + }, + "response": { + "$ref": "Operation" + }, + "scopes": [ + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/compute" + ] } } }, @@ -16399,11 +16862,10 @@ }, "maxResults": { "type": "integer", - "description": "The maximum number of results per page that should be returned. If the number of available results is larger than maxResults, Compute Engine returns a nextPageToken that can be used to get the next page of results in subsequent list requests.", + "description": "The maximum number of results per page that should be returned. If the number of available results is larger than maxResults, Compute Engine returns a nextPageToken that can be used to get the next page of results in subsequent list requests. Acceptable values are 0 to 500, inclusive. (Default: 500)", "default": "500", "format": "uint32", "minimum": "0", - "maximum": "500", "location": "query" }, "orderBy": { @@ -16584,11 +17046,10 @@ }, "maxResults": { "type": "integer", - "description": "The maximum number of results per page that should be returned. If the number of available results is larger than maxResults, Compute Engine returns a nextPageToken that can be used to get the next page of results in subsequent list requests.", + "description": "The maximum number of results per page that should be returned. If the number of available results is larger than maxResults, Compute Engine returns a nextPageToken that can be used to get the next page of results in subsequent list requests. Acceptable values are 0 to 500, inclusive. (Default: 500)", "default": "500", "format": "uint32", "minimum": "0", - "maximum": "500", "location": "query" }, "orderBy": { @@ -16710,11 +17171,10 @@ }, "maxResults": { "type": "integer", - "description": "The maximum number of results per page that should be returned. If the number of available results is larger than maxResults, Compute Engine returns a nextPageToken that can be used to get the next page of results in subsequent list requests.", + "description": "The maximum number of results per page that should be returned. If the number of available results is larger than maxResults, Compute Engine returns a nextPageToken that can be used to get the next page of results in subsequent list requests. Acceptable values are 0 to 500, inclusive. (Default: 500)", "default": "500", "format": "uint32", "minimum": "0", - "maximum": "500", "location": "query" }, "orderBy": { @@ -16879,11 +17339,10 @@ }, "maxResults": { "type": "integer", - "description": "The maximum number of results per page that should be returned. If the number of available results is larger than maxResults, Compute Engine returns a nextPageToken that can be used to get the next page of results in subsequent list requests.", + "description": "The maximum number of results per page that should be returned. If the number of available results is larger than maxResults, Compute Engine returns a nextPageToken that can be used to get the next page of results in subsequent list requests. Acceptable values are 0 to 500, inclusive. (Default: 500)", "default": "500", "format": "uint32", "minimum": "0", - "maximum": "500", "location": "query" }, "orderBy": { @@ -17029,11 +17488,10 @@ }, "maxResults": { "type": "integer", - "description": "The maximum number of results per page that should be returned. If the number of available results is larger than maxResults, Compute Engine returns a nextPageToken that can be used to get the next page of results in subsequent list requests.", + "description": "The maximum number of results per page that should be returned. If the number of available results is larger than maxResults, Compute Engine returns a nextPageToken that can be used to get the next page of results in subsequent list requests. Acceptable values are 0 to 500, inclusive. (Default: 500)", "default": "500", "format": "uint32", "minimum": "0", - "maximum": "500", "location": "query" }, "orderBy": { @@ -17243,11 +17701,10 @@ }, "maxResults": { "type": "integer", - "description": "The maximum number of results per page that should be returned. If the number of available results is larger than maxResults, Compute Engine returns a nextPageToken that can be used to get the next page of results in subsequent list requests.", + "description": "The maximum number of results per page that should be returned. If the number of available results is larger than maxResults, Compute Engine returns a nextPageToken that can be used to get the next page of results in subsequent list requests. Acceptable values are 0 to 500, inclusive. (Default: 500)", "default": "500", "format": "uint32", "minimum": "0", - "maximum": "500", "location": "query" }, "orderBy": { @@ -17538,11 +17995,10 @@ }, "maxResults": { "type": "integer", - "description": "The maximum number of results per page that should be returned. If the number of available results is larger than maxResults, Compute Engine returns a nextPageToken that can be used to get the next page of results in subsequent list requests.", + "description": "The maximum number of results per page that should be returned. If the number of available results is larger than maxResults, Compute Engine returns a nextPageToken that can be used to get the next page of results in subsequent list requests. Acceptable values are 0 to 500, inclusive. (Default: 500)", "default": "500", "format": "uint32", "minimum": "0", - "maximum": "500", "location": "query" }, "orderBy": { @@ -17700,11 +18156,10 @@ }, "maxResults": { "type": "integer", - "description": "The maximum number of results per page that should be returned. If the number of available results is larger than maxResults, Compute Engine returns a nextPageToken that can be used to get the next page of results in subsequent list requests.", + "description": "The maximum number of results per page that should be returned. If the number of available results is larger than maxResults, Compute Engine returns a nextPageToken that can be used to get the next page of results in subsequent list requests. Acceptable values are 0 to 500, inclusive. (Default: 500)", "default": "500", "format": "uint32", "minimum": "0", - "maximum": "500", "location": "query" }, "orderBy": { @@ -17869,11 +18324,10 @@ }, "maxResults": { "type": "integer", - "description": "The maximum number of results per page that should be returned. If the number of available results is larger than maxResults, Compute Engine returns a nextPageToken that can be used to get the next page of results in subsequent list requests.", + "description": "The maximum number of results per page that should be returned. If the number of available results is larger than maxResults, Compute Engine returns a nextPageToken that can be used to get the next page of results in subsequent list requests. Acceptable values are 0 to 500, inclusive. (Default: 500)", "default": "500", "format": "uint32", "minimum": "0", - "maximum": "500", "location": "query" }, "orderBy": { @@ -18062,11 +18516,10 @@ }, "maxResults": { "type": "integer", - "description": "The maximum number of results per page that should be returned. If the number of available results is larger than maxResults, Compute Engine returns a nextPageToken that can be used to get the next page of results in subsequent list requests.", + "description": "The maximum number of results per page that should be returned. If the number of available results is larger than maxResults, Compute Engine returns a nextPageToken that can be used to get the next page of results in subsequent list requests. Acceptable values are 0 to 500, inclusive. (Default: 500)", "default": "500", "format": "uint32", "minimum": "0", - "maximum": "500", "location": "query" }, "orderBy": { @@ -18103,7 +18556,7 @@ "id": "compute.urlMaps.patch", "path": "{project}/global/urlMaps/{urlMap}", "httpMethod": "PATCH", - "description": "Updates the specified UrlMap resource with the data included in the request. This method supports patch semantics.", + "description": "Patches the specified UrlMap resource with the data included in the request. This method supports patch semantics.", "parameters": { "project": { "type": "string", @@ -18114,7 +18567,7 @@ }, "urlMap": { "type": "string", - "description": "Name of the UrlMap resource to update.", + "description": "Name of the UrlMap resource to patch.", "required": true, "pattern": "[a-z](?:[-a-z0-9]{0,61}[a-z0-9])?", "location": "path" @@ -18132,7 +18585,8 @@ }, "scopes": [ "https://www.googleapis.com/auth/cloud-platform", - "https://www.googleapis.com/auth/compute" + "https://www.googleapis.com/auth/compute", + "https://www.googleapis.com/auth/compute.readonly" ] }, "update": { @@ -18224,11 +18678,10 @@ }, "maxResults": { "type": "integer", - "description": "The maximum number of results per page that should be returned. If the number of available results is larger than maxResults, Compute Engine returns a nextPageToken that can be used to get the next page of results in subsequent list requests.", + "description": "The maximum number of results per page that should be returned. If the number of available results is larger than maxResults, Compute Engine returns a nextPageToken that can be used to get the next page of results in subsequent list requests. Acceptable values are 0 to 500, inclusive. (Default: 500)", "default": "500", "format": "uint32", "minimum": "0", - "maximum": "500", "location": "query" }, "orderBy": { @@ -18393,11 +18846,10 @@ }, "maxResults": { "type": "integer", - "description": "The maximum number of results per page that should be returned. If the number of available results is larger than maxResults, Compute Engine returns a nextPageToken that can be used to get the next page of results in subsequent list requests.", + "description": "The maximum number of results per page that should be returned. If the number of available results is larger than maxResults, Compute Engine returns a nextPageToken that can be used to get the next page of results in subsequent list requests. Acceptable values are 0 to 500, inclusive. (Default: 500)", "default": "500", "format": "uint32", "minimum": "0", - "maximum": "500", "location": "query" }, "orderBy": { @@ -18535,11 +18987,10 @@ }, "maxResults": { "type": "integer", - "description": "The maximum number of results per page that should be returned. If the number of available results is larger than maxResults, Compute Engine returns a nextPageToken that can be used to get the next page of results in subsequent list requests.", + "description": "The maximum number of results per page that should be returned. If the number of available results is larger than maxResults, Compute Engine returns a nextPageToken that can be used to get the next page of results in subsequent list requests. Acceptable values are 0 to 500, inclusive. (Default: 500)", "default": "500", "format": "uint32", "minimum": "0", - "maximum": "500", "location": "query" }, "orderBy": { @@ -18631,11 +19082,10 @@ }, "maxResults": { "type": "integer", - "description": "The maximum number of results per page that should be returned. If the number of available results is larger than maxResults, Compute Engine returns a nextPageToken that can be used to get the next page of results in subsequent list requests.", + "description": "The maximum number of results per page that should be returned. If the number of available results is larger than maxResults, Compute Engine returns a nextPageToken that can be used to get the next page of results in subsequent list requests. Acceptable values are 0 to 500, inclusive. (Default: 500)", "default": "500", "format": "uint32", "minimum": "0", - "maximum": "500", "location": "query" }, "orderBy": { diff --git a/vendor/google.golang.org/api/compute/v1/compute-gen.go b/vendor/google.golang.org/api/compute/v1/compute-gen.go index 424e855e2..a2242d45a 100644 --- a/vendor/google.golang.org/api/compute/v1/compute-gen.go +++ b/vendor/google.golang.org/api/compute/v1/compute-gen.go @@ -73,6 +73,7 @@ func New(client *http.Client) (*Service, error) { s := &Service{client: client, BasePath: basePath} s.Addresses = NewAddressesService(s) s.Autoscalers = NewAutoscalersService(s) + s.BackendBuckets = NewBackendBucketsService(s) s.BackendServices = NewBackendServicesService(s) s.DiskTypes = NewDiskTypesService(s) s.Disks = NewDisksService(s) @@ -126,6 +127,8 @@ type Service struct { Autoscalers *AutoscalersService + BackendBuckets *BackendBucketsService + BackendServices *BackendServicesService DiskTypes *DiskTypesService @@ -234,6 +237,15 @@ type AutoscalersService struct { s *Service } +func NewBackendBucketsService(s *Service) *BackendBucketsService { + rs := &BackendBucketsService{s: s} + return rs +} + +type BackendBucketsService struct { + s *Service +} + func NewBackendServicesService(s *Service) *BackendServicesService { rs := &BackendServicesService{s: s} return rs @@ -610,7 +622,9 @@ type AccessConfig struct { // for access configs. Kind string `json:"kind,omitempty"` - // Name: Name of this access configuration. + // Name: The name of this access configuration. The default and + // recommended name is External NAT but you can use any arbitrary string + // you would like. For example, My external IP or Network Access. Name string `json:"name,omitempty"` // NatIP: An external IP address associated with this instance. Specify @@ -881,6 +895,7 @@ type AddressesScopedListWarning struct { // "NOT_CRITICAL_ERROR" // "NO_RESULTS_ON_PAGE" // "REQUIRED_TOS_AGREEMENT" + // "RESOURCE_IN_USE_BY_OTHER_RESOURCE_WARNING" // "RESOURCE_NOT_DELETED" // "SINGLE_INSTANCE_PROPERTY_TEMPLATE" // "UNREACHABLE" @@ -1419,6 +1434,7 @@ type AutoscalersScopedListWarning struct { // "NOT_CRITICAL_ERROR" // "NO_RESULTS_ON_PAGE" // "REQUIRED_TOS_AGREEMENT" + // "RESOURCE_IN_USE_BY_OTHER_RESOURCE_WARNING" // "RESOURCE_NOT_DELETED" // "SINGLE_INSTANCE_PROPERTY_TEMPLATE" // "UNREACHABLE" @@ -1858,6 +1874,115 @@ func (s *Backend) UnmarshalJSON(data []byte) error { return nil } +// BackendBucket: A BackendBucket resource. This resource defines a +// Cloud Storage bucket. +type BackendBucket struct { + // BucketName: Cloud Storage bucket name. + BucketName string `json:"bucketName,omitempty"` + + // CreationTimestamp: [Output Only] Creation timestamp in RFC3339 text + // format. + CreationTimestamp string `json:"creationTimestamp,omitempty"` + + // Description: An optional textual description of the resource; + // provided by the client when the resource is created. + Description string `json:"description,omitempty"` + + // EnableCdn: If true, enable Cloud CDN for this BackendBucket. + EnableCdn bool `json:"enableCdn,omitempty"` + + // Id: [Output Only] Unique identifier for the resource; defined by the + // server. + Id uint64 `json:"id,omitempty,string"` + + // Kind: Type of the resource. + Kind string `json:"kind,omitempty"` + + // Name: Name of the resource. Provided by the client when the resource + // is created. The name must be 1-63 characters long, and comply with + // RFC1035. Specifically, the name must be 1-63 characters long and + // match the regular expression [a-z]([-a-z0-9]*[a-z0-9])? which means + // the first character must be a lowercase letter, and all following + // characters must be a dash, lowercase letter, or digit, except the + // last character, which cannot be a dash. + Name string `json:"name,omitempty"` + + // SelfLink: [Output Only] Server-defined URL for the resource. + SelfLink string `json:"selfLink,omitempty"` + + // ServerResponse contains the HTTP response code and headers from the + // server. + googleapi.ServerResponse `json:"-"` + + // ForceSendFields is a list of field names (e.g. "BucketName") to + // unconditionally include in API requests. By default, fields with + // empty values are omitted from API requests. However, any non-pointer, + // non-interface field appearing in ForceSendFields will be sent to the + // server regardless of whether the field is empty or not. This may be + // used to include empty fields in Patch requests. + ForceSendFields []string `json:"-"` + + // NullFields is a list of field names (e.g. "BucketName") to include in + // API requests with the JSON null value. By default, fields with empty + // values are omitted from API requests. However, any field with an + // empty value appearing in NullFields will be sent to the server as + // null. It is an error if a field in this list has a non-empty value. + // This may be used to include null fields in Patch requests. + NullFields []string `json:"-"` +} + +func (s *BackendBucket) MarshalJSON() ([]byte, error) { + type noMethod BackendBucket + raw := noMethod(*s) + return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) +} + +// BackendBucketList: Contains a list of BackendBucket resources. +type BackendBucketList struct { + // Id: [Output Only] Unique identifier for the resource; defined by the + // server. + Id string `json:"id,omitempty"` + + // Items: A list of BackendBucket resources. + Items []*BackendBucket `json:"items,omitempty"` + + // Kind: Type of resource. + Kind string `json:"kind,omitempty"` + + // NextPageToken: [Output Only] A token used to continue a truncated + // list request. + NextPageToken string `json:"nextPageToken,omitempty"` + + // SelfLink: [Output Only] Server-defined URL for this resource. + SelfLink string `json:"selfLink,omitempty"` + + // ServerResponse contains the HTTP response code and headers from the + // server. + googleapi.ServerResponse `json:"-"` + + // ForceSendFields is a list of field names (e.g. "Id") to + // unconditionally include in API requests. By default, fields with + // empty values are omitted from API requests. However, any non-pointer, + // non-interface field appearing in ForceSendFields will be sent to the + // server regardless of whether the field is empty or not. This may be + // used to include empty fields in Patch requests. + ForceSendFields []string `json:"-"` + + // NullFields is a list of field names (e.g. "Id") to include in API + // requests with the JSON null value. By default, fields with empty + // values are omitted from API requests. However, any field with an + // empty value appearing in NullFields will be sent to the server as + // null. It is an error if a field in this list has a non-empty value. + // This may be used to include null fields in Patch requests. + NullFields []string `json:"-"` +} + +func (s *BackendBucketList) MarshalJSON() ([]byte, error) { + type noMethod BackendBucketList + raw := noMethod(*s) + return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) +} + // BackendService: A BackendService resource. This resource defines a // group of backend virtual machines and their serving capacity. type BackendService struct { @@ -1872,6 +1997,9 @@ type BackendService struct { // Backends: The list of backends that serve this BackendService. Backends []*Backend `json:"backends,omitempty"` + // CdnPolicy: Cloud CDN configuration for this BackendService. + CdnPolicy *BackendServiceCdnPolicy `json:"cdnPolicy,omitempty"` + ConnectionDraining *ConnectionDraining `json:"connectionDraining,omitempty"` // CreationTimestamp: [Output Only] Creation timestamp in RFC3339 text @@ -1941,7 +2069,7 @@ type BackendService struct { // Protocol: The protocol this BackendService uses to communicate with // backends. // - // Possible values are HTTP, HTTPS, HTTP2, TCP and SSL. The default is + // Possible values are HTTP, HTTPS, TCP, and SSL. The default is // HTTP. // // For internal load balancing, the possible values are TCP and UDP, and @@ -2062,6 +2190,36 @@ func (s *BackendServiceAggregatedList) MarshalJSON() ([]byte, error) { return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) } +// BackendServiceCdnPolicy: Message containing Cloud CDN configuration +// for a backend service. +type BackendServiceCdnPolicy struct { + // CacheKeyPolicy: The CacheKeyPolicy for this CdnPolicy. + CacheKeyPolicy *CacheKeyPolicy `json:"cacheKeyPolicy,omitempty"` + + // ForceSendFields is a list of field names (e.g. "CacheKeyPolicy") to + // unconditionally include in API requests. By default, fields with + // empty values are omitted from API requests. However, any non-pointer, + // non-interface field appearing in ForceSendFields will be sent to the + // server regardless of whether the field is empty or not. This may be + // used to include empty fields in Patch requests. + ForceSendFields []string `json:"-"` + + // NullFields is a list of field names (e.g. "CacheKeyPolicy") to + // include in API requests with the JSON null value. By default, fields + // with empty values are omitted from API requests. However, any field + // with an empty value appearing in NullFields will be sent to the + // server as null. It is an error if a field in this list has a + // non-empty value. This may be used to include null fields in Patch + // requests. + NullFields []string `json:"-"` +} + +func (s *BackendServiceCdnPolicy) MarshalJSON() ([]byte, error) { + type noMethod BackendServiceCdnPolicy + raw := noMethod(*s) + return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) +} + type BackendServiceGroupHealth struct { HealthStatus []*HealthStatus `json:"healthStatus,omitempty"` @@ -2109,8 +2267,12 @@ type BackendServiceList struct { // compute#backendServiceList for lists of backend services. Kind string `json:"kind,omitempty"` - // NextPageToken: [Output Only] A token used to continue a truncated - // list request. + // NextPageToken: [Output Only] This token allows you to get the next + // page of results for list requests. If the number of results is larger + // than maxResults, use the nextPageToken as a value for the query + // parameter pageToken in the next list request. Subsequent list + // requests will have their own nextPageToken to continue paging through + // the results. NextPageToken string `json:"nextPageToken,omitempty"` // SelfLink: [Output Only] Server-defined URL for this resource. @@ -2196,6 +2358,7 @@ type BackendServicesScopedListWarning struct { // "NOT_CRITICAL_ERROR" // "NO_RESULTS_ON_PAGE" // "REQUIRED_TOS_AGREEMENT" + // "RESOURCE_IN_USE_BY_OTHER_RESOURCE_WARNING" // "RESOURCE_NOT_DELETED" // "SINGLE_INSTANCE_PROPERTY_TEMPLATE" // "UNREACHABLE" @@ -2300,6 +2463,59 @@ func (s *CacheInvalidationRule) MarshalJSON() ([]byte, error) { return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) } +// CacheKeyPolicy: Message containing what to include in the cache key +// for a request for Cloud CDN. +type CacheKeyPolicy struct { + // IncludeHost: If true, requests to different hosts will be cached + // separately. + IncludeHost bool `json:"includeHost,omitempty"` + + // IncludeProtocol: If true, http and https requests will be cached + // separately. + IncludeProtocol bool `json:"includeProtocol,omitempty"` + + // IncludeQueryString: If true, include query string parameters in the + // cache key according to query_string_whitelist and + // query_string_blacklist. If neither is set, the entire query string + // will be included. If false, the query string will be excluded from + // the cache key entirely. + IncludeQueryString bool `json:"includeQueryString,omitempty"` + + // QueryStringBlacklist: Names of query string parameters to exclude in + // cache keys. All other parameters will be included. Either specify + // query_string_whitelist or query_string_blacklist, not both. '&' and + // '=' will be percent encoded and not treated as delimiters. + QueryStringBlacklist []string `json:"queryStringBlacklist,omitempty"` + + // QueryStringWhitelist: Names of query string parameters to include in + // cache keys. All other parameters will be excluded. Either specify + // query_string_whitelist or query_string_blacklist, not both. '&' and + // '=' will be percent encoded and not treated as delimiters. + QueryStringWhitelist []string `json:"queryStringWhitelist,omitempty"` + + // ForceSendFields is a list of field names (e.g. "IncludeHost") to + // unconditionally include in API requests. By default, fields with + // empty values are omitted from API requests. However, any non-pointer, + // non-interface field appearing in ForceSendFields will be sent to the + // server regardless of whether the field is empty or not. This may be + // used to include empty fields in Patch requests. + ForceSendFields []string `json:"-"` + + // NullFields is a list of field names (e.g. "IncludeHost") to include + // in API requests with the JSON null value. By default, fields with + // empty values are omitted from API requests. However, any field with + // an empty value appearing in NullFields will be sent to the server as + // null. It is an error if a field in this list has a non-empty value. + // This may be used to include null fields in Patch requests. + NullFields []string `json:"-"` +} + +func (s *CacheKeyPolicy) MarshalJSON() ([]byte, error) { + type noMethod CacheKeyPolicy + raw := noMethod(*s) + return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) +} + // ConnectionDraining: Message containing connection draining // configuration. type ConnectionDraining struct { @@ -2658,7 +2874,8 @@ type DiskAggregatedList struct { // than maxResults, use the nextPageToken as a value for the query // parameter pageToken in the next list request. Subsequent list // requests will have their own nextPageToken to continue paging through - // the results. + // the results. Acceptable values are 0 to 500, inclusive. (Default: + // 500) NextPageToken string `json:"nextPageToken,omitempty"` // SelfLink: [Output Only] Server-defined URL for this resource. @@ -2693,23 +2910,22 @@ func (s *DiskAggregatedList) MarshalJSON() ([]byte, error) { // DiskList: A list of Disk resources. type DiskList struct { - // Id: [Output Only] The unique identifier for the resource. This - // identifier is defined by the server. + // Id: [Output Only] Unique identifier for the resource; defined by the + // server. Id string `json:"id,omitempty"` - // Items: [Output Only] A list of persistent disks. + // Items: A list of Disk resources. Items []*Disk `json:"items,omitempty"` // Kind: [Output Only] Type of resource. Always compute#diskList for // lists of disks. Kind string `json:"kind,omitempty"` - // NextPageToken: [Output Only] This token allows you to get the next - // page of results for list requests. If the number of results is larger - // than maxResults, use the nextPageToken as a value for the query - // parameter pageToken in the next list request. Subsequent list - // requests will have their own nextPageToken to continue paging through - // the results. + // NextPageToken: This token allows you to get the next page of results + // for list requests. If the number of results is larger than + // maxResults, use the nextPageToken as a value for the query parameter + // pageToken in the next list request. Subsequent list requests will + // have their own nextPageToken to continue paging through the results. NextPageToken string `json:"nextPageToken,omitempty"` // SelfLink: [Output Only] Server-defined URL for this resource. @@ -3004,6 +3220,7 @@ type DiskTypesScopedListWarning struct { // "NOT_CRITICAL_ERROR" // "NO_RESULTS_ON_PAGE" // "REQUIRED_TOS_AGREEMENT" + // "RESOURCE_IN_USE_BY_OTHER_RESOURCE_WARNING" // "RESOURCE_NOT_DELETED" // "SINGLE_INSTANCE_PROPERTY_TEMPLATE" // "UNREACHABLE" @@ -3158,6 +3375,7 @@ type DisksScopedListWarning struct { // "NOT_CRITICAL_ERROR" // "NO_RESULTS_ON_PAGE" // "REQUIRED_TOS_AGREEMENT" + // "RESOURCE_IN_USE_BY_OTHER_RESOURCE_WARNING" // "RESOURCE_NOT_DELETED" // "SINGLE_INSTANCE_PROPERTY_TEMPLATE" // "UNREACHABLE" @@ -3287,7 +3505,7 @@ type Firewall struct { // will apply to traffic that has source IP address within sourceRanges // OR the source IP that belongs to a tag listed in the sourceTags // property. The connection does not need to match both properties for - // the firewall to apply. + // the firewall to apply. Only IPv4 is supported. SourceRanges []string `json:"sourceRanges,omitempty"` // SourceTags: If source tags are specified, the firewall will apply @@ -3430,7 +3648,7 @@ type ForwardingRule struct { // IPAddress: The IP address that this forwarding rule is serving on // behalf of. // - // For global forwarding rules, the address must be a global IP; for + // For global forwarding rules, the address must be a global IP. For // regional forwarding rules, the address must live in the same region // as the forwarding rule. By default, this field is empty and an // ephemeral IP from the same scope (global or regional) will be @@ -3441,18 +3659,19 @@ type ForwardingRule struct { // the forwarding rule. A reserved address cannot be used. If the field // is empty, the IP address will be automatically allocated from the // internal IP range of the subnetwork or network configured for this - // forwarding rule. + // forwarding rule. Only IPv4 is supported. IPAddress string `json:"IPAddress,omitempty"` // IPProtocol: The IP protocol to which this rule applies. Valid options // are TCP, UDP, ESP, AH, SCTP or ICMP. // - // When the load balancing scheme is INTERNAL 5.1) thread_safe (~> 0.3, >= 0.3.4) tzinfo (~> 1.1) - autoprefixer-rails (6.7.6) + autoprefixer-rails (6.7.7.1) execjs bootstrap-sass (3.3.7) autoprefixer-rails (>= 5.2.1) @@ -77,7 +77,7 @@ GEM rack (>= 1.4.5, < 2.0) thor (>= 0.15.2, < 2.0) tilt (~> 1.4.1, < 2.0) - middleman-hashicorp (0.3.13) + middleman-hashicorp (0.3.22) bootstrap-sass (~> 3.3) builder (~> 3.2) middleman (~> 3.4) @@ -103,7 +103,7 @@ GEM mini_portile2 (2.1.0) minitest (5.10.1) multi_json (1.12.1) - nokogiri (1.7.0.1) + nokogiri (1.7.1) mini_portile2 (~> 2.1.0) padrino-helpers (0.12.8.1) i18n (~> 0.6, >= 0.6.7) @@ -138,7 +138,7 @@ GEM turbolinks (5.0.1) turbolinks-source (~> 5) turbolinks-source (5.0.0) - tzinfo (1.2.2) + tzinfo (1.2.3) thread_safe (~> 0.1) uber (0.0.15) uglifier (2.7.2) @@ -151,7 +151,7 @@ PLATFORMS ruby DEPENDENCIES - middleman-hashicorp (= 0.3.13) + middleman-hashicorp (= 0.3.22) BUNDLED WITH 1.14.6 diff --git a/website/Makefile b/website/Makefile index 41fcf114e..d7620d1c2 100644 --- a/website/Makefile +++ b/website/Makefile @@ -1,14 +1,24 @@ -VERSION?="0.3.13" +VERSION?="0.3.22" + +build: + @echo "==> Starting build in Docker..." + @docker run \ + --interactive \ + --rm \ + --tty \ + --volume "$(shell pwd):/website" \ + hashicorp/middleman-hashicorp:${VERSION} \ + bundle exec middleman build --verbose --clean website: @echo "==> Starting website in Docker..." @docker run \ - --interactive \ - --rm \ + --interactive \ + --rm \ --tty \ --publish "4567:4567" \ --publish "35729:35729" \ --volume "$(shell pwd):/website" \ hashicorp/middleman-hashicorp:${VERSION} -.PHONY: website +.PHONY: build website diff --git a/website/README.md b/website/README.md index 4dad05e12..4dbad10d2 100644 --- a/website/README.md +++ b/website/README.md @@ -12,7 +12,10 @@ like any normal GitHub project, and we'll merge it in. ## Running the Site Locally -Running the site locally is simple. Clone this repo and run `make website`. +Running the site locally is simple: + +1. Install [Docker](https://docs.docker.com/engine/installation/) if you have not already done so +2. Clone this repo and run `make website` Then open up `http://localhost:4567`. Note that some URLs you may need to append ".html" to make them work (in the navigation). diff --git a/website/config.rb b/website/config.rb index 6e2d25511..208249841 100644 --- a/website/config.rb +++ b/website/config.rb @@ -2,11 +2,20 @@ set :base_url, "https://www.terraform.io/" activate :hashicorp do |h| h.name = "terraform" - h.version = "0.9.2" + h.version = "0.9.5" h.github_slug = "hashicorp/terraform" end helpers do + # Returns the FQDN of the image URL. + # + # @param [String] path + # + # @return [String] + def image_url(path) + File.join(base_url, image_path(path)) + end + # Get the title for the page. # # @param [Middleman::Page] page @@ -26,17 +35,66 @@ helpers do # # @return [String] def description_for(page) - return escape_html(page.data.description || "") + description = (page.data.description || "") + .gsub('"', '') + .gsub(/\n+/, ' ') + .squeeze(' ') + + return escape_html(description) end # This helps by setting the "active" class for sidebar nav elements # if the YAML frontmatter matches the expected value. def sidebar_current(expected) current = current_page.data.sidebar_current || "" - if current == expected or (expected.is_a?(Regexp) and expected.match(current)) + if current.start_with?(expected) return " class=\"active\"" else return "" end end + + # Returns the id for this page. + # @return [String] + def body_id_for(page) + if !(name = page.data.sidebar_current).blank? + return "page-#{name.strip}" + end + if page.url == "/" || page.url == "/index.html" + return "page-home" + end + if !(title = page.data.page_title).blank? + return title + .downcase + .gsub('"', '') + .gsub(/[^\w]+/, '-') + .gsub(/_+/, '-') + .squeeze('-') + .squeeze(' ') + end + return "" + end + + # Returns the list of classes for this page. + # @return [String] + def body_classes_for(page) + classes = [] + + if !(layout = page.data.layout).blank? + classes << "layout-#{page.data.layout}" + end + + if !(title = page.data.page_title).blank? + title = title + .downcase + .gsub('"', '') + .gsub(/[^\w]+/, '-') + .gsub(/_+/, '-') + .squeeze('-') + .squeeze(' ') + classes << "page-#{title}" + end + + return classes.join(" ") + end end diff --git a/website/packer.json b/website/packer.json index b51f63801..35de63232 100644 --- a/website/packer.json +++ b/website/packer.json @@ -8,7 +8,7 @@ "builders": [ { "type": "docker", - "image": "hashicorp/middleman-hashicorp:0.3.13", + "image": "hashicorp/middleman-hashicorp:0.3.22", "discard": "true", "run_command": ["-d", "-i", "-t", "{{ .Image }}", "/bin/sh"] } diff --git a/website/source/.gitignore b/website/source/.gitignore deleted file mode 100644 index 67550a149..000000000 --- a/website/source/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -# Source folder -node_modules/ diff --git a/website/source/404.html.erb b/website/source/404.html.erb deleted file mode 100644 index f49742d5d..000000000 --- a/website/source/404.html.erb +++ /dev/null @@ -1,11 +0,0 @@ ---- -layout: "inner" -noindex: true -page_title: "404" ---- - -

Page not found

- -

-Unfortunately, the page you requested can't be found. -

diff --git a/website/source/404.html.md b/website/source/404.html.md new file mode 100644 index 000000000..e99ce088b --- /dev/null +++ b/website/source/404.html.md @@ -0,0 +1,14 @@ +--- +layout: "inner" +page_title: "Not Found" +noindex: true +description: |- + Page not found! +--- + +# Page Not Found + +Sorry, the page you tried to visit does not exist. This could be our fault, +and if so we will fix that up right away. + +Please go back, or go back to get back on track. diff --git a/website/source/android-manifest.json.erb b/website/source/android-manifest.json.erb new file mode 100644 index 000000000..224636a38 --- /dev/null +++ b/website/source/android-manifest.json.erb @@ -0,0 +1,18 @@ +{ + "name": "HashiCorp Terraform", + "icons": [ + { + "src": "<%= image_path('favicons/android-chrome-192x192.png') %>", + "sizes": "192x192", + "type": "image/png" + }, + { + "src": "<%= image_path('favicons/android-chrome-512x512.png') %>", + "sizes": "512x512", + "type": "image/png" + } + ], + "theme_color": "#ffffff", + "background_color": "#ffffff", + "display": "standalone" +} diff --git a/website/source/assets/files/press-kit.zip b/website/source/assets/files/press-kit.zip new file mode 100644 index 000000000..dde265f79 Binary files /dev/null and b/website/source/assets/files/press-kit.zip differ diff --git a/website/source/assets/images/bg-galaxy.jpg b/website/source/assets/images/bg-galaxy.jpg deleted file mode 100644 index 587004afa..000000000 Binary files a/website/source/assets/images/bg-galaxy.jpg and /dev/null differ diff --git a/website/source/assets/images/bg-static.png b/website/source/assets/images/bg-static.png deleted file mode 100644 index 7d6436172..000000000 Binary files a/website/source/assets/images/bg-static.png and /dev/null differ diff --git a/website/source/assets/images/customer-logos/capital-one.svg b/website/source/assets/images/customer-logos/capital-one.svg deleted file mode 100644 index a03474332..000000000 --- a/website/source/assets/images/customer-logos/capital-one.svg +++ /dev/null @@ -1,289 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/website/source/assets/images/customer-logos/hbo.svg b/website/source/assets/images/customer-logos/hbo.svg deleted file mode 100644 index 784d540d0..000000000 --- a/website/source/assets/images/customer-logos/hbo.svg +++ /dev/null @@ -1,18 +0,0 @@ - - - - - - - - - - diff --git a/website/source/assets/images/customer-logos/home-depot.svg b/website/source/assets/images/customer-logos/home-depot.svg deleted file mode 100644 index 553b5ef97..000000000 --- a/website/source/assets/images/customer-logos/home-depot.svg +++ /dev/null @@ -1,63 +0,0 @@ - - - - - - - - - - - diff --git a/website/source/assets/images/customer-logos/hotels-dot-com.svg b/website/source/assets/images/customer-logos/hotels-dot-com.svg deleted file mode 100644 index 1d84ec6e6..000000000 --- a/website/source/assets/images/customer-logos/hotels-dot-com.svg +++ /dev/null @@ -1,50 +0,0 @@ - - - - - - - - - - - - - - - - diff --git a/website/source/assets/images/customer-logos/nike.svg b/website/source/assets/images/customer-logos/nike.svg deleted file mode 100644 index 51fa23ceb..000000000 --- a/website/source/assets/images/customer-logos/nike.svg +++ /dev/null @@ -1,66 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/website/source/assets/images/customer-logos/target.svg b/website/source/assets/images/customer-logos/target.svg deleted file mode 100644 index 4d8094a6a..000000000 --- a/website/source/assets/images/customer-logos/target.svg +++ /dev/null @@ -1,29 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - diff --git a/website/source/assets/images/docs/atlas-workflow.png b/website/source/assets/images/docs/atlas-workflow.png deleted file mode 100644 index 144e2cedc..000000000 Binary files a/website/source/assets/images/docs/atlas-workflow.png and /dev/null differ diff --git a/website/source/assets/images/graph-example.png b/website/source/assets/images/docs/graph-example.png similarity index 100% rename from website/source/assets/images/graph-example.png rename to website/source/assets/images/docs/graph-example.png diff --git a/website/source/assets/images/docs/tfe-organization-variables.png b/website/source/assets/images/docs/tfe-organization-variables.png new file mode 100644 index 000000000..0980c60c0 Binary files /dev/null and b/website/source/assets/images/docs/tfe-organization-variables.png differ diff --git a/website/source/assets/images/docs/tfe-variables.png b/website/source/assets/images/docs/tfe-variables.png new file mode 100644 index 000000000..7b0e735a0 Binary files /dev/null and b/website/source/assets/images/docs/tfe-variables.png differ diff --git a/website/source/assets/images/enterprise-callout-bg copy.svg b/website/source/assets/images/enterprise-callout-bg copy.svg new file mode 100644 index 000000000..14a97072a --- /dev/null +++ b/website/source/assets/images/enterprise-callout-bg copy.svg @@ -0,0 +1,18 @@ + + + + + + + + + + + + + + + diff --git a/website/source/assets/images/enterprise-callout-bg.svg b/website/source/assets/images/enterprise-callout-bg.svg index c7c2649f2..ee4ba0afc 100644 --- a/website/source/assets/images/enterprise-callout-bg.svg +++ b/website/source/assets/images/enterprise-callout-bg.svg @@ -1,21 +1,8 @@ - - - - - - - - - - - - - - - - + + + + + + + diff --git a/website/source/assets/images/favicon.png b/website/source/assets/images/favicon.png deleted file mode 100644 index 14d04676c..000000000 Binary files a/website/source/assets/images/favicon.png and /dev/null differ diff --git a/website/source/assets/images/favicons/android-chrome-192x192.png b/website/source/assets/images/favicons/android-chrome-192x192.png new file mode 100644 index 000000000..c35bdbed5 Binary files /dev/null and b/website/source/assets/images/favicons/android-chrome-192x192.png differ diff --git a/website/source/assets/images/favicons/android-chrome-512x512.png b/website/source/assets/images/favicons/android-chrome-512x512.png new file mode 100644 index 000000000..83a03ab49 Binary files /dev/null and b/website/source/assets/images/favicons/android-chrome-512x512.png differ diff --git a/website/source/assets/images/favicons/apple-touch-icon.png b/website/source/assets/images/favicons/apple-touch-icon.png new file mode 100644 index 000000000..91cb96176 Binary files /dev/null and b/website/source/assets/images/favicons/apple-touch-icon.png differ diff --git a/website/source/assets/images/favicons/favicon-16x16.png b/website/source/assets/images/favicons/favicon-16x16.png new file mode 100644 index 000000000..a474f146f Binary files /dev/null and b/website/source/assets/images/favicons/favicon-16x16.png differ diff --git a/website/source/assets/images/favicons/favicon-32x32.png b/website/source/assets/images/favicons/favicon-32x32.png new file mode 100644 index 000000000..576c5402f Binary files /dev/null and b/website/source/assets/images/favicons/favicon-32x32.png differ diff --git a/website/source/assets/images/favicons/favicon.ico b/website/source/assets/images/favicons/favicon.ico new file mode 100644 index 000000000..fd3d1442e Binary files /dev/null and b/website/source/assets/images/favicons/favicon.ico differ diff --git a/website/source/assets/images/favicons/mstile-150x150.png b/website/source/assets/images/favicons/mstile-150x150.png new file mode 100644 index 000000000..d81ed5df7 Binary files /dev/null and b/website/source/assets/images/favicons/mstile-150x150.png differ diff --git a/website/source/assets/images/favicons/safari-pinned-tab.svg b/website/source/assets/images/favicons/safari-pinned-tab.svg new file mode 100644 index 000000000..d331c170c --- /dev/null +++ b/website/source/assets/images/favicons/safari-pinned-tab.svg @@ -0,0 +1,22 @@ + + + + +Created by potrace 1.11, written by Peter Selinger 2001-2013 + + + + + + + + diff --git a/website/source/assets/images/feature-card-create.svg b/website/source/assets/images/feature-card-create.svg index 0c77fe438..c45fc221e 100644 --- a/website/source/assets/images/feature-card-create.svg +++ b/website/source/assets/images/feature-card-create.svg @@ -1,15 +1,6 @@ - - - - - - - - - - + + + + + diff --git a/website/source/assets/images/feature-card-plan.svg b/website/source/assets/images/feature-card-plan.svg index 765579dce..c1a010733 100644 --- a/website/source/assets/images/feature-card-plan.svg +++ b/website/source/assets/images/feature-card-plan.svg @@ -1,31 +1,3 @@ - - - - - - - - - - - - - - - - - + + diff --git a/website/source/assets/images/feature-card-write.svg b/website/source/assets/images/feature-card-write.svg index 3e81bc1b2..9be021d9a 100644 --- a/website/source/assets/images/feature-card-write.svg +++ b/website/source/assets/images/feature-card-write.svg @@ -1,24 +1,3 @@ - - - - - - - - - - - - - - - - - - - - + + diff --git a/website/source/assets/images/feature-create-bg.svg b/website/source/assets/images/feature-create-bg.svg index 80d89b0f8..0392a2c6a 100644 --- a/website/source/assets/images/feature-create-bg.svg +++ b/website/source/assets/images/feature-create-bg.svg @@ -1,312 +1,45 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/website/source/assets/images/feature-plan-bg.svg b/website/source/assets/images/feature-plan-bg.svg index 31059abf9..9d9e3e012 100644 --- a/website/source/assets/images/feature-plan-bg.svg +++ b/website/source/assets/images/feature-plan-bg.svg @@ -1,429 +1,30 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/website/source/assets/images/feature-plan-sm-bg.svg b/website/source/assets/images/feature-plan-sm-bg.svg deleted file mode 100644 index cf38d86f0..000000000 --- a/website/source/assets/images/feature-plan-sm-bg.svg +++ /dev/null @@ -1,398 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/website/source/assets/images/feature-write-bg.svg b/website/source/assets/images/feature-write-bg.svg index c3ecbb76b..32224066e 100644 --- a/website/source/assets/images/feature-write-bg.svg +++ b/website/source/assets/images/feature-write-bg.svg @@ -1,253 +1,18 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + diff --git a/website/source/assets/images/footer-hashicorp-logo.png b/website/source/assets/images/footer-hashicorp-logo.png deleted file mode 100644 index 96ac85814..000000000 Binary files a/website/source/assets/images/footer-hashicorp-logo.png and /dev/null differ diff --git a/website/source/assets/images/footer-hashicorp-logo@2x.png b/website/source/assets/images/footer-hashicorp-logo@2x.png deleted file mode 100644 index 34699040a..000000000 Binary files a/website/source/assets/images/footer-hashicorp-logo@2x.png and /dev/null differ diff --git a/website/source/assets/images/footer-hashicorp-white-logo.png b/website/source/assets/images/footer-hashicorp-white-logo.png deleted file mode 100644 index 9fddc9779..000000000 Binary files a/website/source/assets/images/footer-hashicorp-white-logo.png and /dev/null differ diff --git a/website/source/assets/images/footer-hashicorp-white-logo@2x.png b/website/source/assets/images/footer-hashicorp-white-logo@2x.png deleted file mode 100644 index a0b479799..000000000 Binary files a/website/source/assets/images/footer-hashicorp-white-logo@2x.png and /dev/null differ diff --git a/website/source/assets/images/header-download-icon.png b/website/source/assets/images/header-download-icon.png deleted file mode 100644 index bface9334..000000000 Binary files a/website/source/assets/images/header-download-icon.png and /dev/null differ diff --git a/website/source/assets/images/header-download-icon@2x.png b/website/source/assets/images/header-download-icon@2x.png deleted file mode 100644 index bd1c9a313..000000000 Binary files a/website/source/assets/images/header-download-icon@2x.png and /dev/null differ diff --git a/website/source/assets/images/header-github-icon.png b/website/source/assets/images/header-github-icon.png deleted file mode 100644 index 5bef9cb89..000000000 Binary files a/website/source/assets/images/header-github-icon.png and /dev/null differ diff --git a/website/source/assets/images/header-github-icon@2x.png b/website/source/assets/images/header-github-icon@2x.png deleted file mode 100644 index ab15e12df..000000000 Binary files a/website/source/assets/images/header-github-icon@2x.png and /dev/null differ diff --git a/website/source/assets/images/header-nav-divider.png b/website/source/assets/images/header-nav-divider.png deleted file mode 100644 index 130f1c71d..000000000 Binary files a/website/source/assets/images/header-nav-divider.png and /dev/null differ diff --git a/website/source/assets/images/header-nav-divider@2x.png b/website/source/assets/images/header-nav-divider@2x.png deleted file mode 100644 index a747226e5..000000000 Binary files a/website/source/assets/images/header-nav-divider@2x.png and /dev/null differ diff --git a/website/source/assets/images/hero-bg.png b/website/source/assets/images/hero-bg.png deleted file mode 100644 index 61cac8172..000000000 Binary files a/website/source/assets/images/hero-bg.png and /dev/null differ diff --git a/website/source/assets/images/latest-announce-bg.svg b/website/source/assets/images/latest-announce-bg.svg deleted file mode 100644 index 1513807fd..000000000 --- a/website/source/assets/images/latest-announce-bg.svg +++ /dev/null @@ -1,142 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/website/source/assets/images/logo-hashicorp.svg b/website/source/assets/images/logo-hashicorp.svg new file mode 100644 index 000000000..e98f8b71f --- /dev/null +++ b/website/source/assets/images/logo-hashicorp.svg @@ -0,0 +1,7 @@ + + + + + + + diff --git a/website/source/assets/images/logo-header-black@2x.png b/website/source/assets/images/logo-header-black@2x.png deleted file mode 100644 index 312f8692e..000000000 Binary files a/website/source/assets/images/logo-header-black@2x.png and /dev/null differ diff --git a/website/source/assets/images/logo-header.png b/website/source/assets/images/logo-header.png deleted file mode 100644 index 76f5eae3a..000000000 Binary files a/website/source/assets/images/logo-header.png and /dev/null differ diff --git a/website/source/assets/images/logo-header.svg b/website/source/assets/images/logo-header.svg deleted file mode 100644 index 7f9e690f4..000000000 --- a/website/source/assets/images/logo-header.svg +++ /dev/null @@ -1,30 +0,0 @@ - - - HashiCorp Terraform - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/website/source/assets/images/logo-header@2x.png b/website/source/assets/images/logo-header@2x.png deleted file mode 100644 index 1fc0bf2e3..000000000 Binary files a/website/source/assets/images/logo-header@2x.png and /dev/null differ diff --git a/website/source/assets/images/logo-static.png b/website/source/assets/images/logo-static.png deleted file mode 100644 index 7cfecc36a..000000000 Binary files a/website/source/assets/images/logo-static.png and /dev/null differ diff --git a/website/source/assets/images/logo-text.svg b/website/source/assets/images/logo-text.svg new file mode 100644 index 000000000..67c40535c --- /dev/null +++ b/website/source/assets/images/logo-text.svg @@ -0,0 +1,7 @@ + + + + + + + diff --git a/website/source/assets/images/logo_large.png b/website/source/assets/images/logo_large.png deleted file mode 100644 index 94b66fdae..000000000 Binary files a/website/source/assets/images/logo_large.png and /dev/null differ diff --git a/website/source/assets/images/news/webinar-Terraform-4-4-2017.png b/website/source/assets/images/news/webinar-Terraform-4-4-2017.png new file mode 100644 index 000000000..8db9560c9 Binary files /dev/null and b/website/source/assets/images/news/webinar-Terraform-4-4-2017.png differ diff --git a/website/source/assets/images/og-image.png b/website/source/assets/images/og-image.png new file mode 100644 index 000000000..dbc7d61cc Binary files /dev/null and b/website/source/assets/images/og-image.png differ diff --git a/website/source/assets/images/readme.png b/website/source/assets/images/readme.png deleted file mode 100644 index bec5aa7f5..000000000 Binary files a/website/source/assets/images/readme.png and /dev/null differ diff --git a/website/source/assets/images/sidebar-wire.png b/website/source/assets/images/sidebar-wire.png deleted file mode 100644 index 87ccdf351..000000000 Binary files a/website/source/assets/images/sidebar-wire.png and /dev/null differ diff --git a/website/source/assets/images/terraform-enterprise-logo.svg b/website/source/assets/images/terraform-enterprise-logo.svg index 5c1b21abe..7bbdd0055 100644 --- a/website/source/assets/images/terraform-enterprise-logo.svg +++ b/website/source/assets/images/terraform-enterprise-logo.svg @@ -1,47 +1,27 @@ - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/website/source/assets/images/webinar-Terraform-4-4-2017.jpg b/website/source/assets/images/webinar-Terraform-4-4-2017.jpg deleted file mode 100644 index 1bc50497c..000000000 Binary files a/website/source/assets/images/webinar-Terraform-4-4-2017.jpg and /dev/null differ diff --git a/website/source/assets/images/webinar-Terraform-4-4-2017@2x.jpg b/website/source/assets/images/webinar-Terraform-4-4-2017@2x.jpg deleted file mode 100644 index 17b3aa725..000000000 Binary files a/website/source/assets/images/webinar-Terraform-4-4-2017@2x.jpg and /dev/null differ diff --git a/website/source/assets/images/webinar-image.jpg b/website/source/assets/images/webinar-image.jpg deleted file mode 100644 index c670b8594..000000000 Binary files a/website/source/assets/images/webinar-image.jpg and /dev/null differ diff --git a/website/source/assets/images/webinar-image@2x.jpg b/website/source/assets/images/webinar-image@2x.jpg deleted file mode 100644 index f03b20ac9..000000000 Binary files a/website/source/assets/images/webinar-image@2x.jpg and /dev/null differ diff --git a/website/source/assets/images/white-wireframe.png b/website/source/assets/images/white-wireframe.png deleted file mode 100644 index 831c0145b..000000000 Binary files a/website/source/assets/images/white-wireframe.png and /dev/null differ diff --git a/website/source/assets/images/white-wireframe@2x.png b/website/source/assets/images/white-wireframe@2x.png deleted file mode 100644 index 3afe389ea..000000000 Binary files a/website/source/assets/images/white-wireframe@2x.png and /dev/null differ diff --git a/website/source/assets/javascripts/app/_Docs.js b/website/source/assets/javascripts/app/_Docs.js deleted file mode 100644 index 5f35a8cd7..000000000 --- a/website/source/assets/javascripts/app/_Docs.js +++ /dev/null @@ -1,46 +0,0 @@ -(function(){ - -var Init = { - - start: function(){ - var classname = this.hasClass(document.body, 'page-sub'); - - if (classname) { - this.addEventListeners(); - } - }, - - hasClass: function (elem, className) { - return new RegExp(' ' + className + ' ').test(' ' + elem.className + ' '); - }, - - addEventListeners: function(){ - var _this = this; - //console.log(document.querySelectorAll('.navbar-static-top')[0]); - window.addEventListener('resize', _this.resizeImage, false); - - this.resizeImage(); - }, - - resizeImage: function(){ - - var header = document.getElementById('header'), - footer = document.getElementById('footer'), - main = document.getElementById('main-content'), - vp = window.innerHeight, - bodyHeight = document.body.clientHeight, - hHeight = header.clientHeight, - fHeight = footer.clientHeight, - withMinHeight = hHeight + fHeight + 830; - - if(withMinHeight < vp && bodyHeight < vp){ - var newHeight = (vp - (hHeight+fHeight)) + 'px'; - main.style.height = newHeight; - } - } - -}; - -Init.start(); - -})(); diff --git a/website/source/assets/javascripts/app/_Engine.Particle.Fixed.js b/website/source/assets/javascripts/app/_Engine.Particle.Fixed.js deleted file mode 100644 index 530edad9c..000000000 --- a/website/source/assets/javascripts/app/_Engine.Particle.Fixed.js +++ /dev/null @@ -1,77 +0,0 @@ -(function( - Particle, - Engine, - Vector -){ - -Particle.Fixed = function(width, height){ - var targetX, targetY; - - this.radius = Engine.getRandomFloat(0.1, 1); - // this.fillA = 'rgba(136,67,237,' + Engine.getRandomFloat(0.4, 0.5) + ')'; - // this.fillB = 'rgba(136,67,237,' + Engine.getRandomFloat(0.51, 0.6) + ')'; - this.fillA = '#3a1066'; - this.fillB = '#561799'; - this.frameMax = Engine.getRandomInt(4, 10); - - this.max = { - x: width + this.maxRadius, - y: height + this.maxRadius - }; - - this.min = { - x: 0 - this.maxRadius, - y: 0 - this.maxRadius - }; - - targetX = Engine.getRandomInt(0 + this.radius, width + this.radius); - targetY = Engine.getRandomInt(0 + this.radius, height + this.radius); - - this.pos = new Vector(targetX, targetY); -}; - -Engine.Particle.Fixed.prototype = { - - radius: 1, - - pos: { - x: 0, - y: 0 - }, - - frame: 0, - showA: false, - - update: function(engine){ - this.frame++; - if (this.frame > this.frameMax) { - this.frame = 0; - this.showA = !this.showA; - } - return this; - }, - - draw: function(ctx, scale){ - // Draw a circle - far less performant - ctx.beginPath(); - ctx.arc( - this.pos.x * scale >> 0, - this.pos.y * scale >> 0, - this.radius * scale, - 0, - Math.PI * 2, - false - ); - if (this.showA) { - ctx.fillStyle = this.fillA; - } else { - ctx.fillStyle = this.fillB; - } - ctx.fill(); - - return this; - } - -}; - -})(window.Engine.Particle, window.Engine, window.Vector); diff --git a/website/source/assets/javascripts/app/_Engine.Particle.js b/website/source/assets/javascripts/app/_Engine.Particle.js deleted file mode 100644 index 6666ac8c9..000000000 --- a/website/source/assets/javascripts/app/_Engine.Particle.js +++ /dev/null @@ -1,154 +0,0 @@ -(function( - Engine, - Vector -){ - -Engine.Particle = function(width, height){ - var side, targetX, targetY; - this.accel = Vector.coerce(this.accel); - this.vel = Vector.coerce(this.vel); - this.pos = new Vector(0, 0); - - this.maxRadius = Engine.getRandomFloat(0.1, 2.5); - // this.maxSpeed = Engine.getRandomFloat(0.01, 1000); - this.maxSpeed = Engine.getRandomFloat(20, 1000); - - // Pick a random target - side = Engine.getRandomInt(0, 3); - if (side === 0 || side === 2) { - targetY = (side === 0) ? -(height / 2) : (height / 2); - targetX = Engine.getRandomInt(-(width / 2), width / 2); - } else { - targetY = Engine.getRandomInt(-(height / 2), height / 2); - targetX = (side === 3) ? -(width / 2) : (width / 2); - } - - this.target = new Vector(targetX, targetY); - this.getAccelVector(); - - this.maxDistance = this.distanceTo(this.target); - - this.fillA = '#8750c2'; - this.fillB = '#b976ff'; - this.frameMax = Engine.getRandomInt(1, 5); -}; - -Engine.Particle.prototype = { - - radius: 1, - - frame: 0, - showA: false, - - accel: { - x: 0, - y: 0 - }, - - vel: { - x: 0, - y: 0 - }, - - pos: { - x: 0, - y: 0 - }, - - opacity: 1, - - maxSpeed: 1500, - maxForce: 1500, - - getAccelVector: function(){ - this.accel = Vector.sub(this.target, this.pos) - .normalize() - .mult(this.maxSpeed); - }, - - update: function(engine){ - var distancePercent, halfWidth, halfHeight; - - this.vel - .add(this.accel) - .limit(this.maxSpeed); - - this.pos.add(Vector.mult(this.vel, engine.tick)); - - halfWidth = engine.width / 2 + this.maxRadius; - halfHeight = engine.height / 2 + this.maxRadius; - - if ( - this.pos.x < -(halfWidth) || - this.pos.x > halfWidth || - this.pos.y < -(halfHeight) || - this.pos.y > halfHeight - ) { - this.kill(engine); - } - - distancePercent = (this.maxDistance - this.distanceTo(this.target)) / this.maxDistance; - this.radius = Math.max(0.1, this.maxRadius * distancePercent); - - this.frame++; - if (this.frame > this.frameMax) { - this.frame = 0; - this.showA = !this.showA; - } - - if (this.showA) { - engine.particlesA[engine.particlesA.length] = this; - } else { - engine.particlesB[engine.particlesB.length] = this; - } - - return this; - }, - - draw: function(ctx, scale){ - if (this.radius < 0.25) { - return; - } - - if (this.showA) { - ctx.fillStyle = this.fillA; - } else { - ctx.fillStyle = this.fillB; - } - - // Draw a square - very performant - ctx.fillRect( - this.pos.x * scale >> 0, - this.pos.y * scale >> 0, - this.radius * scale, - this.radius * scale - ); - - // Draw a circle - far less performant - // ctx.beginPath(); - // ctx.arc( - // this.pos.x * scale, - // this.pos.y * scale, - // this.radius * scale, - // 0, - // Math.PI * 2, - // false - // ); - // ctx.fill(); - - return this; - }, - - kill: function(engine){ - engine._deferredParticles.push(this); - return this; - }, - - distanceTo: function(target) { - var xd = this.pos.x - target.x; - var yd = this.pos.y - target.y; - return Math.sqrt(xd * xd + yd * yd ); - } -}; - -})(window.Engine, window.Vector); diff --git a/website/source/assets/javascripts/app/_Engine.Point.Puller.js b/website/source/assets/javascripts/app/_Engine.Point.Puller.js deleted file mode 100644 index 910093a60..000000000 --- a/website/source/assets/javascripts/app/_Engine.Point.Puller.js +++ /dev/null @@ -1,153 +0,0 @@ -(function( - Engine, - Vector -){ - -Engine.Point.Puller = function(id, x, y, shapeSize){ - this.id = id; - - this.shapeSize = shapeSize; - this.ref = new Vector(x, y); - - this.pos = new Vector( - x * shapeSize.x, - y * shapeSize.y - ); - - this.home = this.pos.clone(); - this.accel = Vector.coerce(this.accel); - this.vel = Vector.coerce(this.vel); -}; - -Engine.Point.Puller.prototype = { - - fillStyle: null, - defaultFillstyle: '#b976ff', - chasingFillstyle: '#ff6b6b', - - radius: 1, - - maxSpeed: 160, - maxForce: 50, - - pos: { - x: 0, - y: 0 - }, - - accel: { - x: 0, - y: 0 - }, - - vel: { - x: 0, - y: 0 - }, - - aRad: 200, - - safety: 0.25, - - resize: function(){ - this.home.x = this.pos.x = this.ref.x * this.shapeSize.x; - this.home.y = this.pos.y = this.ref.y * this.shapeSize.y; - - return this; - }, - - update: function(engine){ - var target = Vector.coerce(engine.mouse), - distanceToMouse, toHome, mag, safety; - - target.x += (this.shapeSize.x - engine.width) / 2; - target.y += (this.shapeSize.y - engine.height) / 2; - - distanceToMouse = this.distanceTo(target); - - this.accel.mult(0); - - if (distanceToMouse < this.aRad) { - this._chasing = true; - this.toChase(target); - this.fillStyle = this.chasingFillstyle; - } else { - this._chasing = false; - this.fillStyle = this.defaultFillstyle; - } - - this.toChase(this.home, this.maxForce / 2); - - this.vel.add(this.accel); - this.pos.add( - Vector.mult(this.vel, engine.tick) - ); - - toHome = Vector.sub(this.home, this.pos); - mag = toHome.mag(); - safety = this.aRad * (this.safety * 3); - if (mag > this.aRad - safety) { - toHome.normalize(); - toHome.mult(this.aRad - safety); - this.pos = Vector.sub(this.home, toHome); - } - - target = null; - toHome = null; - return this; - }, - - toChase: function(target, maxForce){ - var desired, steer, distance, mult, safety; - - maxForce = maxForce || this.maxForce; - - target = Vector.coerce(target); - desired = Vector.sub(target, this.pos); - distance = desired.mag(); - desired.normalize(); - - safety = this.aRad * this.safety; - - if (distance < safety) { - mult = Engine.map(distance, 0, safety, 0, this.maxSpeed); - } else if (distance > this.aRad - safety){ - mult = Engine.map(this.aRad - distance, 0, safety, 0, this.maxSpeed); - } else { - mult = this.maxSpeed; - } - - desired.mult(mult); - - steer = Vector.sub(desired, this.vel); - steer.limit(maxForce); - this.accel.add(steer); - - target = null; - desired = null; - steer = null; - }, - - draw: function(ctx, scale){ - ctx.fillStyle = this.fillStyle; - ctx.fillRect( - (this.pos.x - this.radius / 2) * scale >> 0, - (this.pos.y - this.radius / 2) * scale >> 0, - this.radius * scale, - this.radius * scale - ); - - return this; - }, - - distanceTo: function(target) { - var xd = this.home.x - target.x; - var yd = this.home.y - target.y; - return Math.sqrt(xd * xd + yd * yd ); - } -}; - -})( - window.Engine, - window.Vector -); diff --git a/website/source/assets/javascripts/app/_Engine.Point.js b/website/source/assets/javascripts/app/_Engine.Point.js deleted file mode 100644 index 4d53eb265..000000000 --- a/website/source/assets/javascripts/app/_Engine.Point.js +++ /dev/null @@ -1,118 +0,0 @@ -(function( - Engine, - Vector -){ 'use strict'; - -Engine.Point = function(id, x, y, shapeSize){ - this.id = id; - - this.shapeSize = shapeSize; - this.ref = new Vector(x, y); - - this.pos = new Vector( - x * shapeSize.x, - y * shapeSize.y - ); - - this.target = this.pos.clone(); - this.pos.x = shapeSize.x / 2; - this.pos.y = shapeSize.y / 2; - this.accel = Vector.coerce(this.accel); - this.vel = Vector.coerce(this.vel); - - this.stiffness = Engine.getRandomFloat(150, 600); - this.friction = Engine.getRandomFloat(12, 18); -}; - -Engine.Point.prototype = { - - radius: 1, - - stiffness : 200, - friction : 13, - threshold : 0.03, - - pos: { - x: 0, - y: 0 - }, - - accel: { - x: 0, - y: 0 - }, - - vel : { - x: 0, - y: 0 - }, - - target: { - x: 0, - y: 0 - }, - - resize: function(){ - this.target.x = this.pos.x = this.ref.x * this.shapeSize.x; - this.target.y = this.pos.y = this.ref.y * this.shapeSize.y; - }, - - updateBreathingPhysics: function(){ - this.stiffness = Engine.getRandomFloat(2, 4); - this.friction = Engine.getRandomFloat(1, 2); - }, - - updateTarget: function(newSize){ - var diff; - - this.target.x = this.ref.x * newSize.x; - this.target.y = this.ref.y * newSize.y; - - diff = Vector.sub(newSize, this.shapeSize).div(2); - - this.target.sub(diff); - - this.target.add({ - x: Engine.getRandomFloat(-3, 3), - y: Engine.getRandomFloat(-3, 3) - }); - }, - - update: function(engine){ - var newAccel; - - newAccel = Vector.sub(this.target, this.pos) - .mult(this.stiffness) - .sub(Vector.mult(this.vel, this.friction)); - - this.accel.set(newAccel); - - this.vel.add(Vector.mult(this.accel, engine.tick)); - - this.pos.add( - Vector.mult(this.vel, engine.tick) - ); - - newAccel = null; - - return this; - }, - - draw: function(ctx, scale){ - ctx.beginPath(); - ctx.arc( - this.pos.x * scale, - this.pos.y * scale, - this.radius * scale, - 0, - Math.PI * 2, - false - ); - ctx.fillStyle = '#ffffff'; - ctx.fill(); - return this; - } - -}; - -})(window.Engine, window.Vector); diff --git a/website/source/assets/javascripts/app/_Engine.Polygon.Puller.js b/website/source/assets/javascripts/app/_Engine.Polygon.Puller.js deleted file mode 100644 index 3ad4227b7..000000000 --- a/website/source/assets/javascripts/app/_Engine.Polygon.Puller.js +++ /dev/null @@ -1,29 +0,0 @@ -(function( - Engine, - Vector -){ - -Engine.Polygon.Puller = function(a, b, c, color, simple){ - this.a = a; - this.b = b; - this.c = c; - - this.strokeStyle = '#ffffff'; -}; - -Engine.Polygon.Puller.prototype = { - - checkChasing: function(){ - if ( - this.a._chasing === true && - this.b._chasing === true && - this.c._chasing === true - ) { - return true; - } - return false; - } - -}; - -})(window.Engine, window.Vector); diff --git a/website/source/assets/javascripts/app/_Engine.Polygon.js b/website/source/assets/javascripts/app/_Engine.Polygon.js deleted file mode 100644 index 74e80a96d..000000000 --- a/website/source/assets/javascripts/app/_Engine.Polygon.js +++ /dev/null @@ -1,80 +0,0 @@ -(function( - Engine, - Vector -){ - -Engine.Polygon = function(a, b, c, color, strokeColor){ - this.a = a; - this.b = b; - this.c = c; - - this.color = Engine.clone(color); - this.strokeColor = strokeColor ? Engine.clone(strokeColor) : Engine.clone(color); - - if (strokeColor) { - this.strokeColor = Engine.clone(strokeColor); - } else { - this.strokeColor = Engine.clone(color); - } - - this.strokeWidth = 0.25; - this.maxStrokeS = this.strokeColor.s; - this.maxStrokeL = this.strokeColor.l; - this.maxColorL = this.color.l; - - this.strokeColor.s = 0; - this.strokeColor.l = 100; - this.color.l = 0; - - this.fillStyle = this.hslaTemplate.substitute(this.color); - this.strokeStyle = this.hslaTemplate.substitute(this.strokeColor); -}; - -Engine.Polygon.prototype = { - - rgbaTemplate: 'rgba({r},{g},{b},{a})', - hslaTemplate: 'hsla({h},{s}%,{l}%,{a})', - - hueShiftSpeed: 20, - duration: 2, - delay: 0, - start: 0, - - // Determine color fill? - update: function(engine){ - var delta; - - if (this.simple) { - return; - } - - this.start += engine.tick; - - delta = this.start; - - if ( - delta > this.delay && - delta < this.delay + this.duration + 1 && - this.color.l < this.maxColorL - ) { - this.color.l = this.maxColorL * (delta - this.delay) / this.duration; - - this.strokeColor.s = this.maxStrokeS * (delta - this.delay) / this.duration; - this.strokeColor.l = (this.maxStrokeL - 100) * (delta - this.delay) / this.duration + 100; - - this.strokeWidth = 1.5 * (delta - this.delay) / this.duration + 0.25; - - if (this.color.l > this.maxColorL) { - this.color.l = this.maxColorL; - this.strokeColor.l = this.maxStrokeL; - this.strokeWidth = 1.5; - } - - this.strokeStyle = this.hslaTemplate.substitute(this.strokeColor); - this.fillStyle = this.hslaTemplate.substitute(this.color); - } - } - -}; - -})(window.Engine, window.Vector); diff --git a/website/source/assets/javascripts/app/_Engine.Shape.Puller.js b/website/source/assets/javascripts/app/_Engine.Shape.Puller.js deleted file mode 100644 index 27f7fd7d5..000000000 --- a/website/source/assets/javascripts/app/_Engine.Shape.Puller.js +++ /dev/null @@ -1,179 +0,0 @@ -(function( - Engine, - Point, - Polygon, - Vector -){ - -Engine.Shape.Puller = function(width, height, json){ - var i, ref, point, poly; - - this.pos = new Vector(0, 0); - this.size = new Vector(width, height); - this.heightRatio = json.data.width / json.data.height; - this.widthRatio = json.data.ar; - - this.resize(width, height, true); - - ref = {}; - this.points = []; - this.polygons = []; - - for (i = 0; i < json.points.length; i++) { - point = new Point( - json.points[i].id, - json.points[i].x, - json.points[i].y, - this.size - ); - ref[point.id] = point; - this.points.push(point); - } - - for (i = 0; i < json.polygons.length; i++) { - poly = json.polygons[i]; - this.polygons.push(new Polygon( - ref[poly.points[0]], - ref[poly.points[1]], - ref[poly.points[2]], - poly.color - )); - this.polygons[this.polygons.length - 1].noFill = true; - } - - this.ref = undefined; -}; - -Engine.Shape.Puller.prototype = { - - alpha: 0, - - sizeOffset: 100, - - resize: function(width, height, sizeOnly){ - var len, p, newWidth, newHeight; - - newHeight = height + this.sizeOffset; - newWidth = this.size.y * this.heightRatio; - - if (newWidth < width) { - newWidth = width + this.sizeOffset; - newHeight = newWidth * this.widthRatio; - } - - this.size.y = newHeight; - this.size.x = newWidth; - - this.pos.x = -(newWidth / 2); - this.pos.y = -(newHeight / 2); - - if (sizeOnly) { - return this; - } - - for (p = 0, len = this.points.length; p < len; p++) { - this.points[p].resize(); - } - }, - - update: function(engine){ - var p; - - for (p = 0; p < this.points.length; p++) { - this.points[p].update(engine); - } - - if (this.alpha < 1) { - this.alpha = Math.min(this.alpha + 2 * engine.tick, 1); - } - - return this; - }, - - draw: function(ctx, scale, engine){ - var p, poly; - - ctx.translate( - this.pos.x * scale >> 0, - this.pos.y * scale >> 0 - ); - - if (this.alpha < 1) { - ctx.globalAlpha = this.alpha; - } - - ctx.beginPath(); - for (p = 0; p < this.polygons.length; p++) { - poly = this.polygons[p]; - ctx.moveTo( - poly.a.pos.x * scale >> 0, - poly.a.pos.y * scale >> 0 - ); - ctx.lineTo( - poly.b.pos.x * scale >> 0, - poly.b.pos.y * scale >> 0 - ); - ctx.lineTo( - poly.c.pos.x * scale >> 0, - poly.c.pos.y * scale >> 0 - ); - ctx.lineTo( - poly.a.pos.x * scale >> 0, - poly.a.pos.y * scale >> 0 - ); - } - ctx.closePath(); - ctx.lineWidth = 0.4 * scale; - ctx.strokeStyle = 'rgba(108,0,243,0.15)'; - ctx.stroke(); - - if (this.alpha < 1) { - ctx.globalAlpha = 1; - } - - for (p = 0; p < this.points.length; p++) { - this.points[p].draw(ctx, scale); - } - - ctx.beginPath(); - for (p = 0; p < this.polygons.length; p++) { - if (this.polygons[p].checkChasing()) { - poly = this.polygons[p]; - ctx.moveTo( - poly.a.pos.x * scale >> 0, - poly.a.pos.y * scale >> 0 - ); - ctx.lineTo( - poly.b.pos.x * scale >> 0, - poly.b.pos.y * scale >> 0 - ); - ctx.lineTo( - poly.c.pos.x * scale >> 0, - poly.c.pos.y * scale >> 0 - ); - ctx.lineTo( - poly.a.pos.x * scale >> 0, - poly.a.pos.y * scale >> 0 - ); - } - } - ctx.closePath(); - ctx.fillStyle = 'rgba(108,0,243,0.05)'; - ctx.fill(); - - ctx.setTransform(1, 0, 0, 1, 0, 0); - ctx.translate( - engine.width / 2 * engine.scale >> 0, - engine.height / 2 * engine.scale >> 0 - ); - return this; - } - -}; - -})( - window.Engine, - window.Engine.Point.Puller, - window.Engine.Polygon.Puller, - window.Vector -); diff --git a/website/source/assets/javascripts/app/_Engine.Shape.js b/website/source/assets/javascripts/app/_Engine.Shape.js deleted file mode 100644 index 97be30c83..000000000 --- a/website/source/assets/javascripts/app/_Engine.Shape.js +++ /dev/null @@ -1,159 +0,0 @@ -(function( - Engine, - Point, - Polygon, - Vector -){ - -Engine.Shape = function(x, y, width, height, points, polygons){ - var i, ref, point, poly; - - this.pos = new Vector(x, y); - this.size = new Vector(width, height); - this.sizeRef = this.size.clone(); - - ref = {}; - this.points = []; - this.polygons = []; - - for (i = 0; i < points.length; i++) { - point = new Point( - points[i].id, - points[i].x, - points[i].y, - this.size - ); - ref[point.id] = point; - this.points.push(point); - } - - for (i = 0; i < polygons.length; i++) { - poly = polygons[i]; - this.polygons.push(new Polygon( - ref[poly.points[0]], - ref[poly.points[1]], - ref[poly.points[2]], - poly.color, - poly.stroke - )); - } -}; - -Engine.Shape.prototype = { - - breathing: false, - - breath: 0, - breathLength: 1, - breatheIn: false, - - resize: function(newSize, offset){ - var len, p; - - this.size.x = newSize; - this.size.y = newSize; - this.sizeRef.x = newSize; - this.sizeRef.y = newSize; - - this.pos.x = -(newSize / 2); - this.pos.y = -(newSize / 2 + offset); - - for (p = 0, len = this.points.length; p < len; p++) { - this.points[p].resize(); - } - }, - - startBreathing: function(){ - var p; - - this.breathing = true; - this.breath = this.breathLength; - - for (p = 0; p < this.points.length; p++) { - this.points[p].updateBreathingPhysics(); - } - }, - - breathe: function(tick){ - var p, scale, newSize; - - this.breath += tick; - - if (this.breath < this.breathLength) { - return; - } - - scale = 1; - - newSize = Vector.mult(this.sizeRef, scale); - - for (p = 0; p < this.points.length; p++) { - this.points[p].updateTarget(newSize); - } - - this.breath = 0; - }, - - update: function(engine){ - var p; - - if (this.breathing === true) { - this.breathe(engine.tick); - } - - for (p = 0; p < this.points.length; p++) { - this.points[p].update(engine); - } - - for (p = 0; p < this.polygons.length; p++) { - this.polygons[p].update(engine); - } - - return this; - }, - - draw: function(ctx, scale, engine){ - var p, poly; - - ctx.translate( - this.pos.x * scale >> 0, - this.pos.y * scale >> 0 - ); - for (p = 0; p < this.polygons.length; p++) { - poly = this.polygons[p]; - ctx.beginPath(); - ctx.moveTo( - poly.a.pos.x * scale, - poly.a.pos.y * scale - ); - ctx.lineTo( - poly.b.pos.x * scale, - poly.b.pos.y * scale - ); - ctx.lineTo( - poly.c.pos.x * scale, - poly.c.pos.y * scale - ); - ctx.closePath(); - ctx.fillStyle = poly.fillStyle; - ctx.fill(); - ctx.lineWidth = poly.strokeWidth * scale; - ctx.strokeStyle = poly.strokeStyle; - ctx.stroke(); - } - ctx.setTransform(1, 0, 0, 1, 0, 0); - ctx.translate( - engine.width / 2 * engine.scale >> 0, - engine.height / 2 * engine.scale >> 0 - ); - return this; - } - -}; - -})( - window.Engine, - window.Engine.Point, - window.Engine.Polygon, - window.Vector -); diff --git a/website/source/assets/javascripts/app/_Engine.Typewriter.js b/website/source/assets/javascripts/app/_Engine.Typewriter.js deleted file mode 100644 index 61762c41c..000000000 --- a/website/source/assets/javascripts/app/_Engine.Typewriter.js +++ /dev/null @@ -1,71 +0,0 @@ -/* jshint unused:false */ -/* global console */ -(function(Engine){ 'use strict'; - -Engine.Typewriter = function(element){ - this.element = element; - this.content = this.element.textContent.split(''); - this.element.innerHTML = ''; - this.element.style.visibility = 'visible'; -}; - -Engine.Typewriter.prototype = { - - running: false, - - letterInterval : 0.02, - spaceInterval : 0.4, - - charCount: -1, - waitSpace: false, - - toDraw: '', - - start: function(){ - if (!this.content.length) { - return this; - } - - this._last = this.letterInterval; - this.running = true; - }, - - update: function(engine){ - var newChar; - - if (!this.running) { - return this; - } - - this._last += engine.tick; - - if (this.waitSpace && this._last < this.spaceInterval) { - return this; - } - - if (!this.waitSpace && this._last < this.letterInterval){ - return this; - } - - this._last = 0; - newChar = this.content.shift(); - this.toDraw += newChar; - - if (newChar === ',') { - this.waitSpace = true; - } else { - this.waitSpace = false; - } - - this.element.innerHTML = this.toDraw + '_'; - - if (!this.content.length) { - this.running = false; - } - - return this; - } - -}; - -})(window.Engine); diff --git a/website/source/assets/javascripts/app/_Engine.js b/website/source/assets/javascripts/app/_Engine.js deleted file mode 100644 index e89d61074..000000000 --- a/website/source/assets/javascripts/app/_Engine.js +++ /dev/null @@ -1,388 +0,0 @@ -(function( - Base, - Vector, - Logo, - Grid, - Chainable -){ - -var sqrt, pow, Engine; - -if (!window.requestAnimationFrame) { - window.requestAnimationFrame = (function(){ - return window.requestAnimationFrame || - window.webkitRequestAnimationFrame || - window.mozRequestAnimationFrame || - function( callback ){ - window.setTimeout(callback, 1000 / 60); - }; - })(); -} - -sqrt = Math.sqrt; -pow = Math.pow; - -Engine = Base.extend({ - - scale: window.devicePixelRatio || 1, - // scale:1, - - shapes : [], - particles : [], - particlesA : [], - particlesB : [], - - _deferredParticles: [], - - ticks: [], - - starGeneratorRate: 600, - - mouse: { - x: -9999, - y: -9999 - }, - - constructor: function(canvas, background, tagLine){ - this.canvas = canvas; - this.background = background; - this.tagLine = tagLine; - - if (!this.canvas.getContext) { - return null; - } - - this.context = this.canvas.getContext('2d'); - - this.setupEvents(); - this.setupStarfield(); - this.setupTessellation(); - this.setupMisc(); - - this.startEngine(); - }, - - startEngine: function(){ - var parent = this.canvas.parentNode; - - this.background.className += ' show'; - this.canvas.style.opacity = 1; - - // We have to pass the engine into Chainable to - // enable the timers to properly attach to the - // run/render loop - new Chainable(this) - .wait(1000) - .then(function(){ - this.starGeneratorRate = 200; - }, this) - .wait(500) - .then(function(){ - parent.className += ' state-one'; - }) - .wait(150) - .then(function(){ - parent.className += ' state-two'; - }) - .wait(150) - .then(function(){ - parent.className += ' state-three'; - }) - .wait(500) - .then(function(){ - parent.className += ' state-four'; - }) - .wait(100) - .then(function(){ - this.showShapes = true; - }, this) - .wait(1000) - .then(function(){ - this.logo.startBreathing(); - this.showGrid = true; - }, this) - .wait(1000) - .then(function(){ - this.typewriter.start(); - }, this); - - this.render(); - }, - - - setupMisc: function(){ - this.last = Date.now() / 1000; - this.render = this.render.bind(this); - - this.typewriter = new Engine.Typewriter(this.tagLine); - }, - - setupEvents: function(){ - this.resize = this.resize.bind(this); - this.resize(); - window.addEventListener('resize', this.resize, false); - - this._handleScroll = this._handleScroll.bind(this); - this._handleScroll(); - window.addEventListener('scroll', this._handleScroll, false); - - this._handleMouseCoords = this._handleMouseCoords.bind(this); - window.addEventListener('mousemove', this._handleMouseCoords, false); - }, - - setupStarfield: function(){ - this.particles = []; - // this.generateParticles(50, true); - this.generateParticles(400); - }, - - setupTessellation: function(canvas){ - var size, offset; - this.shapes = []; - if (window.innerWidth < 570) { - size = 300; - offset = 0; - } else { - size = 360; - offset = 40; - } - - this.logo = new Engine.Shape( - -(size / 2), - -(size / 2 + offset), - size, - size, - Logo.points, - Logo.polygons - ); - - this.grid = new Engine.Shape.Puller(this.width, this.height, Grid); - }, - - - getAverageTickTime: function(){ - var sum = 0, s; - - for (s = 0; s < this.ticks.length; s++) { - sum += this.ticks[s]; - } - - window.console.log('Average Tick Time:', sum / this.ticks.length); - }, - - getLongestTick: function(){ - var max = 0, index, s; - - for (s = 0; s < this.ticks.length; s++) { - if (this.ticks[s] > max) { - max = this.ticks[s]; - index = s; - } - } - - window.console.log('Max tick was:', max, 'at index:', index); - }, - - render: function(){ - var scale = this.scale, p, particle, index; - - if (this.paused) { - return; - } - - if (this.scrollY > this.height) { - window.requestAnimationFrame(this.render); - return; - } - - this.context.clearRect( - -(this.width / 2) * scale, - -(this.height / 2) * scale, - this.width * scale, - this.height * scale - ); - - this.now = Date.now() / 1000; - this.tick = Math.min(this.now - this.last, 0.017); - - // We must attach the chainable timer to the engine - // run/render loop or else things can get pretty - // out of wack - if (this.updateChainTimer) { - this.updateChainTimer(this.tick); - } - - // Update all particles... may need to be optimized - for (p = 0; p < this.particles.length; p++) { - this.particles[p].update(this); - } - - // Batch render particles based on color - // to prevent unneeded context state change - this.context.fillStyle = '#8750c2'; - for (p = 0; p < this.particlesA.length; p++) { - particle = this.particlesA[p]; - - if (particle.radius < 0.25) { - continue; - } - this.context.fillRect( - particle.pos.x * scale >> 0, - particle.pos.y * scale >> 0, - particle.radius * scale, - particle.radius * scale - ); - } - - this.context.fillStyle = '#b976ff'; - for (p = 0; p < this.particlesB.length; p++) { - particle = this.particlesB[p]; - - if (particle.radius < 0.25) { - continue; - } - this.context.fillRect( - particle.pos.x * scale >> 0, - particle.pos.y * scale >> 0, - particle.radius * scale, - particle.radius * scale - ); - } - - this.particlesA.length = 0; - this.particlesB.length = 0; - - // Remove destroyed particles - for (p = 0; p < this._deferredParticles.length; p++) { - index = this.particles.indexOf(this._deferredParticles.pop()); - if (index >= 0) { - this.particles.splice(index, 1); - } - } - - if (this.showGrid) { - this.grid - .update(this) - .draw(this.context, scale, this); - } - - if (this.showShapes) { - this.logo - .update(this) - .draw(this.context, scale, this); - } - - this.typewriter.update(this); - - this.last = this.now; - - this.generateParticles(this.starGeneratorRate * this.tick >> 0); - - window.requestAnimationFrame(this.render); - }, - - generateParticles: function(num, fixed){ - var p; - - for (p = 0; p < num; p++) { - if (fixed) { - this.particles.push(new Engine.Particle.Fixed(this.width, this.height)); - } else { - this.particles.push(new Engine.Particle(this.width, this.height)); - } - } - }, - - resize: function(){ - var scale = this.scale, - size, offset; - - if (window.innerWidth < 570) { - this.height = 560; - } else { - this.height = 700; - } - - this.width = window.innerWidth; - - this.canvas.width = this.width * scale; - this.canvas.height = this.height * scale; - - this.context.translate( - this.width / 2 * scale >> 0, - this.height / 2 * scale >> 0 - ); - this.context.lineJoin = 'bevel'; - - if (this.grid) { - this.grid.resize(this.width, this.height); - } - - if (this.logo) { - if (this.height === 560) { - size = 300; - offset = 0; - } else { - size = 360; - offset = 40; - } - this.logo.resize(size, offset); - } - }, - - _handleMouseCoords: function(event){ - this.mouse.x = event.pageX; - this.mouse.y = event.pageY; - }, - - _handleScroll: function(){ - this.scrollY = window.scrollY; - }, - - pause: function(){ - this.paused = true; - }, - - resume: function(){ - if (!this.paused) { - return; - } - this.paused = false; - this.render(); - }, - - getSnapshot: function(){ - window.open(this.canvas.toDataURL('image/png')); - } - -}); - -Engine.map = function(val, istart, istop, ostart, ostop) { - return ostart + (ostop - ostart) * ((val - istart) / (istop - istart)); -}; - -Engine.getRandomFloat = function(min, max) { - return Math.random() * (max - min) + min; -}; - -Engine.getRandomInt = function(min, max) { - return Math.floor(Math.random() * (max - min + 1) + min); -}; - -Engine.clone = function(ref) { - var clone = {}, key; - for (key in ref) { - clone[key] = ref[key]; - } - return clone; -}; - -window.Engine = Engine; - -})( - window.Base, - window.Vector, - window.Logo, - window.Grid, - window.Chainable -); diff --git a/website/source/assets/javascripts/app/_Grid.js b/website/source/assets/javascripts/app/_Grid.js deleted file mode 100644 index 9ea5055ec..000000000 --- a/website/source/assets/javascripts/app/_Grid.js +++ /dev/null @@ -1,2384 +0,0 @@ -var Grid = { - "data": { - "width": 1572, - "height": 979, - "ar": 0.6227735368956743 - }, - "points": [ - { - "id": "point-0", - "x": 0.01743002544529262, - "y": 0.045658835546476005 - }, - { - "id": "point-1", - "x": -0.0001272264631043257, - "y": 0.7701736465781408 - }, - { - "id": "point-2", - "x": 0.012468193384223917, - "y": 0.32665985699693567 - }, - { - "id": "point-7", - "x": 0.04052162849872774, - "y": 0.12277834525025537 - }, - { - "id": "point-12", - "x": 0.13568702290076337, - "y": 0.030847803881511746 - }, - { - "id": "point-17", - "x": 0.14465648854961832, - "y": 0.16772216547497446 - }, - { - "id": "point-22", - "x": 0.20184478371501274, - "y": 0.05536261491317671 - }, - { - "id": "point-27", - "x": 0.37099236641221384, - "y": 0.02696629213483146 - }, - { - "id": "point-32", - "x": 0.49357506361323156, - "y": 0.00020429009193054137 - }, - { - "id": "point-37", - "x": 0.1993002544529262, - "y": 0.16281920326864147 - }, - { - "id": "point-42", - "x": 0.30337150127226464, - "y": 0.05965270684371808 - }, - { - "id": "point-52", - "x": 0.32461832061068707, - "y": 0.1689479060265577 - }, - { - "id": "point-62", - "x": 0.4028625954198473, - "y": 0.12502553626149132 - }, - { - "id": "point-72", - "x": 0.5604325699745547, - "y": 0.13003064351378957 - }, - { - "id": "point-77", - "x": 0.5724554707379135, - "y": 0.01491317671092952 - }, - { - "id": "point-82", - "x": 0.8836513994910941, - "y": 0.05372829417773237 - }, - { - "id": "point-87", - "x": 0.9759541984732825, - "y": 0.061184882533197135 - }, - { - "id": "point-92", - "x": 0.7122137404580152, - "y": 0.07405515832482125 - }, - { - "id": "point-102", - "x": 0.6561704834605598, - "y": 0.218488253319714 - }, - { - "id": "point-107", - "x": 0.7784351145038169, - "y": 0.1319713993871297 - }, - { - "id": "point-112", - "x": 0.7912213740458014, - "y": 0.08672114402451482 - }, - { - "id": "point-122", - "x": 0.8616412213740458, - "y": 0.12941777323799797 - }, - { - "id": "point-132", - "x": 0.9780534351145039, - "y": 0.17242083758937693 - }, - { - "id": "point-142", - "x": 0.9898854961832061, - "y": 0.30960163432073545 - }, - { - "id": "point-152", - "x": 0.12888040712468193, - "y": 0.36149131767109294 - }, - { - "id": "point-162", - "x": 0.21743002544529266, - "y": 0.39662921348314606 - }, - { - "id": "point-167", - "x": 0.3361959287531807, - "y": 0.2868232890704801 - }, - { - "id": "point-182", - "x": 0.37220101781170484, - "y": 0.3344228804902961 - }, - { - "id": "point-187", - "x": 0.4620865139949109, - "y": 0.32533197139938713 - }, - { - "id": "point-192", - "x": 0.5159033078880407, - "y": 0.24106230847803883 - }, - { - "id": "point-202", - "x": 0.5856234096692112, - "y": 0.3547497446373851 - }, - { - "id": "point-217", - "x": 0.7061704834605598, - "y": 0.30643513789581206 - }, - { - "id": "point-227", - "x": 0.7717557251908397, - "y": 0.35556690500510724 - }, - { - "id": "point-232", - "x": 0.8581424936386769, - "y": 0.2822267620020429 - }, - { - "id": "point-252", - "x": 0.009287531806615776, - "y": 0.47477017364657814 - }, - { - "id": "point-257", - "x": 0.10756997455470736, - "y": 0.4454545454545455 - }, - { - "id": "point-267", - "x": 0.17767175572519084, - "y": 0.5234933605720122 - }, - { - "id": "point-277", - "x": 0.2962468193384224, - "y": 0.5465781409601634 - }, - { - "id": "point-292", - "x": 0.4138676844783716, - "y": 0.4349336057201226 - }, - { - "id": "point-302", - "x": 0.5194020356234097, - "y": 0.5248212461695607 - }, - { - "id": "point-307", - "x": 0.5548982188295165, - "y": 0.49836567926455566 - }, - { - "id": "point-317", - "x": 0.6503816793893129, - "y": 0.5194075587334014 - }, - { - "id": "point-327", - "x": 0.7473282442748093, - "y": 0.4626149131767109 - }, - { - "id": "point-337", - "x": 0.8691475826972009, - "y": 0.49458631256384067 - }, - { - "id": "point-352", - "x": 0.9832061068702289, - "y": 0.4917262512768131 - }, - { - "id": "point-357", - "x": 0.9990458015267175, - "y": 0.7504596527068438 - }, - { - "id": "point-362", - "x": 0.05012722646310432, - "y": 0.6356486210418795 - }, - { - "id": "point-372", - "x": 0.14440203562340967, - "y": 0.6027579162410623 - }, - { - "id": "point-382", - "x": 0.17550890585241732, - "y": 0.6821246169560776 - }, - { - "id": "point-392", - "x": 0.3370229007633587, - "y": 0.6620020429009194 - }, - { - "id": "point-397", - "x": 0.38403307888040716, - "y": 0.6074565883554648 - }, - { - "id": "point-407", - "x": 0.49141221374045796, - "y": 0.609090909090909 - }, - { - "id": "point-417", - "x": 0.6092239185750636, - "y": 0.6490296220633298 - }, - { - "id": "point-432", - "x": 0.6994910941475826, - "y": 0.6377936670071501 - }, - { - "id": "point-442", - "x": 0.8021628498727735, - "y": 0.6412665985699693 - }, - { - "id": "point-452", - "x": 0.8450381679389314, - "y": 0.6878447395301328 - }, - { - "id": "point-457", - "x": 0.9385496183206108, - "y": 0.5991828396322778 - }, - { - "id": "point-472", - "x": 0.08269720101781171, - "y": 0.8129724208375894 - }, - { - "id": "point-487", - "x": 0.19293893129770992, - "y": 0.7488253319713994 - }, - { - "id": "point-497", - "x": 0.3399491094147582, - "y": 0.7432073544433095 - }, - { - "id": "point-507", - "x": 0.4349872773536895, - "y": 0.8191011235955056 - }, - { - "id": "point-517", - "x": 0.4825699745547074, - "y": 0.8216547497446374 - }, - { - "id": "point-527", - "x": 0.6143129770992367, - "y": 0.8338100102145046 - }, - { - "id": "point-532", - "x": 0.6626590330788804, - "y": 0.7674157303370785 - }, - { - "id": "point-542", - "x": 0.80470737913486, - "y": 0.7797752808988764 - }, - { - "id": "point-557", - "x": 0.858587786259542, - "y": 0.780388151174668 - }, - { - "id": "point-571", - "x": 0.04058524173027989, - "y": 0.9923391215526047 - }, - { - "id": "point-577", - "x": 0.10038167938931299, - "y": 0.9534218590398367 - }, - { - "id": "point-587", - "x": 0.21615776081424937, - "y": 0.9832482124616956 - }, - { - "id": "point-592", - "x": 0.31653944020356234, - "y": 0.8937691521961184 - }, - { - "id": "point-602", - "x": 0.3648218829516539, - "y": 0.9393258426966292 - }, - { - "id": "point-612", - "x": 0.4798346055979643, - "y": 0.9085801838610827 - }, - { - "id": "point-627", - "x": 0.6159669211195928, - "y": 0.9221654749744637 - }, - { - "id": "point-632", - "x": 0.7001272264631042, - "y": 0.9664964249233913 - }, - { - "id": "point-647", - "x": 0.7608778625954199, - "y": 0.9989785495403473 - }, - { - "id": "point-652", - "x": 0.8911577608142494, - "y": 0.9557711950970379 - }, - { - "id": "point-667", - "x": 0.9989821882951655, - "y": 0.9853932584269665 - } - ], - "polygons": [ - { - "id": "poly-0", - "color": { - "h": 269.25373134328356, - "s": 100, - "l": 60.588235294117645, - "a": 1 - }, - "points": [ - "point-0", - "point-1", - "point-2" - ] - }, - { - "id": "poly-1", - "color": { - "h": 277.1428571428571, - "s": 100, - "l": 67.05882352941177, - "a": 1 - }, - "points": [ - "point-0", - "point-2", - "point-7" - ] - }, - { - "id": "poly-2", - "color": { - "h": 277.1428571428571, - "s": 100, - "l": 67.05882352941177, - "a": 1 - }, - "points": [ - "point-0", - "point-7", - "point-12" - ] - }, - { - "id": "poly-3", - "color": { - "h": 275.31428571428575, - "s": 100, - "l": 65.68627450980392, - "a": 1 - }, - "points": [ - "point-12", - "point-7", - "point-17" - ] - }, - { - "id": "poly-4", - "color": { - "h": 276.26373626373623, - "s": 100, - "l": 64.31372549019608, - "a": 1 - }, - "points": [ - "point-12", - "point-17", - "point-22" - ] - }, - { - "id": "poly-5", - "color": { - "h": 272.23404255319144, - "s": 100, - "l": 63.13725490196078, - "a": 1 - }, - "points": [ - "point-12", - "point-22", - "point-27" - ] - }, - { - "id": "poly-6", - "color": { - "h": 268.2692307692307, - "s": 100, - "l": 59.21568627450981, - "a": 1 - }, - "points": [ - "point-12", - "point-27", - "point-32" - ] - }, - { - "id": "poly-7", - "color": { - "h": 274.46808510638294, - "s": 100, - "l": 63.13725490196078, - "a": 1 - }, - "points": [ - "point-22", - "point-17", - "point-37" - ] - }, - { - "id": "poly-8", - "color": { - "h": 272.23404255319144, - "s": 100, - "l": 63.13725490196078, - "a": 1 - }, - "points": [ - "point-22", - "point-37", - "point-42" - ] - }, - { - "id": "poly-9", - "color": { - "h": 269.25373134328356, - "s": 100, - "l": 60.588235294117645, - "a": 1 - }, - "points": [ - "point-22", - "point-42", - "point-27" - ] - }, - { - "id": "poly-10", - "color": { - "h": 269.25373134328356, - "s": 100, - "l": 60.588235294117645, - "a": 1 - }, - "points": [ - "point-42", - "point-37", - "point-52" - ] - }, - { - "id": "poly-11", - "color": { - "h": 268.2692307692307, - "s": 100, - "l": 59.21568627450981, - "a": 1 - }, - "points": [ - "point-42", - "point-52", - "point-27" - ] - }, - { - "id": "poly-12", - "color": { - "h": 265.96153846153845, - "s": 100, - "l": 59.21568627450981, - "a": 1 - }, - "points": [ - "point-27", - "point-52", - "point-62" - ] - }, - { - "id": "poly-13", - "color": { - "h": 265.88235294117646, - "s": 86.4406779661017, - "l": 53.72549019607843, - "a": 1 - }, - "points": [ - "point-27", - "point-62", - "point-32" - ] - }, - { - "id": "poly-14", - "color": { - "h": 265.48387096774195, - "s": 76.22950819672131, - "l": 47.84313725490196, - "a": 1 - }, - "points": [ - "point-32", - "point-62", - "point-72" - ] - }, - { - "id": "poly-15", - "color": { - "h": 265.1933701657459, - "s": 83.41013824884793, - "l": 42.549019607843135, - "a": 1 - }, - "points": [ - "point-32", - "point-72", - "point-77" - ] - }, - { - "id": "poly-16", - "color": { - "h": 264.45859872611464, - "s": 96.31901840490798, - "l": 31.960784313725487, - "a": 1 - }, - "points": [ - "point-32", - "point-77", - "point-82" - ] - }, - { - "id": "poly-17", - "color": { - "h": 261.69230769230774, - "s": 100, - "l": 25.49019607843137, - "a": 1 - }, - "points": [ - "point-32", - "point-82", - "point-87" - ] - }, - { - "id": "poly-18", - "color": { - "h": 263.3532934131737, - "s": 91.2568306010929, - "l": 35.88235294117647, - "a": 1 - }, - "points": [ - "point-77", - "point-72", - "point-92" - ] - }, - { - "id": "poly-19", - "color": { - "h": 263.64963503649636, - "s": 100, - "l": 26.862745098039216, - "a": 1 - }, - "points": [ - "point-77", - "point-92", - "point-82" - ] - }, - { - "id": "poly-20", - "color": { - "h": 264.45859872611464, - "s": 96.31901840490798, - "l": 31.960784313725487, - "a": 1 - }, - "points": [ - "point-92", - "point-72", - "point-102" - ] - }, - { - "id": "poly-21", - "color": { - "h": 263.64963503649636, - "s": 100, - "l": 26.862745098039216, - "a": 1 - }, - "points": [ - "point-92", - "point-102", - "point-107" - ] - }, - { - "id": "poly-22", - "color": { - "h": 261.69230769230774, - "s": 100, - "l": 25.49019607843137, - "a": 1 - }, - "points": [ - "point-92", - "point-107", - "point-112" - ] - }, - { - "id": "poly-23", - "color": { - "h": 260, - "s": 100, - "l": 24.11764705882353, - "a": 1 - }, - "points": [ - "point-92", - "point-112", - "point-82" - ] - }, - { - "id": "poly-24", - "color": { - "h": 260, - "s": 100, - "l": 24.11764705882353, - "a": 1 - }, - "points": [ - "point-112", - "point-107", - "point-122" - ] - }, - { - "id": "poly-25", - "color": { - "h": 260, - "s": 100, - "l": 24.11764705882353, - "a": 1 - }, - "points": [ - "point-112", - "point-122", - "point-82" - ] - }, - { - "id": "poly-26", - "color": { - "h": 259.44444444444446, - "s": 100, - "l": 21.176470588235293, - "a": 1 - }, - "points": [ - "point-82", - "point-122", - "point-132" - ] - }, - { - "id": "poly-27", - "color": { - "h": 259.44444444444446, - "s": 100, - "l": 21.176470588235293, - "a": 1 - }, - "points": [ - "point-82", - "point-132", - "point-87" - ] - }, - { - "id": "poly-28", - "color": { - "h": 257.2277227722772, - "s": 100, - "l": 19.80392156862745, - "a": 1 - }, - "points": [ - "point-87", - "point-132", - "point-142" - ] - }, - { - "id": "poly-29", - "color": { - "h": 275.31428571428575, - "s": 100, - "l": 65.68627450980392, - "a": 1 - }, - "points": [ - "point-7", - "point-2", - "point-17" - ] - }, - { - "id": "poly-30", - "color": { - "h": 274.46808510638294, - "s": 100, - "l": 63.13725490196078, - "a": 1 - }, - "points": [ - "point-17", - "point-2", - "point-152" - ] - }, - { - "id": "poly-31", - "color": { - "h": 272.23404255319144, - "s": 100, - "l": 63.13725490196078, - "a": 1 - }, - "points": [ - "point-17", - "point-152", - "point-37" - ] - }, - { - "id": "poly-32", - "color": { - "h": 269.25373134328356, - "s": 100, - "l": 60.588235294117645, - "a": 1 - }, - "points": [ - "point-37", - "point-152", - "point-162" - ] - }, - { - "id": "poly-33", - "color": { - "h": 268.2692307692307, - "s": 100, - "l": 59.21568627450981, - "a": 1 - }, - "points": [ - "point-37", - "point-162", - "point-167" - ] - }, - { - "id": "poly-34", - "color": { - "h": 268.2692307692307, - "s": 100, - "l": 59.21568627450981, - "a": 1 - }, - "points": [ - "point-37", - "point-167", - "point-52" - ] - }, - { - "id": "poly-35", - "color": { - "h": 265.92233009708735, - "s": 92.7927927927928, - "l": 56.470588235294116, - "a": 1 - }, - "points": [ - "point-52", - "point-167", - "point-62" - ] - }, - { - "id": "poly-36", - "color": { - "h": 265.88235294117646, - "s": 86.4406779661017, - "l": 53.72549019607843, - "a": 1 - }, - "points": [ - "point-62", - "point-167", - "point-182" - ] - }, - { - "id": "poly-37", - "color": { - "h": 265.48387096774195, - "s": 76.22950819672131, - "l": 47.84313725490196, - "a": 1 - }, - "points": [ - "point-62", - "point-182", - "point-187" - ] - }, - { - "id": "poly-38", - "color": { - "h": 265.24590163934425, - "s": 79.22077922077922, - "l": 45.294117647058826, - "a": 1 - }, - "points": [ - "point-62", - "point-187", - "point-192" - ] - }, - { - "id": "poly-39", - "color": { - "h": 265.24590163934425, - "s": 79.22077922077922, - "l": 45.294117647058826, - "a": 1 - }, - "points": [ - "point-62", - "point-192", - "point-72" - ] - }, - { - "id": "poly-40", - "color": { - "h": 263.3532934131737, - "s": 91.2568306010929, - "l": 35.88235294117647, - "a": 1 - }, - "points": [ - "point-192", - "point-187", - "point-202" - ] - }, - { - "id": "poly-41", - "color": { - "h": 264.45859872611464, - "s": 96.31901840490798, - "l": 31.960784313725487, - "a": 1 - }, - "points": [ - "point-192", - "point-202", - "point-102" - ] - }, - { - "id": "poly-42", - "color": { - "h": 263.3532934131737, - "s": 91.2568306010929, - "l": 35.88235294117647, - "a": 1 - }, - "points": [ - "point-192", - "point-102", - "point-72" - ] - }, - { - "id": "poly-43", - "color": { - "h": 263.64963503649636, - "s": 100, - "l": 26.862745098039216, - "a": 1 - }, - "points": [ - "point-102", - "point-202", - "point-217" - ] - }, - { - "id": "poly-44", - "color": { - "h": 261.69230769230774, - "s": 100, - "l": 25.49019607843137, - "a": 1 - }, - "points": [ - "point-102", - "point-217", - "point-107" - ] - }, - { - "id": "poly-45", - "color": { - "h": 259.44444444444446, - "s": 100, - "l": 21.176470588235293, - "a": 1 - }, - "points": [ - "point-107", - "point-217", - "point-227" - ] - }, - { - "id": "poly-46", - "color": { - "h": 257.2277227722772, - "s": 100, - "l": 19.80392156862745, - "a": 1 - }, - "points": [ - "point-107", - "point-227", - "point-232" - ] - }, - { - "id": "poly-47", - "color": { - "h": 259.44444444444446, - "s": 100, - "l": 21.176470588235293, - "a": 1 - }, - "points": [ - "point-107", - "point-232", - "point-122" - ] - }, - { - "id": "poly-48", - "color": { - "h": 257.2277227722772, - "s": 100, - "l": 19.80392156862745, - "a": 1 - }, - "points": [ - "point-122", - "point-232", - "point-132" - ] - }, - { - "id": "poly-49", - "color": { - "h": 255.31914893617022, - "s": 100, - "l": 18.43137254901961, - "a": 1 - }, - "points": [ - "point-132", - "point-232", - "point-142" - ] - }, - { - "id": "poly-50", - "color": { - "h": 265.24590163934425, - "s": 79.22077922077922, - "l": 45.294117647058826, - "a": 1 - }, - "points": [ - "point-2", - "point-1", - "point-252" - ] - }, - { - "id": "poly-51", - "color": { - "h": 265.96153846153845, - "s": 100, - "l": 59.21568627450981, - "a": 1 - }, - "points": [ - "point-2", - "point-252", - "point-257" - ] - }, - { - "id": "poly-52", - "color": { - "h": 268.2692307692307, - "s": 100, - "l": 59.21568627450981, - "a": 1 - }, - "points": [ - "point-2", - "point-257", - "point-152" - ] - }, - { - "id": "poly-53", - "color": { - "h": 265.54455445544556, - "s": 80.8, - "l": 50.98039215686274, - "a": 1 - }, - "points": [ - "point-152", - "point-257", - "point-267" - ] - }, - { - "id": "poly-54", - "color": { - "h": 265.54455445544556, - "s": 80.8, - "l": 50.98039215686274, - "a": 1 - }, - "points": [ - "point-152", - "point-267", - "point-162" - ] - }, - { - "id": "poly-55", - "color": { - "h": 264.68571428571425, - "s": 91.62303664921467, - "l": 37.450980392156865, - "a": 1 - }, - "points": [ - "point-162", - "point-267", - "point-277" - ] - }, - { - "id": "poly-56", - "color": { - "h": 265.24590163934425, - "s": 79.22077922077922, - "l": 45.294117647058826, - "a": 1 - }, - "points": [ - "point-162", - "point-277", - "point-167" - ] - }, - { - "id": "poly-57", - "color": { - "h": 265.1933701657459, - "s": 83.41013824884793, - "l": 42.549019607843135, - "a": 1 - }, - "points": [ - "point-167", - "point-277", - "point-182" - ] - }, - { - "id": "poly-58", - "color": { - "h": 263.3532934131737, - "s": 91.2568306010929, - "l": 35.88235294117647, - "a": 1 - }, - "points": [ - "point-182", - "point-277", - "point-292" - ] - }, - { - "id": "poly-59", - "color": { - "h": 264.68571428571425, - "s": 91.62303664921467, - "l": 37.450980392156865, - "a": 1 - }, - "points": [ - "point-182", - "point-292", - "point-187" - ] - }, - { - "id": "poly-60", - "color": { - "h": 262.3448275862069, - "s": 100, - "l": 28.431372549019606, - "a": 1 - }, - "points": [ - "point-187", - "point-292", - "point-302" - ] - }, - { - "id": "poly-61", - "color": { - "h": 260, - "s": 100, - "l": 24.11764705882353, - "a": 1 - }, - "points": [ - "point-187", - "point-302", - "point-307" - ] - }, - { - "id": "poly-62", - "color": { - "h": 263.64963503649636, - "s": 100, - "l": 26.862745098039216, - "a": 1 - }, - "points": [ - "point-187", - "point-307", - "point-202" - ] - }, - { - "id": "poly-63", - "color": { - "h": 255.31914893617022, - "s": 100, - "l": 18.43137254901961, - "a": 1 - }, - "points": [ - "point-202", - "point-307", - "point-317" - ] - }, - { - "id": "poly-64", - "color": { - "h": 257.2277227722772, - "s": 100, - "l": 19.80392156862745, - "a": 1 - }, - "points": [ - "point-202", - "point-317", - "point-217" - ] - }, - { - "id": "poly-65", - "color": { - "h": 249.75, - "s": 100, - "l": 15.686274509803921, - "a": 1 - }, - "points": [ - "point-217", - "point-317", - "point-327" - ] - }, - { - "id": "poly-66", - "color": { - "h": 249.75, - "s": 100, - "l": 15.686274509803921, - "a": 1 - }, - "points": [ - "point-217", - "point-327", - "point-227" - ] - }, - { - "id": "poly-67", - "color": { - "h": 240, - "s": 100, - "l": 9.215686274509805, - "a": 1 - }, - "points": [ - "point-227", - "point-327", - "point-337" - ] - }, - { - "id": "poly-68", - "color": { - "h": 246.57534246575347, - "s": 100, - "l": 14.313725490196077, - "a": 1 - }, - "points": [ - "point-227", - "point-337", - "point-232" - ] - }, - { - "id": "poly-69", - "color": { - "h": 242.99999999999997, - "s": 100, - "l": 11.76470588235294, - "a": 1 - }, - "points": [ - "point-232", - "point-337", - "point-142" - ] - }, - { - "id": "poly-70", - "color": { - "h": 240, - "s": 100, - "l": 8.03921568627451, - "a": 1 - }, - "points": [ - "point-142", - "point-337", - "point-352" - ] - }, - { - "id": "poly-71", - "color": { - "h": 240, - "s": 100, - "l": 1.5686274509803921, - "a": 1 - }, - "points": [ - "point-142", - "point-352", - "point-357" - ] - }, - { - "id": "poly-72", - "color": { - "h": 264.45859872611464, - "s": 96.31901840490798, - "l": 31.960784313725487, - "a": 1 - }, - "points": [ - "point-252", - "point-1", - "point-362" - ] - }, - { - "id": "poly-73", - "color": { - "h": 265.24590163934425, - "s": 79.22077922077922, - "l": 45.294117647058826, - "a": 1 - }, - "points": [ - "point-252", - "point-362", - "point-257" - ] - }, - { - "id": "poly-74", - "color": { - "h": 264.68571428571425, - "s": 91.62303664921467, - "l": 37.450980392156865, - "a": 1 - }, - "points": [ - "point-257", - "point-362", - "point-372" - ] - }, - { - "id": "poly-75", - "color": { - "h": 264.9438202247191, - "s": 87.25490196078431, - "l": 40, - "a": 1 - }, - "points": [ - "point-257", - "point-372", - "point-267" - ] - }, - { - "id": "poly-76", - "color": { - "h": 262.3448275862069, - "s": 100, - "l": 28.431372549019606, - "a": 1 - }, - "points": [ - "point-267", - "point-372", - "point-382" - ] - }, - { - "id": "poly-77", - "color": { - "h": 263.64963503649636, - "s": 100, - "l": 26.862745098039216, - "a": 1 - }, - "points": [ - "point-267", - "point-382", - "point-277" - ] - }, - { - "id": "poly-78", - "color": { - "h": 259.44444444444446, - "s": 100, - "l": 21.176470588235293, - "a": 1 - }, - "points": [ - "point-277", - "point-382", - "point-392" - ] - }, - { - "id": "poly-79", - "color": { - "h": 257.2277227722772, - "s": 100, - "l": 19.80392156862745, - "a": 1 - }, - "points": [ - "point-277", - "point-392", - "point-397" - ] - }, - { - "id": "poly-80", - "color": { - "h": 261.69230769230774, - "s": 100, - "l": 25.49019607843137, - "a": 1 - }, - "points": [ - "point-277", - "point-397", - "point-292" - ] - }, - { - "id": "poly-81", - "color": { - "h": 257.2277227722772, - "s": 100, - "l": 19.80392156862745, - "a": 1 - }, - "points": [ - "point-292", - "point-397", - "point-407" - ] - }, - { - "id": "poly-82", - "color": { - "h": 257.2277227722772, - "s": 100, - "l": 19.80392156862745, - "a": 1 - }, - "points": [ - "point-292", - "point-407", - "point-302" - ] - }, - { - "id": "poly-83", - "color": { - "h": 240, - "s": 100, - "l": 10.588235294117647, - "a": 1 - }, - "points": [ - "point-302", - "point-407", - "point-417" - ] - }, - { - "id": "poly-84", - "color": { - "h": 242.99999999999997, - "s": 100, - "l": 11.76470588235294, - "a": 1 - }, - "points": [ - "point-302", - "point-417", - "point-307" - ] - }, - { - "id": "poly-85", - "color": { - "h": 240, - "s": 100, - "l": 9.215686274509805, - "a": 1 - }, - "points": [ - "point-307", - "point-417", - "point-317" - ] - }, - { - "id": "poly-86", - "color": { - "h": 240, - "s": 100, - "l": 4.705882352941177, - "a": 1 - }, - "points": [ - "point-317", - "point-417", - "point-432" - ] - }, - { - "id": "poly-87", - "color": { - "h": 240, - "s": 100, - "l": 6.862745098039216, - "a": 1 - }, - "points": [ - "point-317", - "point-432", - "point-327" - ] - }, - { - "id": "poly-88", - "color": { - "h": 240, - "s": 100, - "l": 1.5686274509803921, - "a": 1 - }, - "points": [ - "point-327", - "point-432", - "point-442" - ] - }, - { - "id": "poly-89", - "color": { - "h": 240, - "s": 100, - "l": 2.549019607843137, - "a": 1 - }, - "points": [ - "point-327", - "point-442", - "point-337" - ] - }, - { - "id": "poly-90", - "color": { - "h": 0, - "s": 0, - "l": 0, - "a": 1 - }, - "points": [ - "point-337", - "point-442", - "point-452" - ] - }, - { - "id": "poly-91", - "color": { - "h": 0, - "s": 0, - "l": 0, - "a": 1 - }, - "points": [ - "point-337", - "point-452", - "point-457" - ] - }, - { - "id": "poly-92", - "color": { - "h": 240, - "s": 100, - "l": 1.5686274509803921, - "a": 1 - }, - "points": [ - "point-337", - "point-457", - "point-352" - ] - }, - { - "id": "poly-93", - "color": { - "h": 0, - "s": 0, - "l": 0, - "a": 1 - }, - "points": [ - "point-352", - "point-457", - "point-357" - ] - }, - { - "id": "poly-94", - "color": { - "h": 261.69230769230774, - "s": 100, - "l": 25.49019607843137, - "a": 1 - }, - "points": [ - "point-362", - "point-1", - "point-472" - ] - }, - { - "id": "poly-95", - "color": { - "h": 260, - "s": 100, - "l": 24.11764705882353, - "a": 1 - }, - "points": [ - "point-362", - "point-472", - "point-382" - ] - }, - { - "id": "poly-96", - "color": { - "h": 263.64963503649636, - "s": 100, - "l": 26.862745098039216, - "a": 1 - }, - "points": [ - "point-362", - "point-382", - "point-372" - ] - }, - { - "id": "poly-97", - "color": { - "h": 257.2277227722772, - "s": 100, - "l": 19.80392156862745, - "a": 1 - }, - "points": [ - "point-382", - "point-472", - "point-487" - ] - }, - { - "id": "poly-98", - "color": { - "h": 255.31914893617022, - "s": 100, - "l": 18.43137254901961, - "a": 1 - }, - "points": [ - "point-382", - "point-487", - "point-392" - ] - }, - { - "id": "poly-99", - "color": { - "h": 249.75, - "s": 100, - "l": 15.686274509803921, - "a": 1 - }, - "points": [ - "point-392", - "point-487", - "point-497" - ] - }, - { - "id": "poly-100", - "color": { - "h": 246.57534246575347, - "s": 100, - "l": 14.313725490196077, - "a": 1 - }, - "points": [ - "point-392", - "point-497", - "point-397" - ] - }, - { - "id": "poly-101", - "color": { - "h": 240, - "s": 100, - "l": 10.588235294117647, - "a": 1 - }, - "points": [ - "point-397", - "point-497", - "point-507" - ] - }, - { - "id": "poly-102", - "color": { - "h": 240, - "s": 100, - "l": 9.215686274509805, - "a": 1 - }, - "points": [ - "point-397", - "point-507", - "point-407" - ] - }, - { - "id": "poly-103", - "color": { - "h": 240, - "s": 100, - "l": 6.862745098039216, - "a": 1 - }, - "points": [ - "point-407", - "point-507", - "point-517" - ] - }, - { - "id": "poly-104", - "color": { - "h": 240, - "s": 100, - "l": 5.686274509803922, - "a": 1 - }, - "points": [ - "point-407", - "point-517", - "point-417" - ] - }, - { - "id": "poly-105", - "color": { - "h": 240, - "s": 100, - "l": 1.5686274509803921, - "a": 1 - }, - "points": [ - "point-417", - "point-517", - "point-527" - ] - }, - { - "id": "poly-106", - "color": { - "h": 0, - "s": 0, - "l": 0, - "a": 1 - }, - "points": [ - "point-417", - "point-527", - "point-532" - ] - }, - { - "id": "poly-107", - "color": { - "h": 0, - "s": 0, - "l": 0, - "a": 1 - }, - "points": [ - "point-417", - "point-532", - "point-432" - ] - }, - { - "id": "poly-108", - "color": { - "h": 0, - "s": 0, - "l": 0, - "a": 1 - }, - "points": [ - "point-432", - "point-532", - "point-542" - ] - }, - { - "id": "poly-109", - "color": { - "h": 0, - "s": 0, - "l": 0, - "a": 1 - }, - "points": [ - "point-432", - "point-542", - "point-442" - ] - }, - { - "id": "poly-110", - "color": { - "h": 0, - "s": 0, - "l": 0, - "a": 1 - }, - "points": [ - "point-442", - "point-542", - "point-452" - ] - }, - { - "id": "poly-111", - "color": { - "h": 0, - "s": 0, - "l": 0, - "a": 1 - }, - "points": [ - "point-452", - "point-542", - "point-557" - ] - }, - { - "id": "poly-112", - "color": { - "h": 0, - "s": 0, - "l": 0, - "a": 1 - }, - "points": [ - "point-452", - "point-557", - "point-457" - ] - }, - { - "id": "poly-113", - "color": { - "h": 0, - "s": 0, - "l": 0, - "a": 1 - }, - "points": [ - "point-457", - "point-557", - "point-357" - ] - }, - { - "id": "poly-114", - "color": { - "h": 259.44444444444446, - "s": 100, - "l": 21.176470588235293, - "a": 1 - }, - "points": [ - "point-1", - "point-571", - "point-472" - ] - }, - { - "id": "poly-115", - "color": { - "h": 257.2277227722772, - "s": 100, - "l": 19.80392156862745, - "a": 1 - }, - "points": [ - "point-472", - "point-571", - "point-577" - ] - }, - { - "id": "poly-116", - "color": { - "h": 257.2277227722772, - "s": 100, - "l": 19.80392156862745, - "a": 1 - }, - "points": [ - "point-472", - "point-577", - "point-487" - ] - }, - { - "id": "poly-117", - "color": { - "h": 252.41379310344828, - "s": 100, - "l": 17.058823529411764, - "a": 1 - }, - "points": [ - "point-487", - "point-577", - "point-587" - ] - }, - { - "id": "poly-118", - "color": { - "h": 246.57534246575347, - "s": 100, - "l": 14.313725490196077, - "a": 1 - }, - "points": [ - "point-487", - "point-587", - "point-592" - ] - }, - { - "id": "poly-119", - "color": { - "h": 246.57534246575347, - "s": 100, - "l": 14.313725490196077, - "a": 1 - }, - "points": [ - "point-487", - "point-592", - "point-497" - ] - }, - { - "id": "poly-120", - "color": { - "h": 240, - "s": 100, - "l": 9.215686274509805, - "a": 1 - }, - "points": [ - "point-497", - "point-592", - "point-602" - ] - }, - { - "id": "poly-121", - "color": { - "h": 240, - "s": 100, - "l": 9.215686274509805, - "a": 1 - }, - "points": [ - "point-497", - "point-602", - "point-507" - ] - }, - { - "id": "poly-122", - "color": { - "h": 240, - "s": 100, - "l": 5.686274509803922, - "a": 1 - }, - "points": [ - "point-507", - "point-602", - "point-612" - ] - }, - { - "id": "poly-123", - "color": { - "h": 240, - "s": 100, - "l": 5.686274509803922, - "a": 1 - }, - "points": [ - "point-507", - "point-612", - "point-517" - ] - }, - { - "id": "poly-124", - "color": { - "h": 240, - "s": 100, - "l": 1.5686274509803921, - "a": 1 - }, - "points": [ - "point-517", - "point-612", - "point-527" - ] - }, - { - "id": "poly-125", - "color": { - "h": 0, - "s": 0, - "l": 0, - "a": 1 - }, - "points": [ - "point-527", - "point-612", - "point-627" - ] - }, - { - "id": "poly-126", - "color": { - "h": 0, - "s": 0, - "l": 0, - "a": 1 - }, - "points": [ - "point-527", - "point-627", - "point-632" - ] - }, - { - "id": "poly-127", - "color": { - "h": 0, - "s": 0, - "l": 0, - "a": 1 - }, - "points": [ - "point-527", - "point-632", - "point-532" - ] - }, - { - "id": "poly-128", - "color": { - "h": 0, - "s": 0, - "l": 0, - "a": 1 - }, - "points": [ - "point-532", - "point-632", - "point-542" - ] - }, - { - "id": "poly-129", - "color": { - "h": 0, - "s": 0, - "l": 0, - "a": 1 - }, - "points": [ - "point-542", - "point-632", - "point-647" - ] - }, - { - "id": "poly-130", - "color": { - "h": 0, - "s": 0, - "l": 0, - "a": 1 - }, - "points": [ - "point-542", - "point-647", - "point-652" - ] - }, - { - "id": "poly-131", - "color": { - "h": 0, - "s": 0, - "l": 0, - "a": 1 - }, - "points": [ - "point-542", - "point-652", - "point-557" - ] - }, - { - "id": "poly-132", - "color": { - "h": 0, - "s": 0, - "l": 0, - "a": 1 - }, - "points": [ - "point-557", - "point-652", - "point-357" - ] - }, - { - "id": "poly-133", - "color": { - "h": 0, - "s": 0, - "l": 0, - "a": 1 - }, - "points": [ - "point-357", - "point-652", - "point-667" - ] - }, - { - "id": "poly-134", - "color": { - "h": 240, - "s": 100, - "l": 6.862745098039216, - "a": 1 - }, - "points": [ - "point-571", - "point-647", - "point-587" - ] - }, - { - "id": "poly-135", - "color": { - "h": 252.41379310344828, - "s": 100, - "l": 17.058823529411764, - "a": 1 - }, - "points": [ - "point-571", - "point-587", - "point-577" - ] - }, - { - "id": "poly-136", - "color": { - "h": 240, - "s": 100, - "l": 2.549019607843137, - "a": 1 - }, - "points": [ - "point-587", - "point-647", - "point-602" - ] - }, - { - "id": "poly-137", - "color": { - "h": 240, - "s": 100, - "l": 9.215686274509805, - "a": 1 - }, - "points": [ - "point-587", - "point-602", - "point-592" - ] - }, - { - "id": "poly-138", - "color": { - "h": 0, - "s": 0, - "l": 0, - "a": 1 - }, - "points": [ - "point-602", - "point-647", - "point-632" - ] - }, - { - "id": "poly-139", - "color": { - "h": 240, - "s": 100, - "l": 0.5882352941176471, - "a": 1 - }, - "points": [ - "point-602", - "point-632", - "point-612" - ] - }, - { - "id": "poly-140", - "color": { - "h": 0, - "s": 0, - "l": 0, - "a": 1 - }, - "points": [ - "point-612", - "point-632", - "point-627" - ] - }, - { - "id": "poly-141", - "color": { - "h": 0, - "s": 0, - "l": 0, - "a": 1 - }, - "points": [ - "point-647", - "point-667", - "point-652" - ] - } - ] -}; diff --git a/website/source/assets/javascripts/app/_Init.js b/website/source/assets/javascripts/app/_Init.js deleted file mode 100644 index 06e772beb..000000000 --- a/website/source/assets/javascripts/app/_Init.js +++ /dev/null @@ -1,89 +0,0 @@ -(function( - Engine -){ - -// Quick and dirty IE detection -var isIE = (function(){ - if (window.navigator.userAgent.match('Trident')) { - return true; - } else { - return false; - } -})(); - -// isIE = true; - -var Init = { - - start: function(){ - var id = document.body.id.toLowerCase(); - - if (this.Pages[id]) { - this.Pages[id](); - } - //always init sidebar - Init.initializeSidebar(); - }, - - initializeSidebar: function(){ - new Sidebar(); - }, - - generateAnimatedLogo: function(){ - var container, x, block; - - container = document.createElement('div'); - container.className = 'animated-logo'; - - for (x = 1; x < 5; x++) { - block = document.createElement('div'); - block.className = 'white-block block-' + x; - container.appendChild(block); - } - - return container; - }, - - initializeEngine: function(){ - var jumbotron = document.getElementById('jumbotron'), - content = document.getElementById('jumbotron-content'), - tagLine = document.getElementById('tag-line'), - canvas, galaxy; - - if (!jumbotron) { - return; - } - - galaxy = document.createElement('div'); - galaxy.id = 'galaxy-bg'; - galaxy.className = 'galaxy-bg'; - jumbotron.appendChild(galaxy); - - content.appendChild( - Init.generateAnimatedLogo() - ); - - canvas = document.createElement('canvas'); - canvas.className = 'terraform-canvas'; - - jumbotron.appendChild(canvas); - new Engine(canvas, galaxy, tagLine); - }, - - Pages: { - 'page-home': function(){ - if (isIE) { - document.getElementById('jumbotron').className += ' static'; - document.getElementById('tag-line').style.visibility = 'visible'; - return; - } - - Init.initializeEngine(); - } - } - -}; - -Init.start(); - -})(window.Engine); diff --git a/website/source/assets/javascripts/app/_Logo.js b/website/source/assets/javascripts/app/_Logo.js deleted file mode 100644 index 0824b1c7e..000000000 --- a/website/source/assets/javascripts/app/_Logo.js +++ /dev/null @@ -1,1330 +0,0 @@ -// jshint unused:false -var Logo = { - "data": { - "width": 587, - "height": 587, - "ar": 1 - }, - "points": [ - { - "id": "point-0", - "x": 0.5809199318568995, - "y": 0.7478705281090289 - }, - { - "id": "point-1", - "x": 0.8160136286201022, - "y": 0.616695059625213 - }, - { - "id": "point-2", - "x": 0.6081771720613288, - "y": 0.8943781942078366 - }, - { - "id": "point-4", - "x": 0.9761499148211243, - "y": 0.6550255536626917 - }, - { - "id": "point-5", - "x": 0.848381601362862, - "y": 0.8603066439522997 - }, - { - "id": "point-12", - "x": 0.6354344122657581, - "y": 0.9829642248722317 - }, - { - "id": "point-16", - "x": 0.5536626916524702, - "y": 0.9982964224872233 - }, - { - "id": "point-20", - "x": 0.45451448040885867, - "y": 0.9463373083475298 - }, - { - "id": "point-24", - "x": 0.48126064735945484, - "y": 0.9982964224872233 - }, - { - "id": "point-28", - "x": 0.403747870528109, - "y": 0.994037478705281 - }, - { - "id": "point-32", - "x": 0.18143100511073254, - "y": 0.8858603066439524 - }, - { - "id": "point-36", - "x": 0.22998296422487224, - "y": 0.8057921635434411 - }, - { - "id": "point-40", - "x": 0.3373083475298126, - "y": 0.7052810902896082 - }, - { - "id": "point-44", - "x": 0.5143100511073253, - "y": 0.6933560477001702 - }, - { - "id": "point-56", - "x": 0.8918228279386712, - "y": 0.46337308347529815 - }, - { - "id": "point-60", - "x": 0.9974446337308348, - "y": 0.5366269165247018 - }, - { - "id": "point-64", - "x": 0.9574105621805792, - "y": 0.368824531516184 - }, - { - "id": "point-68", - "x": 0.9761499148211243, - "y": 0.36201022146507666 - }, - { - "id": "point-72", - "x": 0.6626916524701874, - "y": 0.43781942078364566 - }, - { - "id": "point-84", - "x": 0.4335604770017036, - "y": 0.5698466780238501 - }, - { - "id": "point-92", - "x": 0.11158432708688246, - "y": 0.8197614991482112 - }, - { - "id": "point-96", - "x": 0.09540034071550256, - "y": 0.6669505962521295 - }, - { - "id": "point-104", - "x": 0.05536626916524703, - "y": 0.7257240204429302 - }, - { - "id": "point-108", - "x": 0.03492333901192504, - "y": 0.6831345826235093 - }, - { - "id": "point-112", - "x": 0.15417376490630325, - "y": 0.4892674616695059 - }, - { - "id": "point-116", - "x": 0.22487223168654175, - "y": 0.4599659284497445 - }, - { - "id": "point-124", - "x": 0.2785349233390119, - "y": 0.35945485519591147 - }, - { - "id": "point-128", - "x": 0.48722316865417375, - "y": 0.35945485519591147 - }, - { - "id": "point-136", - "x": 0.5809199318568995, - "y": 0.2925042589437819 - }, - { - "id": "point-140", - "x": 0.889267461669506, - "y": 0.27649063032367976 - }, - { - "id": "point-152", - "x": 0.944633730834753, - "y": 0.2737649063032368 - }, - { - "id": "point-160", - "x": 0.8802385008517888, - "y": 0.18177172061328795 - }, - { - "id": "point-168", - "x": 0.5809199318568995, - "y": 0.19471890971039182 - }, - { - "id": "point-176", - "x": 0.7989778534923339, - "y": 0.10391822827938672 - }, - { - "id": "point-180", - "x": 0.6218057921635435, - "y": 0.018739352640545145 - }, - { - "id": "point-184", - "x": 0.5252129471890972, - "y": 0.0005110732538330494 - }, - { - "id": "point-188", - "x": 0.3889267461669506, - "y": 0.09761499148211243 - }, - { - "id": "point-192", - "x": 0.38126064735945486, - "y": 0.018739352640545145 - }, - { - "id": "point-196", - "x": 0.30153321976149916, - "y": 0.04258943781942079 - }, - { - "id": "point-200", - "x": 0.2969335604770017, - "y": 0.09761499148211243 - }, - { - "id": "point-216", - "x": 0.049403747870528106, - "y": 0.3083475298126065 - }, - { - "id": "point-228", - "x": 0.002214650766609881, - "y": 0.47155025553662694 - }, - { - "id": "point-232", - "x": 0.0005110732538330494, - "y": 0.5289608177172062 - }, - { - "id": "point-244", - "x": 0.17325383304940373, - "y": 0.12180579216354344 - } - ], - "polygons": [ - { - "id": "poly-0", - "color": { - "h": 264.688995215311, - "s": 100, - "l": 59.01960784313726, - "a": 1 - }, - "points": [ - "point-0", - "point-1", - "point-2" - ] - }, - { - "id": "poly-1", - "color": { - "h": 268.3076923076923, - "s": 100, - "l": 61.76470588235294, - "a": 1 - }, - "points": [ - "point-4", - "point-5", - "point-1" - ] - }, - { - "id": "poly-2", - "color": { - "h": 267.1641791044776, - "s": 100, - "l": 60.588235294117645, - "a": 1 - }, - "points": [ - "point-5", - "point-2", - "point-1" - ] - }, - { - "id": "poly-3", - "color": { - "h": 268.3076923076923, - "s": 100, - "l": 61.76470588235294, - "a": 1 - }, - "points": [ - "point-12", - "point-2", - "point-5" - ] - }, - { - "id": "poly-4", - "color": { - "h": 267.1641791044776, - "s": 100, - "l": 60.588235294117645, - "a": 1 - }, - "points": [ - "point-16", - "point-12", - "point-2" - ] - }, - { - "id": "poly-5", - "color": { - "h": 264.9, - "s": 92.59259259259261, - "l": 57.647058823529406, - "a": 1 - }, - "points": [ - "point-20", - "point-2", - "point-16" - ] - }, - { - "id": "poly-6", - "color": { - "h": 264.9, - "s": 92.59259259259261, - "l": 57.647058823529406, - "a": 1 - }, - "points": [ - "point-24", - "point-20", - "point-16" - ] - }, - { - "id": "poly-7", - "color": { - "h": 264.97461928934007, - "s": 85.28138528138528, - "l": 54.70588235294118, - "a": 1 - }, - "points": [ - "point-28", - "point-20", - "point-24" - ] - }, - { - "id": "poly-8", - "color": { - "h": 265.4347826086956, - "s": 80, - "l": 45.09803921568628, - "a": 1 - }, - "points": [ - "point-32", - "point-20", - "point-28" - ] - }, - { - "id": "poly-9", - "color": { - "h": 265.4347826086956, - "s": 80, - "l": 45.09803921568628, - "a": 1 - }, - "points": [ - "point-36", - "point-32", - "point-20" - ] - }, - { - "id": "poly-10", - "color": { - "h": 265.4347826086956, - "s": 80, - "l": 45.09803921568628, - "a": 1 - }, - "points": [ - "point-40", - "point-36", - "point-20" - ] - }, - { - "id": "poly-11", - "color": { - "h": 265.48387096774195, - "s": 76.22950819672131, - "l": 47.84313725490196, - "a": 1 - }, - "points": [ - "point-44", - "point-20", - "point-40" - ] - }, - { - "id": "poly-12", - "color": { - "h": 264.61538461538464, - "s": 79.59183673469387, - "l": 51.9607843137255, - "a": 1 - }, - "points": [ - "point-0", - "point-44", - "point-20" - ] - }, - { - "id": "poly-13", - "color": { - "h": 264.9, - "s": 92.59259259259261, - "l": 57.647058823529406, - "a": 1 - }, - "points": [ - "point-0", - "point-20", - "point-2" - ] - }, - { - "id": "poly-14", - "color": { - "h": 264.61538461538464, - "s": 79.59183673469387, - "l": 51.9607843137255, - "a": 1 - }, - "points": [ - "point-56", - "point-1", - "point-4" - ] - }, - { - "id": "poly-15", - "color": { - "h": 264.61538461538464, - "s": 79.59183673469387, - "l": 51.9607843137255, - "a": 1 - }, - "points": [ - "point-60", - "point-4", - "point-56" - ] - }, - { - "id": "poly-16", - "color": { - "h": 263.64705882352945, - "s": 86.73469387755101, - "l": 38.43137254901961, - "a": 1 - }, - "points": [ - "point-64", - "point-56", - "point-60" - ] - }, - { - "id": "poly-17", - "color": { - "h": 264.9056603773585, - "s": 90.85714285714286, - "l": 34.31372549019608, - "a": 1 - }, - "points": [ - "point-68", - "point-64", - "point-60" - ] - }, - { - "id": "poly-18", - "color": { - "h": 263.64705882352945, - "s": 86.73469387755101, - "l": 38.43137254901961, - "a": 1 - }, - "points": [ - "point-72", - "point-56", - "point-1" - ] - }, - { - "id": "poly-19", - "color": { - "h": 265.4347826086956, - "s": 80, - "l": 45.09803921568628, - "a": 1 - }, - "points": [ - "point-0", - "point-72", - "point-1" - ] - }, - { - "id": "poly-20", - "color": { - "h": 264.20454545454544, - "s": 79.27927927927928, - "l": 43.529411764705884, - "a": 1 - }, - "points": [ - "point-72", - "point-0", - "point-44" - ] - }, - { - "id": "poly-21", - "color": { - "h": 264.2307692307692, - "s": 95.12195121951221, - "l": 32.15686274509804, - "a": 1 - }, - "points": [ - "point-84", - "point-44", - "point-72" - ] - }, - { - "id": "poly-22", - "color": { - "h": 263.64705882352945, - "s": 86.73469387755101, - "l": 38.43137254901961, - "a": 1 - }, - "points": [ - "point-40", - "point-84", - "point-44" - ] - }, - { - "id": "poly-23", - "color": { - "h": 264.9056603773585, - "s": 90.85714285714286, - "l": 34.31372549019608, - "a": 1 - }, - "points": [ - "point-92", - "point-32", - "point-36" - ] - }, - { - "id": "poly-24", - "color": { - "h": 264.2307692307692, - "s": 95.12195121951221, - "l": 32.15686274509804, - "a": 1 - }, - "points": [ - "point-96", - "point-92", - "point-36" - ] - }, - { - "id": "poly-25", - "color": { - "h": 264.9056603773585, - "s": 90.85714285714286, - "l": 34.31372549019608, - "a": 1 - }, - "points": [ - "point-40", - "point-96", - "point-36" - ] - }, - { - "id": "poly-26", - "color": { - "h": 264.2307692307692, - "s": 95.12195121951221, - "l": 32.15686274509804, - "a": 1 - }, - "points": [ - "point-104", - "point-92", - "point-96" - ] - }, - { - "id": "poly-27", - "color": { - "h": 261.6, - "s": 100, - "l": 14.705882352941178, - "a": 1 - }, - "points": [ - "point-108", - "point-104", - "point-96" - ], - "stroke": { - "h": 262.24719101123594, - "s": 60.544217687074834, - "l": 28.82352941176471, - "a": 0.4 - } - }, - { - "id": "poly-28", - "color": { - "h": 261.6, - "s": 100, - "l": 14.705882352941178, - "a": 1 - }, - "points": [ - "point-112", - "point-40", - "point-96" - ], - "stroke": { - "h": 262.24719101123594, - "s": 60.544217687074834, - "l": 28.82352941176471, - "a": 0.4 - } - }, - { - "id": "poly-29", - "color": { - "h": 257.910447761194, - "s": 100, - "l": 13.137254901960786, - "a": 1 - }, - "points": [ - "point-116", - "point-112", - "point-40" - ], - "stroke": { - "h": 262.24719101123594, - "s": 60.544217687074834, - "l": 28.82352941176471, - "a": 0.4 - } - }, - { - "id": "poly-30", - "color": { - "h": 262.8571428571429, - "s": 100, - "l": 16.470588235294116, - "a": 1 - }, - "points": [ - "point-84", - "point-40", - "point-116" - ], - "stroke": { - "h": 262.24719101123594, - "s": 60.544217687074834, - "l": 28.82352941176471, - "a": 0.4 - } - }, - { - "id": "poly-31", - "color": { - "h": 252.00000000000003, - "s": 100, - "l": 9.803921568627452, - "a": 1 - }, - "points": [ - "point-124", - "point-84", - "point-116" - ], - "stroke": { - "h": 262.24719101123594, - "s": 60.544217687074834, - "l": 28.82352941176471, - "a": 0.4 - } - }, - { - "id": "poly-32", - "color": { - "h": 252.00000000000003, - "s": 100, - "l": 9.803921568627452, - "a": 1 - }, - "points": [ - "point-128", - "point-84", - "point-124" - ], - "stroke": { - "h": 262.24719101123594, - "s": 60.544217687074834, - "l": 28.82352941176471, - "a": 0.4 - } - }, - { - "id": "poly-33", - "color": { - "h": 257.910447761194, - "s": 100, - "l": 13.137254901960786, - "a": 1 - }, - "points": [ - "point-72", - "point-128", - "point-84" - ], - "stroke": { - "h": 262.24719101123594, - "s": 60.544217687074834, - "l": 28.82352941176471, - "a": 0.4 - } - }, - { - "id": "poly-34", - "color": { - "h": 252.00000000000003, - "s": 100, - "l": 9.803921568627452, - "a": 1 - }, - "points": [ - "point-136", - "point-128", - "point-72" - ], - "stroke": { - "h": 262.24719101123594, - "s": 60.544217687074834, - "l": 28.82352941176471, - "a": 0.4 - } - }, - { - "id": "poly-35", - "color": { - "h": 253.44827586206898, - "s": 100, - "l": 11.372549019607844, - "a": 1 - }, - "points": [ - "point-140", - "point-136", - "point-72" - ], - "stroke": { - "h": 262.24719101123594, - "s": 60.544217687074834, - "l": 28.82352941176471, - "a": 0.4 - } - }, - { - "id": "poly-36", - "color": { - "h": 261.6, - "s": 100, - "l": 14.705882352941178, - "a": 1 - }, - "points": [ - "point-140", - "point-56", - "point-72" - ], - "stroke": { - "h": 262.24719101123594, - "s": 60.544217687074834, - "l": 28.82352941176471, - "a": 0.4 - } - }, - { - "id": "poly-37", - "color": { - "h": 262.8571428571429, - "s": 100, - "l": 16.470588235294116, - "a": 1 - }, - "points": [ - "point-64", - "point-56", - "point-140" - ], - "stroke": { - "h": 262.24719101123594, - "s": 60.544217687074834, - "l": 28.82352941176471, - "a": 0.4 - } - }, - { - "id": "poly-38", - "color": { - "h": 259.4366197183098, - "s": 100, - "l": 13.92156862745098, - "a": 1 - }, - "points": [ - "point-152", - "point-140", - "point-64" - ], - "stroke": { - "h": 262.24719101123594, - "s": 60.544217687074834, - "l": 28.82352941176471, - "a": 0.4 - } - }, - { - "id": "poly-39", - "color": { - "h": 259.4366197183098, - "s": 100, - "l": 13.92156862745098, - "a": 1 - }, - "points": [ - "point-68", - "point-64", - "point-152" - ], - "stroke": { - "h": 262.24719101123594, - "s": 60.544217687074834, - "l": 28.82352941176471, - "a": 0.4 - } - }, - { - "id": "poly-40", - "color": { - "h": 253.44827586206898, - "s": 100, - "l": 11.372549019607844, - "a": 1 - }, - "points": [ - "point-160", - "point-140", - "point-152" - ], - "stroke": { - "h": 262.24719101123594, - "s": 60.544217687074834, - "l": 28.82352941176471, - "a": 0.4 - } - }, - { - "id": "poly-41", - "color": { - "h": 245.58139534883722, - "s": 100, - "l": 8.431372549019608, - "a": 1 - }, - "points": [ - "point-136", - "point-160", - "point-140" - ], - "stroke": { - "h": 262.24719101123594, - "s": 60.544217687074834, - "l": 28.82352941176471, - "a": 0.4 - } - }, - { - "id": "poly-42", - "color": { - "h": 246.15384615384613, - "s": 100, - "l": 7.647058823529412, - "a": 1 - }, - "points": [ - "point-168", - "point-128", - "point-136" - ], - "stroke": { - "h": 262.24719101123594, - "s": 60.544217687074834, - "l": 28.82352941176471, - "a": 0.4 - } - }, - { - "id": "poly-43", - "color": { - "h": 245.58139534883722, - "s": 100, - "l": 8.431372549019608, - "a": 1 - }, - "points": [ - "point-160", - "point-168", - "point-136" - ], - "stroke": { - "h": 262.24719101123594, - "s": 60.544217687074834, - "l": 28.82352941176471, - "a": 0.4 - } - }, - { - "id": "poly-44", - "color": { - "h": 246.15384615384613, - "s": 100, - "l": 7.647058823529412, - "a": 1 - }, - "points": [ - "point-176", - "point-160", - "point-168" - ], - "stroke": { - "h": 262.24719101123594, - "s": 60.544217687074834, - "l": 28.82352941176471, - "a": 0.4 - } - }, - { - "id": "poly-45", - "color": { - "h": 246.15384615384613, - "s": 100, - "l": 7.647058823529412, - "a": 1 - }, - "points": [ - "point-180", - "point-168", - "point-176" - ], - "stroke": { - "h": 262.24719101123594, - "s": 60.544217687074834, - "l": 28.82352941176471, - "a": 0.4 - } - }, - { - "id": "poly-46", - "color": { - "h": 240, - "s": 100, - "l": 4.509803921568627, - "a": 1 - }, - "points": [ - "point-184", - "point-168", - "point-180" - ], - "stroke": { - "h": 262.24719101123594, - "s": 60.544217687074834, - "l": 28.82352941176471, - "a": 0.4 - } - }, - { - "id": "poly-47", - "color": { - "h": 240, - "s": 100, - "l": 4.509803921568627, - "a": 1 - }, - "points": [ - "point-188", - "point-168", - "point-184" - ], - "stroke": { - "h": 262.24719101123594, - "s": 60.544217687074834, - "l": 28.82352941176471, - "a": 0.4 - } - }, - { - "id": "poly-48", - "color": { - "h": 240, - "s": 100, - "l": 4.509803921568627, - "a": 1 - }, - "points": [ - "point-192", - "point-188", - "point-184" - ], - "stroke": { - "h": 262.24719101123594, - "s": 60.544217687074834, - "l": 28.82352941176471, - "a": 0.4 - } - }, - { - "id": "poly-49", - "color": { - "h": 240, - "s": 100, - "l": 4.509803921568627, - "a": 1 - }, - "points": [ - "point-196", - "point-188", - "point-192" - ], - "stroke": { - "h": 262.24719101123594, - "s": 60.544217687074834, - "l": 28.82352941176471, - "a": 0.4 - } - }, - { - "id": "poly-50", - "color": { - "h": 240, - "s": 100, - "l": 0.5882352941176471, - "a": 1 - }, - "points": [ - "point-200", - "point-196", - "point-188" - ], - "stroke": { - "h": 262.24719101123594, - "s": 60.544217687074834, - "l": 28.82352941176471, - "a": 0.4 - } - }, - { - "id": "poly-51", - "color": { - "h": 240, - "s": 100, - "l": 3.3333333333333335, - "a": 1 - }, - "points": [ - "point-188", - "point-124", - "point-200" - ], - "stroke": { - "h": 262.24719101123594, - "s": 60.544217687074834, - "l": 28.82352941176471, - "a": 0.4 - } - }, - { - "id": "poly-52", - "color": { - "h": 240, - "s": 100, - "l": 5.294117647058823, - "a": 1 - }, - "points": [ - "point-188", - "point-124", - "point-128" - ], - "stroke": { - "h": 262.24719101123594, - "s": 60.544217687074834, - "l": 28.82352941176471, - "a": 0.4 - } - }, - { - "id": "poly-53", - "color": { - "h": 245.1428571428571, - "s": 100, - "l": 6.862745098039216, - "a": 1 - }, - "points": [ - "point-188", - "point-128", - "point-168" - ], - "stroke": { - "h": 262.24719101123594, - "s": 60.544217687074834, - "l": 28.82352941176471, - "a": 0.4 - } - }, - { - "id": "poly-54", - "color": { - "h": 240, - "s": 100, - "l": 3.3333333333333335, - "a": 1 - }, - "points": [ - "point-216", - "point-200", - "point-124" - ], - "stroke": { - "h": 262.24719101123594, - "s": 60.544217687074834, - "l": 28.82352941176471, - "a": 0.4 - } - }, - { - "id": "poly-55", - "color": { - "h": 240, - "s": 100, - "l": 5.294117647058823, - "a": 1 - }, - "points": [ - "point-216", - "point-116", - "point-124" - ], - "stroke": { - "h": 262.24719101123594, - "s": 60.544217687074834, - "l": 28.82352941176471, - "a": 0.4 - } - }, - { - "id": "poly-56", - "color": { - "h": 245.1428571428571, - "s": 100, - "l": 6.862745098039216, - "a": 1 - }, - "points": [ - "point-112", - "point-216", - "point-116" - ], - "stroke": { - "h": 262.24719101123594, - "s": 60.544217687074834, - "l": 28.82352941176471, - "a": 0.4 - } - }, - { - "id": "poly-57", - "color": { - "h": 240, - "s": 100, - "l": 5.294117647058823, - "a": 1 - }, - "points": [ - "point-228", - "point-216", - "point-112" - ], - "stroke": { - "h": 262.24719101123594, - "s": 60.544217687074834, - "l": 28.82352941176471, - "a": 0.4 - } - }, - { - "id": "poly-58", - "color": { - "h": 249.13043478260872, - "s": 100, - "l": 9.019607843137255, - "a": 1 - }, - "points": [ - "point-232", - "point-112", - "point-96" - ], - "stroke": { - "h": 262.24719101123594, - "s": 60.544217687074834, - "l": 28.82352941176471, - "a": 0.4 - } - }, - { - "id": "poly-59", - "color": { - "h": 253.44827586206898, - "s": 100, - "l": 11.372549019607844, - "a": 1 - }, - "points": [ - "point-108", - "point-96", - "point-232" - ], - "stroke": { - "h": 262.24719101123594, - "s": 60.544217687074834, - "l": 28.82352941176471, - "a": 0.4 - } - }, - { - "id": "poly-60", - "color": { - "h": 240, - "s": 100, - "l": 5.294117647058823, - "a": 1 - }, - "points": [ - "point-228", - "point-112", - "point-232" - ], - "stroke": { - "h": 262.24719101123594, - "s": 60.544217687074834, - "l": 28.82352941176471, - "a": 0.4 - } - }, - { - "id": "poly-61", - "color": { - "h": 240, - "s": 100, - "l": 0.5882352941176471, - "a": 1 - }, - "points": [ - "point-244", - "point-216", - "point-200" - ], - "stroke": { - "h": 262.24719101123594, - "s": 60.544217687074834, - "l": 28.82352941176471, - "a": 0.4 - } - }, - { - "id": "poly-62", - "color": { - "h": 240, - "s": 100, - "l": 0.5882352941176471, - "a": 1 - }, - "points": [ - "point-196", - "point-200", - "point-244" - ], - "stroke": { - "h": 262.24719101123594, - "s": 60.544217687074834, - "l": 28.82352941176471, - "a": 0.4 - } - } - ] -}; diff --git a/website/source/assets/javascripts/app/_Puller.js b/website/source/assets/javascripts/app/_Puller.js deleted file mode 100644 index 2df85c733..000000000 --- a/website/source/assets/javascripts/app/_Puller.js +++ /dev/null @@ -1,136 +0,0 @@ -(function( - Engine, - Vector -){ - -var Puller = function(x, y){ - this.pos.x = x; - this.pos.y = y; - this.pos = Vector.coerce(this.pos); - this.home = this.pos.clone(); - this.accel = Vector.coerce(this.accel); - this.vel = Vector.coerce(this.vel); -}; - -Puller.prototype = { - - fillStyle: '#ffffff', - radius: 5, - - maxSpeed: 160, - maxForce: 50, - - pos: { - x: 0, - y: 0 - }, - - accel: { - x: 0, - y: 0 - }, - - vel: { - x: 0, - y: 0 - }, - - aRad: 200, - - safety: 0.25, - - update: function(engine){ - var distanceToMouse = this.distanceTo(engine.mouse), - toHome, mag, safety; - // distanceToHome = this.distanceTo(this.home); - - this.accel.mult(0); - - if (distanceToMouse < this.aRad) { - this.toChase(engine.mouse); - } - - this.toChase(this.home, this.maxForce / 2); - - this.vel.add(this.accel); - this.pos.add( - Vector.mult(this.vel, engine.tick) - ); - - toHome = Vector.sub(this.home, this.pos); - mag = toHome.mag(); - safety = this.aRad * (this.safety * 3); - if (mag > this.aRad - safety) { - toHome.normalize(); - toHome.mult(this.aRad - safety); - this.pos = Vector.sub(this.home, toHome); - } - }, - - toChase: function(target, maxForce){ - var desired, steer, distance, mult, safety; - - maxForce = maxForce || this.maxForce; - - target = Vector.coerce(target); - desired = Vector.sub(target, this.pos); - distance = desired.mag(); - desired.normalize(); - - safety = this.aRad * this.safety; - - if (distance < safety) { - mult = Engine.map(distance, 0, safety, 0, this.maxSpeed); - } else if (distance > this.aRad - safety){ - mult = Engine.map(this.aRad - distance, 0, safety, 0, this.maxSpeed); - } else { - mult = this.maxSpeed; - } - - desired.mult(mult); - - steer = Vector.sub(desired, this.vel); - steer.limit(maxForce); - this.accel.add(steer); - }, - - draw: function(ctx, scale){ - // ctx.beginPath(); - // ctx.arc( - // this.home.x * scale, - // this.home.y * scale, - // this.aRad * scale, - // 0, - // Math.PI * 2, - // false - // ); - // ctx.fillStyle = 'rgba(255,255,255,0.1)'; - // ctx.fill(); - - ctx.beginPath(); - ctx.arc( - this.pos.x * scale, - this.pos.y * scale, - this.radius * scale, - 0, - Math.PI * 2, - false - ); - ctx.fillStyle = this.fillStyle; - ctx.fill(); - - }, - - distanceTo: function(target) { - var xd = this.home.x - target.x; - var yd = this.home.y - target.y; - return Math.sqrt(xd * xd + yd * yd ); - } -}; - -window.Puller = Puller; - -})( - window.Engine, - window.Vector -); diff --git a/website/source/assets/javascripts/app/_Sidebar.js b/website/source/assets/javascripts/app/_Sidebar.js deleted file mode 100644 index b36e508c4..000000000 --- a/website/source/assets/javascripts/app/_Sidebar.js +++ /dev/null @@ -1,50 +0,0 @@ -(function(){ - - Sidebar = Base.extend({ - - $body: null, - $overlay: null, - $sidebar: null, - $sidebarHeader: null, - $sidebarImg: null, - $toggleButton: null, - - constructor: function(){ - this.$body = $('body'); - this.$overlay = $('.sidebar-overlay'); - this.$sidebar = $('#sidebar'); - this.$sidebarHeader = $('#sidebar .sidebar-header'); - this.$toggleButton = $('.navbar-toggle'); - this.sidebarImg = this.$sidebarHeader.css('background-image'); - - this.addEventListeners(); - }, - - addEventListeners: function(){ - var _this = this; - - _this.$toggleButton.on('click', function() { - _this.$sidebar.toggleClass('open'); - if ((_this.$sidebar.hasClass('sidebar-fixed-left') || _this.$sidebar.hasClass('sidebar-fixed-right')) && _this.$sidebar.hasClass('open')) { - _this.$overlay.addClass('active'); - _this.$body.css('overflow', 'hidden'); - } else { - _this.$overlay.removeClass('active'); - _this.$body.css('overflow', 'auto'); - } - - return false; - }); - - _this.$overlay.on('click', function() { - $(this).removeClass('active'); - _this.$body.css('overflow', 'auto'); - _this.$sidebar.removeClass('open'); - }); - } - - }); - - window.Sidebar = Sidebar; - -})(); diff --git a/website/source/assets/javascripts/application.js b/website/source/assets/javascripts/application.js index bc70be7fb..ad181b4cc 100644 --- a/website/source/assets/javascripts/application.js +++ b/website/source/assets/javascripts/application.js @@ -1,29 +1,5 @@ //= require turbolinks //= require jquery -//= require bootstrap -//= require lib/_String.substitute -//= require lib/_Vector -//= require lib/_Function.prototype.bind -//= require lib/_Base -//= require lib/_Chainable -//= require lib/_dbg - -//= require app/_Docs -//= require app/_Logo -//= require app/_Grid -//= require app/_Engine -//= require app/_Engine.Particle -//= require app/_Engine.Particle.Fixed -//= require app/_Engine.Point -//= require app/_Engine.Point.Puller -//= require app/_Engine.Polygon -//= require app/_Engine.Polygon.Puller -//= require app/_Engine.Shape -//= require app/_Engine.Shape.Puller -//= require app/_Engine.Typewriter -//= require app/_Sidebar -//= require app/_Init - -// assets/javascripts/application.js //= require hashicorp/mega-nav +//= require hashicorp/sidebar diff --git a/website/source/assets/javascripts/lib/_Base.js b/website/source/assets/javascripts/lib/_Base.js deleted file mode 100644 index 504e2beea..000000000 --- a/website/source/assets/javascripts/lib/_Base.js +++ /dev/null @@ -1,145 +0,0 @@ -/* - Based on Base.js 1.1a (c) 2006-2010, Dean Edwards - Updated to pass JSHint and converted into a module by Kenneth Powers - License: http://www.opensource.org/licenses/mit-license.php -*/ -/*global define:true module:true*/ -/*jshint eqeqeq:true*/ -(function (name, global, definition) { - if (typeof module !== 'undefined') { - module.exports = definition(); - } else if (typeof define !== 'undefined' && typeof define.amd === 'object') { - define(definition); - } else { - global[name] = definition(); - } -})('Base', this, function () { - // Base Object - var Base = function () {}; - - // Implementation - Base.extend = function (_instance, _static) { // subclass - var extend = Base.prototype.extend; - // build the prototype - Base._prototyping = true; - var proto = new this(); - extend.call(proto, _instance); - proto.base = function () { - // call this method from any other method to invoke that method's ancestor - }; - delete Base._prototyping; - // create the wrapper for the constructor function - //var constructor = proto.constructor.valueOf(); //-dean - var constructor = proto.constructor; - var klass = proto.constructor = function () { - if (!Base._prototyping) { - if (this._constructing || this.constructor === klass) { // instantiation - this._constructing = true; - constructor.apply(this, arguments); - delete this._constructing; - } else if (arguments[0] !== null) { // casting - return (arguments[0].extend || extend).call(arguments[0], proto); - } - } - }; - // build the class interface - klass.ancestor = this; - klass.extend = this.extend; - klass.forEach = this.forEach; - klass.implement = this.implement; - klass.prototype = proto; - klass.toString = this.toString; - klass.valueOf = function (type) { - return (type === 'object') ? klass : constructor.valueOf(); - }; - extend.call(klass, _static); - // class initialization - if (typeof klass.init === 'function') klass.init(); - return klass; - }; - - Base.prototype = { - extend: function (source, value) { - if (arguments.length > 1) { // extending with a name/value pair - var ancestor = this[source]; - if (ancestor && (typeof value === 'function') && // overriding a method? - // the valueOf() comparison is to avoid circular references - (!ancestor.valueOf || ancestor.valueOf() !== value.valueOf()) && /\bbase\b/.test(value)) { - // get the underlying method - var method = value.valueOf(); - // override - value = function () { - var previous = this.base || Base.prototype.base; - this.base = ancestor; - var returnValue = method.apply(this, arguments); - this.base = previous; - return returnValue; - }; - // point to the underlying method - value.valueOf = function (type) { - return (type === 'object') ? value : method; - }; - value.toString = Base.toString; - } - this[source] = value; - } else if (source) { // extending with an object literal - var extend = Base.prototype.extend; - // if this object has a customized extend method then use it - if (!Base._prototyping && typeof this !== 'function') { - extend = this.extend || extend; - } - var proto = { - toSource: null - }; - // do the "toString" and other methods manually - var hidden = ['constructor', 'toString', 'valueOf']; - // if we are prototyping then include the constructor - for (var i = Base._prototyping ? 0 : 1; i < hidden.length; i++) { - var h = hidden[i]; - if (source[h] !== proto[h]) - extend.call(this, h, source[h]); - } - // copy each of the source object's properties to this object - for (var key in source) { - if (!proto[key]) extend.call(this, key, source[key]); - } - } - return this; - } - }; - - // initialize - Base = Base.extend({ - constructor: function () { - this.extend(arguments[0]); - } - }, { - ancestor: Object, - version: '1.1', - forEach: function (object, block, context) { - for (var key in object) { - if (this.prototype[key] === undefined) { - block.call(context, object[key], key, object); - } - } - }, - implement: function () { - for (var i = 0; i < arguments.length; i++) { - if (typeof arguments[i] === 'function') { - // if it's a function, call it - arguments[i](this.prototype); - } else { - // add the interface using the extend method - this.prototype.extend(arguments[i]); - } - } - return this; - }, - toString: function () { - return String(this.valueOf()); - } - }); - - // Return Base implementation - return Base; -}); diff --git a/website/source/assets/javascripts/lib/_Chainable.js b/website/source/assets/javascripts/lib/_Chainable.js deleted file mode 100644 index dbe51dd1d..000000000 --- a/website/source/assets/javascripts/lib/_Chainable.js +++ /dev/null @@ -1,92 +0,0 @@ -(function(){ - -var Chainable = function(engine){ - this.engine = engine; - this._chain = []; - this._updateTimer = this._updateTimer.bind(this); - this._cycle = this._cycle.bind(this); -}; - -Chainable.prototype._running = false; - -Chainable.prototype._updateTimer = function(tick){ - this._timer += tick; - if (this._timer >= this._timerMax) { - this.resetTimer(); - this._cycle(); - } -}; - -Chainable.prototype.resetTimer = function(){ - this.engine.updateChainTimer = undefined; - this._timer = 0; - this._timerMax = 0; - return this; -}; - -Chainable.prototype.start = function(){ - if (this._running || !this._chain.length) { - return this; - } - this._running = true; - return this._cycle(); -}; - -Chainable.prototype.reset = function(){ - if (!this._running) { - return this; - } - this.resetTimer(); - this._timer = 0; - this._running = false; - return this; -}; - -Chainable.prototype._cycle = function(){ - var current; - if (!this._chain.length) { - return this.reset(); - } - - current = this._chain.shift(); - - if (current.type === 'function') { - current.func.apply(current.scope, current.args); - current = null; - return this._cycle(); - } - if (current.type === 'wait') { - this.resetTimer(); - // Convert timer to seconds - this._timerMax = current.time / 1000; - this.engine.updateChainTimer = this._updateTimer; - current = null; - } - - return this; -}; - -Chainable.prototype.then = Chainable.prototype.exec = function(func, scope, args){ - this._chain.push({ - type : 'function', - - func : func, - scope : scope || window, - args : args || [] - }); - - return this.start(); -}; - -Chainable.prototype.wait = function(time){ - this._chain.push({ - type : 'wait', - time : time - }); - - return this.start(); -}; - -window.Chainable = Chainable; - -})(); diff --git a/website/source/assets/javascripts/lib/_Function.prototype.bind.js b/website/source/assets/javascripts/lib/_Function.prototype.bind.js deleted file mode 100644 index 82c3cb6c6..000000000 --- a/website/source/assets/javascripts/lib/_Function.prototype.bind.js +++ /dev/null @@ -1,21 +0,0 @@ -if (!Function.prototype.bind) { - Function.prototype.bind = function (oThis) { - if (typeof this !== "function") { - throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable"); - } - - var aArgs = Array.prototype.slice.call(arguments, 1), - fToBind = this, - fNOP = function () {}, - fBound = function () { - return fToBind.apply(this instanceof fNOP && oThis ? - this : oThis, - aArgs.concat(Array.prototype.slice.call(arguments))); - }; - - fNOP.prototype = this.prototype; - fBound.prototype = new fNOP(); - - return fBound; - }; -} diff --git a/website/source/assets/javascripts/lib/_String.substitute.js b/website/source/assets/javascripts/lib/_String.substitute.js deleted file mode 100644 index da2b52a38..000000000 --- a/website/source/assets/javascripts/lib/_String.substitute.js +++ /dev/null @@ -1,14 +0,0 @@ -(function(String){ - -if (String.prototype.substitute) { - return; -} - -String.prototype.substitute = function(object, regexp){ - return String(this).replace(regexp || (/\\?\{([^{}]+)\}/g), function(match, name){ - if (match.charAt(0) == '\\') return match.slice(1); - return (object[name] !== null) ? object[name] : ''; - }); -}; - -})(String); diff --git a/website/source/assets/javascripts/lib/_Vector.js b/website/source/assets/javascripts/lib/_Vector.js deleted file mode 100644 index 0334c7ac7..000000000 --- a/website/source/assets/javascripts/lib/_Vector.js +++ /dev/null @@ -1,111 +0,0 @@ -(function(global){ 'use strict'; - -var Vector = function(x, y){ - this.x = x || 0; - this.y = y || 0; -}; - -Vector.prototype = { - - clone: function(){ - return new Vector(this.x, this.y); - }, - - add: function(vec){ - this.x += vec.x; - this.y += vec.y; - return this; - }, - - sub: function(vec){ - this.x -= vec.x; - this.y -= vec.y; - return this; - }, - - subVal: function(val){ - this.x -= val; - this.y -= val; - return this; - }, - - mult: function(mul){ - this.x *= mul; - this.y *= mul; - return this; - }, - - div: function(div){ - if (div === 0) { - return this; - } - this.x /= div; - this.y /= div; - return this; - }, - - mag: function(){ - return Math.sqrt( - this.x * this.x + - this.y * this.y - ); - }, - - limit: function(max){ - if (this.mag() > max) { - this.normalize(); - this.mult(max); - } - return this; - }, - - normalize: function(){ - var mag = this.mag(); - if (mag === 0) { - return this; - } - this.div(mag); - return this; - }, - - heading: function(){ - return Math.atan2(this.y, this.x); - }, - - set: function(vec){ - this.x = vec.x; - this.y = vec.y; - return this; - } - -}; - -Vector.add = function(vec1, vec2){ - return vec1.clone().add(vec2.clone()); -}; - -Vector.sub = function(vec1, vec2){ - return vec1.clone().sub(vec2.clone()); -}; - -Vector.mult = function(vec, mult){ - return vec.clone().mult(mult); -}; - -Vector.div = function(vec, div){ - return vec.clone().div(div); -}; - -// Ripped from processing -Vector.random2D = function(){ - var angle = Math.random(0, 1) * Math.PI * 2; - return new Vector(Math.cos(angle), Math.sin(angle)); -}; - -Vector.coerce = function(obj){ - return new Vector(obj.x, obj.y); -}; - -global.Vector = Vector; - -})(this); diff --git a/website/source/assets/javascripts/lib/_dbg.js b/website/source/assets/javascripts/lib/_dbg.js deleted file mode 100644 index 6df4f3762..000000000 --- a/website/source/assets/javascripts/lib/_dbg.js +++ /dev/null @@ -1,60 +0,0 @@ -/* - * - * name: dbg - * - * description: A bad ass little console utility, check the README for deets - * - * license: MIT-style license - * - * author: Amadeus Demarzi - * - * provides: window.dbg - * - */ - -(function(){ - - var global = this, - - // Get the real console or set to null for easy boolean checks - realConsole = global.console || null, - - // Backup / Disabled Lambda - fn = function(){}, - - // Supported console methods - methodNames = ['log', 'error', 'warn', 'info', 'count', 'debug', 'profileEnd', 'trace', 'dir', 'dirxml', 'assert', 'time', 'profile', 'timeEnd', 'group', 'groupEnd'], - - // Disabled Console - disabledConsole = { - - // Enables dbg, if it exists, otherwise it just provides disabled - enable: function(quiet){ - global.dbg = realConsole ? realConsole : disabledConsole; - }, - - // Disable dbg - disable: function(){ - global.dbg = disabledConsole; - } - - }, name, i; - - // Setup disabled console and provide fallbacks on the real console - for (i = 0; i < methodNames.length;i++){ - name = methodNames[i]; - disabledConsole[name] = fn; - if (realConsole && !realConsole[name]) - realConsole[name] = fn; - } - - // Add enable/disable methods - if (realConsole) { - realConsole.disable = disabledConsole.disable; - realConsole.enable = disabledConsole.enable; - } - - // Enable dbg - disabledConsole.enable(); - -}).call(this); diff --git a/website/source/assets/stylesheets/_buttons.scss b/website/source/assets/stylesheets/_buttons.scss index c1f44435d..e1037e818 100755 --- a/website/source/assets/stylesheets/_buttons.scss +++ b/website/source/assets/stylesheets/_buttons.scss @@ -1,137 +1,37 @@ -// -// Button Styles -// -------------------------------------------------- - -.outline-btn{ - position: relative; - display: inline-block; - // Extra 3px of bottom padding compensates for ::after content - padding: 20px 30px 23px; - background-color: transparent; - color: $white; - border: 2px solid $white; - //border-radius: $btn-border-radius; - font-size: 20px; - font-weight: 500; - text-transform: uppercase; - letter-spacing: 2px; - text-decoration: none !important; - @include transition(background-color .3s ease-in-out); - - &::after { - font-size: 1.2em; - content: "»"; - position: relative; - left: 5px; - } - - &.purple{ - color: $purple; - border: 2px solid $purple; - } - - &.small-outline-btn{ - font-size: 16px; - padding: 0px 15px 3px 10px; - letter-spacing: 0; - border: 2px solid rgba(255, 255, 255, .7); - } - - &:hover{ - color: $white; - background-color: rgba(255, 255, 255, .2); - @include transition(background-color .3s ease-in-out); - - &.purple{ - background-color: rgba(255, 255, 255, .5); - } - } -} - -.simple-btn{ - position: relative; - display: inline-block; - // Extra 3px of bottom padding compensates for ::after content - background-color: transparent; - color: $white; - font-size: 16px; - font-weight: 500; - text-transform: uppercase; - text-decoration: none !important; - @include transition(color .3s ease-in-out); - - &::after { - font-size: 1.2em; - content: "»"; - position: relative; - left: 5px; - } - - &:hover{ - color: rgba(255, 255, 255, .4); - @include transition(color .3s ease-in-out); - } -} - -.terra-btn{ - position: relative; - display: inline-block; - // Extra 3px of bottom padding compensates for ::after content - padding: 20px 30px 23px; - color: white; - background-color: $purple; - font-size: 20px; - font-weight: 500; - text-transform: uppercase; - letter-spacing: 2px; - @include transition( background-color 0.3s ease ); - - &::after { - font-size: 1.2em; - content: "»"; - position: relative; - left: 5px; - } - - &:hover{ - color: white; - background-color: rgba(130, 47, 247, 0.8); - text-decoration: none; - @include transition( background-color 0.3s ease ); - } -} - -@media (max-width: 768px) { - .outline-btn, .terra-btn{ - font-size: 16px; - text-align: center; - } -} - -//animation on header main nav link hover -/*.li-under a::after { - position: absolute; - top: 68%; - left: 50%; - margin-left: -4px; - width: 6px; - height: 6px; - background-color: white; - content: ''; - opacity: 0; +.button { + background: $button-background; + border: 1px solid $button-font-color; + box-shadow: 3px 4px 0 rgba(0,0,0,0.1); + color: $button-font-color; + display: inline-block; + font-family: $button-font-family; + font-size: $button-font-size; + font-weight: $button-font-weight; + letter-spacing: 1px; + margin-bottom: 4px; + padding: 10px 30px; + text-transform: uppercase; text-decoration: none; - -webkit-transition: height 0.3s, opacity 0.3s, -webkit-transform 0.3s; - -moz-transition: height 0.3s, opacity 0.3s, -moz-transform 0.3s; - transition: height 0.3s, opacity 0.3s, transform 0.3s; - -webkit-transform: translateY(-10px); - -moz-transform: translateY(-10px); - transform: translateY(-10px); -} -.li-under a:hover::after, -.li-under a:focus::after { - opacity: 1; - -webkit-transform: skewY(15deg) translateY(10px); - -moz-transform: skewY(15deg) translateY(10px); - transform: skewY(15deg) translateY(10px); -}*/ + &:hover, + &:active, + &:focus { + text-decoration: none; + } + + &:hover { + background: $button-font-color; + border: 1px solid $button-font-color; + color: $button-background; + } + + &.primary { + background: $button-primary-background; + border: 1px solid darken($button-primary-background, 5%); + color: $button-primary-font-color; + + &:hover { + background: lighten($button-primary-background, 5%); + } + } +} diff --git a/website/source/assets/stylesheets/_community.scss b/website/source/assets/stylesheets/_community.scss index de945fa38..1ff047de6 100644 --- a/website/source/assets/stylesheets/_community.scss +++ b/website/source/assets/stylesheets/_community.scss @@ -1,20 +1,22 @@ -.people { +#inner { + .people { margin-top: 30px; .person { - margin-bottom: 40px; + &:after { + display: block; + clear: both; + content: ' '; + } - h3 { - text-transform: none; - } + img { + width: 125px; + margin: auto auto; + } - img { - width: 125px; - margin: auto auto; - } - - .bio { - padding-left: 150px; - } + .bio { + padding-left: 150px; + } } + } } diff --git a/website/source/assets/stylesheets/_docs.scss b/website/source/assets/stylesheets/_docs.scss index 35f16eb60..475aa46d8 100755 --- a/website/source/assets/stylesheets/_docs.scss +++ b/website/source/assets/stylesheets/_docs.scss @@ -1,362 +1,91 @@ -// -// Docs -// -------------------------------------------------- - -body.page-sub{ - background-color: $light-black; -} - -body.layout-backend-types, -body.layout-commands-env, -body.layout-commands-state, -body.layout-alicloud, -body.layout-archive, -body.layout-arukas, -body.layout-atlas, -body.layout-aws, -body.layout-azure, -body.layout-bitbucket, -body.layout-chef, -body.layout-azurerm, -body.layout-circonus, -body.layout-clc, -body.layout-cloudflare, -body.layout-cloudstack, -body.layout-cobbler, -body.layout-consul, -body.layout-datadog, -body.layout-digitalocean, -body.layout-dme, -body.layout-dns, -body.layout-dnsimple, -body.layout-docker, -body.layout-dyn, -body.layout-external, -body.layout-github, -body.layout-grafana, -body.layout-fastly, -body.layout-google, -body.layout-heroku, -body.layout-ignition, -body.layout-icinga2, -body.layout-influxdb, -body.layout-kubernetes, -body.layout-librato, -body.layout-logentries, -body.layout-mailgun, -body.layout-mysql, -body.layout-newrelic, -body.layout-nomad, -body.layout-ns1, -body.layout-openstack, -body.layout-opsgenie, -body.layout-packet, -body.layout-pagerduty, -body.layout-postgresql, -body.layout-powerdns, -body.layout-profitbricks, -body.layout-rabbitmq, -body.layout-rancher, -body.layout-random, -body.layout-rundeck, -body.layout-scaleway, -body.layout-spotinst, -body.layout-statuscake, -body.layout-softlayer, -body.layout-template, -body.layout-tls, -body.layout-ultradns, -body.layout-triton, -body.layout-vault, -body.layout-vcd, -body.layout-vsphere, -body.layout-docs, -body.layout-downloads, -body.layout-inner, -body.layout-remotestate, -body.layout-terraform, -body.layout-intro{ - background: $light-black image-url('sidebar-wire.png') left 62px no-repeat; - - >.container{ - .col-md-8[role=main]{ - min-height: 800px; - background-color: white; - - >div{ - position: relative; - z-index: 10; - } - } - } -} - -.docs-sidebar{ - position: relative; - z-index: 20; +#docs-sidebar { margin-bottom: 30px; - margin-top: 50px; - margin-right: 4%; + margin-top: 50px; + overflow: hidden; - a{ - color: $purple; - } - - .docs-sidenav{ - padding-top: 15px; - padding-bottom: 15px; - font-family: $font-family-klavika; - font-size: 16px; - - :last-child{ - border-bottom: none; - } - - //all li > a - li{ - position: relative; - - > a{ - color: white; - @include transition( color 0.5s ease ); - } - - > a:hover, - > a:focus { - background-color: transparent !important; - color: white; - @include transition( color 0.5s ease ); - } - } - - - > li { - padding: 10px 0; - - >.nav{ - li{ - a{ - font-family: $font-family-open-sans; - color: white; - } - } - } - - &.active { - >a{ - color: lighten($purple, 4%); - font-weight: 600; - } - - &:before{ - content: ''; - position: absolute; - width: 6px; - height: 8px; - background-color: $purple; - font-weight: 500; - @include skewY(24deg); - top: 26px; - left: -10px; - } - > a{ - -webkit-font-smoothing: antialiased; - } - - .nav { - display: block; - - li.active a { - color: lighten($purple, 4%); - font-weight: 500; - } - } - } - - > a { - text-transform: uppercase; - letter-spacing: 1px; - -webkit-font-smoothing: antialiased; - } - } - - .nav { - display: none; - margin-bottom: 15px; - - > li{ - margin-left: 20px; - - > a{ - -webkit-font-smoothing: antialiased; - padding: 6px 15px; - } - } - } - - .nav-visible { - display: block; - } - } -} - -.bs-docs-section{ - @media(max-width: 767px){ - padding: 10px 5px 80px 5px; - } - @media(min-width: 768px){ - padding: 10px 20px 80px 20px; - } - - .lead{ - margin-bottom: 48px - } - - .doc-sectional{ - margin-bottom: 48px; - } - - p, li, .alert { - font-size: 18px; - line-height: 1.5; - margin: 0 0 18px; - -webkit-font-smoothing: antialiased; - } - - pre{ - margin: 0 0 18px; - } - - a{ - color: $purple; - &:hover{ - text-decoration: underline; - } - } - - img{ - max-width: 650px; - margin-top: 25px; - margin-bottom: 25px; - } - - h1{ - margin-top: 72px; - color: $purple; - font-weight: 400; - text-transform: uppercase; - letter-spacing: -1px; - word-wrap: break-word; - } - - h2, h3, h4{ - margin-top: 48px; - font-family: $font-family-open-sans; - text-transform: none; - } - - h2 { - margin-bottom: 16px; - padding-bottom: 10px; - border-bottom: 1px solid #eeeeee; - } - - p { - color: $light-black; - } - - #graph { + h1, + h2, + h3, + h4, + h5, + h6 { margin-top: 30px; } -} -@media (max-width: 992px) { - body.layout-docs, - body.layout-inner, - body.layout-intro{ - >.container{ - .col-md-8[role=main]{ - min-height: 0; - &::before { - border-left: 9999px solid white; - } - } - } - } + ul.nav.docs-sidenav { + display: block; + padding-bottom: 15px; - body.page-sub{ - >.container{ - background-color: white; - } - } + li { + a { + color: $sidebar-link-color; + font-size: $sidebar-font-size; + padding: 10px 0 10px 15px; - .docs-sidebar{ - margin-top: 0px; - margin-bottom: 0px; + &:before { + color: $sidebar-link-color-active; + content: '\203A'; + font-size: $font-size; + left: 0; + line-height: 100%; + opacity: 0.4; + position: absolute; - .docs-sidenav{ - padding-bottom: 0; - - //all li > a - li{ - > a{ - color: black; - @include transition( color 0.5s ease ); + height: 100%; + width: 8px } - > a:hover, - > a:focus { - color: $purple; - @include transition( color 0.5s ease ); + &:focus, + &:hover { + background-color: transparent; + color: $sidebar-link-color-hover; + + &:before { + opacity: 1; + } } - } - - > li { - >.nav{ - li{ - a{ - color: black; - - &:hover{ - color: $purple; - } - } + &.back { + &:before { + content: '\2039'; } } } - } - } - .bs-docs-section{ - h1{ - font-size: 32px; - padding-top: 24px; - border-top: 1px solid #eeeeee; + // For forcing sub-navs to appear - in the long term, this should not + // be a thing anymore... + > ul.nav-visible { + display: block; + } } - h2 { - font-size: 24px; - } + li.active { + > a { + color: $sidebar-link-color-active; - h2, h3, h4{ - margin-top: 32px; - } - - p, li, .alert { - font-size: 16px; - } - } -} - -@media (max-width: 480px) { - .bs-docs-section{ - img{ - max-width: 450px; + &:before { + opacity: 1; } + } - h1{ - font-size: 28px; - } - } + // Open nested navigations + > ul.nav { + display: block; + } + } + + // subnav + ul.nav { + display: none; + margin: 10px; + + li { + margin-left: 10px; + + a { + padding: 6px 15px; + } + } + } + } } diff --git a/website/source/assets/stylesheets/_downloads.scss b/website/source/assets/stylesheets/_downloads.scss index be2187eaf..97a4dfc66 100644 --- a/website/source/assets/stylesheets/_downloads.scss +++ b/website/source/assets/stylesheets/_downloads.scss @@ -1,59 +1,60 @@ -.downloads { - margin-top: 20px; +body.layout-downloads { + #inner { + .downloads { + margin-top: 20px; - .description { + .description { margin-bottom: 20px; - } + } - .download { + .download { + align-items: center; border-bottom: 1px solid #b2b2b2; - padding-bottom: 15px; - margin-top: 10px; - margin-bottom: 10px; + display: flex; + padding: 15px; .details { - padding-left: 95px; + padding-left: 20px; - h2 { - margin-top: 30px; + h2 { + margin-top: 4px; + border: none; + } + + ul { + padding-left: 0px; + margin: -8px 0 0 0; + } + + li { + display: inline-block; + + &:after { + content: " | "; } - ul { - padding-left: 0px; - } - - li { - display: inline-block; - - &:after { - content: " | "; - } - - &:last-child:after { - content: ""; - } + &:last-child:after { + content: ""; } + } } .icon { - img { - width: 75px; - } + svg { + width: 75px; + } } .os-name { - font-size: 40px; - margin-bottom: -3px; + font-size: 40px; + margin-bottom: -3px; } - } + } - .poweredby { + .poweredby { margin-top: 20px; - - img { - display: block; - margin: 0 auto; - width: 122px; - } + text-align: center; + } } + } } diff --git a/website/source/assets/stylesheets/_footer.scss b/website/source/assets/stylesheets/_footer.scss index 2bf21204f..ae34a057a 100644 --- a/website/source/assets/stylesheets/_footer.scss +++ b/website/source/assets/stylesheets/_footer.scss @@ -1,98 +1,22 @@ -body.page-sub{ - #footer{ - padding: 40px 0; - margin-top: 0; +#footer { + padding-top: 50px; - .hashicorp-project{ - margin-top: 24px; - &:hover{ - svg{ - .svg-bg-line{ - opacity: .4; - } + ul.footer-links { + li { + a { + color: $footer-link-color; + font-size: $footer-font-size; + font-family: $font-family-open-sans; + text-decoration: none; + + &:hover, &:focus, &:active { + background-color: transparent; + color: $footer-link-color-hover; + outline: 0; } - } - } - } -} -#footer{ - background-color: white; - padding: 150px 0 80px; - margin-top: -40px; - - &.white{ - background-color: $black; - .footer-links{ - li > a { - @include project-footer-a-subpage-style(); - } - } - } - - .footer-links{ - li > a { - @include project-footer-a-style(); - } - } - - .hashicorp-project{ - margin-top: 24px; - } - - .pull-right{ - padding-right: 15px; - } -} - -.edit-page-link{ - position: absolute; - top: -70px; - right: 30px; - z-index: 9999; - - a{ - text-transform: uppercase; - color: $black; - font-size: 13px; - } -} - -@media (max-width: 992px) { - .footer-links { - display: block; - text-align: center; - - ul{ - display: inline-block;; - float: none !important; - } - - .footer-hashi{ - display: block; - float: none !important; - } - } -} - -@media (max-width: 414px) { - #footer{ - ul{ - display: block; - li{ - display: block; - float: none; - } - - &.external-links{ - li{ - svg{ - position: relative; - left: 0; - top: 2px; - margin-top: 0; - margin-right: 4px; - } + @media (max-width: 992px) { + text-align: center; } } } diff --git a/website/source/assets/stylesheets/_global.scss b/website/source/assets/stylesheets/_global.scss index f30bbff6d..fc46858d6 100755 --- a/website/source/assets/stylesheets/_global.scss +++ b/website/source/assets/stylesheets/_global.scss @@ -1,117 +1,43 @@ -// -// Global Site -// -------------------------------------------------- - -/*html{ +html { + height: 100%; + min-height: 100%; text-rendering: optimizeLegibility; -webkit-font-smoothing: antialiased; -}*/ +} body { - // -webkit-font-smoothing: subpixel-antialiased; - color: $black; - font-size: 15px; - font-family: $font-family-open-sans; - font-weight: 500; + -webkit-font-smoothing: antialiased; + color: $body-font-color; + background-color: $white; + font-size: $font-size; + font-family: $font-family-open-sans; + font-weight: $font-weight-reg; + height: 100%; + min-height: 100%; } h1, h2, h3, h4, h5 { - -webkit-font-smoothing: antialiased; - font-family: $font-family-klavika; - font-weight: 600; -} -h1{ - font-size: 42px; - line-height: 40px; - margin-bottom: 24px; - text-transform: uppercase; + font-family: $font-family-klavika; + -webkit-font-smoothing: antialiased; } -h2{ - font-size: 34px; - text-transform: uppercase; +h1 { + margin-bottom: 24px; } -h3{ - font-size: 20px; - line-height: 20px; - text-transform: uppercase; -} - -h4 { - font-size: 18px; -} - -p { - margin-bottom: 30px; - font-size: 16px; - font-weight: regular; - line-height: 1.5; -} - -p.lead{ - font-size: 21px; - font-weight: 400 !important; -} - -//an alternative color for buttons in the doc body -.btn-serf{ - color: $white !important; - background-color: $btn-color; - border-radius: $btn-border-radius; - //@include box-shadow( $shadow ); -} - -.highlight{ - margin-bottom: 18px; -} - -pre { - background-color: $black; - color: $white; - font-size: 14px; - font-weight: normal; - font-family: "Courier New", Monaco, Menlo, Consolas, monospace; - border: none; - padding: 20px; - margin-bottom: 0; -} - -// Typekit utilites to hide FOUC +// Avoid FOUT .wf-loading { visibility: hidden; } + .wf-active, .wf-inactive { visibility: visible; } - -//fixed grid below 992 to prevent smaller responsive sizes -@media (max-width: 992px) { - .container{ - max-width: 970px; - } -} - -//all below styles are overriding corrections for below (min-width: 992px) -//below (min-width: 992px) these styles change -.navbar-nav { - margin: 0; -} - -.navbar-right { - float: right !important; -} - -.navbar-nav > li { - float: left; -} - -.navbar-nav > li > a { - padding-top: 15px; - padding-bottom: 15px; -} - -.center { - text-align: center; +@media (min-width: $screen-sm) and (max-width: $screen-md) { + .container { + padding: 0; + max-width: $screen-md; + min-width: $screen-sm; + } } diff --git a/website/source/assets/stylesheets/_header.scss b/website/source/assets/stylesheets/_header.scss index 310664235..dde70d7d6 100755 --- a/website/source/assets/stylesheets/_header.scss +++ b/website/source/assets/stylesheets/_header.scss @@ -1,57 +1,78 @@ -// -// Header -// - Project Specific -// - edits should be made here -// -------------------------------------------------- - -body.page-sub{ - #header{ - background-color: $purple; - } -} - #header { - .navbar-brand { - .logo{ - width: $project-logo-width; - height: $project-logo-height; - font-size: 0px; - font-family: $font-family-klavika; - background: image-url('logo-header.svg') 0 32% no-repeat; + background: $header-background-color; - &:hover{ - opacity: .6; + .navbar-toggle { + height: $header-height; + margin: 0; + padding-right: 15px; + border-radius: 0; + + .icon-bar { + border: 1px solid $white; + border-radius: 0; + } + } + + .navbar-brand { + display: block; + margin: 0; + padding: 0; + + a { + display: flex; + align-items: center; + height: $header-height; + line-height: $header-height; + + svg.logo { + transition: opacity 0.15s ease-in-out; + @extend svg.logo.white; + + &:hover, &:focus, &:active { + opacity: 0.6; + outline: 0; + text-decoration: none; + } } } + } - .by-hashicorp{ - margin-top: 2px; - &:hover{ - svg{ - .svg-bg-line{ - opacity: .4; + ul.nav { + li { + a { + color: $header-link-color; + font-size: $header-font-size; + font-family: $font-family-open-sans; + font-weight: $font-weight-bold; + height: $header-height; + line-height: $header-height; + padding: 0 10px; + margin: 0; + text-decoration: none; + + &:hover, &:focus, &:active { + background-color: transparent; + color: $header-link-color-hover; + outline: 0; + + svg { + fill: $header-link-color-hover; } } - } - } - } - .buttons{ - margin-top: 2px; //baseline everything - - ul.navbar-nav{ - li { - svg path{ - fill: $white; + svg { + fill: $header-link-color; + position: relative; + top: 2px; + width: 14px; + height: 14px; + margin-right: 3px; } } } } - .main-links, - .external-links { - li > a { - @include project-a-style(); - } + .buttons { + margin-top: 2px; } } diff --git a/website/source/assets/stylesheets/_home.scss b/website/source/assets/stylesheets/_home.scss old mode 100755 new mode 100644 index 807a8b542..442638906 --- a/website/source/assets/stylesheets/_home.scss +++ b/website/source/assets/stylesheets/_home.scss @@ -1,823 +1,338 @@ -// -// Home -// -------------------------------------------------- - -body.page-home { - h2.tag-line { - font-size: 40px; - } - - #primary-cta{ - position: relative; - margin-top: -30px; - padding-bottom: 40px; - color: $white; - background: $black; - z-index: 99; - - .terra-btn{ - margin-top: 30px; - } - } - - .temp-skew { - position: relative; - height: 240px; - background-color: #000; - @include skewY(-3deg); - margin-top: -100px; - -webkit-backface-visibility: hidden; - border: 2px solid #000; - z-index: 0; - } - - .announcement { - margin-top: 60px; - border: 1px solid rgba(255,255,255,.3); - padding: 25px 10px; - - p { - color: $gray; - line-height: 1.2; - margin-bottom: 0; - - a { - color: $purple; - text-decoration: underline; - // inline-block ensures links doesn't text-wrap; - display: inline-block; - } - } - } - - #customer-logos{ - position: relative; - width: 100%; - margin-top: -100px; - padding: 60px 0; - color: $white; - - >.container { - z-index: 91; - } - - p { - text-transform: uppercase; - letter-spacing: 2px; - } - - #customer-logos-bg{ - z-index: 30; - background: $black; - background-size: 100%; - @include skewY(-3deg); - } - } - - ul.customer-list{ - padding-left: 15px; - - li{ - display: inline-block; - width: 16%; - height: 80px; - text-indent: 100%; - white-space: nowrap; - overflow: hidden; - } - - #nike { - background: transparent image-url("customer-logos/nike.svg") left no-repeat; - background-size: 80px; - } - - #hbo { - background: transparent image-url("customer-logos/hbo.svg") left no-repeat; - background-size: 80px; - } - - #target { - background: transparent image-url("customer-logos/target.svg") left no-repeat; - background-size: 50px; - } - - #capital-one { - background: transparent image-url("customer-logos/capital-one.svg") left no-repeat; - background-size: 100px; - } - - #home-depot { - background: transparent image-url("customer-logos/home-depot.svg") left no-repeat; - background-size: 50px; - } - - #hotels-dot-com { - background: transparent image-url("customer-logos/hotels-dot-com.svg") left no-repeat; - background-size: 100px; - } - } - - #feature-overview{ - position: relative; - padding: 120px 0; - border-bottom: 2px solid #E6E7E8; - z-index: 80; - } - - .feature-card{ - display: block; - height: 200px; - border: 2px solid #E6E7E8; - margin-bottom: 15px; - padding:20px; - font-size: 18px; - - h3{ - margin:0; - padding: 0; - color: $purple; - font-size: 16px; - line-height: 1.2; - font-weight: 400; - text-transform: uppercase; - } - - p{ - color: #000; - font-size: 16px; - line-height: 1.2; - font-weight: 400; - text-transform: uppercase; - letter-spacing: 1px; - } - - &.feature-card-write{ - background: image-url("feature-card-write.svg") left 20px top 70% no-repeat; - background-size: 80%; - } - - &.feature-card-plan{ - background: image-url("feature-card-plan.svg") left 0 top 69% no-repeat; - background-size: 100%; - } - - &.feature-card-create{ - background: image-url("feature-card-create.svg") left 0 top 70% no-repeat; - background-size: 80%; - } - - &:hover { - border: 2px solid $purple; - text-decoration: none; - } - } - - .feature{ - - p.lead{ - max-width: 30em; - } - } - - .skew-item{ - >.container{ - position: relative; - top: 0; - z-index: 11; - } - - .feature-skew{ - position: absolute; - top: 0px; - bottom: 0px; - left: 0px; - width: 100%; - height: 100%; - } - } - - #feature-write{ - position: relative; - padding: 180px 0 120px; - margin-top: -80px; - - - >.container { - z-index: 71; - } - - // This svg appears twice in the markup and swapped for layout purposes. - // Image for small screens. Styles below are for larger screens. - #feature-image-write-sm-screen { - display: block; - position: relative; - margin: 0 auto; - width:80%; - max-width: 400px; - } - - // Image hidden, made visible for larger screens - #feature-image-write-lg-screen { - display: none; - position: absolute; - bottom: 2px; - right: 3%; - width: 581px; - @include skewY(-3deg); - } - - #feature-write-bg{ - background: $white; - z-index: 70; - @include skewY(3deg); - overflow: hidden; - } - } - - #feature-plan{ - position: relative; - color: $white; - background-size: 80%; - position: relative; - padding: 220px 0 180px; - margin-top: -80px; - - >.container { - z-index: 61; - // background: image-url("feature-plan-bg.svg") 0% 45% no-repeat; - background-size: 100%; - } - - // This svg appears twice in the markup and swapped for layout purposes. - // Image for small screens. Styles below are for larger screens. - #feature-image-plan-sm-screen { - display: block; - position: relative; - margin: 0 auto; - width: 100%; - max-width: 400px; - } - - // Image hidden, made visible for larger screens - #feature-image-plan-lg-screen { - display: none; - position: relative; - width: 100%; - } - - #feature-plan-bg{ - background: $purple; - z-index: 60; - @include skewY(-3deg); - } - } - - #feature-create{ - position: relative; - margin-top: -80px; - padding: 240px 0 180px; - - >.container{ - z-index: 51; - } - - #feature-image-create { - display: block; - max-width: 500px; - padding-left: 10px; - margin: 0 auto; - margin-bottom: 40px; - } - - #feature-image-create-lg-screen{ - display: none; - } - - #feature-create-bg{ - @include skewY(3deg); - - z-index: 50; - overflow: hidden; - } - } - - #demos{ - position: relative; - padding: 120px 0 60px; - margin-top: -80px; - - >.container{ - z-index: 41; - } - - #demo-bg{ - background-color: #E6E7E8; - @include skewY(3deg); - z-index: 40; - } - - h2{ - text-align: center; - } - - p { - margin-bottom: 20px; - } - - .terminals{ - margin-bottom: 80px; - - .terminal-item{ - margin-bottom: 80px; - - &.last{ - border-bottom: none; - } - >header{ - .left{ - span.icn{ - display: inline-block; - width: 83px; - height: 74px; - } - } - - .right{ - padding-left: 25px; - } - } - - .terminal{ - - border: 2px solid #1e1e1e; - background: $black; - //border-radius: 4px; - - header{ - position: relative; - text-align: center; - padding: 3px; - border-bottom: 2px solid #1e1e1e; - - h4{ - font-size: 14px; - letter-spacing: 1px; - color: white; - } - - ul.shell-dots{ - position: absolute; - top: 10px; - left: 8px; - padding-left: 0; - - li{ - &.d1{ - background-color: #4a08a7; - } - &.d2{ - background-color: #6517cf; - } - &.d3{ - background-color: #7b29ee; - } - - display: inline-block; - width: 12px; - height: 12px; - border-radius: 6px; - margin-left: 6px; - } - } - } - - .terminal-window{ - min-height: 140px; - padding: 20px; - font-size: 15px; - color: $white; - background-color: transparent; - overflow:auto; - font-weight: 500; - -webkit-font-smoothing: subpixel-antialiased; - - p { - font-family: "Courier New", Monaco, Menlo, Consolas, monospace; - } - - .txt-spe { - color: lighten($blue, 5%); - font-weight: 600; - } - - .txt-var { - color: lighten($purple, 8%); - font-weight: 600; - } - - .txt-str { - color: lighten($green, 2%); - } - - .txt-int { - color: lighten($orange, 2%); - font-weight: 600; - } - - p{ - margin-bottom: 2px; - white-space: pre-wrap; - } - .cursor { - background-color: lighten($purple, 5%); - } - } - } - - .feature-bullets{ - list-style-type: none; - padding-left: 35px; - - li{ - padding: 5px 0 5px 45px; - } - } - } - } - } - - #demo-cta{ - text-align: center; - } - - #latest-announcement{ - position: relative; - margin-top: -80px; - padding: 160px 0 200px; - color: $white; - text-align: left; - - >.container{ - z-index: 51; - } - - h2{ - margin-bottom: 60px; - } - - .latest-col-right{ - position: relative; - padding-left: 60px; - - &:after{ - content: ''; - position: absolute; - left: 30px; - top: 0; - width: 2px; - height: 100%; - background-color: rgba(255, 255, 255, .15); +#page-home { + // Override the main header + #header { + background: $home-header-background-color; + + .navbar-toggle { + .icon-bar { + border: 1px solid $home-header-link-color; } } - .latest-item{ - &.latest-item-text{ - border-bottom: 2px solid rgba(255, 255, 255, .15); + .navbar-brand { + a { + svg.logo { + @extend svg.logo.color; + } + } + } - &:first-child{ - h3{ - margin-top: 0; + ul.nav { + li { + a { + color: $home-header-link-color; + + &:hover, &:focus, &:active { + background-color: transparent; + color: $home-header-link-color-hover; + + svg { + fill: $home-header-link-color-hover; + } + } + + svg { + fill: $home-header-link-color; + } + } + } + } + } + + header { + .hero { + margin: 140px auto 160px auto; + text-align: center; + + .button { + margin: 5px; + + @media (max-width: 768px) { + display: block; + margin-top: 10px; + text-align: center; + } + } + + svg { + max-width: 90%; + } + } + } + + section { + background: $white; + padding: 100px 0; + } + + section.marketing { + h2 { + font-family: $font-family-klavika; + font-size: 36px; + font-weight: $font-weight-bold; + line-height: 1.25; + letter-spacing: -0.02em; + margin: 20px 0 10px 0; + padding: 0; + text-transform: uppercase; + } + + h3 { + color: $black; + font-size: 20px; + font-weight: $font-weight-bold; + line-height: 1.2; + margin: 50px 0 15px 0; + text-transform: uppercase; + } + + p { + font-family: $font-family-open-sans; + font-size: 16px; + letter-spacing: 0.01em; + line-height: 1.5; + margin: 0 0 10px; + } + + p.lead { + font-size: 20px; + margin: 15px 0 30px 0; + } + + span.callout { + background: $black; + color: $white; + display: inline-block; + font-family: $font-family-klavika; + font-size: 18px; + font-weight: $font-weight-bold; + line-height: 1; + margin: 0; + padding: 5px; + letter-spacing: 0.05em; + text-transform: uppercase; + } + + &.purple { + background: $terraform-purple; + + h2 { + color: $white; + } + + p { + color: $white; + } + + span.callout { + background: $white; + color: $terraform-purple; + } + + .button { + border: none; + } + } + + &.black { + background: $black; + + h2 { + color: $white; + } + + p { + color: $white; + } + + span.callout { + background: $white; + color: $black; + } + + .button { + border: none; + } + } + + &#features { + .feature-card { + border: 1px solid $gray-darker; + color: $gray-darker; + display: block; + height: 200px; + font-weight: $font-weight-bold; + padding: 20px; + margin-bottom: 15px; + text-transform: uppercase; + transition: all 0.1s ease-in-out; + + p { + line-height: 1.25em; + } + + span { + color: $terraform-purple; + display: block; + font-weight: $font-weight-bold; + margin-bottom: 10px; + } + + svg { + display: block; + margin-top: 20px; + max-width: 100%; + + path { + transition: all 0.1s ease-in-out; + fill: $gray-dark; } } - &:last-child{ - border-bottom: none; - } - } + &:hover, &:active, &:focus { + border: 1px solid $terraform-purple; + color: $terraform-purple; + text-decoration: none; - img{ - box-shadow: 8px 8px 8px rgba(0,0,0,.25); - margin-bottom: 10px; - max-width: 100%; - } - - h3{ - line-height: 1.2; - font-family: $font-family-open-sans; - text-transform: none; - } - - p{ - margin-bottom: 10px; - } - - a{ - margin-top: 5px; - margin-bottom: 10px; - } - } - } - - #latest-announcement-bg{ - @include skewY(-3deg); - z-index: 30; - background: $purple image-url("latest-announce-bg.svg") bottom left no-repeat; - background-size: cover; - } - - #enterprise-intro{ - position: relative; - padding: 220px 0 180px; - margin-top: -80px; - color: #fff; - - >.container{ - z-index: 31; - } - - h2{ - position: relative; - left: -5px; - margin-bottom: 20px; - background: image-url("terraform-enterprise-logo.svg") top left no-repeat; - background-size: 320px; - overflow: hidden; - - span {margin-left: -200%} - } - - .lead{ - max-width: 30em; - margin-bottom: 40px; - } - - #enterprise-intro-bg{ - background: #000 image-url("enterprise-callout-bg.svg") bottom right no-repeat; - background-size: 80%; - @include skewY(3deg); - z-index: 20; - } - } - - @media (-webkit-min-device-pixel-ratio: 2), (min-resolution: 192dpi) { - #demos{ - .terminals{ - .terminal-item{ - .feature-bullets{ - li{ - background-size: 12px 12px; - } - } - } - } - } - } - - @media (min-width: 768px) { - #feature-write{ - // Hide image for small screens - #feature-image-write-sm-screen { - display: none; - } - - // Image hidden, made visible for larger screens - #feature-image-write-lg-screen { - display: block; - } - } - - #feature-plan{ - // Hide image for small screens - #feature-image-plan-sm-screen { - display: none; - } - - // Image hidden, made visible for larger screens - #feature-image-plan-lg-screen { - display: block; - } - } - } - - @media (min-width: 1024px) { - #feature-write{ - #feature-image-write-lg-screen { - right: 10%; - width: 640px; - } - } - } - - @media (min-width: 1440px) { - - #feature-write{ - padding: 280px 0 200px; - margin-top: -120px; - } - - #feature-plan{ - padding: 320px 0 200px; - margin-top: -120px; - } - - #feature-create{ - padding: 320px 0 200px; - margin-top: -120px; - } - - #latest-announcement{ - margin-top: -140px; - padding: 180px 0 240px; - } - - #enterprise-intro{ - margin-top: -140px; - padding: 320px 0 180px; - } - } - - @media (max-width: 992px) { - - #demos{ - .terminals{ - .terminal-item{ - >header{ - .left{ - span.icn{ - } - } - - .right{ - padding-left: 54px; - } - } - } - } - } - - #latest-announcement{ - .latest-col-left{ - .latest-item{ - border-bottom: 2px solid rgba(255, 255, 255, .15); - } - } - - .latest-col-right{ - padding-left: 15px; - - &:after{ - width: 0; - } - } - - .latest-item{ - padding-bottom: 30px; - margin-bottom: 30px; - - &.latest-item-text{ - border-bottom: 2px solid rgba(255, 255, 255, .15); - - &:first-child{ - h3{ - margin-top: 20px; + svg { + path { + fill: $terraform-purple; + transition: all 0.1s ease-in-out; } } } } } - } - @media (max-width: 768px) { - h2{ - margin-bottom: 40px; - font-size: 28px; - line-height: 32px; - letter-spacing: 2px; - text-transform: uppercase; - font-weight: regular; - } + &#plan { + h3 { + color: $white; + } + } - h3{ - margin-bottom: 10px; - font-size: 16px; - line-height: 1.2; - letter-spacing: 1px; - text-transform: uppercase; - font-weight: bold; - } + &#news { + img, iframe { + box-shadow: 5px 5px 0 rgba(0, 0, 0, 0.25); + margin: 0 0 20px 0; + max-width: 100%; + } - p{ - font-size: 14px; - } + iframe { + @media (min-width: $screen-sm) and (max-width: $screen-md) { + width: 100vw; + height: 56.25vw; + } + } - p.lead{ - font-size: 17px; - } + h2 { + margin-bottom: 50px; + } - #primary-cta{ - padding-bottom: 100px; - } + h3 { + color: $white; + margin-top: 0; + text-transform: none; + } - #customer-logos{ - padding: 40px 0; + div.latest-item { + + .latest-item { + border-top: 1px solid rgba(white, .5); + margin-top: 20px; + padding-top: 20px; + } - p { - display: block; - position: relative; - width: 100%; - text-align: center; - } + @media (max-width: $screen-sm-max) { + &:last-child { + border-bottom: 1px solid rgba(white, .5); + margin-bottom: 20px; + padding-bottom: 20px; + } + } - #customer-logos-bg{ - z-index: 30; - background: $black; - background-size: 100%; - @include skewY(-3deg); + p { + padding: 0 0 10px 0; + } - } + .button { + &:hover { + background: $white; + color: $terraform-purple; + } + } + } + } - ul.customer-list{ - padding-left: 15px; + &#examples { + background: #EDEDED; - li{ - display: inline-block; - width: 16%; - height: 80px; - text-indent: 100%; - white-space: nowrap; - overflow: hidden; - } + h1, h2, h3, h4, h5, h6, p { + color: $black; + } + } - #nike { - background: transparent image-url("customer-logos/nike.svg") left no-repeat; - background-size: 40px; - } + &#enterprise { + background-image: image-url('enterprise-callout-bg.svg'); + background-position: right bottom; + background-repeat: no-repeat; + background-size: 80%; + } + } - #hbo { - background: transparent image-url("customer-logos/hbo.svg") left no-repeat; - background-size: 40px; - } + .terminal { + border: 1px solid $white; + background-color: $black; + box-sizing: border-box; + color: $white; + font-family: $font-family-monospace; + font-size: 16px; + line-height: 1.8; + margin: 20px auto; + padding: 10px 20px 20px 20px; - #target { - background: transparent image-url("customer-logos/target.svg") left no-repeat; - background-size: 30px; - } + .terminal-content { + margin-top: 15px; + overflow-x: scroll; + width: 100%; + white-space: nowrap; - #capital-one { - background: transparent image-url("customer-logos/capital-one.svg") left no-repeat; - background-size: 40px; - } + span { + display: block; + white-space: pre; - #home-depot { - background: transparent image-url("customer-logos/home-depot.svg") left no-repeat; - background-size: 30px; - } + span { + display: inline; + } - #hotels-dot-com { - background: transparent image-url("customer-logos/hotels-dot-com.svg") left no-repeat; - background-size: 40px; - } - } + &.text-pink { + color: lighten($consul-pink, 20%); + } + } + } - ul.customer-list{ - display: block; - position: relative; - width: 100%; - margin: 0 auto; - padding: 0; - text-align: center; + span.circle { + &:before { + content: '\25CF'; + color: $white; + font-size: 20px; + line-height: 100%; + height: 100%; + } + } - li{ - display: inline-block; - position: relative; - width: 40px; - height: 40px; - margin: 0 2%; - text-indent: 100%; - white-space: nowrap; - overflow: hidden; - } - } - } + span.txt-spe { + color: #7190EA; + } + span.txt-str { + color: #64E86C; + } - #demos{ + span.txt-int { + color: #E89264; + } - .terminals{ - .terminal-item{ - >header{ - .left{ - span.icn{ - padding-bottom: 15px; - } - } - - .right{ - padding-left: 15px; - } - } - } - } - } - } + span.txt-var { + color: #9A56f9; + } + } } diff --git a/website/source/assets/stylesheets/_inner.scss b/website/source/assets/stylesheets/_inner.scss new file mode 100644 index 000000000..1fd41e3f3 --- /dev/null +++ b/website/source/assets/stylesheets/_inner.scss @@ -0,0 +1,95 @@ +#inner { + p, li, .alert { + font-size: $font-size; + font-family: $font-family-open-sans; + font-weight: $font-weight-reg; + line-height: 1.84em; + margin: 0 0 $font-size; + -webkit-font-smoothing: antialiased; + } + + .alert p:last-child { + margin-bottom: 0; + } + + pre, + code, + pre code, + tt { + font-family: $font-family-monospace; + font-size: $font-size - 2; + line-height: 1.6; + } + + pre { + padding: 20px; + margin: 0 0 $font-size; + + // This will force the code to scroll horizontally on small screens + // instead of wrapping. + code { + overflow-wrap: normal; + white-space: pre; + } + } + + a { + color: $body-link-color; + text-decoration: none; + + &:hover { + text-decoration: underline; + } + + code { + background: inherit; + color: $body-link-color; + } + } + + img { + display: block; + margin: 25px auto; + max-width: 650px; + height: auto; + width: 90%; + } + + h1, + h2, + h3, + h4 { + color: $body-font-color; + margin-top: 54px; + margin-bottom: $font-size; + line-height: 1.3; + } + + h2 { + padding-bottom: 3px; + border-bottom: 1px solid $gray-light; + } + + h1 > code, + h2 > code, + h3 > code, + h4 > code, + h5 > code + h6 > code, + li code, + table code, + p code, + tt, + .alert code { + font-family: $font-family-monospace; + font-size: 90%; + background-color: transparent; + color: inherit; + padding: 0; + } + + table { + @extend .table; + @extend .table-striped; + } +} diff --git a/website/source/assets/stylesheets/_jumbotron.scss b/website/source/assets/stylesheets/_jumbotron.scss deleted file mode 100755 index 52ae80a0f..000000000 --- a/website/source/assets/stylesheets/_jumbotron.scss +++ /dev/null @@ -1,439 +0,0 @@ -// -// Jumbotron -// -------------------------------------------------- - -#jumbotron-mask{ - position:relative; - z-index:0; - height:700px; - margin-top: $negative-hero-margin; - background-color: black; -} - -#jumbotron { - position: relative; - height:700px; - padding-top: 0; - padding-bottom: 0; - color: $jumbotron-color; - - &.static { - background-image:image-url("bg-galaxy.jpg"); - background-position:50% 50%; - background-repeat:no-repeat; - - .jumbotron-content { - background-image:image-url("bg-static.png"); - background-size:cover; - background-position:50% 50%; - background-repeat:no-repeat; - } - - .jumbotron-content:after { - content:''; - display:block; - position:absolute; - top:50%; - left:50%; - background:image-url("logo-static.png"); - - -webkit-background-size:100% 100%; - -moz-background-size:100% 100%; - -ms-background-size:100% 100%; - -o-background-size:100% 100%; - background-size:100% 100%; - - width:360px; - height:360px; - margin:-204px 0 0 -180px; - } - } - - .terraform-canvas { - position:absolute; - top:0; - left:0; - width:100%; - height:100%; - opacity:0; - - -webkit-transition:opacity 2s ease-out; - -moz-transition:opacity 2s ease-out; - -ms-transition:opacity 2s ease-out; - -o-transition:opacity 2s ease-out; - transition:opacity 2s ease-out; - - -webkit-transform:translate3d(0,0,0); - -moz-transform:translate3d(0,0,0); - -ms-transform:translate3d(0,0,0); - -o-transform:translate3d(0,0,0); - transform:translate3d(0,0,0); - } - - .jumbotron-content { - position:absolute; - z-index:999; - top:0; - left:0; - right:0; - bottom:0; - - -webkit-transform:translate3d(0,0,0); - -moz-transform:translate3d(0,0,0); - -ms-transform:translate3d(0,0,0); - -o-transform:translate3d(0,0,0); - transform:translate3d(0,0,0); - } - - .galaxy-bg { - position:absolute; - width:100%; - height:100%; - top:0; - left:0; - - background-image:image-url("bg-galaxy.jpg"); - /* background-size:cover; */ - background-position:50% 50%; - background-repeat: no-repeat; - opacity:0; - - -webkit-transition:opacity 2s ease-out; - -moz-transition:opacity 2s ease-out; - -ms-transition:opacity 2s ease-out; - -o-transition:opacity 2s ease-out; - transition:opacity 2s ease-out; - - -webkit-transform:translate3d(0,0,0); - -moz-transform:translate3d(0,0,0); - -ms-transform:translate3d(0,0,0); - -o-transform:translate3d(0,0,0); - transform:translate3d(0,0,0); - - &.show { - opacity:1; - } - } -} - -.tag-line { - position:absolute; - width:100%; - top:540px; - color:#fff; - visibility:hidden; - - -webkit-transform:translate3d(0,0,0); - -moz-transform:translate3d(0,0,0); - -ms-transform:translate3d(0,0,0); - -o-transform:translate3d(0,0,0); - transform:translate3d(0,0,0); -} - - -.animated-logo { - position:absolute; - z-index:200; - top:50%; - left:50%; - width:140px; - height:140px; - margin:-60px 0 0 -115px; - opacity:1; - - -webkit-transition:-webkit-transform 300ms ease-in-out; - -moz-transition: -moz-transform 300ms ease-in-out; - -ms-transition: -ms-transform 300ms ease-in-out; - -o-transition: -o-transform 300ms ease-in-out; - transition: transform 300ms ease-in-out; - - -webkit-transform-origin:50% 50%; - -moz-transform-origin:50% 50%; - -ms-transform-origin:50% 50%; - -o-transform-origin:50% 50%; - transform-origin:50% 50%; - - -webkit-transform-style:preserve-3d; - -moz-transform-style:preserve-3d; - -ms-transform-style:preserve-3d; - -o-transform-style:preserve-3d; - transform-style:preserve-3d; - - -webkit-transform:translate3d(0,0,0) rotateY(0deg) skewY(0deg) scale(1,1); - -moz-transform:translate3d(0,0,0) rotateY(0deg) skewY(0deg) scale(1,1); - -ms-transform:translate3d(0,0,0) rotateY(0deg) skewY(0deg) scale(1,1); - -o-transform:translate3d(0,0,0) rotateY(0deg) skewY(0deg) scale(1,1); - transform:translate3d(0,0,0) rotateY(0deg) skewY(0deg) scale(1,1); -} - -.state-one .animated-logo { - -webkit-transform:translate3d(0,0,0) rotateY(0deg) skewY(0deg) scale(1,1); - -moz-transform:translate3d(0,0,0) rotateY(0deg) skewY(0deg) scale(1,1); - -ms-transform:translate3d(0,0,0) rotateY(0deg) skewY(0deg) scale(1,1); - -o-transform:translate3d(0,0,0) rotateY(0deg) skewY(0deg) scale(1,1); - transform:translate3d(0,0,0) rotateY(0deg) skewY(0deg) scale(1,1); -} - -.state-one.state-two.state-three.state-four .animated-logo { - -webkit-transform-origin:100% 0; - -moz-transform-origin:100% 0; - -ms-transform-origin:100% 0; - -o-transform-origin:100% 0; - transform-origin:100% 0; - - -webkit-transform:translate3d(0,10px,0) rotateY(-45deg) skewY(22deg) scale(1.26,1); - -moz-transform:translate3d(0,10px,0) rotateY(-45deg) skewY(22deg) scale(1.26,1); - -ms-transform:translate3d(0,10px,0) rotateY(-45deg) skewY(22deg) scale(1.26,1); - -o-transform:translate3d(0,10px,0) rotateY(-45deg) skewY(22deg) scale(1.26,1); - transform:translate3d(0,10px,0) rotateY(-45deg) skewY(22deg) scale(1.26,1); -} - -.state-one.state-two.state-three.state-four .white-block { - background-color:rgba(255,255,255,1); -} - -.white-block { - position:absolute; - width:68px; - height:68px; - - -webkit-box-sizing:border-box; - -moz-box-sizing:border-box; - box-sizing:border-box; - - /* background-color:rgba(255,0,0,0.3); */ - background-color:#fff; - background-color:rgba(255,255,255,0); - - border:1px solid #fff; - - -webkit-transition: - opacity 300ms ease-out, - -webkit-transform 300ms ease-out, - background-color 300ms ease-out; - -moz-transition: - opacity 300ms ease-out, - -moz-transform 300ms ease-out, - background-color 300ms ease-out; - -ms-transition: - opacity 300ms ease-out, - -ms-transform 300ms ease-out, - background-color 300ms ease-out; - -o-transition: - opacity 300ms ease-out, - -o-transform 300ms ease-out, - background-color 300ms ease-out; - transition: - opacity 300ms ease-out, - transform 300ms ease-out, - background-color 300ms ease-out; -} - -.block-1, -.block-2, -.block-3, -.block-4 { - top:0; - left:72px; - - -webkit-transform-origin:50% 50%; - -moz-transform-origin:50% 50%; - -ms-transform-origin:50% 50%; - -o-transform-origin:50% 50%; - transform-origin:50% 50%; - - -webkit-transform:translate3d(0,0,0); - -moz-transform:translate3d(0,0,0); - -ms-transform:translate3d(0,0,0); - -o-transform:translate3d(0,0,0); - transform:translate3d(0,0,0); -} - -.block-1 { - opacity:0; - - -webkit-transform:translate3d(0,0,0) scale(0,0); - -moz-transform:translate3d(0,0,0) scale(0,0); - -ms-transform:translate3d(0,0,0) scale(0,0); - -o-transform:translate3d(0,0,0) scale(0,0); - transform:translate3d(0,0,0) scale(0,0); -} - -.block-2 { - opacity:0; - top:0; - left:0; - - -webkit-transform:translate3d(0,0,0) scale(0,0); - -moz-transform:translate3d(0,0,0) scale(0,0); - -ms-transform:translate3d(0,0,0) scale(0,0); - -o-transform:translate3d(0,0,0) scale(0,0); - transform:translate3d(0,0,0) scale(0,0); -} - -.block-3 { - opacity:0; - top:72px; - - -webkit-transform:translate3d(0,0,0) scale(0,0); - -moz-transform:translate3d(0,0,0) scale(0,0); - -ms-transform:translate3d(0,0,0) scale(0,0); - -o-transform:translate3d(0,0,0) scale(0,0); - transform:translate3d(0,0,0) scale(0,0); -} - -.block-4 { - -webkit-transform-origin:0 0; - -moz-transform-origin:0 0; - -ms-transform-origin:0 0; - -o-transform-origin:0 0; - transform-origin:0 0; - - -webkit-transform:translate3d(72px,-2px,0) rotateY(90deg) skewY(-22deg) scaleX(1.25); - -moz-transform:translate3d(72px,-2px,0) rotateY(90deg) skewY(-22deg) scaleX(1.25); - -ms-transform:translate3d(72px,-2px,0) rotateY(90deg) skewY(-22deg) scaleX(1.25); - -o-transform:translate3d(72px,-2px,0) rotateY(90deg) skewY(-22deg) scaleX(1.25); - transform:translate3d(72px,-2px,0) rotateY(90deg) skewY(-22deg) scaleX(1.25); -} - -.state-one.state-two .block-1 { - opacity:1; - - -webkit-transform:translate3d(0,0,0) scale(1,1); - -moz-transform:translate3d(0,0,0) scale(1,1); - -ms-transform:translate3d(0,0,0) scale(1,1); - -o-transform:translate3d(0,0,0) scale(1,1); - transform:translate3d(0,0,0) scale(1,1); -} - -.state-one .block-2 { - opacity:1; - - -webkit-transform:translate3d(0,0,0) scale(1,1); - -moz-transform:translate3d(0,0,0) scale(1,1); - -ms-transform:translate3d(0,0,0) scale(1,1); - -o-transform:translate3d(0,0,0) scale(1,1); - transform:translate3d(0,0,0) scale(1,1); -} - -.state-one.state-two.state-three .block-3 { - opacity:1; - - -webkit-transform:translate3d(0,0,0) scale(1,1); - -moz-transform:translate3d(0,0,0) scale(1,1); - -ms-transform:translate3d(0,0,0) scale(1,1); - -o-transform:translate3d(0,0,0) scale(1,1); - transform:translate3d(0,0,0) scale(1,1); -} - -.cursor { - font-weight:bold; - - -webkit-animation:Blink 800ms infinite; - -moz-animation:Blink 800ms infinite; - -ms-animation:Blink 800ms infinite; - -o-animation:Blink 800ms infinite; - animation:Blink 800ms infinite; -} - -@-webkit-keyframes Blink { - 0% { - opacity:1; - } - 50% { - opacity:1; - - } - 51% { - opacity:0; - } - 100% { - opacity:0; - } -} - -@-moz-keyframes Blink { - 0% { - opacity:1; - } - 50% { - opacity:1; - } - 51% { - opacity:0; - } - 100% { - opacity:0; - } -} - -@-ms-keyframes Blink { - 0% { - opacity:1; - - } - 50% { - opacity:1; - } - 51% { - opacity:0; - } - 100% { - opacity:0; - } -} - -@-o-keyframes Blink { - 0% { - opacity:1; - - } - 50% { - opacity:1; - } - 51% { - opacity:0; - } - 100% { - opacity:0; - } -} - -@keyframes Blink { - 0% { - opacity:1; - - } - 50% { - opacity:1; - } - 51% { - opacity:0; - } - 100% { - opacity:0; - } -} - -@media (max-width: 570px) { - .tag-line { - display:none; - } - - #jumbotron .jumbotron-content { - -webkit-transform:translate3d(0, 0, 0) scale(0.8); - -moz-transform:translate3d(0, 0, 0) scale(0.8); - -ms-transform:translate3d(0, 0, 0) scale(0.8); - -o-transform:translate3d(0, 0, 0) scale(0.8); - transform:translate3d(0, 0, 0) scale(0.8); - } - - .animated-logo { - margin:-15px 0 0 -113px; - } - - #jumbotron-mask, - #jumbotron { - height:560px; - } -} diff --git a/website/source/assets/stylesheets/_logos.scss b/website/source/assets/stylesheets/_logos.scss new file mode 100644 index 000000000..6e8f39a48 --- /dev/null +++ b/website/source/assets/stylesheets/_logos.scss @@ -0,0 +1,41 @@ +svg.logo { + &.color { + opacity: 1.0; + + path.text { + fill: $black; + opacity: 1.0; + } + + path.rect-light { + fill: $terraform-purple; + opacity: 1.0; + } + + path.rect-dark { + fill: $terraform-purple-dark; + opacity: 1.0; + } + } + + // The default logo class is the colored version + @extend .color; + + &.white { + opacity: 1.0; + + path.text { + fill: $white; + } + + path.rect-light { + fill: $white; + opacity: 1.0; + } + + path.rect-dark { + fill: $white; + opacity: 0.7; + } + } +} diff --git a/website/source/assets/stylesheets/_mixins.scss b/website/source/assets/stylesheets/_mixins.scss deleted file mode 100755 index f49151e3a..000000000 --- a/website/source/assets/stylesheets/_mixins.scss +++ /dev/null @@ -1,724 +0,0 @@ -// -// Mixins -// -------------------------------------------------- - - -// Utilities -// ------------------------- - -// Clearfix -// Source: http://nicolasgallagher.com/micro-clearfix-hack/ -// -// For modern browsers -// 1. The space content is one way to avoid an Opera bug when the -// contenteditable attribute is included anywhere else in the document. -// Otherwise it causes space to appear at the top and bottom of elements -// that are clearfixed. -// 2. The use of `table` rather than `block` is only necessary if using -// `:before` to contain the top-margins of child elements. -@mixin clearfix() { - &:before, - &:after { - content: " "; /* 1 */ - display: table; /* 2 */ - } - &:after { - clear: both; - } -} - -// Webkit-style focus -@mixin tab-focus() { - // Default - outline: thin dotted #333; - // Webkit - outline: 5px auto -webkit-focus-ring-color; - outline-offset: -2px; -} - -// Center-align a block level element -@mixin center-block() { - display: block; - margin-left: auto; - margin-right: auto; -} - -// Sizing shortcuts -@mixin size($width, $height) { - width: $width; - height: $height; -} -@mixin square($size) { - @include size($size, $size); -} - -// Placeholder text -@mixin placeholder($color: $input-color-placeholder) { - &:-moz-placeholder { color: $color; } // Firefox 4-18 - &::-moz-placeholder { color: $color; } // Firefox 19+ - &:-ms-input-placeholder { color: $color; } // Internet Explorer 10+ - &::-webkit-input-placeholder { color: $color; } // Safari and Chrome -} - -// Text overflow -// Requires inline-block or block for proper styling -@mixin text-overflow() { - overflow: hidden; - text-overflow: ellipsis; - white-space: nowrap; -} - -// CSS image replacement -// Source: https://github.com/h5bp/html5-boilerplate/commit/aa0396eae757 -@mixin hide-text() { - font: #{"0/0"} a; - color: transparent; - text-shadow: none; - background-color: transparent; - border: 0; -} - - - -// CSS3 PROPERTIES -// -------------------------------------------------- - -// Single side border-radius -@mixin border-top-radius($radius) { - border-top-right-radius: $radius; - border-top-left-radius: $radius; -} -@mixin border-right-radius($radius) { - border-bottom-right-radius: $radius; - border-top-right-radius: $radius; -} -@mixin border-bottom-radius($radius) { - border-bottom-right-radius: $radius; - border-bottom-left-radius: $radius; -} -@mixin border-left-radius($radius) { - border-bottom-left-radius: $radius; - border-top-left-radius: $radius; -} - -// Drop shadows -@mixin box-shadow($shadow) { - -webkit-box-shadow: $shadow; // iOS <4.3 & Android <4.1 - box-shadow: $shadow; -} - -// Transitions -@mixin transition($transition) { - -webkit-transition: $transition; - transition: $transition; -} -@mixin transition-delay($transition-delay) { - -webkit-transition-delay: $transition-delay; - transition-delay: $transition-delay; -} -@mixin transition-duration($transition-duration) { - -webkit-transition-duration: $transition-duration; - transition-duration: $transition-duration; -} -@mixin transition-transform($transition) { - -webkit-transition: -webkit-transform $transition; - -moz-transition: -moz-transform $transition; - -o-transition: -o-transform $transition; - transition: transform $transition; -} - -// Transformations -@mixin rotate($degrees) { - -webkit-transform: rotate($degrees); - -ms-transform: rotate($degrees); // IE9+ - transform: rotate($degrees); -} -@mixin scale($ratio) { - -webkit-transform: scale($ratio); - -ms-transform: scale($ratio); // IE9+ - transform: scale($ratio); -} -@mixin translate($x, $y) { - -webkit-transform: translate($x, $y); - -ms-transform: translate($x, $y); // IE9+ - transform: translate($x, $y); -} -@mixin skew($x, $y) { - -webkit-transform: skew($x, $y); - -ms-transform: skewX($x) skewY($y); // See https://github.com/twbs/bootstrap/issues/4885; IE9+ - transform: skew($x, $y); -} -@mixin translate3d($x, $y, $z) { - -webkit-transform: translate3d($x, $y, $z); - transform: translate3d($x, $y, $z); -} - -// Backface visibility -// Prevent browsers from flickering when using CSS 3D transforms. -// Default value is `visible`, but can be changed to `hidden` -// See git pull https://github.com/dannykeane/bootstrap.git backface-visibility for examples -@mixin backface-visibility($visibility) { - -webkit-backface-visibility: $visibility; - -moz-backface-visibility: $visibility; - backface-visibility: $visibility; -} - -// Box sizing -@mixin box-sizing($boxmodel) { - -webkit-box-sizing: $boxmodel; - -moz-box-sizing: $boxmodel; - box-sizing: $boxmodel; -} - -// User select -// For selecting text on the page -@mixin user-select($select) { - -webkit-user-select: $select; - -moz-user-select: $select; - -ms-user-select: $select; // IE10+ - -o-user-select: $select; - user-select: $select; -} - -// Resize anything -@mixin resizable($direction) { - resize: $direction; // Options: horizontal, vertical, both - overflow: auto; // Safari fix -} - -// CSS3 Content Columns -@mixin content-columns($column-count, $column-gap: $grid-gutter-width) { - -webkit-column-count: $column-count; - -moz-column-count: $column-count; - column-count: $column-count; - -webkit-column-gap: $column-gap; - -moz-column-gap: $column-gap; - column-gap: $column-gap; -} - -// Optional hyphenation -@mixin hyphens($mode: auto) { - word-wrap: break-word; - -webkit-hyphens: $mode; - -moz-hyphens: $mode; - -ms-hyphens: $mode; // IE10+ - -o-hyphens: $mode; - hyphens: $mode; -} - -// Opacity -@mixin opacity($opacity) { - opacity: $opacity; - // IE8 filter - $opacity-ie: ($opacity * 100); - filter: #{"alpha(opacity=#{opacity-ie})"}; -} - - - -// GRADIENTS -// -------------------------------------------------- - -#gradient { - - // Horizontal gradient, from left to right - // - // Creates two color stops, start and end, by specifying a color and position for each color stop. - // Color stops are not available in IE9 and below. - @mixin horizontal($start-color: #555, $end-color: #333, $start-percent: 0%, $end-percent: 100%) { - background-image: -webkit-gradient(linear, $start-percent top, $end-percent top, from($start-color), to($end-color)); // Safari 4+, Chrome 2+ - background-image: -webkit-linear-gradient(left, color-stop($start-color $start-percent), color-stop($end-color $end-percent)); // Safari 5.1+, Chrome 10+ - background-image: -moz-linear-gradient(left, $start-color $start-percent, $end-color $end-percent); // FF 3.6+ - background-image: linear-gradient(to right, $start-color $start-percent, $end-color $end-percent); // Standard, IE10 - background-repeat: repeat-x; - filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#{argb($start-color)}', endColorstr='#{argb($end-color)}', GradientType=1); // IE9 and down - } - - // Vertical gradient, from top to bottom - // - // Creates two color stops, start and end, by specifying a color and position for each color stop. - // Color stops are not available in IE9 and below. - @mixin vertical($start-color: #555, $end-color: #333, $start-percent: 0%, $end-percent: 100%) { - background-image: -webkit-gradient(linear, left $start-percent, left $end-percent, from($start-color), to($end-color)); // Safari 4+, Chrome 2+ - background-image: -webkit-linear-gradient(top, $start-color, $start-percent, $end-color, $end-percent); // Safari 5.1+, Chrome 10+ - background-image: -moz-linear-gradient(top, $start-color $start-percent, $end-color $end-percent); // FF 3.6+ - background-image: linear-gradient(to bottom, $start-color $start-percent, $end-color $end-percent); // Standard, IE10 - background-repeat: repeat-x; - filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#{argb($start-color)}', endColorstr='#{argb($end-color)}', GradientType=0); // IE9 and down - } - - @mixin directional($start-color: #555, $end-color: #333, $deg: 45deg) { - background-repeat: repeat-x; - background-image: -webkit-linear-gradient($deg, $start-color, $end-color); // Safari 5.1+, Chrome 10+ - background-image: -moz-linear-gradient($deg, $start-color, $end-color); // FF 3.6+ - background-image: linear-gradient($deg, $start-color, $end-color); // Standard, IE10 - } - @mixin horizontal-three-colors($start-color: #00b3ee, $mid-color: #7a43b6, $color-stop: 50%, $end-color: #c3325f) { - background-image: -webkit-gradient(left, linear, 0 0, 0 100%, from($start-color), color-stop($color-stop, $mid-color), to($end-color)); - background-image: -webkit-linear-gradient(left, $start-color, $mid-color $color-stop, $end-color); - background-image: -moz-linear-gradient(left, $start-color, $mid-color $color-stop, $end-color); - background-image: linear-gradient(to right, $start-color, $mid-color $color-stop, $end-color); - background-repeat: no-repeat; - filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#{argb($start-color)}', endColorstr='#{argb($end-color)}', GradientType=1); // IE9 and down - } - @mixin vertical-three-colors($start-color: #00b3ee, $mid-color: #7a43b6, $color-stop: 50%, $end-color: #c3325f) { - background-image: -webkit-gradient(linear, 0 0, 0 100%, from($start-color), color-stop($color-stop, $mid-color), to($end-color)); - background-image: -webkit-linear-gradient($start-color, $mid-color $color-stop, $end-color); - background-image: -moz-linear-gradient(top, $start-color, $mid-color $color-stop, $end-color); - background-image: linear-gradient($start-color, $mid-color $color-stop, $end-color); - background-repeat: no-repeat; - filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#{argb($start-color)}', endColorstr='#{argb($end-color)}', GradientType=0); // IE9 and down - } - @mixin radial($inner-color: #555, $outer-color: #333) { - background-image: -webkit-gradient(radial, center center, 0, center center, 460, from($inner-color), to($outer-color)); - background-image: -webkit-radial-gradient(circle, $inner-color, $outer-color); - background-image: -moz-radial-gradient(circle, $inner-color, $outer-color); - background-image: radial-gradient(circle, $inner-color, $outer-color); - background-repeat: no-repeat; - } - @mixin striped($color: #555, $angle: 45deg) { - background-image: -webkit-gradient(linear, 0 100%, 100% 0, color-stop(.25, rgba(255,255,255,.15)), color-stop(.25, transparent), color-stop(.5, transparent), color-stop(.5, rgba(255,255,255,.15)), color-stop(.75, rgba(255,255,255,.15)), color-stop(.75, transparent), to(transparent)); - background-image: -webkit-linear-gradient($angle, rgba(255,255,255,.15) 25%, transparent 25%, transparent 50%, rgba(255,255,255,.15) 50%, rgba(255,255,255,.15) 75%, transparent 75%, transparent); - background-image: -moz-linear-gradient($angle, rgba(255,255,255,.15) 25%, transparent 25%, transparent 50%, rgba(255,255,255,.15) 50%, rgba(255,255,255,.15) 75%, transparent 75%, transparent); - background-image: linear-gradient($angle, rgba(255,255,255,.15) 25%, transparent 25%, transparent 50%, rgba(255,255,255,.15) 50%, rgba(255,255,255,.15) 75%, transparent 75%, transparent); - } -} - -// Reset filters for IE -// -// When you need to remove a gradient background, do not forget to use this to reset -// the IE filter for IE9 and below. -@mixin reset-filter() { - filter: progid:DXImageTransform.Microsoft.gradient(enabled = false); -} - - - -// Retina images -// -// Short retina mixin for setting background-image and -size - -@mixin img-retina($file-1x, $file-2x, $width-1x, $height-1x) { - background-image: image-url("#{$file-1x}"); - background-size: $width-1x $height-1x; - - @media - only screen and (-webkit-min-device-pixel-ratio: 2), - only screen and ( min--moz-device-pixel-ratio: 2), - only screen and ( -o-min-device-pixel-ratio: 2/1), - only screen and ( min-device-pixel-ratio: 2), - only screen and ( min-resolution: 192dpi), - only screen and ( min-resolution: 2dppx) { - background-image: image-url("#{$file-2x}"); - background-size: $width-1x $height-1x; - } -} - - -// Responsive image -// -// Keep images from scaling beyond the width of their parents. - -@mixin img-responsive($display: block) { - display: $display; - max-width: 100%; // Part 1: Set a maximum relative to the parent - height: auto; // Part 2: Scale the height according to the width, otherwise you get stretching -} - - -// COMPONENT MIXINS -// -------------------------------------------------- - -// Horizontal dividers -// ------------------------- -// Dividers (basically an hr) within dropdowns and nav lists -@mixin nav-divider($color: #e5e5e5) { - height: 1px; - margin: (($line-height-computed / 2) - 1) 0; - overflow: hidden; - background-color: $color; -} - -// Panels -// ------------------------- -@mixin panel-variant($border, $heading-text-color, $heading-bg-color, $heading-border) { - border-color: $border; - & > .panel-heading { - color: $heading-text-color; - background-color: $heading-bg-color; - border-color: $heading-border; - + .panel-collapse .panel-body { - border-top-color: $border; - } - } - & > .panel-footer { - + .panel-collapse .panel-body { - border-bottom-color: $border; - } - } -} - -// Alerts -// ------------------------- -@mixin alert-variant($background, $border, $text-color) { - background-color: $background; - border-color: $border; - color: $text-color; - hr { - border-top-color: darken($border, 5%); - } - .alert-link { - color: darken($text-color, 10%); - } -} - -// Tables -// ------------------------- -@mixin table-row-variant($state, $background, $border) { - // Exact selectors below required to override `.table-striped` and prevent - // inheritance to nested tables. - .table > thead > tr, - .table > tbody > tr, - .table > tfoot > tr { - > td.#{state}, - > th.#{state}, - &.#{state} > td, - &.#{state} > th { - background-color: $background; - border-color: $border; - } - } - - // Hover states for `.table-hover` - // Note: this is not available for cells or rows within `thead` or `tfoot`. - .table-hover > tbody > tr { - > td.#{state}:hover, - > th.#{state}:hover, - &.#{state}:hover > td { - background-color: darken($background, 5%); - border-color: darken($border, 5%); - } - } -} - -// Button variants -// ------------------------- -// Easily pump out default styles, as well as :hover, :focus, :active, -// and disabled options for all buttons -@mixin button-variant($color, $background, $border) { - color: $color; - background-color: $background; - border-color: $border; - - &:hover, - &:focus, - &:active, - &.active, - .open .dropdown-toggle& { - color: $color; - background-color: darken($background, 8%); - border-color: darken($border, 12%); - } - &:active, - &.active, - .open .dropdown-toggle& { - background-image: none; - } - &.disabled, - &[disabled], - fieldset[disabled] & { - &, - &:hover, - &:focus, - &:active, - &.active { - background-color: $background; - border-color: $border - } - } -} - -// Button sizes -// ------------------------- -@mixin button-size($padding-vertical, $padding-horizontal, $font-size, $line-height, $border-radius) { - padding: $padding-vertical $padding-horizontal; - font-size: $font-size; - line-height: $line-height; - border-radius: $border-radius; -} - -// Pagination -// ------------------------- -@mixin pagination-size($padding-vertical, $padding-horizontal, $font-size, $border-radius) { - > li { - > a, - > span { - padding: $padding-vertical $padding-horizontal; - font-size: $font-size; - } - &:first-child { - > a, - > span { - @include border-left-radius($border-radius); - } - } - &:last-child { - > a, - > span { - @include border-right-radius($border-radius); - } - } - } -} - -// Labels -// ------------------------- -@mixin label-variant($color) { - background-color: $color; - &[href] { - &:hover, - &:focus { - background-color: darken($color, 10%); - } - } -} - -// Navbar vertical align -// ------------------------- -// Vertically center elements in the navbar. -// Example: an element has a height of 30px, so write out `@include navbar-vertical-align(30px);` to calculate the appropriate top margin. -@mixin navbar-vertical-align($element-height) { - margin-top: (($navbar-height - $element-height) / 2); - margin-bottom: (($navbar-height - $element-height) / 2); -} - -// Progress bars -// ------------------------- -// @mixin progress-bar-variant($color) { -// background-color: $color; -// .progress-striped & { -// #gradient > @include striped($color); -// } -// } - -// Responsive utilities -// ------------------------- -// More easily include all the states for responsive-utilities.less. -@mixin responsive-visibility() { - display: block !important; - tr& { display: table-row !important; } - th&, - td& { display: table-cell !important; } -} - -@mixin responsive-invisibility() { - display: none !important; - tr& { display: none !important; } - th&, - td& { display: none !important; } -} - -// Grid System -// ----------- - -// Centered container element -@mixin container-fixed() { - margin-right: auto; - margin-left: auto; - padding-left: ($grid-gutter-width / 2); - padding-right: ($grid-gutter-width / 2); - @include clearfix(); -} - -// Creates a wrapper for a series of columns -@mixin make-row($gutter: $grid-gutter-width) { - margin-left: ($gutter / -2); - margin-right: ($gutter / -2); - @include clearfix(); -} - -// Generate the extra small columns -@mixin make-xs-column($columns, $gutter: $grid-gutter-width) { - position: relative; - float: left; - width: percentage(($columns / $grid-columns)); - // Prevent columns from collapsing when empty - min-height: 1px; - // Inner gutter via padding - padding-left: ($gutter / 2); - padding-right: ($gutter / 2); -} - -// Generate the small columns -@mixin make-sm-column($columns, $gutter: $grid-gutter-width) { - position: relative; - // Prevent columns from collapsing when empty - min-height: 1px; - // Inner gutter via padding - padding-left: ($gutter / 2); - padding-right: ($gutter / 2); - - // Calculate width based on number of columns available - @media (min-width: $screen-sm) { - float: left; - width: percentage(($columns / $grid-columns)); - } -} - -// Generate the small column offsets -@mixin make-sm-column-offset($columns) { - @media (min-width: $screen-sm) { - margin-left: percentage(($columns / $grid-columns)); - } -} -@mixin make-sm-column-push($columns) { - @media (min-width: $screen-sm) { - left: percentage(($columns / $grid-columns)); - } -} -@mixin make-sm-column-pull($columns) { - @media (min-width: $screen-sm) { - right: percentage(($columns / $grid-columns)); - } -} - -// Generate the medium columns -@mixin make-md-column($columns, $gutter: $grid-gutter-width) { - position: relative; - // Prevent columns from collapsing when empty - min-height: 1px; - // Inner gutter via padding - padding-left: ($gutter / 2); - padding-right: ($gutter / 2); - - // Calculate width based on number of columns available - @media (min-width: $screen-md) { - float: left; - width: percentage(($columns / $grid-columns)); - } -} - -// Generate the large column offsets -@mixin make-md-column-offset($columns) { - @media (min-width: $screen-md) { - margin-left: percentage(($columns / $grid-columns)); - } -} -@mixin make-md-column-push($columns) { - @media (min-width: $screen-md) { - left: percentage(($columns / $grid-columns)); - } -} -@mixin make-md-column-pull($columns) { - @media (min-width: $screen-md) { - right: percentage(($columns / $grid-columns)); - } -} - -// Generate the large columns -@mixin make-lg-column($columns, $gutter: $grid-gutter-width) { - position: relative; - // Prevent columns from collapsing when empty - min-height: 1px; - // Inner gutter via padding - padding-left: ($gutter / 2); - padding-right: ($gutter / 2); - - // Calculate width based on number of columns available - @media (min-width: $screen-lg) { - float: left; - width: percentage(($columns / $grid-columns)); - } -} - -// Generate the large column offsets -@mixin make-lg-column-offset($columns) { - @media (min-width: $screen-lg) { - margin-left: percentage(($columns / $grid-columns)); - } -} -@mixin make-lg-column-push($columns) { - @media (min-width: $screen-lg) { - left: percentage(($columns / $grid-columns)); - } -} -@mixin make-lg-column-pull($columns) { - @media (min-width: $screen-lg) { - right: percentage(($columns / $grid-columns)); - } -} - - -// Form validation states -// -// Used in forms.less to generate the form validation CSS for warnings, errors, -// and successes. - -@mixin form-control-validation($text-color: #555, $border-color: #ccc, $background-color: #f5f5f5) { - // Color the label and help text - .help-block, - .control-label { - color: $text-color; - } - // Set the border and box shadow on specific inputs to match - .form-control { - border-color: $border-color; - @include box-shadow(inset 0 1px 1px rgba(0,0,0,.075)); // Redeclare so transitions work - &:focus { - border-color: darken($border-color, 10%); - $shadow: inset 0 1px 1px rgba(0,0,0,.075), 0 0 6px lighten($border-color, 20%); - @include box-shadow($shadow); - } - } - // Set validation states also for addons - .input-group-addon { - color: $text-color; - border-color: $border-color; - background-color: $background-color; - } -} - -// Form control focus state -// -// Generate a customized focus state and for any input with the specified color, -// which defaults to the `$input-focus-border` variable. -// -// We highly encourage you to not customize the default value, but instead use -// this to tweak colors on an as-needed basis. This aesthetic change is based on -// WebKit's default styles, but applicable to a wider range of browsers. Its -// usability and accessibility should be taken into account with any change. -// -// Example usage: change the default blue border and shadow to white for better -// contrast against a dark gray background. - -@mixin form-control-focus($color: $input-border-focus) { - $color-rgba: rgba(red($color), green($color), blue($color), .6); - &:focus { - border-color: $color; - outline: 0; - @include box-shadow(#{"inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px #{color-rgba}"}); - } -} - -// Form control sizing -// -// Relative text size, padding, and border-radii changes for form controls. For -// horizontal sizing, wrap controls in the predefined grid classes. `